Variable scope local, pattern match compactly

Hi,
I read lines from a file and would like do something different with the line depending on whether it contains a single word or two words.
var rxA:RegExp = /^\s*(\S+)\s+(\S+)\s*$/;
var rxB:RegExp = /^\s*(\S+)\s*$/;
str is the line I read from a file
if( rxA.test(str) ){
    var match:Object = rxA.exec(str);
    do something with match[1] and match[2];
if( rxB.test(str) ){
    var match:Object = rxB.exec(str);
    do something with match[1];
With this code I get an error message, the object name "match" is used twice. Is it possible to make this variable local such that no other routine outside the "if" block can see this object?
Is it possible to do not only the test, but the exec also inside the if( ... ), like this (similar to Perl):
if( var match:Object = rxA.exec(str) ){
    do something with match[1] and match[2];
Thanks,
Illes

Hi,
Regading the first question, unfortunatelly "match" is function bound.
You can however define it only once outside the two ifs, as in:
var match:Object;
if( rxA.test(str) ){
    match = rxA.exec(str);
    do something with match[1] and match[2];
if( rxB.test(str) ){
    match = rxB.exec(str);
    do something with match[1];

Similar Messages

  • New language feature: lazy local pattern matching

    <p>In the upcoming release of the Open Quark Framework, CAL gets a new language       feature: lazy local pattern matching.</p> <p>The new local pattern match syntax allows one to bind one or more variables to       the fields of a data constructor or a record in a single declaration inside a       let block.</p> <p>      For example:</p> <p>      // data constructor patterns:<br />      public foo1 = let Prelude.Cons a b = ["foo"]; in a;<br />      public foo2 = let Prelude.Cons {head=a, tail=b} = ["foo"]; in a;<br />      <br />      // list cons patterns:<br />      public foo3 = let a:b = [3]; in a;<br />      <br />      // tuple patterns:<br />      public foo4 = let (a, b, c) = (b, c, 1 :: Prelude.Int); in abc;<br />      <br />      // record patterns:<br />      public foo5 = let = {a = "foo"}; in a; // non-polymorphic record pattern<br />      public foo6 = let {_ | a} = {a = "foo", b = "bar"}; in a; // polymorhpic record       pattern<br />      <br />      Whereas a case expression such as (case expr of a:b -> ...) forces the       evaluation of expr to weak-head normal form (WHNF), a similar pattern match       declaration (let a:b = expr; in ...) does not force the evaluation of expr       until one of a or b is evaluated. In this sense, we can regard this as a form       of lazy pattern matching.<br /> </p> <p>Thus,</p> <p>      let a:b = []; in 3.0;</p> <p>is okay and would not cause a pattern match failure, but the case expression</p> <p>      case [] of a:b -> 3.0;</p> <p>would cause a pattern match failure.</p> <p>This laziness is useful in situations where unpacking via a case expression may       result in an infinite loop. For example, the original definition of List.unzip3       looks like this:</p> <p>// Original implementation of List.unzip3<br />      unzip3 :: [(a, b, c)] -> ([a], <b>, [c]);<br />      public unzip3 !list =<br />          case list of<br />          [] -> ([], [], []);<br />          x : xs -><br />              let<br />                  ys =       unzip3 xs;<br />              in<br />                  case x       of<br />                  (x1,       x2, x3) -><br />                      //do       not do a "case" on the ys, since this makes unzip3 strictly evaluate the list!<br />                      (x1       : field1 ys, x2 : field2 ys, x3 : field3 ys);<br />              ;<br />          ;<br /> </p> <p>The use of the accessor functions field1, field2 and field3 here is necessary,       as the alternate implementation shown below would result in "unzip3 xs" to be       evaluated to WHNF during the evaluation of "unzip3 (x:xs)". Thus if the input       list is infinite, the function would never terminate. </p> <p>// Alternate (defective) implementation of List.unzip3<br />      unzip3 :: [(a, b, c)] -> ([a], <b>, [c]);<br />      public unzip3 !list =<br />          case list of<br />          [] -> ([], [], []);<br />          x : xs -><br />              let<br />                  ys =       unzip3 xs;<br />              in<br />                  case x       of<br />                  (x1,       x2, x3) -><br />                      case       ys of // the use of "case" here is inappropriate, as it causes "unzip3 xs" to       be evaluated to WHNF<br />                      (y1,       y2, y3) -> (x1 : y1, x2 : y2, x3 : y3);<br />                  ;<br />              ;<br />          ;<br /> </p> <p>With the new syntax, the original implementation can be expressed more nicely       without changing its semantics:</p> <p>// New implementation of List.unzip3, revised to use the local pattern match       syntax<br />      unzip3 :: [(a, b, c)] -> ([a], <b>, [c]);<br />      public unzip3 !list =<br />          case list of<br />          [] -> ([], [], []);<br />          x : xs -><br />              let<br />                  (y1,       y2, y3) = unzip3 xs; // using a tuple pattern to perform a lazy local pattern       match<br />              in<br />                  case x       of<br />                  (x1,       x2, x3) -><br />                      (x1       : y1, x2 : y2, x3 : y3);<br />              ;<br />          ;<br /> </p> <p style="text-decoration: underline">It is important to note that in places where       a case expression can be used (without having an unwanted change in the       laziness of the expression being unpacked), it should be used instead of this       local pattern match syntax.</p> <p>Things to note about the new syntax:</p> <p>      - local type declarations on the pattern-bound variables are allowed, and these       type declarations can have associated CALDoc comments. On the other hand, the       actual local pattern match declaration itself cannot have a type declaration       nor a CALDoc comment.</p> <p>      - this syntax cannot be used for top-level definitions, only local definitions       in let blocks</p> <p>      - one cannot use patterns with multiple data constructors, e.g.</p> <p>      let (Left|Right) = ...;</p> <p>      is not allowed</p> <p>      - one cannot specify a variable for the base record pattern, e.g.</p> <p>      let {r | a, b} = ...;</p> <p>      is not allowed, but this is okay:</p> <p>      let {_ | a, b} = ...;</p> <p>      - patterns without no variables are disallowed, e.g.</p> <p>      let _ = ...;<br />      let [] = ...;<br />      let () = ...;<br />      let : = ...;<br />      let {_|#1} = ...;      <br /> </p>

    If you use just / it misinterprets it and it ruins
    your " " tags for a string. I don't think so. '/' is not a special character for Java regex, nor for Java String.
    The reason i used
    literal is to try to force it to directly match,
    originally i thought that was the reason it wasn't
    working.That will be no problem because it enforces '.' to be treated as a dot, not as a regex 'any character'.
    Message was edited by:
    hiwa

  • OBIEE 11G : Remove label (is like pattern match) in the prompt

    Hi Experts,
    I have Gone through this thread Re: OBIEE 11G : Remove label (is like pattern match) in the prompt and applied JS as mentioed but
    It works for the first display of the page but its back as soon as you hit the apply button
    can be it be removed permanently? Thanks in Advance

    Hi Nagen,
    You can try the following:
    Create a variable prompt with the column vales that you want to match
    Create a filter in the analysis criteria tab on the column, set to pick up the variable, and define the IS LIKE here.
    It is effectively doing the same task as the standard prompt approach does, but in a round-a-bout way which doesn't include adding any of Oracle's text in.

  • 9@ Route Pattern Matched Issues

    Unfortunately I have to deal with a lot of 9@ route patterns in our deployment.  I understand weird things happen when 9@ is used, but even this one is boggling my mind.  So I was hoping someone could help me understand why it's doing what it's doing.
    I have a CSS with a collection of partitions.   I'll call the 3 I'm interested in the following: One-PT, Two-PT, Three-PT.
    One-PT has a route pattern of 9@ with the Local filter applied going to Gateway 1.
    Two-PT has a route pattern of 9@ with the Local filter applied going to Gateway 2.
    Three-PT has a route pattern of 9.XXXXXXXXXX with no filter applied (those are 10 Xs) going to Gateway 3.
    My phone is assigned to the CSS with these 3 partitions.  When I dial 9 981 xxx xxxx DNA says that 9@ from One-PT is always matched.  If I remove One-PT from the CSS, then 9@ in Two-PT is matched.  Only if I remove those 2 partitions does Three-PT get matched.
    Now, as I said above I understand 9@ can introduce weird routing issues, but I thought that the route pattern with 9 and 10 Xs would be more specific and it would be matched.  Obviously I was wrong, but I'm trying to understand why I was wrong. Is this because the 10 digit number dialed matches the NANP and the Local filter matches a NANP area code?  Thus it's the more exact match?
    Thanks!

    Hi,
    As per the following link
    http://www.cisco.com/c/en/us/td/docs/voice_ip_comm/cucm/admin/5_0_4/ccmsys/ccmsys/a03rp.html#wp1050657
    "Using the @ Wildcard Character in Route Patterns
    Using the @ wildcard character in a route pattern provides a single route pattern to match all NANP numbers, and requires additional consideration.
    The number 92578912 matches both of the following route patterns: 9.@ and 9.XXXXXXX. Even though both these route patterns seem to equally match the address, the 9.@ route pattern actually provides the closest match. The @ wildcard character encompasses many different route patterns, and one of those route patterns is [2-9][02-9]XXXXX. Because the number 2578912 more closely matches [2-9][02-9]XXXXX than it does XXXXXXX, the 9.@ route pattern provides the closest match for routing."
    Also, check the following post
    https://supportforums.cisco.com/discussion/10698966/9-route-pattern
    HTH
    Manish

  • How can I load pattern matching images into memory?

    I discovered this problem by accident when our network went down. I could not run my VI because the .png file used for pattern matching was on a network drive. My concern it the amount of time that is required to read a network file. Is there a way to load the file into memory when the VI is opened?

    Brian,
    Thank you for contacting National Instruments. For most pattern matching programs, the pattern file should only be read from file once and is then copy to a buffer on the local machine. If you examine your code, or an example program for pattern matching, you should see at least two IMAQ Create VI called somewhere near the front of your code. This VI basically creates a memory location and most likely will be called once for your pattern image and once for the image you are searching.
    Unless you are specifically calling a File Dialog VI where you are given a dialog box to open a file or have hard coded the file path so that it is read each iteration of your code, then your pattern file should only need to be called at the beginning of your application, th
    us causing only one file read over the network for that image. Therefore your program most likely already loads the image in memory once it is read and should not be accessing the network constantly.
    Again, I would recommend taking a look at your code to make sure you are not causing a file access every time and then you should be ready to go. Just in case you do have the network go down, I would recommend keeping a copy of the image locally and, if you are feeling ambitious, you can programmatically have your program read the file locally if the network file returns an error.
    Good luck with your application and let us know if we can be of any further assistance.
    Regards,
    Michael
    Applications Engineer
    National Instruments

  • SQL pattern matching

    Hi experts,
    I have a requirement for which I need to write a SQL. On our orders search screen there are 2 prompts.
    1) Dealer name (Table.column - DLR_NAM)
    2) State name (Table.column - STATE_NAM)
    When user wants to find the orders placed by all dealers whose name starts with 'A' and state name with 'B', then our query is something like this
    SELECT ORDER_ID, ORDER_ITEM, ORDER_QTY, ORDER_VALU
    FROM ORDERS
    WHERE DLR_NAM LIKE 'A%'
    AND STATE_NAM LIKE 'B%'; -- A and B entered by user in the respective prompt text box
    But there are countries like Greece for which states doesn't exists. In that case STATE_NAME is NULL and the above query becomes something like the below and doesn't return right results
    SELECT ORDER_ID, ORDER_ITEM, ORDER_QTY, ORDER_VALU
    FROM ORDERS
    WHERE DLR_NAM LIKE 'A%'
    AND STATE_NAM LIKE '%'; -- Pattern matching goes wrong due to this AND clause.
    Please suggest how to fix this. It appears simple and my brain is not working after non-stop working for several days.

    You are saying that the user types something in both variables.
    And then this query:
    SELECT ORDER_ID, ORDER_ITEM, ORDER_QTY, ORDER_VALU
    FROM ORDERS
    WHERE DLR_NAM LIKE :bind_dealer || '%'
    AND ( (:bind_state IS NULL) OR (:bind_state IS NOT NULL AND STATE_NAM LIKE :bind_state || '%') );returns rows with STATE_NAM null.
    That does not make sense. If the users types in both variables, then the bindvariable :bind_state is not null, and then STATE_NAM has to begin with the value of :bind_state.
    The only thing I can think of is if you are binding wrong? What is your application coded in? C#? Java? ASP? .NET? How do you prepare your SQL query from your user inputs?
    You will have to post a test case. Create table, insert some test data, run the sql and show it returns the wrong result. I cannot think of any problem without knowing more details :-)

  • Syslog pattern match

    Hi Guys,
    I'm looking for a way to setup a syslog pattern match on everything except a particular string.
    So for example, I want to monitor the rate at which new logs appears in the local buffer with the exception of messages with %PARSER contained in them.
    I have the basics working but I'm having trouble finding a regex expression that will do this.
    Thanks in advance,
    Neil

    To match everything but a specific pattern you would likely need to use a zero length negative lookahead regular expressin pattern.  These have been supported in Tcl regexp since 8.1 and Cisco IOS provides Tcl 8.3.4 if I remember correctly.  So something along the lines of '^(?!PARSER).*'.  I don't believe the % is presented to EEM (but a debug could help prove that, I simply forget if it is actually) and I assume then that the string you would be comparing this to would then start with PARSER.  If not you could remove the ^ anchor.

  • OLAP universe filter with pattern matching.

    Hi,
    I tried to create both a qaaws and a webi report which contained a filter with pattern matching on an olap universe .  When I ran this it took too long to be usable. I found note 1500666 which says that pattern matching is not supported in MDX and to use BEX query variables instead.
    I have created a bex query with a variable which has "Variable Represents" set to "Selection Option". I can run this query and using the search option I can do a pattern match search. I have built a universe based on this query but the filter that gets created automatically in the universe uses a "Between" operator.
    Does anyone know if it is possible to change the definition of the filter in the  universe so that it does a pattern match search and if so how?
    The end result is that I would like to be able to do a pattern match search on the text description of a BW employee object.
    Thanks
    Quentin.

    It would be better if you post the Filter definition here...
    And why don't you do Pattern matching at BO query panel level??
    Where you can find Matches pattern operator to do same stuff.
    Thank You!!

  • Pattern matching using Regular expression

    Hi,
    I am working on pattern matching using regular expression. I the table, I have 2 columns A and B
    A has value 'A499BPAU4A32A386KBCZ4C13C41D20E'
    B has value like '*CZ4*M11*7NQ+RDR+RSM-R9A-R9B'
    the requirement is that I have to match the columns of B in A. If there is a value with * sign, this must be present in A like 'CZ4' should exit in string A.
    The issue I am facing is that there are 2 values with * sign. The code works fine for first match (CZ4) but it does not look further as M11 does not exist in A.
    I used the condition
    AND instr(A,substr(REGEXP_SUBSTR(B, '*[^*]{3}'),2) ,1)=0
    First of all, is this possible to match multiple patterns in one condition?
    If yes, please suggest.
    Thanks

    user2544469 wrote:
    Thanks a lot Frank. This query worked wonderful for the test data I have provided however I have some concerns:
    - query doesnot include the column BOOK which is a mandatory check.Sorry, that was my mistake. It was a very easy mistake to make, since you posted sample data where it didn't matter. Instead of doing a cross-join between vn and got_must_have_cnt, do an inner join, using book. That means book will have to be in got_must_have_cnt, and all the sub-queries from which it descends. Look for comments that say "March 22".
    If you want to treat '+' in test_cat.codes as '*', then the simplest thing is probably just to use REPLACE, so that when the table has '+', you use '*' instead.
    WITH     got_token_cnt     AS
         SELECT     cat
         ,     book                                        -- Added March 22
         ,     REPLACE (codes, '+', '*') AS codes                    -- If desired.  Changed March 22
         ,     LENGTH (codes) - LENGTH ( TRANSLATE ( codes
                                                       , 'x*+-'
                                      , 'x'
                             ) AS token_cnt
         FROM    test_cat
    ,     cntr     AS
         SELECT     LEVEL     AS n
         FROM     (  SELECT  MAX (token_cnt)     AS max_token_cnt
                 FROM        got_token_cnt
         CONNECT BY     LEVEL     <= max_token_cnt
    ,     got_tokens     AS
         SELECT     t.cat
         ,     t.book                                        -- Added March 22
         ,     REGEXP_SUBSTR ( t.codes
                         , '[*+-]'
                         , 1
                         , c.n
                         )          AS token_type
         ,     SUBSTR ( REGEXP_SUBSTR ( t.codes
                                       , '[*+-][^*+-]*'
                               , 1
                               , c.n
                   , 2
                   )          AS token
         FROM     got_token_cnt     t
         JOIN     cntr          c  ON     c.n     <= t.token_cnt
    ,     got_must_have_cnt     AS
         SELECT       cat, book                                   -- Changed March 22
         ,       COUNT (CASE WHEN token_type = '*' THEN 1 END) AS must_have_cnt
         FROM       got_tokens
         GROUP BY  cat, book                                   -- Changed March 22
    SELECT       mh.cat
    ,       vn.vn_no
    FROM       got_must_have_cnt     mh
    JOIN                    vn  ON  mh.book     = vn.book               -- Changed March 22
    LEFT OUTER JOIN      got_tokens     gt  ON     mh.cat                  = gt.cat
                                     AND INSTR (vn.codes, gt.token) > 1
    GROUP BY  mh.cat
    ,            mh.must_have_cnt
    ,            vn.vn_no
    HAVING       COUNT (CASE WHEN gt.token_type = '*' THEN 1 END)     = mh.must_have_cnt
    AND       COUNT (CASE WHEN gt.token_type = '-' THEN 1 END)     = 0
    ORDER BY  mh.cat
    - query is very slow with 60000 records in vn table. Cost is somewhere around 36000.See these threads:
    When your query takes too long ...
    HOW TO: Post a SQL statement tuning request - template posting
    Relational databases were designed to have (at most) one piece of information in each column. If you decide to have multiple items in the same column (as you have a variable number of tokens in the codes column), don't be surprised if that makes things slower and more complicated. Most of the query I posted, and perhaps most of the time needed, is jsut to normalize the data. If you stored the data in a narmalized form, perhaps something like got_tokens, then you wouldn't need the first 3 sub-queries that I posted.
    Edited by: Frank Kulash on Mar 22, 2011 12:04 PM

  • Pattern matching in Strings

    Hi,
    I need some help using pattern matching in strings .. this is what i need to do ..
    if given a string of this format
    String tempNotes="07/07/05 3:42 PM - 65. Java forum test 07/01/05 5:11 PM - 62. Trying regualt Expressions";I need to extract the number(s) after the time .. in the above case would be 65,62 .
    The string might have more than one line of the above format .. can some one help me with this .
    I tried using regular expressions .. I am pretty new to Regex's tried this
    String regex="\\d(2)/\\d(2)/\\d(2)\\s\\d+:\\d(2)\\sP|AM\\s-";
    Pattern p= Pattern.compile(regex);
    Matcher m1 = p.matcher(tempNotes);
    if(m1.find()){
    System.out.println("Num = "+tempNotes.substring(m1.end()+1,m1.end()+3));
    } I am totally lost .. can someone help me with this please. I need to extract all the numbers after the time .
    Thanks in advance.

    I see two major problems with that regex. First, you're using parentheses where you should be using braces - "\\d{2}", not "\\d(2)". Second, you need to need to limit the scope of the alternation: "(?:P|A)M", or better, use a character class instead: "[PA]M". As it is, the vbar is splitting the whole regex into two alternatives. Also, you can use a capturing group to extract the number.
      String regex="\\d{2}/\\d{2}/\\d{2}\\s\\d+:\\d{2}\\s[AP]M\\s-\\s+(\\d+)";
      Pattern p= Pattern.compile(regex);
      Matcher m1 = p.matcher(tempNotes);
      while (m1.find()) {
        System.out.println("Num = " + m1.group(1));
      }

  • How to accelerate the processing time of pattern match

    How to accelerate the processing time  of pattern match
      If my camera acquire an image in 50ms, but when we analyze this image with pattern match, we need about 300ms. Except using queue to seprate acquisition
    and analysis to different loops, there is another way to directly accelerate the processing time  of pattern match ? Maybe compact rio with FPGA ?
    But I saw a paper in NI web, there is no this function in c-rio ?  
    Any suggersion will be very apperciated ~
    Ricky
    Attachments:
    aa.png ‏65 KB

    Hello,
    what matching algorithm are you using? You can reduce time using the Gaussian pyramids algorithm.You can fine tune the parameters using the advanced options.
    What is your template size/image resolution?
    I suppose using a computer with better performance would also work...
    Best regards,
    K
    https://decibel.ni.com/content/blogs/kl3m3n
    "Kudos: Users may give one another Kudos on the forums for posts that they found particularly helpful or insightful."

  • Retain Pattern Match Attribute for Next Pattern Match Calculation

    When a MATCH_RECOGNIZE PATTERN match occurs, is there any way to retain the underlying event for the next pattern match?
    It's like I want to replay the underlying event (that triggered the match) into the next "batch" of events.

    Here is an approach
    1) Use a (local) cache to hold the "lastMatchedTime"
    2) Augment each input event with the "lastMatchedTime" by first (left outer join) joining with cache
    3) Run the MATCH_RECOGNIZE on the augmented stream
    4) Use a match to update the cache
    Here are the queries that I tried -
      <view id="S">
            <![CDATA[
                 RSTREAM (
                    SELECT
                           id,
                           obs,
                           epoch,
                           nvl(C.lastMatchedTime, 0) as lastMatchedTime
                    FROM
                           InputChannel[now] AS I LEFT OUTER JOIN lastMatchCache AS C
                    ON
                           C.keyValue = "key"      
            ]]>
          </view>
          <view id="v1">
            <![CDATA[                 
                      SELECT
                              T.id,
                              T.obsTotal,
                              T.elapsedTime,
                              T.firstts,
                              T.lastts
                      FROM S MATCH_RECOGNIZE (
                              PARTITION BY id
                              MEASURES
                                        id as id,
                                        sum(obs) as obsTotal,
                                        B.epoch - decode(B.lastMatchedTime, 0L, min(epoch), B.lastMatchedTime) as elapsedTime,
                                        decode(B.lastMatchedTime, 0L, min(epoch), B.lastMatchedTime) as firstts,
                                        B.epoch as lastts
                              PATTERN ( A+? B )
                              DEFINE
                                       B AS (epoch- decode(lastMatchedTime, 0L, min(epoch), lastMatchedTime)) > 20*60*1000
                      ) as T
            ]]>
          </view>
          <query id="qcache">
             <![CDATA[
                 SELECT
                       "key" as keyValue,
                       lastts as lastMatchedTime
                 FROM
                       v1
             ]]> 
          </query>
           <query id="q1">
             <![CDATA[
                 SELECT
                 FROM
                        v1
             ]]> 
          </query>
        Also, include in the config file
    <channel>
           <name>CacheChannel</name>
           <selector>qcache</selector>
       </channel> 
       <channel>
           <name>OutputChannel</name>
           <selector>q1</selector>
       </channel>The EPN that I used was
      <wlevs:event-type-repository>       
            <wlevs:event-type type-name="CacheEvent">
                <wlevs:class>com.bea.wlevs.event.example.helloworld.CacheEvent</wlevs:class>
            </wlevs:event-type>
            <wlevs:event-type type-name="InputEvent">
               <wlevs:properties>
                  <wlevs:property name="id" type="int"/>
                  <wlevs:property name="obs" type="int"/>
                  <wlevs:property name="epoch" type="bigint"/>
               </wlevs:properties>
            </wlevs:event-type>
            <wlevs:event-type type-name="OutputEvent">
               <wlevs:properties>
                  <wlevs:property name="id" type="int"/>
                  <wlevs:property name="obsTotal" type="int"/>
                  <wlevs:property name="elapsedTime" type="bigint"/>
                  <wlevs:property name="firstts" type="bigint"/>
                  <wlevs:property name="lastts" type="bigint"/>
               </wlevs:properties>
            </wlevs:event-type>
        </wlevs:event-type-repository>
        <wlevs:adapter id="InputAdapter" provider="csvgen">
             <wlevs:instance-property name="port" value="9061" />
             <wlevs:instance-property name="eventTypeName" value="InputEvent" />
             <wlevs:instance-property name="eventPropertyNames" value="id,obs,epoch" />
        </wlevs:adapter>     
        <wlevs:channel id="InputChannel" event-type="InputEvent" >
            <wlevs:listener ref="helloworldProcessor"/>
            <wlevs:source ref="InputAdapter"/>
        </wlevs:channel>
        <wlevs:caching-system id="local-caching"/>
        <wlevs:cache id="lastMatchCache" name="lastMatchCache" key-properties="keyValue" value-type="CacheEvent">
           <wlevs:caching-system ref="local-caching"/>
        </wlevs:cache>
        <!-- The default processor for OCEP 11.0.0.0 is CQL -->
        <wlevs:processor id="helloworldProcessor">
           <wlevs:listener ref="CacheChannel"/>
           <wlevs:cache-source ref="lastMatchCache" />      
        </wlevs:processor>
        <wlevs:channel id="CacheChannel" event-type="CacheEvent">
           <wlevs:listener ref="lastMatchCache"/>
        </wlevs:channel>
        <wlevs:channel id="OutputChannel" event-type="OutputEvent" advertise="true">
            <wlevs:listener>
                <bean class="com.bea.wlevs.example.helloworld.HelloWorldBean"/>
            </wlevs:listener>
            <wlevs:source ref="helloworldProcessor"/>
        </wlevs:channel>And the output that I get seems to match your requirement -
    eventType=OutputEvent object=q1  v1.id=4143, v1.obsTotal=9, v1.elapsedTime=7228000, v1.firstts=1199311210000, v1.lastts=1199318438000
    eventType=OutputEvent object=q1  v1.id=4143, v1.obsTotal=17, v1.elapsedTime=30935000, v1.firstts=1199318438000, v1.lastts=1199349373000
    eventType=OutputEvent object=q1  v1.id=4143, v1.obsTotal=7, v1.elapsedTime=41436000, v1.firstts=1199349373000, v1.lastts=1199390809000
    eventType=OutputEvent object=q1  v1.id=4143, v1.obsTotal=13, v1.elapsedTime=5904000, v1.firstts=1199390809000, v1.lastts=1199396713000Edited by: Anand Srinivasan on Sep 30, 2010 12:49 AM
    Edited by: Anand Srinivasan on Sep 30, 2010 12:50 AM

  • Javascript discussion: Variable scopes and functions

    Hi,
    I'm wondering how people proceed regarding variable scope, and calling
    functions and things. For instance, it's finally sunk in that almost
    always a variable should be declared with var to keep it local.
    But along similar lines, how should one deal with functions? That is,
    should every function be completely self contained -- i.e. must any
    variables outside the scope of the function be passed to the function,
    and the function may not alter any variables but those that are local to
    it? Or is that not necessary to be so strict?
    Functions also seem to be limited in that they can only return a single
    variable. But what if I want to create a function that alters a bunch of
    variables?
    So I guess that's two questions:
    (1) Should all functions be self-contained?
    (2) What if the function needs to return a whole bunch of variables?
    Thanks,
    Ariel

    Ariel:
    (Incidentally, I couldn't find any way of  marking answers correct when I visited the web forums a few days ago, so I gave up.)
    It's there...as long as you're logged in at least, and are the poster of the thread.
    What I want is to write code that I can easily come back to a few months later
    and make changes/add features -- so it's only me that sees the code, but
    after long intervals it can almost be as though someone else has written
    it! So I was wondering if I would be doing myself a favour by being more
    strict about make functions independent etc. Also, I was noticing that
    in the sample scripts that accompany InDesign (written by Olav Kvern?)
    the functions seem always to require all variables to be passed to it.
    Where it is not impractical to do so, you should make functions independent and reusable. But there are plenty of cases where it is impractical, or at least very annoying to do so.
    The sample scripts for InDesign are written to be in parallel between three different languages, and have a certain lowest-common-denominator effect. They also make use of some practices I would consider Not Very Good. I would not recommend them as an example for how to learn to write a large Javascript project.
    I'm not 100% sure what you mean by persistent session. Most of my
    scripts are run once and then quit. However, some do create a modeless
    dialog (ie where you can interface with the UI while running it), which
    is the only time I need to use #targetengine.
    Any script that specifies a #targetengine other than "main" is in a persistent session. It means that variables (and functions) will persist from script invokation to invokation. If you have two scripts that run in #targetengine session, for instance, because of their user interfaces, they can have conficting global variables. (Some people will suggest you should give each script its own #targetengine. I am not convinced this is a good idea, but my reasons against it are mostly speculation about performance and memory issues, which are things I will later tell you to not worry about.)
    But I think you've answered one of my questions when you say that the
    thing to avoid is the "v1" scope. Although I don't really see what the
    problem is in the context of InDesign scripting (unless someone else is
    going to using your script as function in one of theirs). Probably in
    Web design it's more of an issue, because a web page could be running
    several scripts at the same time?
    It's more of an issue in web browsers, certainly (which I have ~no experience writing complex Javascript for, by the way), but it matters in ID, too. See above. It also complicates code reuse across projects.
    Regarding functions altering variables: for example, I have a catalog
    script. myMasterPage is a variable that keeps track of which masterpage
    is being used. A function addPage() will add a page, but will need to
    update myMasterPage because many other functions in the script refer to
    that. However, addPage() also needs to update the total page count
    variable, the database-line-number-index-variable and several others,
    which are all used in most other functions. It seems laborious and
    unnecessary to pass them all to each function, then have the function
    alter them and return an array that would then need to be deciphered and
    applied back to the main variables. So in such a case I let the function
    alter these "global" (though not v1) variables. You're saying that's okay.
    Yes, that is OK. It's not a good idea to call that scope "global," though, since you'll promote confusion. You could call it...outer function scope, maybe? Not sure; that assumes addPage() is nested within some other function whose scope is containing myMasterPage.
    It is definitely true that you should not individually pass them to the function and return them as an array and reassign them to the outer function's variables.
    I think it is OK for addPage() to change them, yes.
    Another approach would be something like:
    (function() {
      var MPstate = {
        totalPages: 0,
        dbline: -1
      function addPage(state) {
        state.totalPages++;
        state.dbline=0;
        return state;
      MPstate = addPage(MPstate);
    I don't think this is a particularly good approach, though. It is clunky and also doesn't permit an easy way for addPage() to return success or failure.
    Of course it could instead do something like:
        return { success: true, state: state };
      var returnVal = addPage(MPstate);
      if (returnVal.success) { MPstate = returnVal.state; }
    but that's not very comforting either. Letting addPage() access it's parent functions variables works much much better, as you surmised.
    However, the down-side is that intuitively I feel this makes the script
    more "messy" -- less legible and professional. (On the other hand, I
    recall reading that passing a lot of variables to functions comes with a
    performance penalty.)
    I think that as long as you sufficiently clearly comment your code it is fine.
    Remember this sort of thing is part-and-parcel for a language that has classes and method functions inside those classes (e.g. Java, Python, ActionScript3, C++, etc.). It's totally reasonable for a class to define a bunch of variables that are scoped to that class and then implement a bunch of methods to modify those class variables. You should not sweat it.
    Passing lots of variables to functions does not incur any meaningful performance penalty at the level you should be worrying about. Premature optimization is almost always a bad idea. On the other hand, you should avoid doing so for a different reason -- it is hard to read and confusing to remember when the number of arguments to something is more than three or so. For instance, compare:
    addPage("iv", 3, "The rain in spain", 4, loremIpsumText);
    addPage({ name: "iv", insertAfter: 3, headingText: "The rain in spain",
      numberColumns: 4, bodyText: loremIpsumText});
    The latter is more verbose, but immensely more readable. And the order of parameters no longer matters.
    You should, in general, use Objects in this way when the number of parameters exceeds about three.
    I knew a function could return an array. I'll have to read up on it
    returing an object. (I mean, I guess I intuitively knew that too -- I'm
    sure I've had functions return textFrames or what-have-you),
    Remember that in Javascript, when we say Object we mean something like an associative array or dictionary in other languages. An arbitrary set of name/value pairs. This is confusing because it also means other kinds of objects, like DOM objects (textFrames, etc.), which are technically Javascript Objects too, because everything inherits from Object.prototype. But...that's not what I mean.
    So yes, read up on Objects. They are incredibly handy.

  • Getting Log File Pattern Matched Line Count metric to work ?

    Hi
    has anyone been able to get this to work with more complex Perl expressions ?
    Basically I can get simple, single expressions to match.
    EG *(does not exist)* will match the text *"does not exist"* anywhere in a file.
    However, if I want to match either does not exist OR file not found I should be able to do something like
    *(does not exist)|(file not found)* OR *(does not exist|file not found)* but this just doesn't work.
    I want to be able to do more complex expressions, using *\i* (ignore case), and *^* (start of line) *$* (end of line) expressions too.
    I can test the matching functionality using a simple perl program, and I know the expression works in Perl.
    Oracle is supposed to be using a perl pattern match but seems to fail unless it is a single simple expression.
    Anyone been able to use this functionality at all.
    Many thanks.

    I have a chance to look into the parse-log1.pl script which is responsible for monitoring the log files and generating the alerts for EMGC. I am just pasting the comments given in this file
    # This script is used in EMD to parse log files for critical and
    # warning patterns. The script holds the last line number searched
    # for each file in a state file for each time the script is run. The
    # next run of the script starts from the next line. The state file name
    # is read from the environment variable $EM_STATE_FILE, which must
    # be set for the script to run.
    but in my case this is not happending according to log files it is storing the lst read line of the log file but it is not using that info in its next run. The file will be scanned from the begining again but this is not the case with emagent.log file monitoring its working fine as expected and explained in the script file.
    According to my observation this is becasue of the script is rotating my log file for each run i dont know how stop it. I just want to scan my log file I dont want to rotate my log file for each run of the script. Could any one please help me to solve this problem
    Thanks
    Ashok Chava.

  • Java Pattern Matcher (Pattern.class bug? Stuck in Infinite Loop)

    Hi,
    I'm using the java pattern matcher and it appears to be stuck in an infinite loop and will not return from Pattern.class.
    It stays stuck in the following two code sequences...
    I'm using the following regex...
    java.util.regex.Matcher[pattern=[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|biz|info) region=0,353648 lastmatch=
    MAIN BLOCK STUCK IN LOOP:
    boolean study(TreeInfo info) {
    if (type != INDEPENDENT) {
    int minL = info.minLength;
    atom.study(info);
    info.minLength = minL;
    info.deterministic = false;
    return next.study(info);
    } else {
    atom.study(info);
    return next.study(info);
    SECOND BLOCK STUCK IN LOOP:
    boolean match(Matcher matcher, int i, CharSequence seq) {
    // Check for zero length group
    if (i > matcher.locals[beginIndex]) {
    int count = matcher.locals[countIndex];
    if (count < cmin) {
    matcher.locals[countIndex] = count + 1;
    boolean result = body.match(matcher, i, seq);
    // If match failed we must backtrack, so
    // the loop count should NOT be incremented
    if (!result)
    matcher.locals[countIndex] = count;
    return result;
    if (next.match(matcher, i, seq))
    return true;
    if (count < cmax) {
    matcher.locals[countIndex] = count + 1;
    boolean result = body.match(matcher, i, seq);
    // If match failed we must backtrack, so
    // the loop count should NOT be incremented
    if (!result)
    matcher.locals[countIndex] = count;
    return result;
    return false;
    return next.match(matcher, i, seq);
    Is this a bug with the Java 1.6 Pattern Matcher?
    Thanks
    V$h3r

    The Java Pattern Matcher is getting stuck in the following code...
    boolean study(TreeInfo info) {
    if (type != INDEPENDENT) {
    int minL = info.minLength;
    atom.study(info);
    info.minLength = minL;
    info.deterministic = false;
    return next.study(info);
    } else {
    atom.study(info);
    return next.study(info);
    boolean match(Matcher matcher, int i, CharSequence seq) {
    // Check for zero length group
    if (i > matcher.locals[beginIndex]) {
    int count = matcher.locals[countIndex];
    if (count < cmin) {
    matcher.locals[countIndex] = count 1;
    boolean result = body.match(matcher, i, seq);
    // If match failed we must backtrack, so
    // the loop count should NOT be incremented
    if (!result)
    matcher.locals[countIndex] = count;
    return result;
    if (next.match(matcher, i, seq))
    return true;
    if (count < cmax) {
    matcher.locals[countIndex] = count + 1;
    boolean result = body.match(matcher, i, seq);
    // If match failed we must backtrack, so
    // the loop count should NOT be incremented
    if (!result)
    matcher.locals[countIndex] = count;
    return result;
    return false;
    return next.match(matcher, i, seq);
    }Here is a copy of the REGEX that I'm using...
    It works on most of the other STRINGS but when I do a REGEX on the the html source for http://www.exponent.com it will get stuck...
    Pattern p = Pattern.compile("[a-zA-Z0-9+_~-]+(?:\\.[a-zA-Z0-9+_~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+(?:com|org|net|biz|info|[a-zA-Z]{2})");Thanks,
    V$h3r

Maybe you are looking for