working on it ...

Filters

Explore Public Snippets

Sort by

Found 216 snippets matching: behavioral

    public by mprisznyak modified Apr 15, 2014  229295  0  6  3

    Observer

    a tongue-in-cheek example for the observer pattern
    # -*- coding: utf-8 -*-
    
    """
    a tongue-in-cheek example for the observer pattern
    
    Hungary elects today :)
    """
    
    # let's use a decorator
    def observe(f):
        def decorated(self, something):
            for obs in self.observers:
                obs.notify(self, f.func_name, something)
            return f(self, something)
        return decorated
    
    
    class Observer(object):
    
        def __init__(self, name):
            self.name = name
    
        def notify(self, observed, action, something):
            name = self.name
            observed_name = observed.name
            print "{name} reports that {observed_name} {action} {something}".format(**locals())
    
    
    class Voter(object):
    
        def __init__(self, name):
            self.name = name
            self.observers = []
    
        def add_observers(self, *observers):
            self.observers.extend(observers)
    
        @observe
        def votes(self, party):
            print "{name} votes for {party}".format(name=self.name, party=party)
    
        @observe
        def eats(self, food):
            print "{name} eats {food}".format(name=self.name, food=food)
    
        def digests(self, food):
            print "{name} digests {food}".format(name=self.name, food=food)
    
    
    if __name__ == "__main__":
        # observers
        OSCE = Observer("Organization for Security and Co-operation in Europe")
        UNO  = Observer("United Nations")
        God  = Observer("God")
        # poor voter
        jani = Voter("Kovács János")
        jani.add_observers(OSCE, UNO, God)
        jani.votes("Fidesz")
        print
        jani.eats("Sunday lunch")
        # luckily digestion is not observed
        print
        jani.digests("Sunday lunch")

    public by mprisznyak modified May 3, 2016  4720  2  5  3

    Command pattern

    Look ma, no objects!
    # Command Pattern 
    # using only functions which are "first-class citizen" in Python
    # and therefore they can be passed around 
    
    # do something actually
    def say(msg):
    	print(msg)
    
    # action functions
    def meauw():
    	say("meauw")
    
    def woof():
    	say("woof")
    	
    def neigh():
    	say("nyihaha!!!")
    
    # command -> action mapping
    actions =  {
    	"cat": meauw,
    	"dog": woof,
    	"horse": neigh,
    }
    
    
    def handle(command):
      """
      the command executioner...
      whoohaahaa! :)
      """
    	action = actions.get(command,None)
    	if action: # existing command
    		action() # execute command
    	else: # no command found
    		say("Sorry! No %s here." % command) # no such command!
    
    
    for cmd in ["cat", "horse", "dog", "elephant"]:
      handle(cmd)
                                        

    public by mprisznyak modified Aug 4, 2015  3903  3  6  2

    Command design pattern

    A generic implementation for the Command design pattern It's demonstrated by two toy examples: 1/ a lamp which can be turned on and off 2/ a car which can be started up, filled up with petrol and driven. Some commands have parameters in this example.
    # -*- coding: utf-8 -*-
    """
    Command design pattern
    """
    
    class Command(object):
        """ generic command class
        """
        def __init__(self, action, target):
            if callable(action):
                self._action = action
            else:
                raise Exception("callable action required")
            self.target = target
    
        def execute(self, *args):
            self._action(*args)
    
    
    class CommandClient(object):
        """Generic command client class"""
    
        def __init__(self, subject):
            self.subject = subject
            self._commands = {}
    
        def reset_subject(self):
            self.subject.__init__()
    
        def add_command(self, command_name, action):
            """
            :param command_name: the name of the command
            :type command_name: string
            :param action: a method of 'subject'
            :type action: string
            """
            command_name = command_name.strip().upper()
            action = getattr(self.subject, action, None)
            if action:
                self._commands[command_name] = Command(action, self.subject)
            else:
                raise Exception("invalid action %s" % action)
    
        def execute(self, cmd, *args):
            """
            :param cmd: command name
            :type cmd: string
            :param args: possible arguments for command
            :type args: optional input parameters for command
            """
            cmd = cmd.strip().upper()
            command = self._commands.get(cmd)
            if command is None:
                print 'Unknown command ', cmd
            else:
                command.execute(*args)
    
        def query(self, attr):
            """
            :param attr: name of attribute for 'subject'
            :type attr: string
            """
            return getattr(self.subject, attr, "Undefined")
    
    
    
    class Light(object):
        """An example command receiver class"""
    
        ON = "ON"
        OFF = "OFF"
    
        def __init__(self):
            self.state = Light.OFF
    
        def turn_on(self):
            print "Switching the lights on"
            self.state = Light.ON
    
        def turn_off(self):
            print "Switching the lights off"
            self.state = Light.OFF
    
    class Car(object):
        """Another example command receiver class"""
    
        PETROL_IN_100 = 6.5
    
        def __init__(self):
            self.engine_running = False
            self.speed = 0.0
            self.fuel = 0.0
    
        def start(self):
            if self.fuel > 0.0:
                print "The car engine is starting..."
                self.engine_running = True
            else:
                print "The car tank is empty"
    
        def drive(self, distance):
            " drive distance kilometres"
            if self.engine_running:
                fuel_required = distance*self.PETROL_IN_100/100.0
                if self.fuel < fuel_required:
                    print "The car needs fuel"
                else:
                    print "  travelled %s kms" % distance
                    self.fuel -= fuel_required
                    print "  %s litres of petrol left" % self.fuel
            else:
                print "Car engine hasn't been started..."
    
        def fill_up_with_petrol(self, amount):
            self.fuel += amount
    
    
    if __name__ == "__main__":
    
        print "========= Lights ==========="
        light_switch = CommandClient(Light())
        light_switch.add_command("ON", "turn_on")
        light_switch.add_command("OFF", "turn_off")
    
        light_switch.execute("ON")
        print "The lamp is", light_switch.query("state")
        light_switch.execute("OFF")
        print "The lamp is", light_switch.query("state")
        print "Invalid Command for lights"
        light_switch.execute("****")
        print "Lamp is", light_switch.query("state")
    
    
        print
        print "====== Fine ride ========"
        car_ride = CommandClient(Car())
        car_ride.add_command("fill", "fill_up_with_petrol")
        car_ride.add_command("Start", "start")
        car_ride.add_command("DRIVE", "drive")
    
        car_ride.execute("FILL", 15)
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("START")
        car_ride.execute("DRIVE", 34)
    
        print
        print "==== Fool's ride  ======="
        car_ride.reset_subject()
    
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("DRIVE", 77)
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("START")
        car_ride.execute("FILL", 15)
        car_ride.execute("DRIVE", 18843)
        print "fuel: ", car_ride.query("fuel")            

    public by mprisznyak modified May 1, 2014  2254  1  6  4

    Chain of responsibility

    a tongue-in-cheek example for the chain of responsibility pattern
    """
    The chain of responsibility pattern aims at minimizing the coupling  between request senders and request receivers.
    The patter provides  more than one object a chance to handle the request. The request travels along the chain until an object is found which can handle it.
    
    """
    
    class Handler(object):
    
        def __init__(self, next_handler):
            self.next_handler = next_handler
    
        @property
        def name(self):
            klass_name = self.__class__.__name__
            return klass_name.lower()
    
        def handle(self, request):
            try:
                handler = getattr(self, request)
                handler()
            except AttributeError as e:
                # pass on request
                print "   passing request '{request}' from {from_} to {name}".format(request=request, from_=self.name,
                                                                                  name= self.next_handler.name)
                self.next_handler.handle(request)
    
    
    class Boss(Handler):
        def __init__(self, employee):
            super(Boss, self).__init__(employee)
    
        def shout(self):
            print "Hey!!"
    
    
    class Employee(Handler):
        def __init__(self, wife):
            super(Employee, self).__init__(wife)
    
        def quarrel(self):
            print "you're so nasty, darling!"
    
    class Wife(Handler):
        def __init__(self, kid):
            super(Wife, self).__init__(kid)
    
        def tell_off_kid(self):
            print "{name} says to {next_in_chain}... 'you're a bad boy!' ".format(name=self.name,
                                                                                  next_in_chain=self.next_handler.name)
    
    class Kid(Handler):
    
        def __init__(self, dog):
            super(Kid, self).__init__(dog)
    
        def kick_the_dog(self):
            print "The dog is kicked... and says",
            self.next_handler.handle("kick")
    
    class Dog(object):
    
        def __init__(self):
            self.name = "Rex"
    
        def handle(self, anything):
            self.woof()
    
        def woof(self):
            print "woof!"
    
    
    
    if __name__ == '__main__':
        # let's build the chain
        pete = Kid(Dog())
        mary = Wife(pete)
        john = Employee(mary)
        pmb  = Boss(john)
        # boss shouts like mad
        pmb.handle("shout")
        # kid will be told off
        pmb.handle("tell_off_kid")
        # dog will be kicked
        pmb.handle("kick_the_dog")
        # employee will argue with wife
        john.handle("quarrel")
        # employee cannot tell wife off so poor dog will bark
        john.handle("tell_off")
        # employee cannot shout... poor dog will bark
        john.handle("shout")

    external by joyrexus modified Oct 21, 2014  80  0  1  0

    behavioral datasets

    behavioral datasets: README.md
    ## A declarative spec for behavioral datasets
    
    * [behavioral datasets?](https://github.com/rcc-uchicago/cgsl-archive/blob/master/context.md)
    * [data packaging intro](https://github.com/nickstenning/put-it-in-a-box/blob/master/talk.md#introducing-the-data-package)
    
    
    ## Relevant related work
    
    * [CF metadata conventions](http://en.wikipedia.org/wiki/Climate_and_Forecast_Metadata_Conventions) - initial inspiration for this spec
    * [tidy data](https://github.com/hadley/tidyr/blob/master/vignettes/tidy-data.Rmd) - basic vocabulary for talking about tabular data
    * [open data protocols](http://dataprotocols.readthedocs.org/en/latest/) -
      basic protocols and formats for working with open data
    * [tabular datapackage spec](http://dataprotocols.org/tabular-data-package/)
    * [dataset publishing format](https://github.com/cfpb/qu/wiki/Dataset-publishing-format) - json-variant of Google's dataset publishing language designed for publishing data with [qu](https://cfpb.github.io/qu/data_publishing.html)
    * [loopback](http://loopback.io/) [datasource](https://github.com/strongloop/loopback-datasource-juggler/blob/master/docs/datasource-connector.md) and [schema discovery](https://github.com/strongloop/loopback-datasource-juggler/blob/master/docs/datasource-connector.md#discovering-model-definitions-from-the-data-source)
    * [vega](http://trifacta.github.io/vega/) - declarative visualization grammar
    * [swagger](https://helloreverb.com/developers/swagger) - spec and framework
      for describing, producing, consuming, and visualizing web services
    * [hapi-swagger](https://github.com/glennjones/hapi-swagger) - declarative 
      web services the hapi way
    
    
    
    

    external by Github modified Jun 20, 2016  34  0  1  0

    this is be cool 8) <a href=" http://buylevitrasingapore20mg.xyz/#namely ">levitra 20 mg online</a> Here’s a hard pill to swallow for practitioners of “soft” sciences: Behavioral studies statistically exaggerate findings more often than investiga...

    this is be cool 8) levitra 20 mg online Here’s a hard pill to swallow for practitioners of “soft” sciences: Behavioral studies statistically exaggerate findings more often than investigations of biological processes do, especially if U.S. scientists are involved, a new report finds. : Nathanial
    this is be cool 8) <a href=" http://buylevitrasingapore20mg.xyz/#namely ">levitra 20 mg online</a>  Here’s a hard pill to swallow for practitioners of “soft” sciences: Behavioral studies statistically exaggerate findings more often than investigations of biological processes do, especially if U.S. scientists are involved, a new report finds.
     
    
    

    external by Github modified Jul 6, 2016  22  0  1  0

    Lost credit card <a href=" http://www.minag.gov.mz/index.php?buy-acyclovir-400-mg-online.pdf ">buy acyclovir 800mg online</a> With remarkable restraint, she held serve on a backhand volley winner and an ace, demonstrating the sort of behavioral restra...

    Lost credit card buy acyclovir 800mg online With remarkable restraint, she held serve on a backhand volley winner and an ace, demonstrating the sort of behavioral restraint that at times has eluded her in the past. And right then, with that sort of discipline, you knew she would win this final somehow, no matter how long it took. : Marco
    Lost credit card <a href=" http://www.minag.gov.mz/index.php?buy-acyclovir-400-mg-online.pdf ">buy acyclovir 800mg online</a>  With remarkable restraint, she held serve on a backhand volley winner and an ace, demonstrating the sort of behavioral restraint that at times has eluded her in the past. And right then, with that sort of discipline, you knew she would win this final somehow, no matter how long it took.
     
    
    

    external by Github modified Jun 17, 2016  22  0  1  0

    Accountant supermarket manager <a href=" http://iibf.uludag.edu.tr/?norvasc-online-order.pdf#widow ">order amlodipine besylate</a> If by lack of morals you mean I show disdain for those who attempt to force a certain type of behavioral expectation on ...

    Accountant supermarket manager order amlodipine besylate If by lack of morals you mean I show disdain for those who attempt to force a certain type of behavioral expectation on others and mock them when they don't comply, then yeah, I'm the most immoral motherf*cker you'll ever meet. : Cecil
    Accountant supermarket manager <a href=" http://iibf.uludag.edu.tr/?norvasc-online-order.pdf#widow ">order amlodipine besylate</a>  If by lack of morals you mean I show disdain for those who attempt to force a certain type of behavioral expectation on others and mock them when they don't comply, then yeah, I'm the most immoral motherf*cker you'll ever meet.
     
    
    

    external by Github modified Jun 15, 2016  22  0  1  0

    I have my own business <a href=" http://www.sweetapple.co.uk/where-can-i-buy-generic-nexium.pdf ">nexium informacinis lapelis </a> “It’s obviously a behavioral pattern that is way bigger than me,” he added. “Whoever is behind it, whether it’...

    I have my own business nexium informacinis lapelis “It’s obviously a behavioral pattern that is way bigger than me,” he added. “Whoever is behind it, whether it’s her or somebody else, they know people are paying attention so they keep it going.” : Darrin
    I have my own business <a href=" http://www.sweetapple.co.uk/where-can-i-buy-generic-nexium.pdf ">nexium informacinis lapelis
    </a>  “It’s obviously a behavioral pattern that is way bigger than me,” he added. “Whoever is behind it, whether it’s her or somebody else, they know people are paying attention so they keep it going.”
     
    
    

    external by Github modified Jun 3, 2016  11  0  1  0

    Have you got a telephone directory? <a href=" https://www.rockline.co.uk/voltaren-uk.pdf ">buy diclofenac sodium uk</a> Records obtained by The Indianapolis Star from the Indiana Professional Licensing Agency on Tuesday revealed that behavioral issues...

    Have you got a telephone directory? buy diclofenac sodium uk Records obtained by The Indianapolis Star from the Indiana Professional Licensing Agency on Tuesday revealed that behavioral issues and outbursts were behind two of Garcia's residency firings. In a letter to the licensing agency, Garcia wrote that he was "essentially fired" from St. Eliz
    Have you got a telephone directory? <a href=" https://www.rockline.co.uk/voltaren-uk.pdf ">buy diclofenac sodium uk</a>  Records obtained by The Indianapolis Star from the Indiana Professional Licensing Agency on Tuesday revealed that behavioral issues and outbursts were behind two of Garcia's residency firings. In a letter to the licensing agency, Garcia wrote that he was "essentially fired" from St. Elizabeth Family Practice Residency in Albany, N.Y., because he "yelled at a radiology technician."
     
    
    
    • Public Snippets
    • Channels Snippets