def edit(request, menu_id): # Get menu items for a given menu menu = Menu.objects.get(pk=menu_id) try: menuItems = menu.menuitem_set.all() menuItems = [item.json() for item in menuItems] except AttributeError: menuItems = [] # Get beer choices beers = Beer.objects.all() beerItems = [item.json() for item in beers] tv = {'menu':menu, 'menuItems':json(menuItems), 'beerItems':json(beerItems), 'request':request, 'ABV_COLOR':ABV_COLOR, } dims = make_dims(WIDTH, ASPECT_RATIO, NROWS, NCOLS) tv.update(dims) return render_to_response("billboard/edit.html", tv, context_instance=RequestContext(request))
def menu_item_save(request): if request.method == "POST": post = request.POST data = loads(post.keys()[0]) beer = Beer.objects.get(pk=data['beer_id']) menu = Menu.objects.get(pk=data['menu_id']) # Delete old menu item at the location old_menuitem = MenuItem.objects.filter(menu=menu, position=data['position']) for item in old_menuitem: item.delete() menuitem = MenuItem(menu=menu, beer=beer, position=data['position'], slogan=data['slogan'] ) menuitem.save() return HttpResponse(json("Successfully saved form")) return HttpResponse(json(data)) return HttpResponse("Not a post")
def stats(): keys = ['processor', 'notifier'] with hide('output'): stats = [json(run('redis-cli get stats:{}'.format(s))) for s in keys] for ss in stats: for s, v in json(ss).items(): print "{:>30} {:>10}".format(s, v)
def __get(url, callback): response = get(BASE_URL + url) code = response.status_code if code >= 200 and code < 300: return callback(json(response.content)) elif code >= 400 and code < 500: return json(response.content).get('msg') else: return f"Cannot connect to Binance API: {code}"
def login(self, **kwargs): kwargs['__iter__'] = iter_params params = type('Params', tuple(), kwargs)() request = type('Request', tuple(), { 'env': http.request.env, 'params': params })() response = type('Response', tuple(), {'result': {}})() authenticate(request, response) if response.result.get('status') != 'success': return http.request.make_response(json( response.result), [('Access-Control-Allow-Origin', '*')]) return http.request.make_response(json( response.result), [('Access-Control-Allow-Origin', '*')])
def on_get(self, req, resp, jwt, session): # check if it exists in the cache user = session.get('user', None) if not user: resp.status = falcon.HTTP_200 resp.body = json(user) resp.set_header('Content-Type', 'application/json') return username = req.params.get('username', None) email = req.params.get('email', None) password = req.params.get('password', None) login = { 'type': 'username', 'value': username } if login['value'] == None: login.update({ 'type': 'email', 'value': email }) if login['value'] == None: resp.status = falcon.HTTP_400 resp.body = json({ 'error': 'either the email of username needs to be given' }) resp.set_header('Content-Type'. 'application/json') return get_resp = requests.get(AUTH('/api/auth/user'), {login['type']: login['value']}) users = get_resp.json() if len(users) > 1: resp.status = falcon.HTTP_400 resp.body = json({'message': 'there should only be 1 user with that thing'}) resp.set_header('Content-Type', 'application/json') return user = users[0] if user['password'] != password: resp.status = falcon.HTTP_401 resp.body = json({}) resp.set_header('Content-Type', 'application/json') return session['user'] = user return jsonify(user)
def test_running_extensions(self): headers = self.headers url = self.run_url res = POST(self.api_url + "file/DNA", data="ACGTACGACTACGACTGACGACTACGAGCT", headers=headers) input1 = {"DNA":res.text} res = POST(url + "translate_dna_example", data = json(input1), headers=headers) self.assertTrue(res.status_code==200) self.assertTrue(list(res.json().keys())[0]=='Protein') self.assertTrue(res.json()["Protein"]=="TYDYD*RLRA") input1["Protein"] = "/api/file/myDir/Prot" res = POST(url + "translate_dna_example", data = json(input1), headers=headers) self.assertTrue(res.status_code==200) self.assertTrue(res.json()["Protein"]=='/api/file/myDir/Prot')
def test_genbank_extension(self): headers = self.headers url = self.run_url block1 = { "metadata": { "authors": [], "version": "0.0.0", "tags": {} }, "options": [], "components": [], "rules": {}, "notes": {} } res = POST(self.api_url + "block", data=json(block1), headers=headers) block_id = res.json()["id"] input1 = { "genbank": "extensions/compute/genbank_to_block/sequence.gb", "sequence": "/api/file/block/" + block_id + "/sequence" } res = POST(url + "genbank_to_block", data=json(input1), headers=headers) self.assertTrue(res.status_code == 200) res = res.json() self.assertTrue("block" in res) block = parse(res["block"]) block["sequence"]["url"] = input1["sequence"] res = PUT(self.api_url + "block/" + block_id, data=json(block), headers=headers) self.assertTrue(res.status_code == 200) res = GET(self.api_url + "block/" + block_id, headers=headers) self.assertTrue(res.status_code == 200) self.assertTrue(res.json()["id"] == block_id) self.assertTrue(res.json()["sequence"]["url"] == input1["sequence"]) res = GET(self.api_url + "file/block%2f" + block_id + "%2fsequence", headers=headers) self.assertTrue(res.status_code == 200) self.assertTrue(len(res.text) > 1000)
def evalOptions(): super_evalJS(javascript) self.evalJS(''' var options = {options}; fixupOptionsObject(options); Highcharts.setOptions(options); '''.format(options=json(options)))
def EthereumSourceCode(contract_identifier = None, dat_output = 'Ethereum_SourceCode.csv', API_Code = 'KPDQ8J6VWUH7UE61YSU14U3A76AYB8S7KN'): #with open(dat_output,'w') as file: # file.write("Contract, Name, SourceCode") # file.write('\n') j = 1 for contract in contract_identifier: print('Downloading SourceCode ' + str(j) + ' of ' + str(len(contract_identifier))) link = 'https://api.etherscan.io/api?module=contract&action=getsourcecode&address=' + contract + '&apikey=' + API_Code json = requests.get(link) data = dict(json.json()) try: name = data['result'][0]['ContractName'] code = '"' + data['result'][0]['SourceCode'] + '"' except: name = '' code = '' print(25*'-'+'Error-Report-Start'+23*'-') print("---> Hash " + str(contract)) print("No Source Code Available") print(25*'-'+'Error-Report-Start'+23*'-') try: page_frame = pd.DataFrame( {'Contract' : [contract], 'Name' : [name], 'SourceCode' : [code] }) except: print(25*'-'+'Error-Report-Start'+23*'-') print("---> Hash " + str(contract)) print(25*'-'+'Error-Report-Start'+23*'-') with open(dat_output,'a') as file: file.write(', '.join([str(element) for element in page_frame.loc[0]])) file.write('\n') j += 1
def getLoginRequestPayload (self, appleSessionToken): if not appleSessionToken: raise NameError("getLoginRequestPayload: X-Apple-ID-Session-Id not found") return json({ "dsWebAuthToken": appleSessionToken, "extended_login": False, })
def test_post_customer_using_valid_data_returns_customer_json_object(self): req = self.eazy.customer(self.r + '@test.com', 'Mr', self.r, self.r, self.r, '1 Test Road', 'GL52 2NF', '14785236', '456789', 'Mr Test Test') req_json = json(req) self.assertIn('CustomerRef', req) self.assertIsNotNone(req_json)
def __init__(self, parent=None, bridge=None, options=None, *, highchart='Chart', enable_zoom=False, enable_select=False, selection_callback=None, javascript='', debug=False, **kwargs): options = (options or {}).copy() enable_select = enable_select or '' if not isinstance(options, dict): raise ValueError('options must be dict') if enable_select not in ('', '+', 'x', 'y', 'xy', 'x+', 'y+', 'xy+'): raise ValueError("enable_select must be '+', 'x', 'y', or 'xy'") if enable_select and not selection_callback: raise ValueError('enable_select requires selection_callback') if enable_select: # We need to make sure the _Bridge object below with the selection # callback is exposed in JS via QWebChannel.registerObject() and # not through WebviewWidget.exposeObject() as the latter mechanism # doesn't transmit QObjects correctly. class _Bridge(QObject): @pyqtSlot('QVariantList') def _highcharts_on_selected_points(self, points): selection_callback([np.sort(selected).astype(int) for selected in points]) if bridge is None: bridge = _Bridge() else: # Thus, we patch existing user-passed bridge with our # selection callback method attrs = bridge.__dict__.copy() attrs['_highcharts_on_selected_points'] = _Bridge._highcharts_on_selected_points assert isinstance(bridge, QObject), 'bridge needs to be a QObject' _Bridge = type(bridge.__class__.__name__, bridge.__class__.__mro__, attrs) bridge = _Bridge() super().__init__(parent, bridge, debug=debug) self.highchart = highchart self.enable_zoom = enable_zoom enable_point_select = '+' in enable_select enable_rect_select = enable_select.replace('+', '') self._update_options_dict(options, enable_zoom, enable_select, enable_point_select, enable_rect_select, kwargs) with open(self._HIGHCHARTS_HTML, encoding='utf-8') as html: self.setHtml(html.read() % dict(javascript=javascript, options=json(options)), self.toFileURL(dirname(self._HIGHCHARTS_HTML)) + '/')
def test_searching_customer_with_contracts_returns_contracts(self): req = self.eazy.contracts('310a826b-d095-48e7-a55a-19dba82c566f') req_json = json(req) for record in req_json['Contracts']: id = record['Id'] self.assertIsNotNone(id) self.assertGreaterEqual(len(req_json), 1)
def submission_extraction(self): url = "https://api.pushshift.io/reddit/submission/search?subreddit=iot&before={}&sort=desc&size=1000" count = 0 id_ls = [] previous_epoch = int(self.start_time.timestamp()) while True: new_url = url.format(str(previous_epoch)) json = requests.get( new_url, headers={'User-Agent': 'Comment Extraction (by /u/sgdzhou5)'}) time.sleep(1) json_data = json.json() if 'data' not in json_data: break objects = json_data['data'] if len(objects) == 0: break for object in objects: previous_epoch = object['created_utc'] - 1 count += 1 if object['is_self']: if 'selftext' not in object: continue try: id_ls.append(object['id']) except Exception as err: print(f"Couldn't print post: {object['url']}") print("Saved {} submissions through {}.".format( count, datetime.fromtimestamp(previous_epoch).strftime( "%Y-%m-%d"))) print(f"Saved {count}") return id_ls
def put(self, key): #update project = Project().get(key) project.name = getArgument(self.request, 'name', 'The "name" parameter can\'t be empty') project.put() url = project.url(self.request.url) self.response.headers.add_header("Location", url) self.response.out.write(json(url))
def main(): """main function""" diffSeg = 0.0 diffTer = 0.0 diffQua = 0.0 diffQui = 0.0 diffSex = 0.0 num = 0 json = requests.get( "https://mfinance.com.br/api/v1/stocks/historicals/IBOV?months=120" ) # 10 YEAR json = json.json() for stock in json['historicals']: date = pd.Timestamp(stock['date']) num += 1 if date.weekday() == 0: diffSeg += (float(stock['open'] * -1) + float(stock['close'])) if date.weekday() == 1: diffTer += (float(stock['open'] * -1) + float(stock['close'])) if date.weekday() == 2: diffQua += (float(stock['open'] * -1) + float(stock['close'])) if date.weekday() == 3: diffQui += (float(stock['open'] * -1) + float(stock['close'])) if date.weekday() == 4: diffSex += (float(stock['open'] * -1) + float(stock['close'])) div = num / 5 print('Seg: ' + str(round(diffSeg / div, 2))) print('Ter: ' + str(round(diffTer / div, 2))) print('Qua: ' + str(round(diffQua / div, 2))) print('Qui: ' + str(round(diffQui / div, 2))) print('Sex: ' + str(round(diffSex / div, 2)))
def get_JSON(self): # TODO 2) json = requests.get(self.properties['url'], headers={'user-agent': 'Mozilla/5.0'}) # need to call .json() after since above returns requests self.properties['jsons'] = json.json()
def GetEventsJson(self, namespace='default', involved_obj_kind=None, involved_obj_name=None): url = '{}/namespaces/{}/events'.format(self.base_url, namespace) selector = {} if involved_obj_kind is not None: selector['involvedObject.kind'] = involved_obj_kind if involved_obj_name is not None: selector['involvedObject.name'] = involved_obj_name if len(selector): url = self._BuildUrl(url, extra_params={ 'fieldSelector': self._gen_selector_str(selector) }) json = self._RequestUrl(url, 'GET') if json.status_code not in [200, 404]: raise KubernetesError(json.json()['message'], json.status_code) elif json.status_code == 404: raise KubernetesError('Can not find the resource', 404) result = self._ParseAndCheckKubernetes(json.content) if len(result['items']) == 0: return None return result['items']
async def wiki(self, ctx, *msg): """Look up a subject on wikipedia""" query = " ".join(msg) link = " " json = requests.get( 'https://en.wikipedia.org/w/api.php?action=opensearch&search=' + query + '&limit=5&format=json&redirects=resolve') msg = json.json() if json.status_code == 200 and not len(msg[1]) == 0: if isinstance(msg[1][0], str) and ( "(disambiguation)" in msg[1][0] or "may refer to:" in msg[2][0] ): #wiki has no standard, so we need to check for all of these cases definition_str = "Search for *" + msg[ 0] + "* is too general. Try one of these: \n" for i in range(0, len(msg[1])): if "may refer to:" not in msg[2][i]: definition_str += "\n" + msg[1][i] else: definition_str = "Wiki summary for " + msg[0] + "\n\n" + msg[ 2][0] link = msg[3][0] else: definition_str = "There was an error " + str( json.status_code) + ". There is no page for this." msgs = self.bot.fit_msg(definition_str) await self.bot.embed_this_for_me(definition_str + "\n" + link, ctx)
def getTestJSON(name): json = requests.get( "http://localhost:5000/api/1/public/test/search?name={}".format(name)) json = json.json()['apiPayload'] for x in range(len(json)): if json[x]['name'] == name: return json[x]
def update_catalog(self, tracks): self.log(u"update_catalog(building json)") items = [] item_ids= [] self.log(u"update_catalog(%d songs)" % len(tracks)) for track in tracks: item_id= track['id'] if item_id in item_ids: continue item_ids.append(item_id) item= {} item['action']= 'update' item['item']= {} item['item']['item_id']= item_id item['item']['artist_name']= track.get('artist', 'Unknown') item['item']['song_name']= track.get('title', 'Unknown') item['item']['play_count']= track.get('playcount', 0) item['item']['skip_count']= track.get('skipcount', 0) item['item']['rating']= int(track.get('rating', 0.5) * 10) item['item']['banned']= False items.append(item) self.log(u"update_catalog(sending data)") xml= self._query('catalog/update', { 'id' : self.get_catalog_id(), 'data_type' : 'json', 'data' : json(items) }, True) if xml == "": return "" return True
def retrieve_comment_and_post_count(reddit_data_dict,subreddit): lookback_hours = 24 headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' } stats = {'comment':'num_of_comments', 'submission':'num_of_posts'} url = "https://api.pushshift.io/reddit/{}/search?&limit=1000&sort=desc&subreddit={}&before=" startTime = datetime.datetime.utcnow() endTime = startTime - timedelta(hours=lookback_hours) endEpoch = int(endTime.timestamp()) for stat in stats: count = 0 breakOut = False previousEpoch = int(startTime.timestamp()) while True: newUrl = url.format(stat, subreddit)+str(previousEpoch) json = requests.get(newUrl, headers=headers) objects = json.json()['data'] for obj in objects: previousEpoch = obj['created_utc'] - 1 if previousEpoch < endEpoch: breakOut = True break count += 1 if breakOut: reddit_data_dict[stats[stat]].append(count) break
def post(self): #post = create object project = Project() project.name = getArgument(self.request, 'name', 'The "name" parameter can\'t be empty') project.put() url = project.url(self.request.url) self.response.headers.add_header("Location", url) self.response.out.write(json(url)) self.response.set_status(201)
def getListJSON(id): json = requests.get( "http://{}/api/1/public/test/list".format('localhost:5000')) json = json.json()['apiPayload'] for x in range(len(json)): if json[x]['_id'] == id: return json[x] return '' #Shouldn't ever get here; if it does, test ID doesn't exist
def put(self, projectKey, issueKey, key): #update comment = Comment().get(key) comment.Issue = Issue().get(issueKey) comment.text = getArgument(self.request, 'text', '"text" is a required field!') comment.put() url = comment.url(self.request.url) self.response.headers.add_header("Location", url) self.response.out.write(json(url))
def __init__(self, API_KEY): self.API_KEY = API_KEY if not self.API_KEY: print("No API key given. Register at pro.coinmarketcap.com") return self.api_data = self.grab(API_KEY) self.json = json(self.api_data) self.price = self.json['data'][0]['quote']['USD']['price']
async def fact(ctx): json = requests.get('https://uselessfacts.jsph.pl/random.json?language=en') json = json.json() embedColor = random.choice([3800852, 4149685, 10233776, 16635957]) embed = discord.Embed(title=f'Random Useless Fact', color=embedColor) embed.add_field(name="Fact", value=json["text"], inline=False) embed.add_field(name="ID", value=json["id"], inline=False) await ctx.send(embed=embed)
def methods(self, **kwargs): params = type('Params', (,), kwargs)() request = type('Request', (,), {'env': http.request.env, 'params': params})() response = type('Response', (,), {'result': {}})() authenticate(request, response) if response.result.get('status') != 'success': return http.request.make_response(json(response.result), [('Access-Control-Allow-Origin', '*')]) routes.methods(request, response) return http.request.make_response(json(response.result), [('Access-Control-Allow-Origin', '*')])
def delete(self, projectKey, key): issue = Issue().get(key) keys = [key] for comment in issue.comments: keys.append(str(comment.key())) logging.info('Deleting: ' + str(keys)) db.delete(keys) self.response.out.write(json(keys))
def post(self, projectKey, issueKey): #post = create object comment = Comment() comment.issue = Issue().get(issueKey) comment.text = getArgument(self.request, 'text', '"text" is a required field!') comment.put() url = comment.url(self.request.url) self.response.headers.add_header("Location", url) self.response.out.write(json(url)) self.response.set_status(201)
def google_search(query): """Search using Googles AjaxSearch functionality.""" try: data = util.web.get(uri % quote(query)).read() except: return False if not data: return False return json(data)
def getRequestPayload (self, user, password): if not user: raise NameError("getAuthenticationRequestPayload: user not found") if not password: raise NameError("getAuthenticationRequestPayload: password not found") return json({ "accountName": user, "password": password, "rememberMe": False, })
def __get(self, url, callback, filter_status=True): response = get(self.base_url + url) code = response.status_code success = code >= 200 and code < 300 content = json(response.content) if success else None if not filter_status: return callback(content, code) if code >= 200 and code < 300: return callback(content) return f"{self.name} API: {code}"
def getCrowd(object_id): #/api/crowd/get/name?value=Test from pymongo import MongoClient from bson.objectid import ObjectId client = MongoClient('localhost', 27017) db = client.posts collection = db.tasks finded = collection.find_one({'_id': ObjectId(object_id)}) finded['_id'] = str(finded['_id']) return json(finded)
def test_json(self): config_file = StringIO( '# comment\n' '\n' 'key1 value1\n' ) loader = ConfigLoader([config_file]) options = loader() assert json(options) == '{"key1": "value1"}'
def __get(url, callback, filter_status=True): response = get(BASE_URL + url) code = response.status_code success = code >= 200 and code < 300 content = json(response.content) if success else None if not filter_status: return callback(content, code) if success: return callback(content) return f"Bitstamp API: {code}"
def _parse_options(file_names, options, image_options): if options is None: options_json = "" else: opt = [] for option_name, value in options.items(): line = "params['{}'] = {};".format(option_name, json(value)) opt.append(line) options_json = "\n".join(opt) if image_options is None: image_options_json = "" else: opt = [] for file, image_options in zip(sorted(file_names), image_options): line = "params['{}'] = {};".format(file, json(image_options)) opt.append(line) image_options_json = "\n".join(opt) return options_json, image_options_json
def delete(self, key): keys = [key] project = Project().get(key) for issue in project.issues: for comment in issue.comments: keys.append(str(comment.key())) keys.append(str(issue.key())) logging.info('Deleting: ' + str(keys)) db.delete(keys) self.response.out.write(json(keys))
def test_genbank_extension(self): headers = self.headers url = self.run_url block1 = { "metadata": { "authors": [], "version": "0.0.0", "tags": {} }, "options":[], "components":[], "rules": {}, "notes": {} } res = POST(self.api_url + "block", data = json(block1), headers=headers) block_id = res.json()["id"] input1 = { "genbank":"extensions/compute/genbank_to_block/sequence.gb", "sequence":"/api/file/block/"+block_id+"/sequence" } res = POST(url + "genbank_to_block", data = json(input1), headers=headers) self.assertTrue(res.status_code==200) res = res.json() self.assertTrue("block" in res) block = parse(res["block"]) block["sequence"]["url"] = input1["sequence"] res = PUT(self.api_url + "block/" + block_id, data = json(block), headers=headers) self.assertTrue(res.status_code==200) res = GET(self.api_url + "block/" + block_id, headers=headers) self.assertTrue(res.status_code==200) self.assertTrue(res.json()["id"] == block_id) self.assertTrue(res.json()["sequence"]["url"] == input1["sequence"]) res = GET(self.api_url + "file/block%2f"+block_id+"%2fsequence", headers=headers) self.assertTrue(res.status_code==200) self.assertTrue(len(res.text) > 1000)
def native_get_book(assets): print( "-------------------------------------------------------------- {} / {} ---------------------------------------------------------------" .format(assets['base'], assets['counter'])) data = {} entries = 0 if assets['counter'] == 'XLM': link = "https://horizon.stellar.org/order_book/trades?selling_asset_type=credit_alphanum4&selling_asset_code={}&selling_asset_issuer={}&buying_asset_type=native&limit=200&order=desc".format( assets['base'], assets['base_issuer']) elif assets['base'] == 'XLM': link = "https://horizon.stellar.org/order_book/trades?selling_asset_type=native&buying_asset_type=credit_alphanum4&buying_asset_code={}&buying_asset_issuer={}&limit=200&order=desc".format( assets['counter'], assets['counter_issuer']) else: link = "https://horizon.stellar.org/order_book/trades?selling_asset_type=credit_alphanum4&selling_asset_code={}&selling_asset_issuer={}&buying_asset_type=credit_alphanum4&buying_asset_code={}&buying_asset_issuer={}&limit=200&order=desc".format( assets['base'], assets['base_issuer'], assets['counter'], assets['counter_issuer']) print(link) yesterday = dt.now() - timedelta(hours=17) while True: json = requests.get(link) sub_data = json.json()['_embedded']['records'] upper = len(sub_data) - 1 if upper < 0: #There are no transactions return data index = 0 result = this_page(yesterday, sub_data, upper) if result == 0: #next page while index < upper + 1: #load entire page as data data[entries] = sub_data[index] entries += 1 index += 1 elif result == -1: #done return data #return data else: #this page while index < result: #load relevant info from this page data[entries] = sub_data[index] entries += 1 index += 1 return data #return data link = json.json()['_links']['next']['href'] link.replace("\u0026", "&") #TODO Needs to be removed when horizon bug is fixed
def put(self, projectKey, key): #update issue = Issue().get(key) issue.project = Project().get(projectKey) issue.summary = self.request.get('summary') or issue.summary issue.text = self.request.get('text') or issue.text closed = self.request.get('closed') if closed: issue.closed = closed.lower() == "true" issue.put() url = issue.url(self.request.url) self.response.headers.add_header("Location", url) self.response.out.write(json(url))
def DeleteResourceQuota(self, name, namespace='default'): '''Delete a resource quota ''' url = ('%(base_url)s/namespaces/%(ns)s/resourcequotas/%(name)s' % { "base_url": self.base_url, "ns": namespace, "name": name }) json = self._RequestUrl(url, 'DELETE') if json.status_code not in [200, 404]: raise KubernetesError(json.json()['message'], json.status_code)
def getJson(self): self.checkStatus() header = {'API-Key': self.apikey} json = requests.get("https://urlscan.io/api/v1/result/%s/" % self.scanid, headers=header) if json.status_code == 200: return json.json() else: raise Exception('Non-200 respond: %s - %s' % json.status_code, json.text)
def evalOptions(): super_evalJS(javascript) super_evalJS( """ var options = {options}; fixupOptionsObject(options); Highcharts.setOptions(options); """.format( options=json(options) ) ) self._is_init = True
def __init__(self, parent=None, bridge=None, options=None, *, highchart='Chart', enable_zoom=False, enable_select=False, selection_callback=None, javascript='', debug=False, **kwargs): options = (options or {}).copy() enable_select = enable_select or '' if not isinstance(options, dict): raise ValueError('options must be dict') if enable_select not in ('', '+', 'x', 'y', 'xy', 'x+', 'y+', 'xy+'): raise ValueError("enable_select must be '+', 'x', 'y', or 'xy'") if enable_select and not selection_callback: raise ValueError('enable_select requires selection_callback') super().__init__(parent, bridge, debug=debug) self.highchart = highchart self.enable_zoom = enable_zoom enable_point_select = '+' in enable_select enable_rect_select = enable_select.replace('+', '') if enable_zoom: _merge_dicts(options, _kwargs_options(dict( mapNavigation_enableMouseWheelZoom=True, mapNavigation_enableButtons=False))) if enable_select: self._selection_callback = selection_callback _merge_dicts(options, _kwargs_options(dict( chart_events_click='/**/unselectAllPoints/**/'))) if enable_point_select: _merge_dicts(options, _kwargs_options(dict( plotOptions_series_allowPointSelect=True, plotOptions_series_point_events_click='/**/clickedPointSelect/**/'))) if enable_rect_select: _merge_dicts(options, _kwargs_options(dict( chart_zoomType=enable_rect_select, chart_events_selection='/**/rectSelectPoints/**/'))) if kwargs: _merge_dicts(options, _kwargs_options(kwargs)) with open(self._HIGHCHARTS_HTML) as html: self.setHtml(html.read() % dict(javascript=javascript, options=json(options)), self.toFileURL(dirname(self._HIGHCHARTS_HTML)) + '/')
def menu_item_JSON(request, menu_item_id): if request.method == 'POST': # If the form has been submitted... form = MenuItemForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') # Redirect after POST else: form = MenuItemForm() # An unbound form html = render_to_response('billboard/menu_item_form.html', { 'form': form, }).content return HttpResponse(json(html))
def _edit_html(self, options, image_options): opt_json, imgopt_json = _parse_options(self.file_names, options, image_options) html = """ <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <!-- iOS meta tags --> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <script src="https://code.jquery.com/jquery-2.2.2.min.js" integrity="sha256-36cp2Co+/62rEAAYHLmRCPIych47CvdM+uTBJwSzWjI=" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="/custom/papaya.css?version=0.6.2&build=51212345" /> <script type="text/javascript" src="/custom/papaya.js?version=0.6.2&build=51212345"></script> <title>Papaya Viewer</title> <script type="text/javascript"> var params = []; params["images"] = {images}; {options} {image_options} </script> </head> <body> <div id="papayaContainer"> <div id="papayaToolbar"></div> <div id="papayaViewer" class="checkForJS" data-params="params"></div> <div id="papayaDisplay"></div> </div> </body> </html> """ html = html.format(images=json(self.file_names.keys()), options=opt_json, image_options=imgopt_json) file = NamedTemporaryFile(suffix=".html", dir="papaya_data") file.write(html) # Do not close because it'll delete the file file.flush() self._html_file = file path, name, ext = split_filename(file.name) self.objid = name return html
def server(): serv = server_socket() host = socket.gethostname() port = 8999 serv.bind((host, port)) serv.listen(5) c, addr = serv.accept() while True: msg = c.recv(1024) server_json = json.json() serialized = server_json.serializer(msg) serialized = serialized.split() if serialized[0] == "signup": U = User(serialized[1], serialized[2], serialized[3], serialized[4]) validation = U.validate() if not validation.isstring(): #if project13_forums.model.memory.sign_up(U): if sign_up(U): c.send(U.deserializer("Succesful")) else: c.send(U.deserializer("Username already exists")) else: c.send(U.deserializer("Invalid Credentials " + validation)) pass elif serialized[0] == "login": UA = UserAuth(serialized[1], serialized[2]) validation = UA.validate() if not validation.isstring(): if checkUsername(serialized[1]): pw = getPassword(serialized[1]) if pw == serialized[1]: c.send(UA.deserializer('True')) else: c.send(UA.deserializer("username password mismatch")) else: c.send(UA.deserializer("Invalid Credentials " + validation)) pass elif serialized[0] == "view_forum": VF = ViewForum(serialized[1]) forum_list=view_forum(VF.forum_name) c.send(VF.deserializer(forum_list)) pass elif serialized[0] == "create_sub_forum": pass serv.close() pass
def lint(filepath): """ check given file using JSLint (via Spidermonkey) """ options = {} # TODO: read from argument command = ["js"] for filename in DEPENDENCIES: command.extend(["-f", filename]) source = open(filepath) errors = Popen(command, stdin=source, stdout=PIPE).communicate()[0] # XXX: errors incomplete (e.g. not reporting missing var)!? source.close() return json(errors)
def skip_item(self, item_id): self.log(u"play_item(building json)") items = [] item= {} item['action']= 'skip' item['item']= {} item['item']['item_id']= item_id items.append(item) self.log(u"play_item(sending data)") xml= self._query('catalog/update', { 'id' : self.get_catalog_id(), 'data_type' : 'json', 'data' : json(items) }, True) if xml == "": return "" return True
def test_invalid_session_key(self): headers = self.headers headers["sessionkey"] = "NA" url = self.api_url block1 = { "metadata": { "authors": [], "version": "0.0.0", "tags": {} }, "options":[], "components":[], "rules": {}, "notes": {} } res = POST(url + "block", data = json(block1), headers=headers) self.assertTrue(res.status_code==403)
def test_cloning(self): headers = self.headers url = self.api_url proj1 = { "metadata": { "authors": [], "version": "0.0.0", "tags": {} }, "components": [ ], "settings": {} } res = POST(url + "project", data = json(proj1), headers=headers) pid1 = res.json()['id'] res = POST(url + "clone/" + pid1, headers=headers) pid2 = res.json()['id'] res = POST(url + "clone/" + pid2, headers=headers) pid3 = res.json()['id'] res = POST(url + "clone/" + pid3, headers=headers) pid4 = res.json()['id'] res = GET(url + "project/" + pid4, headers=headers) hist = GET(url + "ancestors/" + pid4, headers=headers) self.assertTrue(hist.status_code==200) hist = hist.json() self.assertTrue(len(hist)==3) self.assertTrue(hist[0]==pid3) self.assertTrue(hist[1]==pid2) self.assertTrue(hist[2]==pid1) child = GET(url + "descendants/" + pid1, headers=headers) self.assertTrue(child.status_code==200) child = child.json() self.assertTrue(len(child)==5) self.assertTrue(len(child['leaves'])==1)
def preview(request, menu_id): menu = Menu.objects.get(pk=menu_id) menuItems = menu.menuitem_set.all() try: menuItems = menu.menuitem_set.all() menuItems = [item.json() for item in menuItems] except AttributeError: menuItems = [] tv = {'menu':menu, 'menuItems':json(menuItems), 'ABV_COLOR':ABV_COLOR, } dims = make_dims(WIDTH, ASPECT_RATIO, NROWS, NCOLS) tv.update(dims) return render_to_response("billboard/preview.html", tv, context_instance=RequestContext(request))
def __call__(self, *args, **kwargs): self.httpfile.sendall( rpcstr(func=kwargs['func'], args=', '.join(json(arg) for arg in args)), kwargs.get('timeout', -1))
def recieve(self): return self.sock.recv(1024) def close(self): self.sock.close() s=mysocket() host=socket.gethostname() port=8999 s.connect((host,port)) while True: msg=raw_input(">> ") #length=len(msg) #print length #s.send(str(length)) #print s.recieve() #s.send(msg) client_json=json.json() client_json.deserializer(msg) s.send(client_json.representation()) #s.send(str(client_json.deserializer(msg))) print "sent" print "1" received= s.recieve() print "2" print received print "3" #recd_msg=client_json.serializer(received) #print recd_msg s.close()