Esempio n. 1
0
    def init():

        commands = {
            'product.add': {'handler': Product.productAddCmd, 'args':2, 'help':'productAdd sku stock'},
            'product.info': {'handler': Product.productInfoCmd, 'args':1, 'help':'productInfo sku'},
            'reservation.add': {'handler': Product.reservationAddCmd, 'args':3, 'help':'reservationAdd client_id sku qty'},
            'reservation.del': {'handler': Product.reservationDelCmd, 'args':3, 'help':'reservationDel client_id sku qty'},
            'reservation.set': {'handler': Product.reservationSetCmd, 'args':3, 'help':'reservationSet client_id sku qty'},
            'stock.set': {'handler': Product.stockSetCmd, 'args':2, 'help':'stockSet sku stock'},
            'stock.dec': {'handler': Product.stockDecCmd, 'args':2, 'help':'stockDec sku qty'},
            'stock.get': {'handler': Product.stockGetCmd, 'args':1, 'help':'stockGet sku'},
            'product.total': {'handler': Product.totalCmd, 'args':0, 'help':'status'}
        }


        for c in commands:
            Command.register(
                commands[c]['handler'], 
                c, 
                commands[c]['args'], 
                commands[c]['help']
            )

        Event.register('db.save', Product.saveDb)
        Event.register('db.load', Product.loadDb)
Esempio n. 2
0
    def __init__(self, url, app_key, app_secret, group_name='default', query_message_interval=50, heartbeat_interval=30,
                 sdk_version='top-sdk-java-201403304', *args, **kwargs):
        super(TmcClient, self).__init__(url, *args, **kwargs)
        Event.__init__(self)

        self.on('on_init', lambda: logger.info('WebSocket Start Connect: %[email protected]%s' % (url, group_name)))

        assert isinstance(url, (str, unicode)) and len(url) > 0
        assert isinstance(app_key, (str, unicode)) and len(app_key) > 0
        assert isinstance(app_secret, (str, unicode)) and len(app_secret) > 0
        assert isinstance(group_name, (str, unicode)) and len(group_name) > 0
        assert isinstance(query_message_interval, int) and 0 < query_message_interval < 60
        assert isinstance(heartbeat_interval, int) and 0 < heartbeat_interval < 60

        self.sdk_version = sdk_version
        self.url = url
        self.app_secret = app_secret
        self.app_key = app_key
        self.group_name = group_name
        self.query_message_interval = query_message_interval
        self.heartbeat_interval = heartbeat_interval

        self.token = None

        self.fire('on_init')
        self.on('on_handshake_success', self._start_query_loop)
        self.on('on_confirm_message', self._on_confirm_message)
 def test_a_listener_is_notified_when_an_event_is_raised(self):
     """"""
     listener = Mock()
     event = Event()
     event.connect(listener)
     event.fire()  
     self.assertTrue(listener.called)
Esempio n. 4
0
File: tell.py Progetto: hlmtre/pybot
  def post_init(self):
    """
    Because of the way this module works we have to make sure to set our
    event like we normally would with __.tell__, but we cannot define our
    event with "^\.tell" like we normally would as it will only look for that
    line to trigger the event and the user being told will never receive his message
    since the bot is only looking for .tell and not the user in the PRIVMSG

    We will set the .tell trigger in our handle function "if event.msg.startswith(".tell"):"
    and set define to PRIVMSG so it searches all lines from users. While simultaneously looking
    for the .tell trigger from the user.
    
    This is because we actually need 2 things for this module to work. 

    1.) The user needs to be able to leave a message for someone else using ".tell someuser <Insert message here>" 
    
    2.) The user who the .tell message is directed towards will be determined by the PRIVMSG definition.
        This is determined in the "else" block that searches every line not starting with .tell.
        If the user matches the stored user from the previous tell trigger, the event will be triggered and pybot will spit out text into
        the proper channel every time the intended user says something in chat until the buffer is out of .tell events.
    """

    tell = Event("__.tell__")
    tell.define("PRIVMSG")
    tell.subscribe(self)

    # register ourself to our new custom event
    self.bot.register_event(tell, self)
Esempio n. 5
0
    def join(self):
        try:
            stdout, stderr, returncode = SubProcessTask.join(self)

            event = Event()
            event.service = self.name
            event.ttl = self.ttl * self.ttl_multiplier
            event.host = self.host
            event.tags = self.tags
            event.attributes = self.attributes

            output, attributes = self.parse_nagios_output(stdout)
            event.description = "Note: %s\nCommand: %s\nOutput: %s\n" % (self.note, self.raw_command, output)

            if returncode in self.exitcodes:
                event.state = self.exitcodes[returncode]
            else:
                event.state = 'unknown'

            if attributes:
                if 'metric' in self.config and self.config['metric'] in attributes:
                    metric_key = self.config['metric']
                else:
                    metric_key = attributes.keys()[0]

                event.attributes.update(attributes)
                event.metric = float(NUMERIC_REGEX.match(attributes[metric_key]).group(1))

            self.events.append(event)
        except Exception as e:
            log.error("Exception joining task '%s':\n%s" % (self.name, str(e)))
Esempio n. 6
0
 def post_init(self):
   kanbo = Event("__.custom__")
   kanbo.define(msg_definition="^\.kanbo")
   kanbo.subscribe(self)
   self.help = ".kanbo (kanbo face)"
   self.bot.register_event(kanbo, self)
   self.messages = [u'( ͡° ͜ʖ ͡°)', u'( ͡0 ͜ʖ ͡0)', u'|╲/( ͡° ͡° ͜ʖ ͡° ͡°)/\╱\\', u'┬┴┬┴┤( ͡° ͜ʖ├┬┴┬┴']
Esempio n. 7
0
  def post_init(self):
    version_event = Event("__.version__")
    version_event.define(msg_definition="^\.version")
    version_event.subscribe(self)

    # register ourself to our new custom event
    self.bot.register_event(version_event, self)
Esempio n. 8
0
 def deploy_event(self, extend_eventtype=None, event=None, **kwargs):
     eventtype = self._importname if not extend_eventtype else self._importname + extend_eventtype
     if not event:
         event = Event(self, eventtype, **kwargs)
     else:
         event.eventtype = eventtype
     self._eventhandler.deploy_event(event)
Esempio n. 9
0
  def post_init(self):
    youtube = Event("__.youtubes__")
    youtube.define(msg_definition="youtube\.com[\S]+")
    youtube2 = Event("__.youtubeshort__")
    youtube2.define(msg_definition="(?<!=)youtu\.be[\S]+")
    youtube.subscribe(self)
    youtube2.subscribe(self)

    self.bot.register_event(youtube, self)
    self.bot.register_event(youtube2, self)

    self.bot.mem_store['youtube'] = OrderedDict()


    # for the new v3 google api >:(
    try: 
        from youtube_credentials import YoutubeCredentials as yc
    except ImportError:
        print "Warning: youtube module requires credentials in modules/youtube_credentials.py"
        class PhonyYc:
            api_key = "None"
        yc = PhonyYc()

    self.api_key = yc.api_key    
    self.api_url = "https://www.googleapis.com/youtube/v3/videos?id="
Esempio n. 10
0
def main():
    frame_duration = 1.0/60.0

    for level in LEVELS:
        load_level(level)

        while not Player.main.at_exit():
            frame_start_time = time.time()

            key = Drawable._window.checkKey()

            if key in KEYMAP:
                eval(KEYMAP[key])

            Event.update()

            if not Config.hidden_flag:
                if Gold.all_taken():
                    HiddenLadder.showAll()
                    Player.main.redraw()
                    for baddie in Baddie.baddies:
                        baddie.redraw()
                    Config.hidden_flag = True

            # baddies should probably move here

            frame_time = time.time() - frame_start_time
            if frame_time < frame_duration:
                time.sleep(frame_duration - frame_time)
        Drawable.won()
Esempio n. 11
0
File: world.py Progetto: bblack/pirc
class World:

  def __init__(self):
    self.connections = []
    self.connection_added = Event()
    self.channel_opened = Event()

  def get_connections(self):
    ret = []
    for c in self.connections:
      ret.append(c)
    return ret

  def remove_connection(self, connection):
    if connection.is_connected:
      raise "I don't think so, tim"
    self.connections.remove(connection)

  def new_connection(self):
    conn = Connection()
    self.connections.append(conn)

    conn.channel_opened += self.handle_channel_opened

    self.connection_added.fire(self, conn)
    return conn

  def shut_it_down(self):
    for c in self.connections:
      c.shut_it_down()

  def handle_channel_opened(self, channel):
    self.channel_opened.fire(self, channel)
Esempio n. 12
0
 def _start_sending(self):
     _logger.debug('%s, _start_sending', str(self))
     if self._close_ev is not None:
         return
     if not Event.isEventSet(self._wev):
         _logger.debug('%s, _start_sending::addEvent', str(self))
         Event.addEvent(self._wev)
Esempio n. 13
0
 def test_Event_SubscribeAndFireWithDupplicateKeyword_RaisesException(self):
     mockListener = mock.Mock()
     event = Event()
     event.subscribe(mockListener, kword1="value1")
 
     with self.assertRaises(DuplicateKeywordArgument):
         event.fire(kword1="value2")
Esempio n. 14
0
  def post_init(self):
    b_event = Event("__.bofh__")

    b_event.define(msg_definition="^\.bofh")
    b_event.subscribe(self)

    self.bot.register_event(b_event, self)
Esempio n. 15
0
 def notify(self, **attrs):
     e = Event()
     e.source = self
     for k, v in attrs.iteritems():
         setattr(e, k, v)
     for fn in self.callbacks:
         fn(e)
Esempio n. 16
0
    def __init__(self, bot, raw):
        Event.__init__(self, bot, raw)

        if not self.is_a(*UPDATE_EVENTS):
            self.channel = models.Channel(self.raw["channel"])
        else:
            self.channel = bot.get_channel(self.raw["channel"])
Esempio n. 17
0
 def get(self):
   self.response.headers['Content-Type'] = 'text/plain'
   asa_number_str = self.request.get('asa_number')
   if asa_number_str == '':
     self.response.out.write( "Missing asa_number" )
     self.response.set_status( 400 )
     return
   stroke_code_str = self.request.get('stroke_code')
   if stroke_code_str == '':
     # If there's no stroke code, then we assume that we want the entire swim history
     swimlist = SwimList.get( int(asa_number_str) )
     if swimlist is not None:
       self.response.out.write( str( swimlist ) )
   else:
     distance_str = self.request.get('distance')
     if distance_str == '':
       self.response.out.write( "Missing distance" )
       self.response.set_status( 400 )
       return
     asa_number = int(asa_number_str)
     stroke_code = int(stroke_code_str)
     distance = int(distance_str)
     
     swims = Swim.fetch_all( asa_number, Event.create( stroke_code, distance, "S" ) )
     swims.extend( Swim.fetch_all( asa_number, Event.create( stroke_code, distance, "L" ) ) )
     swims.extend( UnofficialSwim.fetch_all( asa_number, Event.create( stroke_code, distance, "S" ) ) )
     swims.extend( UnofficialSwim.fetch_all( asa_number, Event.create( stroke_code, distance, "L" ) ) )
     
     for swim in swims:
       self.response.out.write( str( swim ) + "\n" )
Esempio n. 18
0
def findTree():
    ei = EventInterface()
    ei.setDB('citybeat')
    ei.setCollection('candidate_event_25by25_merged')

    events = {}
    fid1 = open('labeled_data_cf/181_positive.txt', 'r')
    true_events = []

    for line in fid1:
        t = line.split(',')
        id = str(t[0])
        label = int(t[1])
        if label == 1:
            pass
        else:
            continue
        events[id] = label

    fid1.close()

    words = ['motor']
    for id, label in events.items():
        event = ei.getEventByID(id)
        e = Event(event)
        if e.containKeywords(words, 1):
            print id
Esempio n. 19
0
  def post_init(self):
    shortener = Event("__urls__")
    shortener.define(msg_definition = "https?://[\S]+") # What to look for to trigger event
    shortener.subscribe(self)

    # register ourself to our new custom event
    self.bot.register_event(shortener, self)
Esempio n. 20
0
 def _add_event(self, event, events):
   e = Event(event)
   if e.start_time().date() == date.today():
     if e.artists():
       events.append(e)
     else:
       print "no artists for for event:", e.name(), "url:", e.url()
Esempio n. 21
0
class Swim():
  def __init__(self, line):
    tokens = line.split( "|" )
    num_tokens = len( tokens )
    
    # Figure out what version data we have
    version = 0
    if tokens[0].startswith( "V" ):
      version = int( tokens[0][1:] )

    if version == 1:
      self.asa_number = int( tokens[1] )
      self.event = Event( int( tokens[2] ) )
      self.date = helpers.ParseDate_dmY( tokens[3] )
      self.meet = tokens[4]
      self.asa_swim_id = int( tokens[5] )
      # Splits are in tokens[6]
      self.is_licensed = True
      if tokens[7] == 'n':
        self.is_licensed = False
      self.race_time = float( tokens[8] )
      
      self.short_course_race_time = self.race_time
      if self.event.is_long_course():
        self.short_course_race_time = self.event.convert_time( self.race_time )
        
      #print( str( self.short_course_race_time ) )
    else:
      raise RuntimeError( "Unhandled swim version" )

  # Returns the asa number of the swimmer that this swim is for.
  def get_asa_swim_id(self):
    if self.asa_swim_id == -1:
      return None
    return self.asa_swim_id
Esempio n. 22
0
 def __init__(self, etype, bubbles=True, cancelable=False,
                 relatedObject=None, shiftKey=None, keyCode=0,
                     direction='none'):
     Event.__init__(self, etype, bubbles, cancelable)
     self.relatedObject = relatedObject
     self.keyCode = keyCode
     self.shiftKey = shiftKey
Esempio n. 23
0
	def test_dates(self):
		e = Event('Test Dates')
		e.addLog('My Date Event')
		L = []
		for i in range(100):
			L.append(i)
		e.save(True)
Esempio n. 24
0
def test_event():
    """Test Event class."""
    # Test __init__
    switch_state = [0, 0, 0]
    event = Event(switch_state, switch_state)
    assert_equals(event.new_switch_state, switch_state)
    assert_items_equal(event._effective_switch_vector, switch_state)

    # Test new_event and state_diff
    switch_state = [1, 0, 0]
    event = event.new_event(switch_state)
    assert_items_equal(event._effective_switch_vector, switch_state)
    assert_equals(event.state_diff(), 0)

    # Test _get_effective_switch_vector and state_diff
    switch_state = [0, 0, 0]
    event = event.new_event(switch_state)
    assert_items_equal(event._effective_switch_vector, [1, 0, 0])
    assert_equals(event.state_diff(), 0)

    # Test count_active and get_active_switch
    switch_state = [1, 0, 0]
    event = event.new_event(switch_state)
    switch_state = [1, 0, 1]
    event = event.new_event(switch_state)
    assert_equals(event.count_active(), 2)
    first = event.get_active_switch(1)
    assert_equals(first, 0)
    second = event.get_active_switch(2)
    assert_equals(second, 2)
Esempio n. 25
0
File: db.py Progetto: mflorin/ir
    def init(self):

        # config options
        self.config = {}

        self.loadConfig()
        
        self.running = False

        # initialize the event object used for sleeping
        self.event = threading.Event()

        if self.config['persistence'] and os.path.exists(self.config['file_name']):
            try:
                Logger.info('loading database from %s' % self.config['file_name'])
                self.load()
            except Exception as e:
                Logger.critical(str(e))

        self.setup()

        # register our 'save' commands
        Command.register(self.saveCmd, 'db.save', 0, 'db.save')
        
        # treat events
        Event.register('core.reload', self.reloadEvent)
        Event.register('core.shutdown', self.shutdownEvent)
Esempio n. 26
0
    def set_event(self, event_id, rank, score):
        event = Event(event_id)
        event.set_score(score).set_rank(rank)

        self.events[event_id] = event

        return self
def loadNextWeekData():
	
	# load modified 
	
	ei = EventInterface()
	ei.setDB('citybeat')
	ei.setCollection('next_week_candidate_event_25by25_merged')
	
	true_events = []
	false_events = []
	
	fid2 = open('labeled_data_cf/label_next_week.txt', 'r')
	
	for line in fid2:
		t = line.split(',')
		id = str(t[0])
		label = int(t[1])
		
		event = ei.getDocument({'_id':ObjectId(id)})
		event['label'] = label
		e = Event(event)
		if e.getActualValue() < 8 or event['label'] == 0:
#			print 'bad event ' + id
			continue
		if event['label'] == 1:
			true_events.append(event)
		else:
			false_events.append(event)
			
	fid2.close()
	return true_events, false_events
Esempio n. 28
0
 def convert_event(self, html_event):
     event = Event()
     event.id = self.extract_id(html_event)
     event.title = self.extract_title(html_event)
     event.date = self.extract_date(html_event)
     event.enrollment_date = self.extract_enrollment_date(html_event)
     return event
 def test_a_listener_is_passed_right_parameters(self):
     """"""
     listener = Mock()
     event = Event()
     event.connect(listener)
     event.fire(5, shape="square")
     listener.assert_called_with(5, shape="square")
Esempio n. 30
0
def GetCandidates( relay, stroke, swimmers ):
  candidates = []
  shortCourseEvent = Event.create( stroke, relay.distance, "S" )
  longCourseEvent = Event.create( stroke, relay.distance, "L" )
  
  for swimmer in swimmers:
    if swimmer.is_male == relay.is_male:
      age_on_day = helpers.CalcAge( swimmer.date_of_birth, relay.date )
      if (age_on_day >= relay.min_age) and (age_on_day <= relay.max_age):
        # Get this swimmer's PB
        scPbSwim = Swim.fetch_pb( swimmer, shortCourseEvent )
        lcPbSwim = Swim.fetch_pb( swimmer, longCourseEvent )
        pbRaceTime = None
        if scPbSwim is None:
          if lcPbSwim is not None:
            pbRaceTime = longCourseEvent.convertTime( lcPbSwim.race_time )
        else:
          pbRaceTime = scPbSwim.race_time
          #logging.info( swimmer.full_name() + str( scPbSwim.race_time ) + "  " + str( pbRaceTime )   )
          if lcPbSwim is not None:
            lcConvertedRaceTime = longCourseEvent.convertTime( lcPbSwim.race_time )
            if lcConvertedRaceTime < pbRaceTime:
              pbRaceTime = lcConvertedRaceTime
          
        #logging.info( swimmer.full_name() + " Age: " + str( age_on_day ) )
        if pbRaceTime is not None:
          #logging.info( swimmer.full_name() + " PB: " + str( age_on_day ) )
          swimmer.relay_time = pbRaceTime
          swimmer.age_on_day = age_on_day
          candidates.append( swimmer )

  candidates.sort( key = lambda swimmer: swimmer.relay_time )
  return candidates;