def post(self): logging.info('newAchievement posted') # Get the current Cheever's profile so we can update their numContribs cheever_key = ndb.Key('Cheever', self.user.email()) cheever = cheever_key.get() # Create new achievement with auto - generated key achievement = Achievement() achievement.populate( title=self.request.get('title'), description=self.request.get('description'), category=self.request.get('category'), score=int(self.request.get('score')), contributor=cheever.username, verified=False ) cheever.numContribs += 1 # Commit our updates to the datastore @ndb.transactional(xg=True) def commit(): achievement.put() cheever.put() commit() self.redirect('/profile')
def create(name, short_description, long_description, difficulty, image_src, bg_image_src): """ Create a new user """ achievement = Achievement( name=name, short_description=short_description, long_description=long_description, difficulty=difficulty, image_src=image_src, bg_image_src=bg_image_src ) return achievement.save()
def mutate(self, info, achievement_data=None): threshold = UserMetrics( works_visited=achievement_data.threshold.works_visited, works_found=achievement_data.threshold.works_found) achievement = Achievement(title=achievement_data.title, description=achievement_data.description, points=achievement_data.points, threshold=threshold) achievement.save() return CreateAchievementMutation(achievement=achievement)
def scrapeAchievements(): for h in range(1, 74): tempurl = baseurl + '/achievement/' + str(h) req = urllib.request.Request(tempurl, headers={'User-Agent': 'Mozilla/5.0'}) try: thejson = urllib.request.urlopen(req, context=context) except: pass else: data_bytes = thejson.read().decode('utf-8') data = json.loads(data_bytes) achievement_id = data['id'] name = data['name'] description = data['description'] reward = data['reward']['name'] reward_type = data['reward']['type']['name'] reward_quality = data['reward']['quality']['name'] f_key = None if (data['hero'] is not None): f_key = data['hero']['id'] # #all the url, info to create each json # print(str(achievement_id) + " "+ name + "\n"+ description) achieve = Achievement(achievement_id, name, description, reward, reward_type, reward_quality, f_key) db.session.add(achieve) db.session.commit()
def achievement(): Entry = namedtuple('Entry', ['achievement_description']) achievement_value = Achievement.load(current_user.id) if achievement_value.achievement_list: data = {'achievement_list': []} for achievement_description in achievement_value.achievement_list: data['achievement_list'].append(Entry(achievement_description)) form = AchievementListForm(data=data) else: form = AchievementListForm() if form.validate_on_submit(): if form.add.data: if bool(form.new_achievement.data): achievement_value.add(form.new_achievement.data) flash('Achievement added', 'success') commit() else: flash('Empty achievement', 'danger') return redirect(url_for('achievement.achievement')) else: for index in range(len(form.achievement_list)): if form.achievement_list[index].save.data: if bool(form.achievement_list[index].achievement_description.data): achievement_value.update(index, form.achievement_list[index].achievement_description.data) commit() flash('Updated successfully', 'success') else: flash('Empty achievement', 'danger') return redirect(url_for('achievement.achievement')) if form.achievement_list[index].delete.data: achievement_value.delete(index) commit() flash('Deleted successfully', 'success') return redirect(url_for('achievement.achievement')) return render_template('achievement.html', form=form)
def get(self): logging.info('AdminPage requested') achievements = Achievement.query().filter( Achievement.verified == False).fetch() self.template_values['achievements'] = achievements template = jinja.get_template('admin.html') self.response.out.write(template.render(self.template_values))
def award_monthly_achievements(year, month): """ Find the user in the top spot of each activity type's leaderboard (and the "all" leaderboard) and create achievements """ activity_types = { 'all': Achievement.TYPE_ALL, 'run': Achievement.TYPE_RUN, 'ride': Achievement.TYPE_RIDE, 'walk': Achievement.TYPE_WALK, } month_start = datetime.datetime(year, month, 1) # First, let's kill the current achievement holders Achievement.objects.filter(month_start=month_start).delete() for activity_type, activity_enum in activity_types.iteritems(): leader_user_id = get_leaderboard_leader(activity_type, year=year, month=month) user = User.objects.get(id=leader_user_id) achievement = Achievement(user=user, month_start=month_start, activity_type=activity_enum) achievement.save()
def get(self): logging.info('Generating SystemStats') achievements = Achievement.query().filter(Achievement.verified == True).fetch() cheevers = Cheever.query().fetch() contributors = Achievement.query( projection=[Achievement.contributor], distinct=True).fetch() maxScore = 0 for a in achievements: maxScore += a.score systemStats = SystemStats( numUsers=cheevers.__len__(), numContributors=contributors.__len__(), numAchievements=achievements.__len__(), maxScore=maxScore, created=datetime.datetime.now() ) systemStats.put() memcache.set('systemStats', systemStats)
def init_db(): art = [ Artwork(title="Street Art", description="A true masterpiece", location=[7,80]), Artwork(title="Hidden Subway Mural", description="Far side of the subway station has a double walled mural.", location=[10,132]), Artwork(title="Blue Bridge", description="Neon blue tentacles of paint wind up the struts of the bridge", location=[0,0], tags=["amazing"]), Artwork(title="Artistic Underpass", description="Bridge ceiling covered in art", location=[0,0], tags=["surreal", "amazing"]), Artwork(title="Fire Wall", description="Tongues of flame comemorate the historic fire of this district", tags=["sad", "historic", "amazing"], location=[0,0]), Artwork(title="Street Corner Fresco", description="This popular street has a decorative fresco spilling out of the alley behind a popular restaurant", tags=["amazing", "unreal"], location=[0,0]) ] for a in art: a.save() portfolios = [ Portfolio(artworks=[art[0], art[1]]), Portfolio(artworks=[art[2], art[4]]), Portfolio(artworks=[art[1], art[2], art[3]]), Portfolio(artworks=[art[3], art[5]]), ] for p in portfolios: p.save() users = [ User(name="Grant", portfolio=portfolios[0], bio="Love me some AI and maybe web dev."), User(name="Braden", portfolio=portfolios[1], bio="Spending some time on CSC 400."), User(name="Kyle", portfolio=portfolios[2], bio="Fitness, meditation and good books."), User(name="John", portfolio=portfolios[3], bio="Looking around for some art. Wasn't satisfied with my dope Windows Vista wallpaper.") ] for user in users: user.save() achievements = [ Achievement(title="Noob", description="You signed up for the service!", points=10) ] for a in achievements: a.save() for user in users: user.achievements.append(achievements[0]) for user, portfolio in zip(users, portfolios): portfolio.owner = user for portfolio in portfolios: portfolio.save()
def post(self): logging.info('AchievementsPage posted') query = Achievement.query() if self.request.get('title') != '': query = query.filter(Achievement.title == self.request.get('title')) if self.request.get('contributor') != '': query = query.filter( Achievement.contributor == self.request.get('contributor')) try: beginDate = datetime.datetime.strptime( self.request.get('beginDate'), '%Y-%m-%d') query = query.filter(Achievement.created >= beginDate) except: beginDate = datetime.datetime(1900, 1, 1) try: endDate = datetime.datetime.strptime( self.request.get('endDate'), '%Y-%m-%d') query = query.filter(Achievement.created <= endDate) except: endDate = datetime.datetime.now() query = query.filter(Achievement.verified == True) query = query.order(ndb.GenericProperty(self.request.get('sort'))) logging.info(self.request.get('sort')) logging.info(query) results = query.fetch() self.template_values['achievements'] = results template = jinja.get_template('achievements.html') self.response.out.write( template.render(self.template_values))
def get(self): logging.info('Home page requested') results = memcache.get('popular') if results is None: results = Achievement.query().order( -Achievement.numLiked, -Achievement.score).fetch(10) memcache.add('popular', results, time=60) self.template_values['achievements'] = results contribStats = memcache.get('contribStats') if contribStats is None: query = LeaderboardStats.query() query = query.filter(LeaderboardStats.statType == 'contribution') query = query.order(-LeaderboardStats.value) contribStats = query.fetch() memcache.add('contribStats', contribStats) self.template_values['contribStats'] = contribStats scoreStats = memcache.get('scoreStats') if scoreStats is None: query = LeaderboardStats.query() query = query.filter(LeaderboardStats.statType == 'score') query = query.order(-LeaderboardStats.value) scoreStats = query.fetch() memcache.add('scoreStats', scoreStats) self.template_values['scoreStats'] = scoreStats systemStats = memcache.get('systemStats') self.template_values['systemStats'] = systemStats template = jinja.get_template('home.html') self.response.out.write(template.render(self.template_values))
def run(self): # global statistics gs = {} gs['users'] = User.count({'active': True}) # FIXME: remove beta levels gs['achievements'] = Achievement.count() gs['expired_coupons'] = Coupon.count({ 'validations_left': 0, }) gs['coupons'] = Coupon.count() gs['level_bought'] = OrganizationLevel.count() gs['level_finished'] = OrganizationLevel.count({ 'status': { '$in': ['pending validation', 'validated'], }, }) gs['levels'] = Level.count() gs['organization_achievements'] = OrganizationAchievement.count() gs['organization_coupons'] = OrganizationCoupon.count() gs['organizations'] = Organization.count() last_record = GlobalStatistics.last_record() if not last_record or not all(item in last_record.items() for item in gs.items()): GlobalStatistics.post_internal(gs) # level statistics levels = mongo_list_to_dict(Level.all()) for level in levels.values(): amount_bought = OrganizationLevel.count({ 'level': level['_id'], }) # FIXME: filter, only 1 by organization amount_finished = OrganizationLevel.count({ 'level': level['_id'], 'status': { '$in': ['pending validation', 'validated'], }, }) level['amount_bought'] = amount_bought LevelStatistics.update_by_id( level['statistics'], { '$set': { 'amount_bought': amount_bought, 'amount_finished': amount_finished, # FIXME: fivestar average # FIXME: duration average # FIXME: amount hints bought }, }) sessions = Session.all() for session in sessions: organization_levels = OrganizationLevel.find({ 'session': session['_id'], }) organizations = mongo_list_to_dict( Organization.find({ 'session': session['_id'], })) validations = OrganizationLevelValidation.all() for validation in validations: if validation['status'] == 'refused': continue organization = organizations.get(validation['organization']) if not organization: continue level = levels.get(validation['level']) if not level: continue level['validations'] = level.get('validations', 0) defaults = { 'validated_levels': [], 'gold_medals': 0, 'silver_medals': 0, 'bronze_medals': 0, } for key, value in defaults.items(): if key not in organization: organization[key] = value if level['validations'] == 0: organization['gold_medals'] += 1 elif level['validations'] == 1: organization['silver_medals'] += 1 elif level['validations'] == 2: organization['bronze_medals'] += 1 organization['validated_levels'].append(level['_id']) level['validations'] += 1 for organization in organizations.values(): coupons = OrganizationCoupon.count({ 'organization': organization['_id'], }) achievements = OrganizationAchievement.count({ 'organization': organization['_id'], }) validated_levels = list( set(organization.get('validated_levels', []))) score = 0 score += organization.get('gold_medals', 0) * 9 score += organization.get('silver_medals', 0) * 5 score += organization.get('bronze_medals', 0) * 2 score += len(validated_levels) * 10 score += achievements * 2 for validated_level in validated_levels: level = levels[validated_level] percent = float(level['validations']) / float( level['amount_bought']) score += int(round(-math.log(percent) * 2)) OrganizationStatistics.update_by_id( organization['statistics'], { '$set': { 'coupons': coupons, 'score': score, 'achievements': achievements, 'gold_medals': organization.get('gold_medals', 0), 'silver_medals': organization.get('silver_medals', 0), 'bronze_medals': organization.get('bronze_medals', 0), 'finished_levels': len(validated_levels), 'bought_levels': OrganizationLevel.count({ 'organization': organization['_id'], }) }, })
def post(self, request): status = 'ok' error = [0, ''] if request.user.is_authenticated(): id = request.POST.get('id', '') tags = request.POST.get('tags', '') text = request.POST.get('text', '') time = request.POST.get('time', '') subject = request.POST.get('subject', '') grade = request.POST.get('grade', '') try: with transaction.atomic(): t = Time.objects.get(id=time) s = Subject.objects.get(id=subject) g = Grade.objects.get(id=grade) try: if id != '' and id != 0 and id != '0': a = MAchievement.objects.get(id=id) else: raise ObjectDoesNotExist except ObjectDoesNotExist as e: a = MAchievement(tags=tags, text=text, time=t, subject=s, grade=g, user=request.user) a.save() else: a.tags = tags a.text = text a.time = t a.subject = s a.grade = g a.user = request.user a.save() except IntegrityError as e: status = 'fail' error = e.args except: status = 'fail' error = [100, 'error inesperado'] else: status = 'fail' error = [401, 'permiso denegado'] return HttpResponse(json.dumps({'status':status, 'error':error}), content_type='application/json')