working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,736 snippets matching: lambda

    public by micurs  6865995  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  13299  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 lbottaro  5522  0  6  0

    sort list using python lambda expression

    Using lambda function it's easy to sort data in array (or list) based on specific object attribute.
    #!/usr/bin/python
    import os
    import sys
    import string
    machineListStatus = list()
    
    for i in range(1, 10):
        currMachine = {
            'machine' : 'name' + str(i),
    	'sizePercentage' : i,
        }
        machineListStatus.append(currMachine)
        # Data ordered as:
        # 1, 2, 3, .. 10
        print currMachine['sizePercentage']
    
    machineListStatus = sorted(machineListStatus, key=lambda x: x['sizePercentage'], reverse=True)
    # Data ordered as:
    # 10, 9, .., 1
    for elem in machineListStatus:
        print elem['sizePercentage']

    public by micurs  3801  2  7  3

    Generate comma separated value string in Typescript using underscore _.reduce()

    Underscore work well with Typescript lambda syntax.
    import _ = require("underscore");
    
    var values: number[] = [ 5, 19, 64, 12, 45 ];
    
    var csv: string = 
     _.reduce( values, 
              ( acc: string, item ) => acc+= ','+item.toString() 
             );
         

    public by lbottaro  1831  0  5  1

    C# LINQ query lambda expression

    This c# code is a LINQ query to easily check data value into a List without looping it
    List<MyObj> actual = new List<MyObj>();
    Assert.IsTrue(actual.Exists(x => x.UserID == userKvp.Value.ID), string.Format("UserID missing! Expected: {0}, GroupID: {1}", userKvp.Value.ID, groupID));

    public by Bobby Kozora  3052  64  3  0

    AWS Lambda AMI Backups

    AWS Lambda AMI Backups: lambdaAMIBackups.py
    # Automated AMI Backups
    #
    # @author Robert Kozora <robert.kozora@wheaton.com>
    #
    # This script will search for all instances having a tag with "Backup" or "backup"
    # on it. As soon as we have the instances list, we loop through each instance
    # and create an AMI of it. Also, it will look for a "Retention" tag key which
    # will be used as a retention policy number in days. If there is no tag with
    # that name, it will use a 7 days default value for each AMI.
    #
    # After creating the AMI it creates a "DeleteOn" tag on the AMI indicating when
    # it will be deleted using the Retention value and another Lambda function 
    
    import boto3
    import collections
    import datetime
    
    ec = boto3.client('ec2')
    
    def lambda_handler(event, context):
        
        reservations = ec.describe_instances(
            Filters=[
                {'Name': 'tag-key', 'Values': ['backup', 'Backup']},
            ]
        ).get(
            'Reservations', []
        )
    
        instances = sum(
            [
                [i for i in r['Instances']]
                for r in reservations
            ], [])
    
        print "Found %d instances that need backing up" % len(instances)
    
        to_tag = collections.defaultdict(list)
    
        for instance in instances:
            try:
                retention_days = [
                    int(t.get('Value')) for t in instance['Tags']
                    if t['Key'] == 'Retention'][0]
            except IndexError:
                retention_days = 7
                
            # Loop through instance's EBS volumes
            #for dev in instance['BlockDeviceMappings']:
            #    if dev.get('Ebs', None) is None:
            #        continue
            #    vol_id = dev['Ebs']['VolumeId']
            #    print "Found EBS volume %s on instance %s" % (
            #        vol_id, instance['InstanceId'])
    
                #snap = ec.create_snapshot(
                #    VolumeId=vol_id,
                #)
                
                #create_image(instance_id, name, description=None, no_reboot=False, block_device_mapping=None, dry_run=False)
                # DryRun, InstanceId, Name, Description, NoReboot, BlockDeviceMappings
                create_time = datetime.datetime.now()
                create_fmt = create_time.strftime('%Y-%m-%d.%H.%M.%S')
            
                AMIid = ec.create_image(InstanceId=instance['InstanceId'], Name="Lambda - " + instance['InstanceId'] + " From " + create_fmt, Description="Lambda created AMI of instance " + instance['InstanceId'], NoReboot=True, DryRun=False)
                to_tag[retention_days].append(AMIid['ImageId'])
    
                print "Retaining AMI %s of instance %s for %d days" % (
                    AMIid['ImageId'],
                    instance['InstanceId'],
                    retention_days,
                )
    
        for retention_days in to_tag.keys():
            delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
            delete_fmt = delete_date.strftime('%m-%d-%Y')
            print "Will delete %d AMIs on %s" % (len(to_tag[retention_days]), delete_fmt)
    
            ec.create_tags(
                Resources=to_tag[retention_days],
                Tags=[
                    {'Key': 'DeleteOn', 'Value': delete_fmt},
                ]
            )
        
    
    

    public by Geometry  1037  0  6  0

    Convert: Converts <see cref="SupportVectorMachineLearningConfigurationFunction "/> into a lambda function that can be passed to the <see cref="OneVsRestLearning{TInput, TBinary, TModel}.Learner"/> property of a <see cref="Multi...

    Converts into a lambda function that can be passed to the property of a learning algorithm.
    /// <summary>
    ///   Converts <see cref="SupportVectorMachineLearningConfigurationFunction "/>
    ///   into a lambda function that can be passed to the <see cref="OneVsRestLearning{TInput, TBinary, TModel}.Learner"/>
    ///   property of a <see cref="MultilabelSupportVectorLearning"/> learning algorithm.
    /// </summary>
    /// 
    public static Func<InnerParameters, InnerLearning> Convert(
        SupportVectorMachineLearningConfigurationFunction conf)
    {
        return delegate(InnerParameters parameters)
        {
            int[] y = Classes.ToMinusOnePlusOne(parameters.Outputs);
            var machine = (KernelSupportVectorMachine)parameters.Model;
            ISupportVectorMachineLearning r = conf(machine, parameters.Inputs, y, parameters.Pair.Class1, parameters.Pair.Class2);
    
            var c = r as ISupervisedLearning<SupportVectorMachine<IKernel<double[]>>, double[], bool>;
            if (c != null)
                return c;
    
    
            // TODO: The following checks exist only to provide support to previous way of using
            // the library and should be removed after a few releases.
            var svc = r as ISupportVectorMachineLearning;
            if (svc != null)
            {
                svc.Run();
                return null;
            }
    
            throw new Exception();
        };
    }

    public by bkozora  1517  33  4  0

    AWS Lambda Function to Delete AMIs and Snapshots

    AWS Lambda Function to Delete AMIs and Snapshots: lambdaAMICleanup.py
    # Automated AMI and Snapshot Deletion
    #
    # @author Robert Kozora <robert.kozora@wheaton.com>
    #
    # This script will search for all instances having a tag with "Backup" or "backup"
    # on it. As soon as we have the instances list, we loop through each instance
    # and reference the AMIs of that instance. We check that the latest daily backup
    # succeeded then we store every image that's reached its DeleteOn tag's date for
    # deletion. We then loop through the AMIs, deregister them and remove all the
    # snapshots associated with that AMI.
    
    import boto3
    import collections
    import datetime
    import time
    import sys
    
    ec = boto3.client('ec2', 'us-east-1')
    ec2 = boto3.resource('ec2', 'us-east-1')
    images = ec2.images.filter(Owners=["xxxxxx"])
    
    def lambda_handler(event, context):
    
        reservations = ec.describe_instances(
            Filters=[
                {'Name': 'tag-key', 'Values': ['backup', 'Backup']},
            ]
        ).get(
            'Reservations', []
        )
    
        instances = sum(
            [
                [i for i in r['Instances']]
                for r in reservations
            ], [])
    
        print "Found %d instances that need evaluated" % len(instances)
    
        to_tag = collections.defaultdict(list)
    
        date = datetime.datetime.now()
        date_fmt = date.strftime('%Y-%m-%d')
    
        imagesList = []
    
        # Set to true once we confirm we have a backup taken today
        backupSuccess = False
    
        # Loop through all of our instances with a tag named "Backup"
        for instance in instances:
    	imagecount = 0
    
            # Loop through each image of our current instance
            for image in images:
    
                # Our other Lambda Function names its AMIs Lambda - i-instancenumber.
                # We now know these images are auto created
                if image.name.startswith('Lambda - ' + instance['InstanceId']):
    
                    # print "FOUND IMAGE " + image.id + " FOR INSTANCE " + instance['InstanceId']
    
                    # Count this image's occcurance
    	        imagecount = imagecount + 1
    
                    try:
                        if image.tags is not None:
                            deletion_date = [
                                t.get('Value') for t in image.tags
                                if t['Key'] == 'DeleteOn'][0]
                            delete_date = time.strptime(deletion_date, "%m-%d-%Y")
                    except IndexError:
                        deletion_date = False
                        delete_date = False
    
                    today_time = datetime.datetime.now().strftime('%m-%d-%Y')
                    # today_fmt = today_time.strftime('%m-%d-%Y')
                    today_date = time.strptime(today_time, '%m-%d-%Y')
    
                    # If image's DeleteOn date is less than or equal to today,
                    # add this image to our list of images to process later
                    if delete_date <= today_date:
                        imagesList.append(image.id)
    
                    # Make sure we have an AMI from today and mark backupSuccess as true
                    if image.name.endswith(date_fmt):
                        # Our latest backup from our other Lambda Function succeeded
                        backupSuccess = True
                        print "Latest backup from " + date_fmt + " was a success"
    
            print "instance " + instance['InstanceId'] + " has " + str(imagecount) + " AMIs"
    
        print "============="
    
        print "About to process the following AMIs:"
        print imagesList
    
        if backupSuccess == True:
    
            snapshots = ec.describe_snapshots(MaxResults=1000, OwnerIds=['xxxxx'])['Snapshots']
    
            # loop through list of image IDs
            for image in imagesList:
                print "deregistering image %s" % image
                amiResponse = ec.deregister_image(
                    DryRun=False,
                    ImageId=image,
                )
    
                for snapshot in snapshots:
                    if snapshot['Description'].find(image) > 0:
                        snap = ec.delete_snapshot(SnapshotId=snapshot['SnapshotId'])
                        print "Deleting snapshot " + snapshot['SnapshotId']
                        print "-------------"
    
        else:
            print "No current backup found. Termination suspended."
    
    

    public by micurs  12305  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 lbottaro  2731  0  6  1

    C# linq expression to check all data in a given List

    This c# linq lambda function example shows how to verify if all items in a List are present in another List object. You don't need to loop or iterate for each element, just use the All extension method.
    List<string> myList = new List<string>();
    myList.Add("123");
    myList.Add("456");
    
    // myTargetList is a given List<string>
    
    Assert.IsTrue(myList.All(x => myTargetList.Contains(x)), "myList has element missing in myTargetList!"));
    • Public Snippets
    • Channels Snippets