def get(self): template_values = {} active_track = self['track_id'] if active_track: template_values['active_track'] = active_track template_values['page_title_centered'] = get_page_title_centered_contents() template_values['tracks'] = [self._make_json(track) for track in Track.all().order('order')] template_values['is_member'] = True if 'member' in self.session else False template_values['track_donuts'] = {} if 'member' in self.session: email = self.session['member'] member = Member.get_by_email(email) template_values['member'] = member template_values['enrolled_tracks'] = {} for track in Tracks.get_tracks(): template_values['enrolled_tracks'][track.id] = EnrollProgram.is_enrolled_track(email, track.id) if member.role == MEMBER_ROLE[MANAGER]: template_values['is_manager'] = True else: for track in Tracks.get_tracks(): enrolled_programs_count = float(len(EnrollProgram.get_enrolled_programs(email, track.id))) programs_count = float(Program.all().ancestor(Track.get_by_key_name(track.id)).count()) score = round((enrolled_programs_count/programs_count)*100,2) engage_score = round(random()*score,0) engage_score = int(engage_score) if engage_score > 1 else 1 template_values['track_donuts'][track.id] = [Donut(100, 0.875, member.name, [DonutSegment(engage_score, '#1c758a'), DonutSegment(score, '#58c4dd')], 'transparent', '#ddd')] self.render_template(template_name='tracks.html', template_values=template_values)
def get_managed(value, arg): managed_users = ManagedUser.get_managed_users(value) donut_vals = [] if managed_users and len(managed_users) > 0: for managed_user in managed_users: args = arg.split(" ") if args[0] == "track": if EnrollProgram.is_enrolled_track(managed_user.user.email, args[1]): enrolled_programs_count = float(len(EnrollProgram.get_enrolled_programs(managed_user.user.email, args[1]))) programs_count = float(Program.all().ancestor(Track.get_by_key_name(args[1])).count()) score = round((enrolled_programs_count/programs_count)*100,2) engage_score = round(random()*score,0) engage_score = int(engage_score) if engage_score > 1 else 1 donut_vals.append((managed_user.user.name,[DonutSegment(engage_score, '#1c758a'), DonutSegment(score, '#58c4dd')])) elif args[0] == "program": if EnrollProgram.is_enrolled_program(managed_user.user.email, args[1], args[2]): track = Track.get_by_key_name(args[2]) program = Program.get_by_key_name(args[1], parent=track) modules = ProgramModule.all().ancestor(program).order('name') modules_count = modules.count()*1.0 completed_modules = [] for module in modules: if module.completed: completed_modules.append(module) completed_modules_count = len(completed_modules) score = (completed_modules_count/modules_count)*100.0 engage_score = round(score*random(),0) engage_score = int(engage_score) if engage_score > 1 else 1 donut_vals.append((managed_user.user.name,[DonutSegment(engage_score, '#1c758a'), DonutSegment(score, '#58c4dd')])) return DonutFactory.get_donuts(100, 0.875, donut_vals, 'transparent', '#ddd')
def _paste_one_track(self, nt, track): g = nt // 4 npn = self.phrase[g] pattern = self.session.get_pattern(npn) new_track = Track(pattern, track.write()) pattern.tracks[nt % 4] = new_track self.tracks[nt] = new_track self.track = track new_track.modified() # dump(new_track) logger.info(f'_paste_one_track to {nt} {new_track} {npn} {pattern}')
def get(self): track = Track.get_by_key_name(self['track_id']) program = Program.get_by_key_name(self['program_id'], parent=track) modules = ProgramModule.all().ancestor(program).order('name') template_values = {'program':program, 'track':track, 'modules':modules, 'listing_heading':program.name} template_values['is_member'] = True if 'member' in self.session else False if 'member' in self.session: email = self.session['member'] member = Member.get_by_email(email) template_values['member'] = member if member.role == MEMBER_ROLE[MANAGER]: template_values['is_manager'] = True else: modules_count = modules.count()*1.0 completed_modules = [] for module in modules: if module.completed: completed_modules.append(module) completed_modules_count = len(completed_modules) score = (completed_modules_count/modules_count)*100.0 engage_score = round(score*random(),0) engage_score = int(engage_score) if engage_score > 1 else 1 template_values['donuts'] = DonutFactory.get_donuts(100, 0.875, [('Engineer1', [DonutSegment(engage_score, '#1c758a'), DonutSegment(score, '#58c4dd')], '/assets/img/tracks/mobile_dev.png')], 'transparent', '#ddd') self.render_template(template_name='program_listing.html', template_values=template_values)
def get_track_dict(num, height=1000): tracks = {} for track_index in range(1, num + 1): tracks[track_index] = Track(width=0, height=height, position=(5 * (track_index - 1), 0)) return tracks
def test(): track_db = Track.query().filter('guys' == Track.artist).fetch() for track in track_db: logging.info(track.title) return 'ok'
def post(self): email = self.session['member'] track_id = self['track_id'] program_id = self['program_id'] program = Program.get_by_key_name(program_id, parent=Track.get_by_key_name(track_id)) EnrollProgram.create(Member.get_by_email(email), program) self.redirect("/tracks/program_listing?program_id=%s&track_id=%s"%(program_id, track_id))
def post(self): track_id = self['track'] program_id = self['program'] expert_email = self['expert'] program = Program.get_by_key_name(program_id, parent=Track.get_by_key_name(track_id)) program.expert = Expert.get_by_key_name(expert_email) program.put() self.redirect("/tracks/program_listing?program_id=%s&track_id=%s"%(program_id, track_id))
def test_accuracy(self): # test calc_accuracy return correct accuracy HEIGHT = 1000 UPDATE = 800 track = Track(0, HEIGHT, (0, 0)) add_update_circle(track, UPDATE) accuracy = calculate_accuracy(track, FRAME_RATE, VELOCITY) self.assertEqual(accuracy, (HEIGHT - UPDATE) / FRAME_RATE / VELOCITY)
def get_managed(value, arg): managed_users = ManagedUser.get_managed_users(value) donut_vals = [] if managed_users and len(managed_users) > 0: for managed_user in managed_users: args = arg.split(" ") if args[0] == "track": if EnrollProgram.is_enrolled_track(managed_user.user.email, args[1]): enrolled_programs_count = float( len( EnrollProgram.get_enrolled_programs( managed_user.user.email, args[1]))) programs_count = float(Program.all().ancestor( Track.get_by_key_name(args[1])).count()) score = round( (enrolled_programs_count / programs_count) * 100, 2) engage_score = round(random() * score, 0) engage_score = int(engage_score) if engage_score > 1 else 1 donut_vals.append((managed_user.user.name, [ DonutSegment(engage_score, '#1c758a'), DonutSegment(score, '#58c4dd') ])) elif args[0] == "program": if EnrollProgram.is_enrolled_program(managed_user.user.email, args[1], args[2]): track = Track.get_by_key_name(args[2]) program = Program.get_by_key_name(args[1], parent=track) modules = ProgramModule.all().ancestor(program).order( 'name') modules_count = modules.count() * 1.0 completed_modules = [] for module in modules: if module.completed: completed_modules.append(module) completed_modules_count = len(completed_modules) score = (completed_modules_count / modules_count) * 100.0 engage_score = round(score * random(), 0) engage_score = int(engage_score) if engage_score > 1 else 1 donut_vals.append((managed_user.user.name, [ DonutSegment(engage_score, '#1c758a'), DonutSegment(score, '#58c4dd') ])) return DonutFactory.get_donuts(100, 0.875, donut_vals, 'transparent', '#ddd')
def post(self): email = self.session['member'] track_id = self['track_id'] program_id = self['program_id'] program = Program.get_by_key_name( program_id, parent=Track.get_by_key_name(track_id)) EnrollProgram.create(Member.get_by_email(email), program) self.redirect("/tracks/program_listing?program_id=%s&track_id=%s" % (program_id, track_id))
def __init_tracks(self): """Initiate all tracks.""" self.tracks = {} # the keys of tracks match directly the mode for track_index in range(1, self.key_num + 1): self.tracks[track_index] = Track( self.track_width, self.track_height, (ceil(self.track_width * (track_index - 0.5)), -self.track_width))
def all_keys(): a_k = memcache.get('all_keys') if a_k is None: item_keys = Track.query().filter(Track.gdrive_id != '').fetch( keys_only=True, limit=10000) memcache.set('all_keys', item_keys, 60 * 60 * 3) return item_keys else: return a_k
def get(self): template_values = {} active_track = self['track_id'] if active_track: template_values['active_track'] = active_track template_values[ 'page_title_centered'] = get_page_title_centered_contents() template_values['tracks'] = [ self._make_json(track) for track in Track.all().order('order') ] template_values[ 'is_member'] = True if 'member' in self.session else False template_values['track_donuts'] = {} if 'member' in self.session: email = self.session['member'] member = Member.get_by_email(email) template_values['member'] = member template_values['enrolled_tracks'] = {} for track in Tracks.get_tracks(): template_values['enrolled_tracks'][ track.id] = EnrollProgram.is_enrolled_track( email, track.id) if member.role == MEMBER_ROLE[MANAGER]: template_values['is_manager'] = True else: for track in Tracks.get_tracks(): enrolled_programs_count = float( len( EnrollProgram.get_enrolled_programs( email, track.id))) programs_count = float(Program.all().ancestor( Track.get_by_key_name(track.id)).count()) score = round( (enrolled_programs_count / programs_count) * 100, 2) engage_score = round(random() * score, 0) engage_score = int(engage_score) if engage_score > 1 else 1 template_values['track_donuts'][track.id] = [ Donut(100, 0.875, member.name, [ DonutSegment(engage_score, '#1c758a'), DonutSegment(score, '#58c4dd') ], 'transparent', '#ddd') ] self.render_template(template_name='tracks.html', template_values=template_values)
def setup_modules(): for track in tracks: track_obj = Track.get_by_key_name(track.id) for program in track.programs: start_date = datetime.now() program_obj = Program.get_by_key_name(program.id, parent=track_obj) if program.modules: for module in program.modules: start_date = start_date + timedelta(days=3) ProgramModule(parent=program_obj, name=module.title, units=module.units, start_date=start_date).put()
def get_enrolled_programs(cls, email, track_id): track_programs = Program.all().ancestor( Track.get_by_key_name(track_id)) enrolled_programs = [] for program in track_programs: enrolled_program = EnrollProgram.get_by_key_name(email, parent=program) if enrolled_program: enrolled_programs.append(enrolled_program) return enrolled_programs
def post(self): track_id = self['track'] program_id = self['program'] expert_email = self['expert'] program = Program.get_by_key_name( program_id, parent=Track.get_by_key_name(track_id)) program.expert = Expert.get_by_key_name(expert_email) program.put() self.redirect("/tracks/program_listing?program_id=%s&track_id=%s" % (program_id, track_id))
def get_track_list_by_genre(genre): data = memcache.get('t_l_b_g' + genre) if data is not None: return data else: query = Track.query() if genre: query = query.filter(Track.genre == genre) track_list = query.fetch(limit=18) memcache.set('t_l_b_g' + genre, track_list, 60 * 60) return track_list
def get(self): redirect_url = self['redirect_url'] if self['redirect_url'] else '/experts' path = 'expert_registration.html' template_values = {} template_values['redirect_url'] = redirect_url template_values['is_member'] = True if 'member' in self.session else False if 'member' in self.session: template_values['member'] = Member.get_member_json(self.session['member']) template_values['form_url'] = blobstore.create_upload_url('/api/members/experts/create') template_values['tracks'] = Track.all().fetch(50) self.write(self.get_rendered_html(path, template_values), 200)
def calculate_accuracy(track: Track, frame, velocity): """Calculate the accuracy of the most front circle. Arguments: track: The track containing circles and a key. frame: The frame rate. velocity: The velocity of circles falling. Returns: The time needed for the frontest circle to flow to the key in sec. """ displacement = track.height - track.get_front_circle() return displacement / velocity / frame
def genres(): template = 'genres.html' if flask.request.headers.get('X-Requested-With') == 'XMLHttpRequest': template = 'genre_content.html' selected_genre = flask.request.args.get('type', '') genre_list = Track.genre_list() track_list = get_track_list_by_genre(selected_genre) return flask.render_template(template, html_class='genres', track_list=track_list, genre_list=genre_list, active=flask.request.args.get('type', ''))
def get(self): expert_id = self['id'] expert = Expert.get_by_key_name(expert_id) redirect_url = self['redirect_url'] if self['redirect_url'] else '/experts/list' path = 'expert_edit.html' template_values = {} template_values['redirect_url'] = redirect_url template_values['is_member'] = True if 'member' in self.session else False if 'member' in self.session: template_values['member'] = Member.get_member_json(self.session['member']) template_values['form_url'] = blobstore.create_upload_url('/api/members/update/expert') template_values['tracks'] = Track.all().fetch(50) template_values['expert'] = expert self.write(self.get_rendered_html(path, template_values), 200)
def _json(self): return { 'name': self.name, 'bio': self.bio, 'image': self.image, 'location': self.city + ', ' + self.state, 'tracks': ', '.join( [Track.get_by_key_name(track).name for track in self.tracks]) }
def get(self): redirect_url = self['redirect_url'] if self[ 'redirect_url'] else '/experts' path = 'expert_registration.html' template_values = {} template_values['redirect_url'] = redirect_url template_values[ 'is_member'] = True if 'member' in self.session else False if 'member' in self.session: template_values['member'] = Member.get_member_json( self.session['member']) template_values['form_url'] = blobstore.create_upload_url( '/api/members/experts/create') template_values['tracks'] = Track.all().fetch(50) self.write(self.get_rendered_html(path, template_values), 200)
def get(self): path = 'associate.html' template_values = {} template_values['form_url'] = '/api/common/save_association' template_values['is_member'] = True if 'member' in self.session else False if 'member' in self.session: template_values['member'] = Member.get_member_json(self.session['member']) track_programs = [] tracks = Track.all() for track in tracks: programs = Program.all().ancestor(track) track_programs.append((track, programs)) template_values['track_programs'] = track_programs template_values['experts'] = Expert.all().fetch(50) self.write(self.get_rendered_html(path, template_values), 200)
def __init__(self, midi_instance: MIDIFile, tempo: int, note_result: List[dict], density_level_list: List[dict], std_volume: int = volume_map['mf'], start_time: int = 0): self.midi_instance = midi_instance self.tempo = tempo self.note_result = note_result self.density_level_list = density_level_list self.std_volume = std_volume self.track_map = Track.create_track_map(midi_instance=midi_instance, tempo=tempo) self.melody = None self.start_time = start_time
def get(self): path = 'associate.html' template_values = {} template_values['form_url'] = '/api/common/save_association' template_values[ 'is_member'] = True if 'member' in self.session else False if 'member' in self.session: template_values['member'] = Member.get_member_json( self.session['member']) track_programs = [] tracks = Track.all() for track in tracks: programs = Program.all().ancestor(track) track_programs.append((track, programs)) template_values['track_programs'] = track_programs template_values['experts'] = Expert.all().fetch(50) self.write(self.get_rendered_html(path, template_values), 200)
def get(self): expert_id = self['id'] expert = Expert.get_by_key_name(expert_id) redirect_url = self['redirect_url'] if self[ 'redirect_url'] else '/experts/list' path = 'expert_edit.html' template_values = {} template_values['redirect_url'] = redirect_url template_values[ 'is_member'] = True if 'member' in self.session else False if 'member' in self.session: template_values['member'] = Member.get_member_json( self.session['member']) template_values['form_url'] = blobstore.create_upload_url( '/api/members/update/expert') template_values['tracks'] = Track.all().fetch(50) template_values['expert'] = expert self.write(self.get_rendered_html(path, template_values), 200)
def render_track(track: Track, key_img, circle_img, screen): """Render the tracks. A track has its key and circles. Arguments: track: The track that has key and circles. key_img: The image of the key. circle_img: The image of the circles. screen: The game screen that the track will be rendered on. """ # render key screen.blit(key_img, track.key_position) # render perform if any perform = track.perform if perform: render_text(perform, track.key_position, screen, style='perform', color='white') # render circles for circle_position in track.get_circles(): screen.blit(circle_img, circle_position)
def get(self): track = Track.get_by_key_name(self['track_id']) program = Program.get_by_key_name(self['program_id'], parent=track) modules = ProgramModule.all().ancestor(program).order('name') template_values = { 'program': program, 'track': track, 'modules': modules, 'listing_heading': program.name } template_values[ 'is_member'] = True if 'member' in self.session else False if 'member' in self.session: email = self.session['member'] member = Member.get_by_email(email) template_values['member'] = member if member.role == MEMBER_ROLE[MANAGER]: template_values['is_manager'] = True else: modules_count = modules.count() * 1.0 completed_modules = [] for module in modules: if module.completed: completed_modules.append(module) completed_modules_count = len(completed_modules) score = (completed_modules_count / modules_count) * 100.0 engage_score = round(score * random(), 0) engage_score = int(engage_score) if engage_score > 1 else 1 template_values['donuts'] = DonutFactory.get_donuts( 100, 0.875, [('Engineer1', [ DonutSegment(engage_score, '#1c758a'), DonutSegment(score, '#58c4dd') ], '/assets/img/tracks/mobile_dev.png')], 'transparent', '#ddd') self.render_template(template_name='program_listing.html', template_values=template_values)
def create_track(): HEIGHT = 1000 return Track(0, HEIGHT, (0, 0))
def is_enrolled_program(cls, email, program_id, track_id): return EnrollProgram.get_by_key_name( email, parent=Program.get_by_key_name( program_id, parent=Track.get_by_key_name(track_id)))
def add_update_circle(track: Track, velocity): track.add_circle() track.update_circles(velocity)
def setup_tracks(): for i, track in enumerate(tracks): Track(key_name=track.id, name=track.name, order=i, image=track_imgs[track.id]).put()
elif suite_no == 3: phrase = Phrase(note_names=note_names, start_time=0, bar_count=16, std_octave=5) elif suite_no == 4: phrase = Phrase(note_names=note_names, start_time=0, bar_count=1, std_octave=5) else: print('unknown test suite %d' % suite_no) notes = phrase.build_notes() chords = phrase.build_chords() appregios = phrase.build_appregios() midi_instance = create_midi_file(num_tracks=3, file_format=1) tempo = 90 track1 = Track(midi_instance=midi_instance, track=0, channel=0, tempo=tempo) track2 = Track(midi_instance=midi_instance, track=1, channel=0, tempo=tempo) track3 = Track(midi_instance=midi_instance, track=2, channel=0, tempo=tempo) for note in notes: track1.add_note(note) for chord in chords: track2.add_chord(chord) for appregio in appregios: track3.add_appregio(appregio) save_midi_file(destination, midi_instance)
def setup_programs(): for track in tracks: track_obj = Track.get_by_key_name(track.id) for program in track.programs: Program(key_name=program.id, parent=track_obj, image=program.snapshot, slots=program.num_spots , name=program.title, description=program.description, start_date=datetime.strptime(program.start_date, "%b %d %Y")).put()
def cron_task_gdrive(): http = credentials.authorize(httplib2.Http(timeout=60)) service = build("drive", "v2", http=http, developerKey="*****@*****.**") param = {} param['q'] = 'mimeType contains "audio" and starred=false' param['maxResults'] = 1000 page_token = None last_call_time = 0 l = Library("iTunes Music Library.xml") itunes_songs = l.songs try: while True: if page_token: param['pageToken'] = page_token files = service.files().list(**param).execute() page_token = files.get('nextPageToken') for item in files['items']: file_name = item['title'].replace( '.%s' % item['fileExtension'], '') # Adding delay cuz of Discogs Rate-Limit DELAY_TIME = 1 # time between each request must more that 1 second in order to avoid 60 request per minute now = time.time() time_since_last = now - last_call_time if time_since_last < DELAY_TIME: time.sleep(DELAY_TIME - time_since_last) last_call_time = now if file_name.isdigit(): track_db = Track.query(Track.sons_id == file_name).get() if track_db is None: track_db = Track(sons_id=file_name) track_db.gdrive_id = item['id'] itunes_song = itunes_songs[file_name] if itunes_song is not None: track_db.genre = itunes_song.genre track_db.duration = itunes_song.total_time sons_track = sons_network.get_track(file_name) if 'default' not in sons_track.image: track_db.cover_img = 'http://sons.mn/' + sons_track.image.replace( '/uploads/', 'image-cache/w300-h300-c/') else: track_db.cover_img = 'http://sons.mn' + sons_track.image track_db.album = sons_track.album_name track_db.title = sons_track.title track_db.artist = sons_track.artist_name track_db.origin = 'Mongolian' track_db.put() if not config.DEVELOPMENT: service.files().update(fileId=item['id'], body={ 'labels': { 'starred': True } }).execute() elif ' - ' in file_name: try: if Track.query().filter( Track.gdrive_id == item['id']).count( limit=1) == 0: title, artist = file_name.split(' - ', 1) discog_result = d.search( '', title=title, artist=artist.replace('.', ' '), token= "mhkqGGqAxmkGFOlbnWRRQZYcqDLxLianrCocIIJE", type="Release", per_page=1) if len(discog_result) > 0: discog_release = discog_result[0] if isinstance(discog_result[0], discogs_client.Master): discog_release = discog_result[ 0].main_release track_db = Track.query().filter( Track.gdrive_id == item['id']).get() if track_db is None: track_db = Track(gdrive_id=item['id']) track_db.title = discog_release.title track_db.year = str(discog_release.year) track_db.cover_img = discog_release.thumb track_db.genre = ','.join( discog_release.genres) if len(discog_release.artists) > 0: track_db.artist = discog_release.artists[ 0].name track_db.put() if not config.DEVELOPMENT: service.files().update(fileId=item['id'], body={ 'labels': { 'starred': True } }).execute() except ConnectionError: pass if not page_token: break except DeadlineExceededError: return 'Ok' return 'Ok' # @app.route('/tasks/collect') # def collect(): # url = "http://www.billboard.com/rss/charts/hot-100" # result = urlfetch.fetch(url) # if result.status_code == 200: # xml = ElementTree.fromstring(result.content) # # for item in xml.iterfind('channel/item'): # if (model.Track.query(model.Track.title == item.find('chart_item_title').text, # model.Track.artist == item.find('artist').text).count(limit=1) == 0): # track_db = model.Track( # title=item.find('chart_item_title').text, # artist=item.find('artist').text # ) # track_db.put() # logging.info(item.find('title').text) # return str(xml.findtext(".//title"))
# { SEQ_CC_ECHO_FB_GATELENGTH, 20 }, // 100% # { SEQ_CC_ECHO_FB_TICKS, 20 }, // 100% # { SEQ_CC_LFO_WAVEFORM, 0x00 }, // off # { SEQ_CC_LFO_AMPLITUDE, 128 + 64 }, # { SEQ_CC_LFO_PHASE, 0 }, # { SEQ_CC_LFO_STEPS, 15 }, # { SEQ_CC_LFO_STEPS_RST, 15 }, # { SEQ_CC_LFO_ENABLE_FLAGS, 0 }, # { SEQ_CC_LFO_CC, 0 }, # { SEQ_CC_LFO_CC_OFFSET, 64 }, # { SEQ_CC_LFO_CC_PPQN, 6 }, // 96 ppqn # { SEQ_CC_LIMIT_LOWER, 0 }, # { SEQ_CC_LIMIT_UPPER, 0 }, # { 0xff, 0xff } // end marker # }; if __name__ == "__main__": '''Test Track configurations''' from model.track import Track class Parent: def __init__(self): self.name = '' for k, v in TRACK_LAYER_CONFIG.items(): t = Track(Parent(), None) t.configure(k) tlr = t.layer_config_repr() print(f'"{k:24}"\n"{tlr:24}" {k == tlr:8}' f' {t.p_tot_size:8} {t.t_tot_size:8}')
def isCheck(self, col): if self.gtmode: return GroupTrack.isCheck(col) else: return Track.isCheck(col)
def isStar(self, col): if self.gtmode: return GroupTrack.isStar(col) else: return Track.isStar(col)
def setfilter(self, rule="", group="", maxrows=0, page=1, orderby=None, orderbyasc=True): ''' make a new query by the rule provided, get maxrows results, skip (page - 1)*maxrows results default values get an unsorted list of all the tracks (tracks are always sorted by id) returns lst list for convenience and a feedback list feedback is a list of tuples with name and value if rule is None previous value are used except for orderby and orderbyasc ''' self._checksession() #print('setfilter(rule="{}", group="{}", maxrows={}, page={}, orderby={}, orderbyasc={})'.format # (rule, group, maxrows, page, orderby, orderbyasc)) fb = [] if self.stats.empty(): self.stats.total = self.session.query(Track).count() if rule is None and group is None: rule = self.prevrule group = self.prevgroup maxrows = self.prevmax page = self.prevpage if not type(maxrows) is int: maxrows = 0 fb.append(("max", 0)) # when group changes, reset page; when mode changes, keep and convert sort order newsortcol = None if group != self.prevgroup: if group == "" or self.prevgroup == "": # mode changed newsortcol = self.orderingconvert() if newsortcol: fb.append(("sortbycol", newsortcol)) fb.append(("page", 1)) page = 1 # if max changes reset page if maxrows != self.prevmax: fb.append(("page", 1)) page = 1 # "register" new orderby if orderby != None: assert(newsortcol == None) # new orderby resets page to 1 fb.append(("page", 1)) page = 1 # shift orderby value to clearly distinguish between asc and desc even for 0 orderno = orderby + 1 ordernosign = orderno if orderbyasc else -orderno if not self.ordering or self.ordering[-1] != ordernosign: self.ordbackup = None if orderno in self.ordering: self.ordering.remove(orderno) elif -orderno in self.ordering: self.ordering.remove(-orderno) self.ordering.append(ordernosign) #print("ordering", self.ordering) # creating basic query q = None if group == "": self.gtmode = False q = self.session.query(Track) else: self.gtmode = True q = self.session.query(GroupTrack).join(Track).join(Group) q = q.filter(GroupTrack.groupid==Group.idno).filter(Group.name==group) #rule filter if rule != "": q = self.buildquery(q, rule) #sorting - remeber the shift between orderby and orderno if self.ordering != None and len(self.ordering) > 0: for on in reversed(self.ordering): if on < 0: oby = -1 - on ofun = sqlalchemy.sql.expression.desc else: oby = on - 1 ofun = sqlalchemy.sql.expression.asc if self.gtmode: q = q.order_by(ofun(GroupTrack.colbycol(oby))) else: q = q.order_by(ofun(Track.colbycol(oby))) #by default or as a last rule, sort tracks by trackid, grouptracks by number if self.gtmode: q = q.order_by(GroupTrack.no) else: q = q.order_by(Track.idno) # query is prepared, execute it if maxrows == 0: self.lst = list(q.all()) elif maxrows == 1: self.lst = q[(page-1*maxrows)] else: self.lst = q[(page-1)*maxrows:page*maxrows] self.stats.newfilter(self.lst, q.count(), q.filter(Track.new == True).count()) # remember filter for sorting self.prevrule = rule self.prevgroup = group self.prevmax = maxrows self.prevpage = page # return lst (for convenience) and feedback return self.lst, fb
def _json(self): return {'name': self.name, 'bio': self.bio, 'image': self.image, 'location': self.city+', '+self.state, 'tracks': ', '.join([Track.get_by_key_name(track).name for track in self.tracks])}