예제 #1
0
 def POST(self):
   var = web.input()
   
   
   if 'fb' in var:
     xsrf = util.select_one('xsrf', where='token=$tok', vars={'tok': var.xsrf})
     if xsrf is None:
       raise status.ApiError('401 Unauthorized')
     
   try:
     xsrf = util.select_one('xsrf', where='token=$tok', vars={'tok': var.xsrf})
     if xsrf is None:
       raise status.ApiError('401 Unauthorized')
     
     user = self.user_auth(var.email, var.pword)
     if user is None:
       print "this one"
       raise status.ApiError('401 Unauthorized')
     
     sess = str(uuid.uuid4())[:64]
     values = {
       'sess': sess,
       'uid': user['id']
     }
     util.insert('sessions', **values)
     web.setcookie('wsid_login', sess, path='/')
   except AttributeError as err:
     print "that one"
     raise status.ApiError('401 Unauthorized (%s)' % err)
     
   web.redirect('/')
    def __init__(self, account_id, class_key, title, semester, start_date, end_date,
                 update_db=False, generate_instructor_key=False):

        self.class_id       = None
        self.account_id     = account_id
        self.class_key      = class_key
        self.title          = title
        self.semester       = semester
        self.start_date     = start_date
        self.end_date       = end_date

        if update_db:
            self.class_id = util.insert(
                'Class',
                ('account_id','class_key','title','semester','start_date', 'end_date'),
                (self.account_id, self.class_key, self.title, self.semester, self.start_date, self.end_date),
                classname=Class.__name__
            )

        if generate_instructor_key:
            #TODO make sure this unique
            key = ''
            for i in range(15):
                key += hex(random.randint(15))[2:]
            util.insert('Instructor_key',('account_id','instruction_key'),(account_id,key),classname=Class.__name__)
def populate_contactgroups(db_from, db_to, contacts, contactgroups):
    members = 0

    for contactgroup in contactgroups:
        where = "contactgroup_id={}".format(
            contactgroup["prev_contactgroup_id"])

        # Get from db members of an old contact group
        contactgroupmembers = [
            cgm for cgm in util.select(db_from, "contactgroupmembers", where)
        ]

        # Put users from previous contacts groups into new ones
        for contactgroupmember in contactgroupmembers:
            contactgroupmember["contactgroup_id"] = contactgroup[
                "contactgroup_id"]
            try:
                contactgroupmember["contact_id"] = get_prev_contact_key(
                    contactgroupmember["contact_id"], contacts)
            except Exception, exc:
                logging.exception(
                    "Error updating contact group membership of %d in %s",
                    contactgroupmember["contact_id"],
                    contactgroup["contactgroup_id"])
                raise
            else:
                util.insert(db_to, "contactgroupmembers", contactgroupmember)

        members += len(contactgroupmembers)
예제 #4
0
 def POST(self, pid):
   qx = util.select_one('qlist', where='id=$id', vars={'id': pid})
   if qx is None:
     raise status.ApiError('401 Invalid Question')
   sess = util.get_sess()
   
   data = web.data()
   util.insert('alist', ans=data, up=0, down=0, qid=qx.id)
   
   raise status.ApiError('200 OK')
예제 #5
0
 def POST(self):
   sess = util.get_sess()
   if not sess:
     raise status.ApiError('401 Unauthorized')
   qx = web.input()
   
   try:
     util.insert('qlist', uid=sess.uid, opt1=qx.opt1, opt2=qx.opt2)
   except AttributeError:
     raise status.ApiError('401 Missing Input(s)')
   
   raise status.ApiError('200 OK')
예제 #6
0
파일: dbt.py 프로젝트: dieterichlawson/dbt
 def lj(xi, i, other_x):
   real_x = util.insert(other_x, xi, i)
   return log_joint(real_x, C, D,
                    prior_var=prior_var,
                    censorship_temp=censorship_temp,
                    distance_threshold=distance_threshold,
                    distance_var=distance_var)
예제 #7
0
def addUser():
    successInfo = ""
    if request.method == 'POST':
        status = request.form['status']
        if status == 'Failed':
            return render_template('addUser.html')
        username = request.form['username']
        ID = request.form['userID']
        Age = request.form['userAge']
        userDepartment = request.form['userDepartment']
        if (util.select_by_id(int(ID)) == "无"):
            util.insert(int(ID), username, int(Age), userDepartment)
            successInfo = "插入成功"
        else:
            successInfo = "ID重复,插入失败"
    return render_template('addUser.html', successInfo=successInfo)
예제 #8
0
def reg():
    if request.method == 'POST':
        user = {k: v[0] for k, v in dict(request.form).items()}
        filed = ['username', 'password', 'role', 'email']
        result = insert('user', filed, user)
        if result['code'] == 0:
            return redirect('/userlist/')
        else:
            return render_template('reg.html', result=result)
    return render_template('reg.html')
    def __init__(self, account_id, title, instructions, class_id, update_db=False):
        self.assignment_def_id  = None
        self.account_id         = account_id
        self.title              = title
        self.instructions       = instructions
        self.class_id           = class_id
        self.def_file_path      = None

        if update_db:
            self.assignment_def_id = util.insert(
                'Assignment_definition',
                ('account_id','title','instructions'),
                (self.account_id,self.title,self.instructions),
                classname='AssignmentDefinition'
            )
            util.insert(
                'Class_assignments',
                ('assignment_def_id','class_id'), (self.assignment_def_id,self.class_id),
                classname='AssignmentDefinition'
            )
    def __init__(self, assignment_id, submission_fpath, submission_dt, update_db=False):
        self.assignment_id      = assignment_id
        self.submission_fpath   = submission_fpath
        self.submission_dt      = submission_dt

        if update_db:
            self.submission_id = util.insert(
                'Submission_files',
                ('assignment_id','submission_fpath', 'submission_datetime'),
                (self.assignment_id,self.submission_fpath,self.submission_dt),
                classname=SubmissionFile.__name__
            )
 def __init__(self, account_type, email, fname, lname, pwd, update_db=False):
     self.account_id         = None
     self.account_type       = account_type
     self.email              = email
     self.fname, self.lname  = fname, lname
     self.pwd                = pwd
     if update_db:
         self.account_id = util.insert(
             'Account',
             ('account_type','email','fname','lname','pwd'),
             (self.account_type,self.email,self.fname,self.lname,self.pwd),
             classname='Account'
         )
예제 #12
0
 def POST(self):
   var = web.input()
   
   if 'fb' in var:
     raise status.ApiError('200 OK')
   try:
     if var.pword != var.repword:
       raise status.ApiError('403 Field Mismatch')
     hpword = bcrypt.hashpw(var.pword, bcrypt.gensalt())
     res = util.insert('users', email=var.email, pword=hpword, name=var.name)
     
     sess = str(uuid.uuid4())[:64]
     values = {
       'sess': sess,
       'uid': res
     }
     util.insert('sessions', **values)
     web.setcookie('wsid_login', sess, expires=86400, path='/')
   except KeyError as err:
     raise status.ApiError('401 Unauthorized')
     
   raise status.ApiError('200 OK')
 def set_answer_key(assignment_def_id,  answer_key_fpath):
     db_read = util.select(
         'Answer_key',
         ('answer_key_id'),
         {'assignment_def_id':assignment_def_id},
         classname='AssignmentDefinition'
     )
     if len(db_read) > 0:    # case that Answer Key already exists for Assignment Def
         answer_key_id = db_read[0][0]
         util.update(
             'Answer_key',
             {'answer_key_id':answer_key_id},
             {'answer_key_file_path':answer_key_fpath},
             classname='AssignmentDefinition'
         )
     else:
         util.insert(
             'Answer_key',
             ('assignment_def_id','answer_key_file_path'),
             (assignment_def_id,answer_key_fpath),
             classname=AssignmentDefinition.__name__
         )
    def __init__(self, assignment_def_id, answer_key_fpath, update_db=False):
        self.answer_key_id      = None
        self.assignment_def_id  = assignment_def_id
        self.answer_key_fpath   = answer_key_fpath
        self.fields             = []

        if update_db:
            self.answer_key_id = util.insert(
                'Answer_key',
                ('assignment_def_id','answer_key_fpath'),
                (self.assignment_def_id,self.answer_key_fpath),
                classname='AnswerKey'
            )
            self.fields = Field.get_fields(self.answer_key_id)
    def __init__(self, answer_key_id, x, y, xdim, ydim, field_type, update_db=False):
        self.field_id           = None
        self.answer_key_id      = answer_key_id
        self.x, self.y          = x, y
        self.xdim, self.ydim    = xdim, ydim
        self.field_type         = field_type

        if update_db:
            self.field_id = util.insert(
                'Field',
                ('answer_key_id','x','y','xdim','ydim','field_type'),
                (self.answer_key_id,self.x,self.y,self.xdim,self.ydim,self.field_type),
                classname=Field.__name__
            )
def transfer_contacts(db_from, db_to, where, user_id):
    # Search for contacts in database
    contacts = [c for c in util.select(db_from, "contacts", where)]
    for contact in contacts:
        # Update user reference
        contact["user_id"] = user_id

        # Keep track of last id for contact
        prev_contact_id = contact["contact_id"]
        del contact["contact_id"]

        # Insert contact in destination db
        contact["contact_id"] = util.insert(db_to, "contacts", contact)
        contact["prev_contact_id"] = prev_contact_id

    return contacts
def transfer_identities(db_from, db_to, where, user_id):
    # Search for identities in database
    identities = [i for i in util.select(db_from, "identities", where)]

    for identity in identities:
        # Update user reference
        identity["user_id"] = user_id

        # Keep track of last id for identity
        prev_identity_id = identity["identity_id"]
        del identity["identity_id"]

        # Insert identity in destination db
        identity["identity_id"] = util.insert(db_to, "identities", identity)

    return identities
    def __init__(self, account_id, assignment_def_id, answer_key_id,
                 open_dt, due_dt, update_db=False):
        self.assignment_id      = None
        self.account_id         = account_id
        self.assignment_def_id  = assignment_def_id
        self.answer_key_id      = answer_key_id
        self.open_dt            = open_dt
        self.due_dt             = due_dt

        self.graded             = False
        self.grade              = 0
        self.marked_up_fpath    = None

        if update_db:
            self.assignment_id = util.insert(
                'Assignment',
                ('account_id','assignment_df_id','answer_key_id','open_datetime','due_datetime','graded','grade'),
                (self.account_id,self.assignment_def_id,self.answer_key_id,self.open_dt,self.due_dt,False,0),
                classname=Assignment.__name__
            )
예제 #19
0
def regist():
    if request.method == 'GET' :
        #code_str = gene_code()
        #session['code'] = code_str.lower()
        return render_template('regist.html')
    else :
        users = request.form.to_dict()
        if users.get('passwd') == users.get('passwd1') :
            inputCode = users.pop('code') #删除字典里的pop并取出值
            if inputCode.lower() ==  session.get('code') :
                del users['passwd1']
                users = passwd_hash.set_password(users)
                if insert(users) :
                    return redirect('/login/')
                else :
                    err_info = "用户名已存在"
                    return render_template('regist.html',m = err_info )
            else :
                err_info = "验证码错误"
                return render_template('regist.html',m = err_info )
        else :
            m = "两次输入密码不一致"
            return render_template('regist.html',m = m )
예제 #20
0
def regist():
    if request.method == 'GET':
        return render_template('regist.html')
    else:
        #passs
        keys = [
            'username', 'passwd', 'passwd1', 'age', 'sex', 'phone', 'email',
            'role'
        ]
        users = {}
        for key in keys:
            users[key] = request.form.get(key)
        if users.get('passwd') == users.get('passwd1'):
            del users['passwd1']
            print users, '123'
            if insert(users):
                return redirect('/login/')
            else:
                err_info = "username already exists"
                return render_template('regist.html', m=err_info)
        else:
            m = "Two passwords are different"
            return render_template('regist.html', m=m)
예제 #21
0
 def POST(self,rid):
   var = web.data()
   util.insert('room_com', com=strip_tags(var), room_id=rid)
예제 #22
0
 def POST(self,hid):
   var = web.data()
   util.insert('house_com', com=strip_tags(var), house_id=hid)
예제 #23
0
def video_crawl(driver, domainid, urlid, url, domain, inttime, table,
                total_links):
    links = get_links(url, domainid, domain, driver)
    print "%s has links :%s" % (domain, len(links))
    total_links = total_links + len(links)
    print total_links
    for srclink in links:
        try:
            driver.get(srclink)

            embed = ""
            print "Source link :", srclink
            if 'rantnow.com' in url:
                embed = "//div[@class='video-player-content']"
                time.sleep(5)
            elif 'rantchic.com' in url:

                embed = "//div[@class='featured-media-player-video']"
                time.sleep(5)
            elif 'time.com' in url:
                embed = "//figure[@class='primary-video-wrapper video-brightcove']"
                time.sleep(5)
            elif 'http://edition.cnn.com' in url:
                time.sleep(5)
                embed = "//div[@class='media__video--thumbnail-wrapper']"
            elif 'http://www.nytimes.com/' in url:
                time.sleep(2)
                embed = "//div[@id='video-container']"
            elif 'http://www.usatoday.com/' in url:
                embed = "//div[@class='ui-video  video-player-loaded']"
                time.sleep(5)
            if 'digitaltrends' not in url:
                #if url:
                try:
                    if srclink.endswith("viral-partners"):
                        link = get_viral(url, driver)
                        if link:
                            util.insert(domainid, urlid, link, srclink,
                                        inttime, table)
                    else:
                        video = driver.find_element_by_xpath(embed)
                        video.click()
                        time.sleep(3)
                        if 'rantchic.com' in url:
                            video.click()
                            time.sleep(1)
                    if len(driver.window_handles) > 1:
                        driver.switch_to_window(driver.window_handles[1])

                        print "Advt Url: %s" % driver.current_url
                        link = driver.current_url
                        print "######################\n"
                        driver.close()
                        driver.switch_to_window(driver.window_handles[0])
                        util.insert(domainid, urlid, link, srclink, inttime,
                                    table)
                except:
                    traceback.print_exc()
                    pass
            else:
                res = urllib2.urlopen(srclink).read()
                data = res[res.find(', tag: "') + 8:]
                url = data[:data.find('"')]
                vid = data[data.find("{content_id: '") + 15:]
                vid = vid[:vid.find("'")]
                tmp = urllib.quote_plus(srclink)
                corr = get_corr()

                #url=url.replace("__random-number__",corr).replace("__item-mediaid__",vid).replace("__page-url__",tmp)
                url = url.replace("&correlator=__random-number__", "").replace(
                    "__item-mediaid__", vid).replace("__page-url__", tmp)
                print url
                print "\n====================\n"
                tmp1 = urllib2.urlopen(url).read()
                if "<AdTitle>" in tmp1:
                    #f=codecs.open("digital%s.html"%corr,"w","utf8")
                    #f.write(tmp1)
                    #f.close()
                    ad = tmp1[tmp1.find("&adurl=") + 7:]
                    ad = ad[:ad.find("]]>")]
                    print "2.Advt: %s" % ad[:250]
                    link = ad[:250]
                    link = urllib.unquote_plus(link)
                    #res=requests.get(link)
                    #link=res.url
                    driver.get(link)
                    time.sleep(1)
                    link = driver.current_url
                    #link=urllib.unquote_plus(link)
                    util.insert(domainid, urlid, link, srclink, inttime, table)
        except:
            traceback.print_exc()
            pass
    return total_links
예제 #24
0
#util.insert(db, flow)
#util.delete_all(db, model.Flow)
#util.delete_all(db, model.Category)

steel = util.create_flow(db, 'Steel', mass)
co2 = util.create_flow(db, 'CO2', mass, 
                       flow_type=model.FlowType.ELEMENTARY_FLOW)

param = util.find(db, model.Parameter, 'param')
if param is None:
    param = model.Parameter()
    param.name = 'param'
    param.scope = model.ParameterScope.GLOBAL
    param.inputParameter = True
    param.value = 42.0
    util.insert(db, param)

steel_production = util.find(db, model.Process, 'Steel production')
if steel_production is None:
    steel_production = model.Process()
    steel_production.name = 'Steel production'
    steel_output = util.create_exchange(steel, 1.0)
    steel_production.exchanges.add(steel_output)
    co2_output = util.create_exchange(co2, 42)
    co2_output.amountFormula = '0.5 * param'
    steel_production.exchanges.add(co2_output)
    steel_production.quantitativeReference = steel_output
    util.insert(db, steel_production)

product = util.create_flow(db, 'Product', mass)
manufacturing = util.find(db, model.Process, 'Manufacturing')
예제 #25
0
def test_insert2():
    from util import insert
    a = [1, 2, 3, 4, 5]
    insert(a, [6, 7, 8], 5)
    assert a == [1, 2, 3, 4, 5, 6, 7, 8]
예제 #26
0
 def GET(self):
   xsrf = str(uuid.uuid1())
   util.insert('xsrf', token=xsrf)
   raise status.ApiReturn('templates/login', xsrf)
예제 #27
0
def test_insert1():
    from util import insert
    a = [1, 2, 3, 4, 5]
    insert(a, [6, 7, 8], 1)
    assert a == [1, 6, 7, 8, 2, 3, 4, 5]
 def set_pwd(account_id, pwd):
     reset_key = ''
     for i in range(15):
         reset_key += hex(random.randint(15))[2:]
     util.insert('Pwd_reset',('account_id','pwd_reset_key'),(account_id,reset_key),classname=PasswordManager.__name__)
     util.insert('Account',('pwd'),(pwd),classname=PasswordManager.__name__)
 def add_student(class_id, account_id):
     util.insert('Class_list',('account_id','class_id'),(account_id,class_id),classname=ClassList.__name__)