当前位置: 首页>>代码示例>>Python>>正文


Python models.Exercise类代码示例

本文整理汇总了Python中models.Exercise的典型用法代码示例。如果您正苦于以下问题:Python Exercise类的具体用法?Python Exercise怎么用?Python Exercise使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Exercise类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: post

	def post(self):
		workout_title = self.request.get("workout")
		new_workout = Workout(parent = PARENT_KEY, title = workout_title)
		new_workout.put()
		arguments = self.request.arguments()
		exercises = [ {} for i in range( utils.findLength(arguments) ) ]
		print exercises
		for argu in arguments:
			if str(argu) != 'workout':
				num = utils.findPosition(argu)
				if utils.is_time(argu):
					exercises[num]['time'] = int(self.request.get(argu))
				if utils.is_rest(argu):
					exercises[num]['rest'] = int(self.request.get(argu))
				if utils.is_name(argu): 
					exercises[num]['name'] = str(self.request.get(argu))
		print exercises
		for counter, exercise in enumerate(exercises): ## Needs to be ordered
			print counter
			print exercise
			new_exercise = Exercise(parent = PARENT_KEY, 
									name = exercise['name'],
									time = exercise['time'],
									rest = exercise['rest'],
									workout_title =  workout_title,
									order =  counter)
			new_exercise.put()

		self.redirect('/home') 
开发者ID:samoretc,项目名称:Workout-Timer,代码行数:29,代码来源:main.py

示例2: get_json_response

    def get_json_response(self):
        # Currently accepts: { "buckets", "all", "newest" }
        to_show = self.request_string('show', 'buckets')
        past_days = self.request_int('past_days', 7)
        refresh_secs = self.request_int('rsecs', 30)

        today = dt.date.today()
        # We don't use App Engine Query filters so as to avoid adding entries to index.yaml
        days = [ today - dt.timedelta(days=i) for i in range(0, past_days) ]

        if to_show == 'all':
            exercise_names = [ex.name for ex in Exercise.get_all_use_cache()]
            return self.exercise_over_time_for_highcharts(exercise_names, days, 'All Exercises', showLegend=True)

        if to_show == 'newest':
            exercises = Exercise.get_all_use_cache()
            exercises.sort(key=lambda ex: ex.creation_date, reverse=True)
            exercise_names = [ex.name for ex in exercises]

            num_newest = self.request_int('newest', 5)
            exid = exercise_names[get_bucket_cursor(refresh_secs, num_newest)]

            title = 'Newest Exercises - %s' % Exercise.to_display_name(exid)

            return self.exercise_over_time_for_highcharts([exid], days, title, showLegend=True)

        num_buckets = self.request_int('buckets', NUM_BUCKETS)
        bucket_index = self.request_int('ix', 0)
        bucket_size = get_bucket_size(num_buckets, bucket_index)
        bucket_cursor = get_bucket_cursor(refresh_secs, bucket_size)

        exercise_names = exercises_in_bucket(num_buckets, bucket_index)
        exid = exercise_names[bucket_cursor]

        return self.exercise_over_time_for_highcharts([exid], days, Exercise.to_display_name(exid))
开发者ID:avh4,项目名称:khan-academy,代码行数:35,代码来源:report_json.py

示例3: exercise_progress_graph_context

def exercise_progress_graph_context(user_data_student):

    if not user_data_student:
        return {}
    
    user = user_data_student.user

    exercise_data = {}
    
    exercises = Exercise.get_all_use_cache()
    user_exercises = UserExercise.get_for_user_use_cache(user)

    dict_user_exercises = {}
    for user_exercise in user_exercises:
        dict_user_exercises[user_exercise.exercise] = user_exercise

    for exercise in exercises:
        chart_link =""
        status = ""
        color = "transparent"
        exercise_display = Exercise.to_display_name(exercise.name)
        ex_link = "/exercises?exid="+exercise.name
        hover = "<b>%s</b><br/><em><nobr>Status: %s</nobr></em><br/><em>Streak: %s</em><br/><em>Problems attempted: %s</em>" % ( exercise_display, "Not Started", 0, 0)

        chart_link = "/profile/graph/exerciseproblems?student_email=%s&exercise_name=%s" % (user.email(), exercise.name) 
                
        user_exercise = dict_user_exercises[exercise.name] if dict_user_exercises.has_key(exercise.name) else None

        if user_data_student.is_proficient_at(exercise.name):
            status = "Proficient"
            color = "proficient"
            if not user_data_student.is_explicitly_proficient_at(exercise.name):
                status = "Proficient (due to proficiency in a more advanced module)"

        elif user_exercise is not None and UserExercise.is_struggling_with(user_exercise, exercise):
            status = "Struggling"
            color = "struggling"
        elif user_exercise is not None and user_exercise.total_done > 0:
            status = "Started"
            color = "started"

        if len(status) > 0:
            hover = "<b>%s</b><br/><em><nobr>Status: %s</nobr></em><br/><em>Streak: %s</em><br/><em>Problems attempted: %s</em>" % (exercise_display, 
                        status, 
                        user_exercise.streak if user_exercise is not None else 0, 
                        user_exercise.total_done if user_exercise is not None else 0)

        exercise_data[exercise.name] = {
                "short_name": exercise.short_name(),
                "chart_link": chart_link,
                "ex_link": ex_link, 
                "hover": hover,
                "color": color
                }
                
    return { 'exercises': exercises, 'exercise_data': exercise_data, }
开发者ID:jdunck,项目名称:khanacademy,代码行数:56,代码来源:exercise_progress_graph.py

示例4: exercise_progress_graph_context

def exercise_progress_graph_context(user_data_student):

    if not user_data_student:
        return {}
    
    exercise_data = {}
    
    exercises = Exercise.get_all_use_cache()
    user_exercise_graph = UserExerciseGraph.get(user_data_student)

    review_exercise_names = user_exercise_graph.review_exercise_names()

    for exercise in exercises:
        chart_link =""
        status = ""
        color = "transparent"
        exercise_display = Exercise.to_display_name(exercise.name)
        hover = "<b>%s</b><br/><em><nobr>Status: %s</nobr></em><br/><em>Progress: %s</em><br/><em>Problems attempted: %s</em>" % ( exercise_display, "Not Started", '0%', 0)

        chart_link = "/profile/graph/exerciseproblems?student_email=%s&exercise_name=%s" % (user_data_student.email, exercise.name) 
                
        graph_dict = user_exercise_graph.graph_dict(exercise.name)

        if graph_dict["proficient"]:

            if exercise.name in review_exercise_names:
                status = "Review"
                color = "review light"
            else:
                status = "Proficient"
                color = "proficient"
                if not graph_dict["explicitly_proficient"]:
                    status = "Proficient (due to proficiency in a more advanced module)"

        elif graph_dict["struggling"]:
            status = "Struggling"
            color = "struggling"
        elif graph_dict["total_done"] > 0:
            status = "Started"
            color = "started"

        if len(status) > 0:
            hover = "<b>%s</b><br/><em><nobr>Status: %s</nobr></em><br/><em>Progress: %s</em><br/><em>Problems attempted: %s</em>" % (exercise_display, 
                        status, 
                        UserExercise.to_progress_display(graph_dict["progress"]),
                        graph_dict["total_done"])

        exercise_data[exercise.name] = {
                "short_name": exercise.short_name(),
                "chart_link": chart_link,
                "ex_link": exercise.relative_url,
                "hover": hover,
                "color": color
                }
                
    return { 'exercises': exercises, 'exercise_data': exercise_data, }
开发者ID:KhanWorld,项目名称:KhanAcademy,代码行数:56,代码来源:exercise_progress_graph.py

示例5: load_csv

def load_csv(self):
    # import codecs
    # reader = codecs.getreader('utf-8')
    reader = csv.reader(open('./data/base_ex_women.csv', 'r'))

    print(repr(reader))
    print(dir(reader))

    try:
        i = True
        while True:
            row = reader.next()
            row = [unicode(s, "utf-8") for s in row]
        # for row in reader.next():
            if i:
                i = False
                continue
            logging.error(row)

            c = Exercise()
            # row = map(str, row)
            row = row + ([''] * 5)
            logging.error(row)

            c.title = row[0]
            c.description = row[1]
            c.image_link = row[2]
            c.link_to = row[3]
            c.video_link = row[4]
            c.for_women = True

            c.save()
    except Exception, e:
        pass
开发者ID:jurka,项目名称:training_builder,代码行数:34,代码来源:views.py

示例6: get_use_cache

    def get_use_cache(self):
        params = self.get_request_params()

        # Get the maximum so we know how the data label circles should be scaled
        most_new_users = 1
        ex_stat_dict = {}
        for ex in Exercise.get_all_use_cache():
            stat = ExerciseStatistic.get_by_date(ex.name, params['interested_day'])
            ex_stat_dict[ex.name] = stat
            if stat:
                most_new_users = max(most_new_users, stat.num_new_users())

        data_points = []
        min_y, max_y = -1, 1
        for ex in Exercise.get_all_use_cache():
            stat = ex_stat_dict[ex.name]

            y, x = -int(ex.h_position), int(ex.v_position)

            min_y, max_y = min(y, min_y), max(y, max_y)

            # Set the area of the circle proportional to the data value
            radius = 1
            if stat:
                radius = math.sqrt(float(stat.num_new_users()) / most_new_users) * MAX_POINT_RADIUS

            point = {
                'x': x,
                'y': y,
                'name': ex.display_name,
                'marker': {
                    'radius': max(radius, 1)
                },
            }
            data_points.append(point)

        context = {
            'title': 'Exercises map - First attempts',
            'series': {
                'name': 'First attempts',
                'data_values': json.dumps(data_points),
            },
            'minYValue': min_y - 1,
            'maxYValue': max_y + 1,
        }

        return self.render_jinja2_template_to_string(
            'exercisestats/highcharts_scatter_map.json', context)
开发者ID:avh4,项目名称:khan-academy,代码行数:48,代码来源:report_json.py

示例7: exercise_counter_for_geckoboard_rag

    def exercise_counter_for_geckoboard_rag():
        exercises = Exercise.get_all_use_cache()
        exercises.sort(key=lambda ex: ex.creation_date, reverse=True)

        last_exercise = exercises[0]
        num_exercises = len(exercises)
        last_exercise_author = last_exercise.author.nickname() if last_exercise.author else 'random person'

        text = "Thanks %s for %s!" % (last_exercise_author, last_exercise.display_name)

        return {
            'item': [
                {
                    'value': None,
                    'text': '',
                },
                {
                    'value': None,
                    'text': '',
                },
                {
                    'value': num_exercises,
                    'text': text,
                },
            ]
        }
开发者ID:avh4,项目名称:khan-academy,代码行数:26,代码来源:report_json.py

示例8: library_content_html

def library_content_html(mobile=False, version_number=None):

    if version_number:
        version = TopicVersion.get_by_number(version_number)
    else:
        version = TopicVersion.get_default_version()

    tree = Topic.get_root(version).make_tree(types = ["Topics", "Video", "Exercise", "Url"])

    videos = [item for item in walk_children(tree) if item.kind()=="Video"]

    root, = prepare(tree)
    topics = root.subtopics

    timestamp = time.time()

    template_values = {
        'topics': topics,
        'is_mobile': mobile,
        # convert timestamp to a nice integer for the JS
        'timestamp': int(round(timestamp * 1000)),
        'version_date': str(version.made_default_on),
        'version_id': version.number,
        'approx_vid_count': Video.approx_count(),
        'exercise_count': Exercise.get_count(),
    }

    html = shared_jinja.get().render_template("library_content_template.html", **template_values)

    return html
开发者ID:di445,项目名称:server,代码行数:30,代码来源:library.py

示例9: exercise_title_dicts

def exercise_title_dicts():
    return [{
        "title": exercise.display_name,
        "key": str(exercise.key()),
        "relative_url": exercise.relative_url,
        "id": exercise.name,
    } for exercise in Exercise.get_all_use_cache() if not exercise.summative]
开发者ID:johnfelipe,项目名称:server,代码行数:7,代码来源:autocomplete.py

示例10: get

	def get(self):
		workouts_query = Workout.query(ancestor = PARENT_KEY)
		exercise_query = Exercise.query(ancestor = PARENT_KEY).order( Exercise.order )
		template = jinja_env.get_template("templates/index.html")
		print 'self response'
		print self.response
		self.response.write(template.render( {"workouts_query": workouts_query, "exercise_query" : exercise_query} ))
开发者ID:samoretc,项目名称:Workout-Timer,代码行数:7,代码来源:main.py

示例11: handle_average

def handle_average(argv, Class, class_str, call_print_averages=True):
    '''Pass the appropriate data to get the corresponding averages.

    Keyword arguments:
    argv -- An array of command line arguments.
    Class -- The class in which to find the averages.
    class_str -- The stringified Classname (e.g., a Student class would be
    "Student").
    call_print_averages -- Boolean value to optionally print the averages
    '''
    arr = []
    for i in mean:
        i["pts_total"] = 0.0
        i["mean"] = 0.0
        i["num"] = 0
    for exercise in Exercise.select():
        compare = {"Student": exercise.student.id,
                   "Batch": exercise.student.batch.id,
                   "School": exercise.student.batch.school.id}
        if str(compare.get(class_str)) == str(argv[2]):
            get_average(exercise, argv)
    for i in range(0, len(mean)):
        if call_print_averages is True:
            print_averages(i)
        else:
            if print_averages(i, False) is not None:
                arr.append(print_averages(i, False))
    for student in Class.select():
        if str(student.id) == str(argv[2]):
            return arr
    print class_str + " not found"
开发者ID:bennettbuchanan,项目名称:holbertonschool-higher_level_programming,代码行数:31,代码来源:main.py

示例12: user_post

	def user_post(self, *args):
		pagename = args[0]
		if args[0] is None:
			pagename=""

		exercise = Exercise.query().filter("url = ",pagename).get()
		submission = self.request.get('code')
		program = exercise.outside_code.format(submission)
		action = self.request.get('action')


		response = dict()
		if action == 'check':
			response = exercise.checker.checkWork(program, self.username)
			if response['passed']:
				user = User.query().filter('username = ', self.username).get()
				if user and (not exercise.key() in user.exercises_completed):
					user.exercises_completed.append(exercise.key())
					user.put()

		elif action == 'test':
			message = ''
			logging.info(self.request.get('input'))
			response = exercise.checker.submit(program, self.username, self.request.get('input'))
			
			if (response['error'] != "OK" or 
				int(response['result']) != 15 or 
				response['output'] is None):
					message = response['error_message']

			response['message'] = message

		self.write_json(response);
开发者ID:chrisuehlinger,项目名称:sg-study-c,代码行数:33,代码来源:views.py

示例13: user_get

	def user_get(self, *args):
		pagename = args[0]
		if pagename is None:
			exercise_list = Exercise.query().order('name')
			page = {'url':'exercises', 'topic_name':'Practice Exercises'}
			self.render_with_user("exerciseindex.html", {'page':page,
														 'exercises':exercise_list})
		else:
			exercise = Exercise.query().filter("url = ",pagename).get()
			if exercise is None:
				self.write("No Exercise named '%s'" % pagename)
			else:
				logging.info("Serving exercise: " + repr(exercise.name))
				logging.info("Serving exercise: " + repr(exercise.start_code))
				logging.info("Serving exercise: " + repr(exercise.description))
				self.render_with_user("exercise.html", {'page':exercise})
开发者ID:chrisuehlinger,项目名称:sg-study-c,代码行数:16,代码来源:views.py

示例14: insert_item

def insert_item(argv):
    '''Takes the system arguments as parameter and then inserts the item.

    Keyword arguments:
    argv -- An array of command line arguments passed to the program.
    '''
    if argv[2] == "school":
        school = School.create(name=argv[3])
        print "New school: " + str(School.get(School.name == argv[3]))
    elif argv[2] == "batch":
        batch = Batch.create(school=argv[3], name=argv[4])
        print "New batch: " + str(Batch.get(Batch.name == argv[4]))
    elif argv[2] == "student":
        print "New student:",
        if len(argv) > 6:
            student = Student.create(batch=argv[3],
                                     age=argv[4],
                                     last_name=argv[5],
                                     first_name=argv[6])
            print str(Student.get(Student.age == argv[4] and
                                  Student.last_name == argv[5] and
                                  Student.first_name == argv[6]))
        else:
            student = Student.create(batch=argv[3],
                                     age=argv[4],
                                     last_name=argv[5])
            print str(Student.get(Student.age == argv[4] and
                                  Student.last_name == argv[5]))
    elif argv[2] == "exercise":
        exercise = Exercise.create(student=argv[3],
                                   subject=argv[4],
                                   note=argv[5])
        print "New Exercise: " + str(exercise)
开发者ID:bennettbuchanan,项目名称:holbertonschool-higher_level_programming,代码行数:33,代码来源:main.py

示例15: exercise_message

def exercise_message(exercise, user_exercise_graph, sees_graph=False,
        review_mode=False):
    """Render UserExercise html for APIActionResults["exercise_message_html"] listener in khan-exercise.js.

    This is called **each time** a problem is either attempted or a hint is called (via /api/v1.py)
    returns nothing unless a user is struggling, proficient, etc. then it returns the appropriat template

    See Also: APIActionResults

    sees_graph is part of an ab_test to see if a small graph will help
    """

    # TODO(david): Should we show a message if the user gets a problem wrong
    #     after proficiency, to explain that this exercise needs to be reviewed?

    exercise_states = user_exercise_graph.states(exercise.name)

    if review_mode and user_exercise_graph.has_completed_review():
        filename = 'exercise_message_review_finished.html'

    elif (exercise_states['proficient'] and not exercise_states['reviewing'] and
            not review_mode):
        if sees_graph:
            filename = 'exercise_message_proficient_withgraph.html'
        else:
            filename = 'exercise_message_proficient.html'

    elif exercise_states['struggling']:
        filename = 'exercise_message_struggling.html'
        suggested_prereqs = []
        if exercise.prerequisites:
            proficient_exercises = user_exercise_graph.proficient_exercise_names()
            for prereq in exercise.prerequisites:
                if prereq not in proficient_exercises:
                    suggested_prereqs.append({
                          'ka_url': Exercise.get_relative_url(prereq),
                          'display_name': Exercise.to_display_name(prereq),
                          })
        exercise_states['suggested_prereqs'] = apijsonify.jsonify(
                suggested_prereqs)

    else:
        return None

    return shared_jinja.get().render_template(filename, **exercise_states)
开发者ID:johnfelipe,项目名称:server,代码行数:45,代码来源:templatetags.py


注:本文中的models.Exercise类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。