Example #1
0
 def POST(self, id_):
     user = self.getcurrentuser()
     account = web.input().get('account')
     password = web.input().get('password')
     
     try:
         bk = Book.get_by_id(int(id_))
     except:
         bk = None
     if not bk:
         return "Not exist the book!<br />"
     
     subs_info = user.subscription_info(bk.title)
     if subs_info:
         #任何一个留空则删除登陆信息
         if not account or not password:
             subs_info.delete()
         else:
             subs_info.account = account
             subs_info.password = password
             subs_info.put()
     elif account and password:
         subs_info = SubscriptionInfo(account=account, user=user, title=bk.title)
         subs_info.put() #先保存一次才有user信息,然后才能加密
         subs_info.password = password
         subs_info.put()
         
     raise web.seeother('/my')
Example #2
0
 def POST(self, path):
     i = web.input(_method='post')
     i = web.storage(helpers.unflatten(i))
     i.key = path
     
     _ = web.storage((k, i.pop(k)) for k in i.keys() if k.startswith('_'))
     action = self.get_action(_)
     comment = _.get('_comment', None)
     
     for k, v in i.items():
         i[k] = self.trim(v)
         
     p = web.ctx.site.get(path) or web.ctx.site.new(path, {})
     p.update(i)
     
     if action == 'preview':
         p['comment_'] = comment
         return render.editpage(p, preview=True)
     elif action == 'save':
         try:
             p._save(comment)
             path = web.input(_method='GET', redirect=None).redirect or web.changequery(query={})
             raise web.seeother(path)
         except (ClientException, db.ValidationException), e:            
             add_flash_message('error', str(e))
             p['comment_'] = comment                
             return render.editpage(p)
Example #3
0
 def POST(self):
     print web.input()
     if web.input().ip != '':
         ip = web.input().ip
     else:
         ip = web.ctx.ip
     return self.renderPage(ip)
Example #4
0
    def POST(self):
        if session.login != True:
            return render.message(site_prefix, "未登录", "您尚未登录", "", "_parent", "登录界面")
        seedid = web.input().productid
        productname = web.input().productname
        brand = web.input().brand   

        db = MySQLdb.connect(host = DB_HOST, user = DB_USER, passwd = DB_PASSWORD, db = DB_NAME, charset='utf8')
        cursor = db.cursor()

        #cmd = "SELECT id FROM type WHERE name='%s';" % producttype
        #cursor.execute(cmd)
        #producttype = cursor.fetchone()[0]             

        #cmd = "SELECT * FROM devices WHERE id='%s' and brand='%s';" % (seedid, brand)
        #cursor.execute(cmd)
        #rows = cursor.fetchall()

        #if productid != session.oldid and len(rows) != 0:
        #    db.close()
        #    return render.message(site_prefix, "修改失败", "产品唯一标识重复", "modify?id=" + str(session.oldid), "main", "重新修改")

        #else:
        #now = time.strftime("%Y-%m-%d %H:%M:%S")
        cmd = "UPDATE devices SET seedid = '%s', name = '%s', brand = '%s' WHERE id = '%s'" % (seedid, productname, brand, session.oldid) 
        cursor.execute(cmd)
        db.close()
    

        return render.message(site_prefix, "修改成功", "产品信息修改成功", "manage", "main", "产品管理")   
Example #5
0
    def POST(self):
        context = web.input().context.encode('utf-8')
        taskid = web.input().taskid
        file_name = web.input().file_name

        # Only segement the title and keyword
        seg_content = []
        lines = context.split('\r')
        for line in lines:
            tmp = line.split('\t')
            seg_content.append(tmp[1])
            seg_content.append(tmp[2])

        results = get_seg_result('\t'.join(seg_content), keep_return=True)
        newcontent = assemble_result(context, results['filtered_result'], taskid=taskid, file_name=file_name)

        # log_message('Task ' + taskid + ' is excecuted (post), result: ' + '<br /> '.join(newcontent))

        # submit to server
        try:
            # payload = urllib.urlencode([('seg_result', ''.join(newcontent).encode('utf-8')), ('taskid', taskid), ])
            # req = urllib2.urlopen(SUBMIT_RESULT_URL, payload)
            # log_message('submit task ' + str(taskid) + ' to server' + req.read())
            from sae.storage import Bucket
            bucket = Bucket('mozillaup')
            bucket.put_object(file_name + '/' + str(taskid), ''.join(newcontent).encode('utf-8'))
            # log_message('submit task ' + str(taskid) + ' to bucket')
        except Exception, ex:
            print ex
            result = 'Encounter an error when submit task' + type(ex).__name__ + ' ' + str(ex.args)
            log_message(result)
Example #6
0
 def SaveToInstapaper(self, user, action, orgUrl):
     web.header('Content-type', "text/html; charset=utf-8")
     
     T_INFO = u"""<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
         <title>%s</title></head><body><p style="text-align:center;font-size:1.5em;">%s</p></body></html>"""
     if not user.instapaper_username or not user.instapaper_password:
         info = T_INFO % ('No authorize info', 'Instapaper username and password have to provided fistly!<br/>Please fill them in your KindleEar application.')
         return info.encode('utf-8')
     
     title = web.input().get('t', '')
     name = web.input().get("n", '')
     if user.instapaper_username != name:
         info = T_INFO % ('Action rejected', 'Username not match!<br/>KindleEar refuse to execute your command.')
         return info.encode('utf-8')
         
     opener = URLOpener()
     password = ke_decrypt(user.instapaper_password, user.secret_key or '')
     apiParameters = {'username': user.instapaper_username, 'password':password, 'title':title.encode('utf-8'), 
                     'selection':'KindleEar', 'url':orgUrl}
     ret = opener.open(INSTAPAPER_API_ADD_URL, data=apiParameters)
     if ret.status_code in (200, 201):
         info = _("'%s'<br/><br/>Saved to your Instapaper account.") % title
         info += '<br/><p style="text-align:right;color:red;">by KindleEar &nbsp;</p>'
         info = T_INFO % ('Saved to Instapaper', info)
     elif ret.status_code == 403:
         info = _("Failed save to Instapaper<br/>'%s'<br/><br/>Reason : Invalid username or password.") % title
         info += '<br/><p style="text-align:right;color:red;">by KindleEar &nbsp;</p>'
         info = T_INFO % ('Failed to save', info)
     else:
         info = _("Failed save to Instapaper<br/>'%s'<br/><br/>Reason : Unknown(%d).") % (title, ret.status_code)
         info += '<br/><p style="text-align:right;color:red;">by KindleEar &nbsp;</p>'
         info = T_INFO % ('Failed to save', info)
     
     return info.encode('utf-8')
     
Example #7
0
 def GET(self):
     action = web.input().get('act')
     username = web.input().get("u")
     url = web.input().get("url")
     if not username or not url or not action:
         return "Some parameter is missing or wrong!<br />"
     
     user = KeUser.all().filter("name = ", username).get()
     if not user or not user.kindle_email:
         return "User not exist!<br />"
     
     #global log
     
     url = urllib.unquote(url)
     
     #debug_mail(content)
     
     if action in ('evernote', 'wiz'): #保存至evernote/wiz
         return self.SaveToEvernoteWiz(user, action, url)    
     elif action == 'pocket': #保存到pocket
         return self.SaveToPocket(user, action, url)
     elif action == 'instapaper':
         return self.SaveToInstapaper(user, action, url)
     else:
         return "Unknown action type : %s !" % action
Example #8
0
	def GET(self):
		#theme可选项:light|dark
		theme=web.input().get("theme","light")
		#output可选项:html|json
		output=web.input().get("output","html")
		#类型的可选项:model|automate
		t=web.input().get("type","model")
		import os
		l=os.listdir(cwd('static','files'))
		ext=".json"
		if t=="automate":
			ext=".txt"
		l= filter(lambda x:x.endswith(ext),l)
		import base64,urllib2
		#base64解码
		l= map(lambda x: to_unicode(base64.b64decode(x[:-len(ext)])),l)
		#为了能在html和json中显示
		l= map(lambda x: (x,urllib2.quote(x.encode("utf-8"))),l)
		if output=='html':
			static=cwd("static")
			render=web.template.render(cwd('templates'),globals=locals())
			return render.list()
		elif output=='json':
			import json
			web.header('Content-Type', 'application/json')
			return json.dumps(l)
Example #9
0
    def SaveToPocket(self, user, action, orgUrl):
        INSTAPAPER_API_ADD_URL = 'https://www.instapaper.com/api/add'

        web.header('Content-type', "text/html; charset=utf-8")
        
        T_INFO = u"""<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
            <title>%s</title></head><body><p style="text-align:center;font-size:1.5em;">%s</p></body></html>"""
        if not user.pocket_access_token:
            info = T_INFO % ('Pocket unauthorized', 'Unauthorized Pocket!<br/>Please authorize your KindleEar application firstly.')
            return info.encode('utf-8')
            
        title = web.input().get('t', '')
        tkHash = web.input().get("h", '')
        if hashlib.md5(user.pocket_acc_token_hash).hexdigest() != tkHash:
            info = T_INFO % ('Action rejected', 'Hash not match!<br/>KindleEar refuse to execute your command.')
            return info.encode('utf-8')
            
        pocket = Pocket(POCKET_CONSUMER_KEY)
        pocket.set_access_token(user.pocket_access_token)
        try:
            item = pocket.add(url=orgUrl, title=title, tags='KindleEar')
        except Exception as e:
            info = T_INFO % ('Failed to save', _('Failed save to Pocket.<br/>') + str(e))
        else:
            info = _("'%s'<br/><br/>Saved to your Pocket account.") % title
            info += u'''<br/><p style="text-align:right;color:red;">by KindleEar &nbsp;</p>
                <br/><hr/><p style="color:silver;">'''
            info += _('See details below:<br/><br/>%s') % repr(item)
            info = T_INFO % ('Saved to pocket', info)
        
        return info.encode('utf-8')
Example #10
0
    def POST(self):

        action, prop1, prop2 = web.input().action, web.input().prop1, web.input().prop2

        username = session.username

        if action == "unfavourite":
            user = prop1

            # Find the user id of the favourite
            user_id = db.select("users", where="username=$user", vars=locals())[0]["id"]

            # load favourites list from database and unpickle
            favouriteslist = pickle.loads(
                str(db.select("users", where="username=$username", vars=locals())[0]["favourites"])
            )

            # Remove user id from favourite
            favouriteslist.remove(user_id)

            # Update the session
            session.favourites = favouriteslist

            # Pickle favourites list
            pickledlist = pickle.dumps(favouriteslist)

            # Update database with new favourites list
            db.update("users", where="username=$username", favourites=pickledlist, vars=locals())

        else:
            print "Unrecognised action"
Example #11
0
    def POST(self):
        username, password = web.input().username, web.input().password

        # retreive user's salt
        try:
            salt = db.select("users", where="username=$username", vars=locals())[0]["salt"]
        except:
            return homepage_render.login("Login Error", session.loggedin)

        password = check_password(password, salt)

        # hash password with salt
        check = db.select("users", where="username=$username AND passwordhash=$password", vars=locals())

        if check:
            favouriteslist = pickle.loads(
                str(db.select("users", where="username=$username", vars=locals())[0]["favourites"])
            )
            favouritesusernamelist = []

            for favourite in favouriteslist:
                favourite = db.select("users", where="id=$favourite", vars=locals())[0]["username"]
                favouritesusernamelist.append(favourite)

            print favouritesusernamelist
            session.favourites = favouritesusernamelist
            session.loggedin = True
            session.username = username
            raise web.seeother("/")
        else:
            return homepage_render.login("Login Failed", session.loggedin)
Example #12
0
  def POST( self, get_string='' ):
    log.loggit( 'update.POST()' )

    # Must be a matching user or administrator to update
    wputil.must_match_username_or_admin( web.input()['username'] )

    # Catch the cancel button
    if  web.input().has_key('cancel'):
      if wputil.is_admin():
        raise web.seeother('../')
      else:
        raise web.seeother('../../')

    # Validate the form
    if wputil.is_admin():
      f = admin_account_form()
    else:
      f = account_form()
    if not f.validates():
      return { 'status' : 'error',
               'message' : 'Verify all information has been provided correctly.',
               'form' : f }

    # update the account in the database
    adb = accountdb.AccountDB()
    try:
      account = adb.update_account( f.d )
    except:
      return { 'status' : 'error',
               'message' : 'An error occurred updating the account.',
               'form' : f }

    raise web.seeother( '../review/%s' % (account['username']) )
Example #13
0
 def GET(self):
     triples = self._triples(web.input().get('url',''))
     callback = web.input().get('callback')
     if callback:
         return "%s(%s)" % (callback, renderer.response(triples))
     else:
         return renderer.response(triples)
Example #14
0
 def POST(self):
     name, passwd = web.input().get('u'), web.input().get('p')
     if name.strip() == '':
         tips = u"用户名为空! "
         return jjenv.get_template("login.html").render(nickname='',
             title='Login',tips=tips)
     elif len(name) > 25:
         tips = u"用户名限制为25个字符! "
         return jjenv.get_template("login.html").render(nickname='',
             title='Login',tips=tips,username=name)
     elif '<' in name or '>' in name or '&' in name:
         tips = u"用户名包含非法字符! "
         return jjenv.get_template("login.html").render(nickname='',
             title='Login',tips=tips)
     
     pwdhash = hashlib.md5(passwd).hexdigest()
     u = KeUser.all().filter("name = ", name).filter("passwd = ", pwdhash).get()
     if u:
         session.login = 1
         session.username = name
         if u.expires: #用户登陆后自动续期
             u.expires = datetime.datetime.utcnow()+datetime.timedelta(days=180)
             u.put()
         raise web.seeother(r'/')
     else:
         tips = u"用户名不存在或密码错误! "
         session.login = 0
         session.username = ''
         session.kill()
         return jjenv.get_template("login.html").render(nickname='',
             title='Login',tips=tips,username=name)
Example #15
0
    def GET(self):
        es = Elasticsearch(conf['fulltext']['serviceUrl'])
        if web.input(wildcard_query=None).wildcard_query:
            query = {
                "wildcard": {
                    "_all": web.input().query
                }
            }
            self.set_wildcard_query(True)
        else:
            query = {
                "multi_match": {
                    "query": web.input().query,
                    "operator": "and",
                    "fields": ["text", "pageName", "tags"]
                }
            }
            self.set_wildcard_query(False)
        res = es.search(index=conf['fulltext']['indexName'],
                        body={"query": query,
                              "fields": ["pageName", "path", "fsPath", "text"]})
        rows = []
        for a in res['hits']['hits']:
            fields = a['fields']

            fs_path = os.path.normpath('%s/%s.md' % (self.data_dir, fields['path'][0]))
            page_chapters, h1 = extract_description(fs_path)
            rows.append({
                'h1': h1 if h1 else fields['path'][0],
                'file': fields['path'][0],
                'chapters': page_chapters
            })
        values = dict(query=web.input().query, ans=rows)
        return self._render('search.html', values)
Example #16
0
	def POST(self):
		language = web.input(language='')['language']
		run = web.input(run='')['run']
		theinput = web.input(input='')['input']

		# if incorrect run id, exit
		if re.match('^[a-z]{5,12}$', run) == None: return 'incorrect run id'

		workdir = 'work/'

		# first state of result
		output = 'unknown language'

		if language == 'cpp':
			output = utils.run_cpp(workdir, run, theinput)
		elif language == 'java':
			output = utils.run_java(workdir, run, theinput)
		elif language == 'csharp':
			output = utils.run_csharp(workdir, run, theinput)

		if output[0] == 0:
			return json.dumps(
				{'status': 'OK', 'output': output[1] })

		return json.dumps(
			{'status': 'RE', 'output': ('Runtime error %s \n %s' % (output[0], output[1])) })
Example #17
0
 def GET(self):
     user = self.getcurrentuser()
     delurlid = web.input().get('delurlid')
     delwlist = web.input().get('delwlist')
     if delurlid:
         try:
             delurlid = int(delurlid)
         except:
             pass
         else:
             flt = UrlFilter.get_by_id(delurlid)
             if flt:
                 flt.delete()
     if delwlist:
         try:
             delwlist = int(delwlist)
         except:
             pass
         else:
             wlist = WhiteList.get_by_id(delwlist)
             if wlist:
                 wlist.delete()
     return jjenv.get_template('advsetting.html').render(nickname=session.username,
         title="Advanced Setting",current='advsetting',user=user,
         urlfilters=UrlFilter.all(),whitelists=WhiteList.all())
Example #18
0
 def POST(self, verType):
     INSTAPAPER_API_AUTH_URL = "https://www.instapaper.com/api/authenticate"
     web.header('Content-Type', 'application/json')
     
     respDict = {'status':'ok', 'correct':0}
     if verType.lower() != 'instapaper':
         respDict['status'] = _('Request type[%s] unsupported') % verType
         return json.dumps(respDict)
     
     user = self.getcurrentuser()
     
     username = web.input().get('username', '')
     password = web.input().get('password', '')
     opener = URLOpener()
     apiParameters = {'username': username, 'password':password}
     ret = opener.open(INSTAPAPER_API_AUTH_URL, data=apiParameters)
     if ret.status_code in (200, 201):
         respDict['correct'] = 1
     elif ret.status_code == 403:
         respDict['correct'] = 0
     else:
         respDict['status'] = _("The Instapaper service encountered an error. Please try again later.")
     
     return json.dumps(respDict)
     
Example #19
0
	def POST(self):
		source = web.input(source='')['source']
		language = web.input(language='')['language']
		run = web.input(run='')['run']

		# if incorrect run id, regenerate it
		if re.match('^[a-z]{5,12}$', run) == None: run = utils.genstr(12)

		workdir = 'work/'

		# first state of result
		result = 'unknown language'

		if language == 'cpp':
			result = utils.compile_cpp(workdir, run, source)
		elif language == 'java':
			result = utils.compile_java(workdir, run, source)
		elif language == 'csharp':
			result = utils.compile_csharp(workdir, run, source)

		if result == None:
			return json.dumps(
				{'status': 'OK', 'message': 'Successfully compiled.', 'run': run })

		return json.dumps(
			{'status': 'CE', 'message': result, 'run': run })
Example #20
0
 def GET(self):
     self.login_required("admin")
     # 可以修改UrlEncoding,如果chardet自动检测的编码错误的话
     action = web.input().get("action")
     if action == "modurlenc":
         id = int(web.input().get("id", 0))
         feedenc = web.input().get("feedenc")
         pageenc = web.input().get("pageenc")
         urlenc = UrlEncoding.get_by_id(id)
         if urlenc:
             if feedenc:
                 urlenc.feedenc = feedenc
             if pageenc:
                 urlenc.pageenc = pageenc
             urlenc.put()
     elif action == "delurlenc":
         id = int(web.input().get("id", 0))
         urlenc = UrlEncoding.get_by_id(id)
         if urlenc:
             urlenc.delete()
     return self.render(
         "dbviewer.html",
         "DbViewer",
         books=Book.all(),
         users=KeUser.all(),
         feeds=Feed.all().order("book"),
         urlencs=UrlEncoding.all(),
     )
Example #21
0
 def GET(self):
     global project_name
     global case_name
     gl.GL_WEBINPUT=web.input()
     print web.input()
     taskid=gl.GL_WEBINPUT.taskid
     project_name=gl.GL_DB.query('SELECT productline_name from productline LEFT JOIN tasks on productline.id=tasks.productid where taskid='+taskid)
     for i in project_name:
         project_name=i.productline_name
     case_name=gl.GL_DB.query('SELECT casename from cases LEFT JOIN tasks on cases.caseid=tasks.caseid where taskid='+taskid)
     for i in case_name:
         case_name=i.casename
     path = sys.path[0]
     file_path = path+"/tests/"+project_name+'/'+case_name+'.py'
     file_path=file_path.replace('\\',r'\\').replace('/',r'\\')
     print file_path
     print os.path.exists(file_path)
     file_object = open(file_path, 'r+')
     try:
         all_text = file_object.read()
         print "hohohohohohohoho"
         print repr(all_text)
     finally:
         file_object.close()
         return render.Case_editor(all_text,project_name,case_name)
Example #22
0
 def POST(self):
     form = novel_form() 
     if not form.validates(web.input(_method="POST")): 
         return render_to_response("admin/add_novel", {
             "form": form,
         })
     else:
         args = web.input(_method="post", rid=None)
         next = "/tuoshui_admin/checkall"
         if args.rid:
             next = "/tuoshui_admin/checkall_recommends"
         del args.rid
         # 获得type
         args.type = get_type_by_url(args.url)
         if not args.type:
             return "type_error"
         ret = self.db.add_novel(args)
         if ret[0] is True:
             rid = web.input(_method="get", rid=None).rid
             # 修改推荐小说的状态
             if rid:
                 self.db.update_recommend_status(rid)
             raise web.seeother(next)
         else:
             return ret
Example #23
0
    def POST(self):
        title = web.input().title
        tags = web.input().tags.split()
        mdName = web.input().filename
        mdSummary = web.input().summary
        fileSrc = web.input().mdfile.decode('utf8')

        newPost = Post(
            title=title,
            upload=datetime.now(),
            modified=datetime.now(),
            summary=mdSummary,
            filename=mdName
        )
        web.ctx.orm.add(newPost)
        web.ctx.orm.flush()

        for tag in tags:
            checkTag = web.ctx.orm.query(Tag).filter_by(name=tag).all()
            if not checkTag:
                newTags = Tag(name=tag)
                web.ctx.orm.add(newTags)
                web.ctx.orm.flush()

            newPost.tags.append(newTags)

        fout = open('articles/'+mdName, 'w')
        fout.write(fileSrc)
        fout.close()
        return json.dumps({
            'success': True
        })
Example #24
0
 def POST(self):
     print web.input()
     userID = web.input()["userID"]
     matchID = web.input()["matchID"]
     message = web.input()["message"]
     usersList[matchID].addMessage(userID, message)
     print userID, matchID, message
Example #25
0
 def POST(self):
     username, password = web.input().username, web.input().password
     web.ctx.session.login, web.ctx.session.uid = models.checkAdmin(username, password)
     if web.ctx.session.login > 0:
         return "login succeed."
     else:
         return "username or password error"
Example #26
0
    def modify_post(self, board_name, board_id, current_uid = -1):
        board_info = board.get_board_info(board_id)
        if not acl.is_allowed('board', board_id, current_uid, 'modify'):
            return util.render().error(error_message=_('NO_PERMISSION'), help_context='error')
        data = web.input()
        comment = 1 if data.has_key('commentable') else 0
        write_by_other = 1 if data.has_key('writable') else 0
        indexable = 1 if data.has_key('indexable') else 0
        show_avatar = 1 if data.has_key('show_avatar') else 0

        owner_uid = user._get_uid_from_username(web.input().owner)
        if owner_uid < 0:
            return util.render().error(error_message=_('NO_SUCH_USER_FOR_BOARD_ADMIN'), help_context='error')

        board_info = dict(path = data.path, name = data.name,
                owner = owner_uid, board_type = int(data.type),
                can_comment = comment, can_write_by_other = write_by_other,
                indexable = indexable, show_avatar = show_avatar,
                stylesheet = data.stylesheet,
                description = data.description,
                cover = data.information)
        result = board.board_edit(current_uid, board_id, board_info)
        if result[0] == False:
            return util.render().error(error_message = result[1], help_context='error')
        else:
            raise web.seeother(util.link('%s') % result[1])
Example #27
0
    def POST(self, selector):

        try:
            assert selector != 'software'
            if selector == 'publicdomain':
                lclass = cc.license.selectors.choose('zero')
            else:
                lclass = cc.license.selectors.choose(selector)
        except:
            return api_exceptions.invalidclass()

        if not web.input().get('answers'):
            return api_exceptions.missingparam('answers')

        try:
            answers_xml = web.input().get('answers')
            if selector == 'publicdomain':
                answers_xml = answers_xml.replace(
                    '<license-publicdomain>',
                    '<license-zero>').replace(
                    '</license-publicdomain>',
                    '</license-zero>')
            
            # parse the answers argument into an xml tree
            answers = ET.parse(StringIO(answers_xml))
            
        except ET.XMLSyntaxError, e:
            return api_exceptions.invalidanswer()
Example #28
0
 def POST(self, path):
     if path == '/multipart':
         i = web.input(file={})
         return i.file.value
     else:
         i = web.input()
         return repr(dict(i)).replace('u','')
Example #29
0
    def write_post(self, board_name, board_id, current_uid = -1):
        a = dict(title = web.input().title, body = web.input().content)
        board_info = board.get_board_info(board_id)
        ret = article.write_article(current_uid, board_id, a)
        if ret[0] == True:
            user.update_unreaded_articles_board(current_uid, board_id)
            user.read_article(current_uid, ret[1])

            fs = web.ctx.get('_fieldstorage')
            try:
                if fs.has_key('new_attachment'):
                    new_attachment = fs['new_attachment']
                    if type(new_attachment) == list:
                        for f in new_attachment:
                            attachment.add_attachment(ret[1], f.filename, f.value)
                    else:
                        try:
                            attachment.add_attachment(ret[1], new_attachment.filename, new_attachment.value)
                        except:
                            pass
            except:
                pass
            url = util.link('/%s/+read/%s' % (board_name, ret[1]))
            raise web.seeother(url)
        else:
            return util.render().error(error_message = ret[1], help_context='error')
Example #30
0
 def POST(self):
     name, passwd = web.input().get("u"), web.input().get("p")
     if name.strip() == "":
         tips = _("Username is empty!")
         return self.render("login.html", "Login", nickname="", tips=tips)
     elif len(name) > 25:
         tips = _("The len of username reached the limit of 25 chars!")
         return self.render("login.html", "Login", nickname="", tips=tips, username=name)
     elif "<" in name or ">" in name or "&" in name:
         tips = _("The username includes unsafe chars!")
         return self.render("login.html", "Login", nickname="", tips=tips)
     try:
         pwdhash = hashlib.md5(passwd).hexdigest()
     except:
         u = None
     else:
         u = KeUser.all().filter("name = ", name).filter("passwd = ", pwdhash).get()
     if u:
         session.login = 1
         session.username = name
         if u.expires:  # 用户登陆后自动续期
             u.expires = datetime.datetime.utcnow() + datetime.timedelta(days=180)
             u.put()
         raise web.seeother(r"/")
     else:
         tips = _("The username no exist or password is wrong!")
         # session.login = 0
         # session.username = ''
         # session.kill()
         return self.render("login.html", "Login", nickname="", tips=tips, username=name)
Example #31
0
 def GET(self):
     x = web.input()
Example #32
0
    def GET(self, did=None):
        '''@params:
            did: (str)device id
            sampling: (datetime'''

        try:
            tanggal = to_date(web.input().get('sampling'))
        except:
            tanggal = datetime.datetime.today()

        conn = pg.connect(dbname="bsolo3", user="******", password="******")
        cursor = conn.cursor()

        if did:
            sql = "SELECT content FROM raw WHERE content->>'device' LIKE %s ORDER BY id DESC LIMIT 35"
            cursor.execute(sql, ('%/' + did + '/%', ))
            '''
            regx = re.compile('.*'+did+'/', re.IGNORECASE)
            rst = [r for r in db.sensors.find({"device": regx},
                                                {"_id": 0}).sort(
                                                    "_id", -1).limit(25)]
            '''
            rst = [r[0] for r in cursor.fetchall()]
            if not rst:
                return web.notfound()
            if web.input().get('sampling', None):
                #try:
                sampling = to_date(web.input().get('sampling'))
                _dari = time.mktime(sampling.timetuple())
                _hingga = _dari + 86400
                # satu hari = 86400 ms
                '''
                    rst = [r for r in db.sensors.find(
                        {"$and": [{"device": regx},
                                  {"sampling": {"$gte": _dari}},
                                  {"sampling": {"$lt": _hingga}}]}, {_id: 0})]
                '''
                sql = "SELECT content FROM raw WHERE content->>'device' LIKE %s AND (content->>'sampling')::int >= %s AND (content->>'sampling')::int <= %s"
                cursor.execute(sql, ('%/' + did + '/%', _dari, _hingga))
                rst = [r[0] for r in cursor.fetchall()]
                if not rst:
                    return "Tidak Ada Data Pada Tanggal " + web.input().get(
                        'sampling')
                rst.reverse()
                #except Exception as e:
                #    print e
            out = {}
            if web.input().get('raw'):
                out['periodic'] = rst
            else:
                out['periodic'] = [map_periodic(r) for r in rst]
            out["bsolo_logger"] = BSOLO_LOGGER.get(did)
        else:
            out = []
            sql = "SELECT DISTINCT(content->>'device') FROM raw"
            cursor.execute(sql)
            out = [r[0] for r in cursor.fetchall()]
        cursor.close()
        conn.close()

        #testing from asnan (data untuk kategori grafik) tinggal return untuk melihat
        data = []
        kategori = []
        battery = []
        signal_quality = []
        tick = []
        are_tick = False
        distance = []
        are_distance = False
        wl_scale = []
        are_wl_scale = False

        sun_radiation_scale = []
        wind_dir_scale = []
        temperature_ambien_scale = []
        humidity_ambien_scale = []
        wind_speed_scale = []
        are_klimatologi = False

        r = out["periodic"]
        r.reverse()

        for j in r:
            if "distance" in j:
                are_distance = True
                distance.append(j.get("distance"))
            if "wl_scale" in j:
                are_wl_scale = True
                wl_scale.append(j.get("wl_scale"))
            if "tick" in j:
                if "sun_radiation_scale" and "wind_dir_scale" and "temperature_ambien_scale" and "humidity_ambien_scale" and "wind_speed_scale" in j:
                    are_klimatologi = True
                    sun_radiation_scale.append(j.get("sun_radiation_scale"))
                    wind_dir_scale.append(j.get("wind_dir_scale"))
                    temperature_ambien_scale.append(
                        j.get("temperature_ambien_scale"))
                    humidity_ambien_scale.append(
                        j.get("humidity_ambien_scale"))
                    wind_speed_scale.append(j.get("wind_speed_scale"))
                    tick.append(j.get("tick"))
                else:
                    are_tick = True
                    tick.append(j.get("tick"))

            kategori.append(j.get("sampling"))
            battery.append(j.get("battery"))
            signal_quality.append(j.get("signal_quality"))
        #end
        data.append({'name': 'signal_quality', 'data': signal_quality})
        data.append({'name': 'battery', 'data': battery})
        if are_distance == True:
            data.append({'name': 'distance', 'data': distance})
            jenis_prima = "SONAR"
        if are_wl_scale == True:
            data.append({'name': 'wl_scale', 'data': wl_scale})
            jenis_prima = "PRESSURE"
        if are_tick == True:
            data.append({'name': 'tick', 'data': tick})
            jenis_prima = "ARR"
        if are_klimatologi == True:
            data.append({'name': 'tick', 'data': tick})
            data.append({
                'name': 'sun_radiation_scale',
                'data': sun_radiation_scale
            })
            data.append({'name': 'wind_dir_scale', 'data': wind_dir_scale})
            data.append({
                'name': 'temperature_ambien_scale',
                'data': temperature_ambien_scale
            })
            data.append({
                'name': 'humidity_ambien_scale',
                'data': humidity_ambien_scale
            })
            data.append({'name': 'wind_speed_scale', 'data': wind_speed_scale})
            jenis_prima = "KLIMATOLOGI"

        conn = Agent._connection
        sql = "SELECT cname from agent where prima_id = %s" % ('"' + did + '"')
        result = conn.queryAll(sql)
        if result:
            pname = result[0][0]
        else:
            pname = "--"
        #print result

        return render.sensor.sensor_graph({
            'data': str(data),
            'kategori': str(kategori),
            'did': did,
            'jenis_prima': jenis_prima,
            'pname': pname,
            'tanggal': tanggal
        })
Example #33
0
 def GET(self):
     referer = web.ctx.env.get('HTTP_REFERER', '/')
     i = web.input(redirect=referer)
     f = forms.login()
     f['redirect'].value = i.redirect
     return render.login(f)
Example #34
0
    def POST(self):
        user = self.getcurrentuser()

        fuckgfw = bool(web.input().get('fuckgfw'))
        evernote = bool(web.input().get('evernote'))
        evernote_mail = web.input().get('evernote_mail', '')
        if not evernote_mail:
            evernote = False
        wiz = bool(web.input().get('wiz'))
        wiz_mail = web.input().get('wiz_mail', '')
        if not wiz_mail:
            wiz = False
        pocket = bool(web.input().get('pocket'))
        instapaper = bool(web.input().get('instapaper'))
        instapaper_username = web.input().get('instapaper_username', '')
        instapaper_password = web.input().get('instapaper_password', '')

        xweibo = bool(web.input().get('xweibo'))
        tweibo = bool(web.input().get('tweibo'))
        facebook = bool(web.input().get('facebook'))
        twitter = bool(web.input().get('twitter'))
        tumblr = bool(web.input().get('tumblr'))
        browser = bool(web.input().get('browser'))

        #将instapaper的密码加密
        if instapaper_username and instapaper_password:
            instapaper_password = ke_encrypt(instapaper_password,
                                             user.secret_key or '')
        else:
            instapaper_username = ''
            instapaper_password = ''

        user.share_fuckgfw = fuckgfw
        user.evernote = evernote
        user.evernote_mail = evernote_mail
        user.wiz = wiz
        user.wiz_mail = wiz_mail
        user.pocket = pocket
        user.instapaper = instapaper
        user.instapaper_username = instapaper_username
        user.instapaper_password = instapaper_password
        user.xweibo = xweibo
        user.tweibo = tweibo
        user.facebook = facebook
        user.twitter = twitter
        user.tumblr = tumblr
        user.browser = browser
        user.put()
        raise web.seeother('')
Example #35
0
    def POST(self):
        pcf_options.web_update(web.input())

        if pcf_sender is not None:
            pcf_sender.update()                
        raise web.seeother(plugin_url(settings_page), True)
Example #36
0
 def POST(self):
     formulario = web.input()
     email = formulario['email']
     password = formulario['password']
     
     raise web.seeother('/')
Example #37
0
 def GET(self):
     x = web.input()
     return render.index2(respl, contentl)
Example #38
0
 def POST(self):
     text = web.input()
     print(text)
     raise web.seeother('/')
Example #39
0
    def GET(self):
        i = web.input(username='', email='', key='')
        if i.key != lending.config_internal_tests_api_key:
            return delegate.RawText(simplejson.dumps(
                {'error': 'Authentication failed for private API'}),
                                    content_type="application/json")
        try:
            if i.username:
                ol_account = OpenLibraryAccount.get(username=i.username)
            elif i.email:
                ol_account = OpenLibraryAccount.get(email=i.email)
        except Exception as e:
            return delegate.RawText(simplejson.dumps({'error': 'bad-account'}),
                                    content_type="application/json")
        if ol_account:
            ol_account.enc_password = '******'
            if ol_account.itemname:
                return delegate.RawText(simplejson.dumps({
                    'status':
                    'link-exists',
                    'username':
                    ol_account.username,
                    'itemname':
                    ol_account.itemname,
                    'email':
                    ol_account.email.lower()
                }),
                                        content_type="application/json")
            if not ol_account.itemname:
                ia_account = InternetArchiveAccount.get(
                    email=ol_account.email.lower())
                if ia_account:
                    ol_account.link(ia_account.itemname)
                    return delegate.RawText(simplejson.dumps({
                        'username':
                        ol_account.username,
                        'status':
                        'link-found',
                        'itemname':
                        ia_account.itemname,
                        'ol-itemname':
                        ol_account.itemname,
                        'email':
                        ol_account.email.lower(),
                        'ia':
                        ia_account
                    }),
                                            content_type="application/json")

                password = OpenLibraryAccount.generate_random_password(16)
                ia_account = InternetArchiveAccount.create(
                    ol_account.username or ol_account.displayname,
                    ol_account.email,
                    password,
                    verified=True,
                    retries=USERNAME_RETRIES)
                return delegate.RawText(simplejson.dumps({
                    'username':
                    ol_account.username,
                    'email':
                    ol_account.email,
                    'itemname':
                    ia_account.itemname,
                    'password':
                    password,
                    'status':
                    'link-created'
                }),
                                        content_type="application/json")
Example #40
0
 def POST(self):
     mydata = web.input(name=None)
     return 'admin page'
Example #41
0
 def POST(self):
     i = web.input()
     ips = [ip.strip() for ip in i.ips.splitlines()]
     self.block_ips(ips)
     add_flash_message("info", "Saved!")
     raise web.seeother("/admin/block")
Example #42
0
 def GET_AUTH(self, courseid):  # pylint: disable=arguments-differ
     """ GET request """
     course, __ = self.get_course_and_check_rights(courseid,
                                                   allow_all_staff=False)
     return self.show_page(course, web.input())
Example #43
0
 def GET(self):
     i = web.input(id=None, name=None)
     return i.id, i.name 
Example #44
0
 def POST(self):
     i = web.input(keys="")
     keys = i['keys'].strip().split()
     web.ctx.site.store['solr-force-update'] = dict(type="solr-force-update", keys=keys, _rev=None)
     add_flash_message("info", "Added the specified keys to solr update queue.!")
     return self.GET()
Example #45
0
 def GET(self):
     yield "hello, "
     yield web.input(name="world").name
Example #46
0
 def POST(self, username):
     i = web.input(changesets=[], comment="Revert", action="revert")
     if i.action == "revert" and i.changesets:
         ipaddress_view().revert(i.changesets, i.comment)
     raise web.redirect(web.ctx.path)
Example #47
0
 def GET(self):
     param = get_param(web.input())
     raise web.redirect(
         get_redirect_loc('http://%s/ui/cate?%s' %
                          (setting.wx_host, param)))
Example #48
0
 def GET(self):
     import simplejson as json
     from db import listingClients
     i = web.input(id=None)
     web.header('content-Type', 'application/json')
     return json.dumps(listingClients(i.id))
Example #49
0
    def POST(self, version='v1'):
        web.header('Content-Type', 'application/json')
        param = web.input(app_id='',
                          dev_id='',
                          ver_code='',
                          session='',
                          page_size='',
                          page_index='',
                          tick='')

        if '' in (param.app_id, param.dev_id, param.ver_code, param.session,
                  param.page_size, param.page_index, param.tick):
            return json.dumps({'ret': -2, 'msg': '参数错误'})

        # 检查session登录
        uname = app_helper.app_logged(param.session)
        if uname is None:
            return json.dumps({'ret': -4, 'msg': '无效的session'})

        #--------------------------------------------------

        course_list = []

        # 用户自己买的课程
        r2 = db.user_property.find(
            {
                'userid': uname['userid'],
                'status': 'paid',
                'obj_type': 'course'
            },
            sort=[('_id', 1)],  # 按时间倒序
            #skip=int(param.page_size)*int(param.page_index),
            #limit=int(param.page_size)
        )

        course_list = [x['obj_id'] for x in r2]

        # 被授权的课程
        r4 = db.employee_auth.find({'employee_userid': uname['userid']})
        for x in r4:
            for y in x['object_list']:
                if y not in course_list:
                    course_list.append(y)

        # 取指定区间的
        start_pos = int(param.page_size) * int(param.page_index)
        end_pos = start_pos + int(param.page_size)
        course_list = course_list[start_pos:end_pos]

        course_data = []

        for i in course_list:
            r3 = db.obj_store.find_one({'obj_id': i})
            if r3 is None:
                continue

            if len(r3['image']) > 0:  # 取第1张图
                image_url = app_helper.image_url(r3['image'][0])
            else:
                image_url = ''

            # 已授权店员数,只统计本店主的店员数
            auth_num = db.employee_auth.find({
                'owner_userid': uname['userid'],
                'object_list': r3['obj_id']
            }).count()

            # 测试成绩
            r5 = db.test_info.find_one({
                'userid': uname['userid'],
                'obj_id': r3['obj_id']
            })
            score = r5['score'] if r5 else -1

            # 完成进度
            r6 = db.progress_info.find_one({
                'userid': uname['userid'],
                'obj_id': r3['obj_id']
            })
            progress = r6['progress'] if r6 else 0

            # 是否有测试题
            r7 = db.exam_info.find({
                'obj_id': r3['obj_id'],
                'available': 1
            }).count()

            course_data.append({
                "object_id": r3['obj_id'],  # 内部唯一标识 
                "title": r3['title'],
                "title2": r3['title2'],
                "speaker": r3['speaker'],
                "type": 1 if r3['media'] == 'video' else 2,  # 1- 视频   2 - 音频  
                "image": image_url,  # 课程主图 
                "length": r3['length'],  # 长度,单位:分钟 
                "progress": progress,  # 课程进度百分比,0表示未上课,100表示已上课 
                "exam_score": score,  # 课后测试成绩,-1表示未测试  
                "auth_num": auth_num,  # 已授权店员数 ,
                "have_exam": 1 if r7 > 0 else 0,  # 是否有课后测试,2017-06-09
            })

        ret_data = {
            "course": course_data,
            "total": len(course_data),  # 返回的课程数量,小于 page_size说明到末尾 
            "page_size": param.page_size,  # 分页尺寸,与调用参数相同 
            "page_index": param.page_index,  # 页索引 
        }

        # 返回
        return json.dumps({
            'ret': 0,
            'data': ret_data,
        })
Example #50
0
 def GET(self):
     url_scheme = web.ctx.environ['wsgi.url_scheme']
     param = get_param(web.input())
     raise web.redirect(
         get_redirect_loc('%s://%s/wx/tnm_init?%s' %
                          (url_scheme, setting.wx_host, param)))
Example #51
0
 def GET(self):
     a = web.input(name=None)
     if a.name == None:
         a.name = "ozg"
     return 'Hello, ' + a.name + '!'
Example #52
0
    def POST(self, work_id):
        """
        Add a work (or a work and an edition) to a bookshelf.

        GET params:
        - edition_id str (optional)
        - action str: e.g. "add", "remove"
        - redir bool: if patron not logged in, redirect back to page after login
        - bookshelf_id int: which bookshelf? e.g. the ID for "want to read"?
        - dont_remove bool: if book exists & action== "add", don't try removal

        :param str work_id: e.g. OL123W
        :rtype: json
        :return: a list of bookshelves_affected
        """
        from openlibrary.core.models import Bookshelves

        user = accounts.get_current_user()
        i = web.input(
            edition_id=None,
            action="add",
            redir=False,
            bookshelf_id=None,
            dont_remove=False,
        )
        key = i.edition_id if i.edition_id else ('/works/OL%sW' % work_id)

        if not user:
            raise web.seeother('/account/login?redirect=%s' % key)

        username = user.key.split('/')[2]
        current_status = Bookshelves.get_users_read_status_of_work(
            username, work_id)

        try:
            bookshelf_id = int(i.bookshelf_id)
            shelf_ids = Bookshelves.PRESET_BOOKSHELVES.values()
            if bookshelf_id != -1 and bookshelf_id not in shelf_ids:
                raise ValueError
        except (TypeError, ValueError):
            return delegate.RawText(
                json.dumps({'error': 'Invalid bookshelf'}),
                content_type="application/json",
            )

        if (not i.dont_remove
            ) and bookshelf_id == current_status or bookshelf_id == -1:
            work_bookshelf = Bookshelves.remove(username=username,
                                                work_id=work_id,
                                                bookshelf_id=current_status)

        else:
            edition_id = int(
                i.edition_id.split('/')[2][2:-1]) if i.edition_id else None
            work_bookshelf = Bookshelves.add(
                username=username,
                bookshelf_id=bookshelf_id,
                work_id=work_id,
                edition_id=edition_id,
            )

        if i.redir:
            raise web.seeother(key)
        return delegate.RawText(
            json.dumps({'bookshelves_affected': work_bookshelf}),
            content_type="application/json",
        )
 def GET(self):
     redis.incr('additions')
     a = int(web.input()['A'])
     b = int(web.input()['B'])
     return "{0} + {1} = {2}".format(a, b, (a + b))
Example #54
0
 def GET(self):
     user_data = web.input()
     #user_data.docid
     return render.post(docid)
Example #55
0
    def POST(self, key):
        """Called when the user wants to borrow the edition"""

        i = web.input(action='borrow',
                      format=None,
                      ol_host=None,
                      _autoReadAloud=None,
                      q="")

        ol_host = i.ol_host or 'openlibrary.org'
        action = i.action
        edition = web.ctx.site.get(key)
        if not edition:
            raise web.notfound()

        archive_url = get_bookreader_stream_url(edition.ocaid) + '?ref=ol'
        if i._autoReadAloud is not None:
            archive_url += '&_autoReadAloud=show'

        if i.q:
            _q = urllib.parse.quote(i.q, safe='')
            archive_url += "#page/-/mode/2up/search/%s" % _q

        # Make a call to availability v2 update the subjects according
        # to result if `open`, redirect to bookreader
        response = lending.get_availability_of_ocaid(edition.ocaid)
        availability = response[edition.ocaid] if response else {}
        if availability and availability['status'] == 'open':
            raise web.seeother(archive_url)

        error_redirect = (archive_url)
        user = accounts.get_current_user()

        if user:
            account = OpenLibraryAccount.get_by_email(user.email)
            ia_itemname = account.itemname if account else None
            s3_keys = web.ctx.site.store.get(account._key).get('s3_keys')
        if not user or not ia_itemname or not s3_keys:
            web.setcookie(config.login_cookie_name, "", expires=-1)
            redirect_url = "/account/login?redirect=%s/borrow?action=%s" % (
                edition.url(), action)
            if i._autoReadAloud is not None:
                redirect_url += '&_autoReadAloud=' + i._autoReadAloud
            raise web.seeother(redirect_url)

        if action == 'return':
            loan_resp = lending.s3_loan_api(edition.ocaid,
                                            s3_keys,
                                            action='return_loan')
            stats.increment('ol.loans.return')
            raise web.seeother(edition.url())
        elif action == 'join-waitinglist':
            loan_resp = lending.s3_loan_api(edition.ocaid,
                                            s3_keys,
                                            action='join_waitlist')
            stats.increment('ol.loans.joinWaitlist')
            raise web.redirect(edition.url())
        elif action == 'leave-waitinglist':
            loan_resp = lending.s3_loan_api(edition.ocaid,
                                            s3_keys,
                                            action='leave_waitlist')
            stats.increment('ol.loans.leaveWaitlist')
            raise web.redirect(edition.url())

        # Intercept a 'borrow' action if the user has already
        # borrowed the book and convert to a 'read' action.
        # Added so that direct bookreader links being routed through
        # here can use a single action of 'borrow', regardless of
        # whether the book has been checked out or not.
        elif user.has_borrowed(edition):
            action = 'read'

        elif action in ('borrow', 'browse'):
            borrow_access = user_can_borrow_edition(user, edition)

            if not (s3_keys or borrow_access):
                raise web.seeother(error_redirect)

            loan_resp = lending.s3_loan_api(edition.ocaid,
                                            s3_keys,
                                            action='%s_book' % borrow_access)
            stats.increment('ol.loans.bookreader')
            stats.increment('ol.loans.%s' % borrow_access)
            action = 'read'

        if action == 'read':
            bookPath = '/stream/' + edition.ocaid
            if i._autoReadAloud is not None:
                bookPath += '?_autoReadAloud=show'

            # Look for loans for this book
            user.update_loan_status()
            loans = get_loans(user)
            for loan in loans:
                if loan['book'] == edition.key:
                    raise web.seeother(
                        make_bookreader_auth_link(loan['_key'],
                                                  edition.ocaid,
                                                  bookPath,
                                                  ol_host,
                                                  ia_userid=ia_itemname))

        # Action not recognized
        raise web.seeother(error_redirect)
Example #56
0
    def POST(self):
        form = web.input(name="Nobody", greet="Hello")

        greeting = "%s, %s" % (form.greet, form.name)
        return render.index(greeting=greeting)
Example #57
0
 def POST(self):
     i = web.input()
     n = db.insert('carti', isbn = i.isbn,titlu=i.titlu,autor=i.autor)
     raise web.seeother('/')
Example #58
0
    def PUT(self):
        requestStart = time.time()
        requestInput = web.input()
        encoding = web.data()
        spSnapshots = [
            SP_SNAPS.ACT_COL,
        ]
        tmSnapshots = [
            TM_SNAPS.ACT_CELLS,
            TM_SNAPS.PRD_CELLS,
        ]

        for snap in SP_SNAPS.listValues():
            getString = "get{}{}".format(snap[:1].upper(), snap[1:])
            if getString in requestInput and requestInput[getString] == "true":
                spSnapshots.append(snap)

        for snap in TM_SNAPS.listValues():
            getString = "get{}{}".format(snap[:1].upper(), snap[1:])
            if getString in requestInput and requestInput[getString] == "true":
                tmSnapshots.append(snap)

        if "id" not in requestInput:
            print "Request must include a model id."
            return web.badrequest()

        modelId = requestInput["id"]

        if modelId not in modelCache.keys():
            print "Unknown Model id {}!".format(modelId)
            return web.badrequest()

        sp = modelCache[modelId]["sp"]

        spLearn = True
        if "spLearn" in requestInput:
            spLearn = requestInput["spLearn"] == "true"

        inputArray = np.array([])
        if len(encoding):
            inputArray = np.array([int(bit) for bit in encoding.split(",")])

        print "Entering SP {} compute cycle | Learning: {}".format(
            modelId, spLearn)
        sp.compute(inputArray, learn=spLearn)
        spResults = sp.getState(*spSnapshots)
        activeColumns = spResults[SP_SNAPS.ACT_COL]['indices']

        tm = modelCache[modelId]["tm"]

        tmLearn = True
        if "tmLearn" in requestInput:
            tmLearn = requestInput["tmLearn"] == "true"

        reset = False
        if "reset" in requestInput:
            reset = requestInput["reset"] == "true"

        print "Entering TM {} compute cycle | Learning: {}".format(
            modelId, tmLearn)
        tm.compute(activeColumns, learn=tmLearn)

        tmResults = tm.getState(*tmSnapshots)

        c = modelCache[modelId]["classifier"]
        bucketIdx = int(requestInput["bucketIdx"])
        actValue = requestInput["actValue"]
        recordNum = int(modelCache[modelId]["recordsSeen"])

        # inference
        inference = c.compute(recordNum=recordNum,
                              patternNZ=tmResults[TM_SNAPS.ACT_CELLS],
                              classification={
                                  "bucketIdx": bucketIdx,
                                  "actValue": actValue
                              },
                              learn=True,
                              infer=True)

        # Print the top three predictions for 1 steps out.
        topPredictions = sorted(zip(inference[1], inference["actualValues"]),
                                reverse=True)[:3]
        for probability, value in topPredictions:
            print "Prediction of {} has probability of {}.".format(
                value, probability * 100.0)

        if reset:
            print "Resetting TM."
            tm.reset()

        completeResults = {}
        completeResults.update(spResults)
        completeResults.update(tmResults)
        completeResults["inference"] = topPredictions

        web.header("Content-Type", "application/json")
        jsonOut = json.dumps(completeResults)

        requestEnd = time.time()
        print("\tFULL compute cycle took %g seconds" %
              (requestEnd - requestStart))

        modelCache[modelId]["recordsSeen"] += 1

        return jsonOut
Example #59
0
 def POST(self):
     postParams = web.input()
     loginAccessToken = postParams.get('loginAccessToken')
     loginType = postParams.get('type')
Example #60
0
 def GET(self):
     i = web.input(url='')
     image_url = i.url
     return web.redirect(image_url)