def manage_products(): if request.method == 'POST': action = request.form['submit'] if action == "Редактировать": prod = Utils.get_product_id(request.form['id']) factories = Utils.clear_select(prod.factory, DbUtils.select_factories_names()) types = Utils.clear_select(prod.product_type, DbUtils.select_product_types_names()) ingredients = Utils.clear_select(prod.ingridients, DbUtils.select_ingredients_name()) return render_template('edit_product.html', product=prod, factories=factories, types=types, ingredients=ingredients, login=app.config['USER'].login, type=app.config['USER'].type) elif action == "Удалить": DbUtils.delete_product(request.form['id']) products = Utils.get_products() return render_template('manage_products.html', products=products, len_p=len(products), login=app.config['USER'].login, type=app.config['USER'].type)
def __init__(self, sqlalchemy_session, base_url='http://127.0.0.1:8080', key: bytes = b"EncryptionAsFuck"): self.scoped_session = sqlalchemy_session self.session = sqlalchemy_session() self.base_url = base_url self.loop = asyncio.get_event_loop() self.encryption = Encryption(key) self.utils = Utils(self.encryption) atexit.register(self.cleanup) self.being_encoded = [] self.routes = [] self.routes += [web.get("/", self.index)] # Add the index route # Add the upload route self.routes += [web.post('/upload', self.upload), web.get('/upload', self.upload_page)] # Add the ts file route self.routes += [web.get('/ts/{b64}', self.ts_file)] # Add the m3u8 file route self.routes += [web.get('/hls/{b64}', self.get_m3u8)] # Add the m3u8 file route self.routes += [web.get('/play/{b64}', self.player)] # Add the key route self.routes += [web.get('/enc/{b64}', self.get_key)] # Add the delete route self.routes += [web.get('/del/{fid}', self.delete)] self.routes += [web.get('/queue', self.queue)]
def calculate_distance_map(self, img_luv, target_distribution): """Calculates a distance map by sliding a window by a given stride""" distances = np.empty( dtype=np.uint8, shape=(int((img_luv.shape[0] - self.window_size) / self.stride), int((img_luv.shape[1] - self.window_size) / self.stride))) for x in range(distances.shape[1]): for y in range(distances.shape[0]): x_px = x * self.stride y_px = y * self.stride local_distribution = Utils.calculate_distribution( img_luv[y_px:y_px + self.window_size, x_px:x_px + self.window_size]) distance = Utils.bhattacharyya_distance( local_distribution, target_distribution) # clamp & check distance if np.isnan(distance): print("Distance calculated was NaN! Setting to 255.") distance = 255 if distance > 255: distance = 255 if distance < 0: distance = 0 distances[y, x] = int(distance) # DEBUG self.distances_img = self.distance_map_to_img(distances, img_luv) return distances
def refresh(self): self.screen.blit(self.intro_screen_background, (0, 0)) self.screen.blit(self.title, (Props.SCREENLENGTH * .22, Props.SCREENHEIGHT * .05)) self.exit_button.draw(self.screen) self.play_button.draw(self.screen) Utils.display_xy(self.screen) self.music.music_button.draw(self.screen)
def test_my_sum__when_floats__expect_to_be_equal(self): numbers = [1.0, 2.0, 3.0, 4.0] utils = Utils() actual_result = utils.sum(numbers) expected_result = 10.0 self.assertEqual(expected_result, actual_result)
def buy_coupon(self, user_id, numbers): if len(numbers) != 6 or not Utils.numbers_in_range( numbers) or not Utils.number_unique(numbers): return {'response': 'COUPON_BUY COUPON_INVALID_NUMBERS'} try: if self.check_balance_enough(user_id): lotto_id = self.get_new_lotto_id() print(lotto_id) if not lotto_id: return { 'response': 'COUPON_BUY COUPON_BUY_LOTTERY_PROBLEM' } if self.update_balance(user_id, lotto_price * (-1)): now = datetime.now() bought_date = now.strftime(date_format) serialize_numbers = Utils.to_string(numbers) print(serialize_numbers, type(serialize_numbers)) self.cursor.execute( 'insert into coupons (bought_date, lotto_id, user_id, numbers) values (?,?,?,?)', (bought_date, lotto_id[0], user_id, serialize_numbers)) self.connection.commit() return {'response': 'COUPON_BUY COUPON_BUY_OK'} else: return {'response': 'UNEXPECTED_ERROR'} else: return {'response': 'COUPON_BUY NO_ENOUGH_BALANCE'} except sqlite3.Error as e: print('buy_coupon error', e) return {'response': 'UNEXPECTED_ERROR'}
def calculate_tax(self, monthly_income, bonus=0, rebates=0, donation=0): annual_income = Utils.get_annual_income(monthly_income) logging.debug( "Calculating tax... | Annual: {} | Bonus: {} | Rebates: {} | Donation: {}" .format(annual_income, bonus, rebates, donation)) try: self._validate_input(annual_income, bonus, rebates, donation) except ValueError as e: logging.error(e) raise e taxable_income = Utils.get_taxable_income(annual_income, bonus, rebates, donation) total_tax = 0 tier_level = '0' tier_info = TAX_TIERS['0'] if taxable_income > 20000: tax_tier = list( filter( lambda item: item[1]['lower_limit'] < taxable_income <= item[1]['upper_limit'], TAX_TIERS.items())) tax_tier_information = tax_tier[0] tier_level = tax_tier_information[0] tier_info = tax_tier_information[1] total_tax = self._get_total_tax(taxable_income, tier_info) logging.debug("Tier: {} | Total tax: {} | Tax Info: {}".format( tier_level, total_tax, tier_info)) result = TaxInformation(tier_level, tier_info, total_tax) return result
def testsequence(self): data = [ { 'input': 'http://test.com asdfasdf http://twitpic.com/adsfk32', 'expected': '<a href="http://test.com">http://test.com</a> asdfasdf <div class="twitpic_img"><a href="http://twitpic.com/adsfk32"><img src="http://twitpic.com/show/large/adsfk32" width="350" alt="adsfk32"/></a></div>' } ] # just testing that we get the same result regardless of the order f1 = lambda str: Utils.twitpic_to_img(Utils.links_to_anchors(str)) f2 = lambda str: Utils.links_to_anchors(Utils.twitpic_to_img(str)) self._runTests( data, f1 ) self._runTests( data, f2 )
def test_send_new_jobs_to_slack(self, wd, keyword): config.base_url = 'https://www.upwork.com/o/jobs/browse/' open_url('?q={_keyword}'.format(_keyword=keyword)) jobs_result = UpworkSearchPage.get_jobs_from_page(keyword) Utils.send_results_to_slack(channel='job-upwork', results=jobs_result, file_name=CSV_FILE_NAME) Utils.write_csv(jobs_result, file_name=CSV_FILE_NAME)
def temp_upload(request): operator = Operators.login_required(request) if operator is None: Operators.set_redirect_field_name(request, request.path) return redirect(reverse("operators_signin")) else: if request.POST: file_path = settings.MEDIA_ROOT + '/temp/' + request.POST['name'] image_data = request.POST['data'] Utils.save_image_base64(image_data, file_path) return HttpResponse('success') else: return HttpResponseBadRequest('no data')
def get_taxable_salary(ns1, nb1, ns2, nb2, ns3, nb3, donation, monthly_salary, annual_bonus, tax_rebates): annual_salary = Utils.get_annual_income(monthly_salary) taxable_salary = Utils.get_taxable_income(annual_salary, annual_bonus, tax_rebates, donation) return html.Div(className="row mt-1", children=[ html.Div(className="col-sm-3 mr-1", children=["Taxable salary: "]), html.Div( className="col-sm-3", children=["S$ {0:.2f}".format(taxable_salary)]) ])
def test_utils_sum__when_ints__expect_correct_result(self, validator_mock): # Arrange (prepare) ValidatorMock = validator_mock.return_value ValidatorMock.validate.return_value = None utils = Utils() numbers = [1, 2, 3, 4] # Act actual_result = utils.sum(numbers) # Assert expected_result = 10.1 self.assertEqual(expected_result, actual_result, 'Actual result is not equal to expected')
def authenticate_user(db: Session, username: str, password: str): user = get_user_by_username(db, username) if not user: return False if not Utils.verify_password(password, user.hashed_password): return False return user
def sign_in(): if request.method == 'POST': action = request.form['submit'] if action == "Регистрация": return render_template('registration.html') login = request.form['login'] password = request.form['password'] p_hash = DbUtils.get_user_password(login) if p_hash is not None: if check_password_hash(DbUtils.get_user_password(login), password): tmp = DbUtils.select_user_full(login) app.config['USER'] = User(tmp[0][0], tmp[0][1], tmp[0][2], tmp[0][3], tmp[0][4]) products = Utils.get_prod_units() return render_template('buy_prod_units.html', products=products, len_p=len(products), login=app.config['USER'].login, type=app.config['USER'].type) else: return render_template('index.html', messege="Неправильный логин или пароль") else: return render_template('index.html', messege="Неправильный логин или пароль") else: return redirect(url_for('index.html')) return render_template('index.html')
def add_prod_unit(): if request.method == 'POST': action = request.form['s_btn'] if action == "Поиск": names = DbUtils.select_products_names_find(request.form['find']) return render_template('add_prod_unit.html', names=names, len_n=len(names), login=app.config['USER'].login, type=app.config['USER'].type) elif action == "Добавить продукт": prod_id = DbUtils.select_products_id( request.form['prod_name'])[0][0] DbUtils.insert_product_units(prod_id, request.form['prod_count'], request.form['prod_date'], "for sale", request.form['price']) products = Utils.get_prod_units() return render_template('manage_prod_units.html', products=products, len_p=len(products), login=app.config['USER'].login, type=app.config['USER'].type) names = DbUtils.select_products_names() return render_template('add_prod_unit.html', names=names, len_n=len(names), login=app.config['USER'].login, type=app.config['USER'].type)
def buy_prod_units(): products = Utils.get_prod_units() return render_template('buy_prod_units.html', products=products, len_p=len(products), login=app.config['USER'].login, type=app.config['USER'].type)
def segment(self, img_original, target_distribution_rect): """Returns a quad or None if segmentation failed""" # DEBUG self.img_original = img_original # norm, preprocess, luv img_normalized = self.normalize(img_original) img_preprocessed = self.preprocess(img_normalized) img_luv = cv2.cvtColor(img_preprocessed, cv2.COLOR_BGR2Luv) # target distribution r = target_distribution_rect.scale(self.scale_factor).floor() target_distribution = Utils.calculate_distribution( img_luv[r.a[1]:r.b[1], r.a[0]:r.b[0]]) # distance map distances = self.calculate_distance_map(img_luv, target_distribution) # region region = self.get_receipt_pixels(distances) if region is None: return None # quad quad = self.extract_quad(region) return quad
def render(self, name, value, attrs=None): if not 'id' in attrs: attrs['id'] = "id_%s" % name STATIC_URL = STATIC_URL_BASE rgb = Utils.hex_to_rgb(value) rendered_input = super(MooRainbowColorPicker, self).render(name, value, attrs) return render_to_string('plugins/color_utils/moorainbow.html', locals())
def get_annual_salary(n_submit, n_blur, value): annual_salary = Utils.get_annual_income(value) return html.Div(className="row mt-1", children=[ html.Div(className="col-sm-3 mr-1", children=["Annual salary: "]), html.Div(className="col-sm-3", children=["S$ {0:.2f}".format(annual_salary)]) ])
def edit_product(): if request.method == 'POST': expiration_size = request.form['expitation_size'] if expiration_size == "час": expiration = int(request.form['expitation_value']) elif expiration_size == "день": expiration = 24 * int(request.form['expitation_value']) elif expiration_size == "месяц": expiration = 730 * int(request.form['expitation_value']) elif expiration_size == "год": expiration = 8760 * int(request.form['expitation_value']) file = request.files['picture'] if file.filename == "": DbUtils.update_product(request.form['id'], request.form['prod_name'],\ DbUtils.select_factories_id(request.form['factory'])[0][0], \ DbUtils.select_product_types_id(request.form['type'])[0][0], \ request.form['calorie_content'],\ expiration,\ request.form['dimension'],\ request.form['weight']) else: file.save(app.config['UPLOAD_FOLDER'] + file.filename) DbUtils.update_product_pic( request.form['id'], request.form['prod_name'], DbUtils.select_factories_id(request.form['factory'])[0][0], DbUtils.select_product_types_id(request.form['type'])[0][0], request.form['calorie_content'], expiration, request.form['dimension'], request.form['weight'], file.filename) DbUtils.delete_product_ingredient(request.form['id']) DbUtils.insert_product_ingredients( request.form['id'], request.form.getlist('ingredient[]')) products = Utils.get_products() return render_template('manage_products.html', products=products, len_p=len(products), login=app.config['USER'].login, type=app.config['USER'].type) factories = DbUtils.select_factories_names() types = DbUtils.select_product_types_names() ingredients = DbUtils.select_ingredients() return render_template('add_product.html', factories=factories, len_f=len(factories), types=types, len_t=len(types), ingredients=ingredients, len_i=len(ingredients), login=app.config['USER'].login, type=app.config['USER'].type)
def get_last_lotto(self, count): try: self.cursor.execute( 'select * from lotto where won_numbers is not null order by lotto_id desc' ) last_won = Utils.serializer(self.cursor.fetchmany(count)) return {'response': 'LAST_WON ' + last_won} except sqlite3.Error as e: return {'response': 'UNEXPECTED_ERROR'}
def refresh(self): self.screen.blit(self.background, (0, 0)) self.screen.blit(self.bow, (830, 115)) self.screen.blit(self.sword, (870, 115)) self.screen.blit(self.spear, (910, 115)) self.screen.blit(self.horseman, (950, 115)) self.ready_button.draw(self.screen) self.back_button.draw(self.screen) self.board_game() self.display_phase() Utils.display_xy(self.screen) self.music.music_button.draw(self.screen) if self.current_phase == self.PHASE_PLANNING: self.ready_button.set_visibility(visible=True) self.ready_button.set_enabled(enabled=True) else: self.ready_button.set_visibility(visible=False) self.ready_button.set_enabled(enabled=False)
def create_lotto(self): try: now = Utils.get_lottery_date() self.cursor.execute( 'insert into lotto (lottery_date, count_of_three, count_of_four, count_of_five, count_of_six, main_prize) values (?,?,?,?,?,?)', (now, 0, 0, 0, 0, 1000000)) self.connection.commit() return True except sqlite3.Error: return False
def get_won_list(self): try: self.cursor.execute( 'select lottery_date , main_prize, won_numbers, count_of_three, count_of_four, count_of_five, count_of_six from lotto where won_numbers is not null order by lotto_id desc limit 10' ) won_list = Utils.serializer(self.cursor.fetchall()) return {'response': 'WON_LIST ' + won_list} except sqlite3.Error as e: print(e) return {'response': 'UNEXPECTED_ERROR'}
def get_count_of_winners(self, lotto_id, won_numbers): count_of_three = 0 count_of_four = 0 count_of_five = 0 count_of_six = 0 try: coupons_list = self.get_coupons(lotto_id) main_prize = self.get_main_prize(lotto_id) for coupon in coupons_list: numbers = Utils.to_array(coupon[4]) count_of_same_number = Utils.get_count_of_same_numbers( won_numbers, numbers) if count_of_same_number == 3: self.update_balance(coupon[3], 100) count_of_three += 1 elif count_of_same_number == 4: self.update_balance(coupon[3], 1000) count_of_four += 1 elif count_of_same_number == 5: self.update_balance(coupon[3], 10000) count_of_five += 1 elif count_of_same_number == 6: self.update_balance(coupon[3], main_prize) count_of_six += 1 last_lottery_id = self.get_last_lottery_id() if count_of_six == 0 and last_lottery_id: self.update_main_prize(last_lottery_id, main_prize) return { 'count_of_three': count_of_three, 'count_of_four': count_of_four, 'count_of_five': count_of_five, 'count_of_six': count_of_six } except: return { 'count_of_three': count_of_three, 'count_of_four': count_of_four, 'count_of_five': count_of_five, 'count_of_six': count_of_six }
def show_statistic(): print('args:', request.args) print('json:', request.json) start_time = str(request.args.get('start_time')) end_time = str(request.args.get('end_time')) print('start_time:', start_time) print('end_time:', end_time) # 查询缓存 statistic_key = f'start_time:{start_time}_end_time:{end_time}' statistic_dict = redis_mgr.get_from_redis(statistic_key) if statistic_dict is not None: return Utils.build_resp(0, 'success', statistic_dict) # 若没有缓存则重新构造数据 raw_key = current_app.config['CACHE_RAW_KEY'] data = redis_mgr.load_df_from_redis(raw_key) if data is None: depth_raw = db_mgr.query('depth_raw') order_raw = db_mgr.query('order_raw') trade_raw = db_mgr.query('trade_raw') data = db_mgr.combine_raw(depth_raw, order_raw, trade_raw, resample_freq='1s') redis_mgr.store_df_to_redis(raw_key, data) # res_df = data.loc['2020-11-20 09:30:03':'2020-11-20 09:30:10'].agg( # {'price': ['max', 'min'], 'OrderVolume': 'sum', 'TradeVolume': 'sum'}) data.set_index('time', inplace=True) res_df = data.loc[start_time:end_time].agg({ 'price': ['max', 'min'], 'OrderVolume': 'sum', 'TradeVolume': 'sum' }) max_price = res_df.loc['max', 'price'] min_price = res_df.loc['min', 'price'] total_order = res_df.loc['sum', 'OrderVolume'] total_trade = res_df.loc['sum', 'TradeVolume'] result = dict(max_price=max_price, min_price=min_price, total_order=total_order, total_trade=total_trade) redis_mgr.set_to_redis(statistic_key, result) return Utils.build_resp(0, 'success', result)
def manage_prod_units(): if request.method == 'POST': action = request.form['submit'] if action == "Удалить": DbUtils.delete_product_units(request.form['id']) products = Utils.get_prod_units() return render_template('manage_prod_units.html', products=products, len_p=len(products), login=app.config['USER'].login, type=app.config['USER'].type)
def good_to_order(): if request.method == 'POST': if app.config['ORDER_ID'] == -1: app.config['ORDER_ID'] = DbUtils.insert_order( "open", app.config['USER'].id) DbUtils.insert_good(request.form['id'], request.form['count'], app.config['ORDER_ID']) products = Utils.get_prod_units() return render_template('buy_prod_units.html', products=products, len_p=len(products), login=app.config['USER'].login, type=app.config['USER'].type, messege="Товар успешно добавлен в корзину") products = Utils.get_prod_units() return render_template('buy_prod_units.html', products=products, len_p=len(products), login=app.config['USER'].login, type=app.config['USER'].type)
def create_users(db: Session, user: schemas.UserCreate): hashed = Utils.get_password_hash(user.password) db_user = models.User( email=user.email, username=user.username, full_name=user.full_name, hashed_password=hashed, ) db.add(db_user) db.commit() db.refresh(db_user) return db_user
class TranslationManager: HUMAN_MONEY_IDENTIFIER = 'Credits' GALACTIC_MONEY_IDENTIFIER = '' def __init__(self): self.items = {} self.utils = Utils() self.human_converter = HumanPrizeConverter() self.galatic_converter = GalacticPrizeConverter() def add_item(self, word: str, translation: str, currency_type: str = ''): item_values = { 'translation': translation, 'currency_type': currency_type } if currency_type == self.GALACTIC_MONEY_IDENTIFIER and not self.utils.check_roman_numerals(translation): raise ValueError('The input value "{}" is not a roman numeral'.format(translation)) self.items.update({word: item_values}) def translate_prize_phrase(self, foreign_phrase: str, asked_type: str = ''): if self._check_if_already_converted(foreign_phrase, asked_type): return foreign_phrase if foreign_phrase in self.items: return self._get_prize_by_asked_type(foreign_phrase, asked_type) words = foreign_phrase.split(sep=' ') translated_phrase = '' for w in words: try: translated_phrase += self.items[w]['translation'] except KeyError: raise KeyError('The word "{}" is not registered in translator'.format(w)) return self._translate_word(asked_type, translated_phrase) def _get_prize_by_asked_type(self, foreign_phrase: str, asked_type: str = ''): if asked_type == self.items[foreign_phrase]['currency_type']: return self.items[foreign_phrase]['translation'] else: return self._translate_word(asked_type, self.items[foreign_phrase]['translation']) def _translate_word(self, type: str, word: str): return { 'Credits': lambda word: self.galatic_converter.convert_to_human_prize(word), '': lambda word: self.human_converter.convert_to_galactic_prize(int(word)) }[type](word) def _check_if_already_converted(self, foreign_phrase: str, asked_type: str = ''): return ( (foreign_phrase.isdigit() and asked_type == self.HUMAN_MONEY_IDENTIFIER) or ( foreign_phrase and not foreign_phrase.isdigit() and asked_type == '' ) )
def toEntry(self, status): from app.utils import StringHelper e = Entry(external_id=str(status['id']), source = self.source_id, text = Utils.links_to_anchors(Utils.twitpic_to_img(status['text'])), title = StringHelper().remove_new_lines(status['text']), url='http://twitter.com/' + str(status['user']['screen_name']) + '/statuses/' + str(status['id'])) e.created = parse(status['created_at']) # extract the tags e.tags = StringHelper().extract_twitter_tags(status['text']) # process the location coordinates if they're available if status['coordinates'] != None: e.lat = str(status['coordinates']['coordinates'][1]) e.lng = str(status['coordinates']['coordinates'][0]) # is this entry a reply-to? logging.debug(e.text[0]) e.twitter_reply = (e.text[0] == '@') return(e)
def refresh(self): self.screen.blit(self.background, (0, 0)) self.ready_button.draw(self.screen) self.back_button.draw(self.screen) self.bow.draw(self.screen) self.sword.draw(self.screen) self.spear.draw(self.screen) self.horseman.draw(self.screen) self.board_game() self.display_phase() self.display_turn_number() Utils.display_xy(self.screen) self.music.music_button.draw(self.screen) if self.selected_unit is not None: self.screen.blit(self.selected_unit, pygame.mouse.get_pos()) if self.current_phase == self.PHASE_PLANNING: self.ready_button.set_visibility(visible=True) self.ready_button.set_enabled(enabled=True) else: self.ready_button.set_visibility(visible=False) self.ready_button.set_enabled(enabled=False)
# Создаем новую группу параметров create_group = create_parser.add_argument_group (title='Settings') # Добавляем параметры create_group.add_argument ('-ip', '--import-path', type=input_path, default=Settings.IMPORT_PATH, help = 'Path to directory with tomographic data (slices, images).') create_group.add_argument ('-snf', '--slice-path-format', type=str, default=Settings.SLICE_PATH_FORMAT, help = r'Format of slices(images) path. Example: [\D,\d]*?(tomo_data.*slices[\D,\d]*?/[^/]+\d+.tif)') create_group.add_argument ('-f', '--force', type=bool, default=False, help = r'Force creation even slicemaps already created') create_group.add_argument ('--help', '-h', action='help', help='Help') return parser if __name__ == '__main__': parser = createParser() namespace = parser.parse_args(sys.argv[1:]) if namespace.command == "run": paths_for_processing = Utils.get_slices_dirs_for_processing( namespace.import_path, namespace.slice_path_format, namespace.force ) sf = SlicemapFactory() sf.processMany( paths_for_processing ) print( json.dumps({"triggered": True, "number_of_new_volumes": len(paths_for_processing), "paths_to_the_new_volumes": paths_for_processing, "datetime": strftime("%d-%m-%Y %H:%M:%S", gmtime()) }) ) cherrypy.log( "triggered: %s, number_of_new_volumes: %s, paths_to_the_new_volumes: %s" % (True, len(paths_for_processing), paths_for_processing) ) else: parser.print_help()