def make_linear_eq(x="", rhs = None, var_coeffs=True): """ Generates linear equation in one variable, and its solution. x : charector for the variable to be solved for. defaults to random selection from the global list `alpha`. OR a list of possible charectors. A random selection will be made from them. rhs : value to set for the right-hand side. If not given, the right-hand side will be a randomly generated linear expression var_coeffs : sets whether we want variables as coefficients in the problem. defaults to True. Set to False if you want a problem with strictly numerical coefficients. """ if not x: x = random.choice(alpha) elif isinstance(x, list): x = random.choice(x) exclude = [x.upper(), x.lower()] x = sympy.Symbol(x) c1, c2, c3, c4 = get_coefficients(4, var_coeffs=var_coeffs, reduce=False, exclude = exclude) lhs = c1*x + c2 rhs = c3*x + c4 e = sympy.Eq(lhs, rhs) sols = [render(ex, x) for ex in sympy.solve(e, x)] return "Solve for $%s$ : %s" % (x, render(e)), sols
def make_linear_eq(x="", rhs=None, var_coeffs=True): """ Generates linear equation in one variable, and its solution. x : charector for the variable to be solved for. defaults to random selection from the global list `alpha`. OR a list of possible charectors. A random selection will be made from them. rhs : value to set for the right-hand side. If not given, the right-hand side will be a randomly generated linear expression var_coeffs : sets whether we want variables as coefficients in the problem. defaults to True. Set to False if you want a problem with strictly numerical coefficients. """ if not x: x = random.choice(alpha) elif isinstance(x, list): x = random.choice(x) exclude = [x.upper(), x.lower()] x = sympy.Symbol(x) c1, c2, c3, c4 = get_coefficients(4, var_coeffs=var_coeffs, reduce=False, exclude=exclude) lhs = c1 * x + c2 rhs = c3 * x + c4 e = sympy.Eq(lhs, rhs) sols = [render(ex, x) for ex in sympy.solve(e, x)] return "Solve for $%s$ : %s" % (x, render(e)), sols
def make_horizontal_tangents(var="x"): if isinstance(var, str): var = sympy.Symbol(var) elif isinstance(var, list): var = sympy.Symbol(random.choice(var)) df = sympy.prod([ var - random.choice(digits_nozero) for i in xrange(random.randint(2, 3)) ]) f = sympy.integrate(df, var) eqn = sympy.Eq(sympy.diff(f, var), 0) fx = "f \\left(%s \\right)" % str(var) return render(f, fx), render(', '.join( [str(var) + "=" + str(i) for i in sympy.solve(eqn)]))
def get(self): ulist = UserTotalStat().all().order('-count') count = 0 top_thirty = [] for k in ulist: if count > 30: break count += 1 row = {} row['username'] = k.username row['count'] = k.count top_thirty.append(row) template_values = {} template_values['topthirty'] = top_thirty template_values['scoreboard'] = True logging.debug(template_values) path = os.path.join (os.path.dirname(__file__), 'views/topscore.html') self.response.out.write (helper.render(self, path, template_values))
def get(self): if os.environ.get('HTTP_HOST'): base_url = 'http://' + os.environ['HTTP_HOST'] + '/' else: base_url = 'http://' + os.environ['SERVER_NAME'] + '/' # get bookmark bookmark = self.request.get('bookmark') logging.debug(self.request.get('bookmark')) template_values = { 'base_url' : base_url } forward = True page = None # check if page set if self.request.get('page'): page = int(self.request.get('page')) elif not bookmark: page = 1 helper.get_data_page(template_values, 'saved', None, None, bookmark, page) template_values['current_bookmark'] = bookmark template_values['current_page'] = page #template_values['surveys'] = extracted template_values['data'] = True path = os.path.join (os.path.dirname(__file__), 'views/data.html') self.response.out.write (helper.render(self, path, template_values))
def POST(self): you = require_you() params = web.input(name='') unique = True name = params['name'] if name and name != you.get('name',None): from helper import slugify slug = slugify(name) for row in dbview.users(db, startkey=slug, endkey=slug): if slug == row.key: unique = False break if unique: you['name'] = name you['slug'] = slug elif not name and 'name' in you: # blanking your name makes you anonymous, and makes your page inaccessible del you['name'] del you['slug'] db[you.id] = you if unique: web.redirect('/') else: return render('settings', errors="Sorry, that name's taken!", you=you)
def get(self): auth_token = self.request.get("oauth_token") auth_verifier = self.request.get("oauth_verifier") fb_token = self.request.get("fb") dr_token = self.request.get("dr") if auth_token and auth_verifier: user = self.twitter_new(auth_token, auth_verifier) elif fb_token: user = self.facebook_new(fb_token) elif dr_token: user = self.draugiem_new(dr_token) else: logging.warning('/new called with incorrect parameters') return self.redirect('/') if not user: logging.warning("Failed to get username from service...") return self.redirect('/') post = Post() post.user = user today = datetime.date.today().strftime("%Y-%m-%d") self.response.out.write(helper.render('new', {'post': post, 'today': today}))
def handle(self): result = CategoryStat().all() data = [] for row in result: if row.count <= 0: cat_avg = 0 else: cat_avg = row.total/row.count datarow = { 'category':str(row.category), 'count':str(row.count), 'avg':str(cat_avg) } subcat = SubCategoryStat().all().filter('category = ', row.category) allsub = [] for subrow in subcat: if subrow.count <= 0: avg = 0 else: avg = subrow.total/subrow.count subdatarow = { 'subcategory':str(subrow.subcategory), 'count':str(subrow.count), 'avg':str(avg) } allsub.append(subdatarow) datarow['subcategories'] = allsub data.append(datarow) num = len(data) template_values = { 'summary1' : data[:int(num/2)], 'summary2' : data[int(num/2):] } template_values['datasummary'] = True template_values['divstyle'] = ['span-11 colborder','span-12 last'] path = os.path.join (os.path.dirname(__file__), 'views/summary.html') self.response.out.write (helper.render(self, path, template_values))
def get(self): try: post = db.get(self.request.get('p')) except: self.redirect('/') return self.response.out.write(helper.render('more', {'post': post}))
def get(self,nickname): nickname = helper.parse_post_id(nickname) session = get_current_session() if session.has_key('user'): user = session['user'] if session.has_key('profile_saved'): profile_saved = session.pop('profile_saved') profiledUser = User.all().filter('nickname =',nickname).fetch(1) if len(profiledUser) == 1: profiledUser = profiledUser[0] #TODO fix this horrible way of testing for the user if session.has_key('user') and user.key() == profiledUser.key(): my_profile = True #self.response.out.write(template.render('templates/profile.html', locals())) helper.render(self,profiledUser,'templates/profile.html', locals()) else: self.redirect('/')
def make_find_derivative_at_value(var="x", rhs="4"): F = sympy.Function("f") if isinstance(var, str): var = sympy.Symbol(var) elif isinstance(var, list): var = sympy.Symbol(random.choice(var)) df = sympy.prod([ var - random.choice(digits_nozero) for i in xrange(random.randint(2, 3)) ]) f = poly3(var) df = int(sympy.diff(f, var).evalf(subs={var: int(rhs)})) eq = sympy.latex(sympy.Derivative(F(rhs), var)) eq = 'd'.join(eq.split("\\partial")) eq = eq + "=" + str(df) fx = "f \\left(%s \\right)" % str(var) return render(f, fx), render(eq)
def handle_exception(self, exception, debug_mode): self.error(500) logging.exception(exception) if debug_mode: lines = ''.join(traceback.format_exception(*sys.exc_info())) self.response.clear() self.response.out.write('<pre>%s</pre>' % (cgi.escape(lines, quote=True))) else: self.response.out.write(helper.render('500'))
def get(self, nickname): nickname = helper.parse_post_id(nickname) session = get_current_session() if session.has_key('user'): user = session['user'] if session.has_key('profile_saved'): profile_saved = session.pop('profile_saved') profiledUser = User.all().filter('nickname =', nickname).fetch(1) if len(profiledUser) == 1: profiledUser = profiledUser[0] #TODO fix this horrible way of testing for the user if session.has_key('user') and user.key() == profiledUser.key(): my_profile = True #self.response.out.write(template.render('templates/profile.html', locals())) helper.render(self, profiledUser, 'templates/profile.html', locals()) else: self.redirect('/')
def get(self): posts = Post.all() if not config.DEBUG and not self.request.host_url.endswith('appspot.com'): posts.filter('confirmed_at !=', None) posts.order('-confirmed_at') values = { 'posts': posts } self.response.out.write(helper.render('main', values))
def get(self, post_id=None, action=None): if action is None: posts = Post.all() self.response.out.write(helper.render('admin/posts', { 'posts': posts })) elif action == "delete": Post.get_by_id(int(post_id)).delete() return self.redirect('/admin/posts') elif action == "confirm": post = Post.get_by_id(int(post_id)) post.confirmed_at = datetime.datetime.today() post.put() return self.redirect('/admin/posts')
def get(self): # redirect to login page if not logged in sess = gmemsess.Session(self) if sess.is_new() or not sess.has_key('username'): sess['error'] = 'Please log in to use this feature.' sess['redirect'] = '/user/show_data_download' sess.save() self.redirect('/user/login') return path = os.path.join (os.path.dirname(__file__), 'views/show_download.html') self.response.out.write (helper.render(self, path, {}))
def make_poly_ratio_limit(var="x", s=[0, 1, 2]): """ Generates a ratio of two polynomials, and evaluates them at infinity. x : charector for the variable to be solved for. defaults to "x". OR a list of possible charectors. A random selection will be made from them. s : selects the kind of solution 0 : limit at infinity is zero 1 : limit as infinity is a nonzero finite number 2 : limit at infinity is either +infinity or -infinity default: one of the above is randomly selected """ if isinstance(var, str): var = sympy.Symbol(var) elif isinstance(var, list): var = sympy.Symbol(random.choice(var)) if isinstance(s, list): s = random.choice(s) if s == 2: # infinity p1 = random.randint(2, 4) p2 = p1 - 1 elif s == 1: # ratio of leading coefficients p1 = random.randint(2, 4) p2 = p1 elif s == 0: # zero p1 = random.randint(2, 4) p2 = random.randint(p1, p1 + 2) select = [shuffle(digits_nozero)[0]] + shuffle(range(10)[:p1 - 1]) num = sum([(k + 1) * var**i for i, k in enumerate(select)]) select = [shuffle(digits_nozero)[0]] + shuffle(range(10)[:p2 - 1]) denom = sum([(k + 1) * var**i for i, k in enumerate(select)]) e = num / denom s = sympy.limit(e, var, sympy.oo) e = "\lim_{x \\to \infty}" + sympy.latex(e) return render(e), render(s)
def get(self): sess = gmemsess.Session(self) # if session is new, user was not logged in, redirect if sess.is_new(): sess['error'] = 'Please log in to view this page.' sess['redirect'] = '/user/data' sess.save() self.redirect('/user/login') return # if username not set in session, user not logged in, redirect if not sess.has_key('username'): sess['error'] = 'Please log in to view this page.' sess['redirect'] = '/user/data' sess.save() self.redirect('/user/login') return if os.environ.get('HTTP_HOST'): base_url = 'http://' + os.environ['HTTP_HOST'] + '/' else: base_url = 'http://' + os.environ['SERVER_NAME'] + '/' # get bookmark bookmark = self.request.get('bookmark') logging.debug(self.request.get('bookmark')) template_values = { 'base_url' : base_url } forward = True page = None # check if page set if self.request.get('page'): page = int(self.request.get('page')) elif not bookmark: page = 1 # form user data cache name cache_name = 'data_' + sess['userid'] helper.get_data_page(template_values, cache_name, 'username ='******'userid'], bookmark, page) template_values['userdata'] = True template_values['current_bookmark'] = bookmark template_values['current_page'] = page path = os.path.join (os.path.dirname(__file__), 'views/user_data.html') self.response.out.write (helper.render(self, path, template_values))
def run(self, edit): if not self.view.file_name().endswith(FILEENDING): sublime.error_message("File is not an Template (Filending must be '"+FILEENDING+"')") return newFileName = os.path.splitext(self.view.file_name())[0] try: f = codecs.open(newFileName, "w", "utf-8") data = helper.render(self.view) f.write(data) f.close() sublime.status_message("Template saved to '%s'"%newFileName) self.view.window().open_file(newFileName) except Exception as ex: sublime.error_message(str(ex))
def get(self): sess = gmemsess.Session(self) # redirect to login page if not logged in if sess.is_new() or not sess.has_key('username'): sess['error'] = 'Please log in to use this feature.' sess['redirect'] = '/user/contact' sess.save() self.redirect('/user/login') return template_values = {} path = os.path.join (os.path.dirname(__file__), 'views/contact.html') self.response.out.write (helper.render(self, path, template_values))
def handler(self): sess = gmemsess.Session(self) if sess.has_key('username'): self.redirect('/user/data') else: template_values = { 'sess' : sess } if sess.has_key('error'): template_values['error'] = sess['error'] del sess['error'] sess.save() path = os.path.join (os.path.dirname(__file__), 'views/login.html') self.response.out.write(helper.render(self, path, template_values))
def run(self, edit): if not self.view.file_name().endswith(FILEENDING): sublime.error_message( "File is not an Template (Filending must be '" + FILEENDING + "')") return newFileName = os.path.splitext(self.view.file_name())[0] try: f = codecs.open(newFileName, "w", "utf-8") data = helper.render(self.view) f.write(data) f.close() sublime.status_message("Template saved to '%s'" % newFileName) self.view.window().open_file(newFileName) except Exception as ex: sublime.error_message(str(ex))
def GET(self, game_id): game = Game.get(game_id) chats = dbview.chats(db, endkey=[game_id, ''], startkey=[game_id, COUCH_MAX], descending=True) you = get_you() #players = dict([(color, db[player_id]) for (color,player_id) in game["players"].iteritems()]) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if you: your_players = [color for (color,player) in game.players.items() if player.id == you.id] #print "Your Players: %s" % game.players.items()[0].id else: print "NOTHING" your_players = [] return render('game',game=game, you=get_you(), chats=chats, your_players=your_players)
def handle(self): q = ClassList().all().filter('active =', True) classlist = [] for row in q: classinfo = { 'name':str(row.classname), 'id':str(row.classid) } classlist.append(classinfo) template_values = {'classlist':classlist} path = os.path.join (os.path.dirname(__file__), 'views/new_user.html') self.response.out.write (helper.render(self, path, template_values))
def make_quadratic_eq(target, var="x", rhs=None, integer=[0, 1]): """ Generates quadratic equation problem expression and set of solutions x : charector for the variable to be solved for. defaults to "x". OR a list of possible charectors. A random selection will be made from them. rhs : value to set for the right-hand side. If not given, the right-hand side will be a randomly generated polynomial expression of degree <= 2, in the same variable. integer : determines whether generated problem will have integer roots or not. Default is a random selection. """ if isinstance(var, str): var = sympy.Symbol(var) elif isinstance(var, list): var = sympy.Symbol(random.choice(var)) if isinstance(integer, list): integer = random.choice(integer) if integer: r1 = random.choice(digits_nozero) r2 = target - r1 #r2 = random.choice(digits_nozero) lhs = (var - r1) * (var - r2) lhs = lhs.expand() rhs = 0 else: c1, c2, c3 = get_coefficients(3) lhs = c1 * var**2 + c2 * var + c3 if rhs == None: c4, c5, c6 = get_coefficients(3, first_nonzero=False) rhs = c4 * var**2 + c5 * var + c6 e = sympy.Eq(lhs, rhs) pvar = str(var) sols = ', '.join( [pvar + " = " + sympy.latex(ex) for ex in sympy.solve(e, var)]) sols = "$$" + sols + "$$" if len(sols) == 0: return make_quadratic_eq() return "\\overline{" + render(e) + "}", sols
def get(self): try: post = db.get(self.request.get('p')) if post.secret != self.request.get('s'): logging.warning('Somebody tried to update post (p=%s) with incorrect secret (s=%s)' % (self.request.get('p'), self.request.get('s'))) self.redirect('/') except: self.redirect('/') return if not config.DEBUG and not post.confirmed_at: logging.warning('Somebody tried edit post (p=%s) that is not yet confirmed' % self.request.get('p')) return self.redirect('/') values = { 'post': post, 'errors': [] } self.response.out.write(helper.render('edit', values))
def get(self): if os.environ.get('HTTP_HOST'): base_url = 'http://' + os.environ['HTTP_HOST'] + '/' else: base_url = 'http://' + os.environ['SERVER_NAME'] + '/' extracted = memcache.get('saved') if not extracted: surveys = SurveyData.all().order('-timestamp').fetch(PAGE_SIZE*5+1) extracted = helper.extract_surveys (surveys) if surveys is not None: #memcache.set('saved', extracted, 604800) memcache.set('saved', extracted) template_values = { 'surveys' : extracted, 'base_url' : base_url } template_values['map'] = True path = os.path.join (os.path.dirname(__file__), 'views/map.html') self.response.out.write (helper.render(self, path, template_values))
def make_quadratic_eq(var="x", rhs = None, integer=[0, 1]): """ Generates quadratic equation problem expression and set of solutions x : charector for the variable to be solved for. defaults to "x". OR a list of possible charectors. A random selection will be made from them. rhs : value to set for the right-hand side. If not given, the right-hand side will be a randomly generated polynomial expression of degree <= 2, in the same variable. integer : determines whether generated problem will have integer roots or not. Default is a random selection. """ if isinstance(var, str): var = sympy.Symbol(var) elif isinstance(var, list): var = sympy.Symbol(random.choice(var)) if isinstance(integer, list): integer = random.choice(integer) if integer: r1 = random.choice(digits_nozero) r2 = random.choice(digits_nozero) lhs = (var - r1) * (var - r2) lhs = lhs.expand() rhs = 0 else: c1, c2, c3 = get_coefficients(3) lhs = c1*var**2 + c2*var + c3 if rhs == None: c4, c5, c6 = get_coefficients(3, first_nonzero=False) rhs = c4*var**2 + c5*var + c6 e = sympy.Eq(lhs, rhs) pvar = str(var) sols = ', '.join([pvar+" = " + sympy.latex(ex) for ex in sympy.solve(e, var)]) sols = "$$" + sols + "$$" if len(sols) == 0: return make_quadratic_eq() return render(e), sols
def get(self): sess = gmemsess.Session(self) # if session is new, user was not logged in, redirect if sess.is_new(): sess['error'] = 'Please log in to view this page.' sess['redirect'] = '/user/map' sess.save() self.redirect('/user/login') return # if username not set in session, user not logged in, redirect if not sess.has_key('username'): sess['error'] = 'Please log in to view this page.' sess['redirect'] = '/user/map' sess.save() self.redirect('/user/login') return if os.environ.get('HTTP_HOST'): base_url = 'http://' + os.environ['HTTP_HOST'] + '/' else: base_url = 'http://' + os.environ['SERVER_NAME'] + '/' # form user data cache name cache_name = 'data_' + sess['userid'] extracted = memcache.get(cache_name) if not extracted: logging.debug('cache miss, populate') # get 5 pages of most recent records and cache surveys = SurveyData.all().filter('username ='******'userid']).order('-timestamp').fetch(PAGE_SIZE*5 + 1) extracted = helper.extract_surveys (surveys) # if values returned, save in cache if surveys is not None: memcache.set(cache_name, extracted) template_values = { 'surveys' : extracted, 'base_url' : base_url } template_values['usermap'] = True path = os.path.join (os.path.dirname(__file__), 'views/map.html') self.response.out.write (helper.render(self, path, template_values))
def get(self): sess = gmemsess.Session(self) # redirect to login page if not logged in if sess.is_new() or not sess.has_key('username'): sess['error'] = 'Please log in to use this feature.' sess['redirect'] = '/admin/create_new_class' sess.save() self.redirect('/user/login') return admin_flag = UserTable().all().filter('ckey =', sess['userid']).get() if not admin_flag.admin: sess['error'] = 'You do not have permission to acces this page' sess.save() self.redirect('/') return path = os.path.join (os.path.dirname(__file__), 'views/new_class.html') self.response.out.write (helper.render(self, path, {}))
def make_rational_poly_simplify(var="x"): """ Generates a rational expression of 4 polynomials, to be simplified. Example: ( (x**2 + 16*x + 60) / (x**2 - 36)) / ( (x**2 - 2*x - 63) / (x**2 - 5*x - 36) x : charector for the variable to be solved for. defaults to random selection from the global list `alpha`. OR a list of possible charectors. A random selection will be made from them. """ if not var: var = random.choice(alpha) elif isinstance(var, list): var = random.choice(var) exclude = [var.upper(), var.lower()] x = sympy.Symbol(var) select = shuffle(range(-10, -1) + range(1, 10))[:6] e1 = sympy.prod([x - i for i in shuffle(select)[:2]]).expand() e2 = sympy.prod([x - i for i in shuffle(select)[:2]]).expand() e3 = sympy.prod([x - i for i in shuffle(select)[:2]]).expand() e4 = sympy.prod([x - i for i in shuffle(select)[:2]]).expand() L = len(set([e1, e2, e3, e4])) e = ((e1 / e2) / (e3 / e4)) s1 = ''.join(["\\frac{", sympy.latex(e1), "}", "{", sympy.latex(e2), "}"]) s2 = ''.join(["\\frac{", sympy.latex(e3), "}", "{", sympy.latex(e4), "}"]) s3 = ''.join(["$$\\frac{", s1, "}", "{", s2, "}$$"]) pieces = str(e.factor()).split("/") try: num, denom = [parse_expr(i).expand() for i in pieces] except: return make_rational_poly_simplify(var) if len(pieces) != 2 or L < 4 or degree(num) > 2 or degree(denom) > 2: return make_rational_poly_simplify(var) return s3, render(num / denom)
def make_rational_poly_simplify(var="x"): """ Generates a rational expression of 4 polynomials, to be simplified. Example: ( (x**2 + 16*x + 60) / (x**2 - 36)) / ( (x**2 - 2*x - 63) / (x**2 - 5*x - 36) x : charector for the variable to be solved for. defaults to random selection from the global list `alpha`. OR a list of possible charectors. A random selection will be made from them. """ if not var: var = random.choice(alpha) elif isinstance(var, list): var = random.choice(var) exclude = [var.upper(), var.lower()] x = sympy.Symbol(var) select = shuffle(range(-10,-1) + range(1,10))[:6] e1 = sympy.prod([x - i for i in shuffle(select)[:2]]).expand() e2 = sympy.prod([x - i for i in shuffle(select)[:2]]).expand() e3 = sympy.prod([x - i for i in shuffle(select)[:2]]).expand() e4 = sympy.prod([x - i for i in shuffle(select)[:2]]).expand() L = len(set([e1, e2, e3, e4])) e = ((e1/e2) / (e3 / e4)) s1 = ''.join(["\\frac{", sympy.latex(e1), "}", "{", sympy.latex(e2), "}"]) s2 = ''.join(["\\frac{", sympy.latex(e3), "}", "{", sympy.latex(e4), "}"]) s3 = ''.join(["$$\\frac{", s1, "}", "{", s2, "}$$"]) pieces = str(e.factor()).split("/") try: num, denom= [parse_expr(i).expand() for i in pieces] except: return make_rational_poly_simplify(var) if len(pieces) !=2 or L < 4 or degree(num) > 2 or degree(denom) > 2: return make_rational_poly_simplify(var) return s3, render(num / denom)
def get(self): try: post = db.get(self.request.get('p')) except: self.redirect('/') return s = self.request.get('s') if s: if s == post.secret: if not post.confirmed_at: post.confirmed_at = datetime.datetime.today() post.put() # send info on how to edit post self.send_information(post) # update twitter taskqueue.add(url='/post/twitter', params={'key': post.key()}) else: logging.warning('Somebody tried to confirm post (key=%s) with incorrect secret (s=%s)', (post.key, s)) return self.redirect('/') else: self.send_confirmation_request(post) self.response.out.write(helper.render('confirm', { 'email': self.request.get('email') }))
def get(self): sess = gmemsess.Session(self) # redirect to login page if not logged in if sess.is_new() or not sess.has_key('username'): sess['error'] = 'Please log in to use this feature.' sess['redirect'] = '/user/delete?key=' + self.request.get('key') sess.save() self.redirect('/user/login') return # check if key set if not self.request.get('key'): sess['error'] = 'No observation was selected.' sess.save() self.redirect('/user/data') return # check valid key try: db_key = db.Key(self.request.get('key')) if db_key.kind() != 'SurveyData': sess['error'] = 'Bad key.' sess.save() self.redirect('/user/data') return except: sess['error'] = 'Bad key.' sess.save() self.redirect('/user/data') return # check if user owns observation observation = db.get(self.request.get('key')) # if no observation exists with key, error if not observation: sess['error'] = 'No observation exists with this key or you do not have permission to delete this observation' sess.save() self.redirect('/user/data') return # if user not have permission, error if observation.username != sess['userid']: sess['error'] = 'No observation exists with this key or you do not have permission to delete this observation' sess.save() self.redirect('/user/data') return # format data... surveys = [] surveys.append(observation) extracted = helper.extract_surveys(surveys) observation = extracted[0] if os.environ.get('HTTP_HOST'): base_url = 'http://' + os.environ['HTTP_HOST'] + '/' else: base_url = 'http://' + os.environ['SERVER_NAME'] + '/' # display delete confirmation page template_values = {'observation': observation, 'base_url':base_url} path = os.path.join (os.path.dirname(__file__), 'views/delete.html') self.response.out.write (helper.render(self, path, template_values))
def get(self): sess = gmemsess.Session(self) # if session is new, user was not logged in, redirect if sess.is_new(): sess['error'] = 'Please log in to view this page.' sess['redirect'] = '/user/data' sess.save() self.redirect('/user/login') return # if username not set in session, user not logged in, redirect if not sess.has_key('username'): sess['error'] = 'Please log in to view this page.' sess['redirect'] = '/user/data' sess.save() self.redirect('/user/login') return if os.environ.get('HTTP_HOST'): base_url = 'http://' + os.environ['HTTP_HOST'] + '/' else: base_url = 'http://' + os.environ['SERVER_NAME'] + '/' # get bookmark bookmark = self.request.get('bookmark') logging.debug(self.request.get('bookmark')) template_values = { 'base_url' : base_url } forward = True page = None # check if page set if self.request.get('page'): page = int(self.request.get('page')) elif not bookmark: page = 1 # fetch cached values if any saved = None extracted = None # form user data cache name cache_name = 'data_' + sess['userid'] # if page set, and page in range, get page for cache if page > 0 and page <=5: saved = memcache.get(cache_name) # if not in cache, try fetching from datastore if not saved: logging.debug('cache miss, populate') # get 5 pages of most recent records and cache surveys = SurveyData.all().filter('username ='******'userid']).order('-timestamp').fetch(PAGE_SIZE*5 + 1) saved = helper.extract_surveys (surveys) # if values returned, save in cache if surveys is not None: memcache.set(cache_name, saved) # if data, setup display if saved: # get page extracted = helper.get_page_from_cache(saved, page, PAGE_SIZE) logging.debug(len(extracted)) # if got page if extracted is not None: if len(extracted) == PAGE_SIZE + 1: template_values['next'] = str(extracted[-1]['realtime']) template_values['nextpage'] = page + 1 extracted = extracted[:PAGE_SIZE-1] # if not on first page, setup back if page > 1: template_values['back'] = str(extracted[0]['realtime']) template_values['backpage'] = page - 1 else: # pages beyond 5th not cached logging.debug('not using cache') # determine direction to retreive records # if starts with '-', going backwards if bookmark.startswith('-'): forward = False bookmark = bookmark[1:] # if bookmark set, retrieve page relative to bookmark if bookmark: # string to datetime code from: # http://aralbalkan.com/1512 m = re.match(r'(.*?)(?:\.(\d+))?(([-+]\d{1,2}):(\d{2}))?$', str(bookmark)) datestr, fractional, tzname, tzhour, tzmin = m.groups() if tzname is None: tz = None else: tzhour, tzmin = int(tzhour), int(tzmin) if tzhour == tzmin == 0: tzname = 'UTC' tz = FixedOffset(timedelta(hours=tzhour, minutes=tzmin), tzname) x = datetime.datetime.strptime(datestr, "%Y-%m-%d %H:%M:%S") if fractional is None: fractional = '0' fracpower = 6 - len(fractional) fractional = float(fractional) * (10 ** fracpower) dt = x.replace(microsecond=int(fractional), tzinfo=tz) if forward: surveys = SurveyData.all().filter('username ='******'userid']).filter('timestamp <', dt).order('-timestamp').fetch(PAGE_SIZE+1) # if PAGE_SIZE + 1 rows returned, more pages to display if len(surveys) == PAGE_SIZE + 1: template_values['next'] = str(surveys[-2].timestamp) if page is not None: logging.debug(page) template_values['nextpage'] = page + 1 surveys = surveys[:PAGE_SIZE] # if bookmark set, assume there was a back page template_values['back'] = '-'+str(surveys[0].timestamp) if page is not None: template_values['backpage'] = page - 1 else: surveys = SurveyData.all().filter('username ='******'userid']).filter('timestamp >', dt).order('timestamp').fetch(PAGE_SIZE+1) # if PAGE_SIZE + 1 rows returned, more pages to diplay if len(surveys) == PAGE_SIZE + 1: template_values['back'] = '-'+str(surveys[-2].timestamp) if page is not None: template_values['backpage'] = page - 1 surveys = surveys[:PAGE_SIZE] # if bookmark set, assume there is a next page template_values['next'] = str(surveys[0].timestamp) if page is not None: template_values['nextpage'] = page + 1 # reverse order of results since they were returned backwards by query surveys.reverse() else: # if no bookmark set, retrieve first records surveys = SurveyData.all().filter('username ='******'userid']).order('-timestamp').fetch(PAGE_SIZE+1) if len(surveys) == PAGE_SIZE + 1: template_values['next'] = str(surveys[-2].timestamp) template_values['nextpage'] = 2 surveys = surveys[:PAGE_SIZE] extracted = helper.extract_surveys (surveys) template_values['surveys'] = extracted template_values['userdata'] = True path = os.path.join (os.path.dirname(__file__), 'views/user_data.html') self.response.out.write (helper.render(self, path, template_values))
def main(): # cap_img = cv2.imread('Images/Test_Markers/7.jpeg') camera_parameters, dist = he.camera_calibration('Images/Calibration') dir_name = os.getcwd() obj = OBJ(os.path.join(dir_name, 'Models/fox/fox.obj'), swapyz=True) model_list = he.create_list('Images') model_keypoints = he.find_model_keypoints(model_list) # print('b') if not args.problem: cap = cv2.VideoCapture(0) while True: # read the current frame ret, frame = cap.read() if not ret: print("Unable to capture video") return cnt = None temp = he.find_marker(he.convert2grayscale(frame), model_list, model_keypoints, camera_parameters, dist) if temp is not None: cnt, homographies, models = temp # compute Homography if enough matches are found if cnt is not None: # if a valid homography matrix was found render cube on model plane for x, h, m in zip(cnt, homographies, models): try: projection = he.projection_matrix(camera_parameters, h) frame = he.render(frame, obj, projection, m, False) # rect = cnt[0] # pseudo_model = h.crop_img(frame.copy(), rect) # r_p, c_p = pseudo_model.shape[0], pseudo_model.shape[1] # pts = [x[0] for x in rect] # pts2 = [[0, 0], [0, r_p], [c_p, r_p], [c_p, 0]] # projection = cv2.getPerspectiveTransform(pts, pts2) break except: pass # draw first 10 matches. if args.rectangle: if cnt is not None: for x in cnt: x = he.convert_to_ndarray(x) cv2.drawContours(frame, [x], -1, (0, 255, 0), 3) points_dum = np.array([[[0, 0, 0]], [[100, 0, 0]], [[0, 100, 0]], [[0, 0, 100]]]) points_dum = np.float32( [np.float32(p) for p in points_dum]) # print(axis) newpts = cv2.perspectiveTransform( points_dum, projection) cap_img = he.draw( frame, newpts[0][0], [newpts[1][0], newpts[2][0], newpts[3][0]]) break # show result else: print('No marker found') cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() elif args.problem: # print('c') no = input('Enter image no. to process: ') # img nos - cap_img = cv2.imread('Images/Test_Markers/Prob2/' + str(no) + '.jpeg') camera_parameters, dist = he.camera_calibration('Images/Calibration') model_list = he.create_list('Images') model_keypoints = he.find_model_keypoints(model_list) cnt = None temp = he.find_marker(he.convert2grayscale(cap_img), model_list, model_keypoints, camera_parameters, dist) if temp is not None: cnt, homographies, models = temp cnt = [cnt[1], cnt[0]] homographies = [homographies[1], homographies[0]] models = [models[1], models[0]] if cnt is not None: if (len(cnt) == 2): ro1, co1 = models[0].shape ro2, co2 = models[1].shape proj1 = he.projection_matrix(camera_parameters, homographies[0]) proj2 = he.projection_matrix(camera_parameters, homographies[1]) points1 = np.array([[[co1 / 2, ro1 / 2, 0]]]) points1 = np.float32([np.float32(p) for p in points1]) origin1 = np.array( cv2.perspectiveTransform(points1, proj1)[0][0]) points2 = np.array([[[0, 0, 0]], [[100, 0, 0]], [[0, 100, 0]], [[0, 0, 100]]]) points2 = np.float32([np.float32(p) for p in points2]) axes2 = cv2.perspectiveTransform(points2, proj2) origin2 = axes2[0][0] ptz = axes2[3][0] ###### if args.rectangle: projection = proj1 points_dum = np.array([[[0, 0, 0]], [[100, 0, 0]], [[0, 100, 0]], [[0, 0, 100]]]) points_dum = np.float32( [np.float32(p) for p in points_dum]) newpts = cv2.perspectiveTransform(points_dum, projection) cap_img = he.draw( cap_img, newpts[0][0], [newpts[1][0], newpts[2][0], newpts[3][0]]) projection = proj2 points_dum = np.array([[[0, 0, 0]], [[100, 0, 0]], [[0, 100, 0]], [[0, 0, 100]]]) points_dum = np.float32( [np.float32(p) for p in points_dum]) newpts = cv2.perspectiveTransform(points_dum, projection) cap_img = he.draw( cap_img, newpts[0][0], [newpts[1][0], newpts[2][0], newpts[3][0]]) ###### origin2 = np.array(origin2) origin1_x = origin1[0] origin1_y = origin1[1] origin2_x = origin2[0] ptz_x = ptz[0] origin2_y = origin2[1] ptz_y = ptz[1] moving_slope = (ptz_y - origin2_y) / (ptz_x - origin2_x) # moving_slope = (origin2_y-origin1_y)/(origin2_x-origin1_x) moving_positive = origin1 + STEP_SIZE * \ np.array([1, moving_slope]) moving_negative = origin1 - STEP_SIZE * \ np.array([1, moving_slope]) distance_pos = np.linalg.norm(origin2 - moving_positive) distance_neg = np.linalg.norm(origin2 - moving_negative) if (distance_pos < distance_neg): counter = 0 old_distance = math.inf while True: print('Slope:' + str(moving_slope)) frame = cap_img.copy() moving_positive = origin1 + counter * STEP_SIZE * \ np.array([1, moving_slope]) new_distance = np.linalg.norm(origin2 - moving_positive) print('new:' + str(new_distance)) print('old:' + str(old_distance)) if (new_distance > old_distance): print('break') break old_distance = new_distance counter += 1 shift = moving_positive - origin1 frame = he.render(frame, obj, proj1, models[0], False, shift[0], shift[1]) print(shift) cv2.imshow('Moving_obj', frame) cv2.waitKey(1) else: counter = 0 old_distance = math.inf while True: print('Slope:' + str(moving_slope)) frame = cap_img.copy() moving_negative = origin1 - counter * STEP_SIZE * \ np.array([1, moving_slope]) new_distance = np.linalg.norm(origin2 - moving_negative) print('new:' + str(new_distance)) print('old:' + str(old_distance)) if (new_distance > old_distance): print('break') break old_distance = new_distance counter += 1 shift = moving_negative - origin1 frame = he.render(frame, obj, proj1, models[0], False, shift[0], shift[1]) print(shift) cv2.imshow('Moving_obj', frame) cv2.waitKey(1) else: print('Less than 2 Markers Found') cv2.destroyAllWindows() return 0
def get(self): path = os.path.join (os.path.dirname(__file__), 'views/about.html') template_values = { 'about' : True } self.response.out.write (helper.render(self, path, template_values))
import bpy import helper helper.setup() # Create scene. cube = bpy.data.objects['Cube'] # Make the animation 3 seconds. scene = bpy.context.scene scene.render.fps = 30 scene.frame_start = 1 scene.frame_end = 90 # Create first key frame. cube.location = [-3, 0, 0] cube.keyframe_insert(data_path="location", frame=1) cube.location = [3, 0, 0] cube.keyframe_insert(data_path="location", frame=90) #bpy.ops.anim.keyframe_insert_menu(type='Rotation') helper.render()
def run(self, edit): data = helper.render(self.view) x = helper.newViewWithContent(data)
def get(self): sess = gmemsess.Session(self) # setup redirect strings bookmark = self.request.get('bookmark') page = self.request.get('page') data_redirect_str = '/admin/data' detail_redirect_str = '/admin/detail?key=' + self.request.get('key') if bookmark and len(bookmark) != 0: data_redirect_str += '?bookmark=' + str(bookmark) detail_redirect_str += '&bookmark=' + str(bookmark) if page and len(page) != 0: data_redirect_str += '&page=' + str(page) detail_redirect_str += '&page=' + str(page) elif page and len(page) != 0: data_redirect_str += '?page=' + str(page) detail_redirect_str += '&page=' + str(page) logging.debug('data direct: ' + data_redirect_str) logging.debug('detail direct: ' + detail_redirect_str) # redirect to login page if not logged in if sess.is_new() or not sess.has_key('username'): sess['error'] = 'Please log in to use this feature.' #sess['redirect'] = '/admin/detail?key=' + self.request.get('key') sess['redirect'] = detail_redirect_str sess.save() self.redirect('/user/login') return logging.debug('key: ' + str(self.request.get('key'))) logging.debug('date: ' + str(self.request.get('date'))) # check if key set or date set if not self.request.get('key') and not self.request.get('date'): sess['error'] = 'No observation was selected.' sess.save() self.redirect(data_redirect_str) return # check valid key db_key = None try: if self.request.get('key'): db_key = db.Key(self.request.get('key')) if db_key.kind() != 'SurveyData': sess['error'] = 'Bad key.' sess.save() self.redirect(data_redirect_str) return else: m = re.match(r'(.*?)(?:\.(\d+))?(([-+]\d{1,2}):(\d{2}))?$', str(self.request.get('date'))) datestr, fractional, tzname, tzhour, tzmin = m.groups() if tzname is None: tz = None else: tzhour, tzmin = int(tzhour), int(tzmin) if tzhour == tzmin == 0: tzname = 'UTC' tz = FixedOffset(timedelta(hours=tzhour, minutes=tzmin), tzname) x = datetime.datetime.strptime(datestr, "%Y-%m-%d %H:%M:%S") if fractional is None: fractional = '0' fracpower = 6 - len(fractional) fractional = float(fractional) * (10 ** fracpower) dt = x.replace(microsecond=int(fractional), tzinfo=tz) db_key = SurveyData().all().filter('timestamp =', dt).key() except: sess['error'] = 'Bad key.' sess.save() self.redirect(data_redirect_str) return # check if user owns observation observation = db.get(db_key) # if no observation exists with key, error if not observation: sess['error'] = 'No observation exists with this key or you do not have permission to delete this observation' sess.save() self.redirect(data_redirect_str) return # if user not have permission, error admin_flag = UserTable().all().filter('ckey =', sess['userid']).get() if not admin_flag.admin: sess['error'] = 'No observation exists with this key or you do not have permission to delete this observation' sess.save() self.redirect(data_redirect_str) return # format data... surveys = [] surveys.append(observation) extracted = helper.extract_surveys(surveys) observation = extracted[0] if os.environ.get('HTTP_HOST'): base_url = 'http://' + os.environ['HTTP_HOST'] + '/' else: base_url = 'http://' + os.environ['SERVER_NAME'] + '/' # display delete confirmation page template_values = {'observation': observation, 'base_url':base_url} template_values['current_bookmark'] = bookmark template_values['current_page'] = page path = os.path.join (os.path.dirname(__file__), 'views/quarantine_observation.html') self.response.out.write (helper.render(self, path, template_values))
def handle(self): path = os.path.join (os.path.dirname(__file__), 'views/new_user.html') self.response.out.write (helper.render(self, path, {}))