def increase_bar(day, item_id) -> Bar: logger.debug("显示增量表") # 创建Session 数据库相关操作 # engine = create_engine('sqlite:///96345.db', echo=True) # Session = sessionmaker(bind=engine) # session = Session() session = db.get_db_session(db_path) # 取得所有当前类目数据库数据 元祖类型 降序 result = tools.get_item_merchants_timelaspes_increase( session, item_id, tools.get_today(), tools.get_assign_year_date(day)) c = (Bar(init_opts=opts.InitOpts(theme=ThemeType.ROMANTIC)).add_xaxis( result.get('name')).add_yaxis( "新增单数", result.get('increment')).reversal_axis().set_global_opts( datazoom_opts=[ opts.DataZoomOpts(range_start=60, range_end=100, orient="vertical"), opts.DataZoomOpts(type_="inside", orient="vertical") ], tooltip_opts=[ opts.TooltipOpts(trigger='axis', axis_pointer_type='shadow') ]).set_series_opts( label_opts=opts.LabelOpts(is_show=True), markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_="max", name="最大值"), ]), )) session.close() return c
def get_chat_current_season_no(chat_id): """ :type chat_id: int :rtype: int """ return DB.get_chat_current_season_no(get_db_session(), chat_id=chat_id)
def eat_winner(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ current_user = update.callback_query.from_user data = json.loads(update.callback_query.data) session = get_db_session() event_id = data['e'] event = DB.get_event(session, event_id=event_id) if event and not event.completed and current_user.username == event.created_by: target_id = data['t'] update_dict = json.loads(event.description) update_dict['winner'] = target_id DB.update_event(session, event_id, {'description': json.dumps(update_dict)}) # Send Loser Select Keyboard message = update.callback_query.message send_player_select_keyboard( bot=bot, game_id=event.game_id, event_id=event.id, action=String.ACTION_WRAP_TOUCH_SELECT_LOSER, chat_id=message.chat_id, text=String.WRAP_TOUCH_ASK_TARGET, exclude_id=update_dict['winner'], reply_to_message_id=event.message_id, message=message)
def eat_target(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ current_user = update.callback_query.from_user data = json.loads(update.callback_query.data) session = get_db_session() event_id = data['e'] event = DB.get_event(session, event_id=event_id) if event and not event.completed and current_user.username == event.created_by: target_id = data['t'] update_dict = json.loads(event.description) update_dict['loser'] = target_id DB.update_event(session, event_id, {'description': json.dumps(update_dict)}) # Send Price Select Keyboard message = update.callback_query.message send_fan_select_keyboard(bot=bot, game_id=event.game_id, event_id=event_id, action=String.ACTION_WRAP_TOUCH_SELECT_FAN, chat_id=message.chat_id, text=String.WRAP_TOUCH_ASK_PRICE, message=message)
def delete_set(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ current_user = update.callback_query.from_user data = json.loads(update.callback_query.data) session = get_db_session() event_id = data['e'] event = DB.get_event(session, event_id=event_id) if event and not event.completed and current_user.username == event.created_by: set_no = data['t'] update_dict = json.loads(event.description) update_dict['set_no'] = int(set_no) DB.update_event(session, event_id, {'description': json.dumps(update_dict)}) # Send Set Select Keyboard message = update.callback_query.message send_wind_select_keyboard(bot, chat_id=message.chat_id, text=String.DELETE_ASK_ROUND, event_id=event_id, action=String.ACTION_DELETE_ASK_ROUND, message=message)
def history_list(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ data = json.loads(update.callback_query.data) game_before_id = data.get('before', None) game_after_id = data.get('after', None) message = update.callback_query.message games = DB.get_games(get_db_session(), chat_id=message.chat_id, status=GameStatus.ENDED, size=10, game_before_id=game_before_id, game_after_id=game_after_id, options=[ joinedload(Game.player_1), joinedload(Game.player_2), joinedload(Game.player_3), joinedload(Game.player_4) ]) send_game_select_keyboard(bot, chat_id=message.chat_id, text=String.HISTORY_ASK_GAME, action=String.ACTION_HISTORY_SELECT_GAME, games=games)
def delete_round(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ current_user = update.callback_query.from_user data = json.loads(update.callback_query.data) session = get_db_session() event_id = data['e'] event = DB.get_event(session, event_id=event_id) if event and not event.completed and current_user.username == event.created_by: round_no = data['t'] update_dict = json.loads(event.description) # Update Game Status DB.update_game(session, game_id=event.game_id, update_dict={ 'set_no': update_dict['set_no'], 'round_no': round_no }) # Delete Events DB.delete_event(session, event_id=update_dict['event_id']) DB.delete_event(session, event_id=event_id) # Update Message message = update.callback_query.message bot.editMessageText(timeout=5, text=String.DELETE_CONFIRM, chat_id=message.chat_id, message_id=message.message_id)
def get_recommend_route(longitude, latitude, user_info, travel_mode, poi_num): db_session = db.get_db_session() poi_scores = [] route = [] for index in range(poi_num): # 一轮景点限制为 行程2h/景点数目 if travel_mode == 'walking': poi_records = db_session.query(db.POIInfo).filter( db.POIInfo.poi_longitude <= longitude + 0.01 * 8 / poi_num, db.POIInfo.poi_latitude <= latitude + 0.013 * 8 / poi_num, db.POIInfo.poi_longitude >= longitude - 0.01 * 8 / poi_num, db.POIInfo.poi_latitude >= latitude - 0.013 * 8 / poi_num, ).all() elif travel_mode == 'riding': poi_records = db_session.query(db.POIInfo).filter( db.POIInfo.poi_longitude <= longitude + 0.04 * 8 / poi_num, db.POIInfo.poi_latitude <= latitude + 0.052 * 8 / poi_num, db.POIInfo.poi_longitude >= longitude - 0.04 * 8 / poi_num, db.POIInfo.poi_latitude >= latitude - 0.052 * 8 / poi_num, ).all() else: # driving poi_records = db_session.query(db.POIInfo).filter( db.POIInfo.poi_longitude <= longitude + 0.16 * 8 / poi_num, db.POIInfo.poi_latitude <= latitude + 0.208 * 8 / poi_num, db.POIInfo.poi_longitude >= longitude - 0.16 * 8 / poi_num, db.POIInfo.poi_latitude >= latitude - 0.208 * 8 / poi_num, ).all() for poi in poi_records: poi_scores.append(calculate_poi_score(user_info, poi)) best_poi = poi_records[poi_scores.index(max(poi_scores))] route.append(str(best_poi.poi_longitude) + ',' + str(best_poi.poi_latitude)) longitude, latitude = best_poi.poi_longitude, best_poi.poi_latitude return route
def eat_2_fan_1(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ current_user = update.callback_query.from_user data = json.loads(update.callback_query.data) session = get_db_session() event_id = data['e'] event = DB.get_event(session, event_id=event_id) if event and not event.completed and current_user.username == event.created_by: fan = data['f'] amount = PRICE_LIST.get(event.game.price).get(int(fan)) update_dict = json.loads(event.description) update_dict['fan_1'] = int(fan) update_dict['amount_1'] = amount DB.update_event(session, event_id, {'description': json.dumps(update_dict)}) send_player_select_keyboard( bot=bot, game_id=event.game_id, event_id=event.id, action=String.ACTION_2_EAT_SELECT_WIN_2, chat_id=update.callback_query.message.chat_id, text=String.EAT_2_ASK_WINNER_2, exclude_id=update_dict['winner_1'], message=update.callback_query.message)
def eat_2_target(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ current_user = update.callback_query.from_user data = json.loads(update.callback_query.data) session = get_db_session() event_id = data['e'] event = DB.get_event(session, event_id=event_id) if event and not event.completed and current_user.username == event.created_by: target_id = data['t'] update_dict = json.loads(event.description) update_dict['loser'] = target_id DB.update_event(session, event_id, { 'description': json.dumps(update_dict), 'completed': 1 }) # Create Transaction DB.create_transaction(session, event_id, from_id=update_dict['loser'], to_id=update_dict['winner_1'], fan_no=update_dict['fan_1'], amount=update_dict['amount_1']) DB.create_transaction(session, event_id, from_id=update_dict['loser'], to_id=update_dict['winner_2'], fan_no=update_dict['fan_2'], amount=update_dict['amount_2']) # Send Message to Group win_player_1 = DB.get_player(session, update_dict['winner_1']) win_player_2 = DB.get_player(session, update_dict['winner_2']) target_player = DB.get_player(session, update_dict['loser']) text = random.choice(String.EAT_2_MESSAGES).format( loser_first=target_player.first_name, loser_last=target_player.last_name, winner_1_first=win_player_1.first_name, winner_1_last=win_player_1.last_name, winner_2_first=win_player_2.first_name, winner_2_last=win_player_2.last_name, fan_1=update_dict['fan_1'], fan_2=update_dict['fan_2']) message = update.callback_query.message bot.editMessageText(timeout=5, text=text, chat_id=message.chat_id, message_id=message.message_id) # Advance Game advance_game_status( bot, game_id=event.game_id, winner=[update_dict['winner_1'], update_dict['winner_2']])
def ask_price_callback(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ current_user = update.callback_query.from_user data = json.loads(update.callback_query.data) session = get_db_session() event_id = data['e'] event = DB.get_event(session, event_id=event_id) if event and not event.completed and current_user.username == event.created_by: price = data['p'] DB.update_game(session, game_id=event.game_id, update_dict={ 'price': price, 'status': GameStatus.WAITING_FOR_PLAYER }) bot.editMessageText( timeout=5, text=String.__dict__.get('PRICE_' + price), chat_id=update.callback_query.message.chat_id, message_id=update.callback_query.message.message_id) with codecs.open('templates/wait_for_players.html', 'r', 'utf-8') as f: html = f.read().format(String.__dict__.get('PRICE_' + price), String.START_GAME_SELECT_SEAT) send_seat_select_keyboard(bot, game_id=event.game_id, text=html, parse_mode='HTML')
def _3eat(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ user = update.message.from_user session = get_db_session() game = DB.get_player_current_game(session, user, status=GameStatus.STARTED) if game: event = DB.create_event(session, game_id=game.id, message_id=update.message.message_id, type=EventType.EAT_3, created_by=user.username) send_player_select_keyboard(bot=bot, game_id=game.id, event_id=event.id, action=String.ACTION_3_SELECT_TARGET, chat_id=game.chat_id, reply_to_message_id=event.message_id, text=String.EAT_3_ASK_TARGET)
def build(self): if setup_db(): print("Database created!") main_window = MainWindow() main_window.db = get_db_session() return main_window
def get_update_time(): session = db.get_db_session(db_path) res = db.query_all_item(session) time = res[7].updateTime ret_time = str(time.month) + '-' + str(time.day) + ' ' + str( time.hour) + ':' + str(time.minute) dict1 = {'updateTime': ret_time} session.close() return json.dumps(dict1)
def tag_article(article_id): logger.info("Tagging %s..." % str(article_id)) s = db.get_db_session() try: _tag_article_inner(s, article_id) s.commit() except: s.rollback() raise
def main(): db_path = 'sqlite:///96345.db?check_same_thread=False' param = {"code": "server_content"} base_url = "http://www.sx96345.com" header = "/centre/life_service/" # url后面跟着的一点 session = db.get_db_session(db_path, True) # 查询所有服务类目 # every_day_update_feedback(param, base_url, header, session, 0) every_day_update_feedback(param, base_url, header, session, 1)
def end(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ user = update.message.from_user message = update.message chat = message.chat if chat.type == Chat.PRIVATE: bot.sendMessage(update.message.chat_id, String.ERROR_PRIVATE_CHAT, timeout=5) else: session = get_db_session() game = DB.get_player_current_game(session, user, status=GameStatus.STARTED) if game: event = DB.create_event(session, game_id=game.id, message_id=update.message.message_id, type=EventType.END, created_by=user.username) btn_text = String.END_GAME_MESSAGE callback_data = json.dumps({ 'a': String.ACTION_END_GAME_CONFIRM, 'e': event.id }) inline_keyboard_buttons = [[ InlineKeyboardButton(text=btn_text, callback_data=callback_data) ], [ InlineKeyboardButton( text=String.CANCEL, callback_data=json.dumps({ 'a': String.ACTION_EVENT_CANCEL, 'e': int(event.id) })) ]] bot.sendMessage( chat_id=game.chat_id, text=String.END_GAME_CONFIRM, reply_to_message_id=message.message_id, reply_markup=InlineKeyboardMarkup(inline_keyboard_buttons), timeout=5)
def eat_fan(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ current_user = update.callback_query.from_user data = json.loads(update.callback_query.data) session = get_db_session() event_id = data['e'] event = DB.get_event(session, event_id=event_id) if event and not event.completed and current_user.username == event.created_by: fan = data['f'] amount = PRICE_LIST.get(event.game.price).get(int(fan)) * 1.5 update_dict = json.loads(event.description) update_dict['fan'] = int(fan) update_dict['amount'] = int(amount * 1.5) DB.update_event(session, event_id, { 'description': json.dumps(update_dict), 'completed': 1 }) # Create Transaction DB.create_transaction(session, event_id=event_id, from_id=update_dict['loser'], to_id=update_dict['winner'], fan_no=update_dict['fan'], amount=amount, self_touch=1) # Send Message to Group from_player = DB.get_player(session, update_dict['loser']) to_player = DB.get_player(session, update_dict['winner']) text = random.choice(String.WRAP_TOUCH_MESSAGES).format( winner_first=to_player.first_name, winner_last=to_player.last_name, loser_first=from_player.first_name, loser_last=from_player.last_name, fan=fan, amount=amount) message = update.callback_query.message bot.editMessageText(timeout=5, text=text, chat_id=message.chat_id, message_id=message.message_id) # Advance Game advance_game_status(bot, game_id=event.game_id, winner=update_dict['winner'])
def get_all(cls, db=None): "Return all settings as a dict" if not db: db = get_db_session() ret = {} for rec in db.query(cls): ret[rec.key] = rec.value return ret
def build_stats(): db_session = db.get_db_session() try: stats = {} num_news = db_session.query(func.count(NewsItem.id)).scalar() stats["total_news"] = num_news # News by source news_by_source = db_session.query(NewsItem.source, func.count(NewsItem.id)).group_by( NewsItem.source).all() stats["total_by_source"] = {} for item in news_by_source: stats["total_by_source"][item[0]] = item[1] midnight_today = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) news_by_source_today = db_session.query( NewsItem.source, func.count(NewsItem.id)).filter( NewsItem.published > midnight_today).group_by( NewsItem.source).all() stats["total_by_source_today"] = {} for item in news_by_source_today: stats["total_by_source_today"][item[0]] = item[1] news_today = db_session.query(func.count( NewsItem.id)).filter(NewsItem.published > midnight_today).scalar() stats["news_today"] = news_today # Get stats for last month this_month = datetime.utcnow() - timedelta(30) years = extract('year', NewsItem.published).label("years") months = extract('month', NewsItem.published).label('months') days = extract('day', NewsItem.published).label('days') news_by_day = db_session.query(years, months, days, func.count(NewsItem.id)) \ .filter(NewsItem.published > this_month) \ .group_by(years, months, days)\ .order_by(years, months, days) stats["news_by_day"] = {} for years, month, day, count in news_by_day: stats["news_by_day"]["%04d-%02d-%02d" % (years, month, day)] = count except Exception as e: logger.error("Failed to get stats.", exc_info=True) db_session.rollback() raise finally: db_session.close() return stats
def get(cls, key, default_val=None, db=None): "Get a key's value from DB or if not found return provided default value" if not db: db = get_db_session() rec = db.query(cls).filter_by(key=key).first() if rec: return rec.value else: return default_val
def set(cls, key, val, db=None): "Set a key's value" if not db: db = get_db_session() rec = db.query(cls).filter_by(key=key).first() if rec: rec.value = val else: rec = cls(key=key, value=val) db.add(rec)
def main(): # 爬取网址 category = "1" # 不同的服务对应不同的类目 68=开锁换锁 db_path = 'sqlite:///96345.db' param = {"code": "server_content"} base_url = "http://www.sx96345.com" header = "/centre/life_service/" # url后面跟着的一点 session = db.get_db_session(db_path, True) all_service_info = get_all_pages_service_info(base_url, header, param, category) all_service_info_detail = get_personal_service_data(all_service_info)
def start(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ # Register User user = update.message.from_user DB.try_register_player(get_db_session(), user) # Display Help Message with codecs.open('templates/help.html', 'r', 'utf-8') as f: html = f.read() bot.sendMessage(update.message.chat_id, html, parse_mode='HTML', timeout=5)
def end_game_confirm(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ current_user = update.callback_query.from_user data = json.loads(update.callback_query.data) session = get_db_session() event_id = data['e'] event = DB.get_event(session, event_id=event_id) if not event.completed and get_player_seat_no( current_user.username, event.game) != 0 and current_user.username != event.created_by: end_game(bot, event.game_id, message=update.callback_query.message)
def cancel(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ data = json.loads(update.callback_query.data) event_id = data.get('event_id', None) if event_id: DB.delete_event(get_db_session(), event_id) message = update.callback_query.message bot.editMessageText(timeout=5, text=String.CANCEL_CONFIRM, chat_id=message.chat_id, message_id=message.message_id)
def get_player_ranks(season_no=None, chat_id=None): session = get_db_session() query = session.query(Game) if season_no: query = query.filter(Game.season_no == season_no) if chat_id: query = query.filter(Game.chat_id == chat_id) games = query.options(joinedload(Game.events).joinedload(Event.transactions)).all() balance_map = {} for game in games: for event in game.events: for transaction in event.transactions: if transaction.from_player_id not in balance_map: balance_map[transaction.from_player_id] = 0 balance_map[transaction.from_player_id] -= transaction.amount if transaction.to_player_id not in balance_map: balance_map[transaction.to_player_id] = 0 balance_map[transaction.to_player_id] += transaction.amount # losings = session.query(func.sum(Transaction.amount), Transaction.from_player_id).group_by( # Transaction.from_player_id).all() # winnings = session.query(func.sum(Transaction.amount), Transaction.to_player_id).group_by( # Transaction.to_player_id).all() # # # for amount, user_id in losings: # if user_id not in balance_map: # balance_map[user_id] = 0 # balance_map[user_id] -= int(amount) # # for amount, user_id in winnings: # if user_id not in balance_map: # balance_map[user_id] = 0 # balance_map[user_id] += int(amount) return sorted( [{'user_id': user_id, 'amount': amount, 'player': DB.get_player(session, username=user_id)} for user_id, amount in balance_map.iteritems()], key=lambda record: record['amount'], reverse=True)
def item_bar(item_id) -> Bar: logger.debug("显示总表") # 创建Session 数据库相关操作 # engine = create_engine('sqlite:///96345.db', echo=True) # Session = sessionmaker(bind=engine) # session = Session() session = db.get_db_session(db_path) # 取得所有当前类目数据库数据 元祖类型 降序 result = db.query_date_feedback_info(session, item_id, tools.get_today()) res = tools.change_2_pyechart_format(result) t = ( Bar(init_opts=opts.InitOpts(theme=ThemeType.WHITE)).add_xaxis( res.get('name')).add_yaxis( "批评", res.get('cri'), stack="stack1", itemstyle_opts=opts.ItemStyleOpts(color='red')).add_yaxis( "满意", res.get('sat'), stack="stack1", itemstyle_opts=opts.ItemStyleOpts( color='#29b394')).add_yaxis( "表扬", res.get('pri'), stack="stack1", itemstyle_opts=opts.ItemStyleOpts( color='#fed861')).set_series_opts( label_opts=opts.LabelOpts( is_show=False), ).set_global_opts( title_opts=opts.TitleOpts( title="当前概况"), xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts( rotate=-15)), datazoom_opts=[ opts.DataZoomOpts( range_start=0, range_end=50), # 设置起始结束范围 opts.DataZoomOpts( type_="inside") ] # 增加内缩放 )) session.close() return t
def export_to_solr(): logging.basicConfig() solr_int = solr.Solr(settings.SOLR_ENDPOINT_URLS, settings.SOLR_DEFAULT_ENDPOINT) solr_int.deleteAll() # Now iterate over news docs = [] count = 0 total = db.get_db_session().query(func.count(db.news.NewsItem.id)).scalar() for news_item in db.news.get_news(): doc = { u"id": news_item.id, u"title": news_item.title, u"source": news_item.source, u"language": u"si", u"source_url": news_item.source_url, u"content": news_item.content, u"published": to_solr_date(news_item.published.replace(tzinfo=pytz.utc)) } if news_item.author is not None: doc[u"author"] = news_item.author docs.append(doc) if len(docs) > 200: solr_int.add(docs) count += len(docs) docs = [] print "%s/%s" % (count, total) print "%s/%s" % (count, total) print "Commiting..." solr_int.commit() print "Running solr defrag..." solr_int.optimize() print "Dispached " + str(count) + " documents to solr. "
def tag_news(retag=False): db_session = db.get_db_session() # Why is this necessary?! try: db_session.query(db.tags.Tag).limit(1).one() except NoResultFound: pass if retag: news_items = db_session.query(db.news.NewsItem.id) else: # Get newsitems without tags news_items = db_session.query(db.news.NewsItem.id).filter(~db.news.NewsItem.tags.any()) for item in news_items: queue = Queue('ner_tag', connection=tasks.redis) queue.enqueue("tasks.tag_article.tag_article", item)
def start_game(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ data = json.loads(update.callback_query.data) session = get_db_session() game = DB.get_game(session, data['g']) if game: if get_game_player_no(game) == 4: update_dict = { 'status': GameStatus.STARTED, 'set_no': 1, 'round_no': 1 } DB.update_game(session, game.id, update_dict) with codecs.open('templates/game_start.html', 'r', 'utf-8') as f: html = f.read() bot.editMessageText( timeout=5, text=html, chat_id=game.chat_id, message_id=update.callback_query.message.message_id, parse_mode='HTML', reply_markup=None) else: extra_msg = String.ERROR_NOT_ENOUGH_PLAYER with codecs.open('templates/wait_for_players.html', 'r', 'utf-8') as f: html = f.read().format( String.__dict__.get('PRICE_' + game.price), extra_msg) send_seat_select_keyboard(bot, game_id=game.id, text=html, parse_mode='HTML', message=update.callback_query.message)
def handle_home(): global user_accounts user_info = {} user_name = request.args.get('user_name') if user_name not in user_accounts: return redirect(url_for('handle_index')) else: user_info['user_name'] = user_name user_info['poi_visited_num'] = request.args.get('poi_visited_num') user_info['distance_sense'] = request.args.get('distance_sense'), user_info['beauty_like'] = request.args.get('beauty_like'), user_info['leisure_like'] = request.args.get('leisure_like'), user_info['romance_like'] = request.args.get('romance_like'), user_info['excitement_like'] = request.args.get('excitement_like'), user_info['humanity_like'] = request.args.get('humanity_like'), user_info['type0_like'] = request.args.get('type0_like'), user_info['type1_like'] = request.args.get('type1_like'), user_info['type2_like'] = request.args.get('type2_like'), user_info['type3_like'] = request.args.get('type3_like'), user_info['type4_like'] = request.args.get('type4_like'), db_session = db.get_db_session() records = db_session.query(db.POIInfo).all() db_session.close() pois = [] for poi in records: pois.append( { "name": poi.poi_name, "url": poi.poi_url, "image": poi.poi_image, "comment": poi.poi_comment, "time": poi.poi_time, "longitude": poi.poi_longitude, "latitude": poi.poi_latitude, "beauty": poi.poi_beauty, "leisure": poi.poi_leisure, "romance": poi.poi_romance, "excitement": poi.poi_excitement, "humanity": poi.poi_humanity } ) return render_template('home.html', user_info=user_info, pois=json.dumps(pois))
def cancel_game(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ current_user = update.callback_query.from_user data = json.loads(update.callback_query.data) session = get_db_session() game_id = data['g'] game = DB.get_game(session, game_id=game_id) if game and game.status == GameStatus.WAITING_FOR_PLAYER and get_player_seat_no( current_user, game): DB.delete_game(session, game_id=game_id) bot.editMessageText( text=String.CANCEL_GAME_MESSAGE, chat_id=update.callback_query.message.chat_id, message_id=update.callback_query.message.message_id)
def purge_duplicates(do_commit): s = db.get_db_session() doubled_urls = s.query(NewsItem.source_url, func.count(NewsItem.source_url))\ .group_by(NewsItem.source_url)\ .having(func.count(NewsItem.source_url) > 1) counter = 0 for url, count in doubled_urls: news_items = s.query(NewsItem).filter_by( source_url=url).order_by(-func.length(NewsItem.id)).all() for item in news_items[1:]: counter += 1 print "Should delete", item.id if do_commit: s.delete(item) print "Commiting deletion for total of", counter, "items." s.commit()
def history(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ message = update.message games = DB.get_games(get_db_session(), chat_id=message.chat_id, options=[ joinedload(Game.player_1), joinedload(Game.player_2), joinedload(Game.player_3), joinedload(Game.player_4) ]) send_game_select_keyboard(bot, chat_id=message.chat_id, text=String.HISTORY_ASK_GAME, action=String.ACTION_HISTORY_SELECT_GAME, games=games)
def delete(bot, update): """ :type bot: telegram.bot.Bot :type update: telegram.update.Update """ user = update.message.from_user message = update.message chat = message.chat if chat.type == Chat.PRIVATE: bot.sendMessage(update.message.chat_id, String.ERROR_PRIVATE_CHAT, timeout=5) else: session = get_db_session() game = DB.get_player_current_game(session, user, status=GameStatus.STARTED) if game: event = DB.create_event(session, game_id=game.id, message_id=update.message.message_id, type=EventType.DELETE, created_by=user.username) target_events = DB.get_events(session, game_id=game.id) send_event_select_keyboard( bot, chat_id=message.chat_id, text=String.DELETE_ASK_EVENT, event_id=event.id, action=String.ACTION_DELETE_SELECT_EVENT, events=target_events) else: with open('assets/eatshit.jpg', 'rb') as f: update.message.reply_photo( photo=f, caption=String.ERROR_NO_GAME_EAT.encode('utf8'))
def handle_login(): data = request.json user_name = data.get('user_name') password = data.get('password') db_session = db.get_db_session() user_record = db_session.query(db.POIUser).filter(db.POIUser.user_name == user_name).first() if not user_record: data = { 'success': False, 'msg': 'no user with name %s' % user_name } return make_response(json.dumps(data), 200) elif user_record.password != password: data = { 'success': False, 'msg': 'wrong password! ' } return make_response(json.dumps(data), 200) data = { 'success': True, 'msg': 'ok', 'poi_visited_num': user_record.poi_visited_num, 'distance_sense': user_record.distance_sense, 'beauty_like': user_record.beauty_like, 'leisure_like': user_record.leisure_like, 'romance_like': user_record.romance_like, 'excitement_like': user_record.excitement_like, 'humanity_like': user_record.humanity_like, 'type0_like': user_record.type0_like, 'type1_like': user_record.type1_like, 'type2_like': user_record.type2_like, 'type3_like': user_record.type3_like, 'type4_like': user_record.type4_like, } user_accounts[user_name] = { 'name': user_name } return make_response(json.dumps(data), 200)
# from kivy.properties import ListProperty, ObjectProperty from kivy.uix.screenmanager import ScreenManager, Screen from kivy.clock import mainthread from datetime import datetime, date, timedelta import calendar import plyer #from android_notify import AndroidNotification from models import Deed, Setting from db import get_db_session, setup_db import sync DB = get_db_session() class MainScreen(Screen): "Main screen of the app" _db = None @property def db(self): if not self._db: self._db = App.get_running_app().root.db return self._db def do_action(self, action): "Called for good or bad button presses"
for score in scores: if not score: continue record = score[0].split(' ') poi_dicts[record[0]] = { record[1].split(':')[0]: float(record[1].split(':')[1]), record[2].split(':')[0]: float(record[2].split(':')[1]), record[3].split(':')[0]: float(record[3].split(':')[1]), record[4].split(':')[0]: float(record[4].split(':')[1]), record[5].split(':')[0]: float(record[5].split(':')[1]) } with open('poi_scores.json', 'w') as poi_scores_file: json.dump(poi_dicts, poi_scores_file, ensure_ascii=False) ''' new_poi_scores = copy.copy(poi_scores) keys = new_poi_scores.keys() db_session = db.get_db_session() records = db_session.query(db.POIInfo).all() for record in records: for key in keys: if get_equal_rate(record.poi_name.encode('utf-8'), key) >= 0.75: record.poi_beauty = new_poi_scores[key]['美丽'] record.poi_leisure = new_poi_scores[key]['休闲'] record.poi_romance = new_poi_scores[key]['浪漫'] record.poi_excitement = new_poi_scores[key]['刺激'] record.poi_humanity = new_poi_scores[key]['人文'] print '[succeed] for record:', record.poi_name.encode('utf-8') db_session.commit() db_session.close()