def run(): client = zerorpc.Client() client.connect("tcp://127.0.0.1:4242") result = client.get_models() print("Result: {}".format(result))
def update_vhosts(*args, **kwargs): if not settings.KUMQUAT_USE_0RPC: return zerorpc.Client(connect_to=settings.KUMQUAT_BACKEND_SOCKET).update_vhosts()
def test_task_context_relay_fork(): endpoint1 = random_ipc_endpoint() endpoint2 = random_ipc_endpoint() srv_ctx = zerorpc.Context() srv_relay_ctx = zerorpc.Context() cli_ctx = zerorpc.Context() srv_tracer = Tracer('[server]') srv_ctx.register_middleware(srv_tracer) srv_relay_tracer = Tracer('[server_relay]') srv_relay_ctx.register_middleware(srv_relay_tracer) cli_tracer = Tracer('[client]') cli_ctx.register_middleware(cli_tracer) class Srv: def echo(self, msg): return msg srv = zerorpc.Server(Srv(), context=srv_ctx) srv.bind(endpoint1) srv_task = gevent.spawn(srv.run) c_relay = zerorpc.Client(context=srv_relay_ctx) c_relay.connect(endpoint1) class SrvRelay: def echo(self, msg): def dothework(msg): return c_relay.echo(msg) + 'relayed' g = gevent.spawn( zerorpc.fork_task_context(dothework, srv_relay_ctx), 'relay' + msg) print 'relaying in separate task:', g r = g.get() print 'back to main task' return r srv_relay = zerorpc.Server(SrvRelay(), context=srv_relay_ctx) srv_relay.bind(endpoint2) srv_relay_task = gevent.spawn(srv_relay.run) c = zerorpc.Client(context=cli_ctx) c.connect(endpoint2) assert c.echo('hello') == 'relayhellorelayed' srv_relay.stop() srv.stop() srv_relay_task.join() srv_task.join() assert cli_tracer._log == [ ('new', cli_tracer.trace_id), ] assert srv_relay_tracer._log == [ ('load', cli_tracer.trace_id), ('reuse', cli_tracer.trace_id), ('load', cli_tracer.trace_id), ('reuse', cli_tracer.trace_id), ('reuse', cli_tracer.trace_id), ] assert srv_tracer._log == [ ('load', cli_tracer.trace_id), ('reuse', cli_tracer.trace_id), ]
def listen(): """ This is the function that MintPatch will be in while idle. Some Output is handled here. However, the main purpose of this function is to parse input and call the appropriate functions to handle the command cases. """ listener = zerorpc.Client() listener.connect("tcp://127.0.0.1:4242") # This dictionary will be used as a switch statement # to quickly parse input. # It translates strings into the appropriate function, # Each of which has the same parameters and return. switch_dict = { 'move': listener.move_motor, 'scan': listener.scan, 'update': listener.running_update, 'move_all': listener.move_motor_sync, 'move_diff': listener.move_motor_different, 'move_cont': listener.move_motor_continuous, 'end': end_listening } # LOOP SETUP Continue = True # Establishes a common, potentially infinite while loop. # It can be ended by inputing "end". while (Continue): # GATHERING INPUT # NODE.JS # Uses this input function to gather one line from the Node. # This is a string. #conin = read_from_json() # CONSOLE conin = sys.stdin.readline() # INPUT SETUP # Since it's a string, and the parts of the input should be seperated # by spaces; we split this to make it an array. cinar = conin.split() # Knowing the length of this string array will # let us catch errors and quickly skip faulty commands. l = cinar.__len__() # In this case, there is no input. # There's no reason to go through the loop. if l == 0: continue # SWITCH # This is the magical switch statement. It runs the first # word of the input through the switch dictionary, # finding the appropriate function to run. Then, it # passes the full input array and its length. Not every # function uses them, but this allows for a very efficient call. # In the case that the input is faulty, the switch will call the # "ignore" function. This does nothing. # Finally, each function returns a Boolean telling the listener # whether or not to continue the loop. Every function except "end" # returns true. Continue = switch_dict.get(cinar[0], ignore)(cinar, l) print(Continue) # END LOOP print("Thank you for using MintPatch!") listener.disconnect("tcp://127.0.0.1:4242")
# Simple ZeroRPC asynchronous client example import zerorpc import logging logging.basicConfig(filename='async_client.log', level=logging.DEBUG) client = zerorpc.Client() client.connect("tcp://127.0.0.1:4444") result1 = client.long_running_task(async=True) result2 = client.other_task(async=True) result3 = client.other_task_with_Error(async=True) zerorpc.gevent.joinall([result1, result2, result3]) print(result1.value) print(result2.value) print("processing result of other_task_with_Error") try: if result3.exception: raise result3.exception except Exception as e: print(e) client.close()
def __init__(self): self.workbench = zerorpc.Client(timeout=300, heartbeat=60) self.workbench.connect("tcp://127.0.0.1:4242")
import zerorpc c1 = zerorpc.Client() c1.connect("tcp://127.0.0.1:4243") c2 = zerorpc.Client() c2.connect("tcp://127.0.0.1:4244") class Hitung(object): def calc(self, n1, n2, op): if (op == 1): #tambah return c1.tambah(n1,n2) elif (op == 2): #kurang return c1.kurang(n1,n2) elif (op == 3): #bagi return c2.bagi(n1,n2) elif (op == 4): #kali return c2.kali(n1,n2) else: return 0 s = zerorpc.Server(Hitung()) s.bind("tcp://0.0.0.0:4242") s.run()
import zerorpc # connect to wikidata-server wd = zerorpc.Client(timeout=600) wd.connect("ipc:///tmp/wikidata") # stream answers for v in wd.vertices(): print(wd.claims(v))
def __init__(self, samplers, url): super(ZeroRPCOutput, self).__init__(samplers) self._url = url self._client = zerorpc.Client()
def __init__(self, message: Message): self.client = zerorpc.Client() self.event = threading.Event() self.message = message # 实例对象 self.state = WAITING # 任务完成状态 self.executor = Executor()
import zmq import zerorpc import sys porta_interfaceBD = "5563" socketInterfaceBD = zerorpc.Client() socketInterfaceBD.connect("tcp://localhost:" + porta_interfaceBD) ''' O administrador pode visualizar e alterar todas as informações do complexo ''' def main(): while True: print("Você esta na interface de administrador \n") print("Para visualizar as informações do complexo pressione 1 \n") print("Para inserir alguma informação do complexo pressione 2 \n") print("Para remover alguma informação do complexo pressione 3 \n") print("Para sair pressione qualquer tecla diferente das anteriores \n") opcao = int(input("Digite sua opcao: \n")) if opcao == 1: print("Visualizar usuários cadastrados pressione 1 \n") print( "Visualizar a quantidade de predios do complexo pressione 2 \n" ) print("Visualizar a lista de andares por prédio pressione 3 \n") print( "Visualizar a lista de usuarios permitidos no complexo pressione 4 \n"
startx = min(rec1.x0, rec2.x0) width = rec1.width + rec2.width - (endx - startx) endy = max(rec1.y1, rec2.y1) starty = min(rec1.y0, rec2.y0) height = rec1.height + rec2.height - (endy - starty) if width <= 0 or height <= 0: Area = 0 # 重叠率为 0 else: Area = width * height # 两矩形相交面积 return Area, width c_det_east = zerorpc.Client() c_det_east.connect("tcp://192.168.1.115:18000") # kuaidi c_det_frcnn = zerorpc.Client() c_det_frcnn.connect("tcp://192.168.1.115:18765") # kuaidi def draw_detect_result(image_path): """ 将某图检测结构可视化 :param image_path: :return: """ # ---------------------------------------- # 连接两个检测 RPC 服务
def trigger_index_update(namespace_id): c = zerorpc.Client() c.connect(config.get('SEARCH_SERVER_LOC', None)) c.index(namespace_id)
def call(self, call): if self.zrpc_client is None: self.zrpc_client = zerorpc.Client(connect_to=self.zmq_url) if call.kwargs: raise ValueError("zerorpc doesn't support kwargs, but %r has kwargs" %(call, )) return self.zrpc_client(call.name, *call.args)
def _create_service(self): logger.info('Connecting to node %s', self.get_id()) c = zerorpc.Client() c.connect('tcp://%s:%s' % (self.host, self.port)) logger.info('Connected.') return c
#encoding=utf8 import zerorpc import os if __name__ == '__main__': c = zerorpc.Client(timeout=2) c.connect("tcp://0.0.0.0:10033") #contents = [u"带份饭", "买包烟"] contents = '悬赏一个键盘手会弹钢琴的,有时间组乐队的' tag = c.tag(contents) print(tag)
import zerorpc import paho.mqtt.client as mqtt Marketplace = zerorpc.Client() Marketplace.connect("tcp://127.0.0.1:8081") nomorhp = 0 # This is the Subscriber def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe("topic/pulsa") def on_message(client, userdata, msg): print("Message: " + msg.payload.decode()) client.disconnect() def login(): print("Masukkan Nilai TopUp (Minimal 10000)") amount = int(input()) if amount >= 10000: print(Marketplace.topUp(nama, int(amount))) else: print("Minimal TopUp sebesar 10000, mohon coba lagi") def beliPulsa(): global nomorhp
def setPartionsToWorker(self, partitions): partitions_usedTosetTask = copy.deepcopy(partitions) # print '1' worker_num = len(self.workers) # print worker_num partition_num = len(partitions_usedTosetTask) # print partition_num if partition_num % worker_num == 0: pop_num = partition_num / worker_num else: pop_num = partition_num / worker_num + 1 for worker in self.workers: # print '-------' # print partitions_usedTosetTask # print '-------' if len(partitions_usedTosetTask) == 0: break # print '2' i = 0 while i < pop_num: p = partitions_usedTosetTask.pop() worker['current_task'].append(p) i += 1 # print i if len(partitions_usedTosetTask) == 0: break # print 'test2' # print worker['current_task'] # # sent partitions to workers worker['status'] = StatusEnum.Status_Working partition_List_toSent = [] p_name_toPrint = [] for ct in worker['current_task']: # print ct['status'] if not ct['status']: partition_List_toSent.append(ct) p_name_toPrint.append(ct['partition_name']) try: c = zerorpc.Client() c.connect('tcp://' + worker['ip'] + ':' + worker['port']) output = StringIO.StringIO() pickler = cloudpickle.CloudPickler(output) pickler.dump(partition_List_toSent) sent = output.getvalue() print colored( '[Master:]', 'white'), colored('Sent partitons:%s to worker: %s', 'red') % (p_name_toPrint, worker['port']) c.getPartitionList(sent, async=True) output = StringIO.StringIO() pickler = cloudpickle.CloudPickler(output) pickler.dump(self.rddLineageList) objstr = output.getvalue() print colored('[Master:]', 'white'), colored( 'sent rdd lineage to worker: %s', 'red') % worker['port'] c.getRddLineage(objstr, async=True) except TimeoutExpired: print colored( '[Exception:]exception happened when sent partition and rdd lineage to workers!', 'red') continue except LostRemote: continue
if __name__ == "__main__": # Argument parsing PARSER = argparse.ArgumentParser( description="Client part of the native backlight utility.") PARSER.add_argument( 'action', metavar='ACTION', type=str, choices=INPUT, nargs=1, help='the action to perform. Supported: increase, decrease, reset') ARGS = PARSER.parse_args() # ZeroRPC CLIENT = zerorpc.Client() ADDRESS = ("tcp://127.0.0.1:%s") % (config.communication_port()) CLIENT.connect(ADDRESS) try: CHOICE = str(*ARGS.action) if CHOICE == "reset": CLIENT.reset() elif CHOICE == "decrease": CLIENT.decrease() elif CHOICE == "increase": CLIENT.increase() else: raise Exception( ("Invalid input paramater. Actual: %s, Expected: one of %s") % (ARGS.action, INPUT))
def controller(self): gevent.sleep(10) # print '1~~' while True: # print '2~~' if self.method != 'repl': # print '3~~' printList = [] for worker in self.workers: # print '4~~' try: # print '5~~' c = zerorpc.Client(timeout=1) c.connect('tcp://' + worker['ip'] + ':' + worker['port']) c.ping() printList.append(worker['port']) except TimeoutExpired: # print '6~~~' # if not worker['current_task']: # # print '7~~~' # # continue # print '1test~~~~' self.workers.remove(worker) if worker['current_task']: # print '2test~~~~' temp = [] for p in worker['current_task']: if not p['status']: temp.append(p) # print 'temp %s' % temp # partiton_num = len(temp) # worker_num = len(self.workers) if len(temp) % len(self.workers) == 0: pop_num = len(temp) / len(self.workers) else: pop_num = len(temp) / len(self.workers) + 1 # print 'pop_num: %s' % pop_num for w in self.workers: if worker['status'] == StatusEnum.Status_Down: continue else: # print '3test~~~' i = 0 partition_List_toSent_inRecovery = [] partitonName_toPrint = [] if len(temp) == 0: break else: while i < pop_num: temp_p = temp.pop() partition_List_toSent_inRecovery.append( temp_p) partitonName_toPrint.append( temp_p['partition_name']) i += 1 if len(temp) == 0: break try: c = zerorpc.Client() c.connect('tcp://' + w['ip'] + ':' + w['port']) # print w['current_task'] w['status'] = StatusEnum.Status_Working output = StringIO.StringIO() pickler = cloudpickle.CloudPickler( output) pickler.dump( partition_List_toSent_inRecovery ) sent = output.getvalue() c.getPartitionList(sent) print colored( '[Master:]', 'white' ), colored( 'Sent partitons:%s to worker: %s', 'red') % (partitonName_toPrint, w['port']) worker['current_task'].extend( partition_List_toSent_inRecovery ) except LostRemote: continue except TimeoutExpired: continue print colored( '[Master:]', 'white'), colored('(%s:%s) down', 'red') % ( worker['ip'], worker['port']) except LostRemote: print 'LostRemote event ignored' continue # print printList gevent.sleep(1)
def rpc(func, *args): rip, rport = lookup('zerorpc-tools') zc = zerorpc.Client() zc.connect("tcp://{}:{}".format(rip, rport)) result = zc(func, *args) return result
def getPyraptordClient(clientName='pyraptord'): ports = json.loads(file(settings.ZEROMQ_PORTS, 'r').read()) rpcPort = ports[clientName]['rpc'] client = zerorpc.Client(rpcPort) return client
def __init__(self, msg: Message, timeout=3): self.msg = msg self.client = zerorpc.Client() self.event = threading.Event() self.timeout = timeout
def _get_service(): import zerorpc client = zerorpc.Client(heartbeat=None, timeout=300) client.connect(cache_server) return client
import zerorpc import sys import collections master_addr = 'tcp://0.0.0.0:4242' if __name__ == '__main__': filename_base = sys.argv[1] output_filename = sys.argv[2] c = zerorpc.Client() c.connect(master_addr) result = c.collect_result(filename_base) od = collections.OrderedDict(sorted(result.items())) output_file = output_filename + '.txt' with open(output_file, 'w') as f_out: for k, v in od.items(): f_out.write('{} : {}\n'.format(k, v)) f_out.close()
def run(self): client = zerorpc.Client() client.connect("tcp://" + self.ip + ":" + self.port) self.real_app = real_app(client) self.real_app.run()
def test_call_procedure(): c = zerorpc.Context() def test(argument): return 'ret_real:' + argument assert c.middleware_call_procedure(test, 'dummy') == 'ret_real:dummy' def middleware_1(procedure, *args, **kwargs): return 'ret_middleware_1:' + procedure(*args, **kwargs) cnt = c.register_middleware({'call_procedure': middleware_1}) assert cnt == 1 assert c.middleware_call_procedure(test, 'dummy') == \ 'ret_middleware_1:ret_real:dummy' def middleware_2(procedure, *args, **kwargs): return 'ret_middleware_2:' + procedure(*args, **kwargs) cnt = c.register_middleware({'call_procedure': middleware_2}) assert cnt == 1 assert c.middleware_call_procedure(test, 'dummy') == \ 'ret_middleware_2:ret_middleware_1:ret_real:dummy' def mangle_arguments(procedure, *args, **kwargs): return procedure(args[0].upper()) cnt = c.register_middleware({'call_procedure': mangle_arguments}) assert cnt == 1 assert c.middleware_call_procedure(test, 'dummy') == \ 'ret_middleware_2:ret_middleware_1:ret_real:DUMMY' endpoint = random_ipc_endpoint() # client/server class Server(zerorpc.Server): def test(self, argument): return 'ret_real:' + argument server = Server(heartbeat=1, context=c) server.bind(endpoint) gevent.spawn(server.run) client = zerorpc.Client(heartbeat=1, context=c) client.connect(endpoint) assert client.test('dummy') == \ 'ret_middleware_2:ret_middleware_1:ret_real:DUMMY' client.close() server.close() # push/pull trigger = gevent.event.Event() class Puller(zerorpc.Puller): argument = None def test(self, argument): self.argument = argument trigger.set() return self.argument puller = Puller(context=c) puller.bind(endpoint) gevent.spawn(puller.run) pusher = zerorpc.Pusher(context=c) pusher.connect(endpoint) trigger.clear() pusher.test('dummy') trigger.wait() assert puller.argument == 'DUMMY' #FIXME: These seems to be broken # pusher.close() # puller.close() # pub/sub trigger = gevent.event.Event() class Subscriber(zerorpc.Subscriber): argument = None def test(self, argument): self.argument = argument trigger.set() return self.argument subscriber = Subscriber(context=c) subscriber.bind(endpoint) gevent.spawn(subscriber.run) publisher = zerorpc.Publisher(context=c) publisher.connect(endpoint) trigger.clear() publisher.test('dummy') trigger.wait() assert subscriber.argument == 'DUMMY'
import zerorpc c = zerorpc.Client() c.connect("tcp://127.0.0.1:9999") operator = zerorpc.Client() operator.connect("tcp://127.0.0.1:7969") saldoAwal = 0 class Marketplace(object): def topUp(self, amount): print (c.transfer(amount)) global saldoAwal saldoAwal = saldoAwal + amount return "TopUp Anda Berhasil Ditambahkan Rp. %s" % saldoAwal def Pulsa(self, number, oper, amount): global saldoAwal print (amount) if amount < saldoAwal: saldoAwal = saldoAwal - amount operator.isi(number, oper, amount) else: return "Saldo Anda Tidak Cukup" s = zerorpc.Server(Marketplace()) s.bind("tcp://0.0.0.0:10000") s.run()
def worker(url_dispatcher: str, url_collector: str, ckpt_loc: str, num_workers: int, num_samples: int): """ The worker definition Args: url_dispatcher: The url for the dispatcher url_collector: The url for the collector ckpt_loc: The location for the checkpoint num_workers: The number of CPU workers used num_samples: The number of samples """ # Initialize clients client_dispatcher = zerorpc.Client() client_collector = zerorpc.Client() # Connect to client client_dispatcher.connect(url_dispatcher) client_collector.connect(url_collector) # Load model mdl = build_model(ckpt_loc) # Build multiprocessing pool # pylint: disable=no-member pool = mp.Pool(num_workers) # Create mapper def mapper(func, iterable): return list(pool.map(func, iterable, chunksize=100)) while True: message: t.Dict = client_dispatcher.dispatch() if message['message_type'] == 'none_message': break else: # Get sample the list of molecules (smiles_sampled, percent_valid, percent_unique) = sample(mdl, message['scaffold_smiles'], num_samples) # Filter out None molecules smiles_sampled = list( filter(lambda _x: _x is not None, smiles_sampled)) # Calculate property statistics prop_stat = np.stack( (get_prop_stat(smiles_sampled, mapper), get_prop_stat(message['molecule_smiles_list'], mapper)), axis=0) prop_stat = prop_stat.tolist() # Get diversity and MMD (diversity_1, diversity_2, mmd) = get_mmd(smiles_sampled, message['molecule_smiles_list'], mapper) result_message = { 'message_type': 'result_message', 'scaffold_smiles': message['scaffold_smiles'], 'molecule_sampled': (smiles_sampled[:100] if len(smiles_sampled) > 100 else smiles_sampled), 'num_test': len(message['molecule_smiles_list']), 'percent_valid': percent_valid, 'percent_unique': percent_unique, 'prop_stat': prop_stat, 'diversity_test': diversity_2, 'diversity_sample': diversity_1, 'mmd': mmd } client_collector.collect(result_message)
cv2.imwrite(face_img, face_roi) if args['save_person_face']: # Save extracted person (w/face) object to disk. obj_img = args['output']+'/'+str(idx)+'-obj'+'.jpg' logging.info('Writing {}'.format(obj_img)) cv2.imwrite(obj_img, roi) idx += 1 return # Grab the paths to the input images. image_paths = glob(args['dataset'] + '/*.*', recursive=False) logging.debug('image_paths: {}'.format(image_paths)) # Grab image paths in text file if given. # Its assumed there is one path per line in the file. try: with open(args['file_path'], 'r') as f: txt_img_paths = f.read().splitlines() except (IOError, TypeError) as e: txt_img_paths = [] # Send images to object detect server. obj_det = zerorpc.Client(heartbeat=60000) obj_det.connect(ZERORPC_PIPE) obj_ans = obj_det.detect_objects(image_paths + txt_img_paths) # Send detected objects to face detector and extractor. # (first deserialize json to Python objects) detect_and_extract(json.loads(obj_ans))