Trying to pass a variable to fuzzy search

I'm trying to write code like this:
   for x in 1 .. 6 loop
       v_searchword := listgetat(replace(p_searchphrase,',',' '),x,' ');
       for c1 in (select * from
                      (select score(1) as score, searchterms, suggestions from suggestions_table
                       where contains(searchterms,'fuzzy({'||v_searchword||'},,,weight)',1)>0
                       order by score desc)
                   where rownum < 10) loop                                    
        end loop;                  
   end loop;Someone passes in a long search phrase. I separate it into words and take up to the first 6. The set of words is looped through. Each word in turn is assigned to the v_searchword variable. I then do an Oracle Text fuzzy search on that word. The above code, however, gives me an Oracle Text parser error (DRG-50901: text query parser syntax error...).
I've modified the code so that the all-important line reads *where contains(searchterms,'fuzzy({v_searchword},,,weight)',1)>0*, and whilst that doesn't produce a syntax error, it doesn't produce any results, either! Words that I know will generate suggestions when I do a manual fuzzy search in plain SQL (such as "womman" and "tomartoe") don't generate anything in this case, because (I think) instead of searching for 'womman' or 'tomartoe' it's actually just searching for the word 'v_searchword' each time.
Could someone tell me how to write my code so that the correct word is passed into the contains function each time, please? It seems syntactically not very difficult, but I'm stumped!

If any value for v_searchword is null it would result in an invalid syntax, searching for {}. This would happen if there was no such element, such as no sixth word in a string of five words. You might also want to remove duplciate spaces from the string. Please see the demonstration below that first reproduces, then corrects the error simply by adding a condition that v_searchword is not null.
SCOTT@orcl_11g> create table suggestions_table
  2    (searchterms  varchar2 (30),
  3       suggestions  varchar2 (20))
  4  /
Table created.
SCOTT@orcl_11g> insert all
  2  into suggestions_table values ('woman', null)
  3  into suggestions_table values ('women', null)
  4  into suggestions_table values ('tomato', null)
  5  into suggestions_table values ('tomatoes', null)
  6  select * from dual
  7  /
4 rows created.
SCOTT@orcl_11g> create index your_index
  2  on suggestions_table (searchterms)
  3  indextype is ctxsys.context
  4  /
Index created.
SCOTT@orcl_11g> CREATE OR REPLACE FUNCTION listgetat
  2       (p_string    VARCHAR2,
  3        p_element   INTEGER,
  4        p_separator VARCHAR2 DEFAULT ' ')
  5       RETURN          VARCHAR2
  6  AS
  7    v_string      VARCHAR2 (32767);
  8  BEGIN
  9    -- ensure there are starting and ending separators:
10    v_string := p_separator || p_string || p_separator;
11    -- remove all double separators:
12    WHILE INSTR (v_string, p_separator || p_separator) > 0 LOOP
13        v_string := REPLACE (v_string, p_separator || p_separator, p_separator);
14    END LOOP;
15    -- check if element exists:
16    IF LENGTH (v_string) - LENGTH (REPLACE (v_string, p_separator, '')) >
17         LENGTH (p_separator) * p_element
18    THEN
19        v_string := SUBSTR (v_string,
20                      INSTR (v_string, p_separator, 1, p_element)
21                      + LENGTH (p_separator));
22        RETURN SUBSTR (v_string, 1, INSTR (v_string, p_separator) - 1);
23    ELSE
24        RETURN NULL;
25    END IF;
26  END listgetat;
27  /
Function created.
SCOTT@orcl_11g> -- reproduction of error:
SCOTT@orcl_11g> create or replace procedure test_proc
  2    (p_searchphrase     in varchar2)
  3  as
  4    v_searchword    varchar2 (100);
  5  begin
  6       for x in 1 .. 6 loop
  7           v_searchword := listgetat(replace(p_searchphrase,',',' '),x,' ');
  8 
  9           for c1 in (select * from
10                    (select score(1) as score, searchterms, suggestions from suggestions_table
11                     where contains(searchterms,'fuzzy({'||v_searchword||'},,,weight)',1)>0
12                     order by score desc)
13                 where rownum < 10) loop
14              dbms_output.put_line
15             (lpad (c1.score, 3) || ' ' ||
16              rpad (c1.searchterms, 30) || ' ' ||
17              v_searchword);
18            end loop;
19       end loop;
20  end test_proc;
21  /
Procedure created.
SCOTT@orcl_11g> show errors
No errors.
SCOTT@orcl_11g> exec test_proc ('womman,and,tomartoe')
38 woman                          womman
25 women                          womman
29 tomato                         tomartoe
26 tomatoes                       tomartoe
BEGIN test_proc ('womman,and,tomartoe'); END;
ERROR at line 1:
ORA-29902: error in executing ODCIIndexStart() routine
ORA-20000: Oracle Text error:
DRG-50901: text query parser syntax error on line 1, column 8
ORA-06512: at "SCOTT.TEST_PROC", line 9
ORA-06512: at line 1
SCOTT@orcl_11g> -- correction of error:
SCOTT@orcl_11g> create or replace procedure test_proc
  2    (p_searchphrase     in varchar2)
  3  as
  4    v_searchword    varchar2 (100);
  5  begin
  6       for x in 1 .. 6 loop
  7           v_searchword := listgetat(replace(p_searchphrase,',',' '),x,' ');
  8           -- check if xth word exists:
  9           if v_searchword is not null then
10             for c1 in (select * from
11                      (select score(1) as score, searchterms, suggestions from suggestions_table
12                       where contains(searchterms,'fuzzy({'||v_searchword||'},,,weight)',1)>0
13                       order by score desc)
14                   where rownum < 10) loop
15             dbms_output.put_line
16               (lpad (c1.score, 3) || ' ' ||
17                rpad (c1.searchterms, 30) || ' ' ||
18                v_searchword);
19              end loop;
20           end if;
21       end loop;
22  end test_proc;
23  /
Procedure created.
SCOTT@orcl_11g> show errors
No errors.
SCOTT@orcl_11g> exec test_proc ('womman,and,tomartoe')
38 woman                          womman
25 women                          womman
29 tomato                         tomartoe
26 tomatoes                       tomartoe
PL/SQL procedure successfully completed.
SCOTT@orcl_11g>

Similar Messages

  • Help: I am trying to pass a variable between classes

    I am trying to pass data in a variable inbetween two classes is there any suggestions as to how to do this? Here is a example of the code I am trying to pass MqMessage to the class MqLog.
    if(MqMessage.equals("END"))               
                                       finalize();
                                       System.exit( 0 );
                             else //else build flat file and launch docusolve
                                       MqLog tempMqLog = new MqLog();
                                       tempMqLog.levelThreeDiagnostic();
                                       aRuntime = null;
                                       aProcess = null;                                   
                                  }

    I don't really undestand what you are asking specifically. If you only want to transfer a value from one Object to another Object, then you should just use a set method:
    if (objectOne.getValue().equals("END"))
    end();
    else
    objectTwo.setValue(objectOne.getValue())

  • Passing a variable from a non DB block to a DB block

    Im getting the error FRM-41003 when I try to pass a variable from a search screen i created to a results screen which is tied to a DB block. Ive searched this error and nothing seemed to match exactly what Im dealing with. Is it possible to do this? Anybody run into this issue?

    This is the code/trigger launched when the search button is clicked from the search screen that is not tied to a DB block.
    IF :NRHR1.NUMBER IS NULL THEN
    Message('Please enter valid search criteria.', NO_ACKNOWLEDGE);
    ELSE
    :Global.BUFFER_VARIABLE := :NRHR1.NUMBER;
    NUM_SEARCH;
    END IF;
    --This is the procedure that is called
    PROCEDURE NUM_SEARCH IS
    BEGIN
    IF :NRHR1.NUMBER IS NOT NULL THEN
         :Global.BUFFER_VARIABLE := :NRHR1.NUMBER;
         ENTER_QUERY;
         :NRHR.NUMBER := :Global.BUFFER_VARIABLE;
         DECLARE
                   blk_id BLOCK;
                   s_old_order_by           VARCHAR(100);
                   s_old_where          VARCHAR(100);
              BEGIN
                   blk_id := FIND_BLOCK( 'NRHR' );
                   s_old_where := GET_BLOCK_PROPERTY(blk_id, DEFAULT_WHERE);
                   SET_BLOCK_PROPERTY( blk_id, DEFAULT_WHERE, 'NRHR.NUMBER = ''' ||:Global.BUFFER_VARIABLE||'''');
                   EXECUTE_QUERY;
                   SHOW_WINDOW('WINDOW1');
                   SET_BLOCK_PROPERTY(blk_id, DEFAULT_WHERE, s_old_where);
              END;
    END IF;
    EXCEPTION
              WHEN NO_DATA_FOUND OR VALUE_ERROR THEN
              MESSAGE('NO RECORDS');
              HIDE_WINDOW('WINDOW1');
              SHOW_WINDOW('SEARCH');
    END;
    I am using forms 10g
    Edited by: user8606340 on Jan 28, 2010 8:17 AM

  • Passing Captivate variables to Flash widget

    Hello,
    I'm developing a simple progress bar widget in Flash to add to a Captivate course I'm building.  I believe what I want to do is very simple, but I appear to be missing something.
    Quick synopsis:
    I have created a variable in Captivate 5.5 called intProgress which should be a percentage of a student's progress through the course. I set this manually via an Advanced Action upon entering the slide.
    I've also created a Progress Bar widget in Flash 5.5.  It consists of nothing more than a manual progress bar component in Flash.
    I want to feed that intProgress value from Captivate into my Flash widget, and have the progress bar update accordingly.
    Here is my function (aPb is my progress bar) -
    function courseProgress(intPercentage)
              aPb.setProgress(intPercentage, 100)
    And here is how I am trying to pass the variable over:
    courseProgress(MovieClip(root).intProgress);
    It doesn't look like the variable is coming across from Captivate to the widget.  How can I correctly do this?
    Please let me know what I'm doing wrong and/or what I'm missing here.
    Thanks for any help anyone can provide!
    Daniel

    Cool - I've found out how to access my custom variable thanks to your help.  Right now, I'm using a simple text field as a debug (instead of the progress bar) just until I get everything sorted out.
    In the cpSetValue function of the widget, I tested with the slide name variable you provided first:
    myText.text = "label:" + m_VariableHandle.cpInfoCurrentSlideLabel;
    And then progressed onward to my custom variable.
    myText.text = "prog:" + m_VariableHandle.intProgress; (my custom variable)
    So I have full connection to those, they're reading perfectly.  That m_VariableHandle is giving me the connection I need (good to know for the future).
    They're just not getting updated.  It just keep showing the values for the first slide - for both the SlideLabel and the custom variable. So now my trouble lies not in the reading of the variable, but the updating of it - to get the most current value.  That's a step forward though, very happy about that.
    To answer your question - yes, I'm doing a variable modification on every slide enter.  I'll set my intProgress variable to 5, then maybe 10 on the next slide, then 15, etc.  It's very important that I set that manually, as my project is not linear.  In other words, there may be a trail of 10 slides later on that are a "side" branch - and not part of the course progression.
    So, thanks again for your help. I'm a whole lot closer than I was before!

  • Passing SessionBean variable to sql query editor

    Hi,
    I am trying to pass a variable that I define locally in SessionBean to sql query via the query editor.
    SELECT ALL comments.id,
                        comments.comment,
                        comments.comment_date
    FROM comments
    WHERE comments.id = **SessionBean1.id**How do I specify **SessionBean1.id** in the WHERE clause?
    Thanks for your help.
    --izumi                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Use this SQL query:
    SELECT ALL comments.id,
                        comments.comment,
                        comments.comment_date
    FROM comments
    WHERE comments.id = ?Then in the page that uses this (wherever the query is executed) provide the variable value with:
    <your row set name>.setObject(1, getSessionBean1().getCommentId());

  • Pass unix variable to pl/sql block

    I am calling a sql file from Unix shell program (sql file contains pl/sql block).
    Can I pass a unix variable to this pl/sql query?
    something like this inside the pl/sql block...
    declare
    begin
    select name into v_name from test where name = '${name}'   ----> need to get unix variable
    end;
    exit

    Satyki, my exact problem is the shell program is not accepting the input when i am trying to pass a variable
    to the pl/sql block. the variable is declared in the varibale file as d='01-SEP-08'
    this variable should replace the SQL where condition...
    Now when i call the shell
    $ test_1.sh '$d'
    test_1.sh[28]: 02-sep-08:  not found
    below is the shell
    #!/usr/bin/ksh
    . /home/btchproc/.profile
    . /home/btchproc/load_process/.BTCHVariables
    . /home/btchproc/load_process/.BTCHFunctions
    LOG_FILES_BATCH=$LOAD_BASE/log_files_batch/test_1.log
    echo " " >> $LOG_FILES_BATCH 2>&1
    echo "****************************************************" >> $LOG_FILES_BATCH 2>&1
    echo "**************  START OF THE PROCESS  **************" >> $LOG_FILES_BATCH 2>&1     
    echo "****************************************************" >> $LOG_FILES_BATCH 2>&1
    echo  >> $LOG_FILES_BATCH 2>&1
    date  >> $LOG_FILES_BATCH 2>&1
    echo "* EXECUTE test.SQL  *" >> $LOG_FILES_BATCH 2>&1
        SQL_NAME=test_1.sql ${d}
        run_sql test_1.sql  ${d}
    Below is the sql
    WHENEVER SQLERROR EXIT FAILURE;
    DECLARE
    x number;
    BEGIN
    -- Insert new daily assets and account records into the summ_new_temp table
    select count(1) into x from summ_new_wrap where trade_d = '&d' ;
    END;
    EXIT SUCCESS
    The variable is declared in BTCHvariable file
    ## * Name:          .BTCHVariables                               * ##
      LOAD_BASE='/home/btchproc/load_process'
      APPL_BASE='/home/btchproc/load_process'
      BATCH_DIR=$LOAD_BASE'/batch_files'
      BATCH_FILES_DIR=$LOAD_BASE/batch_files
      SQL_DIR=$LOAD_BASE/sql_files
      LOG_DIR_LOAD=$LOAD_BASE/log_files_load
      LOG_DIR_BATCH=$LOAD_BASE/log_files_batch
      FACTOR_THRHOLD=.03
      CONNECT_STRING='btchproc/test02'
      COUNT=0
      MAXRETCODE=0
      *d='02-sep-08'*
    ==================
    $ test_1.sh    
    test_1.sh[28]: 02-sep-08:  not found

  • Trying to pass and object variable to a method

    I have yet another question. I'm trying to display my output in succession using a next button. The button works and I get what I want using test results, however what I really want to do is pass it a variable instead of using a set number.
    I want to be able to pass the object variables myProduct, myOfficeSupplies, and maxNumber to method actionPerformed so they can be in-turn passed to the displayResults method which is called in the actionPerformed method. Since there is no direct call to actionPerformed because it is called within one of the built in methods, I can't tell it to receive and pass those variables. Is there a way to do it without having to pass them through the built-in methods?
    import javax.swing.JToolBar;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import java.net.URL;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Panel extends JPanel implements ActionListener
         protected JTextArea myTextArea;
         protected String newline = "\n";
         static final private String FIRST = "first";
         static final private String PREVIOUS = "previous";
         static final private String NEXT = "next";
         public Panel( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
                 super(new BorderLayout());
              int counter = 0;
                 //Create the toolbar.
                 JToolBar myToolBar = new JToolBar( "Still draggable" );
                 addButtons( myToolBar );
                 //Create the text area used for output.
                 myTextArea = new JTextArea( 450, 190 );
                 myTextArea.setEditable( false );
                 JScrollPane scrollPane = new JScrollPane( myTextArea );
                 //Lay out the main panel.
                 setPreferredSize(new Dimension( 450, 190 ));
                 add( myToolBar, BorderLayout.PAGE_START );
                 add( scrollPane, BorderLayout.CENTER );
              myTextArea.setText( packageData( myProduct, myOfficeSupplies, counter ) );
              setCounter( counter );
         } // End Constructor
         protected void addButtons( JToolBar myToolBar )
                 JButton myButton = null;
                 //first button
                 myButton = makeNavigationButton( FIRST, "Display first record", "First" );
                 myToolBar.add(myButton);
                 //second button
                 myButton = makeNavigationButton( PREVIOUS, "Display previous record", "Previous" );
                 myToolBar.add(myButton);
                 //third button
                 myButton = makeNavigationButton( NEXT, "Display next record", "Next" );
                 myToolBar.add(myButton);
         } //End method addButtons
         protected JButton makeNavigationButton( String actionCommand, String toolTipText, String altText )
                 //Create and initialize the button.
                 JButton myButton = new JButton();
                     myButton.setActionCommand( actionCommand );
                 myButton.setToolTipText( toolTipText );
                 myButton.addActionListener( this );
                   myButton.setText( altText );
                 return myButton;
         } // End makeNavigationButton method
             public void actionPerformed( ActionEvent e )
                 String cmd = e.getActionCommand();
                 // Handle each button.
              if (FIRST.equals(cmd))
              { // first button clicked
                          int counter = 0;
                   setCounter( counter );
                 else if (PREVIOUS.equals(cmd))
              { // second button clicked
                   counter = getCounter();
                      if ( counter == 0 )
                        counter = 5;  // 5 would be replaced with variable maxNumber
                        setCounter( counter );
                   else
                        counter = getCounter() - 1;
                        setCounter( counter );
              else if (NEXT.equals(cmd))
              { // third button clicked
                   counter = getCounter();
                   if ( counter == 5 )  // 5 would be replaced with variable maxNumber
                        counter = 0;
                        setCounter( counter );
                      else
                        counter = getCounter() + 1;
                        setCounter( counter );
                 displayResult( counter );
         } // End method actionPerformed
         private int counter;
         public void setCounter( int number ) // Declare setCounter method
              counter = number; // stores the counter
         } // End setCounter method
         public int getCounter()  // Declares getCounter method
              return counter;
         } // End method getCounter
         protected void displayResult( int counter )
              //Test statement
    //                 myTextArea.setText( String.format( "%d", counter ) );
              // How can I carry the myProduct and myOfficeSupplies variables into this method?
              myTextArea.setText( packageData( product, officeSupplies, counter ) );
                 myTextArea.setCaretPosition(myTextArea.getDocument().getLength());
             } // End method displayResult
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event dispatch thread.
         public void createAndShowGUI( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
                 //Create and set up the window.
                 JFrame frame = new JFrame("Products");
                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 //Add content to the window.
                 frame.add(new Panel( myProduct, myOfficeSupplies, maxNumber ));
                 //Display the window.
                 frame.pack();
                 frame.setVisible( true );
             } // End method createAndShowGUI
         public void displayData( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
              JTextArea myTextArea = new JTextArea(); // textarea to display output
              JFrame JFrame = new JFrame( "Products" );
              // For loop to display data array in a single Window
              for ( int counter = 0; counter < maxNumber; counter++ )  // Loop for displaying each product
                   myTextArea.append( packageData( myProduct, myOfficeSupplies, counter ) + "\n\n" );
                   JFrame.add( myTextArea ); // add textarea to JFrame
              } // End For Loop
              JScrollPane scrollPane = new JScrollPane( myTextArea ); //Creates the JScrollPane
              JFrame.setPreferredSize(new Dimension(350, 170)); // Sets the pane size
              JFrame.add(scrollPane, BorderLayout.CENTER); // adds scrollpane to JFrame
              JFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // Sets program to exit on close
              JFrame.setSize( 350, 170 ); // set frame size
              JFrame.setVisible( true ); // display frame
         } // End method displayData
         public String packageData( Product myProduct, OfficeSupplies myOfficeSupplies, int counter ) // Method for formatting output
              return String.format( "%s: %d\n%s: %s\n%s: %s\n%s: %s\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f",
              "Product Number", myOfficeSupplies.getProductNumber( counter ),
              "Product Name", myOfficeSupplies.getProductName( counter ),
              "Product Brand",myProduct.getProductBrand( counter ),
              "Number of Units in stock", myOfficeSupplies.getNumberUnits( counter ),
              "Price per Unit", myOfficeSupplies.getUnitPrice( counter ),
              "Total Value of Item in Stock is", myOfficeSupplies.getProductValue( counter ),
              "Restock charge for this product is", myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ),
              "Total Value of Inventory plus restocking fee", myOfficeSupplies.getProductValue( counter )+
                   myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ) );
         } // end method packageData
    } //End Class Panel

    multarnc wrote:
    My instructor has not been very forthcoming with assistance to her students leaving us to figure it out on our own.Aren't they all the same! Makes one wonder why they are called instructors. <sarcasm/>
    Of course it's highly likely that enough information was imparted for any sincere, reasonably intelligent student to actually figure it out, and learn the subject in the process.
    And if everything were spoonfed, how would one grade the performance of the students? Have them recite from memory
    public class HelloWorld left-brace
    indent public static void main left-parenthesis String left-bracket right-bracket args right-parenthesis left-brace
    And everywhere that Mary went
    The lamb was sure to go
    db

  • How to implement fuzzy search in Query variables

    Dear Experts,
    Fuzzy search is eazy implemented in the abap  , but I do not know how to implement fuzzy search in Query variables
    our company have  a report,with input variable of customer code,   the user want to input 3 bits as fuzzy search. for example,
    the customer code  have 10 bit,  she want to only  input 3 bits before-- EAE *
    and hope the results will  be displayed.  if you have any solution , please advise. 
    ManyTthanks.
    Best Regards.
    Steve

    closed

  • Passing parameters for fuzzy search

    Hello,
    I am using Oracle 11.2 and do fuzzy search as following:
    Create table tb_test(Nm varchar2(32));
    create index fuzzy_idx on tb_test(Nm) indextype is ctxsys.context parameters(' Wordlist STEM_FUZZY_PREF');
    select * from tb_test where contains(Nm, 'fuzzy(Wndy,,,weight)',1) >0;
    The query works fine for hardcoded string 'Wndy'. I just wonder how can I use parameter to pass the match string in PLSQL?
    Thanks,

    try this (not tested):
    Procedure findMatchNm(nmStr in VARCHAR2)
    IS
    oraCursor REF CURSOR
    str_val varchar2(100);BEGIN
    str_val := 'fuzzy('||nmStr||',,,weight)';OPEN OraCursor FOR
    'SELECT NM FROM TB_test WHERE contains(Nm, :s, 1)>0' USING str_val;LOOP
    FETCH...
    END LOOP;
    END;
    Edited by: stefan nebesnak on Jan 17, 2013 12:49 PM
    using bind variable

  • Passing Parameter/Variable into Dashboard URL

    Hi,
    Instead of having someone type in or search for a variable I was trying to determine a way to pass a variable directly into the URL
    I have tried:
    VARIABLE_SCREEN=X&BI_COMMAND_1-BI_COMMAND_TYPE=SET_VARIABLES_STATE&BI_COMMAND_1-VARIABLE_VALUES-VARIABLE_VALUE_1-VARIABLE_TYPE=VARIABLE_INPUT_STRING&BI_COMMAND_1-VARIABLE_VALUES-VARIABLE_VALUE_1-VARIABLE_TYPE-VARIABLE_INPUT_STRING=XXXXXX&BI_COMMAND_1-VARIABLE_VALUES-VARIABLE_VALUE_1-VARIABLE=XXXXXXXXX
    added to the dashboard URL:
    pcd!3aportal_content!2fcom.sap.pct!2fplatform_add_ons!2fcom.sap.ip.bi!2fiViews!2fcom.sap.ip.bi.bex?TEMPLATE=DASHBOARD
    But any time I try this method it just refreshes the variable screen...
    Am I missing something? Maybe I think its easier then it really is.
    Thanks,

    Mike,
    Variable_screen=x will always force the variable screen to display.
    Try just variable_Screen=&BI_command etc etc

  • [Solved] Trying to set environment variables in script

    I'm trying to create a script that will pass environment variables that will stay valid after the script exits.
    The problem with this is that (by design?) when executing a script it opens a child environment, and inherits the environmental variables from the parent.
    The issue is that the child cannot interact with the parent's environment so setting variables like:
    export http_proxy='http://server:port'
    wont stay valid once the script exits. I've verified this by trying to echo the variable once the script completes, and i receive an empty reply.
    The only work around I have for this is to include this within a bash profile, however I cant just keep adding scripts into my bash profile, because that seems counter-intuitive.
    Is there any way to do what I'm trying to do? Or am I just grabbing at straws here?
    below is my code for my script, perhaps I've done something wrong...
    proxy=x.x.x.x
    port=#
    username=domain\\username
    password=userpassword
    export http_proxy='http://$username\:$password@$proxy\:$port'
    export ftp_proxy='ftp://$username\:$password@$proxy\:$port'
    exit
    Last edited by isolatedvirus (2011-10-04 10:58:52)

    One thing to note is that you should specify the sourced file by its path so it includes a slash, quoting bash(1):
    source filename [arguments]
    Read and execute commands from filename in the current shell environment
    and return the exit status of the last command executed from filename.
    If filename does not contain a slash, file names in PATH are used to find
    the directory containing filename. The file searched for in PATH need
    not be executable. When bash is not in posix mode, the current directory
    is searched if no file is found in PATH. If the sourcepath option to the
    shopt builtin command is turned off, the PATH is not searched
    So if sourcepath is set (as by default), you can end up sourcing the wrong file, e.g.
    source file
    (DON'T do it!)
    will really source /usr/bin/file, even if you have 'file' in current directory.
    Instead, always specify the path,
    source ./file
    Keep this in mind or you're in for a big surprise.
    Last edited by lolilolicon (2011-10-04 11:33:48)

  • How do i pass a variable in flex

    i've been looking all over google for how to pass a variable yet
    i've come up empty handed
    i have a C code and as3
    i've never been able to get a C program to compile on my own, this is from a tutorial im trying to understand about raycasting
    from what i can gather i think that the variables are passed threw this
    #######raycaster.c##########
    AS3_Val loop( void* self, AS3_Val args )
        AS3_ArrayValue(args,"IntType,IntType,IntType,IntType",&K_UP,&K_DOWN,&K_LEFT,&K_RIGHT);
        CastRay();
        int opos,j,i,jpos;
        for(j=0; j < resY; j++ ){
            jpos = resX*j;
            for(i=0; i < resX; i++ ){
                opos = (jpos+i);
                tBuffer[opos] = buffer[i][j];
            }//end of for
        }//end of for
        return 0;
    }//end of loop
    however not one of the values inside of AS3_ArrayValue is to be found on the Main.as
    this is the only function that comunicates with the C code, but i could be wrong
    ####Main.as######
            private function enterFrame(event:Event):void {
                alcRCLib.loop(upKey,downKey,leftKey,rightKey);
                alchemyMemory.position=alcScreenBufferPointer;
                screenBitmapData.setPixels(screenBitmapData.rect,alchemyMemory);
    the reason i want to do this, other than to know how, because that would be useful above all else, i've already written a as3 that comunicates with php
    to get a array of images  for a topdown game, and i wouldn't know how to load these variables to C from a HTTP request but if i can get flash to tell c what they are then every thing worked out
    heres both codes in full
    #####Main.as####
    *Alchemy Ray Caster
    *April 6, 2010
    *Bruce Jawn
    *http://bruce-lab.blogspot.com
    *Copyright (c) <2010> <Bruce Jawn>
    *This software is released under the MIT License
    *<http://www.opensource.org/licenses/mit-license.php>
    package {
    //    import cmodule.Ray_Caster._worldMap;
    //    import cmodule.Ray_Caster._worldMap;
        import cmodule.Ray_Caster.CLibInit;
    //    import cmodule.Ray_Caster.TextFieldI;
        import flash.display.*;
        import flash.text.*;
        import flash.events.*;
        import flash.geom.*;
        import flash.text.engine.TextBlock;
        import flash.text.engine.TextLine;
        import flash.text.TextField;
        import flash.utils.*;
        import flash.ui.*;
        [SWF(width="840", height="880")]
        public class Main extends Sprite {
            [Embed(source="../wolftex/barrel.png")]
            public static var barrelClass:Class;
            [Embed(source="../wolftex/bluestone.png")]
            public static var bluestoneClass:Class;
            [Embed(source="../wolftex/colorstone.png")]
            public static var colorstoneClass:Class;
            [Embed(source="../wolftex/eagle.png")]
            public static var eagleClass:Class;
            [Embed(source="../wolftex/greenlight.png")]
            public static var greenlightClass:Class;
            [Embed(source="../wolftex/greystone.png")]
            public static var greystoneClass:Class;
            [Embed(source="../wolftex/mossy.png")]
            public static var mossyClass:Class;
            [Embed(source="../wolftex/pillar.png")]
            public static var pillarClass:Class;
            [Embed(source="../wolftex/purplestone.png")]
            public static var purplestoneClass:Class;
            [Embed(source="../wolftex/redbrick.png")]
            public static var redbrickClass:Class;
            [Embed(source="../wolftex/wood.png")]
            public static var woodClass:Class;
            //Array to hold all the textures
            private var texs:Array=[];
            private var worldMap:Array = [];
            //private var worldMap[1]:Array=[];
            private static const SCREEN_WIDTH:int=640;
            private static const SCREEN_HEIGHT:int=480;
            private var screenBitmapData:BitmapData;
            private var screenBitmap:Bitmap;
            private var alchemyMemory:ByteArray;
            private var alcRCLib:Object;
            private var cLibInit:CLibInit;
            private var alcScreenBufferPointer:uint;
            private var alcTexPointer:uint;
            private var upKey:int=0;
            private var downKey:int=0;
            private var leftKey:int=0;
            private var rightKey:int=0;
            private var a:flash.text.TextField;
            public function Main() {
                stage.frameRate=60;
                stage.align=StageAlign.TOP_LEFT;
                stage.scaleMode=StageScaleMode.NO_SCALE;
                stage.fullScreenSourceRect=new Rectangle(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
                init();
                }//end of function Main
            private function init():void {
                initBitmaps();
                initAlchemy();
                initRendering();
            }//end of function init
            private function initBitmaps():void {
                texs.push(prepareBitmapData(new eagleClass().bitmapData  ));
                texs.push(prepareBitmapData(new redbrickClass().bitmapData  ));
                texs.push(prepareBitmapData(new purplestoneClass().bitmapData  ));
                texs.push(prepareBitmapData(new greystoneClass().bitmapData  ));
                texs.push(prepareBitmapData(new bluestoneClass().bitmapData  ));
                texs.push(prepareBitmapData(new mossyClass().bitmapData  ));
                texs.push(prepareBitmapData(new woodClass().bitmapData  ));
                texs.push(prepareBitmapData(new colorstoneClass().bitmapData  ));
                texs.push(prepareBitmapData(new barrelClass().bitmapData  ));
                texs.push(prepareBitmapData(new pillarClass().bitmapData  ));
                texs.push(prepareBitmapData(new greenlightClass().bitmapData  ));
                screenBitmapData=new BitmapData(SCREEN_WIDTH,SCREEN_HEIGHT,false,0);
                screenBitmap=new Bitmap(screenBitmapData);
                addChild(screenBitmap);
                worldMap[1] = (1,2,3,4);
                worldMap[2] = (1,2,3,4);
                worldMap[3] = (1,2,3,4);
                worldMap[4] = (1,2,3,4);
                worldMap[5] = (1,2,3,4);
                worldMap[6] = (1,2,3,4);
                worldMap[7] = (1,2,3,4);
                }//end of function initBitmaps
            //Prepare the bitmap once to take into account the lower-endianess of the alchemy code.
            private function prepareBitmapData(sourceMap:BitmapData):BitmapData {
                var outBitmapData:BitmapData=sourceMap.clone();
                outBitmapData=new BitmapData(outBitmapData.width,outBitmapData.height,true,0xFF000000);
                outBitmapData.copyChannel(sourceMap,outBitmapData.rect,outBitmapData.rect.topLeft,BitmapD ataChannel.ALPHA,BitmapDataChannel.BLUE);
                outBitmapData.copyChannel(sourceMap,outBitmapData.rect,outBitmapData.rect.topLeft,BitmapD ataChannel.RED,BitmapDataChannel.GREEN);
                outBitmapData.copyChannel(sourceMap,outBitmapData.rect,outBitmapData.rect.topLeft,BitmapD ataChannel.GREEN,BitmapDataChannel.RED);
                outBitmapData.copyChannel(sourceMap,outBitmapData.rect,outBitmapData.rect.topLeft,BitmapD ataChannel.BLUE,BitmapDataChannel.ALPHA);
                return outBitmapData;
            }//end of function prepareBitmapData
            private function initAlchemy():void {
                cLibInit=new CLibInit  ;
                alcRCLib=cLibInit.init();
                //Retrieve the "Alchemy Memory".
                var ns:Namespace=new Namespace("cmodule.Ray_Caster");
                alchemyMemory=ns::gstate.ds;
                //Allocate the buffers in Alchemy.
                alcScreenBufferPointer=alcRCLib.initializeScreenBuffer(SCREEN_WIDTH,SCREEN_HEIGHT);//Setu p a screenbuffer of size x,y;
                //Copy the textures to alchemy memory.
                for (var i:int=0; i<11; i++) {
                    var ba:ByteArray=texs[i].getPixels(texs[i].rect);
                    alcTexPointer=alcRCLib.initializeTexBuffer(i);
                    alchemyMemory.position=alcTexPointer;
                    alchemyMemory.writeBytes(ba,0,ba.length);
                }//end of for
            }//end of function initAlchemy
            private function initRendering():void {
                stage.addEventListener(KeyboardEvent.KEY_DOWN,key_pressed);
                stage.addEventListener(KeyboardEvent.KEY_UP,key_released);
                addEventListener(Event.ENTER_FRAME,enterFrame);
            }//end of function initRendering
            private function enterFrame(event:Event):void {
                alcRCLib.loop(upKey,downKey,leftKey,rightKey);
                alchemyMemory.position=alcScreenBufferPointer;
                screenBitmapData.setPixels(screenBitmapData.rect,alchemyMemory);
                }//end of function enterFrame
            private function key_pressed(e:KeyboardEvent):void {
                switch (e.keyCode) {
                    case Keyboard.UP :
                        upKey=1;
                        break;
                    case Keyboard.DOWN :
                        downKey=1;
                        break;
                    case Keyboard.LEFT :
                        leftKey=1;
                        break;
                    case Keyboard.RIGHT :
                        rightKey=1;
                        break;
                }//end of switch
                }//end of function key_pressed
            private function key_released(e:KeyboardEvent):void {
                switch (e.keyCode) {
                    case Keyboard.UP :
                        upKey=0;
                        break;
                    case Keyboard.DOWN :
                        downKey=0;
                        break;
                    case Keyboard.LEFT :
                        leftKey=0;
                        break;
                    case Keyboard.RIGHT :
                        rightKey=0;
                        break;               
                        }//end of switch
                }//end of function key_released
                }//end of class
    }//end of package
    ###raycaster####
    //Raycasting Engine from Lode's Computer Graphics Tutorial
    //http://www.student.kuleuven.be/~m0216922/CG/raycasting.html
    //Modified for Alchemy by Bruce Jawn
    //http://bruce-lab.blogspot.com
    #include "AS3.h"
    #include <math.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    //============================================================
    //============================================================
    enum bool {false=0,true=!false};
    #define screenWidth 1640
    #define screenHeight 1480
    #define texWidth 64
    #define texHeight 64
    #define mapWidth 24
    #define mapHeight 24
    //1D Screen Buffer
    int* tBuffer;
    int resX = 0;
    int resY = 0;
    //2D Screen Buffer
    int buffer[screenWidth][screenHeight];
    //1D Zbuffer
    double ZBuffer[screenWidth];
    //============================================================
    //============================================================
    //textures
    int texture[11][texWidth*texHeight];
    #define numSprites 19
    //arrays used to sort the sprites
    int spriteOrder[numSprites];
    double spriteDistance[numSprites];
    struct SSprite
      double x;
      double y;
      int texture;
    struct SSprite sprite[numSprites]=
      //green light in front of playerstart
      {20.5, 11.5, 10},
      //green lights in every room
      {18.5,4.5, 10},
      {10.0,4.5, 10},
      {10.0,12.5,10},
      {3.5, 6.5, 10},
      {3.5, 20.5,10},
      {3.5, 14.5,10},
      {14.5,20.5,10},
      //row of pillars in front of wall: fisheye test
      {18.5, 10.5, 9},
      {18.5, 11.5, 9},
      {18.5, 12.5, 9},
      //some barrels around the map
      {21.5, 1.5, 8},
      {15.5, 1.5, 8},
      {16.0, 1.8, 8},
      {16.2, 1.2, 8},
      {3.5,  2.5, 8},
      {9.5, 15.5, 8},
      {10.0, 15.1,8},
      {10.5, 15.8,8},
    //============================================================
    //============================================================
    //map
    int worldMap[mapWidth][mapHeight] =
      {8,8,8,8,8,8,8,8,8,8,8,4,4,6,4,4,6,4,6,4,4,4,6,4},
      {8,0,0,0,0,0,0,0,0,0,8,4,0,0,0,0,0,0,0,0,0,0,0,4},
      {8,0,3,3,0,0,0,0,0,8,8,4,0,0,0,0,0,0,0,0,0,0,0,6},
      {8,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6},
      {8,0,3,3,0,0,0,0,0,8,8,4,0,0,0,0,0,0,0,0,0,0,0,4},
      {8,0,0,0,0,0,0,0,0,0,8,4,0,0,0,0,0,6,6,6,0,6,4,6},
      {8,8,8,8,0,8,8,8,8,8,8,4,4,4,4,4,4,6,0,0,0,0,0,6},
      {7,7,7,7,0,7,7,7,7,0,8,0,8,0,8,0,8,4,0,4,0,6,0,6},
      {7,7,0,0,0,0,0,0,7,8,0,8,0,8,0,8,8,6,0,0,0,0,0,6},
      {7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,6,0,0,0,0,0,4},
      {7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,6,0,6,0,6,0,6},
      {7,7,0,0,0,0,0,0,7,8,0,8,0,8,0,8,8,6,4,6,0,6,6,6},
      {7,7,7,7,0,7,7,7,7,8,8,4,0,6,8,4,8,3,3,3,0,3,3,3},
      {2,2,2,2,0,2,2,2,2,4,6,4,0,0,6,0,6,3,0,0,0,0,0,3},
      {2,2,0,0,0,0,0,2,2,4,0,0,0,0,0,0,4,3,0,0,0,0,0,3},
      {2,0,0,0,0,0,0,0,2,4,0,0,0,0,0,0,4,3,0,0,0,0,0,3},
      {1,0,0,0,0,0,0,0,1,4,4,4,4,4,6,0,6,3,3,0,0,0,3,3},
      {2,0,0,0,0,0,0,0,2,2,2,1,2,2,2,6,6,0,0,5,0,5,0,5},
      {2,2,0,0,0,0,0,2,2,2,0,0,0,2,2,0,5,0,5,0,0,0,5,5},
      {2,0,0,0,0,0,0,0,2,0,0,0,0,0,2,5,0,5,0,5,0,5,0,5},
      {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5},
      {2,0,0,0,0,0,0,0,2,0,0,0,0,0,2,5,0,5,0,5,0,5,0,5},
      {2,2,0,0,0,0,0,2,2,2,0,0,0,2,2,0,5,0,5,0,0,0,5,5},
      {2,2,2,2,1,2,2,2,2,2,2,1,2,2,2,5,5,5,5,5,5,5,5,5}
    //============================================================
    //============================================================
    double posX = 22.0, posY = 11.5; //x and y start position
    double dirX = -1.0, dirY = 0.0; //initial direction vector
    double planeX = 0.0, planeY = 0.66; //the 2d raycaster version of camera plane
    int K_LEFT=0;
    int K_RIGHT=0;
    int K_UP=0;
    int K_DOWN=0;
    //speed modifiers
    double moveSpeed =  .30; //the constant value is in squares/second
    double rotSpeed =   .20; //the constant value is in radians/second
    //============================================================
    //============================================================
    AS3_Val initializeScreenBuffer(void* self, AS3_Val args)
        AS3_ArrayValue(args, "IntType, IntType", &resX, &resY);
        tBuffer = malloc( resX * resY * sizeof(int) );
        return AS3_Ptr( tBuffer );
    }//end of initializeScreenBuffer
    //used to load some textures & sprite textures
    AS3_Val initializeTexBuffer(void* self, AS3_Val args)
        int index;
        AS3_ArrayValue(args, "IntType", &index);
        return AS3_Ptr( texture[index] );
    }//end of initializeTexBuffer
    //start the main loop
    AS3_Val loop( void* self, AS3_Val args )
        AS3_ArrayValue(args,"IntType,IntType,IntType,IntType",&K_UP,&K_DOWN,&K_LEFT,&K_RIGHT);
        CastRay();
        int opos,j,i,jpos;
        for(j=0; j < resY; j++ ){
            jpos = resX*j;
            for(i=0; i < resX; i++ ){
                opos = (jpos+i);
                tBuffer[opos] = buffer[i][j];
            }//end of for
        }//end of for
        return 0;
    }//end of loop
    int main()
        AS3_Val initializeScreenBufferMethod = AS3_Function( NULL,initializeScreenBuffer );
        AS3_Val loopMethod = AS3_Function( NULL,loop );
        AS3_Val initializeTexBufferMethod = AS3_Function( NULL,initializeTexBuffer );
        AS3_Val result = AS3_Object("initializeScreenBuffer:AS3ValType,loop:AS3ValType,initializeTexBuffer:AS3ValT ype"
                                    ,initializeScreenBufferMethod,loopMethod,initializeTexBufferMethod);
        AS3_Release( initializeScreenBufferMethod );
        AS3_Release( loopMethod );
        AS3_Release( initializeTexBufferMethod );
        AS3_LibInit( result );
        return 0;
    }//end of main
    //================================================================
    //================================================================
    void CastRay()
        printf ("Hello World!\n");
        int x;
        int y;
        int w=screenWidth;
        int h=screenHeight;
        for( x = 0; x < screenWidth; x++) for( y = 0; y < screenHeight; y++) {buffer[x][y] = 0;} //clear the buffer instead of cls()
        for(x = 0; x < w; x++)
          //calculate ray position and direction
          double cameraX = 2 * x / (double)(w) - 1; //x-coordinate in camera space    
          double rayPosX = posX;
          double rayPosY = posY;
          double rayDirX = dirX + planeX * cameraX;
          double rayDirY = dirY + planeY * cameraX;
          //which box of the map we're in 
          int mapX = (int)(rayPosX);
          int mapY = (int)(rayPosY);
          //length of ray from current position to next x or y-side
          double sideDistX;
          double sideDistY;
          //length of ray from one x or y-side to next x or y-side
          double deltaDistX = sqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX));
          double deltaDistY = sqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY));
          double perpWallDist;
          //what direction to step in x or y-direction (either +1 or -1)
          int stepX;
          int stepY;
          int hit = 0; //was there a wall hit?
          int side; //was a NS or a EW wall hit?
          //calculate step and initial sideDist
          if (rayDirX < 0)
            stepX = -1;
            sideDistX = (rayPosX - mapX) * deltaDistX;
          }//end of if (rayDirX < 0)
          else
            stepX = 1;
            sideDistX = (mapX + 1.0 - rayPosX) * deltaDistX;
          }//end of else
          if (rayDirY < 0)
            stepY = -1;
            sideDistY = (rayPosY - mapY) * deltaDistY;
          }//end of if (rayDirY < 0)
          else
            stepY = 1;
            sideDistY = (mapY + 1.0 - rayPosY) * deltaDistY;
          }//end of else
          //perform DDA
          while (hit == 0)
            //jump to next map square, OR in x-direction, OR in y-direction
            if (sideDistX < sideDistY)
              sideDistX += deltaDistX;
              mapX += stepX;
              side = 0;
            }//end of if (sideDistX < sideDistY)
            else
              sideDistY += deltaDistY;
              mapY += stepY;
              side = 1;
            }//end of else
            //Check if ray has hit a wall      
            if (worldMap[mapX][mapY] > 0) hit = 1;
          }//end of while (hit == 0)
          //Calculate distance of perpendicular ray (oblique distance will give fisheye effect!)   
          if (side == 0) perpWallDist = fabs((mapX - rayPosX + (1 - stepX) / 2) / rayDirX);
          else       perpWallDist = fabs((mapY - rayPosY + (1 - stepY) / 2) / rayDirY);
          //Calculate height of line to draw on screen      
          int lineHeight = abs((int)(h / perpWallDist));
          //calculate lowest and highest pixel to fill in current stripe
          int drawStart = -lineHeight / 2 + h / 2;
          if(drawStart < 0) drawStart = 0;
          int drawEnd = lineHeight / 2 + h / 2;
          if(drawEnd >= h) drawEnd = h - 1;
          //texturing calculations
          int texNum = worldMap[mapX][mapY] - 1; //1 subtracted from it so that texture 0 can be used!
          //calculate value of wallX
          double wallX; //where exactly the wall was hit
          if (side == 1) wallX = rayPosX + ((mapY - rayPosY + (1 - stepY) / 2) / rayDirY) * rayDirX;
          else       wallX = rayPosY + ((mapX - rayPosX + (1 - stepX) / 2) / rayDirX) * rayDirY;
          wallX -= floor((wallX));
          //x coordinate on the texture
          int texX = (int)(wallX * (double)(texWidth));
          if(side == 0 && rayDirX > 0) texX = texWidth - texX - 1;
          if(side == 1 && rayDirY < 0) texX = texWidth - texX - 1;
          int y;
          for(y = drawStart; y < drawEnd; y++)
            int d = y * 256 - h * 128 + lineHeight * 128; //256 and 128 factors to avoid floats
            int texY = ((d * texHeight) / lineHeight) / 256;
            int color = texture[texNum][texWidth * texY + texX];
            //make color darker for y-sides: R, G and B byte each divided through two with a "shift" and an "and"
            if(side == 1) color = (color >> 1) & 8355711;
            buffer[x][y] = color;
          }//end of for(y = drawStart; y < drawEnd; y++)
          //SET THE ZBUFFER FOR THE SPRITE CASTING
          ZBuffer[x] = perpWallDist; //perpendicular distance is used
          //FLOOR CASTING
          double floorXWall, floorYWall; //x, y position of the floor texel at the bottom of the wall
          //4 different wall directions possible
          if(side == 0 && rayDirX > 0)
            floorXWall = mapX;
            floorYWall = mapY + wallX;
          }//end of if(side == 0 && rayDirX > 0)
          else if(side == 0 && rayDirX < 0)
            floorXWall = mapX + 1.0;
            floorYWall = mapY + wallX;
          }//end of else if(side == 0 && rayDirX < 0)
          else if(side == 1 && rayDirY > 0)
            floorXWall = mapX + wallX;
            floorYWall = mapY;
          }//end of else if(side == 1 && rayDirY > 0)
          else
            floorXWall = mapX + wallX;
            floorYWall = mapY + 1.0;
          }//end of else
          double distWall, distPlayer, currentDist;
          distWall = perpWallDist;
          distPlayer = 0.0;
          if (drawEnd < 0) drawEnd = h; //becomes < 0 when the integer overflows
          //draw the floor from drawEnd to the bottom of the screen
          for(y = drawEnd + 1; y < h; y++)
            currentDist = h / (2.0 * y - h); //you could make a small lookup table for this instead
            double weight = (currentDist - distPlayer) / (distWall - distPlayer);
            double currentFloorX = weight * floorXWall + (1.0 - weight) * posX;
            double currentFloorY = weight * floorYWall + (1.0 - weight) * posY;
            int floorTexX, floorTexY;
            floorTexX = (int)(currentFloorX * texWidth) % texWidth;
            floorTexY = (int)(currentFloorY * texHeight) % texHeight;
            //floor
            buffer[x][y] = (texture[3][texWidth * floorTexY + floorTexX] >> 1) & 8355711;
            //ceiling (symmetrical!)
            buffer[x][h - y] = texture[6][texWidth * floorTexY + floorTexX];
          }//end of for(y = drawEnd + 1; y < h; y++)
        }//end of for(x = 0; x < w; x++)
        //SPRITE CASTING
        //sort sprites from far to close
        int i;
        for(i = 0; i < numSprites; i++)
          spriteOrder[i] = i;
          spriteDistance[i] = ((posX - sprite[i].x) * (posX - sprite[i].x) + (posY - sprite[i].y) * (posY - sprite[i].y)); //sqrt not taken, unneeded
        }//end of for(i = 0; i < numSprites; i++)
        combSort(spriteOrder, spriteDistance, numSprites);
        //after sorting the sprites, do the projection and draw them
        for(i = 0; i < numSprites; i++)
          //translate sprite position to relative to camera
          double spriteX = sprite[spriteOrder[i]].x - posX;
          double spriteY = sprite[spriteOrder[i]].y - posY;
          //transform sprite with the inverse camera matrix
          // [ planeX   dirX ] -1                                       [ dirY      -dirX ]
          // [               ]       =  1/(planeX*dirY-dirX*planeY) *   [                 ]
          // [ planeY   dirY ]                                          [ -planeY  planeX ]
          double invDet = 1.0 / (planeX * dirY - dirX * planeY); //required for correct matrix multiplication
          double transformX = invDet * (dirY * spriteX - dirX * spriteY);
          double transformY = invDet * (-planeY * spriteX + planeX * spriteY); //this is actually the depth inside the screen, that what Z is in 3D      
          int spriteScreenX = (int)((w / 2) * (1 + transformX / transformY));
          //parameters for scaling and moving the sprites
          #define uDiv 1
          #define vDiv 1
          #define vMove 0.0
          int vMoveScreen = (int)(vMove / transformY);
          //calculate height of the sprite on screen
          int spriteHeight = abs((int)(h / (transformY))) / vDiv; //using "transformY" instead of the real distance prevents fisheye
          //calculate lowest and highest pixel to fill in current stripe
          int drawStartY = -spriteHeight / 2 + h / 2 + vMoveScreen;
          if(drawStartY < 0) drawStartY = 0;
          int drawEndY = spriteHeight / 2 + h / 2 + vMoveScreen;
          if(drawEndY >= h) drawEndY = h - 1;
          //calculate width of the sprite
          int spriteWidth = abs( (int) (h / (transformY))) / uDiv;
          int drawStartX = -spriteWidth / 2 + spriteScreenX;
          if(drawStartX < 0) drawStartX = 0;
          int drawEndX = spriteWidth / 2 + spriteScreenX;
          if(drawEndX >= w) drawEndX = w - 1;
          //loop through every vertical stripe of the sprite on screen
          int stripe;
          for(stripe = drawStartX; stripe < drawEndX; stripe++)
            int texX = (int)(256 * (stripe - (-spriteWidth / 2 + spriteScreenX)) * texWidth / spriteWidth) / 256;
            //the conditions in the if are:
            //1) it's in front of camera plane so you don't see things behind you
            //2) it's on the screen (left)
            //3) it's on the screen (right)
            //4) ZBuffer, with perpendicular distance
            int y;
            if(transformY > 0 && stripe > 0 && stripe < w && transformY < ZBuffer[stripe])
            for(y = drawStartY; y < drawEndY; y++) //for every pixel of the current stripe
              int d = (y-vMoveScreen) * 256 - h * 128 + spriteHeight * 128; //256 and 128 factors to avoid floats
              int texY = ((d * texHeight) / spriteHeight) / 256;
              unsigned int color = texture[sprite[spriteOrder[i]].texture][texWidth * texY + texX]; //get current color from the texture//??????????????????
              if((color & 0x00FFFFFF) != 0) buffer[stripe][y] = color; //paint pixel if it isn't black, black is the invisible color
            }//end of for(y = drawStartY; y < drawEndY; y++)
          }//end of for(stripe = drawStartX; stripe < drawEndX; stripe++)
        }//end of for(i = 0; i < numSprites; i++)
        //readKeys
        //move forward if no wall in front of you
        if (K_UP)
          if(worldMap[(int)(posX + dirX * moveSpeed)][(int)(posY)] == false) posX += dirX * moveSpeed;
          if(worldMap[(int)(posX)][(int)(posY + dirY * moveSpeed)] == false) posY += dirY * moveSpeed;
        }//end of if (K_UP)
        //move backwards if no wall behind you
        if (K_DOWN)
          if(worldMap[(int)(posX - dirX * moveSpeed)][(int)(posY)] == false) posX -= dirX * moveSpeed;
          if(worldMap[(int)(posX)][(int)(posY - dirY * moveSpeed)] == false) posY -= dirY * moveSpeed;
        }//end of if (K_DOWN)
        //rotate to the right
        if (K_RIGHT)
          //both camera direction and camera plane must be rotated
          double oldDirX = dirX;
          dirX = dirX * cos(-rotSpeed) - dirY * sin(-rotSpeed);
          dirY = oldDirX * sin(-rotSpeed) + dirY * cos(-rotSpeed);
          double oldPlaneX = planeX;
          planeX = planeX * cos(-rotSpeed) - planeY * sin(-rotSpeed);
          planeY = oldPlaneX * sin(-rotSpeed) + planeY * cos(-rotSpeed);
        }//end of if (K_RIGHT)
        //rotate to the left
        if (K_LEFT)
          //both camera direction and camera plane must be rotated
          double oldDirX = dirX;
          dirX = dirX * cos(rotSpeed) - dirY * sin(rotSpeed);
          dirY = oldDirX * sin(rotSpeed) + dirY * cos(rotSpeed);
          double oldPlaneX = planeX;
          planeX = planeX * cos(rotSpeed) - planeY * sin(rotSpeed);
          planeY = oldPlaneX * sin(rotSpeed) + planeY * cos(rotSpeed);
        }//end of if (K_LEFT)
    }//end of CastRay
    //sort algorithm
    void combSort(int* order, double* dist, int amount)
      int gap = amount;
      enum bool swapped = false;
      while(gap > 1 || swapped)
        //shrink factor 1.3
        gap = (gap * 10) / 13;
        if(gap == 9 || gap == 10) gap = 11;
        if (gap < 1) gap = 1;
        swapped = false;
        int i;
        for (i = 0; i < amount - gap; i++)
          int j = i + gap;
          if (dist[i] < dist[j])
            double disttemp=dist[i];
            dist[i]=dist[j];
            dist[j]=disttemp;
            int ordertemp=order[i];
            order[i]=order[j];
            order[j]=ordertemp;
            swapped = true;
          }//end of if (dist[i] < dist[j])
        }//end of for (i = 0; i < amount - gap; i++)
      }//end of while(gap > 1 || swapped)
    }//end of combSort
    the sorce file can be found here http://bruce-lab.blogspot.com/2010/04/alchemy-ray-casting-engine-source-code.html

    RadioactiveLizard, you need adobe alchemy (http://labs.adobe.com/technologies/alchemy/) to compile the C code to a swc,
    not pass variables to C directly.

  • LoadVars-using send to pass a variable from flash to php

    For the life of me, I've tried everything:
    I've researched LoadVars on Adobe forum, used David Powers'
    books, googled 'flash to php', LoadVars, etc. and tried
    sendAndLoad, send, and using $_POST, $_GET, $_REQUEST.
    $HTTP_POSTVARS but I keep getting this same error. any advice
    please?
    I have a Unix server running Apache/PHP 4 - LoadVars worked
    to load name-value pairs into an array -see thread)
    My goal with this simple app is to prototype being able to
    pass a variable from flash to a variable in php.
    Parse error: syntax error, unexpected T_VARIABLE in
    flash_to_SQL.php on line 5
    Actionscript 2.0 code:
    var c :LoadVars = new LoadVars();
    c.testing = "123FOUR";
    c.send ("
    http://127.0.0.1/flash_to_SQL.php","_self","POST");
    php code: (I also tried $_POST, $_GET, $_REQUEST.
    $HTTP_POSTVARS)
    <?php
    //mysql 4.1.2, php 4 , NO mysqli
    ecbo $_REQUEST ['testing'];
    /?>

    var formData:LoadVars = new LoadVars();
    formData.fname = "Name";
    formData.send("
    http://www.website.com/flash_php.php",
    formData, "POST");
    <?php
    $name = $_POST['fname'];
    echo $name;
    ?>

  • Passing Session variable of DATE data type to opaque view filter

    Hi Everyone,
    Can you guys please help me in passing session variable of DATE data type in RPD's physical layer 'opaque view' filter for Oracle database
    I tried following syntax, syntax wise I didn't got getting any error, but at the same time this opaque view is not fetching any records as well. my session variable is "END_DATE" and its value is 1998/12/31:00:00:00(as shown in RPD session windows, datatype is DATETIME)
    SELECT AMOUNT_SOLD, CHANNEL_ID, CUST_ID, PROD_ID, PROMO_ID, QUANTITY_SOLD, TIME_ID FROM SH.SALES
    WHERE TIME_ID =TO_DATE( 'VALUEOF(NQ_SESSION.END_DATE)','MM/DD/YYYY')
    SELECT AMOUNT_SOLD, CHANNEL_ID, CUST_ID, PROD_ID, PROMO_ID, QUANTITY_SOLD, TIME_ID FROM SH.SALES
    WHERE TIME_ID = TO_DATE( 'VALUEOF(NQ_SESSION."END_DATE")','MM/DD/YYYY')
    SELECT AMOUNT_SOLD, CHANNEL_ID, CUST_ID, PROD_ID, PROMO_ID, QUANTITY_SOLD, TIME_ID FROM SH.SALES
    WHERE TRUNC(TIME_ID) = TO_DATE( 'VALUEOF(NQ_SESSION."END_DATE")','MM/DD/YYYY')
    In past, I was able to pass a session variable into a opaque view filter using DATEOF function, but that was in DB2.
    I appreciate your time and help

    Finally, I got right format. here it is
    to_date(substr('valueof(NQ_SESSION.END_DATE)',1,10), 'yyyy-mm-dd')
    and here is the source from where I got this information
    Using OBIEE Session Variables in Select Tables in the Physical Layer

  • Passing a variable from one thread to another

    Hi. I'm trying to produce a chat program in Java but need to pass a variable between two threads. I have included a snipet of the code.
    import java.io.*;
    import java.net.*;
    class IndividualConnection extends Thread
         public Socket clientSocket;
         String userName = "";
         public IndividualConnection(Socket connectingSocket)
              clientSocket = connectingSocket;
    public login(String name)
    userName = name;
         public void messageUser(Socket socket, String msg)
              try
                   Socket newSocket = new Socket("192.168.0.162",5163);     
                   DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
                   outToServer.writeBytes(msg + '\n');     
              catch(Exception e)
                   System.out.println("The connection with the client has been closed.");
                   this.stop();
    public void run()
         Socket global = clientSocket;
    // etc etc
    A number of threads are created based on code similar to the above. Each thread communicates to a different client on the chat program. However, I want to be able to send messages between the clients.
    Each thread has a method called messageUser(Socket socket, String msg). I should (hopefully) be able to send a message to anyone using the prog if I can access their socket. The problem is that the socket objects for each client is held in the clients own thread. I have tried writing some code to find the Socket object in another thread but to no success. The code I am trying is shown below.
         public Socket findContact(String name)
              ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
              int numThreads = currentGroup.activeCount();
              Thread[] listOfThreads = new Thread[numThreads];
              currentGroup.enumerate(listOfThreads);
              for (int i = 0; i < numThreads; i++)
                   String threadName = listOfThreads.getName();
                   if (threadName.compareTo(name) == 0)
                   //     Socket tempSocket = threadName[i].getClass().getField(clientSocket);
              return tempSocket;
    The line I have commented out does not work. Please could someone tell me how to carry out this task. I have spent many hours trying to solve this but am not able to. The chat server is nearly complete now. I just need to find a way of obtaining another threads socket.
    I hope the problem is comprehensible. I have found it difficult to explain clearly. Many thanks.

    Really simple, inelegant solution:
    class MyThread extends Thread {
    Socket socket;
    MyThread( Socket s ) { socket = s; }
    public Socket getSocket() { return socket; }
    }Better: create a master object that includes an array
    of sockets. Each time you create a Thread, update the
    master object's list of sockets with a reference to
    each Thread's socket. Under the current memory model, the socket field should be declared volatile. The proposed new memory model will guarantee that this will work if the socket field is declared final.
    Sylvia.

Maybe you are looking for

  • How to submit a concurrent request from Discoverer report.

    I would like to know If any one has tried submitting a concurrent request from Discoverer Report?_ This is no stupid question, but our team here finally decided with a solution to our long pending issues with few of the discoverer report. To Proceed

  • Cost Center Security

    HI, We have a security requirement on one the G/L plan to actual BEX report for Cost center. the report has cost center hierarchy. but the 3 levels we need security are: 1) managers that can access all cost centers 2) managers that can access a range

  • Only purchased songs syncing in playlists, other info syncing wrong. Help!

    I've been using iTunes for a while, since getting my first video iPod in 2006, so I'm not a newbie.  I've switched computers more than once and I've gotten used to rebuilding my library, etc.  Recently got a new computer and moved all my music over (

  • Plea to Apple to sort iCal invitations - or has someone got a workaround?

    I know there are a million threads on this topic, so I've phrased this more as a plea to Apple to sort out rather than a question. But there is a question - has anyone got a workaround this? I use iCal and MacMail. I have 2 email accounts and 2 calen

  • 1 copy of AE on 2 computers on a network

    Where I work, we have three Macs on a network. We are buying two copies of After Effects (can't afford three). We want to put a copy on each one. I know that you if have a laptop and desktop you put one copy on both as long as you use don't use them