Search Results

Search found 2455 results on 99 pages for 'lambda expressions'.

Page 38/99 | < Previous Page | 34 35 36 37 38 39 40 41 42 43 44 45  | Next Page >

  • Expression.OrElse, dynamically creating a condition.

    - by Jim
    Hi, I am attempting to create a dynamic where clause using the standard expression API. var query = ( from p in Parties orderby p.PartyId orderby p.FullName select p ).AsQueryable(); Expression<Func<Party, bool>> @fn = (p) => SqlMethods.Like(p.FullName, "%smith%") || SqlMethods.Like(p.Person.FirstName, "%smith%"); Expression<Func<Party, bool>> @sn = (p) => SqlMethods.Like(p.Person.FirstName, words[0]); ParameterExpression pe = Expression.Parameter(typeof(Party), "p"); Expression orelse = Expression.OrElse( Expression.Lambda(@fn, pe), Expression.Lambda(@sn, pe) ); The expressions above will ultimately be added to a where clause. I need to add a bunch of 'likes'. How do I do this? I get InvalidOperationException on the operator OrElse I have also tried Expression.Or Thanks Regards Craig.

    Read the article

  • Why does Scala apply thunks automatically, sometimes?

    - by Anonymouse
    At just after 2:40 in ShadowofCatron's Scala Tutorial 3 video, it's pointed out that the parentheses following the name of a thunk are optional. "Buh?" said my functional programming brain, since the value of a function and the value it evaluates to when applied are completely different things. So I wrote the following to try this out. My thought process is described in the comments. object Main { var counter: Int = 10 def f(): Int = { counter = counter + 1; counter } def runThunk(t: () => Int): Int = { t() } def main(args: Array[String]): Unit = { val a = f() // I expect this to mean "apply f to no args" println(a) // and apparently it does val b = f // I expect this to mean "the value f", a function value println(b) // but it's the value it evaluates to when applied to no args println(b) // and the evaluation happens immediately, not in the call runThunk(b) // This is an error: it's not println doing something funny runThunk(f) // Not an error: seems to be val doing something funny } }   To be clear about the problem, this Scheme program (and the console dump which follows) shows what I expected the Scala program to do. (define counter (list 10)) (define f (lambda () (set-car! counter (+ (car counter) 1)) (car counter))) (define runThunk (lambda (t) (t))) (define main (lambda args (let ((a (f)) (b f)) (display a) (newline) (display b) (newline) (display b) (newline) (runThunk b) (runThunk f)))) > (main) 11 #<procedure:f> #<procedure:f> 13   After coming to this site to ask about this, I came across this answer which told me how to fix the above Scala program: val b = f _ // Hey Scala, I mean f, not f() But the underscore 'hint' is only needed sometimes. When I call runThunk(f), no hint is required. But when I 'alias' f to b with a val then apply it, it doesn't work: the evaluation happens in the val; and even lazy val works this way, so it's not the point of evaluation causing this behaviour.   That all leaves me with the question: Why does Scala sometimes automatically apply thunks when evaluating them? Is it, as I suspect, type inference? And if so, shouldn't a type system stay out of the language's semantics? Is this a good idea? Do Scala programmers apply thunks rather than refer to their values so much more often that making the parens optional is better overall? Examples written using Scala 2.8.0RC3, DrScheme 4.0.1 in R5RS.

    Read the article

  • E4X in ActionScript

    - by Brian Genisio
    Hey all, Looking at the E4X implementation in ActionScript, it occurs to me that they had to figure out how to do three things that I am not sure can be done within ActionScript regularly: Properties/Getters prefixed with @: var myAttribute = xmlPerson.@name; Nameless functions for filtering: xmlData.person.(/* predicate */) lambda syntax for predicates: xmlData.person.(@name == "Brian") So here is my question: Are these just one-off capabilities (much like Vector.<>) they put in just for E4X, therefore keeping out of reach for us? Or do we, as ActionScript developers, have access to these features? More specifically, I'd love to get access to the expression tree of that lambda predicate for my own code (not tied to the XML classes in any way). I figured out that this is called the "filter operator"... but I am not sure how to harness it. Not sure I can... since ActionScript does not allow for operator overloading :(

    Read the article

  • Aquamacs and IDLWAVE

    - by nicolavianello
    I've just installed the new Aquamacs 2.0 in my Mac Os X 10.6.3 and I'm an happy user of IDLWAVE on Aquamacs for programming in IDL. Unfortunately I run into a problem which I can't understand. I used in my configuration file to put the following (setq idlwave-surround-by-blank t) for the beautiful space around operator. This used to work till Aquamacs 2.0 preview b3 (third beta release) from that on, it stops to work and every time I type an operator (the same for '=' '<' '' etc) I got the following message Debugger entered--Lisp error: (void-variable idlwave-expand-equal) (lambda nil (interactive) (self-insert-command 1) idlwave-expand- equal -1 -1)() call-interactively((lambda nil (interactive) (self-insert-command 1) idlwave-expand-equal -1 -1) nil nil) Any help is welcommed

    Read the article

  • Is it possible to change the pane locations in Chrome Developer Tools?

    - by T.J. Crowder
    When debugging browser-based apps using Google Chrome's Developer Tools, is there a way to change the locations of the various panes? E.g., the Watch Expressions, the Call Stack, the code pane, etc.? The defaults are okay (console at bottom, code pane upper left, a column of Watch Expressions, Call Stack, Scope Vars, etc. in the upper right), but I'd rather swap things around a bit of it's possible. There doesn't seem to be anything to grab (other than for sizing) and I haven't found a way in my searching so far, but there are (still) some things about Chrome's options that aren't ... well-advertised in the UI, shall we say :-), especially around developer tools.

    Read the article

  • Replacing multiple patterns in a block of data

    - by VikrantY
    Hi All, I need to find the most efficient way of matching multiple regular expressions on a single block of text. To give an example of what I need, consider a block of text: "Hello World what a beautiful day" I want to replace Hello with "Bye" and "World" with Universe. I can always do this in a loop ofcourse, using something like String.replace functions availiable in various languages. However, I could have a huge block of text with multiple string patterns, that I need to match and replace. I was wondering if I can use Regular Expressions to do this efficiently or do I have to use a Parser like LALR. I need to do this in JavaScript, so if anyone knows tools that can get it done, it would be appreciated.

    Read the article

  • Calling a method with getattr in Python

    - by brain_damage
    How to call a method using getattr? I want to create a metaclass, which can call non-existing methods of some other class that start with the word 'oposite_'. The method should have the same number of arguments, but to return the opposite result. def oposite(func): return lambda s, *args, **kw: not oposite(s, *args, **kw) class Negate(type): def __getattr__(self, name): if name.startswith('oposite_'): return oposite(self.__getattr__(name[8:])) def __init__(self,*args,**kwargs): self.__getattr__ = Negate.__getattr__ class P(metaclass=Negate): def yep(self): return True But the problem is that self.__getattr__(sth) returns a NoneType object. >>> p = P() >>> p.oposite_yep() Traceback (most recent call last): File "<pyshell#115>", line 1, in <module> p.oposite_yep() TypeError: <lambda>() takes at least 1 positional argument (0 given) How to deal with this?

    Read the article

  • Function Composition in C++

    - by Channel72
    There are a lot of impressive Boost libraries such as Boost.Lambda or Boost.Phoenix which go a long way towards making C++ into a truly functional language. But is there a straightforward way to create a composite function from any 2 or more arbitrary functions or functors? If I have: int f(int x) and int g(int x), I want to do something like f . g which would statically generate a new function object equivalent to f(g(x)). This seems to be possible through various techniques, such as those discussed here. Certainly, you can chain calls to boost::lambda::bind to create a composite functor. But is there anything in Boost which easily allows you to take any 2 or more functions or function objects and combine them to create a single composite functor, similar to how you would do it in a language like Haskell?

    Read the article

  • Multiline Find & Replace in Visual Studio

    - by hawbsl
    Can it be done? We're using either VS2005 or VS2008. I don't mean regular expressions - which have their place - but plain old text find & replace. I know we can do it (at a pinch) with regular expressions using the \n tag but prefer not to get tangled up in regex escapes characters, plus there's a readability issue. If it can't be done what plain and simple (free) alternative are people using? That doesn't involve knocking up our own macro.

    Read the article

  • Dynamic Operator Overloading on dict classes in Python

    - by Ishpeck
    I have a class that dynamically overloads basic arithmetic operators like so... import operator class IshyNum: def __init__(self, n): self.num=n self.buildArith() def arithmetic(self, other, o): return o(self.num, other) def buildArith(self): map(lambda o: setattr(self, "__%s__"%o,lambda f: self.arithmetic(f, getattr(operator, o))), ["add", "sub", "mul", "div"]) if __name__=="__main__": number=IshyNum(5) print number+5 print number/2 print number*3 print number-3 But if I change the class to inherit from the dictionary (class IshyNum(dict):) it doesn't work. I need to explicitly def __add__(self, other) or whatever in order for this to work. Why?

    Read the article

  • Extract multiple values from one column in MySql

    - by Neil
    I've noticed that MySql has an extensive search capacity, allowing both wildcards and regular expressions. However, I'm in somewhat in a bind since I'm trying to extract multiple values from a single string in my select query. For example, if I had the text "<span>Test</span> this <span>query</span>", perhaps using regular expressions I could find and extract values "Test" or "query", but in my case, I have potentially n such strings to extract. And since I can't define n columns in my select statement, that means I'm stuck. Is there anyway I could have a list of values (ideally separated by commas) of any text contained with span tags? In other words, if I ran this query, I would get "Test,query" as the value of spanlist: select <insert logic here> as spanlist from HtmlPages ...

    Read the article

  • jQuery and regex for adding icons to specific links?!

    - by rayne
    I'm using jQuery to add icons to specific links, e.g. a myspace icon for sites starting with http://myspace.com etc. However, I can't figure out how to use regular expressions (if that's even possible here), to make jQuery recognize the link either with or without "www." (I'm very bad at regular expressions in general). Here are two examples: $("a[href^='http://www.last.fm']").addClass("lastfm").attr("target", "_blank"); $("a[href^='http://livejournal.com']").addClass("livejournal").attr("target", "_blank"); They work fine, but I now I want the last.fm link to work with http://last.fm, http://www.last.fm and http://www.lastfm.de. Currently it only works for www.last.fm. I also would like to make the livejournal link work with subdomains links like http://username.livejournal.com How can I do that? Thanks in advance!

    Read the article

  • Flymake quits right ahead after loading with js2-mode

    - by artistoex
    When opening .js files, js2-mode and, subsequently, flymake-js is automatically loaded. But flymake unloads right ahead with the message Toggling flymake-mode off; better pass an explicit argument. However, when enabling it manually, using M-x flymake-mode, it keeps activated. Has anybody encountered similar behavior and has fixed it? My setup: I followed the instructions on emacswiki to set up Flymake to work with the most recent js2-mode with a little modification: (add-hook 'js2-mode-hook '(lambda () (flymake-js-load))) instead of (add-hook 'javascript-mode-hook '(lambda () (flymake-js-load)))

    Read the article

  • Closure and nested lambdas in C++0x

    - by DanDan
    Using C++0x, how do I capture a variable when I have a lambda within a lambda? For example: std::vector<int> c1; int v = 10; <--- I want to capture this variable std::for_each( c1.begin(), c1.end(), [v](int num) <--- This is fine... { std::vector<int> c2; std::for_each( c2.begin(), c2.end(), [v](int num) <--- error on this line, how do I recapture v? { // Do something }); });

    Read the article

  • Converting ObjC Blocks to C# Lambas

    - by Sam
    I need some help converting an Objective-C block to C#. Here is the source ObjC: NSDate* addYear = [_calendar dateByAddingComponents:((^{ NSDateComponents* components = [NSDateComponents new]; components.month = 12; return components; })()) toDate:now options:0]; Now I tried the following in C#: NSDate date = _calendar.DateByAddingComponents((() => { NSDateComponents components = new NSDateComponents(); components.Month = 12; return components; })(), now, NSCalendarOptions.None); To which I get the following compiler error: Expression denotes a 'anonymous method' where a 'method group' was expected. Removing the parentheses around the lambda yields Cannot convert 'lambda expression' to non-delegate type 'MonoTouch.Foundation.NSDateComponents'. What is the correct C# syntax? I need to retain the closures as there are a lot more in the code base that I am porting.

    Read the article

  • Instance_eval: why the class of subclass is superclass

    - by Raj
    def singleton_class class << self self end end class Human proc = lambda { puts 'proc says my class is ' + self.name.to_s } singleton_class.instance_eval do define_method(:lab) do proc.call end end end class Developer < Human end Human.lab # class is Human Developer.lab # class is Human ; oops Following solution works. def singleton_class class << self self end end class Human proc = lambda { puts 'proc says my class is ' + self.name.to_s } singleton_class.instance_eval do define_method(:lab) do self.instance_eval &proc end end end class Developer < Human end Human.lab # class is Human Developer.lab # class is Human ; oops Why Developer.lab is reporting that it is Human ? And what can be done so that proc reports Developer when Developer.lab is invoked.

    Read the article

  • PHP Regex Question

    - by oyerli
    Hi, I am developing an application using PHP but I am new to regular expressions, I could not find a solution to my problem. I want to replace all occurences of #word with a link, i have written a preg_match for this: $text=preg_replace('~#([\p{L}|\p{N}]+)~u', '<a href="/?aranan=$1">#$1</a>', $text); The problem is, this regular expression also matches the html character codes like &#039; and gives corrupt output. I need to exclude the words starting with &# but i do not know how to do that using regular expressions. Thanks for your help.

    Read the article

  • Detect if PCRE was built without the --enable-unicode-properties or --enable-utf8 configuration switches

    - by Mark Baker
    I've a PHP library that uses a number of regular expressions featuring the \P expressions for multibyte strings, e.g. ((((?:\P{M}\p{M}*)+?)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d+) While this works on most builds, I've had a few reports of the regexp returning an error. Depending on Operating platform, the error messages from PCRE are: Compilation failed: PCRE does not support \L, \l, \N, \P, \p, \U, \u, or \X at offset n or Compilation failed: support for \\P, \\p, and \\X has not been compiled at offset n I know that I can probably test a regexp at the beginning of my code that uses \P, and trap for a returned error, then use that response to set a compatibility flag and provide a degraded (non UTF-8) regexp without the \P within the main body of my code based on that compatibility flag; but I was wondering if there was any simpler way to identify whether PCRE had been built without the --enable-unicode-properties or --enable-utf8 configuration switches. PHP provides access to PCRE_VERSION constant, but that won't help identify whether \P support is enabled or not.

    Read the article

  • Using Selenium-IDE with a rich Javascript application?

    - by Darien
    Problem At my workplace, we're trying to find the best way to create automated-tests for an almost wholly javascript-driven intranet application. Right now we're stuck trying to find a good tradeoff between: Application code in reusable and nest-able GUI components. Tests which are easily created by the testing team Tests which can be recorded once and then automated Tests which do not break after small cosmetic changes to the site XPath expressions (or other possible expressions, like jQuery selectors) naively generated from Selenium-IDE are often non-repeatable and very fragile. Conversely, having the JS code generate special unique ID values for every important DOM-element on the page... well, that is its own headache, complicated by re-usable GUI components and IDs needing to be consistent when the test is re-run. What successes have other people had with this kind of thing? How do you do automated application-level testing of a rich JS interface? Limitations We are using JavascriptMVC 2.0, hopefully 3.0 soon so that we can upgrade to jQuery 1.4.x. The test-making folks are mostly trained to use Selenium IDE to directly record things. The test leads would prefer a page-unique HTML ID on each clickable element on the page... Training the testers to write or alter special expressions (such as telling them which HTML class-names are important branching points) is a no-go. We try to make re-usable javascript components, but this means very few GUI components can treat themselves (or what they contain) as unique. Some of our components already use HTML ID values in their operation. I'd like to avoid doing this anyway, but it complicates the idea of ID-based testing. It may be possible to add custom facilities (like a locator-builder or new locator method) to the Selenium-IDE installation testers use. Almost everything that goes on occurs within a single "page load" from a conventional browser perspective, even when items are saved Current thoughts I'm considering a system where a custom locator-builder (javascript code) for Selenium-IDE will talk with our application code as the tester is recording. In this way, our application becomes partially responsible for generating a mostly-flexible expression (XPath or jQuery) for any given DOM element. While this can avoid requiring more training for testers, I worry it may be over-thinking things.

    Read the article

  • Dynamic where clause in LINQ - with column names available at runtime

    - by sandesh247
    Disclaimer: I've solved the problem using Expressions from System.Linq.Expressions, but I'm still looking for a better/easier way. Consider the following situation : var query = from c in db.Customers where (c.ContactFirstName.Contains("BlackListed") || c.ContactLastName.Contains("BlackListed") || c.Address.Contains("BlackListed")) select c; The columns/attributes that need to be checked against the blacklisted term are only available to me at runtime. How do I generate this dynamic where clause? An additional complication is that the Queryable collection (db.Customers above) is typed to a Queryable of the base class of 'Customer' (say 'Person'), and therefore writing c.Address as above is not an option.

    Read the article

  • python multiprocessing.Process.Manager not producing consistent results?

    - by COpython
    I've written the following code to illustrate the problem I'm seeing. I'm trying to use a Process.Manager.list() to keep track of a list and increment random indices of that list. Each time there are 100 processes spawned, and each process increments a random index of the list by 1. Therefore, one would expect the SUM of the resulting list to be the same each time, correct? I get something between 203 and 205. from multiprocessing import Process, Manager import random class MyProc(Process): def __init__(self, A): Process.__init__(self) self.A = A def run(self): i = random.randint(0, len(self.A)-1) self.A[i] = self.A[i] + 1 if __name__ == '__main__': procs = [] M = Manager() a = M.list(range(15)) print('A: {0}'.format(a)) print('sum(A) = {0}'.format(sum(a))) for i in range(100): procs.append(MyProc(a)) map(lambda x: x.start(), procs) map(lambda x: x.join(), procs) print('A: {0}'.format(a)) print('sum(A) = {0}'.format(sum(a)))

    Read the article

  • Expression parser library for Android.

    - by Malx
    What is the best way to evaluate simple conditional statements like: "a>b" ? "x-4<10+y & y>x" ? Expressions are loaded from external file. Variables are set in application. Syntax used is not essential. It may be "&" or "and" or any other supported with language/library. I need to take different action depending on result of evaluation - is it true or false. Could I use any parser already included with Andorid? Is there some way to use JS "eval" from browser component? Is it possible to use sqlite expressions to get true/false result without selecting anything? Those libraries are implemented in native code. Will it be faster and less battery expensive?

    Read the article

  • Regex for zeroing in on build output text error

    - by Mike Atlas
    I'd like to quickly hone in on what failed in a build log output that is nearly 5k lines long, using Notepad++ as my editor for the file. Notepad++ has the nice ability to specify regular expressions, so I am wondering if there is a way to not match: Compile complete -- 0 errors, 0 warnings but to match, for example: Compile complete -- 1 errors, 0 warnings Compile complete -- 100 errors, 0 warnings where the match would be (1 or more) errors. If this isn't possible, I will probably just write a quick line-by-line parsing tool instead, but I was hoping someone on StackOverflow could whip out a regular expression in the same amount of time - I'm definitely not proficient enough with regular expressions to be able to write one for my needs in a short amount of time.

    Read the article

  • How to get all captures of subgroup matches with preg_match_all()?

    - by hakre
    Update/Note: I think what I'm probably looking for is to get the captures of a group in PHP. Referenced: PCRE regular expressions using named pattern subroutines. (Read carefully:) I have a string that contains a variable number of segments (simplified): $subject = 'AA BB DD '; // could be 'AA BB DD CC EE ' as well I would like now to match the segments and return them via the matches array: $pattern = '/^(([a-z]+) )+$/i'; $result = preg_match_all($pattern, $subject, $matches); This will only return the last match for the capture group 2: DD. Is there a way that I can retrieve all subpattern captures (AA, BB, DD) with one regex execution? Isn't preg_match_all suitable for this? This question is a generalization. Both the $subject and $pattern are simplified. Naturally with such the general list of AA, BB, .. is much more easy to extract with other functions (e.g. explode) or with a variation of the $pattern. But I'm specifically asking how to return all of the subgroup matches with the preg_...-family of functions. For a real life case imagine you have multiple (nested) level of a variant amount of subpattern matches. Example This is an example in pseudo code to describe a bit of the background. Imagine the following: Regular definitions of tokens: CHARS := [a-z]+ PUNCT := [.,!?] WS := [ ] $subject get's tokenized based on these. The tokenization is stored inside an array of tokens (type, offset, ...). That array is then transformed into a string, containing one character per token: CHARS -> "c" PUNCT -> "p" WS -> "s" So that it's now possible to run regular expressions based on tokens (and not character classes etc.) on the token stream string index. E.g. regex: (cs)?cp to express one or more group of chars followed by a punctuation. As I now can express self-defined tokens as regex, the next step was to build the grammar. This is only an example, this is sort of ABNF style: words = word | (word space)+ word word = CHARS+ space = WS punctuation = PUNCT If I now compile the grammar for words into a (token) regex I would like to have naturally all subgroup matches of each word. words = (CHARS+) | ( (CHARS+) WS )+ (CHARS+) # words resolved to tokens words = (c+)|((c+)s)+c+ # words resolved to regex I could code until this point. Then I ran into the problem that the sub-group matches did only contain their last match. So I have the option to either create an automata for the grammar on my own (which I would like to prevent to keep the grammar expressions generic) or to somewhat make preg_match working for me somehow so I can spare that. That's basically all. Probably now it's understandable why I simplified the question. Related: pcrepattern man page Get repeated matches with preg_match_all()

    Read the article

  • How to Get the F# Name of a Module, Function, etc. From Quoted Expression Match

    - by Stephen Swensen
    I continue to work on a printer for F# quoted expressions, it doesn't have to be perfect, but I'd like to see what is possible. The active patterns in Microsoft.FSharp.Quotations.Patterns and Microsoft.FSharp.Quotations.DerivedPatterns used for decomposing quoted expressions will typically provide MemberInfo instances when appropriate, these can be used to obtain the name of a property, function, etc. and their "declaring" type, such as a module or static class. The problem is, I only know how to obtain the CompiledName from these instances but I'd like the F# name. For example, > <@ List.mapi (fun i j -> i+j) [1;2;3] @> |> (function Call(_,mi,_) -> mi.DeclaringType.Name, mi.Name);; val it : string * string = ("ListModule", "MapIndexed") How can this match be rewritten to return ("List", "mapi")? Is it possible?

    Read the article

< Previous Page | 34 35 36 37 38 39 40 41 42 43 44 45  | Next Page >