def get_dict_info(self): ext_dict = dict() ext_dict['api'] = Api.list_by_api_ids(self.api_ids) ext_dict['user'] = utils.to_dict(inst=self.get_users(), except_clm_list=['enabled']) role_dict = utils.to_dict(inst=self, ext_dict=ext_dict) return role_dict
def get_dict_info(self): ext_dict = dict() ext_dict['role'] = utils.to_dict(inst=self.get_roles(), except_clm_list=['enabled']) user_dict = utils.to_dict( inst=self, except_clm_list=['hashed_password', 'consumer_id'], ext_dict=ext_dict) return user_dict
def UserHandler(request, user_id=None): if request.method == 'GET' and user_id is None: users = User.objects.all() data = [] for user in users: user_dict = to_dict(user) user_dict.pop("password", None) data.append(user_dict) return JsonResponse(data, safe=False) if request.method == 'GET' and user_id is not None: try: user = User.objects.get(pk=user_id) except User.DoesNotExist: return JsonResponse({"error": "User does not exist"}, status=404) user_dict = to_dict(user) user_dict.pop("password", None) return JsonResponse(user_dict, status=200) if request.method == "POST": body = parseJSON(request.body) try: username = body["username"] password = body["password"] except (ValueError, KeyError): return JsonResponse({'error': 'JSON is invalid'}, status=409) try: user = User.objects.create_user(username, None, password) user.save() except IntegrityError: return JsonResponse({'error': 'Username already taken'}, status=409) token = Token.objects.get(user=user) if token is None: token = Token.objects.create(user=user) jsonresponse = { "username": user.username, "firstname": user.first_name, "lastname": user.last_name, "email": user.email } response = JsonResponse(jsonresponse) response["Authorization"] = token return response
def post(self): logging.debug('...........in UpdateHandler') r = json.loads(self.request.body) address = models.UpdateAddress(r['email'], r['name']) r = utils.to_dict(address) self.response.headers = HEADERS self.response.write(json.dumps(r))
def character_search(**args): info = to_dict(args) for field in ['modulus', 'conductor', 'order']: info[field] = info.get(field, '') query = {} print "args = ", args if 'natural' in args: label = info.get('natural', '') try: modulus = int(str(label).partition('.')[0]) number = int(str(label).partition('.')[2]) except ValueError: return "<span style='color:red;'>ERROR: bad query</span>" return redirect( url_for("render_webpage_label", modulus=modulus, number=number)) else: for field in ['modulus', 'conductor', 'order']: if info.get(field): query[field] = parse_range(info[field]) info["bread"] = [('Dirichlet Characters', url_for("render_Character")), ('search results', ' ')] info['credit'] = 'Sage' if (len(query) != 0): from sage.modular.dirichlet import DirichletGroup info['contents'] = charactertable(query) info['title'] = 'Dirichlet Characters' return render_template( "dirichlet_characters/character_search.html", **info) else: return "<span style='color:red;'>ERROR: bad query</span>"
def get(self, obj_t, identifier, *args): cls = getattr(sys.modules['core.model'], obj_t) # dispatch put to that model class. all model classes need to a subclass model.RESTModel obj = utils.to_dict(cls.get(int(identifier))) return self.prep_json_response(200, message = obj)
def character_search(**args): #import base info = to_dict(args) query = {} print args if 'natural' in args: label = info.get('natural', '') modulus = int(str(label).partition('.')[0]) number = int(str(label).partition('.')[2]) return redirect( url_for("render_webpage_label", modulus=modulus, number=number)) else: for field in ['modulus', 'conductor', 'order']: if info.get(field): query[field] = parse_range(info[field]) info["bread"] = [('Dirichlet Characters', url_for("render_Character")), ('search results', ' ')] info['credit'] = 'Sage' if (len(query) != 0): count_default = 100 if info.get('count'): try: count = int(info['count']) except: count = count_default else: info['count'] = count_default count = count_default start_default = 0 if info.get('start'): try: print "Check" start = int(info['start']) if (start < 0): print "Check1" start += (1 - (start + 1) / count) * count except: print "Check2" start = start_default else: start = start_default from sage.modular.dirichlet import DirichletGroup t, texname, number, length = charactertable(query) info['characters'] = t info['texname'] = texname info['number'] = number info['len'] = length if (start >= length): print "Check3" start -= (1 + (start - length) / count) * count if (start < 0): print "Check4" start = 0 info['start'] = start info['title'] = 'Dirichlet Characters' print start, count, length return render_template( "dirichlet_characters/character_search.html", **info)
def put(self, request): try: params = utils.get_params(request) self.logger.info('INICIO WS - TFGASIGVIEWCONVOCATORIA PUT del usuario: %s con parametros: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, params)) if request.user.has_perm('tfgs.tfg_asig.change') or request.user.is_admin: tfg = Tfg.objects.get(titulo=params.get('tfg')) tfg_asig = Tfg_Asig.objects.get(tfg=tfg) serializer = self.serializer_class(tfg) params = json.loads(params.get('datos')) resul = serializer.update(tfg_asig, params) if resul['status']: resul = utils.to_dict(resul) resul_status = status.HTTP_200_OK else: resul = dict(message=resul['message']) resul_status = status.HTTP_400_BAD_REQUEST else: resul = dict(message="Sin privilegios") resul_status = status.HTTP_400_BAD_REQUEST self.logger.info('FIN WS - TFGASIGVIEWCONVOCATORIA PUT del usuario: %s con resultado: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, resul)) return Response(resul, status=resul_status) except Tfg.DoesNotExist: resul = dict(message="El tfg indicado no existe") self.logger.error('TFGASIGVIEWCONVOCATORIA PUT del usuario: %s con resultado: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, resul)) return Response(resul, status=status.HTTP_400_BAD_REQUEST) except Exception as e: resul = dict(status=False, message="Error en la llamada") self.logger.critical('TFGASIGVIEWCONVOCATORIA PUT: %s %s' % (resul, e)) return Response(resul, status=status.HTTP_400_BAD_REQUEST)
def write_to_elasticsearch(conn, data, xen_index): conn.indices.create(index=xen_index, body=PS_REVIEWERS_MAPPING, ignore=400) columns = data.columns.values.tolist() uniq_id = 0 bulk_doc = [] for row in data.itertuples(): uniq_id = uniq_id + 1 doc = to_dict(row, columns) header = { "_index": xen_index, "_type": "patchserie", "_id": uniq_id, "_source": doc } bulk_doc.append(header) if uniq_id % 5000 == 0: helpers.bulk(conn, bulk_doc) bulk_doc = [] helpers.bulk(conn, bulk_doc)
def create(self, request): """ POST Insertar un nuevo subtipo de evento :param request: :return : {status: True/False, data:{datos del subtipo de evento} """ try: params = utils.get_params(request) if params.get('delete'): return SubTipo_EventosViewSet().delete(request) self.logger.info('INICIO WS - SUBTIPOEVENTOSVIEW CREATE del usuario: %s con params: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, params)) resul = SubTipo_Evento.objects.create(codigo=params.get('codigo'), nombre=params.get('nombre')) if resul.id: resul = utils.to_dict(dict(status=True, data=resul)) resul_status = status.HTTP_200_OK else: resul = dict(message=resul['message']) resul_status = status.HTTP_400_BAD_REQUEST self.logger.info('FIN WS - SUBTIPOEVENTOSVIEW CREATE del usuario: %s con params: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, resul)) return Response(resul, status=resul_status) except Exception as e: resul = dict(status=False, message="Error en la llamada") self.logger.critical('FIN WS - SUBTIPOEVENTOSVIEW CREATE del usuario: %s con params: %s %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, resul, e)) return Response(resul, status=status.HTTP_400_BAD_REQUEST)
def process_video(video_path, fps): video_frames = get_frames(video_path, fps) face_img_queue = mp.Queue() video_preds_queue = mp.Queue() face_detection_process = mp.Process(target=run_retinaface, args=(video_frames, face_img_queue)) face_detection_process.start() video_face_imgs = face_img_queue.get() face_detection_process.join() emotion_detection_process = mp.Process(target=run_emotion_net, args=(video_face_imgs, video_preds_queue)) emotion_detection_process.start() video_frame_preds = video_preds_queue.get() emotion_detection_process.join() print('Video Successfully Processed') pred_dict = to_dict(video_frame_preds) r = send_response(pred_dict) if (r.status_code == 200): print("Predictions succesfully posted.") return video_frame_preds
def character_search(**args): info = to_dict(args) for field in ['modulus', 'conductor', 'order']: info[field] = info.get(field, '') query = {} print "args = ", args if 'natural' in args: label = info.get('natural', '') try: modulus = int(str(label).partition('.')[0]) number = int(str(label).partition('.')[2]) except ValueError: return "<span style='color:red;'>ERROR: bad query</span>" return redirect(url_for("render_webpage_label", modulus=modulus, number=number)) else: for field in ['modulus', 'conductor', 'order']: if info.get(field): query[field] = parse_range(info[field]) info["bread"] = [('Dirichlet Characters', url_for("render_Character")), ('search results', ' ')] info['credit'] = 'Sage' if (len(query) != 0): from sage.modular.dirichlet import DirichletGroup info['contents'] = charactertable(query) info['title'] = 'Dirichlet Characters' return render_template("dirichlet_characters/character_search.html", **info) else: return "<span style='color:red;'>ERROR: bad query</span>"
def login(): body = request.get_json() user = User.query.filter_by(**body) if exists(user): data = {**to_dict(user.first(), ['password'])} return jsonify({"status": True, "data": data}) return jsonify({"status": False})
def get(self, obj_t, identifier, *args): cls = getattr(sys.modules['core.model'], obj_t) # dispatch put to that model class. all model classes need to a subclass model.RESTModel obj = utils.to_dict(cls.get(int(identifier))) return self.prep_json_response(200, message=obj)
def recommend(): limit = req.args.get('limit', 10, type=int) pids = pf_rec.recommend(limit=limit) cursor = db.products.find({'_id': {'$in': pids}}) products = [to_dict(doc) for doc in cursor] return {'data': products}
def get(self, team_id): roster = NFL_Player_2015_M.query.\ filter(NFL_Team_2015_M.id == team_id).\ filter(NFL_Team_2015_M.name == NFL_Player_2015_M.team).\ all() return [utils.to_dict(player) for player in roster]
def recommend(method): pids = iir_rec.recommend(method) reviews_collection = db.apps cursor = reviews_collection.find({'id': {'$in': pids}}) print(cursor) products = [to_dict(doc) for doc in cursor] return {'data': products}
def save(self): id = self.request.get('id') user = users.get_current_user() script = None if id: script = Script.get_by_id(int(id)) if not script: script = Script() if script.owner and (not user or script.owner.user_id() != user.user_id()): script = Script() script.title = self.request.get('title') script.data = self.request.get('text') if user: script.owner = user key = script.put() scriptDict = utils.to_dict(script); scriptDict['data'] = script.data scriptDict['title'] = script.title scriptDict['id'] = key.id() self.response.out.write(json.dumps(scriptDict))
def get(self): bio = models.Biography.all().get() if not bio: biod = {} else: biod = utils.to_dict(bio) self.renderjson('bio.html', biod)
def CurrentUserHandler(request): if request.user is None: return JsonResponse({"error": "User not logged in"}, status=404) if request.method == 'GET': user_dict = to_dict(request.user) user_dict.pop("password", None) return JsonResponse(user_dict) if request.method == 'PUT': body = parseJSON(request.body) try: first_name = body["first_name"] last_name = body["last_name"] email = body["email"] except (ValueError, KeyError): return JsonResponse({'error': 'JSON is invalid'}, status=409) user = request.user user.first_name = first_name user.last_name = last_name user.email = email user.save() return HttpResponse(status=200) if request.method == 'DELETE': request.user.delete() return HttpResponse(status=200)
def video(self, id): if not id: video = self.m.all().get() else: video = self.m.get_by_id(id) if not video: return False return utils.to_dict(video)
def get(self): result = [] course_name = self.request.get('course') exercises = db.GqlQuery("SELECT * FROM Exercise WHERE course = :1", \ course_name) for exercise in exercises: result.append(utils.to_dict(exercise)) self.response.out.write(json.dumps(result, sort_keys=True))
def post(self): logging.info('...........in InsertHandler') logging.info(self.request.body) r = json.loads(self.request.body) logging.info('....................r: %s', r) existing = models.is_exists(r['email']) if existing: r = utils.to_dict(existing) r.update({'status': 'exists'}) else: address = models.InsertAddress(email=r['email'], name=r['name']) r = utils.to_dict(address) r.update({'status': 'added'}) self.response.headers['content-type'] = 'application/json' self.response.headers['Access-Control-Allow-Origin'] = '*' # self.response.headers = HEADERS self.response.write(json.dumps(r))
def prepare(self, data=None): if not data: return None for k,v in data.iteritems(): if isinstance(v, db.Model): data[k] = utils.to_dict(v) elif isinstance(v, list) and len(v) and isinstance(v[0], db.Model): data[k] = utils.to_dicts(v) return data
def rols(user_id): query = db.session.query(User, Rol, UsersRol).filter( User.id == UsersRol.user_id).filter( Rol.id == UsersRol.rols_id).filter(User.id == user_id) data = [] for user, rol, userol in query.all(): data.append({**to_dict(rol)}) return jsonify({"status": True, "data": data})
def character_search(**args): # import base info = to_dict(args) query = {} print args if "natural" in args: label = info.get("natural", "") modulus = int(str(label).partition(".")[0]) number = int(str(label).partition(".")[2]) return redirect(url_for("render_webpage_label", modulus=modulus, number=number)) else: for field in ["modulus", "conductor", "order"]: if info.get(field): query[field] = parse_range(info[field]) info["bread"] = [("Dirichlet Characters", url_for("render_Character")), ("search results", " ")] info["credit"] = "Sage" if len(query) != 0: count_default = 100 if info.get("count"): try: count = int(info["count"]) except: count = count_default else: info["count"] = count_default count = count_default start_default = 0 if info.get("start"): try: print "Check" start = int(info["start"]) if start < 0: print "Check1" start += (1 - (start + 1) / count) * count except: print "Check2" start = start_default else: start = start_default from sage.modular.dirichlet import DirichletGroup t, texname, number, length = charactertable(query) info["characters"] = t info["texname"] = texname info["number"] = number info["len"] = length if start >= length: print "Check3" start -= (1 + (start - length) / count) * count if start < 0: print "Check4" start = 0 info["start"] = start info["title"] = "Dirichlet Characters" print start, count, length return render_template("dirichlet_characters/character_search.html", **info)
def recommend(): body = req.get_json() limit = req.args.get('limit', 10, type=int) pids = ubr_rec.recommend(body) print(pids) cursor = db.products.find({'_id': {'$in': pids}}) products = [to_dict(doc) for doc in cursor] return {'data': products}
def recommend(uid): offset = req.args.get('offset', 0, type=int) limit = req.args.get('limit', 10, type=int) pids = ucf_rec.recommend(uid, offset=offset, limit=limit) print(pids) cursor = db.products.find({'_id': {'$in': pids}}) products = [to_dict(doc) for doc in cursor] return {'data': products}
def post(self, obj_t, identifier, *args): kvs = json.decode(self.request.body) # find model class cls = getattr(sys.modules['core.model'], obj_t) obj = utils.to_dict(cls.post(int(identifier), kvs)) return self.prep_json_response(200, message=obj)
def post(self, obj_t, identifier, *args): kvs = json.decode(self.request.body) # find model class cls = getattr(sys.modules['core.model'], obj_t) obj = utils.to_dict(cls.post(int(identifier), kvs)) return self.prep_json_response(200, message = obj)
def text(self, id): if not id: song = self.q.get() else: song = models.Song.get_by_id(id) songd = utils.to_dict(song) songd['album'] = song.album.title songd['mp3'] = serve_url % songd['mp3'] return songd
def article(self, id): if not id: item = self.m.all().get() else: item = self.m.get_by_id(id) if not item: return False itemd = utils.to_dict(item) return itemd
def get(self): try: players = [utils.to_dict(player) for player in NFL_Player_2015_M.query.all()] except: abort(400, response={ 'status': 400, 'message': 'Players not found' }) else: return utils.success(players)
def CommentHandler(request, comment_id=None): if request.method == "GET" and comment_id is None: comments = Comment.objects.all() data = [] for comment in comments: comment_dict = to_dict(comment) data.append(comment_dict) return JsonResponse(data, safe=False) if request.method == "GET" and comment_id is not None: try: comment = Comment.objects.get(pk=comment_id) except Comment.DoesNotExist: return JsonResponse({"error": "Comment does not exist"}, status=404) comment_dict = to_dict(comment) return JsonResponse(comment_dict, status=200)
def put(self, obj_t, *args): kvs = json.decode(self.request.body) # find model class cls = getattr(sys.modules['core.model'], obj_t) # dispatch put to that model class. all model classes need to a subclass model.RESTModel obj = utils.to_dict(cls.put1(kvs)) return self.prep_json_response(200, message=obj)
def put(self, obj_t, *args): kvs = json.decode(self.request.body) # find model class cls = getattr(sys.modules['core.model'], obj_t) # dispatch put to that model class. all model classes need to a subclass model.RESTModel obj = utils.to_dict(cls.put1(kvs)) return self.prep_json_response(200, message = obj)
def create(self, request): """ POST Asignar un TFG a uno o varios alumnos :param request: :return: {status: True/False, data:{serializer del tfg asignado y de los alumnos} """ try: params = utils.get_params(request) if params.get('delete'): return Tfg_asigViewSet().delete(request) self.logger.info('INICIO WS - TFGASIGVIEW POST del usuario: %s con parametros: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, params)) if request.user.has_perm('tfgs.tfg_asig.change') or request.user.is_admin: alumno_2 = None alumno_3 = None tfg = Tfg.objects.get(titulo=params.get('tfg')) # Si es profesor if Profesor.objects.filter(email=request.user.email).exists() and request.user.email != tfg.tutor.\ email: raise NameError("El profesor no es tutor del Tfg") alumno_1 = utils.get_or_create_alumno(params.get('alumno_1')) if 'alumno_2' in params: alumno_2 = utils.get_or_create_alumno(params.get('alumno_2')) if 'alumno_3' in params: alumno_3 = utils.get_or_create_alumno(params.get('alumno_3')) serializer = self.serializer_class(data=dict(tfg=tfg.id, alumno_1=alumno_1.id, alumno_2=alumno_2, alumno_3=alumno_3)) if serializer.is_valid(): resul = serializer.create(serializer.validated_data) if resul['status']: resul = utils.to_dict(resul) resul_status = status.HTTP_200_OK else: resul = dict(message=resul['message']) resul_status = status.HTTP_400_BAD_REQUEST else: resul = dict(message=serializer.errors) resul_status = status.HTTP_400_BAD_REQUEST else: resul = dict(message="Sin privilegios") resul_status = status.HTTP_400_BAD_REQUEST self.logger.info('FIN WS - TFGASIGVIEW POST del usuario: %s con resultado: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, resul)) return Response(resul, status=resul_status) except NameError as e: self.logger.error('FIN WS - TFGASIGVIEW POST: %s' % e.message) return Response(dict(message=e.message), status=status.HTTP_400_BAD_REQUEST) except Exception as e: resul = dict(status=False, message="Error en la llamada") self.logger.critical('FIN WS - TFGASIGVIEW POST: %s %s' % (resul, e)) return Response(resul, status=status.HTTP_400_BAD_REQUEST)
def main(config): # WandB Resume Handling resume = False if config.resume is not None: resume = True if config['track_experiment']: # Send Config to WandB wandb.init(config=flatten(to_dict(config.config)), **flatten(config['wandb']), resume=resume) # Logger logger = config.get_logger('train') # setup data_loader instances data_loader = config.init_obj('data_loader', module_data) valid_data_loader = data_loader.split_validation() # build model architecture, then print to console model = config.init_obj('arch', module_arch) logger.info(model) # get function handles of loss and metrics criterion = getattr(module_loss, config['loss']) metrics = [getattr(module_metric, met) for met in config['metrics']] # build optimizer, learning rate scheduler. delete every lines containing lr_scheduler for disabling scheduler trainable_params = filter(lambda p: p.requires_grad, model.parameters()) if 'module' not in config['optimizer']: module = torch.optim else: module = config['optimizer']['module'] optimizer = config.init_obj('optimizer', module, trainable_params) lr_scheduler = config.init_obj('lr_scheduler', torch.optim.lr_scheduler, optimizer) if config['track_experiment']: # Send model to WandB wandb.watch(model) # Trainer trainer = Trainer(model, criterion, metrics, optimizer, config=config, data_loader=data_loader, valid_data_loader=valid_data_loader, lr_scheduler=lr_scheduler) trainer.train()
def get(self, pos): m = model_map[pos] try: games = [ utils.to_dict(m) for m in m.query.filter_by(is_season_totals=False).all() ] except: abort(400, response={'status': 400, 'message': 'Games not found'}) else: return utils.success(games)
def process(user_id, all=False): print('process user_id=%s, all=%s' % (user_id, all)) medias = get_medias(user_id, all) for m in medias: d = to_dict(m) pprint.pprint(d) if all: print('medias total: %s' % len(medias)) urls = [m.get_standard_resolution_url() for m in medias] write_list(u'%s_list.txt' % user_id, urls) download_insta_files(get_medias(user_id, all), output=user_id)
def permissions(user_id): query = db.session.query(User, Rol, UsersRol, RolsFunctionality, Functionality).filter( User.id == UsersRol.user_id).filter(Rol.id == UsersRol.rols_id).filter( User.id == user_id).filter(Functionality.id == RolsFunctionality.functionality_id).filter( RolsFunctionality.rol_id == UsersRol.rols_id) data = [] for user, rl, userrol, rolfunc, func in query.all(): data.append({**to_dict(func, ['view_id'])}) return jsonify({"status": True, "data": data})
def get(self, pos): m = model_map[pos] try: totals = [utils.to_dict(m) for m in m.query.filter_by(is_season_totals=True).all()] except: abort(400, response={ 'status': 400, 'message': 'Season totals not found' }) else: return utils.success(totals)
def select(self, id=None, *args, **kwargs): model = self.model data = request_json() if not id: id = data.get('id') if id: # return one row item = model.objects.filter(id=id).first() return ut.success(data=to_dict(item)) if item else ut.failed( 'Not found', code=404) else: # return resources list # default page: 1, per_page: 20 page = int(request.args.get('page') or 1) per_page = int(request.args.get('per_page') or 20) start = (page - 1) * per_page end = page * per_page models = model.objects.all()[start:end] modelsDict = [to_dict(item) for item in models] return ut.success(modelsDict)
def render_webpage(request, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9): args = request.args temp_args = to_dict(args) if len(args) == 0: #This ensures it's a navigation page if not arg1: # this means we're at the start page info = set_info_for_start_page() return render_template("LfunctionNavigate.html", **info) elif arg1.startswith("degree"): degree = int(arg1[6:]) info = { "degree" : degree } info["key"] = 777 info["bread"] = [('L-functions', url_for("render_Lfunction")), ('Degree '+str(degree), '/L/degree'+str(degree))] if degree == 1: info["contents"] = [LfunctionPlot.getOneGraphHtmlChar(1,35,1,13)] info['friends'] = [('Dirichlet Characters', '/Character/Dirichlet/')] elif degree == 2: info["contents"] = [processEllipticCurveNavigation(args), LfunctionPlot.getOneGraphHtmlHolo(1, 22, 2, 14)] elif degree == 3 or degree == 4: info["contents"] = LfunctionPlot.getAllMaassGraphHtml(degree) return render_template("DegreeNavigateL.html", info=info, title = 'Degree ' + str(degree)+ ' L-functions', bread = info["bread"]) elif arg1 == 'custom': # need a better name return "not yet implemented" try: L = generateLfunctionFromUrl(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, temp_args) except Exception as inst: # There was an exception when creating the page error_message = ('There was an error loading this page. Please report the ' + 'address of this page and the following error message: ' + str(inst.args)) if len(inst.args) >1: if inst.args[1]== "UserError": error_message = inst.args[0] info = { 'content': error_message, 'title': 'Error' } return render_template('LfunctionSimple.html', info=info, **info) try: logger.info(temp_args) if temp_args['download'] == 'lcalcfile': return render_lcalcfile(L, request.url) except: 1 #Do nothing info = initLfunction(L, temp_args, request) return render_template('Lfunction.html', **info)
def dirichlet_table(**args): modulus = request.args.get("modulus", 1, type=int) info = to_dict(args) info['modulus'] = modulus info["bread"] = [('Dirichlet Character Table', url_for("dirichlet_table")), ('result', ' ')] info['credit'] = 'Sage' h, c, = get_entries(modulus) info['headers'] = h info['contents'] = c info['title'] = 'Dirichlet Characters' return render_template("/dirichlet_characters/CharacterTable.html", **info)
def get(self): p = re.compile('.*/draw/([0-9]+)$') match = p.search(self.request.url) id = match.group(1) script = Script.get_by_id(int(id)) item = utils.to_dict(script) item['data'] = script.data item['title'] = script.title item['id'] = script.key().id() self.response.out.write(json.dumps(item))
def album(self, id): if not id: album = self.m.all().get() else: album = self.m.get_by_id(id) if not album: return False albumd = utils.to_dict(album) albumd['artwork'] = images.get_serving_url(albumd['artwork'], 320) albumd['songs'] = self.songs(album) return albumd
def get(self): id = self.request.get('id') scripts = [] query = Script.all().order('-date') for script in query.fetch(10): item = utils.to_dict(script) item['id'] = script.key().id() scripts.append(item) self.response.out.write(json.dumps(scripts))
def write_to_elasticsearch(conn, data, xen_index): conn.indices.create(index=xen_index, body=PS_TIMEFOCUSED_MAPPING, ignore=400) columns = data.columns.values.tolist() for row in data.itertuples(): uniq_id = row[0] doc = to_dict(row, columns) _ = conn.index(index=xen_index, doc_type='patchserie', id=uniq_id, body=doc)
def article(self, id): if not id: item = self.m.all().get() else: item = self.m.get_by_id(id) if not item: return False itemd = utils.to_dict(item) key = itemd['img'] itemd['img'] = images.get_serving_url(key, 200) itemd['img_big'] = images.get_serving_url(key, 1024) return itemd
def get(self, player_id): try: row = NFL_Player_2015_M.query.filter(NFL_Player_2015_M.id == player_id).all() player = utils.to_dict(row) game_model = pos_map[player['position']] games = game_model.query.filter(game_model.player_name == player['name']).all() except: abort(400, response={ 'status': 400, 'message': 'Player not found' }) else: return utils.success(games)
def recommend(): try: limit = request.args.get('limit', 10, type=int) body = request.get_json() ids = ctp_rec.recommend(body, limit=limit) print(ids) cursor = db.product.find({'_id': {'$in': ids}}) products = [to_dict(doc) for doc in cursor] # return response_to_client(status= HTTP_Status.SUCCESS, data= dumps(products)) return {'data': products} except: return {'error': 'Lấy gợi ý thất bại'}