working on it ...

Filters

Explore Public Snippets

Sort by

Found 96 snippets matching: "lambda expression"

    public by micurs  6865990  355  9  18

    Typescript: passing a class member function as parameter to another function

    Typescript introduces the class construct and the concept of member functions. However if you try to pass a instance member function as parameter to another function the binding with the instance is lost. To solve this problem you can use the capability of javascript (and Typescript) to support closures on anonymous function (or lambda expressio
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    class SomePeople {
      values : string[] = [ 'John', 'Mary', 'Peter'];
    
      out() {
        _.each( this.values, (v) => process.stdout.write( v + '\n') );
      }
    }
    // This function accept a function it will execute internally
    function outSomething( outFunc : () => any ) {
      outFunc();
    }
    
    var crowd = new SomePeople();
    
    // This won't work since the actual crowd instance binding will be lost
    outSomething( crowd.out );
    
    // This will work: the closure within the lambda expression retain the
    // crowd instance and its data
    outSomething( () => crowd.out() );
        

    public by lbottaro  13296  66  8  0

    Using lambda function to pass extra argument to slots using PyQt4 python

    When programming with PyQt is useful to pass extra arguments to slots callback methods, in order to execute some code when a UI control's action is invoked. In this example you can see the usage of lambda expression to pass the extra argument to the method invoked when pressing a button. Thanks to http://eli.thegreenplace.net/2011/04/25/passi
    self.greeting = QLabel('', self)
    
    # Create the build button with its caption
    self.build_button = QPushButton('&Build Greeting', self)
     
    # Connect the button's clicked signal to AddControl
    self.build_button.clicked.connect(lambda: self.AddControl('fooData'))
    
    def AddControl(self, name):
        self.greeting.setText('%s!' % (name))
    
    

    public by micurs  12304  4  10  4

    Typescript + underscore: serializing objects

    This little example runs on node.js and assumes you have the typescript type-definition file in the types subdirectory. The example defines two classes one representing a undergrad course in computer science and another one representing possible students for the course. Few things are interesting here: 1 - the overloading of the toString()
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    function write(msg) {
        process.stdout.write(msg+'\n');
    }
    
    class Student {
      firstName : string;
      lastName : string;
    
      constructor( n: string, v: string ) {
        this.firstName = n;
        this.lastName = v;
      }
    
      toString() : string {
        return '[ ' + this.firstName + ' ' + this.lastName + ' ]';
      }
    }
    
    class Class {
      title : string = "Computer Science 101";
      participants : Student[] = new Array();
    
      addStudent( s : Student ) : any {
        this.participants.push(s);
      }
    
      toString() : string {
        return this.title + '\n\t' 
              + _.reduce( this.participants, (acc,s) => acc += '\n\t'+ s );
      }
    
    }
    
    var firstSemesterClass : Class = new Class();
    
    firstSemesterClass.addStudent( new Student("John","Smith"));
    firstSemesterClass.addStudent( new Student("Frank","Gehry"));
    
    write( firstSemesterClass );
    
        

    public by cghersi  3147  1  6  0

    Create a usage pattern for several heterogeneous methods

    Let's say we have several methods implemented in the same way but that should invoke different operations inside their implementation. e.g. we have a wrapper of API, and each API should be checked for the reload of endpoint if failed... Under these circumstances, C# lambda expressions should be very useful, but what about Java? Here there is a so
    public interface CallableOp<T> {
    	T exec();
    }
    
    /**
     * This is the generic method that provides the common implementation for several methods,
     * which are implemented in exec() method of the given input
     * @param op object of anonymous class that implement the internal logic of the method
     * @param clazz class of the returning object
     */
    public <T> T execOp(CallableOp<T> op, Class<T> clazz) {
    	try{
    		return op.exec();
    	}catch(WebServiceException webSerExc){
    		if (checkReloadEndpoint(webSerExc)) {
    			//with this exception we prepare reload endpoints and try again invoking ws
    			forcedReloaded = true;
    			return op.exec();
    		}else{
    			//forward the exception
    			throw webSerExc;
    		}
    	}
    }
    
    public void test() {
    	//here you don't need any cast nor reflection!
    	boolean res = execOp(new CallableOp<Boolean>() {
    		public Boolean exec() {
    			//parameters and other business logic may be implemented here 
    			//or directly in the test() method
    			int param1 = 1;
    			String param2 = "test";
    			return apiInvocation(param1, param2); // thi is the API invocation method 
    		}
    	}, Boolean.class);
    }

    public by msdn  856  0  6  0

    Between: Use the extension method to implement the Between operation in EF

    Use the extension method to implement the Between operation in EF Type of the entity Type of the return value The entity used to apply the method The lambda expression used to get the return value Low boundary of the return value High boundary of the return value return the IQueryable
    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    
    /// <summary>
       /// Use the extension method to implement the Between operation in EF
       /// </summary>
       /// <typeparam name="TSource">Type of the entity</typeparam>
       /// <typeparam name="TKey">Type of the return value</typeparam>
       /// <param name="source">The entity used to apply the method</param>
       /// <param name="keySelector">The lambda expression used to get the return value</param>
       /// <param name="low">Low boundary of the return value</param>
       /// <param name="high">High boundary of the return value</param>
       /// <returns>return the IQueryable</returns>
       public static IQueryable<TSource> Between<TSource, TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     TKey low, TKey high) where TKey : IComparable<TKey>
       {
           // Get a ParameterExpression node of the TSource that is used in the expression tree
           ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource));
    
           // Get the body and parameter of the lambda expression
           Expression body = keySelector.Body;
           ParameterExpression parameter = null;
           if (keySelector.Parameters.Count>0)
               parameter = keySelector.Parameters[0];
    
           // Get the Compare method of the type of the return value
           MethodInfo compareMethod = typeof(TKey).GetMethod("CompareTo", new[] { typeof(TKey) });
    
           // Expression.LessThanOrEqual and Expression.GreaterThanOrEqua method are only used in
           // the numeric comparision. If we want to compare the non-numeric type, we can't directly 
           // use the two methods. 
           // So we first use the Compare method to compare the objects, and the Compare method 
           // will return a int number. Then we can use the LessThanOrEqual and GreaterThanOrEqua method.
           // For this reason, we ask all the TKey type implement the IComparable<> interface.
           Expression upper = Expression.LessThanOrEqual(
               Expression.Call(body, compareMethod, Expression.Constant(high)),
               Expression.Constant(0, typeof(int)));
           Expression lower = Expression.GreaterThanOrEqual(
               Expression.Call(body, compareMethod, Expression.Constant(low)),
               Expression.Constant(0, typeof(int)));
    
           Expression andExpression = Expression.And(upper, lower);
    
           // Get the Where method expression.
           MethodCallExpression whereCallExpression = Expression.Call(
               typeof(Queryable),
               "Where",
               new Type[] { source.ElementType },
               source.Expression,
               Expression.Lambda<Func<TSource, bool>>(andExpression,
               new ParameterExpression[] { parameter }));
                
           return source.Provider.CreateQuery<TSource>(whereCallExpression);
       }

    external by garata  242  1  3  0

    C# Dispatch table based on "Generic Dictionary", "Collection Initializer" and "Lambda Expressions"

    C# Dispatch table based on "Generic Dictionary", "Collection Initializer" and "Lambda Expressions": tryjsil.cs
    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    public class Program
    {
        static void Main()
        {
            Func<int, bool> Default = (x => true);
            
            var myNum = 29;
    		// A dispatch table is a data structure that associates an index (or key) value to an action.
    		// It's a rather elegant replacement for a switch-case statement .
            var cases = new Dictionary<Func<int, bool>, Action>
            {
                { x => x < 3,   () => Console.WriteLine(String.Format("{0} is smaller than or equal to 3", myNum))     },
                { x => x < 30,  () => Console.WriteLine(String.Format("{0} is smaller than or equal to 30", myNum))    },
                { x => x < 300, () => Console.WriteLine(String.Format("{0} is smaller than or equal to 300", myNum))   },
                { Default,      () => Console.WriteLine("Default case")                                                }
            };
            cases.FirstOrDefault(kvp => kvp.Key(myNum)).Value();
        }
    }
    
    

    external by i88ca  162  0  2  0

    http://it.i88.ca/2015/09/java-lambda-expression-simple-example.html

    http://it.i88.ca/2015/09/java-lambda-expression-simple-example.html: Java Lambda Expression Simple Example.java
    /**
     *
     * @author i88.ca
     */
    public class Main {
    
        public static void main(String[] args) {
    
            String[] atp = {"Johon Doe", "Peter Smith", "Bruce Lee", "Jacky Chen"};
            List<String> contacts = Arrays.asList(atp);
    
    // Old looping
            for (String contact : contacts) {
                System.out.print(contact + "; ");
            }
            System.out.println();
    // Using lambda expression and functional operations
            contacts.forEach((contact) -> System.out.print(contact + "; "));
            System.out.println();
    // Using double colon operator in Java 8
            contacts.forEach(System.out::println);
        }
    }
    
    
    

    external by Ruslan Shevchenko  24  0  1  0

    jdv_article_4 (simple lambda-expression in java)

    jdv_article_4 (simple lambda-expression in java): gistfile1.java
     list.sort((x,y)-> { 
        int cmp = x.lastName.compareTo(y.lastName);
        return cmp!=0 ? cmp : x.firstName.compareTo(y.firstName)
    }
    
    
    
    

    external by Topi Ojala  13  0  1  0

    Aaron's solution with lambda-expression

    Aaron's solution with lambda-expression: Distinct_nonDistinct.cs
    [TestMethod]
    public void Observe_distint_nonDistinc()
    {
          var scheduler = new TestScheduler();
          var source = scheduler.CreateHotObservable(
              OnNext(100, "a"),
              OnNext(110, "b"),
              OnNext(200, "a"),
              OnNext(220, "c")
          );
    
          var results = scheduler.CreateObserver<string>();
          source.Distinct().Subscribe(results);
    
          var duplicates = scheduler.CreateObserver<string>();
          source.GroupBy(i => i)
                .SelectMany(i => i.Buffer(2)
                                .Where(j => j.Count > 1)
                                .Select(j => i.Key))
                .Subscribe(duplicates);
    
          scheduler.AdvanceBy(1000);
    
          results.Messages.AssertEqual(OnNext(100, "a"), OnNext(110, "b"), OnNext(220, "c"));
          duplicates.Messages.AssertEqual(OnNext(200,"a"));
     }
    
    

    external by Patrick Lautsch  6  0  1  0

    Delegate-Examples => Methods: named + anonymous + lambda-expression

    Delegate-Examples = Methods: named + anonymous + lambda-expression: delegate_examples.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    
    
    namespace SandboxConsole
    {
        // Declare delegate -- defines required signature:
        delegate double DTaschenrechner(double zahl);
    
    
    
        class Program
        {
            // Define: Regular method that matches the signature of the delegate:
            static double MalZwei(double input)
            {
                return (input * 2);
            }
    
        
            static void Main(string[] args)
            {
                // Instantiate delegate with named method:
                DTaschenrechner rechner = MalZwei;
                Console.WriteLine( rechner(5) ); // Ausgabe: 10
    
                // Instantiate delegate with anonymous method:
                DTaschenrechner rechner2 = delegate(double input)
                {
                    return (input * 2);
                };
                Console.WriteLine( rechner2(5) ); // Ausgabe: 10
    
                // Instatiate delegate with lambda expression
                DTaschenrechner rechner3 = s => s * 2;
                double zahl = rechner3(5);
                Console.WriteLine(zahl); // Ausgabe: 10
    
                Console.ReadKey();
            }
    
            
        }
    
    
    
    }
    
    
    
    • Public Snippets
    • Channels Snippets