def finish_request(self, request, client_address):
   #Sets a lock object for the server. Updating groups/data in another thread will lock the server from responding to a request
   lock = Events.getLockObject()
   if lock:
     print("Acquiring lock for message processing") #Honestly I don't want to log this, but if I come look at the screen I would want to see this
     lock.acquire()
     print("Acquired lock")
     
   try:
     super().finish_request(request, client_address) #Actually processes the message
   except ConnectionAbortedError:
     log.net.debug("Of note: Connection Aborted")
   
   if not Events.NonBlockingShutdownLock.acquire(blocking = False):
     self.exitValue = False
     log.info.debug("Request indicates shutdown. Shutting down server")
     Events.quickDaemonThread(self.shutdown) #Because shutdown does a "wait" for the current request to end and causes deadlock
   Events.NonBlockingShutdownLock.release() #Release once checked
   
   if not Events.NonBlockingRestartLock.acquire(blocking = False):
     self.exitValue = True
     log.info.debug("Request indicates restart. Shutting down server")
     Events.quickDaemonThread(self.shutdown) #Because shutdown does a "wait" for the current request to end and causes deadlock
   Events.NonBlockingRestartLock.release() #Release once checked
   
   
   if lock:
     lock.release()
示例#2
0
 def send_comment(self, userid, prefix, comment):
   self.lock.acquire()  # only send one comment at a time (since we're hitting multiple rootids)
   try:
     sent_to = {}
     for sessionid, rootid in self.sessions.items():
       # get the session; if the session has expired, remove and move on
       session = Directory.get_session(sessionid)
       if not session:
         del self.sessions[sessionid]
         continue
         
       # if we've already sent to this rootid, skip and move on
       if sent_to.has_key(rootid):
         continue
       sent_to[rootid] = rootid
       
       # find the actual parent of this comment
       root = datagate.get_item(rootid)
       if not root:
         print "RatingProxy couldn't find rootid:", rootid
         continue
       parentid = self.find_parent(root, prefix) or rootid
       
       # create and send the event to the system (goes to all interested users)
       # I'm using a blank windowid so it goes to anyone looking at this rootid
       item = datagate.create_item(parentid=parentid, creatorid=userid)
       item.text = comment
       item.save()
       event = BaseView.views['rating']._create_event(item, 'processAdd')
       Events.send_event(rootid, event)
   
   finally:
     self.lock.release()
 def handle_error(self, request, client_address):
   Events.getLockObject().release() #Release the lock we have on message processing
   
   stringBuffer = io.StringIO()
   traceback.print_exc(file = stringBuffer)
   stringBuffer.seek(0) #Reset to start of message
   errorMessage = stringBuffer.read().replace("\n","\r\n")
   log.error("==== ERROR OCCURRED IN SERVER. PRINTING ERROR ====")
   log.error(errorMessage) #Output the message to logging
   
   if SEND_ERRORS_OVER_GROUPME:
     sendGroup = makeNamedGroup(99, "23222092", ("27094908", Files.getTokenList()[0]))
     sendGroup.setBot("3da109b71b8c3363c4b87a7e67")
     sendGroup.save()
     
     try:
       if sendGroup:
         log.network.statePush(False)
         success = sendGroup.handler.write("\nMESSAGE FOR YOU SIR:\n" + errorMessage)
         log.network.statePop()
         if success:
           log.error("Successful error report sent")
         else:
           log.error("Failed to send error report")
         
     except Exception as e: #I don't care about any errors here. jk
       raise e #Jk I do
def init():
    InitQuit.init()

    G.BGD = G.SCREEN.copy()
    pg.display.flip()

    Events.register(pg.QUIT, lambda e: InitQuit.quit())
示例#5
0
    def __init__(self):
        """Constructor"""
        self.debug = True
        super(DeeBot, self).__init__("UnoBot")

        # Config
        self.config = {}
        self.config["server"] = os.environ['IRC_SERVER']
        self.config["channel"] = os.environ['IRC_CHANNEL']
        self.config["admins"] = [
            x.strip() for x in os.environ['IRC_ADMINS'].split(',')
        ]
        self.config["plugins"] = ["Uno"]

        # Add events.
        self.addEvent("connected", Events.ConnectedEvent())
        self.addEvent("message", Events.MessageEvent())

        # Plugin modules are loaded into the plugin dictionary, with the key
        # being the name of the module.
        self.plugins = {}

        # Load plugins.
        for plugin in self.config["plugins"]:
            self.loadPlugin(plugin)

        # Check PID Files
        pid = str(os.getpid())
        pidfile = "UnoBot.pid"

        if os.path.isfile(pidfile):
            os.remove(pidfile)
            file(pidfile, 'w').write(pid)
        else:
            file(pidfile, 'w').write(pid)
示例#6
0
def event_loop():
    while True:
        for event in pygame.event.get():
            if event.type == 5:
                Events.mouse_click(pygame.mouse.get_pos())
            if event.type == 6:
                Events.mouse_release()
示例#7
0
文件: task.py 项目: kamilsudol/PITE
 def __init__(self):
     self.events = [
         Events.NailOnTheRoad(),
         Events.RockUnderWheels(),
         Events.DeadEnd(),
         Events.Nothing()
     ]
示例#8
0
 def finish_request(self, request, client_address):
   #Sets a lock object for the server. Updating groups/data in another thread will lock the server from responding to a request
   lock = Events.getLockObject()
   if lock:
     print("Acquiring lock for message processing") #Honestly I don't want to log this, but if I come look at the screen I would want to see this
     lock.acquire()
     print("Acquired lock")
     
   try:
     super().finish_request(request, client_address) #Actually processes the message
   except ConnectionAbortedError:
     log.net.debug("Of note: Connection Aborted")
   
   if not Events.NonBlockingShutdownLock.acquire(blocking = False):
     self.exitValue = False
     log.info.debug("Request indicates shutdown. Shutting down server")
     Events.quickDaemonThread(self.shutdown) #Because shutdown does a "wait" for the current request to end and causes deadlock
   Events.NonBlockingShutdownLock.release() #Release once checked
   
   if not Events.NonBlockingRestartLock.acquire(blocking = False):
     self.exitValue = True
     log.info.debug("Request indicates restart. Shutting down server")
     Events.quickDaemonThread(self.shutdown) #Because shutdown does a "wait" for the current request to end and causes deadlock
   Events.NonBlockingRestartLock.release() #Release once checked
   
   
   if lock:
     lock.release()
示例#9
0
    def submit_job(self, debug_on=False):
        #submits job to batch_mgr, if there is one present
        try:
            if self.my_vals["batch_mgr"] == "SLURM":
                if self.my_vals["mpi_job"]:
                    # "sam_run" calls mpi_run.py if it is an mpi job
                    cmd = "srun -N %d -b sam_run" % self.my_vals["num_nodes"]
                else:
                    #grab nodes, run, and grab stderr to get the jobid
                    cmd = "srun -N %d -b %s" % (self.my_vals["num_nodes"], \
                           self.my_vals["executable"])   #assume it has ./ if needed

                #using subprocess
                p1 = sp.Popen(cmd, shell=True, stderr=sp.PIPE)
                s = p1.stderr.read()
                g = s.split()
                self.my_vals["jobid"] = g[2]
                self.my_vals["status"] = g[3]

            elif self.my_vals["batch_mgr"] == "PBS":
                scriptfile = open("scriptfile", "w")
                scriptfile.write("#!/bin/tcsh\n")
                scriptfile.write("#PBS -l ncpus=" +
                                 str(self.my_vals["num_nodes"]) + "\n")
                scriptfile.write("#PBS -l walltime=00:05:00\n")
                scriptfile.write("#PBS -l mem=50mb\n")
                scriptfile.write("#PBS -r n\n")
                scriptfile.write("#PBS -N FSPjobname\n")
                scriptfile.write("#PBS -q sgi\n")
                scriptfile.write("#PBS -V\n")
                scriptfile.write("cd " + os.getcwd() + "\n")
                scriptfile.write(self.my_vals["executable"] + "\n")
                scriptfile.close()
                #cmd = "qsub -l nodes=" + self.my_vals["num_nodes"] + " scriptfile"
                cmd = "qsub scriptfile"
                os.system("pwd")
                p1 = sp.Popen(cmd, shell=True, stderr=sp.PIPE, stdout=sp.PIPE)
                s = p1.stdout.read()
                g = s.split(".")
                self.my_vals["jobid"] = g[0]

            else:
                #just run
                # need to get pid... storing it in jobid should be fine
                cmd = self.my_vals["executable"]

                #new version using subprocess
                #print "starting the script"
                p1 = sp.Popen(cmd, shell=True)
                #print "done running script"
                self.my_vals["jobid"] = str(p1.pid)

            if debug_on:
                print cmd
                print "my jobid is: %s" % self.my_vals["jobid"]

            message = "job %s started" % self.my_vals["jobid"]
            Events.publish_event(message, topic='FSP_job')
        except Exception, ex:
            print "submit_job failed with exception %s" % ex
示例#10
0
 def handle_error(self, request, client_address):
   Events.getLockObject().release() #Release the lock we have on message processing
   
   stringBuffer = io.StringIO()
   traceback.print_exc(file = stringBuffer)
   stringBuffer.seek(0) #Reset to start of message
   errorMessage = stringBuffer.read().replace("\n","\r\n")
   log.error("==== ERROR OCCURRED IN SERVER. PRINTING ERROR ====")
   log.error(errorMessage) #Output the message to logging
   
   sendGroup = makeNamedGroup(99, "23222092", ("27094908", Files.getTokenList()[0]))
   sendGroup.setBot("3da109b71b8c3363c4b87a7e67")
   sendGroup.save()
   
   try:
     if SEND_ERRORS_OVER_GROUPME and sendGroup:
       log.network.statePush(False)
       success = sendGroup.handler.write("\nMESSAGE FOR YOU SIR:\n" + errorMessage)
       log.network.statePop()
       if success:
         log.error("Successful error report sent")
       else:
         log.error("Failed to send error report")
         
   except Exception as e: #I don't care about any errors here. jk
     raise e #Jk I do
示例#11
0
def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    pw = "$5$rounds=535000$TbjfFguG9yEaDQWS$6joRKlWuiXMBP8dTYoMQ5woWDepmcfcGWBKZtX9vvT0"
                        #TODO Nergy hashen
    passed = username == 'Nergy' and sha256_crypt.verify(password, pw)
    if not passed:
        date = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')

        payload = Events.loginFailedEvent(date, password)  # maak loginSuccesEvent
        message = json.dumps(payload.__dict__)  # naar json
        channel.basic_publish(exchange='',
                              routing_key='task_queue',
                              body=message,
                              properties=pika.BasicProperties(
                                  delivery_mode=2,  # make message persistent
                              ))



        payload = Events.loginSuccesEvent(date)  # maak loginSuccesEvent
        message = json.dumps(payload.__dict__)  # naar json
        channel.basic_publish(exchange='',
                              routing_key='task_queue',
                              body=message,
                              properties=pika.BasicProperties(
                                  delivery_mode=2,  # make message persistent
                              ))

    return passed
示例#12
0
def update():
    Events.update()

    global bgd
    Drawing.update(G.SCREEN)
    pg.display.flip()
    Drawing.clear(G.SCREEN, bgd)
示例#13
0
def update():
    Events.update()
    PlayerMoveSystem.update()

    DrawSystem.update(G.SCREEN)
    pg.display.flip()
    DrawSystem.clear(G.SCREEN, G.BGD)

    G.CLOCK.tick(60)
示例#14
0
    def request(self, json_info):

        print("[API] Message Request Received", json_info['text'])

        separate_data = Data(json_info['text'])

        evt = Events(separate_data)
        result = evt.get_response()

        self.response(json_info, result)
示例#15
0
    def mouseReleaseEvent(self, event):
        names = []
        for item in self.selectedItems():
            nodeName = item.getName()
            names.append(nodeName)

        Events.queueEvent('node_select', names=names)
        Events.processEvents()

        super(NodegraphScene, self).mouseReleaseEvent(event)
示例#16
0
def init(PC, RC, VC):
	Events.register(pg.KEYDOWN, moveHandler)
	
	global velUpdate
	velUpdate = VC.update().where(VC.c.RectID.in_(
		sqa.select(
			[RC.c.RectID]
		).select_from(
			RC.join(PC, RC.c.EntID == PC.c.EntID))
		)
	)
示例#17
0
def stop():
    '''
    stops the graphic thread
    '''
    if g.multithreading:
        g.running = False
        GraphicThread.join()
        Events.eraseEvents()
    while True:
        Events.updateEvents()
        g.clock.tick(g.deltaTime)
示例#18
0
def flipOnce():
    Events.updateEvents()
    g.window.fill(g.world.color)
    world = g.world
    world.acquire()
    for gobj in world.world:
        gobj.acquire()
        gobj.draw(g.window)
        gobj.release()
    world.release()
    g.pygame.display.flip()
示例#19
0
    def __init__(self):
        #gets the info from the config file
        self.parse_config()

        #set the path to Jpype
        sys.path.append(self.my_vals["Jpype"])

        try:
            Events.set_default_broker(self.my_vals["event_channel"])
        except Exception, ex:
            print "events not working: %s" % ex
def update():
    global elapsed

    Events.update()
    VelocitySystem.update(elapsed)

    DrawSystem.update(G.SCREEN)
    pg.display.flip()
    DrawSystem.clear(G.SCREEN, G.BGD)

    elapsed = G.CLOCK.tick(60)
示例#21
0
def flipOnce():
    Events.updateEvents()
    g.window.fill(g.world.color)
    world = g.world
    world.acquire()
    for gobj in world.world:
        gobj.acquire()
        gobj.draw(g.window)
        gobj.release()
    world.release()
    g.pygame.display.flip()
示例#22
0
    def __init__(self, player, map_cell_to_event_object=None):
        self.player = player
        self.map_array = []

        if not map_cell_to_event_object:
            self.map_cell_to_event_object = {
                ' ': Events.Blank(self.player),
                'I': Events.Inn(self.player),
                'J': Events.JackCH2(self.player),
                'E': Events.MazeEnd(self.player)
            }
        else:
            self.map_cell_to_event_object = map_cell_to_event_object
示例#23
0
def stop():
    '''
    stops the graphic thread
    '''
    g.running = False
    if g.multithreading:
        GraphicThread.join()
        Events.eraseEvents()
    else:
        flipOnce()
    while True:
        Events.updateEvents()
        g.clock.tick(g.deltaTime)
示例#24
0
    def run(self):
        Util.clear()
        Util.slow_print(Cfg.get('RIDDLE') + '\n')
        Util.clear_with_enter()

        for l in Cfg.getLines('RIDDLE_ON_HILL_INTRO'):
            Util.slow_print(l)

        Util.clear_with_enter()

        Util.slow_print(Cfg.get('SND_RIDDLE'))

        answers = Cfg.getLines('SND_RIDDLE_ANSW')
        user_answ = input('\n' + Cfg.get('WHAT_IS_ANSW') + ' ')

        if user_answ.strip().upper() in answers:
            Util.slow_print('\n' + Cfg.get('RIGHT_ANSW_ON_HILL'))
            Util.clear_with_enter()
            next_event = Events.MonsterFight(self.player,
                                Monster.get_slime,
                                allow_to_flee=False,
                                money_received=20)
            next_event.run()
            # self.player.proceed_to_next_chapter = True
        else:
            Util.slow_print(Cfg.get('WRONG_ANSW_ON_HILL'))
            Util.clear_with_enter()
示例#25
0
def createNode(type, name=None, deferred=True, addRegisteredPorts=True):
    if type not in __registeredNodes:
        logger.warning('Could not find node %s in registry' % type)
        return

    node = __registeredNodes[type]['class']()
    if not name: name = type
    node.setName(name)
    __nodes[name] = node
    Events.queueEvent('node_create', node=node)

    if addRegisteredPorts: node.addRegisteredPorts()
    node.addRegisteredParameters()

    if not deferred: Events.processEvents()
    return node
示例#26
0
    def on_receive(self, msg):
        """
		Implements the receiving of a message
		"""
        #Simulate message loss while receiving
        if random.random() < config.drop:
            return

        self.sim.rcv_messages += 1  #for simulation statistics

        # If I already received this message (RECOVERED state) I don't do anything
        if self.state == State.RECOVERED:
            return

        if self.state == State.VULNERABLE:
            # If it's the first time that I receive the message, then transition to state infected and update simulation stats
            self.sim.t_last_infected = self.sim.t
            self.sim.t_infected[self.sim.t] += 1
            self.sim.infected_counter += 1
            self.state = State.INFECTED

            # Add waiting phase event
            waiting_time = self.getWaitingTime(msg.last_emit)
            event = Events.WaitingEvent(self, waiting_time)
            self.sim.schedule_event(event)

        # Store the received message
        self.messages.append(msg)
示例#27
0
 def __init__(self):
     BaseEntity.__init__(self)
     # 先初始化消息管理器
     self.event_mgr = Events.EventMgr()
     self.table_mgr = TableManager(self)
     self.registerEvent()
     self.dismiss_apply = {}
示例#28
0
 def __init__(self, type_map, name):
     pygame.init()
     if type_map < 3:
         self.empty_map(type_map)
     else:
         self.load_file(name)
     self.type = 0
     self.resources = Resources()
     self.graphical_logic = Graphical_logic()
     self.w_event = Events()
     self.minimap_x = 0
     self.minimap_y = 0
     self.count = 0
     self.days = 0
     self.cell_type = 0
     self.fraction = 0
     self.stage = 0
     self.save_load_name = ''
示例#29
0
 def __init__(self, width, height):
     super().__init__(width, height)
     self.font = pygame.font.SysFont("arial", 64)
     self.optionSelect = 0
     self.Keys = Events.KeyBinder()
     self.options = ['Rebind Controls', 'View Controls', 'Main Menu']
     #May need this if I don't want to create another scene as I can just change what is written to the screen
     self.temp = self.options 
     self.toRender = self.changeRender(self.options)
     self.rebinding = False
示例#30
0
 def __init__(self,map_name):
     pygame.init()
     self.core = Core()
     self.mode = Event_Handler()
     self.file = 'ingame_temp'#заміна self.file в Core.py
     #self.map_type - треба замінити в Core.py
     #self.x_coord_start self.x_coord_end - замінити в Core.py
     self.battle = Battle('1')
     self.resources = Resources()
     self.graphical_logic = Graphical_logic()
     self.w_event = Events()
     self.minimap_x =0
     self.minimap_y =0
     self.count = 0
     self.days = 0
     self.fraction = 1 # першими ходять червоні
     self.map_name = map_name
     self.stage = 0
     self.save_load_name = ''
     self.fractions = [[1, 1, 0, 0, 3, 1],[2, 1, 0, 0, 0, 0]]
示例#31
0
    def __init__(self, parent):
        super(ParameterPanel, self).__init__(parent)
        self.setMinimumSize(250, 250)
        self.setMaximumSize(500, 500)

        QtGui.QVBoxLayout(self)
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().setSpacing(0)

        # Add navigation arrows
        hbox = QtGui.QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.setSpacing(0)

        self.layout().addLayout(hbox, 0)

        self.__panelScrollArea = PanelScrollArea(self)
        self.layout().addWidget(self.__panelScrollArea, 10)

        Events.registerHandler(self.__selectNode, 'node_select')
示例#32
0
 def SetupWindow(self, window):
     '''
     Sets up the window in the level
     '''
     # Prevent weird repeat setups
     if not self._setup:
         self._userInput = Events.UserInputHandler(self)
         window.push_handlers(self._userInput)
         self._window = window
         glDisable(GL_DEPTH_TEST)
         self.Setup()
         self._setup = True
 def run_prod(self):
     while True:
         # poll for actuation of button every 10th of a second
         # note that shutdown button is active-low
         if not GPIO.input(self.shutdown_pin):
             # shutdown pressed, debounce once for simplicity
             time.sleep(.1)
             if not GPIO.input(self.shutdown_pin):
                 # shutdown pressed for at least .1s, post the event
                 # note that this is very poor debouncing
                 self.eventQueue.put(Events.ShutdownEvent())
         time.sleep(.1)
示例#34
0
    def getRunningInstanceList(self):
        dic_resources={}
        pName="admin"
        eName="compute.instance.create.end"
        instanceList=nova.servers.list(search_opts={'all_tenants': 1})
        obj1=Events()
        temp=''
        for i in range(0,len(instanceList),1):
            try:
                temp=obj1.getEventTime(pName,instanceList[i].name,eName)
                values = [instanceList[i].id,instanceList[i].name,instanceList[i].image['id'],instanceList[i].status,temp]
                # values=[]

                dic_resources[instanceList[i].id]=values
            except:

                values = [instanceList[i].id,instanceList[i].name,"Not Available",instanceList[i].status,"Not Available"]
                # values=[]
                dic_resources[instanceList[i].id]=values

        return dic_resources
    def run_prod(self):
        while True:
            # scan for devices
            devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
            # find card reader device
            if (len(devices) > 0):
                print("Input event devices available (" + str(len(devices)) +
                      "). Devices are: ")
                # init card reader discovery bool
                discovered_card_reader = False
                # display input devices
                for i, device in enumerate(devices):
                    print("    " + str(i) + ") (" + device.fn + ", " +
                          device.name + ", " + device.phys + ")")
                    # search for card reader by its name, "HID c216:0180"
                    if str(device.name) == "HID c216:0180":
                        print("Discovered card reader..listening for events \
                                until test harness is closed.")
                        # rename device for readability
                        card_reader = device
                        # indefinitely listen for events
                        byte_count = 0
                        student_id = 0
                        for event in card_reader.read_loop():
                            if event.type == evdev.ecodes.EV_KEY:
                                event_key_state = evdev.util.categorize(
                                    event).keystate
                                keycode_str = evdev.util.categorize(
                                    event).keycode
                                if byte_count < 7:
                                    if event_key_state == KEY_STATE_DOWN and keycode_str in VALID_KEY_HASH:
                                        keycode_int = VALID_KEY_HASH[
                                            keycode_str]
                                        exponent = int(
                                            math.pow(10, (6 - byte_count)))
                                        student_id += int(
                                            keycode_int) * exponent
                                        byte_count += 1
                                        # end of student id
                                        if byte_count == 7:
                                            self.eventQueue.put(
                                                Events.CardReadEvent(
                                                    {"id": student_id}))
                                            student_id = 0
                                if event_key_state == KEY_STATE_UP and keycode_str == "KEY_ENTER":
                                    # last byte in card, so reset byte count
                                    byte_count = 0

                # error out if unable to find card reader
                if not discovered_card_reader:
                    print("ERROR: Unable to find the card reader")
                    time.sleep(1)  # delay until next attempt to connect
示例#36
0
def __init__():  # Intitalizes program
    global clock
    clock = pygame.time.Clock()
    clock.tick(60)  # Controls frame rate

    global eventHandler
    eventHandler = Events()  # Listens for mouse and keyboard clicks

    global display
    display = Display(eventHandler)  # Initializes the Display

    while True:
        Game()
示例#37
0
 def __init__(self,type_map,name):
     pygame.init()
     if type_map < 3:
         self.empty_map(type_map)
     else:
         self.load_file(name)
     self.type = 0
     self.resources = Resources()
     self.graphical_logic = Graphical_logic()
     self.w_event = Events()
     self.minimap_x =0
     self.minimap_y =0
     self.count = 0
     self.days = 0
     self.cell_type = 0
     self.fraction = 0 
     self.stage = 0
     self.save_load_name = ''
    print "testODE.showWarnings() => "
    print testODE.showWarnings()
    print "\ntestODE.indepvariable.depdomain => ", testODE.indepvariable.depdomain
    print "testtraj(0.2, 'aux_other') => ", \
        testtraj(0.2, 'aux_other')

    print "\nNow adding a terminating co-ordinate threshold event..."
    ev_args = {'name': 'threshold',
               'eventtol': 1e-4,
               'eventdelay': 1e-5,
               'starttime': 0,
               'active': True,  # = default
               'term': True,
               'precise': True  # = default
               }
    thresh_ev = Events.makePythonStateZeroCrossEvent('w', 20, 1, ev_args)
    testODE.eventstruct.add(thresh_ev)
    print "Recomputing trajectory:"
    print "traj2 = testODE.compute('test2')"
    traj2 = testODE.compute('test2')
    print "\ntestODE.showWarnings() => "
    print testODE.showWarnings()
    print "\ntestODE.indepvariable.depdomain => ", testODE.indepvariable.depdomain


    print '\n-------- Test: Explicit functional trajectory'
    print "Explicit functional trajectory 'sin_gen' computes sin(t*speed)"

    print "Make 'xdomain' argument smaller than known limits for sine wave: [-1.001, 0.7]"
    args = {'tdomain': [-50, 50],
            'pars': {'speed': 1},
示例#39
0
  def handle_request(self, request, viewname):
    '''Handles the main request.'''
    # send the common javascript that every view enjoys
    request.writeln('''
      <script language='JavaScript' type='text/javascript'>
        /* Clears an input field (the first time it is entered) */
        function clearField(field) {
          if (!field.cleared) { // only clear once
            field.value = '';
          }
          field.cleared = true;
        }
        
        /* Confirms a url given a message before going to it in a target frame */
        function confirm_target_url(msg, frame, urlst) {
          if (confirm(msg)) {
            frame.location.href = urlst;
          }
        }
        
        /* Confirms a url given a message before going to it */    
        function confirm_url(msg, urlst) {
          confirm_target_url(msg, window, urlst);
        }
        
        /* Retrieves the text children of an XML node */
        function getNodeText(node) {
          var text = "";
          for (var i = 0; i < node.childNodes.length; i++) {
            if (node.childNodes[i].nodeType == 3) { // IE doesn't recognize the TEXT_NODE constant
              text += node.childNodes[i].nodeValue;
            }
          }
          return text;
        }
        
        /* Translates the evt object to get a cross-browser event source element.
           Note that this is a JavaScript event, and it has nothing to do with the
           server-side event system! */
        function getEventSource(evt) {
          // this code is taken from Dynamic HTML Reference by Danny Goodman
          evt = (evt) ? evt : ((event) ? event : null);
          if (evt) {
            var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
            if (elem) {
              return elem;
            }
          }
          return null;
        }
        
        /* Replaces all occurances of one string within another string (JavaScript's replace only does one - this ensures consistencies across DOM implementations) */
        function replaceAll(st, oldSt, newSt) {
          // short circuit
          if (st == null || oldSt == null || newSt == null) {
            return st;
          }//if
          var buf = "";
          // step through and replace each occurance
          var current = 0;
          var pos;
          while ((pos = st.indexOf(oldSt, current)) >= 0) {
            buf += st.substring(current, pos);
            buf += newSt;
            current = pos + oldSt.length;
          }//while
      
          // add any remaining text at the end
          buf += st.substring(current, st.length);
          return buf;  
        }
         
        /* Convenience method to get the first child with nodeName=name (case insensitive) for an element */
        function xmlGetChild(node, name) {
          for (var i = 0; i < node.childNodes.length; i++) {
            var child = node.childNodes.item(i);
            if (child.nodeName.toLowerCase() == name.toLowerCase()) {
              return child;
            }
          }
        }
        /* Convenience method to get a list of children with nodeName=name (case insensitive) for an element */
        function xmlGetChildren(node, name) {
          var children = new Array();
          for (var i = 0; i < node.childNodes.length; i++) {
            var child = node.childNodes.item(i);
            if (child.nodeName.toLowerCase() == name.toLowerCase()) {
              children[children.length] = child;
            }
          }
          return children;
        }
        /* Convenience function to clear all children of an XML element */
        function xmlClear(node) {
          while (node.firstChild != null) { 
            node.removeChild(node.firstChild);
          }
        }
            
        /*
         * Javascript's native encodeURI and encodeURIComponent does not handle all characters,
         * (and base64 doesn't work either because it uses reserved characters in the url,)
         * so I have a homegrown solution that does everything except the following chars:
         */
        var alphanumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        var qualifier = "_";
        var base = 16;
        var pad = 4;
        function encode(st) {
          var newst = "";
          for (var i = 0; i < st.length; i++) {
            if (alphanumeric.indexOf(st.charAt(i)) >= 0) {
              newst += st.charAt(i);
            }else{
              newst += qualifier;
              var h = st.charCodeAt(i).toString(base);
              for (var j = h.length; j < pad; j++) {
                newst += '0';
              }
              newst += h;
            }
          }
          return newst;
        }
        function html(st) {
           ''' + html_conversions + '''
           return st;
        }
        function decode(st) {
          var newst = "";
          for (var i = 0; i < st.length; i++) {
            if (st.charAt(i) == qualifier && st.length >= i + pad + 1) {
              newst += String.fromCharCode(parseInt(st.substring(i+1,i+pad+1), 16));
              i += pad;
            }else{
              newst += st.charAt(i);
            }
          }
          return newst;
        }      

        </script>
    ''')     

    if self.interactive:
      # register for events on this item
      request.windowid = GUID.generate()
      rootid = request.getvalue('global_rootid', '')
      request.session.add_event_queue(request.windowid, rootid) 
      Events.add_listener(request.session, rootid)
      
      # send the initial events for this view to the event system
      for event in self.get_initial_events(request, rootid):
        request.session.process(rootid, event, request.windowid)
        
      # send the interactive code
      request.writeln('''
        <script language='JavaScript' type='text/javascript'>
          var refreshEnabled = false;
          var timerid = -1;
          var eventsRequest = null;
          
          /** Sends a change action to the server.  This function takes the action_method to be called,
              then a variable number of arguments to be sent to the server as part of the call. */
          function sendEvent(action_method) {
            // short circuit if we're already in a call -- we don't allow two calls at once
            if (eventsRequest != null || !refreshEnabled) {
              return;
            }

            // clear the timer (just in case we were called directly)
            if (timerid) {
              clearTimeout(timerid);
            }

            // create the eventsRequest object
            if (window.XMLHttpRequest) { // Mozilla, Safari,...
              eventsRequest = new XMLHttpRequest();
              if (eventsRequest.overrideMimeType) {
                eventsRequest.overrideMimeType('text/xml');
              }
            }else if (window.ActiveXObject) { // IE
              try {
                eventsRequest = new ActiveXObject("Msxml2.XMLHTTP");
              }catch (e) {
                try {
                  eventsRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }catch (e2) {
                  alert("Your browser does not support AJAX.  Please upgrade your browser to run this application");
                  return;
                }
              }
            }

            // wrap up the arguments
            var args = [];
            var debugargs = [];
      ''')
      for key, value in request.get_global_parameters({'gm_contenttype':'text/xml', 
                                                       'gm_internal_action':'send_events_xml',
                                                       'global_windowid': request.windowid,
                                                      }):
        request.writeln('            args[args.length] = "' + key + '=' + value + '";')
      request.writeln('''
      
            // is there an action to encode with this call?
            if (action_method != null) {
              args[args.length] = "gm_action=" + action_method;
              for (var i = 1; i < sendEvent.arguments.length; i++) {
                var arg = sendEvent.arguments[i];
                args[args.length] = "gm_arg" + i + "=" + event_arg_encode(arg);
                debugargs[debugargs.length] = arg;
              }
            }
            
            // show the event in the debugger, if open
            if (top.showDebugEvent) {
              if (action_method == null) {  // a normal update
                //took this out because it causes too much traffic in the events window
                //top.showDebugEvent("QueuePop", "\xA0", "\xA0", "#99FF99");
              }else{
                top.showDebugEvent("Send", action_method, debugargs, "#99CCFF");
              }
            }
            
            // send the request
            eventsRequest.open('POST', "''' + CGI_PROGRAM_URL + '''", true);
            eventsRequest.onreadystatechange = receiveRefreshResponse;
            eventsRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            eventsRequest.send(args.join('&'));
          }//sendEvent function
          
          /** Recursively encodes an argument, including Array types. */
          function event_arg_encode(arg) {
            if (arg instanceof Array && arg.length) { // regular array/python list
              encodedarg = "a";
              for (var i = 0; i < arg.length; i++) {
                encodedarg += event_arg_encode(arg[i]);
              }
              encodedarg += '-';
              return encodedarg;
            }else if (arg instanceof Array) { // associative array/python dictionary
              encodedarg = "d";
              for (key in arg) {
                encodedarg += event_arg_encode(key) + event_arg_encode(arg[key]);
              }
              encodedarg += '-';
              return encodedarg;
            }else if (typeof arg == 'number') {
              if (arg % 1 == 0) {
                return "i" + encode(arg + "") + '-';
              }else{
                return "f" + encode(arg + "") + '-';
              }
            }else if (typeof arg == 'boolean') {
              return "b" + encode(arg ? 'True' : 'False') + '-';
            }else {
              return "s" + encode(arg + "") + '-';
            }          
          }
          
          /** Automatically called by the XMLHttpRequest object with the refresh response from the server */
          function receiveRefreshResponse() {
            // ensure everything is here and we have a good response (this gets called whenever data comes, so it happens multiple times)
            try {
              if (eventsRequest.readyState != 4 || eventsRequest.status != 200) {
                // don't reset anything -- this method will get called again when status == 200 (i.e. everything's here)
                return;
              }
            }catch (e) {  
              // we have to reset everything or else the pop events call won't work next time
              eventsRequest = null;  // reset for next call
              if (timerid) {
                clearTimeout(timerid);
              }
              timerid = setTimeout('sendEvent(null)', ''' + str(POLLING_TIME_IN_SECONDS * 1000) + ''');
              return;
            }

            try {
              // get the XML and free up the eventsRequest object for another call
              var xmldoc = eventsRequest.responseXML;
  
              // get the xml and call the handler function for each event node
              var events = xmldoc.firstChild.childNodes;
              for (var i = 0; i < events.length; i++ ) {
                var event = events[i];
                if (event.nodeName == 'event') {
                  // get the arguments
                  var args = [];
                  for (var j = 0; j < event.childNodes.length; j++) {
                    args[args.length] = event_arg_decode(event.childNodes[j]);
                  }
                  
                  // show the event in the debugger, if open
                  if (top.showDebugEvent) {
                    top.showDebugEvent("Receive", event.getAttribute('handler'), args, "#CCCC99");
                  }

                  // call the function
                  var handler = window[event.getAttribute('handler')];
                  handler.apply(null, args);
                }
              }

            }finally{
              // reset the eventsRequest and timer for another call
              eventsRequest = null;  // reset for next call
              if (timerid) {
                clearTimeout(timerid);
              }
              timerid = setTimeout('sendEvent(null)', ''' + str(POLLING_TIME_IN_SECONDS * 1000) + ''');
            }
          }//receiveRefreshResponse function


          /** Recursively decodes xml-encoded arguments, including Array types. 
              See Events.process_argument for the creator this xml. */
          function event_arg_decode(argnode) {
            if (argnode.nodeName == 'argument') {
              if (argnode.getAttribute('type') == 'list') {
                var args = [];
                for (var j = 0; j < argnode.childNodes.length; j++) {
                  args[args.length] = event_arg_decode(argnode.childNodes[j]);
                }
                return args;
              
              }else if (argnode.getAttribute('type') == 'dict') {
                var args = new Array();
                for (var j = 0; j < argnode.childNodes.length; j += 2) {
                  args[event_arg_decode(argnode.childNodes[j])] = event_arg_decode(argnode.childNodes[j+1]);
                }
                return args;

              }else{
                var value = argnode.firstChild.nodeValue; // CDATA section
                if (argnode.getAttribute('type') == 'bool') {
                  return (value == 'True');
                }else if (argnode.getAttribute('type') == 'int') {
                  return parseInt(value);
                }else if (argnode.getAttribute('type') == 'float') {
                  return parseFloat(value);
                }else {
                  return value;
                }
              }
            }
          }
          
          
          /** Starts the event loop.  Subclasses must call this when they are finished setting up.
              if we started pulling events before the web page is set up, we might call functions that
              don't exist yet.  Because views might be made up of multiple frames, there is no way
              to automatically know when the page is ready (onLoad doesn't work).  Therefore, 
              subclasses MUST call this method when they are done setting up to start the event loop. */
          function startEventLoop() {
            refreshEnabled = true;
            sendEvent(null);
          }
          
          
          /** Disables the refreshing of events from the server.  Call this when you
              want to stop events from happening, such as when the user is entering
              a comment.  Don't forget to enableRefresh() when done! */
          function disableRefresh() {
            refreshEnabled = false;
            if (timerid) {
              clearTimeout(timerid);
            }
          }
          
          
          /** Enables the refreshing of events */
          function enableRefresh() {
            refreshEnabled = true;
            sendEvent(null);
          }
          
          /** Refreshes the events now */
          function refreshEvents() {
            enableRefresh();
          }
          
          /** Tells the client to log in again */
          function gm_loginAgain() {
            alert('Your session has timed out.  Please log in again.');
            window.location.replace("''' + CGI_PROGRAM_URL + '''");
          }
          
        </script>
      ''')
    
    # let the subclass send it's content
    self.send_content(request)
示例#40
0
文件: cs0.py 项目: csZero/PythonCS0
def mouseClickedEvent(handle):
    Events.addMouseClickedEvent(handle)
示例#41
0
    def handle_cgi_request(self):
        """Handles a cgi request.  This is the main entry point for client requests,
       whether POST or GET, that are cgi-bin requests.  They all share the
       same memory space (i.e. this singleton object)."""

        # parse the form parameters to the form object
        # if a post request, encode everything (post requests can't encode on the client side because they come from forms)
        # get requests should encode on the client side (to handle special characters in the URL)
        if self.method.lower() == "get":
            for item in self.form.list:
                item.value = Constants.decode(item.value)

        # set the window id
        self.windowid = self.getvalue("global_windowid")

        # send the headers
        self.send_headers()

        try:

            # get the view
            viewst = self.getvalue("global_view", "meetingchooser").lower()

            # get the session, if there is one
            self.session = Directory.get_session(self.form.getvalue("z", ""))

            # if session is none, try logging the user in based upon their username and password parameters
            if self.session == None:
                self.session = Directory.login(self.form.getvalue("username", ""), self.form.getvalue("password", ""))

            # if the view is login, log the session out
            if (viewst == "login" or viewst == "logout") and self.session != None:
                Directory.logout(self.session)
                self.session = None

            # if session is still None, send them to the login page
            if self.session == None:
                viewst = "login"

            # process actions
            if self.session:
                Events.process_actions(self)

            # send events xml or send to view processing
            if self.getvalue("gm_internal_action") == "send_events_xml":
                Events.send_events_xml(self)

            else:
                # get the view
                if not BaseView.views.has_key(viewst):
                    self.writeln("<html><body>Error!  No view named " + viewst + " found.</body></html>")
                    return
                view = BaseView.views[viewst]
                self.view = view

                # send processing to the view
                Constants.log.debug("Sending processing to view: " + viewst)
                view.handle_request(self, viewst)

        except:
            self.writeln("<html><body>")
            self.writeln("<hr>")
            self.writeln("<b>The following error has occurred in the GroupMind application:</b>")
            self.writeln("<pre><tt>")
            traceback.print_exc(file=self.out)
            traceback.print_exc()
            self.writeln("</pre></tt>")
            self.writeln("</body></html>")
示例#42
0
def waitForClick():
    Events.waitForClick()
示例#43
0
def keyReleasedEvent(handle):
    Events.addKeyReleasedEvent(handle)
示例#44
0
def sessionRemoved(key, session):
  Events.remove_session_listeners(session.id)
示例#45
0
def mouseReleasedEvent(handle):
    Events.addMouseReleasedEvent(handle)
示例#46
0
def mouseMovedEvent(handle):
    Events.addMouseMovedEvent(handle)
示例#47
0
def mouseDraggedEvent(handle):
    Events.addMouseDraggedEvent(handle)
示例#48
0
def keyPressedEvent(handle):
    Events.addKeyPressedEvent(handle)
示例#49
0
文件: Ack.py 项目: ArildF/rogie
 def __init__( self, aSocket, theRoom, theLength ):
     self.sock = aSocket
     self.events = Events.getEvents()
     self.length = theLength
     self.room = theRoom
示例#50
0
class Window():
     
    def __init__(self,map_name):
        pygame.init()
        self.core = Core()
        self.mode = Event_Handler()
        self.file = 'ingame_temp'#заміна self.file в Core.py
        #self.map_type - треба замінити в Core.py
        #self.x_coord_start self.x_coord_end - замінити в Core.py
        self.battle = Battle('1')
        self.resources = Resources()
        self.graphical_logic = Graphical_logic()
        self.w_event = Events()
        self.minimap_x =0
        self.minimap_y =0
        self.count = 0
        self.days = 0
        self.fraction = 1 # першими ходять червоні
        self.map_name = map_name
        self.stage = 0
        self.save_load_name = ''
        self.fractions = [[1, 1, 0, 0, 3, 1],[2, 1, 0, 0, 0, 0]]
        
    def Main_Window(self):
        self.display = pygame.display.set_mode((1280,720))
        manager = ResManager()
        pygame.display.set_icon(manager.get_image('icon.png'))
        pygame.display.set_caption("War for cookies")
        self.map_type = self.core.load_file(self.map_name,self.file)
        self.display.fill((220,220,250))
        pygame.display.flip()
        i = 0
        
    def Maps_grid(self):
        self.big_step = 50
        self.big_steps =14
        pygame.display.flip()# лол, костЫль

    def Minimaps_grid(self):
        if self.map_type == 0:  
           self.step_p = 6
           self.steps = 50
        elif self.map_type == 1:
            self.step_p = 3
            self.steps = 100
        elif self.map_type == 2:
            self.step_p = 2
            self.steps = 150
        cell = Rect((800,0),(300,300))
        pygame.draw.rect(self.display,(0,0,0),cell,2)
        pygame.display.flip()
        
    def load_cells_list(self):
        self.cells_list = self.core.load_minimap_cells(self.file)

    def Minimap(self):
        colour = self.resources.colours()
        for i in range(self.steps):
            for j in range(self.steps):
                cell = Rect((800+self.step_p*i,self.step_p*j),(self.step_p,self.step_p))
                cell_type = self.cells_list[i*self.steps+j][2]
                pygame.draw.rect(self.display,colour[cell_type],cell,0)
        pygame.display.flip()
        self.Minimaps_grid()
        
    def game_buttons(self):
        textures = self.resources.textures_for_menu()
        for i in range(4):
            first_textures =textures[i].get_rect()
            first_textures.center=(1215,90+180*i)
            self.display.blit(textures[i],first_textures)  
        pygame.display.update()

    def reload_window(self,x,y):
        self.Maps_grid()
        self.Minimaps_grid()
        self.Minimap()
        self.Load_part_of_map(x,y)
        self.game_buttons()
        pygame.display.flip()
    
    def status_army(self,id_army):
        cell = Rect((900,350),(225,400))
        pygame.draw.rect(self.display,(220,220,250),cell,0)
        textures_default = self.resources.textures_for_army()
        fraction = self.fraction
        textures = []
        list_army = self.core.load_army(self.file, id_army)
        for i in range(5):
            textures.append(textures_default[fraction*5+fraction+i+1])
            first_texture = textures[i].get_rect()
            first_texture.center=(932,370+64*i)
            self.display.blit(textures[i],first_texture)
            try:
                font1 = pygame.font.SysFont("Monospace", 40, bold=True, italic=False)
                item = str(list_army[i+1])
                font1 = font1.render(item,0,(20,20,20))
                self.display.blit(font1,(964,350+64*i))
            except TypeError:         
                pass
        pygame.display.flip()
    
    def res_view(self,fraction):
        list_1 = self.core.get_fraction_status(self.file, fraction)
        
        cell = Rect((750,350),(140,300+100))
        pygame.draw.rect(self.display,(220,220,250),cell,0)
        font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)
        item = 'Milk'
        font1_1 = font1.render(item,0,(20,20,20))
        self.display.blit(font1_1,(800,350))
        item = str(list_1[2])
        font2 = font1.render(item,0,(20,20,20))
        self.display.blit(font2,(800,350+40))                
        item = 'cookies'
        font3 = font1.render(item,0,(20,20,20))        
        self.display.blit(font3,(800,350+80))
        item = str(list_1[3])
        font4 = font1.render(item,0,(20,20,20))
        self.display.blit(font4,(800,350+120))
        item = 'Farms'
        font5 = font1.render(item,0,(20,20,20))
        self.display.blit(font5,(800,350+160))
        item = str(list_1[4])
        font6 = font1.render(item,0,(20,20,20))
        self.display.blit(font6,(800,350+160+40))                
        item = 'Mines'
        font7 = font1.render(item,0,(20,20,20))
        self.display.blit(font7,(800,350+200+40))
        item = str(list_1[5])
        font8 = font1.render(item,0,(20,20,20))
        self.display.blit(font8,(800,350+240+40))        
                        
    def Load_part_of_map(self,x,y):
        textures = self.resources.textures()
        textures_army = self.resources.textures_for_army()
        cells_list,x_coord_start,y_coord_start= self.core.load_cells(x,y,self.file)
        for i in range(self.big_steps):
            for j in range(self.big_steps):
                cell_type = cells_list[i*self.big_steps+j][2]
                fraction  = cells_list[i*self.big_steps+j][3]
                army = cells_list[i*self.big_steps+j][4]
                if (cell_type >6) and (cell_type<12) or ((fraction!=0) and (army == 0)):
                    x = cells_list[i*self.big_steps+j][0]
                    y = cells_list[i*self.big_steps+j][1]
                    local_list = self.core.load_cells_for_transparent_textures(x, y,self.file)
                    result_type = self.graphical_logic.get_type_background_textures(x, y, local_list)
                    first_texture = textures[result_type].get_rect()
                    first_texture.center=(45+self.big_step*i,25+self.big_step*j)
                    self.display.blit(textures[result_type],first_texture) 
                if (fraction > 0) and (cell_type == 9):
                    first_texture = textures[cell_type+fraction-1].get_rect()
                    first_texture.center=(45+self.big_step*i,25+self.big_step*j)
                    self.display.blit(textures[cell_type+fraction-1],first_texture)
                elif((cell_type<3) and (army > 0)):
                    first_texture = textures[cell_type].get_rect()
                    first_texture.center=(45+self.big_step*i,25+self.big_step*j)
                    self.display.blit(textures[cell_type],first_texture)      
                    first_texture = textures[cell_type].get_rect()
                    first_texture.center=(45+self.big_step*i,25+self.big_step*j)
                    self.display.blit(textures_army[fraction*5+fraction],first_texture)
                else:
                    first_texture = textures[cell_type].get_rect()
                    first_texture.center=(45+self.big_step*i,25+self.big_step*j)
                    self.display.blit(textures[cell_type],first_texture)               
        cell = Rect((800+x_coord_start*self.step_p,0+y_coord_start*self.step_p),(self.step_p*14,self.step_p*14))
        self.Minimap()
        pygame.draw.rect(self.display,(0,0,0),cell,2)
        self.Maps_grid()
        pygame.display.flip()

    def event_handler(self):
        event = self.w_event.get_event(self.stage, self.big_step, self.step_p)
        self.res_view(self.fraction)
        if (event != None):
            if self.stage == 0:
                try:
                    self.stage,self.last_x,self.last_y,self.fraction,self.days,self.army_coords,self.id_army,self.x_start,self.y_start \
                    = self.mode.stage_0(event, self.fraction, self.days, self.action_to_map_coords, self.action_to_minimap_coords,self.last_x,self.last_y,self.file,self.x_start,self.y_start)
                except AttributeError:
                    self.status_army(0)
                    self.stage,self.last_x,self.last_y,self.fraction,self.days,self.army_coords,self.id_army,self.x_start,self.y_start \
                    = self.mode.stage_0(event, self.fraction, self.days, self.action_to_map_coords, self.action_to_minimap_coords,0,0,self.file,0,0)           

                days = 'Day '+str(self.days+1)
                fraction_out = str(self.fraction)
                cell = Rect((800,650),(300,50))
                pygame.draw.rect(self.display,(220,220,250),cell,0)
                font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)
                font2 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)        
                font1 = font1.render(days,0,(20,20,20))
                self.display.blit(font1,(825,675))
                font2 = font2.render(fraction_out,0,(20,20,20))
                self.display.blit(font2,(975,675))
                pygame.display.update()    
            if self.stage == 1:
                self.action_for_save(self.save_load_name)
                if len(event) > 2:
                    try:
                        self.stage,self.save_load_name = self.mode.stage_1(event, self.save_load_name, self.file, self.action_for_save, self.reload_window, self.last_x, self.last_y)
                    except AttributeError:
                        self.stage,self.save_load_name = self.mode.stage_1(event, self.save_load_name, self.file, self.action_for_save, self.reload_window, 0,0)
                    print self.save_load_name

            if self.stage == 2:
                self.action_for_load(self.save_load_name)
                if len(event) > 2:
                    try:
                        self.stage,self.save_load_name = self.mode.stage_2(event, self.save_load_name, self.file, self.action_for_load, self.reload_window, self.last_x, self.last_y)
                    except AttributeError:
                        self.stage,self.save_load_name = self.mode.stage_2(event, self.save_load_name, self.file, self.action_for_load, self.reload_window, 0,0)
                    print self.save_load_name

            if self.stage == 3:
                self.stage,self.last_x,self.last_y,self.armies_list = self.mode.stage_3(event, self.stage, self.moving_army,self.file,self.id_army,self.last_x,self.last_y)

            if self.stage == 4:
                pass
            
            if self.stage == 5:
                pass

            if self.stage == 6:
                self.battle_dialog_window()
                self.stage = self.mode.stage_6(event, self.battle_dialog_window,self.stage,self.reload_window,self.last_x,self.last_y,self.armies_list)

            if self.stage == 7:
                pass
            
            if self.stage == 8:
                pass

    def action_to_map_coords(self,x,y,last_x,last_y):
#        self.Load_part_of_map(x,y)

        cell = self.core.load_cell(y+last_y,x+last_x,self.file)
        if ((cell[3] == self.fraction) and (cell[4]>0)):
            stage = 3
            army_coords = [y+last_y,x+last_x]
            id_army = cell[4]
            self.status_army(id_army)
            return stage, army_coords, id_army
        
        else:
            return 0,0,0


    def moving_army(self,x,y,last_x,last_y):## Диагноз - говнокод 90лвл(2:14 ночи)
        armies_lists = 0
        self.status_army(self.id_army)
        cell = self.core.load_cell(self.army_coords[0],self.army_coords[1],self.file)
        if cell[4]!=0:
            self.id_army = cell[4]
        print 'army '+str(self.id_army)
        self.core.change_cell(cell[0],cell[1],cell[2],0,0,self.file)
        if ((self.army_coords[0]+x>-1) and (self.army_coords[1]+y>-1) and (self.army_coords[1]+y<self.steps) and (self.army_coords[0]+x<self.steps)):
            cell = self.core.load_cell(self.army_coords[0]+x,self.army_coords[1]+y,self.file)
            if (((cell[2]>=0) and (cell[2]<3)) and (cell[4] == 0)):
                self.core.change_cell(self.army_coords[0]+x,self.army_coords[1]+y,cell[2],self.fraction,self.id_army,self.file)
                self.army_coords[0] += x
                self.army_coords[1] += y
                print 'last_x '+str(last_x)+'last_y = '+str(last_y)
                try:
                    if (self.army_coords[1] - self.x_start >6):
                        self.x_start+=5
                        last_x = self.x_start+7
                        if (self.x_start>self.steps-1):
                            self.x_start = self.steps - self.big_steps
                        self.reload_window(last_x,last_y)
                        print 'last_x '+str(last_x)+'last_y = '+str(last_y)
                    elif (self.army_coords[0]- self.y_start >6):
                        self.y_start +=5
                        last_y = self.y_start+7
                        if (self.y_start>self.steps-1):
                            self.y_start = self.steps - self.big_steps
                        print 'Event!'
                        self.reload_window(last_x,last_y)
                        print 'last_x '+str(last_x)+'last_y = '+str(last_y)
                    elif (self.army_coords[1] - self.last_x <-6):
                        self.x_start-=5
                        if (self.x_start<0):
                            self.x_start = 0
                            last_x = self.x_start+7
                        self.reload_window(last_x,last_y)
                        print 'last_x '+str(last_x)+'last_y = '+str(last_y)
                    elif (self.army_coords[0]- self.last_y <-6):
                        self.y_start -=5
                        last_y = self.y_start+7
                        if (self.y_start<0):
                            self.y_start = 0
                        print 'Event!'
                        self.reload_window(last_x,last_y)
                        print 'last_x '+str(last_x)+'last_y = '+str(last_y)
                    else:
                        self.reload_window(last_x,last_y)
                except AttributeError:
                    self.reload_window(0,0)
                    print 'last_x '+str(last_x)+'last_y = '+str(last_y)
                return True,3, last_x,last_y,0
            
            elif ((((cell[2]>=0) and (cell[2]<3)) and(cell[3]!=self.fraction) and (cell[4] != 0))or ((cell[2]==9) and (cell[3]==self.fraction))):
                armies_lists = []
                stage = 6
                armies_lists.append(self.core.load_army(self.file, self.id_army))
                temp = []
                for i in range(6):
                    temp.append(armies_lists[0][i])
                armies_lists[0] = temp
                self.core.change_cell(self.army_coords[0],self.army_coords[1],cell[2],self.fraction,self.id_army,self.file)                
                cell = self.core.load_cell(self.army_coords[0]+x,self.army_coords[1]+y,self.file)
                armies_lists.append(self.core.load_army(self.file, cell[4]))
                temp = []
                for i in range(6):
                    temp.append(armies_lists[1][i])
                armies_lists[1] = temp

                return False, stage,last_x,last_y,armies_lists
            elif (((cell[2]>=7) and (cell[2]<9)) and (cell[3] != self.fraction)):
                stage = 3
                lose_fraction  = cell[3]
                print 'Alert'
                if lose_fraction > 0:
                    if cell[2] == 7:
                        frac = self.core.get_fraction_status(self.file, lose_fraction)
                        self.core.change_fraction_status(self.file, lose_fraction, frac[1], frac[2], frac[3], frac[4]-1, frac[5])
                        frac = self.core.get_fraction_status(self.file, self.fraction)
                        self.core.change_fraction_status(self.file, self.fraction, frac[1], frac[2], frac[3], frac[4]+1, frac[5])
                        self.core.change_cell(cell[0], cell[1], 7, self.fraction, 0, self.file)
                    if cell[2] == 8:
                        frac = self.core.get_fraction_status(self.file, lose_fraction)
                        self.core.change_fraction_status(self.file, lose_fraction, frac[1], frac[2], frac[3], frac[4], frac[5]-1)
                        frac = self.core.get_fraction_status(self.file, self.fraction)
                        self.core.change_fraction_status(self.file, self.fraction, frac[1], frac[2], frac[3], frac[4], frac[5]+1)
                        self.core.change_cell(cell[0], cell[1], 8, self.fraction, 0, self.file)                        
                else:
                    if cell[2] == 7:
                        frac = self.core.get_fraction_status(self.file, self.fraction)
                        self.core.change_fraction_status(self.file, self.fraction, frac[1], frac[2], frac[3], frac[4]+1, frac[5])
                        self.core.change_cell(cell[0], cell[1], 7, self.fraction, 0, self.file)
                    if cell[2] == 8:
                        frac = self.core.get_fraction_status(self.file, self.fraction)
                        self.core.change_fraction_status(self.file, self.fraction, frac[1], frac[2], frac[3], frac[4], frac[5]+1)
                        self.core.change_cell(cell[0], cell[1], 8, self.fraction, 0, self.file)
                return False, stage,last_x,last_y,armies_lists
            elif ((cell[3]== self.fraction) and (cell[4]!=0)):
                list_start = self.core.load_army(self.file,self.id_army)
                list_end = self.core.load_army(self.file, cell[4])
                list_resoult = []
                for i in range(len(list_start)-3):
                    if i == 0:
                        list_resoult.append(list_end[i])
                    else:
                        list_resoult.append(list_start[i]+list_end[i])
                list_resoult.append(20)
                list_resoult.append(0)
                list_resoult.append(self.fraction)
                self.core.change_army(self.file, list_resoult[0], list_resoult[1], list_resoult[2], list_resoult[3], list_resoult[4], list_resoult[5], list_resoult[6], list_resoult[7], list_resoult[8])
                self.core.change_army(self.file, self.id_army,0,0,0,0,0,0,0,0)
                cell = self.core.load_cell(self.army_coords[0],self.army_coords[1],self.file)
                self.core.change_cell(self.army_coords[0],self.army_coords[1],cell[2],0,0,self.file)
                self.reload_window(last_x,last_y)
#            elif (((cell[2]>=7)) and (cell[4] == 0)):
#                stage = 5
#                return False, stage,last_x,last_y,armies_lists            
            else:
                return False,3,last_x,self.last_y,armies_lists

    def battle_dialog_window(self):
        textures = self.resources.textures_for_battle_gialog_window()
        first_textures = textures[0].get_rect()
        first_textures.center=(450,350)
        self.display.blit(textures[0],first_textures)
        for i in range(3):
            first_textures = textures[i+1].get_rect()
            first_textures.center=(350+100*i,450)
            self.display.blit(textures[i+1],first_textures)
        font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)       

        pygame.display.flip()
    
    def winrar_window(self,fraction):                
        textures = self.resources.textures_for_battle_gialog_window()
        first_textures = textures[0].get_rect()
        first_textures.center=(450,350)
        font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)
        item = u'Fraction '+str()
        font1 = font1.render(item,0,(20,20,20))
        self.display.blit(font1,(385,360)) 
        
    def action_to_minimap_coords(self,x,y): #вернуть стартовые х и у!
        self.Load_part_of_map(x,y)
        cells_list,x_coord_start,y_coord_start = self.core.load_cells(x, y, self.file)
        cell = Rect((800+x_coord_start*self.step_p,0+y_coord_start*self.step_p),(self.step_p*14,self.step_p*14))
        self.load_cells_list()
        self.Minimap()
        pygame.draw.rect(self.display,(0,0,0),cell,2)
        self.Maps_grid()
        return x_coord_start,y_coord_start
    
    def action_for_save(self,text):
        cell = Rect((360,260),(300,200))
        pygame.draw.rect(self.display,(204,204,204),cell,0)
        cell = Rect((385,280),(250,50))
        pygame.draw.rect(self.display,(255,255,204),cell,0)
        pygame.draw.rect(self.display,(0,0,0),cell,2)
        filename = pygame.font.SysFont("Times New Roman", 20, bold=False, italic=True)
        font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)
        font2 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)        
        item = u'Press enter for save'
        item2 = u'Press ESC for exit'
        font1 = font1.render(item,0,(20,20,20))
        self.display.blit(font1,(385,360))
        font2 = font2.render(item2,0,(20,20,20))
        self.display.blit(font2,(385,410))
        filename = filename.render(text,0,(20,20,20))
        self.display.blit(filename,(455,290))
        pygame.display.update()
        
    def action_for_load(self,text):
        cell = Rect((360,260),(300,200))
        pygame.draw.rect(self.display,(204,204,204),cell,0)
        cell = Rect((385,280),(250,50))
        pygame.draw.rect(self.display,(255,255,204),cell,0)
        pygame.draw.rect(self.display,(0,0,0),cell,2)
        filename = pygame.font.SysFont("Times New Roman", 20, bold=False, italic=True)
        font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)
        font2 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)        
        item = u'Press enter for load'
        item2 = u'Press ESC for exit'
        font1 = font1.render(item,0,(20,20,20))
        self.display.blit(font1,(385,360))
        font2 = font2.render(item2,0,(20,20,20))
        self.display.blit(font2,(385,410))
        filename = filename.render(text,0,(20,20,20))
        self.display.blit(filename,(455,290))
        pygame.display.update()
            #self.Minimap()        
# 28x28, 25x25 cells
    def Rewrite_cell(self):
        self.event_handler()

    def Run(self):
        self.Main_Window()
        self.load_cells_list()
        self.Maps_grid()
        self.game_buttons()
        self.Minimaps_grid()
        self.Minimap()
        self.Load_part_of_map(0,0)
        while True:
            self.Rewrite_cell()
示例#51
0
 def generateEvent(self,port,value):
   Events.generate(self.componentId,port,value)
示例#52
0
#
# Example use of the event profiler
#
import Events as ev
import datetime as dt
import EventProfiler as ep
import numpy as np
#symbols = ['BFRE','ATCS','RSERF','GDNEF','LAST','ATTUF','JBFCF','CYVA','SPF','XPO','EHECF','TEMO','AOLS','CSNT','REMI','GLRP','AIFLY','BEE','DJRT','CHSTF','AICAF']
#symbols = ['QQQ','AAPL','GOOG','ORCL','MSFT']
symbols = np.loadtxt('symbol-set1.txt', dtype='S10', comments='#')
#symbols = symbols[0:20]
startday = dt.datetime(2008, 1, 1)
endday = dt.datetime(2009, 12, 31)
eventMatrix = ev.findEvents(symbols, startday, endday, verbose=True)
eventProfiler = ep.EventProfiler(
    eventMatrix, startday, endday,
    lookback_days=20, lookforward_days=20, verbose=True)
eventProfiler.study(
    filename="MyEventStudy.pdf",
    plotErrorBars=True,
    plotMarketNeutral=True,
    plotEvents=False,
    marketSymbol='$SPX')
示例#53
0
class Window(Core):
     
    def __init__(self,type_map,name):
        pygame.init()
        if type_map < 3:
            self.empty_map(type_map)
        else:
            self.load_file(name)
        self.type = 0
        self.resources = Resources()
        self.graphical_logic = Graphical_logic()
        self.w_event = Events()
        self.minimap_x =0
        self.minimap_y =0
        self.count = 0
        self.days = 0
        self.cell_type = 0
        self.fraction = 0 
        self.stage = 0
        self.save_load_name = ''
        
    def Main_Window(self):
        self.display = pygame.display.set_mode((1280,720))
        manager = ResManager()
        pygame.display.set_icon(manager.get_image('icon.png'))
        pygame.display.set_caption("Map Editor")
        
        self.display.fill((220,220,250))
        pygame.display.flip()
        i = 0
        
    def Maps_grid(self):
        self.big_step = 60
        self.steps_x =20
        self.steps_y =11
        for i in range(self.steps_x):
            for j in range(self.steps_y):
                cell = Rect((20+self.big_step*i,self.big_step*j),(self.big_step,self.big_step))
                pygame.draw.rect(self.display,(0,0,0),cell,1)
        pygame.display.flip()# лол, костЫль

    def Minimaps_grid(self):
        if self.map_type == 0:  
           self.step_p = 6
           self.steps = 50
        elif self.map_type == 1:
            self.step_p = 3
            self.steps = 100
        elif self.map_type == 2:
            self.step_p = 2
            self.steps = 150
        cell = Rect((800,0),(300,300))
        pygame.draw.rect(self.display,(0,0,0),cell,2)
        pygame.display.flip()
        
    def load_cells_list(self):
        self.cells_list = self.load_minimap_cells()

    def type_of_grids(self):       
        textures = self.resources.textures()
        colours = self.resources.colours()
        for i in range(11):
            textures[i]= pygame.transform.scale(textures[i],(60,60)) 
        for i in range(7):            
            first_texture = textures[i].get_rect()
            first_texture.center=(500+30+60*i,690)
            self.display.blit(textures[i],first_texture)
            cell = Rect((500+60*i,660),(60,60))       
            pygame.draw.rect(self.display,(0,0,0),cell,3)  
        pygame.display.update()

    def moving_army(self):
        pass

    def reload_window(self,x,y):
        self.Maps_grid()
        self.Minimaps_grid()
        
        self.Load_part_of_map(x,y)
        pygame.display.flip()
                
    def Load_part_of_map(self,x,y):
        textures = self.resources.textures()
        cells_list = self.load_cells(x, y)
        print len(cells_list)
        for i in range(11):
            textures[i]= pygame.transform.scale(textures[i],(60,60)) 
        for i in range(self.steps_x):
            for j in range(self.steps_y):
                print (j*self.steps_x+i)
                print len(cells_list)
                cell_type = cells_list[j*self.steps_x+i][2]

                if (cell_type >7) and (cell_type<12):
                    x = cells_list[i*self.big_steps+j][0]
                    y = cells_list[i*self.big_steps+j][1]
                    local_list = self.load_cells_for_transparent_textures(x, y)
                    result_type = self.graphical_logic.get_type_background_textures(x, y, local_list)
                    first_texture = textures[result_type].get_rect()
                    first_texture.center=(50+self.big_step*i,30+self.big_step*j)
                    self.display.blit(textures[result_type],first_texture) 

                else:
                    first_texture = textures[cell_type].get_rect()
                    first_texture.center=(50+self.big_step*i,30+self.big_step*j)
                    self.display.blit(textures[cell_type],first_texture)               

        self.Maps_grid()
        pygame.display.flip()

    def event_handler(self):
        event = self.w_event.get_event(self.stage, self.big_step, self.step_p)
        if (event != None):
            print self.stage
            if self.stage == 0:
                if (event[0]=='map_coords'):
                    self.action_to_map_coords(event[2],event[3])
                    self.stage = event[1]
                elif (event[0]=='minimap_coords'):
                    self.action_to_minimap_coords(event[2],event[3])
                    self.stage = event[1]
                    self.last_x = event[2]
                    self.last_y = event[3]
                elif (event[0]=='type_cell'):
                    self.stage = event[1]
                    self.type = event[2]
                    self.fraction = event[3]
                
                elif (event[0]=='save_mode'):
                    self.stage = event[1]
            if self.stage == 1:
                self.action_for_save(self.save_load_name)
                if len(event) > 2:
                    self.stage = event[1]
                    if event[3] == 'continue':
                        if len(self.save_load_name) <10:
                            self.save_load_name += event[2]
                            self.action_for_save(self.save_load_name)
                    if event[3] == 'backspace':
                        if len(self.save_load_name)>0:
                            self.save_load_name = self.save_load_name[:-1]
                            self.action_for_save(self.save_load_name)
                    if event[3] == 'save':
                        if self.save_load_name >2:
                            self.save_file(self.save_load_name)
                            self.save_load_name = ''
                            try:
                                self.reload_window(self.last_x,self.last_y)
                            except AttributeError:
                                self.reload_window(0,0)
                    if event[3] == 'cancel':
                        self.save_load_name = ''
                        try:
                            self.reload_window(self.last_x,self.last_y)
                        except AttributeError:
                            self.reload_window(0,0)

                    print self.save_load_name

    def action_to_map_coords(self,x,y):
        textures = self.resources.textures()        
        for i in range(11):
            textures[i]= pygame.transform.scale(textures[i],(60,60))
        a = (y in [1,3,5,7,9])
        if ((x == 0) and (a==True)):
            self.change_cell(x,y,self.type, ((y+1)//2))
        elif((x==19) and (a==True)):
            self.change_cell(x,y,self.type, ((y+1)//2)+5)            
        else:
            self.change_cell(x,y,self.type, 0)    
        textures = pygame.transform.scale(textures[self.type],(60,60))
        first_texture = textures.get_rect()
        first_texture.center=(50+x*self.big_step,30+y*self.big_step)
        self.display.blit(textures,first_texture)  
        #pygame.draw.rect(self.display,(0,0,0),cell,2)
        self.Maps_grid()
        pygame.display.flip()        

    
    def action_for_save(self,text):
        cell = Rect((360,260),(300,200))
        pygame.draw.rect(self.display,(204,204,204),cell,0)
        cell = Rect((385,280),(250,50))
        pygame.draw.rect(self.display,(255,255,204),cell,0)
        pygame.draw.rect(self.display,(0,0,0),cell,2)
        filename = pygame.font.SysFont("Times New Roman", 20, bold=False, italic=True)
        font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)
        font2 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False)        
        item = u'Press enter for save'
        item2 = u'Press ESC for exit'
        font1 = font1.render(item,0,(20,20,20))
        self.display.blit(font1,(385,360))
        font2 = font2.render(item2,0,(20,20,20))
        self.display.blit(font2,(385,410))
        filename = filename.render(text,0,(20,20,20))
        self.display.blit(filename,(455,290))
        pygame.display.update()
            #        
# 28x28, 25x25 cells
    def Rewrite_cell(self):
        self.event_handler()

    def Run(self):
        self.Main_Window()
        self.load_cells_list()
        self.Maps_grid()
        self.Minimaps_grid()
        
        self.Load_part_of_map(0,0)
        self.type_of_grids()
        while True:
            self.Rewrite_cell()
示例#54
0
文件: main.py 项目: ArildF/rogie
    Config.loadConfig( "rogie.cfg" )
    config = Config.getConfig()
    
    protocol = config.getString("login", "protocol")
    
    #init the protocol we are going to use
    Protocol.initProtocol( protocol )
    
    protocol = Protocol.getProtocol()   
    
    
    #first get the cookie and id's     
    nick = config.getString( "login", "username" )
    passwd = config.getString( "login", "password" )

    events = Events.getEvents()
    events.addListener( Display.getDisplay() )
    events.addListener( SpamFilter.getInstance() )

    #create the socket
    sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    sock.settimeout( 120.0 )
    chatserver = config.getString( "login", "chatserver" )
    chatport = config.getInt( "login", "chatport" ) 


    #recreate the acl?
    if sys.argv.count( "-newacl" ):
        os.unlink( Acl.ACLFILE )

    chatRoom = config.getString( "login", "chatroom" )
示例#55
0
def main():

  """Initialize All Modules"""
  tokenList = Files.getTokenList() #[0] should be mine, and [1] should be my alt for group creation
  log.debug("Tokens:",tokenList)
  #Just my user id and token
  put = ("27094908", tokenList[0])
  
  #Totally Not The NSA Token
  Groups.Group.overlord = tokenList[1]
  
  #Just things
  log.network.debug.disable() #Suppress the return value of every message
  #log.command.low.enable() #For going through all the commands every time we get a command
  #log.user.low.enable() #For going through all the users every time we search for a user
  if Events.IS_TESTING:
    log.save.low.enable()
  
  #First load all the groups
  log.info("========== PRE-INIT (LOAD) ==========")
  toLoadList = []
  for folder in Files.getDirsInDir():
    if "Group " in folder: #If it a folder containing a group to load
      number = int(folder.split(" ")[-1])
      obj = (number, folder,) #Tuple of number and folder name
      flag = True
      for i in range(len(toLoadList)): #Sort the list
        if number < toLoadList[i][0]:
          toLoadList.insert(i, obj)
          flag = False
          break
      if flag: #If did not insert anywhere else
        toLoadList.append(obj)
        
  #Loadsd the groups guarenteed in order
  for group in toLoadList:
    Groups.loadGroup(group[1])
    
  log.info("Groups: ", Groups.getSortedList())
    
  #Do init and post-init
  log.info("========== INIT ==========")
  for group in list(Groups.getSortedList()): group.init()
  
  ### Named groups should be made after INIT to avoid duplicated initial users
  testGroup = makeNamedGroup(1, "23199161", put)
  
  toriGroup = makeNamedGroup(15, "23317842", put, "DLARulez")
  
  groupFam  = makeNamedGroup(2, "13972393", put, "easier")
  
  groupOldRocket  = makeNamedGroup(10, "26730422", put, "password")
    
  rocketMainGroup = makeCollective(20, "33057510", put)
  
  electronicsGroup = makeCollector(21, "33057523", put, rocketMainGroup)
  
  designAndMGroup = makeCollector(22, "33058451", put, rocketMainGroup)
  
  propulsionGroup = makeCollector(23, "33058488", put, rocketMainGroup)
  
  civGroup = makeCollective(30, "36614847", put, classType = Groups.Group) #Just a collective because I'm lazy in properly naming things. Is a normal group
  
  

  try: #This is so we can have our finally block remove any extra threads in case of error
    
    log.info("========== POST-INIT ==========")
    for group in list(Groups.getSortedList()): 
      try: group.postInit()
      except AssertionError: pass
    
        
    log.info("========== GROUP CLEANUP ==========")
    deletionList = Groups.getSortedList()
    deletionList.reverse()
    for i in deletionList.copy():
      if i.markedForDeletion:
        log.info("Deleting group", i)
        i.deleteSelf()
        del i
    del deletionList
    
  #try:
    def postEarlyMorningFact():
      joke = Jokes.funFacts.getJoke()
      if type(joke) == tuple:
        return Jokes.funFacts._postJoke(groupFam, ("Oh boy 3 A.M.!\n"+joke[0], joke[1]))
      return Jokes.funFacts._postJoke(groupFam, "Oh boy 3 A.M.!\n" + joke)
      
    def updateAllMsgLists():
      for searcher in MsgSearch._searcherList: #We could also probably get from all active groups instead of the searcher list
        searcher.GenerateCache()
        
    def postCivReminder():
      civGroup.handler.write("Don't forget to do your civ turn!")
    
    server = Server(('', Network.SERVER_CONNECTION_PORT), ServerHandler)
    
    #Update things for the groups every day at 5 a.m.
    log.info("Starting daily triggers")
    updaterDaily      = Events.DailyUpdater( time(5, 0), Groups.groupDailyDuties)
    updaterWebsite    = Events.DailyUpdater( time(4,58), Website.securityPurge) #Just do this seperately
    earlyMorningFacts = Events.DailyUpdater( time(3, 0), postEarlyMorningFact)
    monthlyMsgRefresh = Events.WeeklyUpdater(time(5,10), Events.WEEKDAY.SATURDAY, updateAllMsgLists, unitDifference = 4) #Once a month
    dailyCivReminder  = Events.DailyUpdater( time(15,0), postCivReminder)
    
    log.info("========== BEGINNING SERVER RECEIVING ==========")
    try:
      log.web("Starting server on port",Network.SERVER_CONNECTION_PORT)
      server.serve_forever()
    except KeyboardInterrupt:
      pass
      
    if server.exitValue != None: #Value of none means exited due to KeyboardInterrupt or something else
      log.info("Server shutting down from user input")
      if server.exitValue: #Exit value true means restart
        return 0;
      else: #False means shutdown
        raise AssertionError("Signal to main that we are done")
      
    #TESTING CODE:
    if Events.IS_TESTING:
      import traceback
      while True:
        print("> ", end = "")
        try:
          statement = input()
          if statement.lower() == "quit":
            break
          elif "=" in statement:
            exec(statement)
          else:
            print(eval(statement))
        except Exception as e:
          if isinstance(e, KeyboardInterrupt) or isinstance(e, EOFError):
            from os import _exit
            _exit(0) #Screw this crap, just get out of here. It's only for testing
          else:
            traceback.print_exc()
          
    raise AssertionError("Signal to main that we are done")
  #We need to kill all threads before exiting
  finally:
    Events.stopAllTimers()
    Events.SyncSave().saveAll(final = True)