def favorite_creator(num_favorites): for i in range(num_favorites): Favorite.create( uuid=fake.uuid4(), item=Item.select().order_by(fn.Random()).get(), user=User.select().order_by(fn.Random()).get(), )
def init_db(): """initialize database and create schema""" from app import db # drop and create tables models = db.Model.__subclasses__() models += {m2m.get_through_model() for model in models for m2m in model._meta.manytomany.values()} model_dict = {model.__name__: model for model in models} db.database.drop_tables(models) db.database.create_tables(models) # initialize data from flask_peewee.utils import make_password User.create(username='******', password=make_password('admin'), email='*****@*****.**', permission=0b10000) user = User.create(username='******', password=make_password('user'), email='*****@*****.**') User.create(username='******', password=make_password('user2'), email='*****@*****.**') with open(join(dirname(__file__), 'data.json'), encoding='utf-8') as f: data = json.load(f) for key, items in data.items(): model = model_dict[key] for item in items: model.create(**item) TestPaper.get_by_id(1).choices.add(Choice.select().order_by(fn.Random()).limit(3)) TestPaper.get_by_id(2).choices.add(Choice.select().order_by(fn.Random()).limit(3)) Exam.get_by_id(1).users.add(User.select().where(User.id > 0)) Exam.get_by_id(2).users.add(User.select().where(User.id > 1)) Report.create(user=user, exam=Exam.get_by_id(1), score=100) print('db init finished')
def order_creator(num_order): for i in range(num_order): order_id = fake.uuid4() Order.create(uuid=order_id, user=User.select().order_by(fn.Random()).get(), total_price=0, delivery_address=Address.select().order_by( fn.Random()).get(), items=[])
def getremainingtask(): payload = request.get_json() df = pd.read_csv('occsDWAsIndustries_full_clean.csv', sep=',') #set user id user_id_qualtrics = payload['userid'] task_set = False #get a list of tasks that the user has already done. query_usr_done = AssignedTask.select().where( AssignedTask.user_id == user_id_qualtrics) dwas_ratedby_usr = [rating.dwa for rating in query_usr_done] while task_set == False: ##then, select a random task from the table that has a remainingNeedCount greater than zero. ##if this returns nothing, return one from the badcount table where badcount is greater than zero ##keep doing this until we find one the user has never rated. query_remaining = DwaEvalCounts_ml.select().where( DwaEvalCounts_ml.remainingneedcount > 0).order_by( fn.Random()).limit(1) if query_remaining.exists(): #select the task from the database task = query_remaining[0].dwatitle if task in dwas_ratedby_usr: continue #get a subset of the big occupational dataframe where the DWA title is equal to the task df_selectfrom = df[df['DWA Title'] == task] #randomly select one of the rows and set the job equal to the job in that row random_dwa = df_selectfrom.sample(n=1) job = random_dwa.iloc[0, 1] task_set = True else: query_bad = DwaBadCounts_ml.select().where( DwaBadCounts_ml.badcount > 0).order_by(fn.Random()).limit(1) task = query_bad[0].dwatitle if task in dwas_ratedby_usr: continue #get a subset of the big occupational dataframe where the DWA title is equal to the task df_selectfrom = df_all[df_all['DWA Title'] == task] #randomly select one of the rows and set the job equal to the job in that row random_dwa = df_selectfrom.sample(n=1) job = random_dwa.iloc[0, 1] task_set = True return jsonify({'task': task, 'job': job})
def get_random_encounter(generations: list, rarity_tier: str, shiny=False) -> WildEncounter: pokemon = (Pokemon.select().where( (Pokemon.number == Pokemon.select(Pokemon.number).where( Pokemon.generation.in_(generations) & (Pokemon.mega == 0) & (Pokemon.enabled == 1) & (Pokemon.rarity_tier == rarity_tier)).group_by( Pokemon.number).order_by(fn.Random()).limit(1)) & (Pokemon.mega == 0) & (Pokemon.enabled == 1) & (Pokemon.rarity_tier == rarity_tier)).order_by( fn.Random()).limit(1).execute())[0] return WildEncounter(pokemon, shiny)
def run(insight_type: str): count = 0 insight: ProductInsight annotator = InsightAnnotatorFactory.get(insight_type) for insight in ProductInsight.select().where(ProductInsight.type == insight_type, ProductInsight.annotation.is_null())\ .order_by(fn.Random()): if insight.process_after is not None and insight.process_after >= datetime.datetime.utcnow( ): continue if insight_type == InsightType.label.name and insight.value_tag not in AUTHORIZED_LABELS: continue try: is_processable = is_automatically_processable(insight) except InvalidInsight: logger.info("Deleting insight {}".format(insight.id)) insight.delete_instance() continue if is_processable: logger.info("Annotating insight {} (barcode: {})".format( insight.value_tag, insight.barcode)) annotator.annotate(insight, 1, update=True) count += 1 logger.info("Annotated insights: {}".format(count))
def send_anecdotes(chat_id): global chat_states anecs = list(Anecdote.select().order_by(fn.Random()).limit(2)) try: chat_states[chat_id].last_anecs = anecs except KeyError: bot.send_message(chat_id, 'Что-то пошло не так. Нажмите /play еще раз', reply_markup=telebot.types.ReplyKeyboardRemove()) for i, anec in enumerate(anecs): reply_text = '\n\n'.join([f'<b>АНЕКДОТ {i + 1}</b>', anec.text]) bot.send_message(chat_id, reply_text, parse_mode='HTML') keyboard = telebot.types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True, one_time_keyboard=True) button_first = telebot.types.KeyboardButton(chr(0x261D) + 'Первый') button_second = telebot.types.KeyboardButton(chr(0x270C) + 'Второй') not_anec_msg = chr(0x1F612) + 'Что-то из этого вообще не анек' button_not_anec = telebot.types.KeyboardButton(not_anec_msg) keyboard.add(button_first, button_second, button_not_anec) bot.send_message(chat_id, 'Какой из этих анеков набрал больше лайков?', reply_markup=keyboard)
def test_get_user_endpoint(client: CustomFlaskClient, auth_header: any): user_id = (UserModel.select(UserModel.id).where( UserModel.deleted_at.is_null()).order_by( fn.Random()).limit(1).get().id) user = UserModel.get(UserModel.id == user_id) role = user.roles[0] db_wrapper.database.close() response = client.get('/api/users/%s' % user_id, json={}, headers=auth_header()) json_response = response.get_json() json_data = json_response.get('data') assert 200 == response.status_code assert user_id == json_data.get('id') assert user.name == json_data.get('name') assert user.last_name == json_data.get('last_name') assert user.birth_date.strftime('%Y-%m-%d') == json_data.get('birth_date') assert user.created_at.strftime('%Y-%m-%d %H:%M:%S') == json_data.get( 'created_at') assert user.updated_at.strftime('%Y-%m-%d %H:%M:%S') == json_data.get( 'updated_at') assert user.deleted_at == json_data.get('deleted_at') role_data = json_data.get('roles')[0] assert role.name == role_data.get('name') assert role.label == role_data.get('label')
def get_similar_producers(consumer, limit=5, min_statuses=10, max_threshold=0.5): """ Retrieve the top producers by their similarity with the given consumer. This is an expensive computation and could be optimized in the future. """ producers = Producer.select().where( Producer.imported_statuses > min_statuses) producers = producers.order_by(fn.Random()).limit(max(2000, limit * 2)) raw_producers = [] for producer in producers: score = users_similarity_score(consumer, producer) if score <= max_threshold: raw_producers.append((score, producer)) raw_producers.sort(key=lambda p: p[0]) if limit <= 0: # sane default limit = 5 return raw_producers[:limit]
def test_update_document(client: CustomFlaskClient, auth_header: any): pdf_file = '%s/example.pdf' % current_app.config.get('MOCKUP_DIRECTORY') document = (DocumentModel.select().where( DocumentModel.deleted_at.is_null()).order_by( fn.Random()).limit(1).get()) db_wrapper.database.close() document_id = document.id data = { 'document': open(pdf_file, 'rb'), } headers = auth_header() headers['Content-Type'] = 'multipart/form-data' response = client.put(f'/api/documents/{document_id}', data=data, headers=headers) json_response = response.get_json() json_data = json_response.get('data') parse_url = urlparse(json_data.get('url')) assert 200 == response.status_code assert isinstance(json_data.get('created_by').get('id'), int) assert pdf_file == json_data.get('name') assert document.mime_type == json_data.get('mime_type') assert FileStorage.get_filesize(pdf_file) == json_data.get('size') assert parse_url.scheme and parse_url.netloc assert document.created_at.strftime('%Y-%m-%d %H:%M:%S') == json_data.get( 'created_at') assert json_data.get('updated_at') > json_data.get('created_at') assert json_data.get('deleted_at') is None
def test_get_document_data(client: CustomFlaskClient, auth_header: any): document = (DocumentModel.select().where( DocumentModel.deleted_at.is_null()).order_by( fn.Random()).limit(1).get()) db_wrapper.database.close() document_id = document.id response = client.get(f'/api/documents/{document_id}', json={}, headers=auth_header()) json_response = response.get_json() json_data = json_response.get('data') parse_url = urlparse(json_data.get('url')) assert 200 == response.status_code assert document.created_by.id == json_data.get('created_by').get('id') assert document.name == json_data.get('name') assert document.mime_type == json_data.get('mime_type') assert document.size == json_data.get('size') assert parse_url.scheme and parse_url.netloc assert document.created_at.strftime('%Y-%m-%d %H:%M:%S') == json_data.get( 'created_at') assert document.updated_at.strftime('%Y-%m-%d %H:%M:%S') == json_data.get( 'updated_at') assert document.deleted_at == json_data.get('deleted_at')
def test_export_excel_task(app: Flask): user = (UserModel.select(UserModel.id) .where(UserModel.email == app.config.get('TEST_USER_EMAIL')) .order_by(fn.Random()) .limit(1) .get()) request_data = { 'search': [], 'order': [ {'field_name': 'name', 'sorting': 'asc'}, ], 'items_per_page': 100, 'page_number': 1, } result = export_user_data_in_excel_task(created_by=user.id, request_data=request_data) document_data = result.get('result') parse_url = urlparse(document_data.get('url')) assert result.get('current') == result.get('total') assert result.get('status') == 'Task completed!' assert user.id == document_data.get('created_by').get('id') assert document_data.get('name') assert MS_EXCEL_MIME_TYPE == document_data.get('mime_type') assert document_data.get('size') > 0 assert parse_url.scheme and parse_url.netloc assert document_data.get('created_at') == document_data.get('updated_at') assert document_data.get('deleted_at') is None
def crearEvaluacionPost(request): cursada = Cursada.get(id=request.form["cursada"]) examen = Examen.get(id=request.form["examen"]) titulo = request.form["titulo"] fecha = dateparser.parse(request.form['fecha']).date() evaluacion = Evaluacion.create(examen=examen, titulo=titulo, cursada=cursada, fecha=fecha) evaluacion.save() idsSeleccionadas = [] for item in request.form.items(): partes = item[0].split('-') if (len(partes) == 2 and partes[0] == 'pregunta'): idsSeleccionadas.append(int(partes[1])) preguntas = Pregunta.select().where(Pregunta.id << idsSeleccionadas) evaluacion.preguntas.add(preguntas) if (len(idsSeleccionadas) < cantidadPreguntasRequeridas): preguntas = Pregunta.select().where( (Pregunta.examen == examen) & ~(Pregunta.id << idsSeleccionadas)) preguntas = preguntas.order_by( fn.Random()).limit(cantidadPreguntasRequeridas - len(idsSeleccionadas)) evaluacion.preguntas.add(preguntas) evaluacion.save() return redirect("/crearevaluacion")
def rand_quote(ctx, query=None): """ Random quote. Retrieve a random quote from the database. If a query is specified, then it is used. """ if query is not None: q = _find_quotes(ctx.storage, query) else: q = Quote.select() q = q \ .order_by(fn.Random()) \ .limit(1) if not q.exists(): ctx.respond(ctx._("Couldn't find any quotes.")) return quote = q[0] ctx.respond( ctx._("Quote {id}: {text}").format(id=quote.id, text=quote.quote))
def apply_insights(insight_type: str, max_timedelta: datetime.timedelta): logger.info("Timedelta: {}".format(max_timedelta)) count = 0 insight: ProductInsight annotator = InsightAnnotatorFactory.get(insight_type) authorized_labels: Set[str] = AUTHORIZED_LABELS_STORE.get() for insight in (ProductInsight.select().where( ProductInsight.type == insight_type, ProductInsight.annotation.is_null(), ).order_by(fn.Random())): if (insight.process_after is not None and insight.process_after >= datetime.datetime.utcnow()): continue if (insight_type == InsightType.label.name and insight.value_tag not in authorized_labels): continue try: is_processable = is_automatically_processable( insight, max_timedelta) except InvalidInsight: logger.info("Deleting insight {}".format(insight.id)) insight.delete_instance() continue if is_processable: logger.info("Annotating insight {} (barcode: {})".format( insight.value_tag or insight.value, insight.barcode)) annotator.annotate(insight, 1, update=True, automatic=True) count += 1 logger.info("Annotated insights: {}".format(count))
def get_unrated_statuses(user, count=20): """ Return a random sample of statuses unrated by ``user`` of max ``count``. """ # PERF This could be optimized, we're using quick & dirty code for now ratings = list(user.ratings) raw_statuses = Status.select().order_by(fn.Random()).limit(count * 2) add_expected_score = user.beta_features feat_keys = user._meta.fields.keys() feats_user_count = float(user.rated_statuses) statuses = [] for st in raw_statuses: for rt in ratings: if rt.status == st: ratings.remove(rt) continue if add_expected_score: score = users_similarity_score(user, st.author) #score = similarity_score(feat_keys, user, feats_user_count, st, 1) setattr(st, "expected_score", score) statuses.append(st) count -= 1 if count <= 0: break return statuses
def getBooks(): response = [] try: books = model.Book.select().join( model.Author, on=(model.Author.id == model.Book.author)).order_by( fn.Random()).limit(5) for book in books: response.append({ 'id': book.id, 'title': book.title, 'author': book.author.name, 'about': book.author.about, 'published': book.published, 'rating': book.rating, 'price': book.price, 'genres': book.genres, }) if books: return jsonify(response), 200 else: return jsonify({'msg': 'No more entries'}), 204 except: return jsonify({'msg': 'No picture/book is present'}), 204 return jsonify({'msg': 'Sorry something went wrong'}), 400
def start_requests(self): query = ( mod.Question.select() .join( mod.Solution, JOIN.LEFT_OUTER, on=(mod.Question.question_id == mod.Solution.question_id), ) .where(mod.Solution.question_id.is_null()) .order_by(fn.Random()) # .limit(50) ) for row in query: url = "https://leetcode.com/graphql" data = { "query": GRAPHQL_QUERY, "variables": {"titleSlug": row.question_id}, "operationName": "getQuestionDetail", } headers = { "Content-Type": "application/json", "Origin": "https://leetcode.com", "Referer": f"https://leetcode.com/problems/{row.question_id}/description", "X-Requested-With": "XMLHttpRequest", } meta = {"slug": row.question_id} yield Request( url, method="POST", body=json.dumps(data), headers=headers, meta=meta, callback=self.parse_graphql, )
def order_item_creator(num_items): orders = Order.select() for order in orders: for e in range(num_items): an_item = Item.select().order_by(fn.Random()).get() quantity = random.randint(1, 5) order.add_item(an_item, quantity)
def index(): q = User.select().where(User._state != state_to_num(Sleep)) if q.exists(): return render_template('index.html', user_id=q.order_by(fn.Random()).get().id) else: return "Сичас никого нет"
def test_insert(db_fixture, person, dependent, application, preapproval, job, asset, rental, referral, communication): with db_fixture.atomic() as txn: objects = [ person, dependent, application, preapproval, job, asset, rental, referral, communication ] before_count = list() for object in objects: object.create_table(True) note("Initial {} = {}".format(object.__class__.__name__, model_to_dict(object))) for object in objects: before_count.append(object.select().count()) if isinstance(object, Person): main.insert(db_fixture, object) random_person = Person.select().order_by( fn.Random()).limit(1).get() for key, value in model_to_dict(object).items(): if key in ['person', 'parent', 'referrer', 'referral']: object.key = random_person setattr(object, "{}_id".format(key), random_person.id) try: # Need to do this try in case the application table is empty. random_application = Application.select().order_by( fn.Random()).limit(1).get() for key, value in model_to_dict(object).items(): if key in ['application']: object.key = random_application setattr(object, "{}_id".format(key), random_application.id) except Application.DoesNotExist: pass if not isinstance(object, Person): main.insert(db_fixture, object) after_count = (person.select().count(), dependent.select().count(), application.select().count()) for counts in zip(before_count, after_count): assert counts[0] == counts[1] - 1
def send_random_bot(bot, update): from components.explore import send_bot_details random_bot = (Bot.select().where( (Bot.approved == True, Bot.disabled == False), (Bot.description.is_null(False)), ).order_by(fn.Random()).limit(1)[0]) send_bot_details(bot, update, random_bot)
async def random_(self, ctx): """Показать случайную цитату""" quote = Quote.select().order_by(fn.Random()).get() if not quote: return await ctx.send(f"В базе цитат пусто") message = f'Автор: **{self.bot.get_user(quote.author_id).name}**\n' \ f' - *"{quote.text}"*' await ctx.send(message)
def get_next_movie(imdb_id=None): if imdb_id: movie = Movie.select().where(Movie.imdb_id == imdb_id).first() return movie movie = Movie.select() \ .where((Movie.last_upload.is_null()) & (Movie.opensubtittle_id.is_null(False))) \ .order_by(fn.Random()) \ .first() if movie: return movie movie = Movie.select() \ .where(Movie.opensubtittle_id.is_null(False)) \ .order_by(Movie.last_upload.asc()) \ .order_by(fn.Random()) \ .first() return movie
def gen_schol_base(self, q_type): q_row = (QuestionTable.select().where( QuestionTable.question_type == q_type).order_by( fn.Random()).limit(1))[0] while q_row.prev_b: q_row = (QuestionTable.select().where( QuestionTable.qid == q_row.prev_b))[0] return q_row
def handler_get_random_quote(update, context): chat = update.effective_chat if Quote.select().where(Quote.chat_id == chat.id).count(): selected_quote = Quote.select().where( Quote.chat_id == chat.id).order_by(fn.Random()).limit(1)[0] chat.bot.forward_message(chat_id=chat.id, from_chat_id=-355145151, message_id=selected_quote.stored_message_id) return update.message.reply_text('Please add at least one quote first.')
def tick(): slack = Slacker(SLACK_TOKEN) randomSortValue = randint(0,100) tick_message = TickMessage.select() \ .where(TickMessage.frequency >= randomSortValue) \ .order_by(fn.Random()) \ .limit(1).get() slack.chat.post_message(target_channel, tick_message.message, as_user=True)
def get_random_content(kinds=None, limit=1, **kwargs): """ Convenience function for returning random content nodes for use in testing :param kinds: A list of node kinds to select from. :param limit: The maximum number of items to return. :return: A list of randomly selected content dictionaries. """ if not kinds: kinds = ["Video", "Audio", "Exercise", "Document"] return Item.select().where(Item.kind.in_(kinds)).order_by( fn.Random()).limit(limit)
def getApplication() -> Response: application_data = ('first_name', 'venmo_username', 'employer', 'employment_information') try: application: Application = Application.select().order_by( fn.Random()).limit(1).get() return jsonify(projection(model_to_dict(application), application_data)) except (DoesNotExist) as ex: logger.warning('getApplication error', exc_info=True) return 'Application does not exist.', 404
async def get_random_quote(author: discord.Member, guild: discord.Guild) -> QuoteEntity: query = QuoteModel.select().order_by(fn.Random()) if author is not None: query = query.filter(QuoteModel.author_id == author.id) if guild is not None: query = query.filter(QuoteModel.guild_id == guild.id) quote: QuoteModel = query.get() return QuoteEntity(quote.id, quote.content, quote.author, quote.timestamp)