def join(self, model_, limit_, offset_, sort_=None, order_=None, on=None, fields_: list = None, where_: list = None): """ Сджойнить и отдать много """ if sort_: if order_ == 'DESC': order = desc(sort_) else: order = asc(sort_) else: order = asc(self.id) if fields_: _select_ = select(fields_) else: _select_ = select([self, model_]).apply_labels() if where_: if len(where_) == 1: _select_ = _select_.where(where_[0]) else: _select_ = _select_.where(and_(*where_)) return _select_.select_from(self.__table__.join( model_, on)).order_by(order).limit(limit_).offset(offset_)
def execute(self, request, user, page="1", sort="score"): page = int(page) offset = (page - 1)*50 order = {"score" : (asc(Alliance.score_rank),), "size" : (asc(Alliance.size_rank),), "avg_score" : (asc(Alliance.score_avg_rank),), "avg_size" : (asc(Alliance.size_avg_rank),), "members" : (asc(Alliance.members_rank),), "score_growth" : (desc(Alliance.score_growth),), "size_growth" : (desc(Alliance.size_growth),), "avg_score_growth" : (desc(Alliance.score_avg_growth),), "avg_size_growth" : (desc(Alliance.size_avg_growth),), "score_growth_pc" : (desc(Alliance.score_growth_pc),), "size_growth_pc" : (desc(Alliance.size_growth_pc),), "avg_score_growth_pc" : (desc(Alliance.score_avg_growth_pc),), "avg_size_growth_pc" : (desc(Alliance.size_avg_growth_pc),), } if sort not in order.keys(): sort = "score" order = order.get(sort) Q = session.query(Alliance) Q = Q.filter(Alliance.active == True) count = Q.count() pages = count/50 + int(count%50 > 0) pages = range(1, 1+pages) for o in order: Q = Q.order_by(o) Q = Q.limit(50).offset(offset) return render("alliances.tpl", request, alliances=Q.all(), offset=offset, pages=pages, page=page, sort=sort)
def execute(self, request, user, page="1", sort="score"): page = int(page) offset = (page - 1) * 50 order = { "score": (asc(Galaxy.score_rank),), "value": (asc(Galaxy.value_rank),), "size": (asc(Galaxy.size_rank),), "xp": (asc(Galaxy.xp_rank),), } if sort not in order.keys(): sort = "score" order = order.get(sort) tick = Updates.midnight_tick() Q = session.query(Galaxy, GalaxyHistory) Q = Q.outerjoin((GalaxyHistory, and_(Galaxy.id == GalaxyHistory.id, GalaxyHistory.tick == tick))) Q = Q.filter(Galaxy.active == True) count = Q.count() pages = count / 50 + int(count % 50 > 0) pages = range(1, 1 + pages) for o in order: Q = Q.order_by(o) Q = Q.limit(50).offset(offset) return render("galaxies.tpl", request, galaxies=Q.all(), offset=offset, pages=pages, page=page, sort=sort)
def execute(self, request, user, page="1", sort="score"): page = int(page) offset = (page - 1)*50 order = {"score" : (asc(Alliance.score_rank),), "size" : (asc(Alliance.size_rank),), "avg_score" : (asc(Alliance.score_avg_rank),), "avg_size" : (asc(Alliance.size_avg_rank),), "members" : (asc(Alliance.members_rank),), } if sort not in order.keys(): sort = "score" order = order.get(sort) tick = Updates.midnight_tick() Q = session.query(Alliance, AllianceHistory) Q = Q.outerjoin((AllianceHistory, and_(Alliance.id == AllianceHistory.id, AllianceHistory.tick == tick))) Q = Q.filter(Alliance.active == True) count = Q.count() pages = count/50 + int(count%50 > 0) pages = range(1, 1+pages) for o in order: Q = Q.order_by(o) Q = Q.limit(50).offset(offset) return render("alliances.tpl", request, alliances=Q.all(), offset=offset, pages=pages, page=page, sort=sort)
def execute(self, request, user, sort=None): levels = [] + User.levels order = { "name": (asc(User.name), ), "sponsor": (asc(User.sponsor), ), "access": (desc(User.access), ), "planet": ( asc(Planet.x), asc(Planet.y), asc(Planet.z), ), } if sort not in order.keys(): sort = "name" order = order.get(sort) members = [] Q = session.query( User.name, User.alias, User.sponsor, User.access, Planet, User.phone, User.pubphone, User.id.in_( session.query(PhoneFriend.user_id).filter_by(friend=user))) Q = Q.outerjoin(User.planet) Q = Q.filter(User.active == True) Q = Q.filter(User.access < levels[-1][1]) for o in order: Q = Q.order_by(o) return render("galmates.tpl", request, members=Q.all())
def execute(self, request, user): planet, galaxy = (user.planet, user.planet.galaxy,) if user.planet else (Planet(), Galaxy(),) planets = session.query(Planet).filter(Planet.active == True) galaxies = session.query(Galaxy).filter(Galaxy.active == True) alliances = session.query(Alliance).filter(Alliance.active == True) dup = lambda l,o,c=True: l+[o] if o in session and c and o not in l else l return render("index.tpl", request, topplanets = dup(planets.order_by(asc(Planet.score_rank))[:20], planet), roidingplanets = dup(planets.filter(Planet.size_growth > 0).order_by(desc(Planet.size_growth))[:5], planet, planet.size_growth > 0), roidedplanets = dup(planets.filter(Planet.size_growth < 0).order_by(asc(Planet.size_growth))[:5], planet, planet.size_growth < 0), xpplanets = dup(planets.filter(Planet.xp_growth > 0).order_by(desc(Planet.xp_growth))[:5], planet, planet.xp_growth > 0), bashedplanets = dup(planets.filter(Planet.value_growth < 0).order_by(asc(Planet.value_growth))[:5], planet, planet.value_growth < 0), topgalaxies = dup(galaxies.order_by(asc(Galaxy.score_rank))[:10], galaxy), roidinggalaxies = dup(galaxies.filter(Galaxy.size_growth > 0).order_by(desc(Galaxy.size_growth))[:5], galaxy, galaxy.size_growth > 0), roidedgalaxies = dup(galaxies.filter(Galaxy.size_growth < 0).order_by(asc(Galaxy.size_growth))[:5], galaxy, galaxy.size_growth < 0), xpgalaxies = dup(galaxies.filter(Galaxy.xp_growth > 0).order_by(desc(Galaxy.xp_growth))[:5], galaxy, galaxy.xp_growth > 0), bashedgalaxies = dup(galaxies.filter(Galaxy.value_growth < 0).order_by(asc(Galaxy.value_growth))[:5], galaxy, galaxy.value_growth < 0), topalliances = alliances.order_by(asc(Alliance.score_rank))[:8], )
def execute(self, request, user, message=None): tick = Updates.current_tick() Q = session.query(Attack) if user.access < ( Config.getint("Access", "hc") if "hc" in Config.options("Access") else 1000 ): # Hide attacks until they are active, unless the user has access Q = Q.filter( Attack.landtick <= tick + Config.getint("Misc", "attactive")) Q = Q.filter( Attack.landtick + Attack.waves >= tick) # Hide attacks one tick after the last wave has landed Q = Q.order_by(asc(Attack.id)) attacks = Q.all() Q = session.query(Planet, Target.tick) Q = Q.join(Target.planet) Q = Q.join(Target.user) Q = Q.filter(Planet.active == True) Q = Q.filter(Target.user == user) Q = Q.filter( Target.tick >= tick - 12) # We shouldn't need any bookings 12 ticks after landing Q = Q.order_by(asc(Target.tick), asc(Planet.x), asc(Planet.y), asc(Planet.z)) bookings = [] scans = [] for planet, tock in Q.all(): bookings.append(( planet, tock, [], )) if planet.scan("P"): bookings[-1][2].append(planet.scan("P")) scans.append(planet.scan("P")) if planet.scan("D"): bookings[-1][2].append(planet.scan("D")) scans.append(planet.scan("D")) if planet.scan("A") or planet.scan("U"): bookings[-1][2].append(planet.scan("A") or planet.scan("U")) scans.append(planet.scan("A") or planet.scan("U")) if tock <= tick + Config.getint("Misc", "attjgp") and planet.scan( "J"): bookings[-1][2].append(planet.scan("J")) scans.append(planet.scan("J")) return render("attacks.tpl", request, message=message, attacks=attacks, bookings=bookings, scans=scans)
def list_airdrop_with_stat(db: Session, page: int, sort: int, count: int, user_id: int): q = db.query(models.Airdrop) airdrop_count = db.query(models.Airdrop).count() sortDict = { 1: desc(models.Airdrop.id), 2: asc(models.Airdrop.id), 3: desc(models.Airdrop.name), 4: asc(models.Airdrop.name) } if sort > 4: sort = 1 q = q.order_by(sortDict[sort]) q = q.limit(count).offset((page - 1) * count).all() resp = [] # Javascriptを想定して "2008-05-01T02:00:00+09:00" という型にする requested_date = datetime.datetime.now() for airdrop in q: data = { "id": airdrop.id, "name": airdrop.name, "description": airdrop.description, "amount": airdrop.amount, "interval": airdrop.interval, "receivable": True, "next_receivable": requested_date.strftime('%Y-%m-%dT%H:%M:%S+09:00') } last_transaction = db.query(models.Transaction).order_by( desc(models.Transaction.id)).filter( models.Transaction.provider_type == 1, models.Transaction.provider == airdrop.id, models.Transaction.receiver_type == 0, models.Transaction.receiver == user_id).first() if last_transaction: # 次に受け取れる日時 receivable_date = last_transaction.reception # 要求日時 # 経過した分数を見る if airdrop.mode == 0: receivable_date += datetime.timedelta(minutes=airdrop.interval) # 経過した日数を見る else: receivable_date += datetime.timedelta(days=airdrop.interval) receivable_date = receivable_date.replace(hour=0, minute=0, second=0, microsecond=0) # 要求した時刻が 受け取りできる時刻以下ならエラー if receivable_date > requested_date: data["receivable"] = False data["next_receivable"] = receivable_date.strftime( '%Y-%m-%dT%H:%M:%S+09:00') resp.append(data) return resp, airdrop_count
def execute(self, message, user, params): alliance = Alliance(name="Unknown") if params.group(1).lower() == "unknown" else Alliance.load(params.group(1)) if alliance is None: message.reply("No alliance matching '%s' found"%(params.group(1),)) return tick = Updates.current_tick() when = int(params.group(2) or 0) if when and when < 32: when += tick elif when and when <= tick: message.alert("Can not check status on the past. You wanted tick %s, but current tick is %s." % (when, tick,)) return Q = session.query(Planet, User.name, Target.tick) Q = Q.join(Target.planet) Q = Q.join(Planet.intel) if alliance.id else Q.outerjoin(Planet.intel) Q = Q.join(Target.user) Q = Q.filter(Planet.active == True) Q = Q.filter(Intel.alliance == (alliance if alliance.id else None)) Q = Q.filter(Target.tick == when) if when else Q.filter(Target.tick > tick) Q = Q.order_by(asc(Planet.x)) Q = Q.order_by(asc(Planet.y)) Q = Q.order_by(asc(Planet.z)) result = Q.all() if len(result) < 1: reply="No active bookings matching alliance %s" %(alliance.name) if when: reply+=" for tick %s."%(when,) message.reply(reply) return reply="Target information for %s"%(alliance.name) reply+=" landing on tick %s (eta %s): "%(when,when-tick) if when else ": " ticks={} for planet, user, land in result: if not ticks.has_key(land): ticks[land]=[] ticks[land].append((planet, user,)) sorted_keys=ticks.keys() sorted_keys.sort() replies = [] for land in sorted_keys: prev=[] for planet, user in ticks[land]: prev.append("(%s:%s:%s %s)" % (planet.x,planet.y,planet.z,user)) replies.append("Tick %s (eta %s) "%(land,land-tick) +", ".join(prev)) replies[0] = reply + replies[0] message.reply("\n".join(replies))
def list_airdrop(db: Session, page: int, sort: int, count: int): q = db.query(models.Airdrop) airdrop_count = db.query(models.Airdrop).count() sortDict = { 1: desc(models.Airdrop.id), 2: asc(models.Airdrop.id), 3: desc(models.Airdrop.name), 4: asc(models.Airdrop.name) } if sort > 4: sort = 1 q = q.order_by(sortDict[sort]) q = q.limit(count).offset((page - 1) * count).all() return q, airdrop_count
def list_machine(db: Session, page: int, sort: int, count: int): q = db.query(models.Machine) machine_count = db.query(models.Product).count() sortDict = { 1: desc(models.Machine.id), 2: asc(models.Machine.id), 3: desc(models.Machine.name), 4: asc(models.Machine.name) } if sort > 4: sort = 1 q = q.order_by(sortDict[sort]) q = q.limit(count).offset((page - 1) * count).all() return q, machine_count
def execute(self, request, user, message=None): tick = Updates.current_tick() Q = session.query(Attack) Q = Q.filter( Attack.landtick >= tick - Config.getint("Misc", "attactive")) Q = Q.order_by(asc(Attack.id)) attacks = Q.all() Q = session.query(Planet, Target.tick) Q = Q.join(Target.planet) Q = Q.join(Target.user) Q = Q.filter(Planet.active == True) Q = Q.filter(Target.user == user) Q = Q.filter(Target.tick >= tick - Config.getint("Misc", "attactive")) Q = Q.order_by(asc(Target.tick), asc(Planet.x), asc(Planet.y), asc(Planet.z)) bookings = [] scans = [] for planet, tock in Q.all(): bookings.append(( planet, tock, [], )) if planet.scan("P"): bookings[-1][2].append(planet.scan("P")) scans.append(planet.scan("P")) if planet.scan("D"): bookings[-1][2].append(planet.scan("D")) scans.append(planet.scan("D")) if planet.scan("A") or planet.scan("U"): bookings[-1][2].append(planet.scan("A") or planet.scan("U")) scans.append(planet.scan("A") or planet.scan("U")) if tock <= tick + Config.getint("Misc", "attjgp") and planet.scan( "J"): bookings[-1][2].append(planet.scan("J")) scans.append(planet.scan("J")) return render("attacks.tpl", request, message=message, attacks=attacks, bookings=bookings, scans=scans)
def execute(self, request, user, tick): Q = session.query(Planet, Scan) Q = Q.join(Scan.planet) Q = Q.filter(Scan.tick == tick) Q = Q.order_by(asc(Planet.x), asc(Planet.y), asc(Planet.z), asc(Scan.scantype), asc(Scan.tick)) result = Q.all() group = [] for planet, scan in result: if len(group) < 1 or group[-1][0] is not planet: group.append((planet, [scan],)) else: group[-1][1].append(scan) return render("scans/tick.tpl", request, tick=tick, group=group)
def execute(self, request, user, sort=None): levels = [] + User.levels if "galmate" in Config.options("Access"): levels.append(("Galaxy", Config.getint("Access","galmate"),)) else: levels.append(("Galaxy", 0,)) if sort is not None: levels = [("All", 0,),] order = {"name" : (asc(Channel.name),), "userlevel" : (desc(Channel.userlevel),), "maxlevel" : (desc(Channel.maxlevel),), } if sort not in order.keys(): sort = "name" order = order.get(sort) channels = [] for level in levels: Q = session.query(Channel.name, Channel.userlevel, Channel.maxlevel) Q = Q.filter(Channel.userlevel >= level[1]) Q = Q.filter(Channel.userlevel < levels[levels.index(level)-1][1]) if levels.index(level) > 0 else Q for o in order: Q = Q.order_by(o) channels.append((level[0], Q.all(),)) return render("channels.tpl", request, accesslist=channels)
def getRSAModuli(self, off=0, lim=0, order='desc', maxSize=0, distinct=False): """ query RSA Public Keys' moduli between cursors """ s = (select([self.pkTable.c.modulus]), select([self.pkTable.c.modulus ]).distinct(self.pkTable.c.modulus))[distinct] try: s = s.where(self.pkTable.c.type == 'RSA') if maxSize > 0: s = s.where( and_(self.pkTable.c.type == 'RSA', self.pkTable.c.modulus_size < maxSize / 8)) s = (s.order_by(desc(self.pkTable.c.modulus)), s.order_by(asc(self.pkTable.c.modulus)))[order == 'asc'] s = s.offset(off) if lim > 0: s = s.limit(lim) rows = self.conn.execute(s) l = [] for r in rows: l.append(r['modulus']) result = [ZZ(i) for i in l] rows.close() except (Exception) as error: print(error) return result
def test_get_list_sort_saved_query(self): """ Saved Query API: Test get list and sort saved query """ all_queries = (db.session.query(SavedQuery).order_by( asc(SavedQuery.schema)).all()) self.login(username="******") query_string = {"order_column": "schema", "order_direction": "asc"} uri = f"api/v1/saved_query/?q={prison.dumps(query_string)}" rv = self.get_assert_metric(uri, "get_list") assert rv.status_code == 200 data = json.loads(rv.data.decode("utf-8")) assert data["count"] == len(all_queries) for i, query in enumerate(all_queries): assert query.schema == data["result"][i]["schema"] query_string = { "order_column": "database.database_name", "order_direction": "asc", } uri = f"api/v1/saved_query/?q={prison.dumps(query_string)}" rv = self.get_assert_metric(uri, "get_list") assert rv.status_code == 200 query_string = { "order_column": "user.first_name", "order_direction": "asc" } uri = f"api/v1/saved_query/?q={prison.dumps(query_string)}" rv = self.get_assert_metric(uri, "get_list") assert rv.status_code == 200
def list(self, message, user, params): Q = session.query(func.count().label("count"), func.max(Request.id).label("max_id")) Q = Q.filter(Request.tick > Updates.current_tick() - 5) Q = Q.filter(Request.active == True) Q = Q.group_by(Request.planet_id, Request.scantype) Q = Q.order_by(asc("max_id")) SQ = Q.subquery() Q = session.query(Request, SQ.c.count).join((SQ, and_(Request.id == SQ.c.max_id))) if Q.count() < 1: message.reply("There are no open scan requests") return message.reply( " ".join( map( lambda (request, count): Config.get("Misc", "reqlist").decode("string_escape") % ( request.id, request.target.intel.dists if request.target.intel else "0", "/%s" % request.dists if request.dists > 0 else "", request.scantype, request.target.x, request.target.y, request.target.z, ), Q.all(), ) ) )
def execute(self, request, user, message=None, planet=None): tick = Updates.current_tick() Q = session.query(Request) Q = Q.filter(Request.user == user) Q = Q.filter(Request.tick > tick - 5) Q = Q.filter(Request.active == True) Q = Q.order_by(asc(Request.id)) open = Q.all() Q = session.query(Scan) Q = Q.join(Request.scan) Q = Q.filter(Request.user == user) Q = Q.filter(Request.tick > tick - 24) Q = Q.filter(Request.scan != None) Q = Q.order_by(desc(Request.id)) completed = Q.all() Q = session.query(Scan) Q = Q.filter(Scan.scanner == user) Q = Q.order_by(desc(Scan.id)) scans = Q[:25] return render("scans/scans.tpl", request, anonscans=Config.getboolean("Misc", "anonscans"), types=Request._requestable, open=open, completed=completed, scans=scans, message=message, planet=planet)
def user_state_request(workspace_id, user, mode, last_evt_id): ulist = [] # Get current user id (in pubws mode, it might not be defined yet.. just send WS creator in that case). cur_user_id = -1; if user: cur_user_id = user['id'] # Get members. last_user_evt_id = 0 for u in User.query.filter(User.workspace_id == workspace_id).order_by(asc(User.id)): # Send all users, except for pubws mode, where we just send only # the workspace creator and the current user (if defined). if mode == kwmolib.MODE_WS or \ ( mode == kwmolib.MODE_PUBWS and \ ( u.id in [0, 1, cur_user_id] ) ): ulist.append(u.to_dict()) # Scan ALL the users fetched to get the latest event ID, no matter if in skurl mode or not. last_user_evt_id = u.evt_id log.debug("user_state_request(): Users list has %i entries." % ( len(ulist) ) ) return max(last_evt_id, last_user_evt_id), ulist
def sort_and_filter_public_analyses_by_column(self,column, order, filter_variable): """Sorts the public analyses by the column name and applies a filter on the model variable value selected Params: column: The name of the column to sort on order: either "asc" or "desc" filter_variable: the model_variable value used to filter the analyses """ with self.readonly_scope() as session: query = session.query(Analysis) \ .options(subqueryload(Analysis.point_dataset)) \ .options(subqueryload(Analysis.coverage_datasets)) \ .options(subqueryload(Analysis.run_by_user)) \ .filter(Analysis.viewable_by == None, Analysis.deleted != True) if filter_variable: query = query.filter(Analysis.model_variable == filter_variable) if order == "asc": return query.order_by(asc(column)).all() elif order == "desc": return query.order_by(desc(column)).all() else: return query.all()
def chat_state_request(workspace_id, channel_id, last_evt_id): data = {} if last_evt_id == 0: # Send all messages. log.debug("Chat messages request: sending all messages.") data["mode"] = "all" messages = ChatMessage.query.filter(and_(ChatMessage.workspace_id == workspace_id, ChatMessage.channel_id == channel_id)).order_by(asc(ChatMessage.date)) else: # Sending an update only. log.debug("Chat messages request: sending newest messages.") data["mode"] = "update" messages = ChatMessage.query.filter(and_(ChatMessage.workspace_id == workspace_id, ChatMessage.channel_id == channel_id, ChatMessage.evt_id > last_evt_id)) l = [] for message in messages: d = message.to_dict() d['msg'] = cgi.escape(d['msg']) l.append(d) last_evt_id = max(last_evt_id, d['evt_id']) data['messages'] = l #log.debug("Chat messages request: data='%s'" % ( str(data) ) ) log.debug("Chat messages request: data has %s messages." % ( str(len(data["messages"])) ) ) return last_evt_id, data
def chat_state_request(workspace_id, channel_id, last_evt_id): data = {} if last_evt_id == 0: # Send all messages. log.debug("Chat messages request: sending all messages.") data["mode"] = "all" messages = ChatMessage.query.filter( and_(ChatMessage.workspace_id == workspace_id, ChatMessage.channel_id == channel_id)).order_by( asc(ChatMessage.date)) else: # Sending an update only. log.debug("Chat messages request: sending newest messages.") data["mode"] = "update" messages = ChatMessage.query.filter( and_(ChatMessage.workspace_id == workspace_id, ChatMessage.channel_id == channel_id, ChatMessage.evt_id > last_evt_id)) l = [] for message in messages: d = message.to_dict() d['msg'] = cgi.escape(d['msg']) l.append(d) last_evt_id = max(last_evt_id, d['evt_id']) data['messages'] = l #log.debug("Chat messages request: data='%s'" % ( str(data) ) ) log.debug("Chat messages request: data has %s messages." % (str(len(data["messages"])))) return last_evt_id, data
def user_state_request(workspace_id, user, mode, last_evt_id): ulist = [] # Get current user id (in pubws mode, it might not be defined yet.. just send WS creator in that case). cur_user_id = -1 if user: cur_user_id = user['id'] # Get members. last_user_evt_id = 0 for u in User.query.filter(User.workspace_id == workspace_id).order_by( asc(User.id)): # Send all users, except for pubws mode, where we just send only # the workspace creator and the current user (if defined). if mode == kwmolib.MODE_WS or \ ( mode == kwmolib.MODE_PUBWS and \ ( u.id in [0, 1, cur_user_id] ) ): ulist.append(u.to_dict()) # Scan ALL the users fetched to get the latest event ID, no matter if in skurl mode or not. last_user_evt_id = u.evt_id log.debug("user_state_request(): Users list has %i entries." % (len(ulist))) return max(last_evt_id, last_user_evt_id), ulist
def execute(self, request, user): Q = session.query(User, Planet, epenis) Q = Q.join(User.planet) Q = Q.join(User.epenis) Q = Q.order_by(asc(epenis.rank)) return render("equeens.tpl", request, queens=Q.all())
def get_total_distances_by_user_in_last_days(self, user_id: int, days: int): """ Returns the total distance taken by a specified user in last days. :param user_id: ID of user. :param days: Number of days for which the total distances are returned. :returns: The total distances for each day as dictionary. """ last_day = dt.date.today() first_day = last_day - dt.timedelta(days=days - 1) query_result = db.session.query(func.date(Activity.datetime).label('day'), func.sum(Activity.distance).label('distance')). \ filter(Activity.user_id == user_id, func.date(Activity.datetime) >= first_day, func.date(Activity.datetime) <= last_day, func.date(Activity.datetime) >= self.SEASON.start_date, func.date(Activity.datetime) <= self.SEASON.end_date). \ group_by('day'). \ order_by(asc('day')). \ all() result = {} for i in range(7): result[(first_day + dt.timedelta(days=i)).isoformat()] = 0 for item in query_result: result[item.day] = item.distance return result
def links(self, message, user, params): Q = session.query(Request) Q = Q.filter(Request.tick > Updates.current_tick() - 5) Q = Q.filter(Request.active == True) Q = Q.order_by(asc(Request.id)) message.reply(" ".join(map(lambda request: "[%s: %s]" % (request.id, request.link,), Q[:5])))
def list(self, message, user, params): Q = session.query(Request) Q = Q.filter(Request.tick > Updates.current_tick() - 5) Q = Q.filter(Request.active == True) Q = Q.order_by(asc(Request.id)) message.reply(" ".join(map(lambda request: "[%s: %s %s:%s:%s]" % (request.id, request.scantype, request.target.x, request.target.y, request.target.z,), Q.all())))
def execute(self, message, user, params): alliance = Alliance.load(params.group(1)) if alliance is None: message.reply("No alliance matching '%s' found"%(params.group(1),)) return Q = session.query(sum(Planet.value), sum(Planet.score), sum(Planet.size), sum(Planet.xp), count(), Planet.race) Q = Q.join(Planet.intel) Q = Q.filter(Planet.active == True) Q = Q.filter(Intel.alliance==alliance) Q = Q.group_by(Intel.alliance_id, Planet.race) Q = Q.order_by(asc(Planet.race)) result = Q.all() if len(result) < 1: message.reply("No planets in intel match alliance %s"%(alliance.name,)) return prev=[] for value, score, size, xp, members, race in result: reply="%s %s Val(%s)" % (members,race,self.num2short(value/members),) reply+=" Score(%s)" % (self.num2short(score/members),) reply+=" Size(%s) XP(%s)" % (size/members,self.num2short(xp/members),) prev.append(reply) reply="Demographics for %s: "%(alliance.name,)+ ' | '.join(prev) message.reply(reply)
def get_categories(cls, template_id): hierarchy = [] categories = [] for category in cls.query.filter_by(template_id=template_id).order_by( asc(cls.created_at)).all(): category_type = category.category_type api_json = category.to_api_json() if category_type == 'Category': # A 'Category' can have both courses and subcategories. A 'Subcategory' can have courses. api_json['courseRequirements'] = [] api_json['subcategories'] = [] elif category_type == 'Subcategory': api_json['courseRequirements'] = [] categories.append(api_json) categories_by_id = dict( (category['id'], category) for category in categories) for category in categories: parent_category_id = category['parentCategoryId'] if parent_category_id: parent = categories_by_id[parent_category_id] key = 'subcategories' if category[ 'categoryType'] == 'Subcategory' else 'courseRequirements' parent[key].append(category) else: hierarchy.append(category) return hierarchy
def get(self, limit_, offset_, sort_=None, order_=None, where_: list = None): """ Отдать много """ if not sort_: sort_ = self.id if order_ == 'DESC': order = desc(sort_) else: order = asc(sort_) _select_ = select([self]) if where_: if len(where_) == 1: _select_ = _select_.where(where_[0]) else: _select_ = _select_.where(and_(*where_)) return _select_.order_by(order).limit(limit_).offset(offset_)
def list_product(db: Session, page: int, sort: int, count: int): q = db.query(models.Product) product_count = db.query(models.Product).count() sortDict = { 1: desc(models.Product.id), 2: asc(models.Product.id), 3: desc(models.Product.name), 4: asc(models.Product.name), 5: desc(models.Product.price), 6: asc(models.Product.price) } if sort > 6: sort = 1 q = q.order_by(sortDict[sort]) q = q.limit(count).offset((page - 1) * count).all() return q, product_count
def execute(self, message, user, params): reply = "" tick = Updates.current_tick() opts = params.group(1).split() for o in reversed(Config.options("Access")): if ("galmates" not in opts) and (Config.getint("Access", o) == 0): continue Q = session.query(User) Q = Q.filter(User.access == Config.getint("Access", o)) Q = Q.order_by(asc(User.name)) result = Q.all() if len(result) < 1: continue printable = map( lambda (u): "%s%s%s%s%s" % (u.name, ' (' + u.alias + ')' if u.alias else '', " (%d:%d:%d)" % (u.planet.x, u.planet.y, u.planet.z) if "coords" in opts and u.planet is not None else '', " (%s)" % ((u.fleetupdated or 0) - tick) if "defage" in opts else '', " (%s)" % (u.fleetupdated or 0) if "mydef" in opts else ''), result) reply += "%s: " % (o) reply += ', '.join(printable) reply += '\n' message.reply(reply[:-1])
def properties(self, name): connection = self._client.connect() rval = {} for interval,config in self._intervals.items(): rval.setdefault(interval, {}) stmt = select([self._table.c.i_time]).where( and_( self._table.c.name==name, self._table.c.interval==interval ) ).order_by( asc(self._table.c.i_time) ).limit(1) rval[interval]['first'] = config['i_calc'].from_bucket( connection.execute(stmt).first()['i_time'] ) stmt = select([self._table.c.i_time]).where( and_( self._table.c.name==name, self._table.c.interval==interval ) ).order_by( desc(self._table.c.i_time) ).limit(1) rval[interval]['last'] = config['i_calc'].from_bucket( connection.execute(stmt).first()['i_time'] ) return rval
def _get_remoteci_configuration(last_rconfiguration_id): """Get a remoteci configuration. This will iterate over each configuration in a round robin manner depending on the last rconfiguration used by the remoteci.""" _RCONFIGURATIONS = models.REMOTECIS_RCONFIGURATIONS _J_RCONFIGURATIONS = models.JOIN_REMOTECIS_RCONFIGURATIONS query = sql.select([_RCONFIGURATIONS]). \ select_from(_J_RCONFIGURATIONS. join(_RCONFIGURATIONS)). \ where(_J_RCONFIGURATIONS.c.remoteci_id == remoteci['id']) query = query.where(sql.and_(_RCONFIGURATIONS.c.state != 'archived', _RCONFIGURATIONS.c.topic_id == topic_id)) query = query.order_by(sql.desc(_RCONFIGURATIONS.c.created_at)) query = query.order_by(sql.asc(_RCONFIGURATIONS.c.name)) all_rconfigurations = flask.g.db_conn.execute(query).fetchall() if len(all_rconfigurations) > 0: for i in range(len(all_rconfigurations)): if str(all_rconfigurations[i]['id']) == last_rconfiguration_id: # if i==0, then indice -1 is the last element return all_rconfigurations[i - 1] return all_rconfigurations[0] else: return None
def get_product_out_info(allrecs=False, productcode='', subproductcode='', version='undefined'): db = connectdb.ConnectDB().db try: if allrecs: product_out_info = db.product.order_by(asc( db.product.productcode)).all() else: where = and_(db.product.productcode == productcode, db.product.subproductcode == subproductcode, db.product.version == version) product_out_info = db.product.filter(where).all() return product_out_info except: exceptiontype, exceptionvalue, exceptiontraceback = sys.exc_info() # Exit the script and print an error telling what happened. logger.error( "get_product_out_info: Database query error!\n -> {}".format( exceptionvalue)) #raise Exception("get_product_out_info: Database query error!\n ->%s" % exceptionvalue) finally: if db.session: db.session.close() db = None
def list_user(db: Session, page: int, sort: int, count: int): q = db.query(models.User) user_count = db.query(models.User).count() sortDict = { 1: desc(models.User.id), 2: asc(models.User.id), 3: desc(models.User.name), 4: asc(models.User.name), 5: desc(models.User.money), 6: asc(models.User.money) } if sort > 6: sort = 1 q = q.order_by(sortDict[sort]) q = q.limit(count).offset((page - 1) * count).all() return q, user_count
def execute(self, request, user, message=None): tick = Updates.current_tick() Q = session.query(Request) Q = Q.filter(Request.user == user) Q = Q.filter(Request.tick > tick - 5) Q = Q.filter(Request.active == True) Q = Q.order_by(asc(Request.id)) mine = Q.all() Q = session.query(Request) Q = Q.filter(Request.tick > tick - 5) Q = Q.filter(Request.active == True) Q = Q.order_by(asc(Request.id)) everyone = Q.all() return render("scans/requests.tpl", request, types=Request._requestable, mine=mine, everyone=everyone, message=message)
def _build_order_by(query, table, orders): ''' selectのorder_by句のクエリを作成 ''' for order in orders: if order[0] == 'asc': query = query.order_by(asc(table.columns[order[1]])) elif order[0] == 'desc': query = query.order_by(desc(table.columns[order[1]])) return query
def get_forms_user_can_access(self, user, paginator=None): query = _filter_restricted_models_from_query( 'Form', self.dbsession.query(old_models.Form), user).order_by(asc(old_models.Form.id)) if paginator: start, end = _get_start_and_end_from_paginator(paginator) return query.slice(start, end).all() return query.all()
def transactionsInDateRange(start, end): session = requireSession() query = session \ .query(M.transactionListMapper) \ .filter((M.transactionListMapper.c.date >= start) & (M.transactionListMapper.c.date < end)) \ .order_by(asc(M.transactionListMapper.c.date)) return list(query)
class Testrun(DeclarativeBase): __tablename__ = 'testruns' id = Column(Integer, primary_key=True) date = Column(DateTime, nullable=False, default=datetime.now) output_data = deferred(Column(Unicode(10 * 1024 * 1024)), group='data', doc='''Output data from testrun Captured from stdout or content of test output file, depending on the test specification ''') error_data = deferred(Column(Unicode(10 * 1024 * 1024)), group='data', doc='Error data from testrun (stderr)') runtime = Column(Float) result = Column(Boolean, nullable=False, default=False) partial = Column(Boolean, nullable=False, default=False) test_id = Column(Integer, ForeignKey('tests.id'), nullable=False, index=True) test = relationship('Test', backref=backref('testruns', order_by=id, cascade='all, delete-orphan'), doc='Test that was run in this testrun') submission_id = Column(Integer, ForeignKey('submissions.id'), nullable=False, index=True) submission = relationship('Submission', backref=backref('testruns', order_by=id, cascade='all,delete-orphan'), doc='Submission that was run in this testrun') __mapper_args__ = {'order_by': asc(date)} __table_args__ = (Index('idx_test_submission', test_id, submission_id), ) def __repr__(self): return (u'<Testrun: id=%r, test_id=%r, submission_id=%r>' % (self.id, self.test_id, self.submission_id)).encode('utf-8') def __unicode__(self): return u'Testrun %s for Submission %d' % (self.id or '', self.submission.id or '') @property def parent(self): '''Parent entity for generic hierarchy traversal''' return self.test
def execute(self, request, user, sort=None): levels = [] + User.levels if sort is not None: levels = [("All member", levels[-1][1],),] order = {"name" : (asc(User.name),), "sponsor" : (asc(User.sponsor),), "access" : (desc(User.access),desc(User.carebears),asc(User.name),), "carebears" : (desc(User.carebears),), "planet" : (asc(Planet.x),asc(Planet.y),asc(Planet.z),), "defage" : (asc(User.fleetupdated),), } if sort not in order.keys(): sort = "name" order = order.get(sort) members = [] for level in levels: Q = session.query(User.name, User.alias, User.sponsor, User.access, User.carebears, Planet, User.fleetupdated, User.phone, User.pubphone, User._smsmode, or_(User.id == user.id, User.id.in_(session.query(PhoneFriend.user_id).filter_by(friend=user)))) Q = Q.outerjoin(User.planet) Q = Q.filter(User.active == True) Q = Q.filter(User.access >= level[1]) Q = Q.filter(User.access < levels[levels.index(level)-1][1]) if levels.index(level) > 0 else Q for o in order: Q = Q.order_by(o) members.append((level[0], Q.all(),)) return render("members.tpl", request, accesslist=members)
def _get_order_by(self, request): """ Return an SA order_by """ attr = request.params.get('sort', request.params.get('order_by')) if attr is None or not hasattr(self.mapped_class, attr): return None if request.params.get('dir', '').upper() == 'DESC': return desc(getattr(self.mapped_class, attr)) else: return asc(getattr(self.mapped_class, attr))
def execute(self, request, user, message=None): tick = Updates.current_tick() Q = session.query(Attack) Q = Q.filter(Attack.landtick >= tick - Attack._active_ticks) Q = Q.order_by(asc(Attack.id)) attacks = Q.all() Q = session.query(Planet, Target.tick) Q = Q.join(Target.planet) Q = Q.join(Target.user) Q = Q.filter(Planet.active == True) Q = Q.filter(Target.user == user) Q = Q.filter(Target.tick > tick) Q = Q.order_by(asc(Target.tick), asc(Planet.x), asc(Planet.y), asc(Planet.z)) bookings = Q.all() return render("attacks.tpl", request, message=message, attacks=attacks, bookings=bookings)
def list_transaction_as_admin(db: Session, page: int, sort: int, count: int): q = db.query(models.Transaction) transaction_count = q.count() sortDict = {1: desc(models.Transaction.id), 2: asc(models.Transaction.id)} if sort > 2: sort = 1 q = q.order_by(sortDict[sort]) q = q.limit(count).offset((page - 1) * count).all() return q, transaction_count
def allTransactionMonths(): session = requireSession() parts = "year", "month" query = session \ .query(*[cast(date_part(p, M.Transaction.date), INT) .label(p) for p in parts]) \ .order_by(*[asc(p) for p in parts]) \ .distinct() return list(query)
def get_forms(self, paginator=None, eagerload=False): form_query = self.dbsession.query(old_models.Form)\ .order_by(asc(old_models.Form.id)) if eagerload: form_query = eagerload_form(form_query) if paginator: start, end = _get_start_and_end_from_paginator(paginator) return form_query.slice(start, end).all() return form_query.all()
def execute(self, request, user, id): Q = session.query(Planet, Scan) Q = Q.join(Scan.planet) Q = Q.filter(Scan.group_id.ilike("%"+id+"%")) Q = Q.order_by(asc(Planet.x), asc(Planet.y), asc(Planet.z), asc(Scan.scantype), asc(Scan.tick)) result = Q.all() if len(result) == 0: return HttpResponseRedirect(reverse("scans")) group = [] scans = [] for planet, scan in result: if len(group) < 1 or group[-1][0] is not planet: group.append((planet, [scan],)) else: group[-1][1].append(scan) scans.append(scan) return render("scans/group.tpl", request, group=group, scans=scans)
def execute(self, request, user, page="1", sort="score"): page = int(page) offset = (page - 1) * 50 order = { "score": (asc(Galaxy.score_rank), ), "real_score": (asc(Galaxy.real_score_rank), ), "value": (asc(Galaxy.value_rank), ), "size": (asc(Galaxy.size_rank), ), "planets": (desc(Galaxy.members), ), "ratio": (desc(Galaxy.ratio), ), "xp": (asc(Galaxy.xp_rank), ), "score_growth": (desc(Galaxy.score_growth), ), "real_score_growth": (desc(Galaxy.real_score_growth), ), "value_growth": (desc(Galaxy.value_growth), ), "size_growth": (desc(Galaxy.size_growth), ), "xp_growth": (desc(Galaxy.xp_growth), ), "score_growth_pc": (desc(Galaxy.score_growth_pc), ), "real_score_growth_pc": (desc(Galaxy.real_score_growth_pc), ), "value_growth_pc": (desc(Galaxy.value_growth_pc), ), "size_growth_pc": (desc(Galaxy.size_growth_pc), ), "xp_growth_pc": (desc(Galaxy.xp_growth_pc), ), } if sort not in order.keys(): sort = "score" order = order.get(sort) Q = session.query(Galaxy) Q = Q.filter(Galaxy.active == True) count = Q.count() pages = count / 50 + int(count % 50 > 0) pages = range(1, 1 + pages) for o in order: Q = Q.order_by(o) Q = Q.limit(50).offset(offset) return render("galaxies.tpl", request, galaxies=Q.all(), offset=offset, pages=pages, page=page, sort=sort)
def index(self): """Get all application settings resources. :URL: ``GET /applicationsettings`` :returns: a list of all application settings resources. """ return h.eagerload_application_settings( Session.query(ApplicationSettings)).order_by( asc(ApplicationSettings.id)).all()
def execute(self, message, user, params): planet = Planet.load(*params.group(1,3,5)) if planet is None: message.alert("No planet with coords %s:%s:%s" % params.group(1,3,5)) return tick = Updates.current_tick() when = int(params.group(6) or 0) if 0 < when < 32: eta = when when += tick elif 0 < when <= tick: message.alert("Can not unbook targets in the past. You wanted tick %s, but current tick is %s." % (when, tick,)) return else: eta = when - tick if when > 32767: when = 32767 override = params.group(7) Q = session.query(Target) Q = Q.join(Target.user) Q = Q.filter(Target.planet == planet) Q = Q.filter(Target.user == user) if override is None else Q Q = Q.filter(Target.tick == when) if when else Q.filter(Target.tick >= tick) Q = Q.order_by(asc(Target.tick)) result = Q.all() for target in result: session.delete(target) count = len(result) session.commit() if count < 1: reply=("You have no " if override is None else "No ") +"bookings matching %s:%s:%s"%(planet.x,planet.y,planet.z,) if when: reply+=" for landing on tick %s"%(when,) reply+=". If you are trying to unbook someone else's target, you must confirm with 'yes'." if override is None else "" else: reply="You have unbooked %s:%s:%s"%(planet.x,planet.y,planet.z,) if when: reply+=" for landing pt %s"%(when,) if override: reply+=" (previously held by user %s)"%(result[0].user.name) else: reply+=" for %d booking(s)"%(count,) if override: prev=[] for target in result: prev.append("(%s user:%s)" % (target.tick,target.user.name)) reply+=": "+", ".join(prev) reply+="." message.reply(reply) return
def execute(self, request, user, x, y, h=False, hs=False, ticks=None): galaxy = Galaxy.load(x,y) if galaxy is None: return HttpResponseRedirect(reverse("galaxy_ranks")) ticks = int(ticks or 0) if (h or hs) else 12 if not (h or hs): Q = session.query(Planet, Intel.nick, Alliance.name) Q = Q.outerjoin(Planet.intel) Q = Q.outerjoin(Intel.alliance) Q = Q.filter(Planet.active == True) Q = Q.filter(Planet.galaxy == galaxy) Q = Q.order_by(asc(Planet.z)) planets = Q.all() exiles = galaxy.exiles[:10] else: planets, exiles = None, None if not hs: sizediffvalue = GalaxyHistory.rdiff * PA.getint("numbers", "roid_value") valuediffwsizevalue = GalaxyHistory.vdiff - sizediffvalue resvalue = valuediffwsizevalue * PA.getint("numbers", "res_value") shipvalue = valuediffwsizevalue * PA.getint("numbers", "ship_value") xpvalue = GalaxyHistory.xdiff * PA.getint("numbers", "xp_value") Q = session.query(GalaxyHistory, sizediffvalue, valuediffwsizevalue, resvalue, shipvalue, xpvalue, ) Q = Q.filter(GalaxyHistory.current == galaxy) Q = Q.order_by(desc(GalaxyHistory.tick)) history = Q[:ticks] if ticks else Q.all() else: history = None if not h: Q = session.query(GalaxyHistory) Q = Q.filter(or_(GalaxyHistory.hour == 23, GalaxyHistory.tick == Updates.current_tick())) Q = Q.filter(GalaxyHistory.current == galaxy) Q = Q.order_by(desc(GalaxyHistory.tick)) hsummary = Q.all() if hs else Q[:14] else: hsummary = None return render(["galaxy.tpl",["hgalaxy.tpl","hsgalaxy.tpl"][hs]][h or hs], request, galaxy = galaxy, planets = planets, exiles = exiles, history = history, hsummary = hsummary, ticks = ticks, )
def list(self, message, user, params): Q = session.query(Attack) Q = Q.filter(Attack.landtick >= Updates.current_tick() - Attack._active_ticks) Q = Q.order_by(asc(Attack.id)) replies = [] for attack in Q: replies.append("(%d LT: %d %s)" % (attack.id, attack.landtick, attack.comment)) reply = "Open attacks: " + " ".join(replies) message.reply(reply)
def actions_for(self, ref, sha1, db): _c = golem.db.commit _a = golem.db.action _f = golem.db.artefact cid = db.execute(_c.select('id').where(sql.and_(_c.c.ref==ref, _c.c.sha1==sha1))).fetchone()['id'] data = db.execute(_a.select().where(_a.c.commit==cid).order_by(sql.asc(_a.c.start_time))).fetchall() data = [{'name': x.name, 'status': x.status, 'start_time': x.start_time, 'end_time': x.end_time, 'host': x.host, 'duration': x.duration, 'config': self.actions[x.name].config, 'files':[{'filename': y.filename, 'sha1': y.sha1} for y in db.execute(_f.select().where(_f.c.action==x.id)).fetchall()]} for x in data if x.name in self.actions] return data
def links(self, message, user, params): Q = session.query(Request) Q = Q.filter(Request.tick > Updates.current_tick() - 5) Q = Q.filter(Request.active == True) Q = Q.order_by(asc(Request.id)) if Q.count() < 1: message.reply("There are no open scan requests") return message.reply(" ".join(map(lambda request: "[%s: %s]" % (request.id, request.link,), Q[:5])))
def execute(self, message, user, params): alliance = Alliance.load(params.group(1), active=False) if alliance is None: message.reply("No alliance matching '%s' found"%(params.group(1),)) return Q = session.query(Planet, Intel) Q = Q.join(Planet.intel) Q = Q.filter(Planet.active == True) Q = Q.filter(Intel.alliance==alliance) Q = Q.order_by(asc(Planet.x), asc(Planet.y), asc(Planet.z)) result = Q.all() if len(result) < 1: message.reply("No planets in intel match alliance %s"%(alliance.name,)) return printable=map(lambda (p, i): "%s:%s:%s" % (p.x,p.y,p.z),result) reply="Spam on alliance %s - " %(alliance.name) reply += ' | '.join(printable) message.reply(reply)