def from_json(cls, json): instance_id = json.get('EC2InstanceId', None) hostname = json.get('Hostname') resource_arn = json.get('ResourceARN') telemetry_records = json['TelemetryRecords'] return cls(instance_id, hostname, resource_arn, telemetry_records)
def listsummary(appid): url = "https://itunes.apple.com/cn/customer-reviews/id{0}?dataOnly=true&displayable-kind=11&l=en&appVersion=all" url = url.format(appid) try: response = requests.get(url,headers=headers) response.encoding='utf8' json = response.json() # The total count of rating app_review['ratingCount'] = json.get('ratingCount') # The total count of reviews totalReview = json.get('totalNumberOfReviews') app_review['totalNumberOfReviews'] = totalReview # "ratingCountList": [ # 127, # 21, # 42, # 121, # 2075 # ], app_review['ratingCountList'] = json.get('ratingCountList') app_review['ratingAverage'] = json.get('ratingAverage') print(app_review) listreviews(appid, totalReview); except: print("The given appid {} is not found in iTunes Store".format(appid))
def geocode(address): """ 利用百度geocoding服务解析地址获取位置坐标 :param address:需要解析的地址 :return: """ geocoding = {'s': 'rsv3', 'key': key, 'city': '全国', 'address': address} res = requests.get( "http://restapi.amap.com/v3/geocode/geo", params=geocoding) if res.status_code == 200: json = res.json() status = json.get('status') count = json.get('count') if status == '1' and int(count) >= 1: geocodes = json.get('geocodes')[0] lng = float(geocodes.get('location').split(',')[0]) lat = float(geocodes.get('location').split(',')[1]) return [lng, lat] else: return None else: return None
def json_print_value(json,key,number): number = number +1 #number代表第几层结构 key_value = "not found" if isinstance(json,dict): for k in json.keys(): if k == key: #print json.get(key),number return json.get(key),number else: #print k #print json.get(k); s = json_print_value(json.get(k), key, number) if s != 'not found': #print s return s elif isinstance(json,list): print "is a list" for json_array in json: s = json_print_value(json_array, key, number) if s != 'not found': #print s return s #print key_value return key_value
def signup(): conn = rethink_conn.conn() json = request.get_json(force=True) email = json.get('username','') # Email validation if not re.match("^[^@ ]+@[^@ ]+\.[^@ ]+$", email): return jsonify({'status': 'Not a valid email'}) already_taken = len(list(r.table("users").filter( r.row["email"] == email).run(conn))) > 0 if already_taken: return jsonify({'status': 'Already Taken'}) password = b"%s" % json.get('password', '') # Create user token = _auth.create_user(email, password.encode('utf-8')) # Create Redis Token And Current Plan # TODO # days left till end of trial # end of current plan # billing cycle # return token return jsonify({'status': 'OK', 'token': token})
def fromJsonFragment(json, nameFromParent): if isinstance(json, dict) and hasKeys(json.keys(), ["entries", "sum"], ["name"]): if json["entries"] in ("nan", "inf", "-inf") or isinstance(json["entries"], numbers.Real): entries = float(json["entries"]) else: raise JsonFormatException(json["entries"], "Sum.entries") if isinstance(json.get("name", None), basestring): name = json["name"] elif json.get("name", None) is None: name = None else: raise JsonFormatException(json["name"], "Sum.name") if json["sum"] in ("nan", "inf", "-inf") or isinstance(json["sum"], numbers.Real): sum = float(json["sum"]) else: raise JsonFormatException(json["sum"], "Sum.sum") out = Sum.ed(entries, sum) out.quantity.name = nameFromParent if name is None else name return out.specialize() else: raise JsonFormatException(json, "Sum")
def BDXY(self,address): "百度地图bd09 return (lng,lat)" """ 利用百度geocoding服务解析地址获取位置坐标 :param address:需要解析的地址 :return: """ key = '2ae1130ce176b453fb29e59a69b18407' geocoding = {'output': 'json', 'ak': key, 'address': address} res = requests.get("http://api.map.baidu.com/geocoder/v2/", params=geocoding) if res.status_code == 200: json = res.json() status = json.get('status') #confidence = json.get('confidence') if status == 0 : geocodes = json.get('result') location = geocodes.get('location') lng = float(location.get('lng')) lat = float(location.get('lat')) return (lng, lat) else: return None else: return None
def grant(self): params = dict( grant_type="client_credential", appid=self.appid, secret=self.appsecret ) resp = self.requests("get", "/token", params=params) try: json = resp.json() code = json.get("errcode") if code: if self.on_wechaterror: self.on_wechaterror(resp, code) else: self.__accesstoken = json["access_token"] expires_in = json.get("expires_in") or 7200 # 更新外部token if self.on_wechatgranted: self.on_wechatgranted(resp, self.__accesstoken, expires_in) self._update_accesstoken(self.__accesstoken, expires_in) except Exception as e: if self.on_servererror: self.on_servererror(resp, code, e) return self.__accesstoken
def response(json, cb): """ Отвечает на один RPC запрос """ if not isinstance(json, dict) or len(json) == 0: return JsonRpcRequestPipe.invalid_request() _id, params, method, version = json.get("id"), json.get("params", []), json.get("method"), json.get("jsonrpc") if not version: return JsonRpcRequestPipe.invalid_request(_id) if _id else None if not isinstance(method, str): return JsonRpcRequestPipe.invalid_request(_id) if _id else None if not isinstance(params, (dict, list)): return JsonRpcRequestPipe.invalid_params(_id) if _id else None # noinspection PyBroadException try: return JsonRpcRequestPipe.success(cb(method, params), _id) if _id else None except (Request.RequiredArgumentIsMissing, Request.ArgumentTypeError): return JsonRpcRequestPipe.invalid_params(_id) if _id else None except NotImplementedError: return JsonRpcRequestPipe.method_not_found(_id) if _id else None except: return JsonRpcRequestPipe.server_error(0, _id) if _id else None
def _onresponse(self, resp): """处理一般返回""" try: json = resp.json() code = int(json.get("errcode")) or 0 rv = (json, code) if code: # 处理异常 if self.on_wechaterror: self.on_wechaterror(resp, code) resp = self._handleerror(json, code) if resp: json = resp.json() code = int(json.get("errcode")) or 0 if code: if self.on_wechaterror: self.on_wechaterror(resp, code) else: # 成功处理 rv = (json, code) return rv except Exception as e: if self.on_servererror: self.on_servererror(resp, code, e) return {}, -2
def fromJsonFragment(json, nameFromParent): if isinstance(json, dict) and hasKeys(json.keys(), ["entries", "mean", "variance"], ["name"]): if json["entries"] in ("nan", "inf", "-inf") or isinstance(json["entries"], numbers.Real): entries = float(json["entries"]) else: raise JsonFormatException(json["entries"], "Deviate.entries") if isinstance(json.get("name", None), basestring): name = json["name"] elif json.get("name", None) is None: name = None else: raise JsonFormatException(json["name"], "Deviate.name") if json["mean"] in ("nan", "inf", "-inf") or isinstance(json["mean"], numbers.Real): mean = float(json["mean"]) else: raise JsonFormatException(json["mean"], "Deviate.mean") if json["variance"] in ("nan", "inf", "-inf") or isinstance(json["variance"], numbers.Real): variance = float(json["variance"]) else: raise JsonFormatException(json["variance"], "Deviate.variance") out = Deviate.ed(entries, mean, variance) out.quantity.name = nameFromParent if name is None else name return out.specialize() else: raise JsonFormatException(json, "Deviate")
def fromJsonFragment(json, nameFromParent): if isinstance(json, dict) and hasKeys(json.keys(), ["entries", "sub:type", "numerator", "denominator"], ["name", "sub:name"]): if json["entries"] in ("nan", "inf", "-inf") or isinstance(json["entries"], numbers.Real): entries = float(json["entries"]) else: raise JsonFormatException(json, "Fraction.entries") if isinstance(json.get("name", None), basestring): name = json["name"] elif json.get("name", None) is None: name = None else: raise JsonFormatException(json["name"], "Fraction.name") if isinstance(json["sub:type"], basestring): factory = Factory.registered[json["sub:type"]] else: raise JsonFormatException(json, "Fraction.type") if isinstance(json.get("sub:name", None), basestring): subName = json["sub:name"] elif json.get("sub:name", None) is None: subName = None else: raise JsonFormatException(json["sub:name"], "Fraction.sub:name") numerator = factory.fromJsonFragment(json["numerator"], subName) denominator = factory.fromJsonFragment(json["denominator"], subName) out = Fraction.ed(entries, numerator, denominator) out.quantity.name = nameFromParent if name is None else name return out.specialize() else: raise JsonFormatException(json, "Fraction")
def from_json(pr, name, deps, json): return DeployStep(pr, name, deps, json['namespace'], # FIXME config_file json['config'], json.get('link'), json.get('wait'))
def add_result(): if request.json: json = request.json access_token = json.get("accessToken") # Check that this is an admin user. if auth.is_admin(access_token) is False: return Response(status=PERMISSION_DENIED) event_id = json.get("event_id") member_id = json.get("member_id") score = json.get("score") if not event_id: return Response(status=MISSING_PARAM_CODE) if not member_id: return Response(status=MISSING_PARAM_CODE) if not score: return Response(status=MISSING_PARAM_CODE) else: connection = query_db.get_connection(current_db_location()) if connection is not None: query_db.insert_into_result(connection, event_id, member_id, score) connection.close() return Response(status=SUCCESS_CODE) else: # Connection to database failed return Response(status=FAILURE_CODE) # Failure return Response(status=FAILURE_CODE)
def from_json(json): email = json.get("email") password = json.get("password") password2 = json.get("repeatPassword") phone_primary = json.get("primary_phone") user_name = json.get("username") first_name = json.get("first_name") last_name = json.get("last_name") role = json.get("role_name") organization_id = json.get("organization_id") email_opt_in = json.get("email_opt_in") # Validate some of the field. new_user = User() new_user.validate_email(email) new_user.validate_username(user_name) new_user.validate_password(password, password2) pass_hash = generate_password_hash(password) # All passes, return the User object ready to be stored. return User( email=email, pass_hash=pass_hash, phone_primary=phone_primary, user_name=user_name, user_id=user_name, first_name=first_name, last_name=last_name, organization_id=organization_id, role=role, email_opt_in=email_opt_in, )
def fromJsonFragment(json, nameFromParent): if isinstance(json, dict) and hasKeys(json.keys(), ["entries", "values", "range"], ["name"]): if json["entries"] in ("nan", "inf", "-inf") or isinstance(json["entries"], numbers.Real): entries = json["entries"] else: raise JsonFormatException(json["entries"], "Bag.entries") if isinstance(json.get("name", None), basestring): name = json["name"] elif json.get("name", None) is None: name = None else: raise JsonFormatException(json["name"], "Bag.name") if json["values"] is None: values = None elif json["values"] is None or isinstance(json["values"], list): values = {} for i, nv in enumerate(json["values"]): if isinstance(nv, dict) and hasKeys(nv.keys(), ["w", "v"]): if nv["w"] in ("nan", "inf", "-inf") or isinstance(nv["w"], numbers.Real): n = float(nv["w"]) else: raise JsonFormatException(nv["w"], "Bag.values {0} n".format(i)) if nv["v"] in ("nan", "inf", "-inf") or isinstance(nv["v"], numbers.Real): v = floatOrNan(nv["v"]) elif isinstance(nv["v"], basestring): v = nv["v"] elif isinstance(nv["v"], (list, tuple)): for j, d in enumerate(nv["v"]): if d not in ("nan", "inf", "-inf") and not isinstance(d, numbers.Real): raise JsonFormatException(d, "Bag.values {0} v {1}".format(i, j)) v = tuple(map(floatOrNan, nv["v"])) else: raise JsonFormatException(nv["v"], "Bag.values {0} v".format(i)) values[v] = n else: raise JsonFormatException(nv, "Bag.values {0}".format(i)) elif json["values"] is None: values = None else: raise JsonFormatException(json["values"], "Bag.values") if isinstance(json["range"], basestring): range = json["range"] else: raise JsonFormatException(json["range"], "Bag.range") out = Bag.ed(entries, values, range) out.quantity.name = nameFromParent if name is None else name return out.specialize() else: raise JsonFormatException(json, "Bag")
def __init__(self, json=None): #self.cloud_id = json.get('cloud_id') if json else None self.token_id = json.get('token_id') if json else None self.token_type = json.get('token_type') if json else None self.token_str = json.get('token_str') if json else None self.opr_code = json.get('opr_code') if json else None self.details = json.get('details') if json else None
def __init__(self, json, *args, **kwargs): """Initializes a sim state varioable from the given JSON dict. Args: json: JSON dict. """ super(SimVar, self).__init__(*args, **kwargs) self.json = json self.name = json["name"] self.cap_name = self.name[0:1].capitalize() + self.name[1:] self.type = SIM_TYPES_[json["type"]] self.entity_type = json.get("entity_type", None) self.flags = self._parse_flags(json.get("flags", [])) self.onchange = json.get("onchange", "") self.extra_args = "" if self.type.get("extra_args", None): for arg_name in self.type["extra_args"]: if len(self.extra_args): self.extra_args += ", " value = json.get(arg_name, "undefined") if value == True: value = "true" elif value == False: value = "false" self.extra_args += value
def member_obj_from_json(json, identifier): firstname = json.get("firstname") lastname = json.get("lastname") handicap = json.get("handicap") if not firstname or not lastname or not handicap: return None return Member(identifier, firstname, lastname, handicap)
def add_member(): if request.json: json = request.json access_token = json.get("accessToken") # Check that this is an admin user. if auth.is_admin(access_token) is False: return Response(status=PERMISSION_DENIED) firstname = json.get("firstname") lastname = json.get("lastname") handicap = json.get("handicap") if not firstname: return Response(status=MISSING_PARAM_CODE) if not lastname: return Response(status=MISSING_PARAM_CODE) if not handicap: return Response(status=MISSING_PARAM_CODE) else: connection = query_db.get_connection(current_db_location()) if connection is not None: query_db.insert_into_member(connection, firstname, lastname, handicap) connection.close() return Response(status=SUCCESS_CODE) else: # Connection to database failed return Response(status=FAILURE_CODE) return Response(status=FAILURE_CODE)
def add_poy(): if request.json: json = request.json access_token = json.get('accessToken') # Check that this user is admin. if auth.is_admin(access_token) is False: return Response(status=PERMISSION_DENIED) member_id = json.get('member_id') year = json.get('year') score = json.get('score') if not member_id: return Response(status=MISSING_PARAM_CODE) else: connection = query_db.get_connection(current_db_location()) if connection is not None: query_db.insert_into_poy(connection, member_id, year, score) connection.close() return Response(status=SUCCESS_CODE) else: return Response(status=FAILURE_CODE) else: return Response(status=FAILURE_CODE)
def process(self, json): result = sympy.sympify(json.get('Item')) if json.get('CalculatorKeyword') == "combien": self.stored_calculation = result if json.get('CalculatorKeyword') == "ajoute": self.stored_calculation += result print("cela fait %s" % self.stored_calculation)
def __init__(self, filename): json = self.read_json(filename) self.preferred_team = json.get("preferred_team") self.preferred_division = json.get("preferred_division", "NL Central") self.rotate_games = json.get("rotate_games", False) self.display_standings = json.get("display_standings", False) self.debug_enabled = json.get("debug_enabled", False)
def authenticate_post(): json = request.json user_id = json['userId'] device_id = json['deviceId'] installation_id = json['installationId'] # Get optionally - old clients do not send this client_version = json.get('clientVersion') messaging_token = json.get('messagingToken', '') # 1. check that user exists or abort users_table_id = verify_user_id(user_id) devices_table_id = get_device_table_id( users_table_id, device_id, installation_id) session_token = get_session_token_for_device(devices_table_id) if session_token is None: print('User is not registered. userId=' + user_id) abort(403) # 2. Update messaging token, if included if len(messaging_token) > 1: update_messaging_token(devices_table_id, messaging_token) update_last_activity(devices_table_id, client_version) # 3. Update log client_log_table_insert( devices_table_id, get_user_id_from_device_id(devices_table_id), "MOBILE-AUTHENTICATE", "ClientVersion:" + (client_version or "")) return jsonify({ 'sessionToken': session_token })
def __init__(self, json): self.id = json["id"] if isinstance(self.id, float): self.id = int(self.id) self.first_name = json["first_name"] self.last_name = json.get("last_name", None) self.username = json.get("username", None)
def GDXY(self,address): "高德地图gcj02 return (lng,lat)" """ 利用高德geocoding服务解析地址获取位置坐标 :param address:需要解析的地址 :return: """ key = '7ba42b62224e28a20770deeb2a2ce246' geocoding = {'s': 'rsv3', 'key': key, 'city': '全国', 'address': address} res = requests.get( "http://restapi.amap.com/v3/geocode/geo", params=geocoding) if res.status_code == 200: json = res.json() status = json.get('status') count = json.get('count') if status == '1' and int(count) >= 1: geocodes = json.get('geocodes')[0] lng = float(geocodes.get('location').split(',')[0]) lat = float(geocodes.get('location').split(',')[1]) return (lng, lat) else: return None else: return None
def http_call(self, name, method, json, xml, output=True): name = name.replace('_', '-') print "http call for %s" % name http = httplib2.Http() req_headers = {'User-Agent': "python-example-client", 'Content-Type': "application/json", 'Accept': "application/json" } req_headers.update(self.headers) content_type = 'json' request_body = json.get('body', None) url = json.get('url') if output: with open("%sdb-%s-request.%s" % (self.directory, name, content_type), "w") as file: output = self.output_request(url, req_headers, request_body, content_type, method) if self.replace_host: output = output.replace(self.api_url, self.replace_host) pre_host_port = urlparse(self.api_url).netloc post_host = urlparse(self.replace_host).netloc output = output.replace(pre_host_port, post_host) file.write(output) json_resp = resp, resp_content = http.request(url, method, body=request_body, headers=req_headers) if output: with open("%sdb-%s-response.%s" % (self.directory, name, content_type), "w") as file: output = self.output_response(resp, resp_content, content_type) if self.replace_host: output = output.replace(self.api_url, self.replace_host) pre_host_port = urlparse(self.api_url).netloc post_host = urlparse(self.replace_host).netloc output = output.replace(pre_host_port, post_host) file.write(output) content_type = 'xml' req_headers['Accept'] = 'application/xml' req_headers['Content-Type'] = 'application/xml' request_body = xml.get('body', None) url = xml.get('url') if output: with open("%sdb-%s-request.%s" % (self.directory, name, content_type), "w") as file: output = self.output_request(url, req_headers, request_body, content_type, method) if self.replace_host: output = output.replace(self.api_url, self.replace_host) pre_host_port = urlparse(self.api_url).netloc post_host = urlparse(self.replace_host).netloc output = output.replace(pre_host_port, post_host) file.write(output) xml_resp = resp, resp_content = http.request(url, method, body=request_body, headers=req_headers) if output: with open("%sdb-%s-response.%s" % (self.directory, name, content_type), "w") as file: output = self.output_response(resp, resp_content, content_type) if self.replace_host: output = output.replace(self.api_url, self.replace_host) pre_host_port = urlparse(self.api_url).netloc post_host = urlparse(self.replace_host).netloc output = output.replace(pre_host_port, post_host) file.write(output) return json_resp, xml_resp
def fromJson(self, json): self.is_end = json.get('endOfWord') self.pos = json.get('pos', 0) self.src = json.get('src') self.text = json.get('text') self.variants = json.get('data', []) self.variants.insert(0, self.words) return self
def __init__(self, action, json): self.action = action self.json = json self.result = json['result'] self.feedback = json.get('feedback', {}) self.message = json.get('message', None) self.cause = json.get('cause', None) self.stacktrace = json.get('stacktrace', None)
def instantiate_from_json(json, default_class=None, default_parameters=None, pass_parameters=None): if pass_parameters is None: pass_parameters = [] return proso.util.instantiate( json.get('class', default_class), *pass_parameters, **json.get('parameters', default_parameters if default_parameters else {}) )
def get_images(self,json): if json.get('data'): for item in json.get('data'): title = item.get('title') # images = item.get('imgae_url') print(title)
import json headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer eyJrIjoiM09kR0RFWjNZSzUxWXRZNDR0SEdKN2Y1RERHOFVZbU0iLCJuIjoic2hhZHIxayIsImlkIjoxfQ==' } def get_json(uid): resp = requests.get('http://localhost:3000/api/dashboards/uid/' + uid, headers=headers) return json.loads(resp.text) def push_json(uid, json): resp = requests.post('http://localhost:3000/api/dashboards/db', json=json, headers=headers) def get_name_panel(json): return json.get('dashboard').get('panels')[0].get('title') def change_name(json, name): json.get('dashboard').get('panels')[0].update({'title': name}) requests.post('http://localhost:3000/api/dashboards/db', json=json, headers=headers) # print(d) # change time panel # print(d.get('dashboard')) # post changes # # print(resp) # print(resp.text) if __name__ == '__main__': json = get_json('rzlhlzrik') print(json.get('dashboard').get('panels')[0].get('targets')[0].get('tags'))
def change_name(json, name): json.get('dashboard').get('panels')[0].update({'title': name}) requests.post('http://localhost:3000/api/dashboards/db', json=json, headers=headers)
def parseDaraJson(self, json): for item in json.get("response").get("docs"): yield item
def from_json(params): json = params.json return RunImageStep(params, json['image'], json['script'], json.get('inputs'), json.get('outputs'), json.get('resources'), json.get('serviceAccount'), json.get('secrets'), json.get('alwaysRun', False))
def _parse_object(name: str, json: Dict[str, Any]) -> Optional[SchemaObject]: if json.get("type", None) == "object": properties = _parse_items(json.get("properties", {})) return SchemaObject(name=name, properties=properties) return None
def from_json(params): json = params.json return CreateDatabaseStep(params, json['databaseName'], json['namespace'], json['migrations'], json.get('shutdowns', []), json.get('inputs'))
def from_json(params): json = params.json return CreateNamespaceStep(params, json['namespaceName'], json.get('adminServiceAccount'), json.get('public', False), json.get('secrets'))
def from_json(params): json = params.json return BuildImageStep(params, json['dockerFile'], json.get('contextPath'), json.get('publishAs'), json.get('inputs'))
def getProductDataFromJson(request): json = request.get_json() return (json.get('name'), json.get('desc'), json.get('category'))
def editar_tarefa(id): json = get_json() TAREFAS[id] = Tarefa(id, json.get('titulo'), json.get('usuario'), json.get('completo')) return jsonify(TAREFAS[id].__dict__)
import json import xlwt with open('/home/Tyella/文档/student.txt') as f: content = f.read() wb = xlwt.Workbook() ws = wb.add_sheet('stduent') json = json.loads(content) i = 0 for con in json: values = json.get(con) ws.write(i, 0, con) j = 1 for value in values: ws.write(i, j, value) j += 1 i += 1 wb.save('/home/Tyella/文档/stduent.xls')
def check_json_has_paramters(json, parameters): for parameter in parameters: if json.get(parameter) is None: return False return True
def _parse_any_of(name: str, json: Dict[str, Any]) -> Optional[SchemaAnyOf]: if json.get("anyOf", None): items = [_parse_item(name, item) for item in json["anyOf"]] return SchemaAnyOf(name=name, any_of=items) return None
def _parse_array(name: str, json: Dict[str, Any]) -> Optional[SchemaArray]: if json.get("type", None) == "array": return SchemaArray(name=name, item=_parse_item("", json.get("items", {}))) return None
def is_pingdom(json): return json.get('check_name', None) is not None
def is_ga(json): return json.get('query', None) is not None
def is_ga_realtime(json): return is_ga(json) and json.get('collector', None) is not None
import json import xlwt wb = xlwt.Workbook() ws = wb.add_sheet('city') with open('/home/Tyella/文档/city.txt') as f: content = f.read() json = json.loads(content) i = 0 for con in json: ws.write(i, 0, con) ws.write(i, 1, json.get(con)) i += 1 wb.save('/home/Tyella/文档/city.xls')
def is_ga_content(json): return is_ga(json) and json.get('filtersets', None) is not None
def _board_from_json(self, json): board = Board(self, json['id'], name=json['name'].encode('utf-8')) board.description = json.get('desc', '').encode('utf-8') board.closed = json['closed'] board.url = json['url'] return board
def evaluate(json, variables): result = {} result['edges'] = json['edges'] result['faces'] = json['faces'] result['vertices'] = [] result['vertexdata'] = [] result['facedata'] = [] groups = {} def eval_list(coords): if isinstance(coords, str): coords = [coords] if isinstance(coords, dict): result = dict() for key in coords: result[key] = eval_list(coords[key]) return result v = [] for c in coords: if isinstance(c, str): try: val = safe_eval(c, variables) #self.debug("EVAL: {} with {} => {}".format(c, variables, val)) except NameError as e: exception(e) val = 0.0 else: val = c v.append(val) return v for idx, vertex in enumerate(json['vertices']): if isinstance(vertex, (list, tuple)) and len(vertex) == 3: coords = vertex elif isinstance(vertex, (list, tuple)) and len(vertex) == 4 and isinstance( vertex[-1], (str, list, tuple)): coords = vertex[:-1] g = vertex[-1] if isinstance(g, str): groupnames = [g] else: groupnames = g for groupname in groupnames: if groupname in groups: groups[groupname].append(idx) else: groups[groupname] = [idx] v = eval_list(coords) result['vertices'].append(v) for idx, item in enumerate(json.get('vertexdata', [])): if isinstance(item, (str, list, tuple, dict)): coords = item else: result['vertexdata'].append(item) continue v = eval_list(coords) result['vertexdata'].append(v) for idx, item in enumerate(json.get('facedata', [])): if isinstance(item, (str, list, tuple, dict)): coords = item else: result['facedata'].append(item) continue v = eval_list(coords) result['facedata'].append(v) return result, groups
def fromJsonFragment(json, nameFromParent): if isinstance(json, dict) and hasKeys(json.keys(), [ "low", "high", "entries", "values:type", "values", "underflow:type", "underflow", "overflow:type", "overflow", "nanflow:type", "nanflow" ], ["name", "values:name"]): if json["low"] in ("nan", "inf", "-inf") or isinstance( json["low"], numbers.Real): low = float(json["low"]) else: raise JsonFormatException(json, "Bin.low") if json["high"] in ("nan", "inf", "-inf") or isinstance( json["high"], numbers.Real): high = float(json["high"]) else: raise JsonFormatException(json, "Bin.high") if json["entries"] in ("nan", "inf", "-inf") or isinstance( json["entries"], numbers.Real): entries = float(json["entries"]) else: raise JsonFormatException(json, "Bin.entries") if isinstance(json.get("name", None), basestring): name = json["name"] elif json.get("name", None) is None: name = None else: raise JsonFormatException(json["name"], "Bin.name") if isinstance(json["values:type"], basestring): valuesFactory = Factory.registered[json["values:type"]] else: raise JsonFormatException(json, "Bin.values:type") if isinstance(json.get("values:name", None), basestring): valuesName = json["values:name"] elif json.get("values:name", None) is None: valuesName = None else: raise JsonFormatException(json["values:name"], "Bin.values:name") if isinstance(json["values"], list): values = [ valuesFactory.fromJsonFragment(x, valuesName) for x in json["values"] ] else: raise JsonFormatException(json, "Bin.values") if isinstance(json["underflow:type"], basestring): underflowFactory = Factory.registered[json["underflow:type"]] else: raise JsonFormatException(json, "Bin.underflow:type") underflow = underflowFactory.fromJsonFragment( json["underflow"], None) if isinstance(json["overflow:type"], basestring): overflowFactory = Factory.registered[json["overflow:type"]] else: raise JsonFormatException(json, "Bin.overflow:type") overflow = overflowFactory.fromJsonFragment(json["overflow"], None) if isinstance(json["nanflow:type"], basestring): nanflowFactory = Factory.registered[json["nanflow:type"]] else: raise JsonFormatException(json, "Bin.nanflow:type") nanflow = nanflowFactory.fromJsonFragment(json["nanflow"], None) out = Bin.ed(low, high, entries, values, underflow, overflow, nanflow) out.quantity.name = nameFromParent if name is None else name return out.specialize() else: raise JsonFormatException(json, "Bin")
def __init__(self, resolutions=None, resolution=None, protocols=None, protocol=None, authorizationTypes=None, authorizationType=None, videoCodecs=None, videoCodec=None, audioCodecs=None, audioCodec=None, uri=None, expirationTime=None, idleTimeoutSeconds=None, json=None): self.resolution_value = self.Resolution() self.resolutions_value = {} self.protocol_value = None self.protocols_value = [] self.authorizationType_value = None self.authorizationTypes_value = [] self.videoCodec_value = None self.videoCodecs_value = [] self.audioCodec_value = None self.audioCodecs_value = [] self.uri = None self.expirationTime = None self.idleTimeoutSeconds = None if json: self.resolutions = json.get('resolutions') self.resolution = json.get('resolution') self.protocols = json.get('protocols') self.protocol = json.get('protocol') self.authorizationTypes = json.get('authorizationTypes') self.authorizationType = json.get('authorizationType') self.videoCodecs = json.get('videoCodecs') self.videoCodec = json.get('videoCodec') self.audioCodecs = json.get('audioCodecs') self.audioCodec = json.get('audioCodec') self.uri = json.get('uri') self.expirationTime = json.get('expirationTime') self.idleTimeoutSeconds = json.get('idleTimeoutSeconds') else: self.resolutions = resolutions self.resolution = resolution self.protocols = protocols self.protocol = protocol self.authorizationTypes = authorizationTypes self.authorizationType = authorizationType self.videoCodecs = videoCodecs self.videoCodec = videoCodec self.audioCodecs = audioCodecs self.audioCodec = audioCodec self.uri = uri self.expirationTime = expirationTime self.idleTimeoutSeconds = idleTimeoutSeconds
def get_name_panel(json): return json.get('dashboard').get('panels')[0].get('title')
def cadastrar_tarefa(): json = get_json() tarefa = Tarefa(len(TAREFAS), json.get('titulo'), json.get('usuario')) TAREFAS.append(tarefa) return jsonify(todo=tarefa.__dict__)
async def wrapper(*args, **kwargs): json = await request.json query_kind = "NA" if json is None else json.get("query_kind", "NA") log_elements = [ "", f"{func.__name__.upper()}", query_kind.upper(), get_jwt_identity(), request.headers.get("Remote-Addr"), kwargs.get("query_id", "NA"), ] current_app.query_run_logger.info(":".join(log_elements)) try: # Cross-check the query kind with the backend request.socket.send_json( {"action": "get_query_kind", "query_id": kwargs["query_id"]} ) message = await request.socket.recv_json() if "query_kind" in message: query_kind = message["query_kind"] log_elements[2] = query_kind.upper() else: return jsonify({}), 404 except KeyError: if query_kind == "NA": return ( jsonify( { "status": "Error", "reason": "Expected 'query_kind' parameter.", } ), 400, ) claims = get_jwt_claims().get(query_kind, {}) endpoint_claims = claims.get("permissions", {}) spatial_claims = claims.get("spatial_aggregation", {}) if (claim_type not in endpoint_claims) or ( endpoint_claims[claim_type] == False ): # Check access claims log_elements[0] = "UNAUTHORIZED" current_app.query_run_logger.error(":".join(log_elements)) return ( jsonify( { "status": "Error", "reason": f"'{claim_type}' access denied for '{query_kind}' query", } ), 401, ) elif claim_type == "get_result": # Check spatial aggregation claims request.socket.send_json( {"action": "get_params", "query_id": kwargs["query_id"]} ) message = await request.socket.recv_json() if "params" not in message: return jsonify({}), 404 try: aggregation_unit = message["params"]["aggregation_unit"] except KeyError: return ( jsonify( { "status": "Error", "reason": "Missing parameter: 'aggregation_unit'", } ), 500, ) if aggregation_unit not in spatial_claims: log_elements[0] = "UNAUTHORIZED" current_app.query_run_logger.error(":".join(log_elements)) return ( jsonify( { "status": "Error", "reason": f"'get_result' access denied for '{aggregation_unit}' " f"aggregated result of '{query_kind}' query", } ), 401, ) else: pass else: pass return await func(*args, **kwargs)
def readable_output(json, organization='biocontainers', channel='bioconda'): # if json is empty: if sum([ len(json[destination][results]) for destination in json for results in json[destination] ]) == 0: sys.stdout.write('No results found for that query.\n') return # return results for quay, conda and singularity together if sum([ len(json[destination][results]) for destination in [ 'quay', 'conda', 'singularity', ] for results in json.get(destination, []) ]) > 0: sys.stdout.write("The query returned the following result(s).\n") # put quay, conda etc results as lists in lines lines = [['LOCATION', 'NAME', 'VERSION', 'COMMAND\n']] for results in json.get('quay', {}).values(): for result in results: lines.append([ 'quay', result['package'], result['version'], 'docker pull quay.io/%s/%s:%s\n' % (organization, result['package'], result['version']) ]) # NOT a real solution for results in json.get('conda', {}).values(): for result in results: lines.append([ 'conda', result['package'], '{}--{}'.format(result['version'], result['build']), 'conda install -c {} {}={}={}\n'.format( channel, result['package'], result['version'], result['build']) ]) for results in json.get('singularity', {}).values(): for result in results: lines.append([ 'singularity', result['package'], result['version'], 'wget https://depot.galaxyproject.org/singularity/{}:{}\n'. format(result['package'], result['version']) ]) col_width0, col_width1, col_width2 = ( max(len(line[n]) for line in lines) + 2 for n in (0, 1, 2)) # def max col widths for the output # create table for line in lines: sys.stdout.write("".join( (line[0].ljust(col_width0), line[1].ljust(col_width1), line[2].ljust(col_width2), line[3]))) # output if json.get('github_recipe_present', False): sys.stdout.write('\n' if 'lines' in locals() else '') sys.stdout.write( 'The following recipes were found in the bioconda-recipes repository which exactly matched one of the search terms:\n' ) lines = [['QUERY', 'LOCATION\n']] for recipe in json['github_recipe_present']['recipes']: lines.append([ recipe, "https://api.github.com/repos/bioconda/bioconda-recipes/contents/recipes/%s\n" % recipe ]) col_width0 = max(len(line[0]) for line in lines) + 2 for line in lines: sys.stdout.write("".join( (line[0].ljust(col_width0), line[1]))) # output if sum( [len(json['github'][results]) for results in json.get('github', [])]) > 0: sys.stdout.write('\n' if 'lines' in locals() else '') sys.stdout.write( "Other result(s) on the bioconda-recipes GitHub repository:\n") lines = [['QUERY', 'FILE', 'URL\n']] for search_string, results in json.get('github', {}).items(): for result in results: lines.append([ search_string, result['name'], 'https://github.com/bioconda/bioconda-recipes/tree/master/%s\n' % result['path'] ]) # def max col widths for the output col_width0, col_width1 = (max(len(line[n]) for line in lines) + 2 for n in (0, 1)) for line in lines: sys.stdout.write("".join( (line[0].ljust(col_width0), line[1].ljust(col_width1), line[2]))) # output
def get_rates(self, ccy): json = self.get_json('poloniex.com', '/public?command=returnTicker') quote_currencies = {} zcash_ticker = json.get('BTC_ZEC') quote_currencies['BTC'] = Decimal(zcash_ticker['last']) return quote_currencies
def handle_say(json): mq.publish(exchange='wizard', routing_key='action.say', body={'text': json.get('text', '')}, no_time=True)