def remote_training(self, missing_rules): # create the process for the remote connections thread_lock = threading.Lock() workers = [] t_count_list = [] with open(self.config_path, 'r') as myfile: connection_strings = set() for line in (myfile): if line[0] == '#': continue connection_strings.add(line.rstrip()) for tid, line in enumerate(connection_strings): client_worker = pyjsonrpc.HttpClient(url=line) worker = TaintInduceThread(tid, t_count_list, client_worker, missing_rules, thread_lock, self.rule_path) t_count_list.append([0, None]) workers.append(worker) for worker in workers: worker.start() for worker in workers: worker.join() print('----Processed Jobs Stats----') for worker in workers: print('{}: {}'.format(worker.remote.url, t_count_list[worker.tid][0]))
def __init__(self, config): self.title = "bitcoind stats" self.CONNECTION_YELLOW_THRESHOLD = 4 self.CONNECTION_GREEN_THRESHOLD = 9 self.host = config["host"] self.addrlocal = "N/A" self.utx_count_on_block = -1 self.utx_count = 0 # The time since last block or when we started tracking new transactions # (eg. on first tab launch) self.utx_start_time = -1 self.connections = 0 self.inbound = 0 self.outbound = 0 self.difficulty = 1.0 self.block_count = 0 self.last_block_time = int(time.time()) # Create the JSON-RPC client self.client = pyjsonrpc.HttpClient(url=config["host"], username=config["username"], password=config["password"], timeout=4) self.error = None
def coinbase(endpoint): """ curl -X POST --data '{"jsonrpc":"2.0","method":"eth_coinbase","params":[],"id":1}' http://54.67.35.229:20000 """ c = pyjsonrpc.HttpClient(endpoint) r = c.call('eth_coinbase') return r
def main(): """ the main function """ opts = parse_args() fOpen = open(opts.input_file, 'r') cRead = fOpen.read() fOpen.close() cREQList = [cRead] http_client = pyjsonrpc.HttpClient(url=opts.server_url) fWrite = open(opts.output_file, 'w') for cREQ in cREQList: if cREQ == '': break callParaDict = json.loads(cREQ) inferDict = http_client.call( 'infer', query=callParaDict['query'], assign=callParaDict['assign'] ) inferJSON = json.dumps(inferDict) fWrite.write(str(inferJSON).replace(' ', '') + '\n') fWrite.close()
def __init__(self,url): """ :param url: URL of piccolo server :type url: str """ self._http_client = pyjsonrpc.HttpClient(url=url) PiccoloBaseClient.__init__(self)
def login(): global cookie global http_client global ws_thread global session global nxapi_ip global http # Login to the switch: print "Login to the switch with ip: {0}".format(nxapi_ip) url = "{0}://{1}/api/aaaLogin.json".format(http, nxapi_ip) data = json.dumps({"aaaUser" : {"attributes" : {"name" : "admin","pwd" : "my_password"}}}) r = session.post(url, data) # Parse the received contents and extract the cookie resp = json.loads(r.text) cookie = resp[u'imdata'][0][u'aaaLogin'][u'attributes'][u'token'] # Establish the web-socket using the cookie http_client = pyjsonrpc.HttpClient(url = url, cookies = "INS-cookie={0}".format(cookie)) # Create the web-socket thread, in order to listen to any # notification from MOs that we subscribed to ws_thread = WsThread() ws_thread.start()
def setTransfers(self): http_client = pyjsonrpc.HttpClient( url = "http://10.0.3.112:5050/", #url = "http://192.168.1.7:5050/", ) svr_response = http_client.call("returntransfers") print svr_response newstruct = {'transfers_list': svr_response} n = 0 for entry in newstruct: x = 0 for obj in newstruct[entry]: sublist = svr_response[x] v = 0 for g in sublist: titem = sublist[v] newitem = QTableWidgetItem(titem) self.setItem(x, v, newitem) v += 1 btn = ExtendedQLabel.ExtendedQLabel(self) btn.setText('Download Collection') print "Row x = ", x self.setCellWidget(x, 6, btn) x += 1 self.connect(btn, SIGNAL('clicked()'), self.downloadTransfer) n += 1
def main(): parser = argparse.ArgumentParser( description='JSON RPC calls on gstreamer pipeline test.') parser.add_argument('message', help='Test to display on video stream', type=str) #parser.add_argument('pid', help='Pid of closed caption ES to extract from stream.', type=int) parser.add_argument( '-m', '--message_name', help='Friendly name to remove/change this message later.', type=str) args = parser.parse_args() http_client = pyjsonrpc.HttpClient( url='http://localhost:8080', #username = '******', #password = '******', ) msg = args.message x = 1 y = 2 friendly_name = args.message_name or 'message_one' #response = http_client.call('ShowMessage', msg, x, y, friendly_name) response = http_client.ShowMessage(msg=msg, x=x, y=y, friendlyName=friendly_name) print('Response from server: {r}'.format(r=response))
def __init__(self): # prepare client rpc self.httpClient = pyjsonrpc.HttpClient(url='http://' + sys.argv[1] + ':' + str(RPC_PORT)) print 'Format: <qid> <dst_ip> <dst_port> <min_rate>' while True: self.add_qos_rule()
def balance(endpoint, address_hex): """ curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance", "params":["0x4c6634475af56fe370d9841607c9f65099693ef8", "latest"],"id":1}' http://54.67.35.229:20000 {"id":1,"jsonrpc":"2.0","result":"0x058788cb94b1d7f6f0"}% """ c = pyjsonrpc.HttpClient(endpoint) r = c.call('eth_getBalance', address_hex, 'latest') return long(r, 16)
def __init__(self, ip=None, port=config.my_sdn_switch_port, username=config.my_sdn_switch_user, password=config.my_sdn_switch_password): self.client = pyjsonrpc.HttpClient( url="http://{0}:{1}/command-api".format(ip, port), username=username, password=password)
def test_client(): user_provider = pyjsonrpc.HttpClient(url="http://{0}{1}".format('172.19.3.111:38080/', 'com.ofpay.demo.api.UserProvider')) for x in range(number): user_provider.getUser('A003') user_provider.queryUser( {u'age': 18, u'time': 1428463514153, u'sex': u'MAN', u'id': u'A003', u'name': u'zhangsan'}) # user_provider.queryAll() user_provider.isLimit('MAN', 'Joe') user_provider('getUser', 'A005')
def __init__(self): # prepare client rpc self.httpClient = pyjsonrpc.HttpClient(url='http://' + sys.argv[1] + ':' + str(RPC_PORT)) FORMAT_STR = 'Format: <meter_id> <dst_ip> <dst_port> <max_rate>' print FORMAT_STR while True: self.add_qos_rule()
def transact(endpoint, sender, to, value=0, data=''): """ curl -X POST --data '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from": "0x4c6634475af56fe370d9841607c9f65099693ef8", "to":"0xd46e8dd67c5d32be8058bb8eb970870f072445675", "value": "0x910"}],"id":1}' http://54.67.35.229:20000 """ c = pyjsonrpc.HttpClient(endpoint) r = c.call('eth_sendTransaction', { 'from': sender, 'to': to, 'value': hex(value), 'data': data }) return r
def get_service(): """ TODO: add retry mecanism for when service is unreachable """ global service if service is None: service = pyjsonrpc.HttpClient(url=url, username=username, password=password, timeout=timeout) return service
def main(argv): http_client = pyjsonrpc.HttpClient(url="http://localhost:4000/jsonrpc") if http_client is None: print 'Could not connect to rcp server' sys.exit() usage = "\nusage: report_throughput.py <url> [options]\n"\ "\nOptions:\n-a\t\tall ports all switchs\n"\ "-s <switch_id>\tall ports on <switch_id>\n"\ "-p <port_no>\tport <port_no>. To be used with -s.\n"\ "-m request max stats not current stats\n" al = False max_wanted = False flows_wanted = False switch = None port = None try: opts, args = getopt.getopt(argv, "fmas:p:", []) except getopt.GetoptError: print usage sys.exit(2) for opt, arg in opts: if opt == '-f': flows_wanted = True elif opt == '-m': max_wanted = True elif opt == '-a': al = True elif opt == '-s': switch = arg elif opt == '-p': port = arg else: print usage sys.exit(2) if al == True: pprint(http_client.call("report_all_ports", flows_wanted, max_wanted)) elif switch is not None and port is not None: pprint( http_client.call("report_port", flows_wanted, max_wanted, switch, port)) elif switch is not None: pprint( http_client.call("report_switch_ports", flows_wanted, max_wanted, switch)) else: print usage
def __init__(self, myconf): config = ConfigParser.RawConfigParser() config.read(myconf) self.port = config.getint('global', 'port') self.listen = config.get('global', 'listen') self.http_client = pyjsonrpc.HttpClient("http://localhost:%s" % self.port) Pinger.cmdup = config.get('global', 'cmdup') Pinger.cmddown = config.get('global', 'cmddown') Pinger.checkip = config.get('global', 'checkip') testing = config.getboolean('global', 'testing') if testing: Pinger.pstats = collections.deque([1], 1) # just one ping for testing Pinger.mailer = Mailer(myconf)
def GetJsonRpcClient(sJsonRpcHostPort, sJsonRpcUserPass): import pyjsonrpc lsUP = sJsonRpcUserPass.split(':') if len(lsUP) < 2: return None #PrintMsTimeMsg("GetJsonRpcClient(%s)..." % sJsonRpcHostPort) oRet = pyjsonrpc.HttpClient( url="http://%s/" % sJsonRpcHostPort, username=lsUP[0], password=lsUP[1], #timeout = 60, #Specifies a timeout in seconds for blocking operations ) PrintMsTimeMsg("GetJsonRpcClient.oRet=(%s)..." % oRet) return oRet
def test_client_every_new(): user_provider = pyjsonrpc.HttpClient(url="http://{0}{1}".format( 'zookeeper:38081/', 'com.ofpay.demo.api.UserProvider2')) print(user_provider.getUser('A003')) print( user_provider.queryUser({ u'age': 18, u'time': 1428463514153, u'sex': u'MAN', u'id': u'A003', u'name': u'zhangsan' })) print(user_provider.queryAll()) print(user_provider.isLimit('MAN', 'Joe')) print(user_provider('getUser', 'A005'))
def getBlock(block_hash): #print block_hash http_client = pyjsonrpc.HttpClient( url="http://10.81.232.151:9332", username="******", password="******" #url = "http://192.168.2.201:19332", #username = "******", #password = "******" ) blockinfo = http_client.call("getblock", block_hash) #print blockinfo return blockinfo
def update_library(host, username, password, processes, output, pretty, debug): if debug: logger.setLevel(logging.DEBUG) jsonrpc_endpoint = "http://{}/jsonrpc".format(host) logger.debug("Connecting to {} with {}:{}".format(jsonrpc_endpoint, username, password)) global jsonclient jsonclient = pyjsonrpc.HttpClient(url=jsonrpc_endpoint, username=username, password=password) response = jsonclient.call('VideoLibrary.GetMovies', properties = [ "director", "title", "genre", "dateadded", "playcount", "originaltitle", "thumbnail", "year", "imdbnumber", "lastplayed", "plot", ], sort = dict(order="descending", method="dateadded") ) logger.debug("Retrieved list of movies") movies = response['movies'] if not os.path.isdir(THUMBNAIL_CACHE): logger.info("Thumbnail cache dir doesn't exist. Creating it...") os.makedirs(THUMBNAIL_CACHE) logger.info("Found {} movies to process. Using up to {} processes".format( len(movies), processes )) pool = multiprocessing.Pool(processes) logger.info("Downloading metadata") pool.map(download_original_thumbnail, movies) logger.info("Resizing thumbnails") pool.map(resize_thumbnail, movies) logger.info("Generating json output") write_json_data(movies, output, pretty) logger.info("Done")
class Tablette(Widget): http_client = pyjsonrpc.HttpClient(url=TableURL) TrueColor = ListProperty([0, 0, 0]) Status = StringProperty("Disconnected") def appairage(self, adresse): reponse = self.http_client.appairage(adresse, self.Status) reponse_tab = json.decode(reponse) self.Status = reponse_tab["status"] if self.Status == "Connected": r = float(reponse_tab["color"]["r"]) g = float(reponse_tab["color"]["g"]) b = float(reponse_tab["color"]["b"]) self.TrueColor = [r, g, b] def setColor(self, color): self.TrueColor = color def finish(self): self.http_client.goodbye()
def main(argv): http_client = pyjsonrpc.HttpClient(url="http://localhost:4000/jsonrpc") if http_client is None: print 'Could not connect to JSON-RPC server' sys.exit(2) usage = "usage: python enforce_throughput.py <switch_id> <port_no> <speed B/s>" try: opts, args = getopt.getopt(argv, "h", []) except getopt.GetoptError: print usage sys.exit() switch = args[0] port = args[1] speed = args[2] http_client.notify("enforce_port_outbound", switch, port, speed)
def rpc_connect(self): """Connect to a coin daemon's JSON RPC interface. Returns: bool: True if successfully connected, False otherwise. """ if self.coin in COINS: rpc_url = COINS[self.coin]["rpc-url"] + ":" if self.testnet: rpc_url += COINS[self.coin]["rpc-port-testnet"] else: rpc_url += COINS[self.coin]["rpc-port"] self.rpc = pyjsonrpc.HttpClient( url=rpc_url, username=COINS[self.coin]["rpc-user"], password=COINS[self.coin]["rpc-password"]) self.logger.debug(self.coin, "RPC connection ok") self.connected = True else: self.logger.debug(self.coin, "bridge not found") return self.connected
def main(argv): http_client = pyjsonrpc.HttpClient(url="http://localhost:4000/jsonrpc") if http_client is None: print 'Could not connect to JSON-RPC server' sys.exit(2) usage = "usage: python enforce_throughput_service.py <switch_id> <src> <dst> <speed B/s>" try: opts, args = getopt.getopt(argv, "h", []) except getopt.GetoptError: print usage sys.exit() switch = args[0] src = args[1] dst = args[2] speed = args[3] meter_id = http_client.call("enforce_service", switch, src, [dst], speed) print "Meter ID is: %d" % meter_id
def recognise(request): # only if get 'image' ,run this code? f = request.FILES['image'] #Return a k length list of unique elements chosen from the population sequence name=''.join(random.sample(string.ascii_letters + string.digits, 3))+f.name # store the file in disk with open('static/img/'+name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) image = caffe.io.load_image('static/img/'+name) #images,conf_List = cropImageWithSSD(detection_net,image) images = cropImageWithSSD(detection_net,image) if not isinstance(images,list): images = images[0] img = scipy.misc.toimage(images[0]) img.save('static/img/det'+name) #print img.shape # exmaple.jpg 为需要传给接口的图片,最好缩放到256*256*3 的jpg格式 # 这句话不是没有道理的。 # can we 传递 filename #content = base64.b64encode(open('static/img/'+name, 'rb').read()) #content_det = base64.b64encode(open('static/img/det'+name, 'rb').read()) beg = time.time() url = 'http://localhost:9010' rpc_client = pyjsonrpc.HttpClient(url,gzipped=True) # return a list resp = rpc_client.add([name,'det'+name]) print time.time()-beg data={} data["image_name"] = name data["image_det_name"]='det'+name # for src image data["result"] = resp[:8] # for detection image data["result2"] = resp[8:] return render(request, 'search.html',data)
import pyjsonrpc import yaml #URL = "http://localhost:6060/" with open('../configuration/common_conf.yaml', 'r') as stream: try: config = yaml.load(stream) except yaml.YAMLError as error5: print error5 client = pyjsonrpc.HttpClient( url=config['news_topic_modeling_service_client']['URL']) def classify(text): topic = client.call('classify', text) print "Topic: %s" % str(topic) return topic
def send_checkpoint(): global remote_base_path print "- send CHECKPOINT to %s:%s" % (dest, remote_base_path) run_cmd_timed("rsync -aqz checkpoint %s:%s" % (dest, remote_base_path), "checkpoint_send") def stop_kad(): print "- stop keepalived..." run_cmd_timed("killall keepalived") if __name__ == "__main__": ip = get_ip() print "- host ip: %s, service ip (vip): %s" % (ip, vip) cli = pyjsonrpc.HttpClient(url="http://%s:9000/jsonrpc" % dest) status_cli = pyjsonrpc.HttpClient(url="http://%s/jsonrpc" % status_server) # tell the status server that we have the container now status_cli.set_container(container, ip) os.system("rm -rf predump checkpoint") times["migrate_start"] = time.time() remote_base_path = cli.prepare(ip, container) print "- remote path: %s:%s" % (dest, remote_base_path) send_rootfs() pre_dump() send_pre_dump() # checkpoint_dump()
import pyjsonrpc import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import parameters # Recommendation_SERVER_PORT = 5050 URL = "http://" + parameters.AWS_RPC_SERVER_HOST + ":5050/" client = pyjsonrpc.HttpClient(url=URL) def getPreferenceForUser(userId): preference = client.call('getPreferenceForUser', userId) print("Preference list: {}".format(str(preference))) return preference
#!/usr/bin/env python # coding: utf-8 # BEGIN --- required only for testing, remove in real world code --- BEGIN import os import sys THISDIR = os.path.dirname(os.path.abspath(__file__)) APPDIR = os.path.abspath(os.path.join(THISDIR, os.path.pardir, os.path.pardir)) sys.path.insert(0, APPDIR) # END --- required only for testing, remove in real world code --- END import pyjsonrpc import collections rpc_client = pyjsonrpc.HttpClient("http://localhost:8080", gzipped=True) print u"UNORDERED" print rpc_client.call( "format_text", dict([("a", "AAA"), ("b", "BBB"), ("c", "CCC"), ("d", "DDD"), ("e", "EEE"), ("f", "FFF"), ("g", "GGG")])) print u"ORDERED" print rpc_client.call( "format_text", collections.OrderedDict([("a", "AAA"), ("b", "BBB"), ("c", "CCC"), ("d", "DDD"), ("e", "EEE"), ("f", "FFF"), ("g", "GGG")]))