Example #1
0
File: inds.py Project: dayzhou/inds
    def POST(self):
        try:
            f = web.input()
            if not self.check(f):
                self.args.username = f.username
                self.args.password = f.password
                self.args.pw2 = f.pw2
                self.args.email = f.email
                self.args.realname = f.realname
                return render.index('FB_FORM_REGISTER', self.args)

            db.insert(APP,
                      username=f.username,
                      password=web.SQLLiteral("PASSWORD('%s')" % f.password),
                      email=f.email,
                      realname=f.realname,
                      date=web.SQLLiteral('CURDATE()'))
            Thread(target=send_email,
                   kwargs={
                       'receiver': AdminEmails,
                       'subject': u'A New Applicant for INDS',
                       'content':
                       u'有人提交了INDS帐号申请,请点击下面的链接处理申请:\n\n%s' % INDS_URL
                   }).start()
            return render.index('FB_MSG_REGISTER', (f, AdminEmails))

        except Exception, e:
            write_log(e, 'REGISTER-POST')
            return render.index('FB_FAIL_UNEXPECTED',
                                (AdminEmails, 'REGISTER-POST', e))
Example #2
0
def buy_and_sell(strategy_id,strategy_batch_no,stock_no,buy_date,hold_days=1,buy_price='open_price',sell_price='open_price',trade_hands=1):
    stocks = load_dates_stock(stock_no,buy_date,hold_days)
    if len(stocks)< hold_days + 1:
        raise Exception('no-sell-date-stock-info')
    buy_stock = stocks[0]
    sell_stock = stocks[-1]

    earnings = ( sell_stock[sell_price] - buy_stock[buy_price] )*  trade_hands * 100
    earnings_rate = ( sell_stock[sell_price] - buy_stock[buy_price] )/ buy_stock[buy_price] * 100

    dbw.insert('trading_records',
        strategy_id = strategy_id,
        strategy_batch_no = strategy_batch_no,
        buy_or_sell = 0,
        stock_no = buy_stock.stock_no,
        date = buy_stock.date,
        open_or_close = buy_price,
        price = buy_stock[buy_price],
        hands = trade_hands,
        input_output = 0 - buy_stock[buy_price] * trade_hands  * 100 ,
        earnings=earnings,earn_rate=earnings_rate,
        create_date=web.SQLLiteral('now()'))

    dbw.insert('trading_records',
        strategy_id = strategy_id,
        strategy_batch_no = strategy_batch_no,
        stock_no = sell_stock.stock_no,
        buy_or_sell = 1,
        date = sell_stock.date,
        open_or_close = sell_price,
        price = sell_stock[sell_price],
        hands = trade_hands,
        input_output =  sell_stock[sell_price] * trade_hands  * 100 ,
        earnings = earnings, earn_rate=earnings_rate,
        create_date=web.SQLLiteral('now()'))
Example #3
0
def insert(user_id, val_sort, val_account, val_code):
    return dbw.insert(tname,
                      user_id=user_id,
                      validate_sort=val_sort,
                      validate_account=val_account,
                      validate_code=val_code,
                      code_status=0,
                      creation_date=web.SQLLiteral('now()'),
                      last_update=web.SQLLiteral('now()'))
Example #4
0
def add(form):
    i = db.insert('users',
                  username=form.username.value,
                  password=web.SQLLiteral("PASSWORD('%s')" %
                                          form.password.value),
                  created_at=web.SQLLiteral("NOW()"),
                  firstname=form.firstname.value,
                  lastname=form.lastname.value,
                  isactive=1)
    db.insert('users_roles', user_id=i, role_id=get_role_by_name('login').id)
    return i
Example #5
0
def insert2(user_id,body,device_type,device_no,local_id,created_date,last_update):
    rows = list(dbw.select(table_name,what="pk_id,body", where="user_id=$user_id",vars=locals(),order="pk_id desc", limit=80))
    for r in rows:
        if cmp(r.body,body)==0:
            return r.pk_id
    return dbw.insert(table_name,user_id=user_id,subject="",body=body,
            device_no = device_no, local_id=local_id, device_type=device_type,
            app_created_date=created_date,
            last_update=last_update,
            created_date = web.SQLLiteral('now()'),
            plan_start_date=web.SQLLiteral('now()'))
Example #6
0
def insert(user_id,subject):
    #避免重复提交
    last_one = load_last_one(user_id)
    if last_one and last_one.body.strip()==subject.strip():  
        return last_one.pk_id

    return dbw.insert(table_name,user_id=user_id,subject="",body=subject,
        created_date=web.SQLLiteral('now()'),
        app_created_date = web.SQLLiteral('now()'),
        last_update=web.SQLLiteral('now()'),
        plan_start_date=web.SQLLiteral('now()'))
Example #7
0
def insert(date, stock_no, open, close, high, low, volume):
    return dbw.insert(
        'stock_daily',
        trade_date=date,
        stock_no=stock_no,
        open=open,
        close=close,
        high=high,
        low=low,
        volume=volume,
        create_date=web.SQLLiteral('NOW()'),
        last_update=web.SQLLiteral('NOW()'),
    )
Example #8
0
    def POST(self):
        web.input()  # init web.ctx.data

        try:
            data = json.loads(web.ctx.data)
            description = data['description'].strip()
        except:
            return 0

        if len(description) == 0:
            return 0

        now = web.SQLLiteral("DATETIME('now','localtime')")

        newId = db.insert('projects',
                          description=description,
                          estimate='p50',
                          units='days',
                          userid=CurrentUser(),
                          publish=False,
                          schedule=False,
                          created=now,
                          updated=now,
                          trials=10000,
                          capacity=1)
        db.insert('tasks',
                  project=newId,
                  include=True,
                  count=1,
                  estimate=1.0,
                  risk='medium',
                  description='task 1')

        return newId
Example #9
0
def update_sogou_idf(term, count, idf):
    return dbw.update(tname,
                      sogou_ix_count=count,
                      sogou_idf=idf,
                      sogou_last_get=web.SQLLiteral('now()'),
                      where="term=$term",
                      vars=locals())
Example #10
0
def import_rows(rows):
    date = rows[0].date
    for r in rows:
        candle = r.candle_2
        results = check_exist(date, r.stock_no)
        pk_id = insert_row(date,
                           r.stock_no) if not results else results[0].pk_id
        dbw.update('stock_daily',
                   open=r.open_price,
                   close=r.close_price,
                   high=r.high_price,
                   low=r.low_price,
                   volume=r.volume,
                   amount=r.amount,
                   last_close=r.last_close,
                   high_low=r.high_low,
                   close_open=r.close_open,
                   open_last_close=r.open_last_close,
                   jump_rate=r.jump_rate,
                   price_rate=r.raise_drop_rate,
                   high_rate=r.high_rate,
                   low_rate=r.low_rate,
                   hig_low_rate=r.high_rate - r.low_rate,
                   range_1=candle[0],
                   range_2=candle[1],
                   range_3=candle[2],
                   last_update=web.SQLLiteral('NOW()'),
                   where='pk_id=$pk_id',
                   vars=locals())
Example #11
0
    def POST(self, id):
        q = "select * from projects where id=%s" % (id)
        for r in db.query(q):
            type = r.estimate
            units = r.units

        i = web.input()
        now = web.SQLLiteral("DATETIME('now','localtime')")
        newId = db.insert('projects',
                          description=i.desc,
                          estimate=type,
                          units=units,
                          userid=CurrentUser(),
                          publish=False,
                          created=now,
                          updated=now)

        q = "select * from tasks where project=%s" % (id)
        with db.transaction():
            for r in db.query(q):
                db.insert('tasks',
                          project=newId,
                          include=r.include,
                          count=r.count,
                          estimate=r.estimate,
                          risk=r.risk,
                          description=r.description)
        raise web.seeother("/project/%d/edit" % (newId))
Example #12
0
File: inds.py Project: dayzhou/inds
    def POST(self):
        try:
            f = web.input()
            user = self.check(f)
            if not user:
                self.args.username = f.username
                self.args.realname = f.realname
                return render.index('FB_FORM_FORGETPW', self.args)

            useremail = user[0].email
            newpasswd = md5rand()
            db.update(USR,
                      where="username='******'" % f.username,
                      password=web.SQLLiteral("PASSWORD('%s')" % newpasswd))
            Thread(
                target=send_email,
                kwargs={
                    'receiver': useremail,
                    'subject' : u'Your New Password',
                    'content' : u'您在ICTS文章编号分配系统的帐户密码被重置' + \
                                u'\n\nYour New Password:%s' % newpasswd + \
                                u'\n\n请尽快使用新密码登陆并修改密码'
                }
            ).start()
            return render.index('FB_MSG_RESETPW_SUCCEED', useremail)
        except Exception, e:
            write_log(e, 'FORGETPASSWORD-POST')
            return render.index('FB_FAIL_UNEXPECTED',
                                (AdminEmails, 'FORGETPASSWORD-POST', e))
Example #13
0
  def POST(self):
    if not 'user' in session or session.user is None:
      f = register_form()
      return render.login(f)
    
    i = web.input(name="", description="", subfolder="", tube_prefix="",
                  max_files=100, max_iteration=1000000,
                  ignore_duplicates=0)
    if i.name == "":
      return render.error("No project name specified")
    elif i.description == "":
      return render.error("No project description specified")
    elif i.tube_prefix == "":
      return render.error("Invalid tube prefix")
    
    if i.ignore_duplicates == "on":
      ignore_duplicates = 1
    else:
      ignore_duplicates = 0

    db = init_web_db()
    with db.transaction():
      db.insert("projects", name=i.name, description=i.description,
              subfolder=i.subfolder, tube_prefix=i.tube_prefix, 
              maximum_samples=i.max_files, archived=0,
              maximum_iteration=i.max_iteration,
              date=web.SQLLiteral("CURRENT_DATE"),
              ignore_duplicates=ignore_duplicates)

    return web.redirect("/projects")
    def POST(self):
        if not 'user' in session or session.user is None:
            f = register_form()
            return render.login(f)
        i = web.input(name="", description="", command="")

        if i.name == "":
            return render.error("No mutation engine name specified")
        elif i.description == "":
            return render.error("No mutation engine description specified")
        elif i.command == "":
            return render.error("No mutation engine command specified")
        elif i.command.find("%OUTPUT%") == -1:
            return render.error(
                "No output mutated filename specified in the mutation engine command"
            )

        db = init_web_db()
        with db.transaction():
            db.insert("mutation_engines",
                      name=i.name,
                      command=i.command,
                      description=i.description,
                      date=web.SQLLiteral("CURRENT_DATE"))
        return web.redirect("/engines")
Example #15
0
def find_author(name, send_mail=True):
    q = {'type': '/type/author', 'name': name, 'limit': 0}
    reply = list(ol.query(q))
    authors = [ol.get(k) for k in reply]
    if any(a['type'] != '/type/author' for a in authors):
        subject = 'author query redirect: ' + ` q['name'] `
        body = 'Error: author query result should not contain redirects\n\n'
        body += 'query: ' + ` q ` + '\n\nresult\n'
        if send_mail:
            result = ''
            for a in authors:
                if a['type'] == '/type/redirect':
                    result += a['key'] + ' redirects to ' + a['location'] + '\n'
                elif a['type'] == '/type/delete':
                    result += a['key'] + ' is deleted ' + '\n'
                elif a['type'] == '/type/author':
                    result += a['key'] + ' is an author: ' + a['name'] + '\n'
                else:
                    result += a['key'] + 'has bad type' + a + '\n'
            body += result
            addr = '*****@*****.**'
            #error_mail(addr, [addr], subject, body)
            db_error.insert('errors',
                            query=name,
                            result=result,
                            t=web.SQLLiteral("now()"))
        seen = set()
        authors = [
            walk_redirects(a, seen) for a in authors if a['key'] not in seen
        ]
    return authors
Example #16
0
def find_author(name, log_errors=True):
    q = {'type': '/type/author', 'name': name, 'limit': 0}
    reply = list(ol.query(q))
    authors = [ol.get(k) for k in reply]
    if any(a['type'] != '/type/author' for a in authors):
        if log_errors:
            result = ''
            for a in authors:
                if a['type'] == '/type/redirect':
                    result += a['key'] + ' redirects to ' + a['location'] + '\n'
                elif a['type'] == '/type/delete':
                    result += a['key'] + ' is deleted ' + '\n'
                elif a['type'] == '/type/author':
                    result += a['key'] + ' is an author: ' + a['name'] + '\n'
                else:
                    result += a['key'] + 'has bad type' + a + '\n'
            db_error.insert('errors',
                            query=name,
                            result=result,
                            t=web.SQLLiteral("now()"))
        seen = set()
        authors = [
            walk_redirects(a, seen) for a in authors if a['key'] not in seen
        ]
    return authors
Example #17
0
def insert_row(date, stock_no):
    return dbw.insert(
        'stock_daily',
        trade_date=date,
        stock_no=stock_no,
        create_date=web.SQLLiteral('NOW()'),
    )
Example #18
0
def register(name, password):
    #,device_type,device_no,os_type
    # mobile = 0
    # email =''
    # if '@' in name:
    #     email = name
    # else:
    #     mobile = name
    #email=email,
    user_id = dbw.insert(tname,
                         mobile=name,
                         password=password,
                         creation_date=web.SQLLiteral('now()'),
                         last_update=web.SQLLiteral('now()'),
                         last_login=web.SQLLiteral('now()'))
    return user_id
Example #19
0
def register_user(username, password, email):
    password, salt = gen_password(password)
    return db.insert(
        'users', **{
            'username': username, 'password': password,
            'email': email, 'salt': salt,
            'create_time': web.SQLLiteral("unix_timestamp(NOW())")}
    )
Example #20
0
def get_datetimestr(time=None, dbtype='mysql'):
    """得到指定时间的yyyy-mm-dd hh:mm:ss形式字符串,为数据库使用;Oracle时字符串不会自动转日期时间需要添加to_date函数"""
    time = time or datetime.now()
    retval = time.strftime('%Y-%m-%d %H:%M:%S')
    if dbtype == 'oracle':
        retval = web.SQLLiteral("to_date('%s','yyyy-mm-dd hh24:mi:ss')" %
                                retval)
    return retval
Example #21
0
    def update(task, mdb=None):
        "更新task记录"
        message = task.status_text
        if isinstance(message, (list, tuple, dict, storage)):
            message = utils.json_dumps(message)

        mdb = mdb or db.manager.master_core
        return mdb.update('task',
                          last_time=web.SQLLiteral('UNIX_TIMESTAMP()'),
                          status=task.status.value,
                          status_text=message,
                          content=utils.json_dumps(task.content),
                          exec_times=web.SQLLiteral('exec_times + 1')
                          if task._executed else web.SQLLiteral('exec_times'),
                          active_time=task.active_time,
                          where='id = $id',
                          vars=task)
Example #22
0
File: inds.py Project: dayzhou/inds
    def POST(self):  # change password or email
        try:
            if not session.user:
                raise web.seeother("login")

            f = web.input()

            if f.has_key('passwd'):
                submit = 'passwd'
                if not self.passwd_check(f):
                    self.args.password = f.password
                    self.args.newpassword = f.newpassword
                    self.args.newpw2 = f.newpw2
                    return render.user('FB_OP_PASSWD', self.args)
            elif f.has_key('email'):
                submit = 'email'
                if not self.email_check(f):
                    self.args.password = f.password
                    self.args.newemail = f.newemail
                    return render.user('FB_OP_EMAIL', self.args)

            if submit == 'passwd':
                db.update(USR,
                          where="username='******'" % session.user.username,
                          password=web.SQLLiteral("PASSWORD('%s')" %
                                                  f.newpassword))
                Thread(
                    target=send_email,
                    kwargs={
                        'receiver': session.user.email,
                        'subject' : u'Your Password Has Changed',
                        'content' : u'您在ICTS文章编号分配系统的帐户密码已被修改' + \
                                    u'\n\nYour New Password:%s' % f.newpassword
                    }
                ).start()
                return render.user('FB_MSG_PWCHANGED')
            elif submit == 'email':
                db.update(USR,
                          where="username='******'" % session.user.username,
                          email=f.newemail)
                session.user.email = f.newemail
                Thread(
                    target=send_email,
                    kwargs={
                        'receiver': f.newemail,
                        'subject' : 'Your Email Address Has Changed',
                        'content' : u'您在ICTS文章编号分配系统的帐户邮箱已被修改为当前邮箱' + \
                                    u'\n\n%s\n(如果您不知道为何收到本邮件,请忽略它)' % ( '-' * 50 )
                    }
                ).start()
                return render.user('FB_MSG_EMCHANGED', (f.newemail, ))

        except web.SeeOther:
            return
        except Exception, e:
            write_log(e, 'GENERALUSER-POST')
            return render.index('FB_FAIL_UNEXPECTED',
                                (AdminEmails, 'GENERALUSER-POST', e))
Example #23
0
def term_insert(term):
    tname = 'terms'
    result = list(dbr.select(tname, where="term=$term", vars=locals()))
    if not result:
        return dbw.insert(tname,
                          term=term,
                          term_len=len(term),
                          last_update=web.SQLLiteral('now()'))
    return result[0].term_id
Example #24
0
 def POST(self):
     i = web.input()
     id = db.insert('projects',
                    description=i.desc,
                    estimate='p50',
                    units='days',
                    userid=CurrentUser(),
                    publish=False,
                    created=web.SQLLiteral("DATETIME('now','localtime')"),
                    updated=web.SQLLiteral("DATETIME('now','localtime')"))
     db.insert('tasks',
               project=id,
               include=True,
               count=1,
               estimate=1.0,
               risk='medium',
               description='task 1')
     raise web.seeother("/project/%d/edit" % (id))
    def POST(self):
        if not 'user' in session or session.user is None:
            f = register_form()
            return render.login(f)

        i = web.input(name="",
                      description="",
                      subfolder="",
                      tube_prefix="",
                      max_files=100,
                      max_iteration=1000000,
                      ignore_duplicates=0)
        if i.name == "":
            return render.error("No project name specified")
        elif i.description == "":
            return render.error("No project description specified")
        elif i.tube_prefix == "":
            return render.error("Invalid tube prefix")

        if i.ignore_duplicates == "on":
            ignore_duplicates = 1
        else:
            ignore_duplicates = 0

        db = init_web_db()
        sql = """select value from config where name in ('WORKING_PATH')"""
        res = db.query(sql)
        res = list(res)
        working_path = res[0]['value']

        with db.transaction():
            db.insert("projects",
                      name=i.name,
                      description=i.description,
                      subfolder=i.subfolder,
                      tube_prefix=i.tube_prefix,
                      maximum_samples=i.max_files,
                      archived=0,
                      maximum_iteration=i.max_iteration,
                      date=web.SQLLiteral("CURRENT_DATE"),
                      ignore_duplicates=ignore_duplicates)

        project_folder = os.path.join(working_path, i.subfolder)
        if not os.path.exists(project_folder):
            os.makedirs(project_folder)

        if not os.path.exists(os.path.join(project_folder, "samples")):
            os.makedirs(os.path.join(project_folder, "samples"))

        if not os.path.exists(os.path.join(project_folder, "templates")):
            os.makedirs(os.path.join(project_folder, "templates"))

        if not os.path.exists(os.path.join(project_folder, "input")):
            os.makedirs(os.path.join(project_folder, "input"))

        return web.redirect("/projects")
Example #26
0
def update(pk_id, result):
    dbw.update('stock_base_infos',
               days_count_5=result.days_count_5,
               trend_5=result.trend_5,
               trend_3=result.trend_3,
               prate_3=result.prate_3,
               prate_5=result.prate_5,
               ratetrend_date=web.SQLLiteral('NOW()'),
               where='pk_id=$pk_id',
               vars=locals())
Example #27
0
 def add(task, mdb=None):
     "添加任务记录"
     mdb = mdb or db.manager.master_core
     return mdb.insert('task',
                       type=task.type.value,
                       type_id=task.type_id,
                       content=utils.json_dumps(task.content),
                       time_created=web.SQLLiteral('UNIX_TIMESTAMP()'),
                       active_time=task.active_time,
                       last_time=task.last_time,
                       tail_num=task.tail_num)
Example #28
0
 def companyConfirm(self, openid, company_id):
     icfg.db.update("Company",
                    where="id=$company_id",
                    confirmed_at=web.SQLLiteral('NOW()'),
                    owner_openid=openid,
                    vars=locals(),
                    valid="有效")
     cfgPara = {'openid': openid}
     cfgPara["result"] = "success"
     ret = uTools.formatPostMsg(cfgPara)
     return ret
Example #29
0
def UpdateProject(id, wi, tasks):
    pub =  bool(wi.get('publish'))
    now = web.SQLLiteral("DATETIME('now','localtime')")
    db.update('projects', where="id=%s" % (id), description=wi.project, estimate=wi.type, units=wi.units, userid=CurrentUser(), publish=pub, updated=now)
    
    q = "delete from tasks where project=%s" % (id)
    db.query(q)
    for task in tasks:
        desc, count, median, risk, inc, rem = task
        if desc and median and risk and not rem:
            db.insert('tasks', project=id, description=desc, count=count, estimate=median, risk=risk, include=inc)
Example #30
0
def get_access_token(user_id, device_no, device_type, os_type, channel,
                     version):
    result = list(
        dbr.select('user_devices',
                   what="user_id,device_no,access_token,device_type,os_type",
                   where="user_id=$user_id and device_no=$device_no",
                   vars=locals()))

    access_token = generate_access_token()
    if not result:
        dbw.insert('user_devices',
                   user_id=user_id,
                   device_no=device_no,
                   device_type=device_type,
                   os_type=os_type,
                   access_token=access_token,
                   channel=channel,
                   version=version,
                   creation_date=web.SQLLiteral('now()'),
                   last_update=web.SQLLiteral('now()'))

        result = list(
            dbr.select(
                'user_devices',
                what="user_id,device_no,access_token,device_type,os_type",
                where="user_id=$user_id and device_no=$device_no",
                vars=locals()))
    else:
        dbw.update('user_devices',
                   device_no=device_no,
                   device_type=device_type,
                   os_type=os_type,
                   access_token=access_token,
                   channel=channel,
                   version=version,
                   last_update=web.SQLLiteral('now()'),
                   where="user_id=$user_id and device_no=$device_no",
                   vars=locals())
        result[0].access_token = access_token

    return load_user(result[0].user_id)