Search Results

Search found 6394 results on 256 pages for 'regular expressions'.

Page 7/256 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Use Expressions with LINQ to Entities

    - by EltonStoneman
    [Source: http://geekswithblogs.net/EltonStoneman] Recently I've been putting together a generic approach for paging the response from a WCF service. Paging changes the service signature, so it's not as simple as adding a behavior to an existing service in config, but the complexity of the paging is isolated in a generic base class. We're using the Entity Framework talking to SQL Server, so when we ask for a page using LINQ's .Take() method we get a nice efficient SQL query for just the rows we want, with minimal impact on SQL Server and network traffic. We use the maximum ID of the record returned as a high-water mark (rather than using .Skip() to go to the next record), so the approach caters for records being deleted between page requests. In the paged response we include a HasMorePages indicator, computed by comparing the max ID in the page of results to the max ID for the whole resultset - if the latter is bigger, then there are more pages. In some quick performance testing, the paged version of the service performed much more slowly than the unpaged version, which was unexpected. We narrowed it down to the code which gets the max ID for the full resultset - instead of building an efficient MAX() SQL query, EF was returning the whole resultset and then computing the max ID in the service layer. It's easy to reproduce - take this AdventureWorks query:             var context = new AdventureWorksEntities();             var query = from od in context.SalesOrderDetail                         where od.ModifiedDate >= modified                          && od.SalesOrderDetailID.CompareTo(id) > 0                         orderby od.SalesOrderDetailID                         select od;   We can find the maximum SalesOrderDetailID like this:             var maxIdEfficiently = query.Max(od => od.SalesOrderDetailID);   which produces our efficient MAX() SQL query. If we're doing this generically and we already have the ID function in a Func:             Func<SalesOrderDetail, int> idFunc = od => od.SalesOrderDetailID;             var maxIdInefficiently = query.Max(idFunc);   This fetches all the results from the query and then runs the Max() function in code. If you look at the difference in Reflector, the first call passes an Expression to the Max(), while the second call passes a Func. So it's an easy fix - wrap the Func in an Expression:             Expression<Func<SalesOrderDetail, int>> idExpression = od => od.SalesOrderDetailID;             var maxIdEfficientlyAgain = query.Max(idExpression);   - and we're back to running an efficient MAX() statement. Evidently the EF provider can dissect an Expression and build its equivalent in SQL, but it can't do that with Funcs.

    Read the article

  • Expressions that are idiomatic in one language but not used or impossible in another

    - by Tungsten
    I often find myself working in unfamiliar languages. I like to read code written by others and then jump in and write something myself before going back and learning the corners of each language. To speed up this process, it really helps to know a few of the idioms you'll encounter ahead of time. Some of these, I've found are fairly unique. In Python you might do something like this: '\n'.join(listOfThings) Not all languages allow you to call methods on string literals like this. In C, you can write a loop like this: int i = 50; while(i--) { /* do something 50 times */ } C lets you decrement in the loop condition expression. Most more modern languages disallow this. Do you have any other good examples? I'm interested in often used constructions not odd corner cases.

    Read the article

  • SQL Server: Writing CASE expressions properly when NULLs are involved

    - by Mladen Prajdic
    We’ve all written a CASE expression (yes, it’s an expression and not a statement) or two every now and then. But did you know there are actually 2 formats you can write the CASE expression in? This actually bit me when I was trying to add some new functionality to an old stored procedure. In some rare cases the stored procedure just didn’t work correctly. After a quick look it turned out to be a CASE expression problem when dealing with NULLS. In the first format we make simple “equals to” comparisons to a value: SELECT CASE <value> WHEN <equals this value> THEN <return this> WHEN <equals this value> THEN <return this> -- ... more WHEN's here ELSE <return this> END Second format is much more flexible since it allows for complex conditions. USE THIS ONE! SELECT CASE WHEN <value> <compared to> <value> THEN <return this> WHEN <value> <compared to> <value> THEN <return this> -- ... more WHEN's here ELSE <return this> END Now that we know both formats and you know which to use (the second one if that hasn’t been clear enough) here’s an example how the first format WILL make your evaluation logic WRONG. Run the following code for different values of @i. Just comment out any 2 out of 3 “SELECT @i =” statements. DECLARE @i INTSELECT  @i = -1 -- first resultSELECT  @i = 55 -- second resultSELECT  @i = NULL -- third resultSELECT @i AS OriginalValue, -- first CASE format. DON'T USE THIS! CASE @i WHEN -1 THEN '-1' WHEN NULL THEN 'We have a NULL!' ELSE 'We landed in ELSE' END AS DontUseThisCaseFormatValue, -- second CASE format. USE THIS! CASE WHEN @i = -1 THEN '-1' WHEN @i IS NULL THEN 'We have a NULL!' ELSE 'We landed in ELSE' END AS UseThisCaseFormatValue When the value of @i is –1 everything works as expected, since both formats go into the –1 WHEN branch. When the value of @i is 55 everything again works as expected, since both formats go into the ELSE branch. When the value of @i is NULL the problems become evident. The first format doesn’t go into the WHEN NULL branch because it makes an equality comparison between two NULLs. Because a NULL is an unknown value: NULL = NULL is false. That is why the first format goes into the ELSE Branch but the second format correctly handles the proper IS NULL comparison.   Please use the second more explicit format. Your future self will be very grateful to you when he doesn’t have to discover these kinds of bugs.

    Read the article

  • List of events triggered on pages matching regex

    - by Cubius
    Is there a way to get the grouped list of events (such as in Top events) which were triggered on pages matching a regular expression? I may add the Page secondary dimension in Top events and apply the regex filter but this way I won't get a grouped list. I may apply the filter to Events - Pages report but this way the events will be grouped only inside pages whilst I need global grouping. Any suggestions?

    Read the article

  • Finding the html tag value with Python [on hold]

    - by MrWho
    Consider a html page, which contains a line like below: file: 'http://google.com/video.mp4' I want to search for google.com/video.mp4 in that file and save it in a variable.I want to code it with python. Shortly, I want to elicit a link from a html page, so I need to get the link by using regular expressions or the other techniques in which I'm asking about. PS: What should I exactly try to clarify?it's really annoying that the administrators don't even say what is exactly unclear about the question, they've just learned to close or on hold the topics!

    Read the article

  • What are some examples of MemberBinding linq expressions?

    - by michielvoo
    There are three possibilities, but I can't find examples: System.Linq.Expressions.MemberAssignment System.Linq.Expressions.MemberListBinding System.Linq.Expressions.MemberMemberBinding I want to write some unit tests to see if I can handle them, but I don't know how to write them except for the first one, which seems to be new Foo { Property = "value" } where Property = "value" is an expression of type MemberAssignment. See also this MSDN article.

    Read the article

  • Freely-available, well-debugged regular expressions

    - by fsb
    I was reading ICU documentation and came across this fine advice: For common tasks like this there are libraries of freely available regular expressions that have been well debugged. It's worth making a quick search before writing a new expression. To which libraries of well-debugged regular expressions do you commonly refer? I'm not much taken with http://regexlib.com where the expressions don't seem all that well debugged. It appears to have no QA process besides user comments and ratings.

    Read the article

  • Double interpolation of regular expressions in Perl

    - by tomdee
    I have a Perl program that stores regular expressions in configuration files. They are in the form: regex = ^/d+$ Elsewhere, the regex gets parsed from the file and stored in a variable - $regex. I then use the variable when checking the regex, e.g. $lValid = ($valuetocheck =~ /$regex/); I want to be able to include perl variables in the config file, e.g. regex = ^\d+$stored_regex$ But I can't work out how to do it. When regular expressions are parsed by Perl they get interpreted twice. First the variables are expanded, and then the the regular expression itself is parsed. What I need is a three stage process: First interpolate $regex, then interpolate the variables it contains and then parse the resulting regular expression. Both the first two interpolations need to be "regular expression aware". e.g. they should know that the string contain $ as an anchor etc... Any ideas?

    Read the article

  • Building a regex builder

    - by i.h4d35
    I am a beginner in programming in general and web development in particular. I am especially bad at regular expressions. Recently I was involved in building a couple of cPanel plugins(Perl-CGI) and that's when I realized how bad I am in regex. As a result, I have decided to build an online regex builder - this will help me to learn regex and help other struggling with regex. I have checked out GSkinner, Rubular and a couple of others like regexpal. It seemed to be a little difficult to use, hence i thought of writing another one. I do not know which tool is best suited for the job. should I write it in Perl or Python? My skill level is between beginner and intermediate in both those languages. What would be a good starting point - building it for the CLI or for the browser? I plan to get a string as an input, ask if the user want to search or search and replace, enter the search string (and the replace string where applicable) and then generate a regex. Would this be the right way to go?

    Read the article

  • Perl: Negative look behind regex question [migrated]

    - by James
    The Perlre in Perldoc didn't go into much detail on negative look around but I tried testing it, and didn't work as expected. I want to see if I can differentiate a C preprocessor macro definition (e.g. #define MAX(X) ....) from actual usage (y = MAX(x);), but it didn't work as expected. my $macroName = 'MAX'; my $macroCall = "y = MAX(X);"; my $macroDef = "# define MAX(X)"; my $boundary = qr{\b$macroName\b}; my $bstr = " MAX(X)"; if($bstr =~ /$boundary/) { print "boundary: $bstr matches: $boundary\n"; } else { print "Error: no match: boundary: $bstr, $boundary\n"; } my $negLookBehind = qr{(?<!define)\b$macroName\b}; if($macroCall =~ /$negLookBehind/) # "y = MAX(X)" matches "(?<!define)\bMAX\b" { print "negative look behind: $macroCall matches: $negLookBehind\n"; } else { print "no match: negative look behind: $macroCall, $negLookBehind\n"; } if($macroDef =~ /$negLookBehind/) # "#define MAX(X)" should not match "(?<!define)\bMAX\b" { print "Error: negative look behind: $macroDef matches: $negLookBehind\n"; } else { print "no match: negative look behind: $macroDef, $negLookBehind\n"; } It seems that both $macroDef and $macroCall seem to match regex /(?<!define)\b$macroName\b/. I backed off from the original /(?<\#)\s*(?<!define)\b$macroName\b/ since that didn't work either. So what did I screw up? Also does Perl allow chaining of multiple look around expressions?

    Read the article

  • Lambda expressions in C#?

    - by user30457
    Hey I'm rather new to these could someone explain the significance or prehaps give a link to some useful information on lambda expressions? I encounter the following code in a test and I am wondering why someone would do this: foo.MyEvent += (o, e) = { fCount++; Console.WriteLine(fCount); }; foo.MyEvent -= (o, e) = { fCount++; Console.WriteLine(fCount); }; My instinct tells me it is something simple and not a mistake, but I don't know enough about these expressions to understand why this is being done. Regards,

    Read the article

  • Python regular expression implementation details

    - by Tom
    A question that I answered got me wondering: How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or is it subject to change? I thought that regular expressions would be implemented as DFAs, and therefore were very efficient (requiring at most one scan of the input string). Laurence Gonsalves raised an interesting point that not all Python regular expressions are regular. (His example is r"(a+)b\1", which matches some number of a's, a b, and then the same number of a's as before). This clearly cannot be implemented with a DFA. So, to reiterate: what are the implementation details and guarantees of Python regular expressions? It would also be nice if someone could give some sort of explanation (in light of the implementation) as to why the regular expressions "cat|catdog" and "catdog|cat" lead to different search results in the string "catdog", as mentioned in the question that I referenced before.

    Read the article

  • Helper method to Replace/Remove characters that do not match the Regular Expression

    - by Michael Freidgeim
    I have a few fields, that use regEx for validation. In case if provided field has unaccepted characters, I don't want to reject the whole field, as most of validators do, but just remove invalid characters. I am expecting to keep only Character Classes for allowed characters and created a helper method to strip unaccepted characters. The allowed pattern should be in Regex format, expect them wrapped in square brackets. function will insert a tilde after opening squere bracket , according to http://stackoverflow.com/questions/4460290/replace-chars-if-not-match.  [^ ] at the start of a character class negates it - it matches characters not in the class.I anticipate that it could work not for all RegEx describing valid characters sets,but it works for relatively simple sets, that we are using.         /// <summary>               /// Replaces  not expected characters.               /// </summary>               /// <param name="text"> The text.</param>               /// <param name="allowedPattern"> The allowed pattern in Regex format, expect them wrapped in brackets</param>               /// <param name="replacement"> The replacement.</param>               /// <returns></returns>               /// //        http://stackoverflow.com/questions/4460290/replace-chars-if-not-match.               //http://stackoverflow.com/questions/6154426/replace-remove-characters-that-do-not-match-the-regular-expression-net               //[^ ] at the start of a character class negates it - it matches characters not in the class.               //Replace/Remove characters that do not match the Regular Expression               static public string ReplaceNotExpectedCharacters( this string text, string allowedPattern,string replacement )              {                     allowedPattern = allowedPattern.StripBrackets( "[", "]" );                      //[^ ] at the start of a character class negates it - it matches characters not in the class.                      var result = Regex .Replace(text, @"[^" + allowedPattern + "]", replacement);                      return result;              }static public string RemoveNonAlphanumericCharacters( this string text)              {                      var result = text.ReplaceNotExpectedCharacters(NonAlphaNumericCharacters, "" );                      return result;              }        public const string NonAlphaNumericCharacters = "[a-zA-Z0-9]";There are a couple of functions from my StringHelper class  http://geekswithblogs.net/mnf/archive/2006/07/13/84942.aspx , that are used here.    //                           /// <summary>               /// 'StripBrackets checks that starts from sStart and ends with sEnd (case sensitive).               ///           'If yes, than removes sStart and sEnd.               ///           'Otherwise returns full string unchanges               ///           'See also MidBetween               /// </summary>               /// <param name="str"></param>               /// <param name="sStart"></param>               /// <param name="sEnd"></param>               /// <returns></returns>               public static string StripBrackets( this string str, string sStart, string sEnd)              {                      if (CheckBrackets(str, sStart, sEnd))                     {                           str = str.Substring(sStart.Length, (str.Length - sStart.Length) - sEnd.Length);                     }                      return str;              }               public static bool CheckBrackets( string str, string sStart, string sEnd)              {                      bool flag1 = (str != null ) && (str.StartsWith(sStart) && str.EndsWith(sEnd));                      return flag1;              }               public static string WrapBrackets( string str, string sStartBracket, string sEndBracket)              {                      StringBuilder builder1 = new StringBuilder(sStartBracket);                     builder1.Append(str);                     builder1.Append(sEndBracket);                      return builder1.ToString();              }v

    Read the article

  • Parse filename from full path using regular expressions in C#

    - by WindyCityEagle
    How do I pull out the filename from a full path using regular expressions in C#? Say I have the full path C:\CoolDirectory\CoolSubdirectory\CoolFile.txt. How do I get out CoolFile.txt using the .NET flavor of regular expressions? I'm not really good with regular expressions, and my RegEx buddy and me couldn't figure this one out. Also, in the course of trying to solve this problem, I realized that I can just use System.IO.Path.GetFileName, but the fact that I couldn't figure out the regular expression is just making me unhappy and it's going to bother me until I know what the answer is.

    Read the article

  • How to perform regular expression based replacements on files with MSBuild

    - by Daniel Cazzulino
    And without a custom DLL with a task, too . The example at the bottom of the MSDN page on MSBuild Inline Tasks already provides pretty much all you need for that with a TokenReplace task that receives a file path, a token and a replacement and uses string.Replace with that. Similar in spirit but way more useful in its implementation is the RegexTransform in NuGet’s Build.tasks. It’s much better not only because it supports full regular expressions, but also because it receives items, which makes it very amenable to batching (applying the transforms to multiple items). You can read about how to use it for updating assemblies with a version number, for example. I recently had a need to also supply RegexOptions to the task so I extended the metadata and a little bit of the inline task so that it can parse the optional flags. So when using the task, I can pass the flags as item metadata as follows:...Read full article

    Read the article

  • Equivalence of boolean expressions

    - by Iulian Serbanoiu
    Hello, I have a problem that consist in comparing boolean expressions ( OR is +, AND is * ). To be more precise here is an example: I have the following expression: "A+B+C" and I want to compare it with "B+A+C". Comparing it like string is not a solution - it will tell me that the expressions don't match which is of course false. Any ideas on how to compare those expressions? Any ideas about how can I tackle this problem? I accept any kind of suggestions but (as a note) the final code in my application will be written in C++ (C accepted of course). An normal expression could contain also parenthesis: (A * B * C) + D or A+B*(C+D)+X*Y Thanks in advance, Iulian

    Read the article

  • Delphi component or library to display mathematical expressions

    - by Svein Bringsli
    I'm looking for a simple component that displays mathematical expressions in Delphi. When I started out I thought it would be easy to find something on the net, but it turns out it was harder than anticipated. There are lots and lots of components that will parse mathematical expressions, but few (none?) that will display them. Ideally I would like a component as simple as a TLabel, where I could set the caption to some expression and it would be displayed correctly, but some sort of library that let's me draw expressions to a canvas would also be sufficient for my needs. Update: I'm not talking about plotting graphs of functions or something like that. I want to display (for instance) (X^2+3)/X like this:

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >