Search Results

Search found 1037 results on 42 pages for 'lambda calculus'.

Page 33/42 | < Previous Page | 29 30 31 32 33 34 35 36 37 38 39 40  | Next Page >

  • Access to nested methods when DSL

    - by Vyacheslav Loginov
    class Warcraft def initialize &block instance_eval &block end def method_missing name, *args, &block instance_variable_set("@#{name}".to_sym, args[0]) self.class.send(:define_method, name, proc { instance_variable_get("@#{name}")}) end def game &block @game = Game.new &block end class Game def initialize &block instance_eval &block end def method_missing name, *args, &block instance_variable_set("@#{name}".to_sym, args[0]) self.class.send(:define_method, name, proc { instance_variable_get("@#{name}")}) end end end warcraft = Warcraft.new do name "Warcraft III" battle_net :iccup game do side :sentinels hero "Furion" rune_appear_every 2 end end puts warcraft.inspect # => #<Warcraft:0x00000000be3e80 @name="Warcraft III", @battle_net=:iccup, @game=#<Warcraft::Game:0x000000009c6c38 @side=:sentinels, @hero="Furion", @rune_appear_every=2>> How to access nested methods? puts warcraft.battle_net # => iccup puts warcraft.side #=> #<Proc:[email protected]:9 (lambda)> puts warcraft.game #=> dsl.rb:18:in `instance_eval': block not supplied (ArgumentError) puts warcraft.game.side #=> dsl.rb:18:in `instance_eval': block not supplied (ArgumentError)

    Read the article

  • How to sort a list by the 2nd tuple element in python and C#

    - by user350468
    I had a list of tuples where every tuple consists of two integers and I wanted to sort by the 2nd integer. After looking in the python help I got this: sorted(myList, key=lambda x: x[1]) which is great. My question is, is there an equally succinct way of doing this in C# (the language I have to work in)? I know the obvious answer involving creating classes and specifying an anonymous delegate for the whole compare step but perhaps there is a linq oriented way as well. Thanks in advance for any suggestions.

    Read the article

  • make tree in scheme

    - by ???
    (define (entry tree) (car tree)) (define (left-branch tree) (cadr tree)) (define (right-branch tree) (caddr tree)) (define (make-tree entry left right) (list entry left right)) (define (mktree order items_list) (cond ((= (length items_list) 1) (make-tree (car items_list) '() '())) (else (insert2 order (car items_list) (mktree order (cdr items_list)))))) (define (insert2 order x t) (cond ((null? t) (make-tree x '() '())) ((order x (entry t)) (make-tree (entry t) (insert2 order x (left-branch t)) (right-branch t))) ((order (entry t) x ) (make-tree (entry t) (left-branch t) (insert2 order x (right-branch t)))) (else t))) The result is: (mktree (lambda (x y) (< x y)) (list 7 3 5 1 9 11)) (11 (9 (1 () (5 (3 () ()) (7 () ()))) ()) ()) But I'm trying to get: (7 (3 (1 () ()) (5 () ())) (9 () (11 () ()))) Where is the problem?

    Read the article

  • How to save and load an array of complex numbers using numpy.savetxt?

    - by ptomato
    I want to use numpy.savetxt() to save an array of complex numbers to a text file. Problems: If you save the complex array with the default format string, the imaginary part is discarded. If you use fmt='%s', then numpy.loadtxt() can't load it unless you specify dtype=complex, converters={0: lambda s: complex(s)}. Even then, if there are NaN's in the array, loading still fails. It looks like someone has inquired about this multiple times on the Numpy mailing list and even filed a bug, but has not gotten a response. Before I put something together myself, is there a canonical way to do this?

    Read the article

  • How do I write a scheme macro that defines a variable and also gets the name of that variable as a s

    - by Jason Baker
    This is mostly a follow-up to this question. I decided to just keep YAGNI in mind and created a global variable (libpython). I set it to #f initially, then set! it when init is called. I added a function that should handle checking if that value has been initialized: (define (get-cpyfunc name type) (lambda args (if libpython (apply (get-ffi-obj name libpython type) args) (error "Call init before using any Python C functions")))) So now here's what I want to do. I want to define a macro that will take the following: (define-cpyfunc Py_Initialize (_fun -> _void)) And convert it into this: (define Py_Initialize (get-cpyfunc "Py_Initialize" (_fun -> _void))) I've been reading through the macro documentation to try figuring this out, but I can't seem to figure out a way to make it work. Can anyone help me with this (or at least give me a general idea of what the macro would look like)? Or is there a way to do this without macros?

    Read the article

  • Intellisense in Visual Studio 2010

    - by Erik
    For some reason the Intellisense in vb.net stopped working when I use an Aggregate Lambda expression inside a With statement. With Me.SalesPackage .WebLinks = Sales.Where(Function(f) f.Current.BookerWeb > 0).Count .WebAmount = Aggregate o In Sales.Where(Function(f) f.Current.WebBooker > 0) Into Sum(o.Current.WebPrice) End With If I insert a new line between .WebLinks and .WebAmount and start typing, it works. But it won't work if I do it after the Aggregate statement... Any ideas?

    Read the article

  • Rewriting usort function because of fatal error (PHP bug)

    - by Lionel
    The two following usort functions throw fatal error Base lambda function for closure not found in our productive environment (PHP 5.4). This seems to be a known PHP bug that should be fixed by now (https://bugs.php.net/bug.php?id=52144), but it still occurs for us. Anyway, we unfortunately don't have time to figure out what's wrong with our PHP configurations etc. We would like to rewrite these two functions without the use of anonymous functions, so that the error doesn't occur anymore. Ordering of a multidimensional array ($array) by value of key "position": usort($array, function($a, $b) { return $a['position'] - $b['position']; }); Ordering of a multidimensional array ($array) according to the order of a second array ($position_order): usort($array, function($a, $b) use($position_order) { return (isset($position_order[$a['ftid']]) ? ($position_order[$a['ftid']] - $position_order[$b['ftid']]) : 1); }); Especially the latter causes some headache, as we don't know how to pass the "outside" array $position_order.

    Read the article

  • Apply function to one element of a list in Python

    - by user189637
    I'm looking for a concise and functional style way to apply a function to one element of a tuple and return the new tuple, in Python. For example, for the following input: inp = ("hello", "my", "friend") I would like to be able to get the following output: out = ("hello", "MY", "friend") I came up with two solutions which I'm not satisfied with. One uses a higher-order function. def apply_at(arr, func, i): return arr[0:i] + [func(arr[i])] + arr[i+1:] apply_at(inp, lambda x: x.upper(), 1) One uses list comprehensions (this one assumes the length of the tuple is known). [(a,b.upper(),c) for a,b,c in [inp]][0] Is there a better way? Thanks!

    Read the article

  • Running Python code from Java program, shoudl i be doing this?

    - by Space Rocker
    i have a scenario where i draw a network and set all it's paraments on swing based gui, after that i have to translate this network into a python based script which another framework reads and realize this network in the form of virtual machines. As an example have look here: from mininet.topo import Topo, Node class MyTopo( Topo ): def *__init__*( self, enable_all = True ): super( MyTopo, self ).__init__() Host = 1 Switch = 2 self.add_node( Switch, Node( is_switch=True ) ) self.add_node( Host, Node( is_switch=False ) ) self.add_edge( Host, Switch ) self.enable_all() topos = { 'mytopo': ( lambda: MyTopo() ) } It simply connects a host to a switch and realize this topology on mininet framework. Now for now in order to realize the drawn network on java GUI here is what i am doing: I simply take the information from GUI and creates a new python file like the one above using java code and then run this file in mininet, which works fine somehow. I want to know, is this the correct and robust way how i am doing this or should i be looking further into java-python bridge like scenarios to be more effective or so as to say more professional.

    Read the article

  • Rails: has_many association with a table in another database and without foreign key

    - by Fernando
    Here is my situation. I have model called Account. An account can have one or more contracts. The problem is that i'm dealing with a legacy application and each account's contracts are stored in a different database. Example: Account 1's contract are in account1_db.contracts. Account 2's contract are in account2_db.contracts. The database name is a field stored in accounts table. How can i make rails association work with this? This is a legacy PHP application and i simply can't change it to store everything in one table. I need to make it work somehow. I tried this, but it didn't worked: has_many :contracts, :conditions => [lambda{ Contract.set_table_name(self.database + '.contracts'); return '1' }] Any ideas?

    Read the article

  • define method for instance of class

    - by aharon
    Let there be class Example defined as: class Example def initialize(test='hey') self.class.send(:define_method, :say_hello, lambda { test }) end end On calling Example.new; Example.new I get a warning: method redefined; discarding old say_hello. This, I conclude, must be because it defines a method in the actual class (which makes sense, from the syntax). And that, of course, would prove disastrous should there be multiple instances of Example with different values in their methods. Is there a way to create methods just for the instance of a class from inside that instance? Thanks so much.

    Read the article

  • C# ToDictionary can valueSelector give null?

    - by Trimack
    Hi, I want to make a dictionary out of list in a way, that the list becomes keys and values would be empty. I have following code Dictionary<XmlTest, int?> testBattery = new XmlTests().GetRandomTestBattery(id). ToDictionary(k => k, v => null); But I am getting the error "Cannot convert lambda expression to type System.Collections.Generic.IEqualityComparer' because it is not a delegate type" Any ideas how could I fix it? (I know I could iterate through and fill the dict one element at a time, but I simply want to use something more elegant)

    Read the article

  • What are the other new features of C# 4.0, after dynamic and optional parameters?

    - by Abel
    So, C# 4.0 came out yesterday. It introduced the much-debated dynamic keyword, named and optional parameters. Smaller improvements were the implicit ref and recognizing of indexed and default properties on COM methods, contra- and co-variance (really a .NET CLR feature, not C# only) and... Is that really it? Are dynamic and optional/named params the only real improvements to C#? Or did I miss something? Not that I'm complaining, but it seems a bit meager after C# 2.0 (generics) and C# 3.0 (lambda, LINQ). Maybe the language just reached actual maturity?

    Read the article

  • Is there an easy way in Python to wait until certain condition is true?

    - by Checkers
    I need to wait in a script until a certain number of conditions become true? I know I can roll my own eventing using condition variables and friends, but I don't want to go through all the trouble of implementing it, since some object property changes come from external thread in a wrapped C++ library (Boost.Python), so I can't just hijack __setattr__ in a class and put a condition variable there, which leaves me with either trying to create and signal a Python condition variable from C++, or wrap a native one and wait on it in Python, both of which sound fiddly, needlessly complicated and boring. Is there an easier way to do it, barring continuous polling of the condition? Ideally it would be along the lines of res = wait_until(lambda: some_predicate, timeout) if (not res): print 'timed out'

    Read the article

  • Is it possible to refactor this C# if(..) statement?

    - by Pure.Krome
    Hi folks, simple question :- i have the following simple if (..) statements :- if (foo == Animal.Cat || foo == Animal.Dog) { .. } if (baa == 1|| baa == 69) { .. } is it possible to refactor these into something like ... DISCLAIMER: I know this doesn't compile .. but this is sorta what i'm trying to get... if (foo == (Animal.Cat || Animal.Dog)) { .. } if (baa == (1 || 69)) { .. } Cheers :) EDIT I wonder if a lambda expression extension could do this? :P

    Read the article

  • How do I bind a key to "the function represented by the following key sequence"?

    - by katrielalex
    I'm just starting to learn emacs (woohoo!) and I've been mucking around in my .emacs quite happily. Unfortunately, I don't know Lisp yet, so I'm having issues with the basics. I've already remapped a few keys until I fix my muscle memory: (global-set-key (kbd "<f9>") 'recompile) That's fine. But how can I tell a key to 'simulate pressing several keys'? For instance, I don't know, make <f1> do the same as C-u 2 C-x } (widen buffer by two chars). One way is to look up that C-x } calls shrink-window-horizontally, and do some sort of lambda thing. This is of course the neat and elegant way (how do you do this?). But surely there's a way to define <f1> to send the keystrokes C-u 2 C-x }?

    Read the article

  • Using Rails and Rspec, how do you test that the database is not touched by a method

    - by Will Tomlins
    So I'm writing a test for a method which for performance reasons should achieve what it needs to achieve without using SQL queries. I'm thinking all I need to know is what to stub: describe SomeModel do describe 'a_getter_method' do it 'should not touch the database' do thing = SomeModel.create something_inside_rails.should_not_receive(:a_method_querying_the_database) thing.a_getter_method end end end EDIT: to provide a more specific example: class Publication << ActiveRecord::Base end class Book << Publication end class Magazine << Publication end class Student << ActiveRecord::Base has_many :publications def publications_of_type(type) #this is the method I am trying to test. #The test should show that when I do the following, the database is queried. self.publications.find_all_by_type(type) end end describe Student do describe "publications_of_type" do it 'should not touch the database' do Student.create() student = Student.first(:include => :publications) #the publications relationship is already loaded, so no need to touch the DB lambda { student.publications_of_type(:magazine) }.should_not touch_the_database end end end So the test should fail in this example, because the rails 'find_all_by' method relies on SQL.

    Read the article

  • Vb.Net action delegate problem?

    - by Ramesh Vel
    Hi, Am vb.net newbie. This question might be very novice and answered before, but i couldn't find. I was trying the lambda features and got struck here. Private Function HigerOrderTest(highFunction as Func(Of Int16,Int16)) As Action(of String) Dim sam = highFunction(3) Dim DoIt as Action(of String) DoIt = sub(s) console.WriteLine(s) return DoIt End Function I got "Expression expected." at line DoIt = sub(s) console.WriteLine(s). And when i changed this to DoIt = function(s) console.WriteLine(s) i got Expression does not produce a value. error. Whats the problem? Cheers

    Read the article

  • Storing expression template functors

    - by UncaughtException
    Hello guys, at the moment I'm really interested in expression templates and want to code a library for writing and differentiating mathematical functions with a lambda-style syntax. At the moment, I'm able to write (_x * _x)(2); and get the correct result 4. But I would really like to do something like MathFunction f = _x * _x; f(2);, but I don't have any ideas on how to cope with the recursive expression templates on the right side. Is it possible to achieve this without using the 'auto'-Keyword instead of MathFunction or having to make the operator() virtual? Thanks for your help!

    Read the article

  • Removing whitespace in Java string?

    - by waitinforatrain
    Hi guys, I'm writing a parser for some LISP files. I'm trying to get rid of leading whitespace in a string. The string contents are along the lines of: :FUNCTION (LAMBDA (DELTA PLASMA-IN-0) (IF (OR (>= #61=(+ (* 1 DELTA) PLASMA-IN-0) 100) (<= #61# 0)) PLASMA-IN-0 #61#)) The tabs are all printed as 4 spaces in the file, so I want to get rid of these leading tabs. I tried to do this: string.replaceAll("\\s{4}", " ") - but it had no effect at all on the string. Does anyone know what I'm doing wrong? Is it because it is a multi-line string? Thanks

    Read the article

  • Mapping over multiple Seq in Scala

    - by bsdfish
    Suppose I have val foo : Seq[Double] = ... val bar : Seq[Double] = ... and I wish to produce a seq where the baz(i) = foo(i) + bar(i). One way I can think of to do this is val baz : Seq[Double] = (foo.toList zip bar.toList) map ((f: Double, b : Double) => f+b) However, this feels both ugly and inefficient -- I have to convert both seqs to lists (which explodes with lazy lists), create this temporary list of tuples, only to map over it and let it be GCed. Maybe streams solve the lazy problem, but in any case, this feels like unnecessarily ugly. In lisp, the map function would map over multiple sequences. I would write (mapcar (lambda (f b) (+ f b)) foo bar) And no temporary lists would get created anywhere. Is there a map-over-multiple-lists function in Scala, or is zip combined with destructuring really the 'right' way to do this?

    Read the article

  • What is the best way to set default values in ActiveRecord?

    - by ryw
    What is the best way to set default value in ActiveRecord? I see a post from Pratik that describes an ugly, complicated chunk of code: http://m.onkey.org/2007/7/24/how-to-set-default-values-in-your-model class Item < ActiveRecord::Base def initialize_with_defaults(attrs = nil, &block) initialize_without_defaults(attrs) do setter = lambda { |key, value| self.send("#{key.to_s}=", value) unless !attrs.nil? && attrs.keys.map(&:to_s).include?(key.to_s) } setter.call('scheduler_type', 'hotseat') yield self if block_given? end end alias_method_chain :initialize, :defaults end YUCK! I have seen the following examples googling around: def initialize super self.status = ACTIVE unless self.status end and def after_initialize return unless new_record? self.status = ACTIVE end I've also seen people put it in their migration, but I'd rather see it defined in the model code. What's the best way to set default value for fields in ActiveRecord model?

    Read the article

  • Linq To SQL: Retain list order when using .Contains

    - by rockinthesixstring
    I'm using Lucene.net to build a MyListOfIds As List(Of Integer) which I then pass on to my Linq service. I then search the database as follows Return _EventRepository.Read().Where(Function(e) MyListOfIds.Contains(e.ID)).ToList Now I know that Lucene is already ordering MyListOfIds based on the weight it gave each term. What sucks is that Linq is losing that order in it's SQL search. My Question: How can I retain that sort order when building my Lambda expression? I tried using LINQPad to see how the query is being built, but because I had to declare a variable LINQPad didn't show me the resultant SQL :-( Here's what I tried in LINQPad Dim i As New List(Of Integer) i.Add(1) i.Add(100) i.Add(15) i.Add(3) i.Add(123) Dim r = (From e In Events Where i.Contains(e.ID) Select e) note: my example is in VB.NET, but I don't mind if responses are in C#

    Read the article

  • Safely dereferencing FirstOrDefault call in Linq c#

    - by samy
    For brevity's sake in my code, i'd like to be able to do the following: having a collection, find the first element matching a lambda expression; if it exists, return the value of a property or function. If it doesn't exist, return null. var stuff = {"I", "am", "many", "strings", "obviously"}; var UpperValueOfAString = stuff.FirstOrDefault(s => s.contains("bvi")).ToUpper(); // would return "OBVIOUSLY" var UpperValueOfAStringWannabe = stuff.FirstOrDefault(s => s.contains("unknown token")).ToUpper(); // would return null Is it possible with some linq-syntax-fu or do i have to check explicitly for the return value before proceeding?

    Read the article

  • deploying a war to tomcat using python

    - by Decado
    Hi, I'm trying to deploy a war to a Apache Tomcat server (Build 6.0.24) using python (2.4.2) as part of a build process. I'm using the following code import urllib2 import base64 war_file_contents = open('war_file.war','rb').read() username='some_user' password='some_pwd' base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = "Basic %s" % base64string opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request('http://158.155.40.110:8080/manager/deploy?path=war_file', data=war_file_contents) request.add_header('Content-Type', 'application/octet-stream') request.add_header("Authorization", authheader) request.get_method = lambda: 'PUT' url = opener.open(request) the url.code is 200, and the url.msg is "OK". However the web archive doesn't appear on the manager list applications page. Thanks.

    Read the article

< Previous Page | 29 30 31 32 33 34 35 36 37 38 39 40  | Next Page >