def start_client(): if sys.platform == "win32": gobject.threads_init() else: gtk.gdk.threads_init() client() gtk.main()
def test_multi_client(self): print "\n[Info] ######[INTEGRATION TEST MULTI CLIENT SINGLE SERVER TEST]#### \n\n" # generate a lock file for each client CMD_FILES = ["client_0.txt", "client_1.txt"] LOCKS = 10 make_simple_file(LOCKS, CMD_FILES[0]) make_simple_file(LOCKS, CMD_FILES[1]) # connect to the first server in the list only # connect to the first server in the list port = self.server_list[0]["client_port"] host = self.server_list[0]["host"] assert((int(port) % 2) == 0) # initialize the clients cli0 = client.client(CMD_FILES[0], host, port, 0) cli0.c_process.join() cli1 = client.client(CMD_FILES[1], host, port, 0) failed = False try: cli0.c_process.join() cli1.c_process.join() except Exception, e: cli0.c_process.terminate() cli1.c_process.terminate() failed = True
def test_non_ascii(): """Test if echo is same text that was sent if message contains non-ascii character""" message = u"¡¢" # hasattr() determines the python version, if the string has the ability # to be decoded, then we are running python2 and requires the string to be # decoded and encoded. if hasattr(message, "decode"): with pytest.raises(TypeError): assert client.client("GET " + message + " HTTP/1.1\r\nHost: localhost\r\n\r\n").startswith(HTTP_RESPONSE_CODE).decode('utf-8') else: client.client("GET " + message + " HTTP/1.1\r\nHost: localhost\r\n\r\n").startswith("HTTP/1.1 404")
def test_multi_server(self): print "\n[Info] ##########[INTEGRATION TEST MULTIPLE CLIENT MULTIPLE SERVER TEST]########## \n\n" LOCKS = 100 # generate the lock files for i in range(0, len(self.server_list)): filename = "client_" + str(i) + ".txt" make_simple_file(LOCKS, filename) # instantiate a client to each server client_list = [] client_files = [] for i in range(0, len(self.server_list)): port = self.server_list[i]["client_port"] host = self.server_list[i]["host"] assert((int(port) % 2) == 0) cli = client.client( "client_" + str(i) + ".txt", host, port, len(client_list)) client_list.append(cli) client_files.append("client_" + str(i) + ".txt") # join each client failed = False for c in client_list: try: c.c_process.join() except Exception, e: c.terminate() failed = True
def test_lock_contention(self): print "\n[Info] #######[INTEGRATION TEST MULTIPLE CLIENT MULTIPLE SERVER TEST]########## \n\n" # generate a contentious lock file f = open("contention_test.txt", "w+") for i in range(0, 50): f.write("lock 1\n") f.write("unlock 1\n") f.close() # instantiate each client with a copy of the contentious lock file client_list = [] client_files = [] for i in range(0, len(self.server_list)): port = self.server_list[i]["client_port"] host = self.server_list[i]["host"] assert((int(port) % 2) == 0) cli = client.client("contention_test.txt", host, port, len(client_list)) client_list.append(cli) client_files.append("contention_test.txt") # join each client failed = False for c in client_list: try: c.c_process.join() except Exception, e: c.terminate() failed = True
def get_normalized_keywords(bibc): """ For a given publication, construct a list of normalized keywords of this publication and its references """ keywords = [] headers = {"X-Forwarded-Authorization": request.headers.get("Authorization")} q = "bibcode:%s or references(bibcode:%s)" % (bibc, bibc) # Get the information from Solr solr_args = {"wt": "json", "q": q, "fl": "keyword_norm", "rows": current_app.config["RECOMMENDER_MAX_HITS"]} response = client().get(current_app.config.get("RECOMMENDER_SOLR_PATH"), params=solr_args, headers=headers) if response.status_code != 200: return {"Error": "There was a connection error", "Error Info": response.text, "Status Code": "500"} resp = response.json() for doc in resp["response"]["docs"]: try: keywords += map(lambda a: a.lower(), doc["keyword_norm"]) except: pass keywords = filter(lambda a: a in ASTkeywords, keywords) if len(keywords) == 0: return { "Error": "Unable to get results!", "Error Info": "No or unusable keywords in data", "Status Code": "200", } else: return {"Results": keywords}
def status(self, match, ignored, clean, unknown=True): files = match.files() if '.' in files: files = [] if self._inotifyon and not ignored: cli = client(ui, repo) try: result = cli.statusquery(files, match, False, clean, unknown) except QueryFailed, instr: ui.debug(str(instr)) # don't retry within the same hg instance inotifydirstate._inotifyon = False pass else: if ui.config('inotify', 'debug'): r2 = super(inotifydirstate, self).status( match, False, clean, unknown) for c,a,b in zip('LMARDUIC', result, r2): for f in a: if f not in b: ui.warn('*** inotify: %s +%s\n' % (c, f)) for f in b: if f not in a: ui.warn('*** inotify: %s -%s\n' % (c, f)) result = r2 return result
def clone_mode(): set_title('Clone') ip = raw_input(colors.HEADER + 'ip: ' + colors.ENDC) if ip == 'exit': return ip = swap_vars(ip) s = client(ip, PORT, 5) try: if s.connect() == False: print(colors.FAIL + ('Failed to connect to: %s' % ip) + colors.ENDC) return except: print(colors.FAIL + ('Failed to connect to: %s' % ip) + colors.ENDC) return print('connected') top = raw_input(colors.HEADER + 'top: ' + colors.ENDC) set_title('Cloning') clone_from(top, s) print('done!') set_title('Clone Complete')
def get(self): solr_args = dict(request.args) solr_args["rows"] = min(int(solr_args.get("rows", [current_app.config.get("VIS_SERVICE_AN_MAX_RECORDS")])[0]), current_app.config.get("VIS_SERVICE_AN_MAX_RECORDS")) solr_args['fl'] = ['author_norm', 'title', 'citation_count', 'read_count','bibcode', 'pubdate'] solr_args['wt'] ='json' headers = {'X-Forwarded-Authorization' : request.headers.get('Authorization')} response = client().get(current_app.config.get("VIS_SERVICE_SOLR_PATH") , params = solr_args, headers=headers) if response.status_code == 200: full_response = response.json() else: return {"Error": "There was a connection error. Please try again later", "Error Info": response.text}, response.status_code #get_network_with_groups expects a list of normalized authors author_norm = [d.get("author_norm", []) for d in full_response["response"]["docs"]] author_network_json = author_network.get_network_with_groups(author_norm, full_response["response"]["docs"]) if author_network_json: return {"msg" : {"numFound" : full_response["response"]["numFound"], "start": full_response["response"].get("start", 0), "rows": int(full_response["responseHeader"]["params"]["rows"]) }, "data" : author_network_json}, 200 else: return {"Error": "Empty network."}, 200
def status(self, match, subrepos, ignored, clean, unknown): files = match.files() if "." in files: files = [] if self._inotifyon and not ignored and not subrepos and not self._dirty: cli = client(ui, repo) try: result = cli.statusquery(files, match, False, clean, unknown) except QueryFailed, instr: ui.debug(str(instr)) # don't retry within the same hg instance inotifydirstate._inotifyon = False pass else: if ui.config("inotify", "debug"): r2 = super(inotifydirstate, self).status(match, [], False, clean, unknown) for c, a, b in zip("LMARDUIC", result, r2): for f in a: if f not in b: ui.warn("*** inotify: %s +%s\n" % (c, f)) for f in b: if f not in a: ui.warn("*** inotify: %s -%s\n" % (c, f)) result = r2 return result
def genericClient(req,reqHanderInstance=None): global reqNumber, getReqNumber reqCmd='.'.join(req) return '*** Request Number = {0} ***\n Got a client init request - {1}'.format(reqNumber,reqCmd) myClient=client() ret,msg=myClient.initReq(req,reqHanderInstance) return msg
def get_normalized_keywords(bibc): ''' For a given publication, construct a list of normalized keywords of this publication and its references ''' keywords = [] headers = {'X-Forwarded-Authorization': request.headers.get('Authorization')} q = 'bibcode:%s or references(bibcode:%s)' % (bibc, bibc) # Get the information from Solr solr_args = {'wt': 'json', 'q': q, 'fl': 'keyword_norm', 'rows': current_app.config['RECOMMENDER_MAX_HITS']} response = client().get( current_app.config.get("RECOMMENDER_SOLR_PATH"), params=solr_args, headers=headers) if response.status_code != 200: return {"Error": "There was a connection error in Solr request (normalized keywords)", "Reponse Code": response.status_code, "Error Info": response.text, "Status Code": "500"} resp = response.json() for doc in resp['response']['docs']: try: keywords += map(lambda a: a.lower(), doc['keyword_norm']) except: pass keywords = filter(lambda a: a in ASTkeywords, keywords) if len(keywords) == 0: return {"Error": "Unable to get results!", "Error Info": "No or unusable keywords in data", "Status Code": "200"} else: return {"Results": keywords}
def test_system(cli_request, msg): """Test that messages to server are returned as the same message.""" from client import client response = client(cli_request) response_parts = response.split('\r\n') assert response_parts[0] == msg assert '' in response_parts
def get_meta_data(**args): """ Get the meta data for a set of bibcodes """ data_dict = {} # This information can be retrieved with one single Solr query # (just an 'OR' query of a list of bibcodes) bibcodes = [bibcode for (bibcode, score) in args['results']] list = " OR ".join(map(lambda a: "bibcode:%s" % a, bibcodes)) q = '%s' % list # Get the information from Solr headers = {'X-Forwarded-Authorization': request.headers.get('Authorization')} params = {'wt': 'json', 'q': q, 'fl': 'bibcode,title,first_author', 'rows': current_app.config.get('CITATION_HELPER_MAX_HITS')} response = client().get( current_app.config.get('CITATION_HELPER_SOLR_PATH'), params=params, headers=headers) if response.status_code != 200: return {"Error": "Unable to get results!", "Error Info": response.text, "Status Code": response.status_code} resp = response.json() # Collect meta data for doc in resp['response']['docs']: title = 'NA' if 'title' in doc: title = doc['title'][0] author = 'NA' if 'first_author' in doc: author = "%s et al." % doc['first_author'] data_dict[doc['bibcode']] = {'title': title, 'author': author} return data_dict
def get(self): solr_args = dict(request.args) if 'max_groups' in solr_args: del solr_args['max_groups'] solr_args["rows"] = min(int(solr_args.get("rows", [current_app.config.get("VIS_SERVICE_PN_MAX_RECORDS")])[0]), current_app.config.get("VIS_SERVICE_PN_MAX_RECORDS")) solr_args['fl'] = ['bibcode,title,first_author,year,citation_count,read_count,reference'] solr_args['wt'] ='json' headers = {'X-Forwarded-Authorization' : request.headers.get('Authorization')} response = client().get(current_app.config.get("VIS_SERVICE_SOLR_PATH") , params = solr_args, headers=headers) if response.status_code == 200: full_response = response.json() else: return {"Error": "There was a connection error. Please try again later", "Error Info": response.text}, response.status_code #get_network_with_groups expects a list of normalized authors data = full_response["response"]["docs"] paper_network_json = paper_network.get_papernetwork(data, request.args.get("max_groups", current_app.config.get("VIS_SERVICE_PN_MAX_GROUPS"))) if paper_network_json: return {"msg" : {"numFound" : full_response["response"]["numFound"], "start": full_response["response"].get("start", 0), "rows": int(full_response["responseHeader"]["params"]["rows"]) }, "data" : paper_network_json}, 200 else: return {"Error": "Empty network."}, 200
def capture_mode(): set_title('Connect') ip = raw_input(colors.HEADER + 'ip: ' + colors.ENDC) if ip == 'exit': return ip = swap_vars(ip) s = client(ip, PORT, 5) try: if s.connect() == False: print(colors.FAIL + ('Failed to connect to: %s' % ip) + colors.ENDC) return except: print(colors.FAIL + ('Failed to connect to: %s' % ip) + colors.ENDC) return set_title('Capturing') print(colors.OKGREEN + 'capturing mouse position: control+c to exit' + colors.ENDC) while 1: pos = get_mouse_pos() #translate y coord for windows pos.Y = abs(900 - pos.Y) s.send('mpos&%d&%d' % (pos.X, pos.Y)) #swallow s.recv()
def decode(self): empty_hypo = Hypothesis() empty_hypo.words_covered = [0 for x in range(self.input_length)] self.m_stacks[0].stack.append(empty_hypo) self.best_score[0] = empty_hypo.score for i in range(len(self.m_stacks)): current_stack = self.m_stacks[i].stack if i!=0: #sending batch of sentences to the server for dep parsing to_send = json.dumps(map(lambda x: {'uuid':x.uuid,'sentence':x.phrase_pair.get_target()},current_stack)) responset = json.loads(json.loads(client(to_send))["result"]) for hyp in current_stack: hyp.def_info = responset['response'][hyp.uuid] print hyp.def_info print 'current stack...%d::elements in it...%d' %(i,len(current_stack)) for j in range(len(current_stack)): current_hypo = current_stack[j] self.expand(current_hypo)
def make_request(request, service_string, required_fields): bibcodes = [] query = None if 'bibcodes' in request.json: if 'query' in request.json and request.json['query']: raise QueryException('Cannot send both bibcodes and query') bibcodes = map(str, request.json['bibcodes']) if len(bibcodes) > current_app.config.get("VIS_SERVICE_" + service_string + "_MAX_RECORDS"): raise QueryException('No results: number of submitted bibcodes exceeds maximum number') elif len(bibcodes) == 0: raise QueryException('No bibcodes found in POST body') #we have bibcodes, which might be up to 1000 ( too long for solr using GET), #so use bigquery headers = { 'X-Forwarded-Authorization' : request.headers.get('Authorization'), 'Content-Type': 'big-query/csv', } big_query_params = {'q':'*:*', 'wt':'json', 'fl': required_fields, 'fq': '{!bitset}', 'rows' : len(bibcodes)} response = client().post( current_app.config.get("VIS_SERVICE_BIGQUERY_PATH"), params = big_query_params, headers = headers, data = 'bibcode\n' + '\n'.join(bibcodes) ) return response #this shouldnt be advertised, it's there only as a convenience for Bumblebee elif 'query' in request.json: try: solr_args = json.loads(request.json["query"][0]) except Exception: raise QueryException('couldn\'t decode query, it should be json-encoded before being sent (so double encoded)') solr_args["rows"] = min(int(solr_args.get("rows", [current_app.config.get("VIS_SERVICE_AN_MAX_RECORDS")])[0]), current_app.config.get("VIS_SERVICE_AN_MAX_RECORDS")) solr_args['fl'] = required_fields solr_args['wt'] ='json' headers = {'X-Forwarded-Authorization' : request.headers.get('Authorization')} response = client().get(current_app.config.get("VIS_SERVICE_SOLR_PATH"), params = solr_args, headers = headers ) return response else: #neither bibcodes nor query were provided raise QueryException('Nothing to calculate network!')
def get(self, cn): with self.lock: if self.list.has_key(cn): return self.list[cn] else: c = client() self.list[cn] = c return c
def main(): ip = raw_input(colors.HEADER + 'ip: ' + colors.ENDC) if ip == 'exit': return 0 ip = swap_vars(ip) s = client(ip, PORT, 5) try: if s.connect() == False: print(colors.FAIL + ('Failed to connect to: %s' % ip) + colors.ENDC) return 1 except: print(colors.FAIL + ('Failed to connect to: %s' % ip) + colors.ENDC) return 1 s.send('usr') user = s.recv() #swallow s.recv() set_title(user) print(colors.OKGREEN + ('connected to %s' % ip) + colors.ENDC) while 1: cmd = raw_input(colors.HEADER + user + ': ' + colors.ENDC) if cmd == 'exit': break elif cmd.startswith('let'): print(colors.WARNING + add_var(cmd) + colors.ENDC) continue elif cmd == 'vars': print_vars() continue elif cmd == 'vload': load_vars() continue elif cmd == 'vsave': save_vars() continue elif cmd == 'vreset': variables = BACKUPVARS continue cmd = swap_vars(cmd) set_var_args(cmd) s.send(cmd) response = s.recv() if response == 'waiting': continue else: print(colors.OKBLUE + response + colors.ENDC) #swallow waiting message s.recv() if s.connected == True: s.disconnect()
def test_client_connection_loopback(self): # file initialization self.test_file_name = "test_file.txt" self.test_file = open(self.test_file_name, "w+") self.test_file.write("lock 1\n") self.test_file.close() # Tests if connecting to the server works and # that loopback works appropriately # start up the test loopback server SERVER_HOSTNAME = 'localhost' SERVER_PORT = 9000 print "[Lock Client Test] Attempt to open socket for server..." server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((SERVER_HOSTNAME, SERVER_PORT)) server_socket.listen(10) print "[Lock Client Test] Launched server socket..." # instantiate a client self.client_id = 239 self.client = client.client( self.test_file_name, 'localhost', 9000, self.client_id) print "[Lock Client Test] Client initialized to server..." # allow server socket to accept connection from the client (connection_socket, connection_address) = server_socket.accept() print "[Lock Client Test] Client connected to server..." # Server receives and unpickles command rmsgs = connection_socket.recv(1024) rmsg = pickle.loads(rmsgs) assert isinstance(rmsg, message.message) assert rmsg.value.command_type == command.COMMAND_TYPE.LOCK assert rmsg.value.resource_id == 1 assert rmsg.client_id == self.client_id assert rmsg.msg_type == message.MESSAGE_TYPE.CLIENT # loopback the data to the client with a modified CLIENT ACK type rmsg.msg_type = message.MESSAGE_TYPE.CLIENT_ACK connection_socket.send(pickle.dumps(rmsg)) # shutdown the client self.client.exit() server_socket.close() connection_socket.close()
def start(self): while True: readsock, writesock, errsock = select.select(self.connections, [], []) for sock in readsock: if sock == self.serv: (clientsocket, address) = self.serv.accept() self.connections.append(clientsocket) self.client = client.client(clientsocket) self.addr = address self.receive() elif sock == sys.stdin: # TODO check port port = 5000 sstr = sys.stdin.readline() msg = sstr self.send(msg, "166.143.225.234", port) else: self.client = client.client(sock) self.receive()
def debuginotify(ui, repo, **opts): '''debugging information for inotify extension Prints the list of directories being watched by the inotify server. ''' cli = client(ui, repo) response = cli.debugquery() ui.write(_('directories being watched:\n')) for path in response: ui.write((' %s/\n') % path)
def get(self): """ HTTP GET request using the apps client session defined in the config :return: HTTP response from the API """ r = client().get( current_app.config.get('SAMPLE_APPLICATION_ADSWS_API_URL') ) return r.json()
def test_single_server_failure(self): print "\n[Info] ##########[INTEGRATION TEST MULTIPLE CLIENT MULTIPLE SERVER TEST]########## \n\n" LOCKS = 100 kill_server = self.servers[random.randint(0, len(self.servers)-1)] # generate the lock files for i in range(0, len(self.server_list)): filename = "client_" + str(i) + ".txt" make_simple_file(LOCKS, filename) # instantiate a client to each server client_list = [] for i in range(0, len(self.server_list)): port = self.server_list[i]["client_port"] host = self.server_list[i]["host"] assert((int(port) % 2) == 0) cli = client.client( "client_" + str(i) + ".txt", host, port, len(client_list)) client_list.append(cli) time.sleep(1) # implement a hard terminate on each server kill_server.proposer_process.terminate() kill_server.acceptor_process.terminate() kill_server.listening_process.terminate() try: kill_server.listening_process.join(1) except: pass try: kill_server.acceptor_process.join(1) except: pass try: kill_server.proposer_process.join(1) except: pass self.servers.remove(kill_server) # join each client failed = False for c in client_list: try: c.c_process.join() except Exception, e: c.terminate() failed = True
def _run(self, server_ip, server_port, wait_time, isSafe, printStates): if wait_time==None: while self.gameOver == False: time.sleep(update_interval) self.update() else: intervalExecute(update_interval, self.update) time.sleep(wait_time) self.gameCon.page() self.gameCon.text(0,0, "play again?") self.gameOver = self.isAI while self.gameOver == False: foo = kbpass() if foo == self.keyLeft: self.gameOver = true elif foo == self.keyRight: self.gameCon.text(5,5,"FINDING GAME") ## @var self._holding # A queue for messages recieve while the game is not yet in play self._holding = Queue.Queue() ## @var self._msgs # A queue for the messages recieved self._msgs = Queue.Queue() ## @var self._play # A boolean to trigger the game play. Game loop won't run until true self._play = False ## @var self._numPlayers # The number of players currently in the game self._numPlayers = 1 ## @var self._states # A dictionary of all the players states self._states = {} ## @var self._shouldPrint # A toggle for the state printing self._shouldPrint = printStates ## @var self._c # A Client object self._c = client.client(server_ip, server_port, self._handleMsg, self._playerAdded, self._playerRemoved, self._newLeader,isSafe) players = self._c.findGame() ## @var self.gameOver #game is over self.gameOver = False ## @var self.gameCon #better control of the screen if not players: self._states[self._c.getSelf()] = state(sops['PACMAN']) self._run(server_ip, server_port, wait_time, isSafe, printStates) self.gameOver = True
def __init__(self, port): self.messageNum = 0 self.client = client.client() self.connections = [] self.port = port #TODO check ip hostname = "128.205.54.9" self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) self.serv.bind((hostname, int(port))) self.serv.listen(10) self.connections.append(self.serv) self.connections.append(sys.stdin)
def __init__(self, form, hostname, port): QtCore.QThread.__init__(self) self.form = form self.hostname = hostname self.port = port self.client = client.client(self.hostname, self.port, self.form.mode) self.right_updated = None self.client.workspace_received = self.__workspace_received self.client.write_status_changed = self.__write_status_changed self.client.write_status_quo = self.__write_status_quo # todo to be removed self.client.write_update = self.__write_update self.client.user_assigned = self.__user_assigned self.client.message_received = self.__message_received
def method(*args): """ Runs client methods """ test_client = client.client(port=args[0]) action = getattr(test_client, args[1]) decodedArgs = [] for arg in args[2:]: try: decodedArgs.append(json.loads(arg)) except: decodedArgs.append(arg) print action(*decodedArgs)
def createNewClient(industry): subprocess.call("clear") print''' === CREATE NEW CLIENT === ''' name = "" while len(name) == 0: print "[+] Please enter client name (can be pseudonym):" name = raw_input() c = cli.client(industry, "", name, "", "data/industries/" + industry +'/' + name +'/') print "[-] New client added..." time.sleep(1) newClientOptions(c)
import client import opencv incolor = client.client() print("The selected is", incolor) opencv.image_processing(incolor)
"path to the simulation program harness, e.g.: /home/boris/freshs/harnesses/espresso_plain", metavar="harnesspath", type="string", default='auto') parser.add_option( "-S", "--server-host", dest="server", help= "network address(:port) of the server, e.g.: localhost:1000 or www.google.com", metavar="server_address(:port)", type="string", default='auto') (options, args) = parser.parse_args() if os.path.isfile(options.config): print("Client: reading client config file: " + options.config) else: # if filename is not given print('Client: A valid client config file is required.\n'+\ '\tCurrent value is: "'+\ options.config +'", which is not a valid file.\n'+\ '\tLook at examples in the test directory.') exit(8) ci = client(options.config, options.execprefix, options.execpath, options.harness, options.startconf, options.server) asyncore.loop()
def test_client_receives_png_image(): """Test that client gets back requested image type.""" from client import client assert 'Content-Type: image/png' in client('images/sample_1.png')
import sys sys.path.append(r'../') from client import client url = 'http://www.yunqi.com/index.php/openapi/rpc/service' flag = 'test' token = 'OaYMGiaNlXXsspjnsnTjzjrDCYWngEkh' obj = "pda_delivery.check" parameter = { 'pda_token' : '4dac86652016327bdd327d1c4c836ed5', 'device_code' : '1000000', 'delivery_bn' : '1812290000003', } client = client() cli = client.client(url,parameter,obj,flag,token) print(cli)
def test_client_error(req, reason, resp): """Test specific request errors.""" from client import client assert client(req).split(b'\r\n')[0] == b'HTTP/1.1 ' + reason + resp
# Tags: no-replicated-database, no-parallel, no-fasttest import os import sys import signal CURDIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(CURDIR, "helpers")) from client import client, prompt, end_of_block log = None # uncomment the line below for debugging # log=sys.stdout with client(name="client1>", log=log) as client1, client(name="client2>", log=log) as client2: client1.expect(prompt) client2.expect(prompt) client1.send("SET allow_experimental_live_view = 1") client1.expect(prompt) client2.send("SET allow_experimental_live_view = 1") client2.expect(prompt) client1.send("DROP TABLE IF EXISTS test.lv") client1.expect(prompt) client1.send( "CREATE LIVE VIEW test.lv WITH REFRESH 1" " AS SELECT value FROM system.events WHERE event = 'OSCPUVirtualTimeMicroseconds'" )
#!/usr/bin/env python3 # Tags: no-parallel import os import sys CURDIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(CURDIR, "helpers")) from client import client, prompt, end_of_block log = None # uncomment the line below for debugging # log=sys.stdout with client(name="client1>", log=log) as client1, client( name="client2>", log=log ) as client2, client(name="client3>", log=log) as client3: client1.expect(prompt) client2.expect(prompt) client3.expect(prompt) client1.send("SET allow_experimental_window_view = 1") client1.expect(prompt) client1.send("SET window_view_heartbeat_interval = 1") client1.expect(prompt) client2.send("SET allow_experimental_window_view = 1") client2.expect(prompt) client3.send("SET allow_experimental_window_view = 1") client3.expect(prompt) client3.send("SET window_view_heartbeat_interval = 1")
newlist = [] for i in range(3): randomInt = random.randint(1, 10) newlist.append(randomInt) normaliser(newlist) return newlist def randomMatrixGenerator(basic=True): """ Génère matrice pour appliquer avec multiMatrix """ if basic: n = 3 else: n = random.randint(1, 5) * 2 + 1 mat = [] for i in range(n): mat.append([]) for j in range(n): mat[i].append([]) for i in range(n): for j in range(n): mat[i][j] = random.randint(1, 100) normaliser(mat) return mat if __name__ == "__main__": client.client(sys.argv)
load_dotenv() if __name__ == "__main__": epoch = 0 EPOCH_COUNT = 10 if (sys.argv[1] == 'azure'): cloud_helper = AzureBlob() if (sys.argv[1] == 'gcp'): cloud_helper = GCPBlob() if (sys.argv[2]): container_name = sys.argv[2] else: container_name = 'loans-a' if (sys.argv[3]): epoch = int(sys.argv[3]) client = client(cloud_helper, container_name) if (sys.argv[4]): client.solo_train() else: while epoch < EPOCH_COUNT: epoch = client.poll_server(epoch) print('ab to sleep' + str(epoch)) time.sleep(5)
import machine, micropython from sensor import sensor from client import client w = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP) l = machine.Pin(2, machine.Pin.OUT, value=0) i = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4)) s = sensor(i, 0x77) c = client(s) try: c.on_send() except: pass if c.is_sleep() and w.value(): rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) rtc.alarm(rtc.ALARM0, c.get_sleep()) machine.deepsleep() else: tim = machine.Timer(-1) wc = lambda x: c.on_send()
def test_client_requests_unsupported_file_type(): """.""" from client import client assert client('images/sample.bmp') == "HTTP/1.1 415 Unsupported Media Type"
def test_client_receives_jpeg_image(): """Test that client gets back requested image type.""" from client import client assert 'Content-Type: image/jpeg' in client('images/JPEG_example.jpg')
#!/usr/bin/env python import os import sys CURDIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(CURDIR, 'helpers')) from client import client, prompt, end_of_block from httpclient import client as http_client log = None # uncomment the line below for debugging #log=sys.stdout with client(name='client1>', log=log) as client1: client1.expect(prompt) client1.send('DROP TABLE IF EXISTS test.lv') client1.expect(prompt) client1.send(' DROP TABLE IF EXISTS test.mt') client1.expect(prompt) client1.send( 'CREATE TABLE test.mt (a Int32) Engine=MergeTree order by tuple()') client1.expect(prompt) client1.send('CREATE LIVE VIEW test.lv AS SELECT sum(a) FROM test.mt') client1.expect(prompt) with http_client( { 'method': 'GET',
def test_client_sending_valid_request(): """Test 200 ok response when client sends proper request.""" from client import client assert client('sample.txt')[:15] == 'HTTP/1.1 200 OK'
import functions as func from os import system; import re; #class from client import client; from service import service; #from sys import exit validator=True resp="s" escolhamenu=None s1=service(); c1=client(); #print(func.isEnter("s")); ''' for i in range(0,test.letters().__len__()): print(test.letters()[i]+":"+str(func.isSpecialChar(test.letters()[i]))); ''' while(validator): while escolhamenu not in {'1','2','3'}: print("welcome to "+sett.systenName); func.creatinMenu(); escolhamenu=input("key ur option.. "); system("clear");
def test_uri_good_root_dir(): """.""" from client import client assert client('GET / HTTP/1.1\r\nHost: asdfafjasldkfjei\r\n\r\n') == ROOT_LIST_RESP
-mode=client-IPC : runs the client side when in interprocess (IPC) mode -mode=server-IPC : runs the server side when using IPC """) if __name__ == '__main__': if len(sys.argv) != 2: print_help() exit(-1) arg = sys.argv[1] server = None if arg == "-mode=direct": server = TimeServer() elif arg == "-mode=simple_proxy": server = TimeServerProxy() elif arg == "-mode=client-IPC": server = TimeServerProxyIPC() elif arg == "-mode=server-IPC": time_server_process() else: print_help() exit(-1) clients = [None, None] clients_task = [None, None] for i in range(2): clients[i] = client(server=server, id_client=i) clients_task[i] = threading.Thread(target=main_simple, args=(clients[i], )) clients_task[i].start()
def test_uri_good_images_dir(): """.""" from client import client assert client('GET /images HTTP/1.1\r\nHost: www.example.com\r\n\r\n') == IMAGES_LIST_RESP
import os import sys import signal import time import mysql.connector CURDIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(CURDIR, '../../../helpers')) from client import client log = None # uncomment the line below for debugging log = sys.stdout client1 = client(name='client1>', log=log) sqls = """ DROP DATABASE IF EXISTS db1; CREATE DATABASE db1; USE db1; CREATE TABLE IF NOT EXISTS t1(a String, b String, c String, d String, e String, f String, g String, h String) Engine = Memory; """ client1.run(sqls) time.sleep(2) mydb = mysql.connector.connect(host="127.0.0.1", user="******", passwd="root", port="3307") mycursor = mydb.cursor()
def test_uri_good_html(): """.""" from client import client assert client('GET /a_web_page.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n').startswith(WEB_PAGE_RESP)
def clientSelected(clientName, industry): subprocess.call("clear") c = cli.client(industry, "", clientName, "", "data/industries/" + industry +'/' + clientName +'/') newClientOptions(c) pass
def test_exceptions_405(request): """.""" from client import client assert client(request) == RESPONSE_405
def test_timeout(): """Test recv loop times out properly.""" from client import client assert b"Timed out" in client("GET HTTP PLEASE").split(b'\r\n')[0]
thread = None TESTING = False if len(sys.argv) == 3: TESTING = True print('TESTING') if TESTING: # with open('./logs/2017-10-10-12-19-14.csv', 'r') as f: with open('./logs/2018-11-03-16-42-33.csv', 'r') as f: labels = f.readline() labels = labels.split(',', 1)[-1] LOG_PATH = './logs/' table = ['40K', '4K', '1K', 'switch', 'pump', 'hp', 'hs'] LABEL_OFFSET = 1 YAML_FILE = './config.yaml' else: labels = client.client('127.0.0.1', 50326, 'getlabels') LOG_PATH = '../logs/' table = ['40K', '4K', '1K', 'switch', 'pump', 'hp', 'hs', 'relays'] LABEL_OFFSET = 2 YAML_FILE = '../config.yaml' with open(YAML_FILE, 'r') as f: CONFIG = yaml.load(f) table = CONFIG['show_list'] graph = CONFIG['graph'] labels = labels.split(',') labels = [label.strip() for label in labels] for l in labels: print(len(l), l, type(l)) # graph = ['40K', '4K', '1K', 'switch', 'pump'] DATA = None SIZE = 100000
# Tags: no-replicated-database, no-parallel, no-fasttest import os import sys CURDIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(CURDIR, "helpers")) from client import client, prompt, end_of_block from httpclient import client as http_client log = None # uncomment the line below for debugging # log=sys.stdout with client(name="client1>", log=log) as client1: client1.expect(prompt) client1.send("SET allow_experimental_live_view = 1") client1.expect(prompt) client1.send("DROP TABLE IF EXISTS test.lv") client1.expect(prompt) client1.send(" DROP TABLE IF EXISTS test.mt") client1.expect(prompt) client1.send( "CREATE TABLE test.mt (a Int32) Engine=MergeTree order by tuple()") client1.expect(prompt) client1.send("CREATE LIVE VIEW test.lv AS SELECT sum(a) FROM test.mt") client1.expect(prompt)
def get_temp(): ip = '127.0.0.1' port = 50326 temps = client.client(ip, port, 'getall').split(',') return float(temps[1])
# Tags: no-parallel import os import sys import signal CURDIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(CURDIR, 'helpers')) from client import client, prompt, end_of_block log = None # uncomment the line below for debugging # log=sys.stdout with client(name='client1>', log=log) as client1, client(name='client2>', log=log) as client2: client1.expect(prompt) client2.expect(prompt) client1.send('SET allow_experimental_window_view = 1') client1.expect(prompt) client1.send('SET window_view_heartbeat_interval = 1') client1.expect(prompt) client2.send('SET allow_experimental_window_view = 1') client2.expect(prompt) client1.send( 'CREATE DATABASE IF NOT EXISTS 01070_window_view_watch_events') client1.expect(prompt) client1.send(
def client_start(): client.client()
def test_client_requests_file_not_in_directory(): """.""" from client import client assert client('your_mom') == "HTTP/1.1 404 File or Directory Not Found"
def __init__(self, caseName, testEnvXml): #TBD update #self.nodelist = nodelist #self.monlist = monlist #Init the node testEnvTree = ET.parse(testEnvXml) treeRoot = testEnvTree.getroot() self.env_type = treeRoot.attrib['env_type'] self.vboxbuildpath = treeRoot.find('builds/vboxbuildpath').text self.vagrantfile = treeRoot.find('builds/vagrantfile').text self.sdopd = treeRoot.find('builds/sdopd').text self.clientlist = [] self.nodelist = [] self.monlist = [] self.osdlist = [] #Init client object for clientInfo in treeRoot.findall('hardwares/clients/client'): clientId = clientInfo.attrib['id'] ip_address = clientInfo.find('communication').attrib['ip_address'] hostname = clientInfo.find('communication').attrib['hostname'] password = clientInfo.find('communication').attrib['password'] username = clientInfo.find('communication').attrib['username'] clientObj = client.client(clientId, ip_address, hostname, password, username) self.clientlist.append(clientObj) #Init node object for nodeInfo in treeRoot.findall('hardwares/nodes/node'): nodeId = nodeInfo.attrib['id'] ip_address = nodeInfo.find('communication').attrib['ip_address'] hostname = nodeInfo.find('communication').attrib['hostname'] password = nodeInfo.find('communication').attrib['password'] username = nodeInfo.find('communication').attrib['username'] nodeObj = node.node(nodeId, ip_address, hostname, password, username) self.nodelist.append(nodeObj) #Init monitors object for monitorInfo in treeRoot.findall('hardwares/monitors/monitor'): monitorId = monitorInfo.attrib['id'] ip_address = monitorInfo.find('communication').attrib['ip_address'] hostname = monitorInfo.find('communication').attrib['hostname'] password = monitorInfo.find('communication').attrib['password'] username = monitorInfo.find('communication').attrib['username'] #monitorObj = monitors.monitors(monitorId, ip_address, hostname, password, username) monitorObj = monitors.monitors(monitorId, ip_address, hostname, password, username) self.monlist.append(monitorObj) #ssh to copy files from ceph nod print self.getMonitors() t = paramiko.Transport(self.monlist[0].getIpAddress(), '22') t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.get('/etc/ceph/ceph.conf', '/mnt/ceph.conf') #sftp.get('/etc/ceph/ceph.conf','E:\\ceph.conf') t.close() #paramiko.util.log_to_file("filename.log") #use ceph.conf file to init the cluster f = open('/mnt/ceph.conf') #f = open('E:\\ceph.conf') reg = r'^\[osd\.(\d*)\]$' osdRe = re.compile(reg) lines = f.readlines() for i in range(0, len(lines)): osdlist = osdRe.findall(lines[i]) if (osdlist): i = i + 1 hostname = lines[i].strip() hostname = hostname[7:] osdId = osdlist[0] #logging.getLogger(caseName).info(osdId) #logging.getLogger(caseName).info(hostname) osdObj = osd.osd(osdId, hostname) self.osdlist.append(osdObj) for nodeObj in self.nodelist: newOsdList = [] for osdObj in self.osdlist: if (nodeObj.gethostName() == osdObj.gethostName()): newOsdList.append(osdObj) nodeObj.createOsds(newOsdList) #get monitor information leaderId = self.monlist[0].getQuorumLeader(caseName) for mon in self.monlist: if (leaderId == mon.gethostName()): mon.setleader()