def setup_server(self, api): api.update( api_gen.get_decorated() ) self.setup_websocket_callback_api(api) self.setup_blender_hack( bpy.context, use_gtk=False, headless=True ) print('blender hack setup ok') Server.set_api( self ) print('custom api set')
def newApp(args, options): from j25.Configuration import Configuration if len(args) < 2: print >> sys.stderr, "you must supply the name of the app" exit(1) _checkProject(AUTO_PROJECT_DIRS) appName = args[1] appDirectory = os.path.join('apps', appName) print Server.getBanner() print COLOR_SEQ % 33 try: _createPythonPackage(HERE, appDirectory, True) f = open(os.path.join(appDirectory, 'config.py'), 'w') f.write(app_config_template) f.close() f = open(os.path.join(appDirectory, 'routing.py'), 'w') f.write(app_routing_template % appName) f.close() for directory, is_python_package in AUTO_APP_DIRS: _createPythonPackage(appDirectory, directory, is_python_package) #update configuration config = Configuration.load_file("server.ini", False) currentApps = eval(config.main.applications) assert isinstance(currentApps, list) currentApps.append('apps.%s' % appName) config.main.applications = str(list(set(currentApps))) Configuration.dump_file("server.ini", config) logger.info("Application %s has been created. Current project has been configured." % appName) finally: print RESET_SEQ
def __init__(self, *args): Privilege.init() PyExt.init() StdChal.init() IOLoop.configure(EvIOLoop) Server.init_socket_server() super().__init__(*args)
def newProject(args, options): from j25.Configuration import Configuration if len(args) < 2: print >> sys.stderr, "Please supply a project name" exit(1) appName = options.withapp projectName = args[1] print Server.getBanner() print COLOR_SEQ % 33 print "Creating project: %s" % projectName _createPythonPackage(HERE, projectName, False) #creating project structure for directory, is_python_package in AUTO_PROJECT_DIRS: _createPythonPackage(projectName, directory, is_python_package) #creating templates config = Configuration.create_empty_config() s1 = config.add_section('main') s1.add_option('project_name', projectName) s1.add_option('applications', []) s1.add_option('excluded_applications_from_worker', []) s1.add_option("mode", "DEV") s1.add_option("ip", "0.0.0.0") s1.add_option("port", "8800") s1.add_option("is_subdomain_aware", True) s2 = config.add_section('session') s1.add_option('project_name', projectName) s2.add_option('secret', uuid4().hex + uuid4().hex) s2.add_option('url', ('%s/c9#session' % Constants.MONGODB_URL)) s2.add_option('secure', 'False') s2.add_option('timeout', '600') s3 = config.add_section('store') s3.add_option("db_name", "c9_%s" % projectName) s3.add_option("ip", "127.0.0.1") s3.add_option("auto_create_collections", None) Configuration.dump_file(os.path.join(projectName, 'server.ini'), config) f = open(os.path.join(projectName, 'routing.py'), 'w') f.write(project_routing_template) f.close() f = open(os.path.join(projectName, 'workerconfig.py'), 'w') f.write(app_workerconfig) f.close() if options.withapp: config = Configuration.load_file(os.path.join(projectName, 'server.ini'), False) builtin_Apps = eval(config.main.applications) assert isinstance(builtin_Apps, list) if not appName in builtin_Apps: builtin_Apps.append(appName) config.main.applications = str(builtin_Apps) Configuration.dump_file(os.path.join(projectName, 'server.ini'), config) logger.info("\033[1;33mProject %s Created with Application %s.\033[0m"% (projectName, appName)) else: logger.info("\033[1;33mApplication %s already installed in the project by Default.\033[0m" % appName) print RESET_SEQ
def key_up_event(event, response, chan): channel = synth.channels[int(chan)] elem = minidom.Document().createElement("note") elem.setAttribute("start", str(Server.getTime(channel.getEnvelope().startTime))) elem.setAttribute("end", str(Server.getTime(time.time()))) elem.setAttribute("note", str(channel.getNote())) elem.setAttribute("vol", str(channel.getVelocity())) elem.setAttribute("chan", str(chan)) appendLog(elem) channel.noteOff()
def Init_Mode() : global Script_mode global Script_Path #return_code = subprocess.call(['ping','-c','5','157.182.184.52']) return_code = 0 if return_code == 1 : Script_mode = True script.init_dir() script.read(Script_Path) else : Server.open(url)
def update(self): key = pygame.key.get_pressed() mouse = pygame.mouse.get_pressed() for event in pygame.event.get(): if event.type == QUIT or (key[K_F4] and key[K_LALT]): return False, self elif event.type == MOUSEBUTTONDOWN: mse = pygame.mouse.get_pos() if self.buttons["server"].onButton(mse): self.buttonSound.play() server = Server(''); server.connect() return True, MultiGameRabbitMenu.MultiGameRabbitMenu(server) # server.accept() # server.send(b"connexion avec client : OK") # server.recieve() elif self.buttons["client"].onButton(mse): self.buttonSound.play() return True, MultiGameRabbitMenu.MultiGameRabbitMenu() # client = Client('localhost') # client.connect() # client.recieve() # client.send(b"connexion avec serveur : OK") elif self.buttons["back"].onButton(mse): self.buttonSound.play() return True, PlayModeMenu.PlayModeMenu() elif event.type == MOUSEMOTION: mse = pygame.mouse.get_pos() pygame.mouse.set_cursor(*pygame.cursors.arrow) for button in self.buttons.values(): if button.onButton(mse): pygame.mouse.set_cursor(*pygame.cursors.tri_left) self.screen.blit(self.background, self.background.get_rect(), self.background.get_rect()) for button in self.buttons.values(): button.update() pygame.display.update() return True, self
def serverTesting(): # only for testing . #configuration ServerHandler = Server.qcServer(8080) serverThread = Server.openServerThread(ServerHandler) serverThread.start() try: while True: Hello = 1 except Exception: ServerHandler.closeServer() return 0
def main(): print_lock = Lock() socket_lock = Lock() server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) Server.setupSocket(print_lock, server_addr, server_socket) rasp_serial = serial.Serial( port='/dev/ttyACM0', # Linux #port='COM8', # Windows baudrate=9600, ) settings.init() threads = [] update_sensors_thread = Thread( target=Server.update_sensors, args=(print_lock, rasp_serial) ) threads.append(update_sensors_thread) update_sensors_thread.start() update_cameras_thread = Thread( target=Server.update_camera ) threads.append(update_cameras_thread) update_cameras_thread.start() should_continue = True while should_continue: with print_lock: print "Waiting for new client..." client, addr = server_socket.accept() thread = Thread(target=Server.run, args=(print_lock, client)) threads.append(thread) thread.start() with print_lock: print "Joining threads." for thread in threads: thread.join() with print_lock: print "All threads closed."
def main(): ADDR = getArg( "a", "127.0.0.1", "Address" ) PORT = getArg( "p", 5005, "Port" ) MAX_CLIENTS = getArg( "m", 50, "Max Clients" ) # Create server SERVER = Server( ADDR, PORT, MAX_CLIENTS ) # Server main loop SERVER.main() SERVER.close()
def handle_exception (self, exception, client = None): """ Handles an unexpected exception that occurs during client processing. @param exception (Exception) The exception raised. @param client (FastcgiClient) The client instance that generated the exception. """ Server.handle_exception(self, exception, client) if not client or not client.request_id: return client._write_record(_StreamRecord(FCGI_STDERR, "Could not process request: Internal error", client.request_id)) client._write_record(_EndRequestRecord(1, FCGI_REQUEST_COMPLETE, client.request_id))
def OnStart(self, event=None): if not self.status: if not self.me or self.me == '*': common.showerror(self, tr("Username should not be empty or '*'")) self.txtName.SetFocus() return ip = self.txtIP.GetValue() if not ip: common.showerror(self, tr("Host address cannot be empty!")) self.txtIP.SetFocus() return port = int(self.txtPort.GetValue()) self.pref.pairprog_host = ip self.pref.pairprog_port = port self.pref.pairprog_username = self.me self.pref.save() try: self.server = Server.start_server(ip, port, self.servercommands) if self.server: self.AddUser(self.me, manager=True) self.change_status('startserver') self.callplugin('start', self, 'server') except: common.warn(tr("Start server error!")) error.traceback() else: self.server.shut_down() self.server = None self.change_status('stopserver') self.callplugin('stop', self, 'server')
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setupUi(self) # self.clients = [] if sys.platform == 'darwin': self.menubar.setNativeMenuBar(False) # self.pc_names = {} # self.pc_names['localhost'] = 'Randy' self.server = Server(self) self.server.message.connect(self.receiveMessage) self.server.start() self.createActions() self.createTrayIcon() self.sendButton.clicked.connect(self.send_message) self.lineEdit.returnPressed.connect(self.send_message) self.actionQuit.triggered.connect(qApp.quit) self.trayIcon.setIcon(QIcon(':images/trash.svg')) self.trayIcon.show()
class World(DirectObject): def __init__(self): # Start our server up self.server = Server(9099, compress=True) # Create a task to print and send data taskMgr.doMethodLater(2.0, self.printTask, "printData") def printTask(self, task): # Print out results print "Received: " + str(self.server.getData()) print "Clients: " + str(self.server.getClients()) # Broadcast data to all clients self.server.broadcastData("Server's Data") return Task.again
def installApp(args, options): from j25.Configuration import Configuration if len(args) < 2: print >> sys.stderr, "you must supply the name of the app" exit(1) _checkProject(AUTO_PROJECT_DIRS) appName = args[1] print Server.getBanner() print COLOR_SEQ % 33 config = Configuration.load_file('server.ini', False) currentApps = eval(config.main.applications) assert isinstance(currentApps, list) if not appName in currentApps: currentApps.append(appName) config.main.applications = str(currentApps) Configuration.dump_file('server.ini', config) logger.info("\033[1;33mApplication %s added to project.\033[0m"% appName) else: logger.info("\033[1;33mApplication %s already installed in the project.\033[0m" % appName)
def client(address , cause_error=False,Username = '******'): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(address) Users = list(Server.Users) if cause_error : sock.sendall(Users[0][:-1]) return for Users in random.sample(Users,3) : sock.sendall(Users) print(Users.decode("utf-8"),Server.recv_until(sock,b'.').decode("utf-8")) sock.close()
def content(): yield "retry: 10000\r\n" while True: for tvshow in self.tvshowlist: data = 'id: progression\r\ndata: {\r\n' data += 'data: "' + unicode(tvshow.seriesid) + '":' + unicode(tvshow.get_progression(self.downloader)) + "\r\n" data += 'data: }\n\n' yield data #data = "id: server-time\r\ndata: " + time.ctime(os.path.getmtime(confPath+"/series.json")) + "\n\n" data = "id: server-time\r\ndata: " + Server.md5sum(confPath+"/series.json") + "\n\n" if self.testPath is not None: for testFile in self.testFiles: filename = os.path.join(self.testPath,testFile) if os.path.isfile(filename): if (testFile not in self.testFilesMd5.keys() or self.testFilesMd5[testFile] != Server.md5sum(filename)): data = "id: conf-test\r\ndata: " + testFile + "\n\n" self.testFilesMd5[testFile] = Server.md5sum(filename) yield data time.sleep(10)
def createNewServer(self, wherex, wherey, screenCoordinates = 1): self.fromClass = None self.toClass = None # try the global constraints... res = self.ASGroot.preCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return new_semantic_obj = Server(self) ne = len(self.ASGroot.listNodes["Server"]) if new_semantic_obj.keyword_: new_semantic_obj.keyword_.setValue(new_semantic_obj.keyword_.toString()+str(ne)) if screenCoordinates: new_obj = graph_Server(self.UMLmodel.canvasx(wherex), self.UMLmodel.canvasy(wherey), new_semantic_obj) else: # already in canvas coordinates new_obj = graph_Server(wherex, wherey, new_semantic_obj) new_obj.DrawObject(self.UMLmodel, self.editGGLabel) self.UMLmodel.addtag_withtag("Server", new_obj.tag) new_semantic_obj.graphObject_ = new_obj self.ASGroot.addNode(new_semantic_obj) res = self.ASGroot.postCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return res = new_semantic_obj.postCondition(ASGNode.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return self.mode=self.IDLEMODE if self.editGGLabel : self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE) else: self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE) return new_semantic_obj
def start_server(self): self.websocket_server = s = UserServer() host = Server.HOST_NAME port = 8080 for arg in sys.argv: if arg.startswith('--port='): port = int( arg.split('=')[-1] ) if arg.startswith('--ip='): a = arg.split('=') if len(a) == 2 and a[-1]: host = a[-1] Server.set_host_and_port( host, port ) s.initialize( listen_host=host, listen_port=port, read_callback=self.on_websocket_read_update, write_callback=self.on_websocket_write_update, new_client_callback=self.on_new_client, ) lsock = s.create_listener_socket() s.start_listener_thread()
Print.info(' `"\'') if args.usb: try: from nut import Usb except BaseException as e: Print.error('pip3 install pyusb, required for USB coms: ' + str(e)) nut.scan() Usb.daemon() if args.server: nut.initTitles() nut.initFiles() nut.scan() Server.run() if args.scan: nut.initTitles() nut.initFiles() nut.scan() if len(sys.argv) == 1: import server server.run() Status.close() except KeyboardInterrupt: Config.isRunning = False Status.close()
def checkProcessError(station, nErrors, lines, execTime=None): errCode = Server.RETRY_IT #errCode = Server.HAS_NO_DATA # Print messages from client # t1 = Logfile.MSG_TOKEN n = 2 * len(t1) for s in lines: if t1 in s: Logfile.add(s[n:-1]) Logfile.add(' ') # Check if errors in log # for lineNr in range(len(lines)): line = lines[lineNr] isEnd = False s = ' ' # UserWarning: MAX_REQUESTS exceeded - breaking current request loop -> retry access if 'MAX_REQUESTS' in line: errCode = Server.RETRY_IT s = 'UserWarning: MAX_REQUESTS exceeded - breaking current request loop' s += '(' + str(nErrors) + ')' elif 'deprecated' in line: s = ' ' # ignore ObsPyDeprecation Warning #15.7.2016 elif 'python' in line: s = line elif 'Signal handler' in line: errCode = Server.RETRY_IT s = line elif Server.CLIENT_ABORT_MSG in line: errCode = Server.RETRY_IT s = line elif HAS_DATA in line: # station has data errCode = Server.HAS_DATA isEnd = True elif 'Traceback' in line: # client aborted with traceback info sn = [] for i in range(0, 300): if lineNr + i >= len(lines): break #10.12.2015 if 'KeyboardInterrupt' in lines[lineNr + i]: sn = [] break #if lineNr+i >= len(lines): break #10.12.2015 sn.append(lines[lineNr + i]) #endfor if Server.checkIsTimeOut(station, sn): # Traceback shows timeout #if True: Logfile.error('Retry access later') errCode = Server.RETRY_IT else: # Traceback --> log Server.printLines(station, sn, onlyErrorLog=True) isEnd = True #endif if s != ' ': Server.printMsg(station, s) if isEnd: break #endwhile return errCode
# all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # Program entry point. import sys import Server # Default values if no cmd parameters are passed __address = 'localhost' __port = 1090 __startshell = False for arg in sys.argv: temp = str.split(arg, '=') if temp[0] == '-address': __address = temp[1] elif temp[0] == '-port': __port = temp[1] elif temp[0] == '-shell': __startshell = True Server.startserver(__address, int(__port), __startshell)
def test_users(self): u = Server.Users() self.assertTrue(isinstance(u.index(), list))
import rdd import Server Server.initServer() Server.initIO() def example(): import random data = [random.randint(66, 76) for i in xrange(100)] result = rdd.RDD(data, ctx=Server.Context).map(chr).map( lambda x: (x, 1)).reduceByKey(lambda x, y: x + y).collectAsMap() print result if __name__ == '__main__': example() while True: pass
import Server as server if __name__ == '__main__': print("Server Starting.....") server.run() # todo : run the anomaly and FIM code
def runSim(num_sim=20, train_samples=3000, test_samples=100, learning_rate=0.005, num_rounds=5, local_epochs=40, alpha=1, metric="Demographic disparity", adaptive_alpha=True, option="FairBatch", optimizer='adam', penalty=500, adjusting_rounds=10, adjusting_epochs=30, adjusting_alpha=0.7, epsilon=0.02, adaptive_lr=True, test_lr=0.01, test_rounds=3, lr_g=0.005, lr_d=0.01, init_epochs=50, lambda_d=0.8, bs_iter=10, alpha_decay=0.5, fixed_dataset=None, trace=False, client_split=((.5, .2), (.3, .4), (.2, .4))): """ Run simulations. """ test_acc, rd = [], [] start = time.time() if fixed_dataset: synthetic_info = dataGenerate(seed=fixed_dataset, train_samples=train_samples, test_samples=test_samples, client_split=client_split) for i in range(num_sim): seed = int(time.time() % 1000) print("| Simulation : %d | " % (i + 1)) print(" seed : %d -----" % seed) # generate the synthetic dataset if fixed_dataset == None: synthetic_info = dataGenerate(seed=seed, train_samples=train_samples, test_samples=test_samples) server = Server(logReg(num_features=3, num_classes=2, seed=seed), synthetic_info, seed=seed, ret=True, train_prn=False, metric=metric) # train the model with the synthetic dataset if option == 'unconstrained': test_acc_i, rd_i = server.Unconstrained( num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer) elif option == 'local zafar': test_acc_i, rd_i = server.LocalZafar(num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer, penalty=penalty, epsilon=epsilon) elif option == 'threshold adjusting': server.Unconstrained(num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer) test_acc_i, rd_i = server.ThresholdAdjust( num_rounds=adjusting_rounds, local_epochs=adjusting_epochs, learning_rate=adjusting_alpha, epsilon=epsilon) elif option == 'FairBatch': test_acc_i, rd_i = server.FairBatch(num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer, adaptive_alpha=adaptive_alpha, alpha=alpha) elif option == 'adversarial learning': server.Unconstrained(num_rounds=1, local_epochs=local_epochs, learning_rate=0.01, optimizer='adam') test_acc_i, rd_i = server.AdversarialLearning( num_rounds=num_rounds - 1, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer, epsilon=epsilon, alpha=alpha, adaptive_lr=adaptive_lr) elif option == 'bias correcting': test_acc_i, rd_i = server.BiasCorrecting( num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer, epsilon=epsilon, alpha=alpha) elif option == 'zafar': test_acc_i, rd_i = server.Zafar(test_rounds=test_rounds, test_lr=test_lr, num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer, penalty=penalty) elif option == 'ftrain': test_acc_i, rd_i = server.FTrain(num_rounds=num_rounds, local_epochs=local_epochs, init_epochs=init_epochs, lr_g=lr_g, lr_d=lr_d, lambda_d=lambda_d) elif option == 'bc-variant1': test_acc_i, rd_i = server.BCVariant1(num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer, epsilon=epsilon, alpha=alpha) elif option == 'bc-variant2': test_acc_i, rd_i = server.BCVariant2(num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer, epsilon=epsilon, bs_iter=bs_iter) elif option == 'bc-variant3': test_acc_i, rd_i = server.BCVariant3(num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer, epsilon=epsilon, alpha=alpha) elif option == 'fb-variant1': test_acc_i, rd_i = server.FBVariant1(num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer, alpha=alpha, trace=trace) elif option == 'fb-variant2': test_acc_i, rd_i = server.FBVariant2(num_rounds=num_rounds, local_epochs=local_epochs, learning_rate=learning_rate, optimizer=optimizer, alpha=alpha, alpha_decay=alpha_decay) else: print('Approach %s is not supported!' % option) return None test_acc.append(test_acc_i) rd.append(rd_i) if not trace: print(" Accuracy: %.2f%% %s: %.2f" % (test_acc_i * 100, metric, rd_i)) else: print(test_acc_i) print(rd_i) if trace: test_acc, rd = np.array(test_acc), np.array(rd) mean_acc, mean_rd = test_acc.mean(axis=0), rd.mean(axis=0) return mean_acc.tolist(), mean_rd.tolist() else: mean_acc, std_acc, mean_rd, std_rd = np.mean(test_acc), np.std( test_acc), np.mean(rd), np.std(rd) print("| Test Accuracy: %.3f(%.3f) | %s: %.3f(%.3f) |" % (mean_acc, std_acc, metric, mean_rd, std_rd)) print("| Time elapsed: %.2f seconds |" % (time.time() - start)) return mean_acc, std_acc, mean_rd, std_rd
def test_get_server_data(self,obj1): obj1.return_value = {'AA': 'EE'} self.assertEquals(Server.get_server_data(),{'AA': 'EE'} )
from Server import * from db_server_handlers.EchoHandler import * from db_server_handlers.RegistrationHandler import * from db_server_handlers.AuthorizationHandler import * from db_server_handlers.GetUserInfoHandler import * from db_server_handlers.SetUserInfoHandler import * from db_server_handlers.SetAvatarHandler import * from db_server_handlers.ReportGameHandler import * from db_server_handlers.GetUserCoinsInfoHandler import * from db_server_handlers.LeaderboardHandler import * from db_server_handlers.AddCoinsHandler import * from db_server_handlers.GetUsersInfoHandler import * from db_server_handlers.GetUsersCoinsInfoHandler import * from settings import * import sys server = Server(db_server[1]) server.add_handler(RegistrationHandler()) server.add_handler(AuthorizationHandler()) server.add_handler(GetUserInfoHandler()) server.add_handler(SetUserInfoHandler()) server.add_handler(SetAvatarHandler()) server.add_handler(ReportGameHandler()) server.add_handler(GetUserCoinsInfoHandler()) server.add_handler(LeaderboardHandler()) server.add_handler(AddCoinsHandler()) server.add_handler(GetUsersInfoHandler()) server.add_handler(GetUsersCoinsInfoHandler()) #log.startLogging(open('db_server.txt', 'w+')) server.launch()
class Game(object): """description of class""" #login 0 def __init__(self): self.input = Input() self.input.game = self self.output = Output() self.player = Player() self.server = Server() self.server.game = self self.locations = dict() self.event = multiprocessing.queues.SimpleQueue() def run(self, address, port): self.input.run() if (self.server.connect(address, port)): self.output.printConnectStatus(True) else: self.output.printConnectStatus(False) return self.server.run() self.loop() pass def loop(self): while (True): args = self.event.get() eventType = args[0] if (eventType == 0): # disconnect self.output.printDisconnect() self.server.stop() self.input.stop() break continue if (eventType == 1): # login self.server.sendLoginMsg(args[1]) continue if (eventType == 2): # move self.server.sendMoveMsg(args[1]) continue if (eventType == 3): # attack if (self.player.name != args[1]): self.server.sendAttackMsg(args[1]) continue if (eventType == 4): # speak self.server.sendSpeakMsg(args[1]) continue if (eventType == 5): # logout self.server.sendLogoutMsg() continue if (eventType == 6): # login reply code = args[1] hp = args[2] exp = args[3] x = args[4] y = args[5] if (code == 0): # sucess self.player.hp = hp self.player.exp = exp self.player.location.x = x self.player.location.y = y self.output.printLoginReply(True) pass elif (code == 1): self.output.printLoginReply(False) pass else: # undefined pass continue if (eventType == 7): # move notify player = args[1] x = args[2] y = args[3] hp = args[4] exp = args[5] self.locations[player] = Location(x, y) if (self.player.isVisible(self.locations[player])): self.output.printMoveNotify(player, self.locations[player].x, self.locations[player].y, hp, exp) continue if (eventType == 8): # attack notify attacker = args[1] victim = args[2] damage = args[3] hp = args[4] if (self.player.isVisible(self.locations.get(attacker)) and self.player.isVisible(self.locations.get(victim))): self.output.printAttackNotify(attacker, victim, damage, hp) continue if (eventType == 9): # speak notify player = args[1] msg = args[2] self.output.printSpeakNotify(player, msg) continue if (eventType == 10): # logout notify name = args[1] self.locations.pop(name) self.output.printLogoutNotify(name) continue if (eventType == 11): # invalid state code = args[1] self.output.printInvalidState(code) continue pass def stop(self): self.event.put((0, )) # called by input def login(self, name): self.event.put((1, name)) def move(self, direction): self.event.put((2, direction)) def attack(self, victim): self.event.put((3, victim)) def speak(self, msg): self.event.put((4, msg)) def logout(self): self.event.put((5, )) # called by server.recv def onLoginReply(self, code, x, y, hp, exp): self.event.put((6, code, x, y, hp, exp)) pass def onMoveNotify(self, name, x, y, hp, exp): self.event.put((7, name, x, y, hp, exp)) pass def onAttackNotify(self, attacker, victim, damaged, hp): self.event.put((8, attacker, victim, damaged, hp)) pass def onSpeakNotify(self, player, msg): self.event.put((9, player, msg)) pass def onLogoutNotify(self, name): self.event.put((10, name)) pass def onInvalidState(self, code): self.event.put((11, code)) pass
def getDownload(request, response, start=None, end=None): try: nsp = Nsps.getByTitleId(request.bits[2]) response.attachFile(nsp.titleId + '.nsp') if len(request.bits) >= 5: start = int(request.bits[-2]) end = int(request.bits[-1]) #chunkSize = 0x1000000 chunkSize = 0x400000 with open(nsp.path, "rb") as f: f.seek(0, 2) size = f.tell() if 'Range' in request.headers: start, end = request.headers.get('Range').strip().strip( 'bytes=').split('-') if end == '': end = size - 1 else: end = int(end) + 1 if start == '': start = size - end else: start = int(start) if start >= size or start < 0 or end <= 0: return Server.Response400( request, response, 'Invalid range request %d - %d' % (start, end)) response.setStatus(206) else: if start == None: start = 0 if end == None: end = size if end >= size: end = size if end <= start: response.write(b'') return print('ranged request for %d - %d' % (start, end)) f.seek(start, 0) response.setMime(nsp.path) response.setHeader('Accept-Ranges', 'bytes') response.setHeader('Content-Range', 'bytes %s-%s/%s' % (start, end - 1, size)) response.setHeader('Content-Length', str(end - start)) #Print.info(response.headers['Content-Range']) response.sendHeader() if not response.head: size = end - start i = 0 status = Status.create( size, 'Downloading ' + os.path.basename(nsp.path)) while i < size: chunk = f.read(min(size - i, chunkSize)) i += len(chunk) status.add(len(chunk)) if chunk: pass response.write(chunk) else: break status.close() except BaseException as e: Print.error('NSP download exception: ' + str(e)) if response.bytesSent == 0: response.write(b'')
def serveFile(response, path, filename=None, start=None, end=None): try: if start is not None: start = int(start) if end is not None: end = int(end) if not filename: filename = os.path.basename(path) response.attachFile(filename) chunkSize = 0x400000 with open(path, "rb") as f: f.seek(0, 2) size = f.tell() if start and end: if end == None: end = size - 1 else: end = int(end) if start == None: start = size - end else: start = int(start) if start >= size or start < 0 or end <= 0: return Server.Response400( request, response, 'Invalid range request %d - %d' % (start, end)) response.setStatus(206) else: if start == None: start = 0 if end == None: end = size if end >= size: end = size if end <= start: response.write(b'') return print('ranged request for %d - %d' % (start, end)) f.seek(start, 0) response.setMime(path) response.setHeader('Accept-Ranges', 'bytes') response.setHeader('Content-Range', 'bytes %s-%s/%s' % (start, end - 1, size)) response.setHeader('Content-Length', str(end - start)) response.sendHeader() if not response.head: size = end - start i = 0 status = Status.create(size, 'Downloading ' + os.path.basename(path)) while i < size: chunk = f.read(min(size - i, chunkSize)) i += len(chunk) status.add(len(chunk)) if chunk: pass response.write(chunk) else: break status.close() except BaseException as e: Print.error('File download exception: ' + str(e)) if response.bytesSent == 0: response.write(b'')
def nutThread(): Server.run()
def test_server(self, obj1): obj1.return_value = "I am server" self.assertEquals(Server.server(), "I am server", "Look at the page server")
import logging import ConfigParser import sys sys.path.append("logic") sys.path.append("..") import Server import log if __name__ == '__main__': subtype = 1 # 默认为1 if len(sys.argv) == 2: subtype = int(sys.argv[1]) log.initLog("srs", subtype) logging.info("subytype=%d" % subtype) conf = ConfigParser.ConfigParser() conf.read('config.ini') svr = Server.Server() try: svr.init(subtype, conf) svr.run() except BaseException as e: logging.exception(e) svr.stop() else: logging.error("Crash Unknown!") svr.stop()
def test_get_static(self,obj1): obj1.return_value = 'ERROR get_static' self.assertEquals(Server.get_static(), "ERROR get_static")
from threading import Thread from Server import * from Client import * def manual(): print('./chat --server -p <PORT>') print('./chat --client -p <PORT> <IP>') if __name__ == "__main__": if len(sys.argv) > 1: if len(sys.argv) == 4: if sys.argv[1] == '--server' and sys.argv[2] == '-p': server = Server(int(sys.argv[3])) server.iniciar_servidor() else: manual() elif len(sys.argv) == 5: if sys.argv[1] == '--client'and sys.argv[2] == '-p': nome = str(input('coloque um nome de usuario para a conversa -> ')) clinte = Client(nome, int(sys.argv[3]), str(sys.argv[4])) clinte.iniciar_cliente() else: manual() else: manual() else: manual()
def saveSettings(self): server = Server() server.setName(self.name.originalText()) server.setHostIP(self.hostIP.originalText()) server.setPort(str(self.port.value())) server.setSwitches(str(self.switches.originalText())) server.setLogin(self.login.originalText()) if (Qt.Checked == self.passCheckbox.checkState()): server.setAuthenticationType(AUTH_TYPE_PASSWORD) server.setPassword(self.password.originalText()) elif (Qt.Checked == self.keyCheckbox.checkState()): server.setAuthenticationType(AUTH_TYPE_PRIVATE_KEY) server.setKeyPath(self.keyFilePath.originalText()) else: server.setAuthenticationType(AUTH_TYPE_NONE) if self.isEdit: self.parent.saveServer(self.oldName, server) else: self.parent.addServer(server)
required='True') parser.add_argument( '--ranking', type=bool, choices=[True, False], help='"True" for getting the rank for every intent, ' '"False for getting just the response corresponding to the predicted intent' ) args = parser.parse_args() if args.mode == "cli": while True: sentence = prompt(u'>') if sentence == "exit": break ranking = False if args.ranking: ranking = True ovation_intent = intent_classify.intent_classify( ranking=ranking, test_input=sentence, model_type='blstm') rasa_intent = intent_classify.intent_classify(ranking=ranking, test_input=sentence, model_type='rasa') print("ovation> " + intent_classify.get_response(ovation_intent)) print("rasa> " + intent_classify.get_response(rasa_intent)) if args.mode == "web": Server.init()
from threading import * import Server import Screen import Map screen = Screen.Screen(800, 800, 300, 300) mmap = Map.Map(300, 300, 5) pos = [0, 0, 0] measurements = [] server = Server.Server('', 8888) server.listen(1) connaddr = server.accept() def thrd(conn): ret = server.handleCommand(conn) while ret: if ret[0] == 'T': pos[0] = pos[0] + ret[1][0] pos[1] = pos[1] + ret[1][1] elif ret[0] == 'R': pos[2] = pos[2] + ret[1][0] elif ret[0] == 'M': measurements.append(ret[1]) server.threadFunc(thrd, (connaddr[0], ))
#indication if number of locations reached zero if(Number==0): LED.On1() else: LED.Off1() #checking mode of operation mode = SW.GetToggleValue() #Manual mode if mode==1: #initializing 3 interrupts INT.Init(Inc_ISR, Dec_ISR, Res_ISR) print('Manual') #establishing connection with server message = Server.listen() #taking action according to message recieved from server if(message.lower()=='inc'): Number+=1 if(message.lower()=='dec'): Number-=1 if(message.lower()=='res'): Number=0 SSD.SendNumber(Number) #Automatic mode else: print('Automatic') #disabling interrupt INT.Disable()
return db_conf.masterDbConn if __name__ == "__main__": CmdArgs = sys.argv if len(CmdArgs) > 1: ################################################################################# # Check whether there are any command line arguments. In case there # # are any, process them. Needs to be looked into once the arguments # # are considered. # ################################################################################# pass ##################################################################################### # Load the configuration file, db configuration file, language # # configuration file, test the database, and if all operations # # are successful, start the server with the configurations specified # ##################################################################################### try: config = loadConfig() print(config) chLang = loadLanguage(config["lang"]) dbConf = loadDbConf() dbConn = DbController(dbConf) dbCheck = True#dbConn.testDb() if not dbCheck: raise DbException else: #server = Server(config, dbConf, chLang) Server.startServer() except DbException as dbError: print(chLang["MSG0001"]) comm = Communication(chLang)
def start_server(): Server.main()
def test_groups(self): u = Server.Groups() self.assertTrue(isinstance(u.index(), list))
from Server import * import lobby_server_handlers.AuthorizationHandler import chat_server_handlers.ChatHandler import lobby_server_handlers.factory_utils import settings server = Server(settings.chat_server[1]) server.add_handler( lobby_server_handlers.AuthorizationHandler.AuthorizationHandler()) server.add_handler(chat_server_handlers.ChatHandler.ChatHandler()) server.setLostConnectionFunc( lobby_server_handlers.factory_utils.lostConnectionFunc) log.startLogging(open('chat_server.txt', 'w+')) server.launch()
def setup_server(port): global s s = Server.Server('', port) s.establishConnection()
import Server import Notification if __name__ == "__main__": Server.main() Notification.notificatioMain()
def printMsg(station, text=' '): try: Server.printMsg(Logfile.MSG_TOKEN + station, text) except: dummy = 1
def __init__(self): # Start our server up self.server = Server(9099, compress=True) # Create a task to print and send data taskMgr.doMethodLater(2.0, self.printTask, "printData")
def run_parallel(options): ''' Starts station search procedure :type options: instance :param options: parameter to initialize the networklist class ''' isClient = (options.args != None) if not init(options): return False if isClient: # Run client clt = StationListClient(options) clt.run() return True else: # Run server # Create directory for clients # clientDir = os.path.join(options.evpath, 'keyfiles-' + str(time.time())) Logfile.add('Create keyfile directory ', clientDir, ' ') create_dir(clientDir) # Build network list # C = config.Config(options.evpath) Origin = C.parseConfig('origin') Conf = Globals.ConfigDict checkConfigFile(Conf) globalCfg = ConfigObj(dict=Conf) originCfg = ConfigObj(dict=Origin) ot = originCfg.Time() # str(Origin['time']) elat = originCfg.lat() # Origin['lat'] elon = originCfg.lon() # Origin['lon'] minDist = globalCfg.Distance('mindist') # Conf ['mindist'] maxDist = globalCfg.Distance('maxdist') # Conf ['maxdist'] duration = globalCfg.Duration() # Conf ['duration'] paramList = [ot, maxDist, minDist, elat, elon] BL = [] if 'blacklist' in Conf: K = (Conf['blacklist']).split(',') BL = ['# Network Code'] BL.extend(K) T = NetworkList(ot, elat, elon, minDist, maxDist, duration, blacklist=BL, mail=Conf['mail']) SERVER_NAME = 'network' # Handle Iris networks # inetworks = T.getIRISList() #inetworks = ['BF'] if len(inetworks) == 0: Logfile.error('No iris networks found') else: args = Server.joinClientArgs([IRIS_TAG, clientDir], paramList) ctrl = Server.ServerCtrl(nRetries=1, nParallel=1, waitTime=1.0, printStat=False) srv = Server.ServerBase(SERVER_NAME, checkProcessError, ctrl) #if WINDOWS: srv.control.ClientProc = MainProc if not srv.run(inetworks, args): return False #endif # Handle Geofon networks # gnetworks = T.getWEBDCList() #gnetworks = ['AF'] #gnetworks = ['FR'] #gnetworks = [] if len(gnetworks) == 0: Logfile.error('No geofon networks found') else: # Access network infos now from Geofo # args = Server.joinClientArgs([GEOFON_TAG, clientDir], paramList) ctrl = Server.ServerCtrl(nRetries=4, nParallel=1, waitTime=2.0, printStat=False) srv = Server.ServerBase(SERVER_NAME, checkProcessError, ctrl) #if WINDOWS: srv.control.ClientProc = MainProc if not srv.run(gnetworks, args): return False #endif # Print statistic nIres = len(inetworks) nWebDC = len(gnetworks) nAll = nIres + nWebDC if nIres != 0: Logfile.add(' ', 'Processed ' + str(nIres) + ' IRES networks') if nWebDC != 0: Logfile.add('Processed ' + str(nWebDC) + ' WEBDC networks') if nAll == 0: return Logfile.error('No networks found') if nIres == 0: err = 'No IRIS network found' elif nWebDC == 0: err = 'No WEBDC network found' else: err = None if err != None: Logfile.add(err) # showNextStep # evpath = options.evpath.split('/')[-1] keyfoldername = clientDir.split('/')[-1] Logfile.add(' ', 'NEXT PROCESSING STEP:', ' ') Logfile.add(' 1) change keyfolder value in global.conf to ' + keyfoldername) Logfile.add(' 2) python arraytool.py getdata ' + evpath, ' ') return True
def main(): db = DatabaseHelper() server = Server("test", "test", "test", "test") blacklist = db.add_blacklist(server, "1.1.1.1")
def test_worker(self, obj1): obj1.return_value = "SAVE" self.assertEquals(Server.worker(), "SAVE")
def test_create(self): Server.delete("h") self.assertEqual(Server.success, Server.create("h", "h")) self.assertEqual("Fail! h : h", Server.create("h", "h"))
def test_get_js(self,obj1): obj1.return_value = 'ERROR get_js' self.assertEquals(Server.get_js(), "ERROR get_js")
def test_read(self): Server.delete("h") self.assertEqual("Fail! Record with key \"h\" was not found!", Server.read("h")) Server.create("h", "h") self.assertEqual("h : h", Server.read("h")) return
import sys from Server import * if __name__ == '__main__': ServerId = int(sys.argv[1]) ServerConfig = "config.json" ClientId = 111 ClientConfig = 10000 server = Server(ServerId, ServerConfig, ClientId, ClientConfig) server.run()
def test_delete(self): Server.delete("h") self.assertEqual("Fail! Record with key \"h\" was not found!", Server.delete("h")) Server.create("h", "ha") self.assertEqual(Server.success, Server.delete("h"))
def startGame(): global server, client, enmid, maxenemy, tillboss, enmyhealth, endgame, bosshow, enmyhealth, localhero, \ remotehero, boss, enemygroup, herogroup, herobgroup, bossbgroup, blastgroup, bonusgroup bosshow = False endgame = 'game' maxenemy = 5 tillboss = 100 enmyhealth = 100 boss = BossClass() localhero = LocalHeroClass() herogroup = pygame.sprite.Group(localhero) bossgroup = pygame.sprite.Group(boss) herobgroup = pygame.sprite.Group() bossbgroup = pygame.sprite.Group() enemygroup = pygame.sprite.Group() blastgroup = pygame.sprite.Group() bonusgroup = pygame.sprite.Group() if server or client: tillboss = 200 remotehero = RemoteHeroClass() herogroup.add(remotehero) if server: server = Server.ServerClass(localhero, remotehero, enemygroup, boss) if client: client = Client.ClientClass(localhero, remotehero, enemygroup, boss, server_addr) pygame.mouse.set_visible(0) enmid = [] for i in range(maxenemy): enmid.append(i) while True: #---------------------------------------- main game loop ----------------------------------------------- for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() makenemy() herofire() # fill screen SCREEN.fill(BACK) # update & draw sprites bgroundgroup.update() bgroundgroup.draw(SCREEN) enemygroup.update() enemygroup.draw(SCREEN) bonusgroup.update() bonusgroup.draw(SCREEN) herobgroup.update() herobgroup.draw(SCREEN) herogroup.update() herogroup.draw(SCREEN) if bosshow == True: bossgroup.update() bossbgroup.update() bossgroup.draw(SCREEN) bossbgroup.draw(SCREEN) bossHealthMeter() bosscollide() blastgroup.update() blastgroup.draw(SCREEN) gameinfo() enemycollide() herocollide() if client or server: if localhero.enmkiled + remotehero.enmkiled > tillboss: bosshow = True else: if localhero.enmkiled > tillboss: bosshow = True if endgame == 'win': gameover(True) elif endgame == 'loose': gameover(False) # Server if server: server.receive() server.send() # Client elif client: client.receive() client.send() cakemake() pygame.display.update() fpsClock.tick(FPS)
def Timer_ISR(): #check for flag to perform suitable write operation global write_flag if(write_flag==1): Server.write_dec() elif(write_flag==2): Server.write_inc()
import sys log.startLogging(sys.stdout) if len(sys.argv) != 4: print("Usage: python query.py <bootstrap ip> <bootstrap port> <key>") sys.exit(1) ip = sys.argv[1] port = int(sys.argv[2]) key = sys.argv[3] print("Getting %s (with bootstrap %s:%i)" % (key, ip, port)) def done(result): print("Key result:") print(result) reactor.stop() def bootstrapDone(found, server, key): if len(found) == 0: print("Could not connect to the bootstrap server.") reactor.stop() server.get(key).addCallback(done) server = Server() server.listen(port) server.bootstrap([(ip, port)]).addCallback(bootstrapDone, server, key) reactor.run()
#!/usr/bin/env python3 import pymongo from datetime import datetime, timedelta import Envelope import Server server = Server.Server() import bson class ModList(object): def __init__(self): MAP_FUNCTION = bson.code.Code(""" function(){ if (this.envelope.payload.class == 'usertrust') { var timestamp = Number(new Date()/1000); mtime = this.envelope.local.time_added; // 60 * 60 * 24 * 7 * 26 = 15724800 if ( (mtime + 15724800) > timestamp ) { var topic = this.envelope.payload.topic; var moderator = this.envelope.payload.trusted_pubkey; var trust = this.envelope.payload.trust; emit({topic:topic,moderator:moderator},{trust:trust,count:1}); } } } """)