def exchange(message): # /exchange 10 CAD - convert my base_currency to CAD params = message.text.split('/exchange')[1].strip() # base currency to the second if re.fullmatch(r'^[0-9.]+ +[a-zA-Z]{3}$', params): params = params.split() params = {'number': params[0], 'target_currency': params[1]} number = utils.is_valid_number(params['number']) if not number: bot.send_message(message.chat.id, 'invalid number {}'.format(params['number'])) elif params['target_currency'] not in rate_database['rates']: bot.send_message( message.chat.id, 'target currency {} is not present in my database. Try to /list to update my database' .format(params['target_currency'])) else: converted = '{:.2f}'.format( number * rate_database['rates'][params['target_currency']]) bot.send_message( message.chat.id, '{} {} to {} is {}'.format(number, base_currency, params['target_currency'], converted)) else: bot.send_message(message.chat.id, 'invalid request')
def valid_freezer_id(self, token, freezer_id, available=True): """ Check if the id of the freezer given is correct :param available: :param token: a user token to have access to the database :param freezer_id: An integer :return: A boolean (true if it is correct) """ if not utils.is_valid_number(freezer_id): return False query = """SELECT EXISTS (SELECT * FROM List_freezer WHERE freezer_id = %s AND token = %s)""" res = self.query_db.get_query_db(query, ( freezer_id, token, ), one=True) if res[0] == 1: val = False else: val = True if available: return val else: return not val
def check_product_emplacement(self, token, freezer_id, box_num, prod_num): """ Check if the emplacement given is valid. It checks the freezer identifier with the box number and the product number. :param token: a user token to have access to the database :param freezer_id: An integer that represents the id of the :param box_num: An integer that represents the box where the product is stored :param prod_num: An integer that represents the id of the product in the box :return: A boolean (true if it is correct) """ if not utils.is_valid_number(freezer_id) \ and utils.is_valid_number(box_num) \ and utils.is_valid_number(prod_num): return False query = """SELECT * FROM List_freezer WHERE token = %s AND freezer_id = %s""" valid_freezer_id = self.query_db.get_query_db(query, ( token, freezer_id, )) if not valid_freezer_id: return False query = """SELECT prod_num FROM Product WHERE token = %s AND freezer_id = %s AND box_num = %s AND prod_num = %s AND date_out IS NULL """ res = self.query_db.get_query_db(query, ( token, freezer_id, box_num, prod_num, )) for l in res: for e in l: if e == int(prod_num): return False return True
def check_type_id(self, type_id): """ Check if the type of the product given is correct :param type_id: An integer :return: A boolean (true if it is correct) """ if not utils.is_valid_number(type_id): return False query = """SELECT EXISTS (SELECT * FROM Description_type WHERE type_id = %s)""" res = self.query_db.get_query_db(query, (type_id, ), one=True) if res[0] == 1: return True else: return False
def train(model, criterion, optimizer, epoch, coco): losses = AverageMeter() batch_time = AverageMeter() data_time = AverageMeter() train_loader = torch.utils.data.DataLoader(dataset.listDataset( args.ilsvrc, args.youtube, args.data_type, shuffle=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]), train=True, batch_size=args.batch_size, num_workers=args.workers, coco=coco), batch_size=args.batch_size) model.train() end = time.time() for i, (z, x, template, gt_box) in enumerate(train_loader): data_time.update(time.time() - end) z = z.cuda() z = Variable(z) x = x.cuda() x = Variable(x) template = template.type(torch.FloatTensor).cuda() template = Variable(template) oup = model(z, x) if isinstance(model, SiamFC) or isinstance(model, SiamVGG): loss = criterion(oup, template) elif isinstance(model, SiamFCRes22): loss = model.train_loss(oup, template) losses.update(loss.item(), x.size(0)) optimizer.zero_grad() loss.backward() if isinstance(model, SiamFCRes22): torch.nn.utils.clip_grad_norm_(model.parameters(), 10) # gradient clip if is_valid_number(loss.item()): optimizer.step() # optimizer.step() batch_time.update(time.time() - end) end = time.time() if i % args.print_freq == 0: print('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t'.format( epoch, i, len(train_loader), batch_time=batch_time, data_time=data_time, loss=losses))
def freezers(token): """ This functions has a different behavior depending on the request Type: - GET method will return a json object containing the different freezers owned by the user - POST method will add a freezer to the freezers' list of the user. The POST request takes a JSON of the following form: {"num_boxes":"4","name":"xyz"} :param token: a user token to have access to the database :return: - GET method returns a JSON object or a custom error in case of bad request - POST method returns a status code with possible a custom response if it was not a success """ # Avoid SQL injection before doing requests # with the token and check the validity of it token = MySQLdb.escape_string(token) if not validator_db.valid_token(token): return custom_response(400, responseMessage.BAD_TOKEN) if request.method == 'GET': return jsonify(query_db.get_query_db(mysqlRequests.GET_FREEZERS, (token,), header=True)) if request.method == 'POST': freezer = request.get_json() # data sent is not 'application/json' type if freezer is None: return custom_response(415, responseMessage.BAD_CONTENT_TYPE) # Check if the JSON field is correct if set(freezer.keys()) == {'num_boxes', 'name'}: if not utils.is_valid_number(freezer['num_boxes']): return custom_response(400, responseMessage.BAD_FORMAT) freezer['name'] = MySQLdb.escape_string(freezer['name']).decode("utf-8") if not query_db.insert_query_db(mysqlRequests.INSERT_FREEZER, (freezer['num_boxes'], freezer['name'], token,)): return custom_response(500, responseMessage.SERVER_ERROR) else: return custom_response(400, responseMessage.BAD_FORMAT) return Response(status=200) # Update an existing freezer if request.method == 'PUT': freezer = request.get_json() # data sent is not 'application/json' type if freezer is None: return custom_response(415, responseMessage.BAD_CONTENT_TYPE) # Check if the JSON field is correct if set(freezer.keys()) == {'freezer_id', 'num_boxes', 'name'}: if not validator_db.valid_freezer_id(token, freezer['freezer_id'], available=False): return custom_response(400, responseMessage.BAD_FORMAT) curr_freezer = query_db.get_query_db(mysqlRequests.GET_SPECIFIC_FREERZER, (freezer['freezer_id'],), one=True, header=True) if not freezer['num_boxes']: freezer['num_boxes'] = curr_freezer['number_boxes'] else: if not utils.is_valid_number(freezer['number_boxes']): return custom_response(400, responseMessage.BAD_FORMAT) if not freezer['name']: freezer['name'] = curr_freezer['freezer_name'] else: freezer['name'] = MySQLdb.escape_string(freezer['name']).decode("utf-8") query_db.insert_query_db(mysqlRequests.UPDATE_FREEZER_NAME_AND_BOXES, (freezer['name'], freezer['num_boxes'], freezer['freezer_id'],)) else: return custom_response(400, responseMessage.BAD_FORMAT) return Response(status=200) if request.method == 'DELETE': freezer = request.get_json() # data sent is not 'application/json' type if freezer is None: return custom_response(415, responseMessage.BAD_CONTENT_TYPE) # Check if the JSON field is correct if set(freezer.keys()) == {'freezer_id'}: if not validator_db.valid_freezer_id(token, freezer['freezer_id'], available=False): return custom_response(400, responseMessage.BAD_FORMAT) res = query_db.get_query_db(mysqlRequests.GET_PROD_NUM_LIST, (token, freezer['freezer_id'],), one=True, header=True) if res: return custom_response(400, responseMessage.DELETE_FREEZER) query_db.insert_query_db(mysqlRequests.DELETE_FREEZER, (freezer['freezer_id'],)) return Response(status=200) return custom_response(400, responseMessage.BAD_REQUEST)
def check_update_product(self, token, product, update): """ Check if the product follows the rules to be inserted in the database :param token: a user token to have access to the database :param update: A list of that represents the keys that the json object need to have :param product: A json object that represent the product to check :return: a Tuple True with the formatted object or False with the {'error_type': 'explanation...'} """ can_be_updated = [ 'product_name', 'text_descr', 'freezer_id', 'type_id', 'date_in', 'date_out', 'period', 'box_num', 'prod_num', 'quantity' ] if not can_be_updated == list(update.keys()): # TODO change the message sent return False, {'error_type': responseMessage.BAD_FORMAT} # set keys with None value format_prod = dict.fromkeys(can_be_updated) if update['box_num'] or update['freezer_id'] or update['prod_num']: if not update['freezer_id']: format_prod['freezer_id'] = product['freezer_id'] elif utils.is_valid_number(update['freezer_id']): format_prod['freezer_id'] = int(update['freezer_id']) else: return False, {'error_type': responseMessage.BAD_FORMAT} if not update['box_num']: format_prod['box_num'] = product['box_num'] elif utils.is_valid_number(update['box_num']): format_prod['box_num'] = int(update['box_num']) else: return False, {'error_type': responseMessage.BAD_FORMAT} if not update['prod_num']: format_prod['prod_num'] = product['prod_num'] elif utils.is_valid_number(update['prod_num']): format_prod['prod_num'] = int(update['prod_num']) else: return False, {'error_type': responseMessage.BAD_FORMAT} # to detect if the parameters given are the same or not # If it is the case there is no change done if format_prod['freezer_id'] == product['freezer_id'] and \ format_prod['box_num'] == product['box_num'] and \ format_prod['prod_num'] == product['prod_num']: pass elif not self.check_product_emplacement( token, format_prod['freezer_id'], format_prod['box_num'], format_prod['prod_num']): return False, { 'error_type': responseMessage.BAD_PRODUCT_EMPLACEMENT } if update['type_id']: if not self.check_type_id(update['type_id']): return False, {'error_type': responseMessage.BAD_PRODUCT_TYPE} format_prod['type_id'] = update['type_id'] if update['date_in']: if not self.check_date(update['date_in']): return False, {'error_type': responseMessage.BAD_PRODUCT_DATE} format_prod['date_in'] = update['date_in'] if update['date_out']: format_prod['date_remove'] = False if update['date_out'] == 'null': format_prod['date_remove'] = True elif not self.check_date(update['date_out']): return False, {'error_type': responseMessage.BAD_PRODUCT_DATE} format_prod['date_out'] = update['date_out'] if update['period']: if not utils.is_valid_number(update['period']): return False, { 'error_type': responseMessage.BAD_PRODUCT_PERIOD } format_prod['period'] = update['period'] if update['quantity']: if not utils.is_valid_number(update['quantity']): return False, { 'error_type': responseMessage.BAD_PRODUCT_QUANTITY } format_prod['quantity'] = update['quantity'] if update['product_name']: format_prod['product_name'] = MySQLdb.escape_string( update['product_name']).decode("utf-8") if update['text_descr']: format_prod['text_descr'] = MySQLdb.escape_string( update['text_descr']).decode("utf-8") return True, format_prod
def check_insert_product(self, token, header, product): """ Check if the product follows the rules to be inserted in the database :param token: a user token to have access to the database :param header: A list of that represents the keys that the json object need to have :param product: A json object that represent the product to check :return: a Tuple True with the formatted object or False with the {'error_type': 'explanation...'} """ product_formatted = {} if list(product.keys()) == header: if not self.check_product_emplacement(token, product['freezer_id'], product['box_num'], product['prod_num']): return False, { 'error_type': responseMessage.BAD_PRODUCT_EMPLACEMENT } product_formatted['freezer_id'] = int(product['freezer_id']) product_formatted['box_num'] = int(product['box_num']) product_formatted['prod_num'] = int(product['prod_num']) for idx, value in enumerate(header): if value == 'type_id' and not self.check_type_id( product[header[idx]]): return False, { 'error_type': responseMessage.BAD_PRODUCT_TYPE } elif value == 'type_id': product_formatted[header[idx]] = int(product[header[idx]]) continue if value == 'date_in' and not self.check_date( product[header[idx]]): return False, { 'error_type': responseMessage.BAD_PRODUCT_DATE } elif value == 'date_in': product_formatted[header[idx]] = datetime.strptime( product[header[idx]], '%Y-%m-%d') continue if value == 'period' and not utils.is_valid_number( product[header[idx]]): return False, { 'error_type': responseMessage.BAD_PRODUCT_PERIOD } elif value == 'period': product_formatted[header[idx]] = int(product[header[idx]]) continue if value == 'quantity' and not utils.is_valid_number( product[header[idx]]): return False, { 'error_type': responseMessage.BAD_PRODUCT_QUANTITY } elif value == 'quantity': product_formatted[header[idx]] = int(product[header[idx]]) continue if value == 'product_name': # To have the characters in utf8 and not in unicode format in the database product_formatted[header[idx]] = MySQLdb.escape_string( product[header[idx]]).decode('utf-8') continue if value == 'text_descr': # To have the characters in utf8 and not in unicode format in the database product_formatted[header[idx]] = MySQLdb.escape_string( product[header[idx]]).decode('utf-8') continue return True, product_formatted else: return False, {'error_type': responseMessage.BAD_FORMAT}