Exemplo n.º 1
0
def update_post(id=None, where=None, vars=None, **values):
    if id is not None:
        where = 'id=$id'
        vars = {'id': id}

    filter_values(values)
    tags = values.pop('tags', None)
    category_ids = values.pop('category_ids', None)

    values['modified'] = datetime.utcnow()
    t = db.transaction()
    try:
        db.update('posts', where=where, vars=vars, **values)

        if tags:
            tag_model.save_tag_relationships(post_id, 'post', tags)

        if category_ids:
            category_model.save_category_relationships(post_id, category_ids)
    except:
        t.rollback()
        return False
    else:
        t.commit()
        return True
Exemplo n.º 2
0
def make_attendee(ids, user_id):
    print(ids)
    ids = web.sqllist(map(str, ids))
    db.update('applicants',
              where='id in (%s)' % ids,
              status='attendee',
              decided_by_user_id=user_id)
Exemplo n.º 3
0
def execute_task(task_id):
    """执行任务"""
    # 取任务信息
    task_hash_key = '%s%s' % (task_detail_key_prefix, task_id)
    current_task_settings = redis_cursor.hgetall(task_hash_key)
    task_type = current_task_settings['type']
    current_task_settings['task_id'] = task_id
    logging.debug('current_task_settings: {0}'.format(current_task_settings))

    update_task_state(task_id, 1)

    # 开始扫描
    tasks = []

    task_runner = load_task(task_type)(**current_task_settings)
    task_runner_thread = threading.Thread(target=task_runner.run)
    tasks.append(task_runner_thread)
    task_runner_thread.setDaemon(True)
    task_runner_thread.start()

    while not misc.is_threads_done(tasks):
        logging.debug('111')
        time.sleep(0.1)

    db.update('''
        UPDATE
            `system_task_records`
        SET
            `finish_time` = %s,
            `state` = %s
        WHERE
            `id` = %s''',
              misc.now(),
              2,
              task_id)
Exemplo n.º 4
0
 def moveData2History(self):
     #step0: 判定是否需要启动数据搬迁>_max_start_num
     _ret = db.query("SELECT COUNT(*) AS sum FROM HistoryTrack")
     if _ret[0].sum<_max_start_num:
         return 0
     #step1:确定当前流入历史库的速度
     incrNum   = self.getCurrentInputSpeed()
     #step2: 确定迁移的目标数据库
     selTable =self.getInput2Table(incrNum)
     selTableId = selTable.id
     #step3: 确定选定要迁移的数据
     items = db.query("SELECT * FROM HistoryTrack ORDER BY report_at LIMIT {0}".format(incrNum))
     for i in range(incrNum):
         item = items[i]
         if selTable.sum==0:
             db.update("HistoryTrackTable",where='id=$selTableId',
                                          from_time=item.report_at.strftime("%Y-%m-%d %H:%M:%S"),
                                          vars=locals())
         #将数据移入新的数据库
         db.insert(selTable.tableName,imei   =  item.imei,          
                             report_at       =  item.report_at,     
                             gpsLat    	    =  item.gpsLat,    	  
                             gpsLng          =  item.gpsLng,        
                             speed     	    =  item.speed,     	  
                             realState       =  item.realState,     
                             lngType         =  item.lngType,       
                             latType         =  item.latType,       
                             direction       =  item.direction,     
                             addr            =  item.addr,          
                             province        =  item.province,     
                             city            =  item.city,          
                             gpsReport       =  item.gpsReport,     
                             reportMode      =  item.reportMode,    
                             ACC             =  item.ACC,           
                             CellID          =  item.CellID,        
                             LAC             =  item.LAC,           
                             MNC             =  item.MNC,           
                             MCC             =  item.MCC,           
                             satNum          =  item.satNum,        
                             locatedState    =  item.locatedState,  
                             gpsTime         =  item.gpsTime,       
                             qqLat           =  item.qqLat,         
                             qqLng           =  item.qqLng,         
                             baiduLat        =  item.baiduLat,      
                             baiduLng        =  item.baiduLng,      
                             country         =  ('中国' if item.country is None else item.country),       
                             alarm           =  ('' if item.alarm is None else item.alarm),        
                             height          =  item.height,        
                             battery         =  item.battery,       
                             gsm_intensity   =  item.gsm_intensity,      
                             seatStatus      =  item.seatStatus,    
                             mileage         =  item.mileage,      
         )               
         #删除原来库的数据
         db.query("DELETE FROM HistoryTrack WHERE id={0}".format(item.id))
     #刷新截至时间与最新数据
     db.update("HistoryTrackTable",where='id=$selTableId',
                                   sum = selTable.sum+incrNum,
                                   to_time=item.report_at.strftime("%Y-%m-%d %H:%M:%S"),vars=locals())
     return incrNum
Exemplo n.º 5
0
def update_issue(issue_id, content, status, priority, milestone_id, user_id, category, assignee):
    issue = db.select('issue', where='id=$issue_id', vars=locals())[0]
    db.update(
            'issue',
            where='id=$issue_id',
            vars=locals(),
            status=status,
            priority=priority,
            milestone_id=milestone_id,
            category_id=category,
            assignee_id=assignee)
    return db.insert(
            'issue_update',
            issue_id=issue_id,
            content=content,
            user_id=user_id,
            old_category=issue.category_id,
            new_category=category,
            old_assignee=issue.assignee_id,
            new_assignee=assignee,
            old_status=issue.status,
            new_status=status,
            old_priority=issue.priority,
            new_priority=priority,
            old_milestone=issue.milestone_id,
            new_milestone=milestone_id)
Exemplo n.º 6
0
    def POST(self, client_id, entry_id=None):
        entry = get_one("time_entries", entry_id)
        f = self.form(client_id)
        if f.validates():
            date_str = "{} {}".format(f.d.start_date.strip(),
                                      f.d.start_time.strip())
            start_time = end_time = datetime.strptime(date_str,
                                                      "%m/%d/%Y %I:%M %p")

            end_time = utils.compute_end_time(f.d.duration, start_time)
            if entry:
                db.update("time_entries",
                          where="id=$entry_id",
                          vars={'entry_id': entry_id},
                          description=f.d.description,
                          start_time=start_time,
                          end_time=end_time,
                          category_id=f.d.category_id)
            else:
                db.insert("time_entries",
                          client_id=client_id,
                          description=f.d.description,
                          start_time=start_time,
                          end_time=end_time,
                          category_id=f.d.category_id)
            raise web.seeother("/clients/%s/entries/" % client_id)
        else:
            return render.form(f)
Exemplo n.º 7
0
def nodeUpdate(arg, **kw):
    # if not nodeOpen:
    #     nodeOpen = '0'
    # else:
    #     nodeOpen = '1'

    db.update('_node', vars=dict(id=arg), where='id = $id', **kw)
Exemplo n.º 8
0
def nodeUpdate(arg, **kw):
    # if not nodeOpen:
    #     nodeOpen = '0'
    # else:
    #     nodeOpen = '1'

    db.update('_node', vars=dict(id=arg), where='id = $id', **kw)
Exemplo n.º 9
0
def saveTitleDescribe(imagePath, imageTitle, imageDescribe):
    for i in xrange(len(imagePath)):
        db.update(
            'image',
            vars=dict(path=imagePath[i]),
            where='path = $path',
            imageDescribe=imageDescribe[i].strip().replace("\r\n", " "),
            imageTitle=imageTitle[i])  #这个imageDescribe需要替换回车,花了我好多时间才知道怎么替换
Exemplo n.º 10
0
def update_unreaded_articles_board(uid, bSerial):
    subscription = db.select('Subscriptions', dict(uid=uid, bSerial=bSerial), where='uSerial=$uid and bSerial=$bSerial')
    if len(subscription) is not 0:
        sub = subscription[0]
        val = dict(uSerial = uid, bSerial = sub.bSerial, subscriptedDate = sub.lastSubscriptedDate)
        db.query('INSERT ignore INTO UserArticles (SELECT $uSerial, aSerial, NOW() FROM Articles WHERE bSerial = $bSerial AND aUpdatedDatetime > $subscriptedDate)', val)

        db.update('Subscriptions', vars=dict(uSerial=uid, bSerial=sub.bSerial), where='uSerial=$uSerial and bSerial = $bSerial', lastSubscriptedDate = web.SQLLiteral('NOW()'))
Exemplo n.º 11
0
def update_data(object_id, question_id, value):
    '''Updates the weight for a specified object_id and question_id in data with
       the specified value.'''

    db.update('data',
              where='object_id = $object_id AND question_id = $question_id',
              vars=locals(),
              value=value)
Exemplo n.º 12
0
def update_times_played(object_id):
    '''Increments the number of times played for a particular object_id.'''
    current = db.select('objects', vars=locals(),
                        where='id=$object_id')[0].times_played
    if current == None: current = 0
    db.update('objects',
              where='id = $object_id',
              vars=locals(),
              times_played=current + 1)
Exemplo n.º 13
0
def login(username, password):
    where = 'username=$username AND password=$password'
    vars = {'username': username, 'password': md5(password).hexdigest()}
    try:
        user = db.select('users', what='id, username, last_login', where=where, vars=vars, limit=1)[0]
        db.update('users', where=user['id'], **{'last_login': datetime.utcnow()})
        return user
    except IndexError:
        return False;
Exemplo n.º 14
0
 def POST(self, client_id, invoice_id):
     i = web.input(receipt={}, status="")
     to_update = {'status': i.status}
     if i.receipt.filename:
         to_update = {'receipt_name': i.receipt.filename,
                      'receipt': buffer(i.receipt.file.read())}
     db.update("invoices", where="id=$invoice_id and client_id=$client_id",
               vars=locals(), **to_update)
     raise web.seeother("/clients/%s/invoices/" % client_id)
Exemplo n.º 15
0
def make_single_read(id, uid):
    db.update('_notification',
              vars=dict(id=id, aid=uid),
              where='id = $id and aid=$aid',
              isread=1)
    db.update('_notification_mention',
              vars=dict(id=id, mid=uid),
              where='id = $id and mid=$mid',
              isread=1)
Exemplo n.º 16
0
def make_all_read(id_list, uid):
    for id in id_list:
        db.update('_notification',
                  vars=dict(id=id, aid=uid),
                  where='id = $id and aid=$aid',
                  isread=1)
        db.update('_notification_mention',
                  vars=dict(id=id, mid=uid),
                  where='id = $id and mid=$mid',
                  isread=1)
Exemplo n.º 17
0
 def POST(self, client_id=None):
     f = self.form()
     if f.validates():
         if client_id:
             db.update("clients", where="id=$client_id",
                       vars=locals(), **f.d)
         else:
             db.insert("clients", **f.d)
         raise web.seeother("/clients/")
     else:
         return render.form(f)
Exemplo n.º 18
0
def update_calculated_votes(applicant_id):
    calculated = \
    db.select('votes', 
        vars = dict(applicant_id=applicant_id),
        what = 'sum(score) / count(score) as vote, count(score) as vote_counts',       
        where = 'applicant_id = $applicant_id')[0]
    
    db.update('applicants', 
        vars = dict(id=applicant_id),
        where = 'id = $id',
        calculated_vote = calculated.vote, calculated_vote_counts = calculated.vote_counts)
Exemplo n.º 19
0
 def POST(self, client_id, category_id=None):
     client = get_one("clients", client_id)
     category = get_one("categories", category_id)
     form = self.form()
     if not form.validates():
         return render.form(form)
     if category:
         db.update("categories",  where="id=$cat_id",
                   vars={'cat_id': category.id}, name=form.d.name)
     else:
         get_or_create_category(client, form.d.name)
     raise web.seeother("/clients/%s/categories/" % client_id)
Exemplo n.º 20
0
def update_calculated_votes(applicant_id):
    calculated = \
    db.select('votes',
        vars = dict(applicant_id=applicant_id),
        what = 'sum(score) / count(score) as vote, count(score) as vote_counts',
        where = 'applicant_id = $applicant_id')[0]

    db.update('applicants',
              vars=dict(id=applicant_id),
              where='id = $id',
              calculated_vote=calculated.vote,
              calculated_vote_counts=calculated.vote_counts)
Exemplo n.º 21
0
def save_sort(pids, nids):
    #note: 可以优化 因为有时候只是修改了node sort,post sort根本没变
    for i in xrange(len(pids)):
        db.update('_admin_rec_home',
                  vars=dict(pid=pids[i]),
                  where='pid = $pid',
                  pid_sort=i + 1)
    for i in xrange(len(nids)):
        db.update('_admin_rec_home',
                  vars=dict(nid=nids[i]),
                  where='nid = $nid',
                  nid_sort=i + 1)
Exemplo n.º 22
0
def modify_user(uid, member):
    """
    회원 정보 수정. frontend에서 접근 권한을 통제해야 한다. 시삽은 임의
    회원의 정보를 수정할 수 있다. C{member} 딕셔너리는 수정할 정보로,
    형식은 L{register}를 참고한다. 빈 값이 들어오면 삭제를 의미하므로,
    기존 정보를 수정하려면 정보를 그대로 넘겨줘야 한다.

    @type uid: int
    @param uid: 수정할 회원의 사용자 ID.
    @type member: dict
    @param member: 회원 정보 딕셔너리. (password: 암호, email: E-Mail,
    homepage: 홈페이지, sig: 시그, introduction: 자기 소개)
    @rtype tuple
    @return: 정보 수정 성공 여부(T/F)와 오류 코드(실패 시)를 포함하는 튜플.
    """
    profile_image_path = os.path.join(config.pi_disk_path, '%s.png' % member['user_id'])
    m = magic.Magic(mime = True)
    mime_type = m.from_buffer(member['profile_image'])
    if member['delete_profile_image']:
        if os.path.exists(profile_image_path):
            os.remove(profile_image_path)
    else:
        if mime_type.startswith('image'):
            image_file = StringIO.StringIO(member['profile_image'])
            if pil:
                pi = Image.open(image_file)
                r = pi.resize(config.pi_size, Image.ANTIALIAS)
                r.save(profile_image_path)

    t = db.transaction()
    try:
        if member['password']:
            result = db.update('Users', vars=member, where='uSerial = $user_id',
                    uNick = member['nick'], uEmail = member['email'],
                    uSig = member['sig'], uPlan = member['introduction'],
                    uHomepage = member['homepage'],
                    language = member['language'],
                    theme = member['theme'],
                    uPasswd = generate_password(member['password']))
        else:
            result = db.update('Users', vars=member, where='uSerial = $user_id',
                    uNick = member['nick'], uEmail = member['email'],
                    uHomepage = member['homepage'],
                    uSig = member['sig'], uPlan = member['introduction'],
                    language = member['language'],
                    theme = member['theme'])
    except:
        t.rollback()
        return False
    else:
        t.commit()
    return result
Exemplo n.º 23
0
def update_calculated_vote(module_id):
    min_votes = 5
    r = web.listget(
        db.select('votes',
            vars = dict(id=module_id),
            what = 'sum(vote) / count(module_id) as calculated_vote', 
            where = 'module_id = $id',
            group = 'module_id having count(module_id) > %s' % min_votes), 0, False)
    
    if r:
        db.update('modules', 
            vars = dict(id=module_id),
            where='id = $id',    
            calculated_vote=r.calculated_vote)
Exemplo n.º 24
0
 def update(self):
     self.pre_update and self.pre_update()
     D = {}
     for k, v in self.__mappings__.iteritems():
         if v.updatable:
             if hasattr(self, k):
                 arg = getattr(self, k)
             else:
                 arg = v.default
                 setattr(self, k, arg)
             D[k] = arg
     pk = self.__primary_key__.name
     value = getattr(self, pk)
     db.update(self.__table__, where="{}=$value".format(pk), vars={'value': value}, **D)
     return self
Exemplo n.º 25
0
 def changeKey(self,data,uid):
     import re
     import hashlib
     user=data.Name.strip()
     pwd1=data.Pwd1.strip()
     pwd2=data.Pwd2.strip()
     u_r=re.compile(r"^\w{1,10}$")
     p_r=re.compile(r"^[\x21-\x7e]{5,16}$")
     if pwd1!=pwd2:raise Exception
     if u_r.match(user) and p_r.match(pwd1):
         db.update("accounts",where="Uid=%d"%int(uid),
                 UserName=user,
                 PassWord=hashlib.md5(pwd1).hexdigest())
     else:
         raise Exception
Exemplo n.º 26
0
def update_group(group_info):

    s = app.helpers.session.get_session()

    if 'is_active' in group_info:
        group_info.is_active = '1'
    else:
        group_info.is_active = '0'

    result = db.update('groups',
                        where='id = $id',
                        vars={'id': group_info.id},
                        name=group_info.name, description=group_info.description, email=group_info.email, lastupdated=int(time.time()), lastupdatedby=s.userid, is_active=group_info.is_active)

    # initiate dictionary
    records = {}

    # se last_insert_rowid == True, assume que grupo foi atualizado com sucesso
    if result == 1:
        # set response message to OK
        records['Result'] = 'OK'
    else:
        records['Result'] = 'ERROR'
        records['Message'] = 'Nenhuma informação alterada'

    return json.dumps(records)
Exemplo n.º 27
0
 def changeKey(self, data, uid):
     import re
     import hashlib
     user = data.Name.strip()
     pwd1 = data.Pwd1.strip()
     pwd2 = data.Pwd2.strip()
     u_r = re.compile(r"^\w{1,10}$")
     p_r = re.compile(r"^[\x21-\x7e]{5,16}$")
     if pwd1 != pwd2: raise Exception
     if u_r.match(user) and p_r.match(pwd1):
         db.update("accounts",
                   where="Uid=%d" % int(uid),
                   UserName=user,
                   PassWord=hashlib.md5(pwd1).hexdigest())
     else:
         raise Exception
Exemplo n.º 28
0
def update_message(message_info):

    s = app.helpers.session.get_session()

    if 'is_active' in message_info:
        message_info.is_active = '1'
    else:
        message_info.is_active = '0'

    result = db.update('messages',
                        where='id = $id',
                        vars={'id': message_info.id},
                        title=message_info.title, message=message_info.message, lastupdated=int(time.time()), lastupdatedby=s.userid, is_active=message_info.is_active)

    # initiate dictionary
    records = {}

    # se last_insert_rowid == True, assume que grupo foi atualizado com sucesso
    if result == 1:
        # set response message to OK
        records['Result'] = 'OK'
    else:
        records['Result'] = 'ERROR'
        records['Message'] = 'Nenhuma informação alterada'

    return json.dumps(records)
Exemplo n.º 29
0
    def interact(cls, line, stdin):
        """Handle text output of mplayer, line by line.

        The data contains ICY data / track metadata.
        """
        logger = logging.getLogger("oxo")
        if line.startswith("ICY"):
            logger.debug("Found ICY data: {}".format(line))
            s = "StreamTitle="
            start = line.find(s) + len(s) + 1
            end = line.find(";", start) - 1
            if start and end:
                title = line[start:end]
                logger.debug("Found title in ICY: {}".format(title))
                if len(title) > 0:
                    q = Query()
                    db.update({"station_title": title}, q.type == "radio")
Exemplo n.º 30
0
    def POST(self, client_id):
        start = datetime.now().date().replace(day=1)
        start = datetime(start.year, start.month, start.day)
        earliest = time_entries(
            "time_entries.client_id=$client_id and invoice_id is null",
            client_id=client_id)[0]

        beg_month = earliest.start_time.date().replace(day=1)
        invoice_id = db.insert("invoices",
                               month=beg_month,
                               client_id=client_id,
                               status='billed')
        db.update('time_entries',
                  where="client_id=$client_id and invoice_id is null",
                  vars=locals(),
                  invoice_id=invoice_id)
        raise web.seeother("/clients/%s/entries/" % client_id)
Exemplo n.º 31
0
 def get_next(cls):
     """Select recently added video or a random one from db."""
     q = Query()
     q_incoming = db.search(q.incoming == True)
     if len(q_incoming) > 0:
         rv = q_incoming[0]
         db.update({"incoming": False}, q.incoming == True)
         logger.info("Enqueuing shortlisted clip {}".format(rv["filename"]))
     else:
         q = Query()
         try:
             q_clips = db.search(q.type == "clip")
         except JSONDecodeError:
             rv = None
         else:
             rv = choice(q_clips) if len(q_clips) > 0 else None
     return rv
Exemplo n.º 32
0
def save_setting(data):
    setting = get_setting()
    keys = setting.keys()
    rows = []

    for key, value in data.iteritems():
        if key in keys and value != setting[key]:
            rows.append({'key': key, 'value': value})
            setting[key] = value

    if rows:
        for row in rows:
            where = '`key`=$key'
            vars = {'key': row['key']}
            db.update(
                'settings', where=where, vars=vars, **{'value': row['value']})

    update_view_site_setting()
    return True
Exemplo n.º 33
0
def add_reg(uid,s):
    with db.transaction():
        db.insert('reg_log',uid = uid ,
                  studentid=s.studentid,
                  college=s.college,
                  name=s.name,
                  telephone=s.telephone,
                  gender=s.gender,
        )
        db.update('users', vars = dict(uid=uid),
                  where = 'uid = $uid',
                  studentid=s.studentid,
                  college=s.college,
                  name=s.name,
                  telephone=s.telephone,
                  gender=s.gender,
        )
        return True
    return False
Exemplo n.º 34
0
    def send_title(cls, bot, job):
        """Send current title to chat."""
        logger = logging.getLogger("oxo")

        q, state = Radio.state()
        t = state.get("station_title")
        t0 = state.get("station_title_sent")

        if t != t0:
            if t:
                msg = "▶️ Now playing {}".format(t)
                bot.sendMessage(chat_id=job.context, text=msg)
                if t.find(" - "):
                    cls.send_research(t[:t.find(" - ")], bot, job)
                else:
                    logger.debug("Not compiling research for this title")
            logger.debug("Title changed from '{}' to '{}'".format(t0, t))

            db.update({"station_title_sent": t}, q.type == "radio")
Exemplo n.º 35
0
def board_edit(current_uid, board_id, settings):
    # settings로 넘어오는 내용
    # path, name: 보드 전체 경로
    # description: 보드 짧은 설명
    # owner: 보대 ID. uid로 변환해야 함.
    # cover: 긴 설명, cover에 들어가는 내용
    # board_type: 0 - 폴더, 1 - 게시판
    # can_write_by_other: 쓰기 가능/불가능
    # can_comment: 0 - 불가능, 1 - 가능
    # indexable: 0 - 검색 제외, 1 - 검색 포함
    # show_avatar: 0 - 안 보임, 1 - 보임
    if not acl.is_allowed('board', board_id, current_uid, 'edit'):
        return (False, _('NO_PERMISSION'))
    original_board_info = get_board_info(board_id)
    if original_board_info == None:
        return (False, _('NO_SUCH_BOARD'))
    settings['board_id'] = board_id
    new_path = posixpath.join(settings['path'], settings['name'])
    if not util.validate_boardname(new_path):
        return (False, _('INVALID_BOARDNAME'))
    if settings['board_type'] == 2:
        if article._get_article_count(board_id) > 0:
            return (False, _('ALIAS_CANT_HAVE_ARTICLE'))
        if _get_board_id_from_path(settings['description']) < 0 or settings['description'].strip() == '':
            return (False, _('NO_SUCH_BOARD'))
    old_path = original_board_info.bName
    old_directory = posixpath.dirname(old_path)
    new_directory = settings['path']
    if _get_board_id_from_path(new_path) > 0 and old_path != new_path:
        return (False, _('BOARD_ALREADY_EXIST'))
    new_parent_id = _get_board_id_from_path(settings['path'])
    if new_parent_id < 0:
        return (False, _('INVALID_PARENT'))
    if new_parent_id != original_board_info.bParent:
        if not acl.is_allowed('board', new_parent_id, current_uid, 'create'):
            return (False, _('NO_PERMISSION_ON_NEW_PARENT'))

    t = db.transaction()
    try:
        result = db.update('Boards', vars=settings, where='bSerial = $board_id',
                bInformation = settings['cover'], bDescription = settings['description'],
                bType = settings['board_type'], 
                bReply = 1, bComment = settings['can_comment'],
                indexable = settings['indexable'], 
                stylesheet = settings['stylesheet'],
                show_avatar = settings['show_avatar'],
                bWrite = settings['can_write_by_other'], 
                uSerial = settings['owner'],
                bName = new_path, bParent = new_parent_id)
        result = move_child_boards(board_id, old_path, new_path)
    except:
        t.rollback()
    else:
        t.commit()
    return (True, new_path)
Exemplo n.º 36
0
    def POST(self):
        events = [web.storage(e) for e
                  in gcal.fetch_events(config.g_username,
                                       config.g_password,
                                        config.g_calendar_name)]

        for event in events:
            client = get_safe(db.select("clients",
                                        where="lower(name)=lower($name)",
                                        vars={'name': event.client_name}))
            if not client:
                event['status'] = 'Client could not be found.'
                continue
            category_id = None
            if event.category_name:
                category = get_or_create_category(client, event.category_name)
                category_id = category.id

            entry = get_safe(db.select("time_entries",
                                       where="external_reference=$ref",                                      vars={'ref': event.id}))
            if not entry:
                db.insert("time_entries",
                          client_id=client.id,
                          description=event.description,
                          start_time=event.start,
                          end_time=event.end,
                          category_id=category_id,
                          external_reference=event.id)
                event.status = 'Creating new time entry'

            elif entry.invoice_id:
                event.status = 'Skipping, entry has already been invoiced.'
            else:
                db.update("time_entries",
                          where="id=$entry_id",
                          vars={'entry_id': entry.id},
                          description=event.description,
                          start_time=event.start,
                          end_time=event.end,
                          category_id=category_id)
                event.status = 'Updated time entry'
        return render.fetch_status(events=events)
Exemplo n.º 37
0
def update_new_article_none_hit(uid):
    t = db.transaction()
    try:
        result = db.update('Users', vars=locals(), where = 'uSerial = $uid',
                new_article_none_hit = web.SQLLiteral('new_article_none_hit + 1'))
    except:
        t.rollback()
        return False
    else:
        t.commit()
    return result
Exemplo n.º 38
0
Arquivo: pm.py Projeto: peremen/noah3k
def mark_as_read(mail_id):
    t = db.transaction()
    try:
        result = db.update('Mails', vars=locals(), where='mSerial = $mail_id',
            mMark = 1)
    except:
        t.rollback()
        return False
    else:
        t.commit()
        return True
Exemplo n.º 39
0
def import_db(pk_id,bd_imgs,attrs):
    field_values = ['last_update=now()'] 
    raw_kv = [] 
    for attr in attrs:
        k =  attr.split(',')[0].replace('"','').strip()  
        v = attr.split(':')[-1].replace('"','').strip() 
        raw_kv.append('"%s":"%s"'%(k,v))
        if k in cn_fields.keys():
            field = cn_fields[k]             
            field_values.append("%s='%s'" %(field,v))
    if field_values:
        sql = "update plants set %s where pk_id=%s" % (','.join(field_values),pk_id) 
        db.query(sql) 
      

    str_attrs = ','.join(raw_kv)    
    db.update('plants',
        bd_imgs = bd_imgs,
        bd_baike = str_attrs,
        where="pk_id=$pk_id",vars=locals())
Exemplo n.º 40
0
def backpopulateCurrentFrameScores():
    t = db.transaction()

    try:
        breaks = list(
            db.query("""
                        SELECT * FROM tbreak
                    """))

        for breakx in breaks:
            frame_score, foul_points = tframe.getCurrentFrameScore(
                breakx['frame_id'],
                breakx['player_id'],
                break_num=breakx['break_num'],
                foul_num=breakx['foul_num'])

            rowcount = db.update('tbreak',
                                 where='break_id=$break_id',
                                 vars={'break_id': breakx['break_id']},
                                 frame_score=frame_score)

            opp_frame_score, opp_foul_points = tframe.getCurrentFrameScore(
                breakx['frame_id'],
                breakx['player_id'],
                break_num=breakx['break_num'],
                foul_num=breakx['foul_num'],
                opponent=True)

            rowcount += db.update('tbreak',
                                  where='break_id=$break_id',
                                  vars={'break_id': breakx['break_id']},
                                  opp_frame_score=opp_frame_score)

            if rowcount != 2:
                print "F*****G HELL"
                raise
    except:
        t.rollback()
        raise
    else:
        t.commit()
Exemplo n.º 41
0
def commitMatch(match_id):
    try:
        rowcount = db.update('tmatch',
                                where='match_id=$match_id',
                                vars={'match_id':match_id},
                                confirmed="Y")

        if rowcount != 1:
            error = "Bad number of rows deleted: "
            raise
    except:
        log.error('Failed to commit match '+str(match_id))
Exemplo n.º 42
0
    def update_competition_by_public_id(self, public_id: str, status: str,
                                        name: str, event_date: str,
                                        modality: str) -> dict:

        query = db.update(competitions_table).values(
            status=status,
            name=name,
            event_date=event_date,
            modality=self.modality[f"{modality}"])
        query = query.where(competitions_table.columns.public_id == public_id)
        results = connection.execute(query)
        return results
Exemplo n.º 43
0
    def run(self):
        """Thread target."""
        self.stopped = False
        current_url = None
        current_title = None

        q, state = Radio.state()
        db.update({"station_title": None}, q.type == "radio")

        while not self.stopped:
            # Restart mplayer whenever station changes
            q, state = Radio.state()
            title = state.get("station_title")

            q_station = db.search(q.name == state.get("station_playing"))
            url = q_station[0]["url"] if len(q_station) > 0 else None

            if current_url != url:
                self.logger.debug("Station changed")
                try:
                    self.stop()
                    self.player = None
                    self.stopped = False  # keep this loop running
                except Exception as e:
                    self.logger.debug("Player is already stopped {}".format(e))

                if url is not None:
                    self.logger.info("Playing {}".format(url))
                    self.player = mplayer(url,
                                          _bg=True,
                                          _out=self.interact,
                                          _ok_code=[0, 1])

                current_url = url

            elif current_title != title:
                current_title = title
                self.logger.info("Title is {}".format(current_title))

            sleep(1)
Exemplo n.º 44
0
def update_last_login(uid, ip_address):
    val = dict(uid = uid, ip_address = ip_address)
    t = db.transaction()
    try:
        result = db.update('Users', vars=val, where = 'uSerial = $uid',
                uNumLogin = web.SQLLiteral('uNumLogin + 1'),
                uLastLogin = web.SQLLiteral('NOW()'),
                uLastHost = ip_address)
    except:
        t.rollback()
        return False
    else:
        t.commit()
    return result
Exemplo n.º 45
0
 def POST(self):
     import time
     data=web.input()
     try:
         bug=db.update("bugs",where="Pid = %s and IsOver=0"%data.YesPid,
             YesWhy=data.YesContent,
             IsOver=1,YesNo=data.YesNo,
             YesTime=time.strftime("%Y-%m-%d %T",time.localtime()))
     except:
         return "提交失败,请返回重试"
     if not bug:
         return self.MESS
     else:
         raise web.seeother('/list')
Exemplo n.º 46
0
def add_reg(uid, s):
    with db.transaction():
        db.insert(
            'reg_log',
            uid=uid,
            studentid=s.studentid,
            college=s.college,
            name=s.name,
            telephone=s.telephone,
            gender=s.gender,
        )
        db.update(
            'users',
            vars=dict(uid=uid),
            where='uid = $uid',
            studentid=s.studentid,
            college=s.college,
            name=s.name,
            telephone=s.telephone,
            gender=s.gender,
        )
        return True
    return False
Exemplo n.º 47
0
 def POST(self):
     import time
     data=web.input()
     try:
         bug=db.update("bugs",where="Pid = %s and IsOver=0"%data.YesPid,
             YesWhy=data.YesContent,
             IsOver=1,YesNo=data.YesNo,
             YesTime=time.strftime("%Y-%m-%d %T",time.localtime()))
     except:
         return "提交失败,请返回重试"
     if not bug:
         return self.MESS
     else:
         raise web.seeother('/list')
Exemplo n.º 48
0
    def telegram_change_station(cls, bot, update, job_queue):
        """Answer callback from radio station selector."""
        q = update.callback_query
        station = q.data
        logger = logging.getLogger('oxo')

        db_q = Query()
        q_station = db.search(db_q.name == station)
        if len(q_station) > 0:
            logger.info("Requesting station {} (inline)".format(station))
            bot.answerCallbackQuery(q.id,
                                    text="Tuning to {}...".format(station))

            db.update({"station_playing": station}, db_q.type == "radio")

            if station.startswith("fip"):
                logger.info("Starting fip api title crawler...")
                job_function = Radio.send_fip_title
                delay = 7.0
            else:
                job_function = Radio.send_title
                delay = 1.0

            rv = Job(job_function,
                     delay,
                     repeat=True,
                     context=q.message.chat_id)
            job_queue.put(rv)

            bot.editMessageText(
                text="📻 Changed station to {}.".format(station),
                chat_id=q.message.chat_id,
                message_id=q.message.message_id)
        else:
            bot.answerCallbackQuery(q.id)
            bot.sendMessage(q.message.chat_id,
                            text="I don't know about '{}'".format(station))
Exemplo n.º 49
0
    def telegram_command(cls, bot, update, job_queue, args=list()):
        """Handle telegram /radio command."""
        logger = logging.getLogger('oxo')

        # Remove the old title data job
        if len(job_queue.jobs()) > 0:
            job = job_queue.jobs()[0]
            logger.debug("Removing {}".format(job))
            job.schedule_removal()

        q, state = Radio.state()
        db.update({
            "station_playing": None,
            "station_playing_sent": None
        }, q.type == "radio")

        # Radio station selector
        q_station_names = db.search(q.type == "station")
        station_dict = {s["name"]: s["name"] for s in q_station_names}
        msg = "⏹ Radio turned off.\n\nSelect a station to start."
        kb = inline_keyboard(OrderedDict(sorted(station_dict.items())))
        bot.sendMessage(chat_id=update.message.chat_id,
                        text=msg,
                        reply_markup=kb)
Exemplo n.º 50
0
def move_child_boards(board_id, old_path, new_path):
    # board_id 보드의 자식 보드가 속해 있는 경로를 new_path로 이동한다.
    val = dict(old_path = old_path + r'%')
    result = db.select('Boards', val, where = 'bName LIKE $old_path')
    t = db.transaction()
    try:
        for r in result:
            if not r.bName.startswith(old_path):
                continue
            val2 = dict(board_id = r.bSerial)
            update = db.update('Boards', vars = val2, where = 'bSerial = $board_id',
                    bName = new_path + r.bName[len(old_path):])
    except:
        t.rollback()
    else:
        t.commit()
Exemplo n.º 51
0
def save(user_id, file_id, name, body, parent_id=None):
	if file_id == 0:
		result = 0
		try:
			result = db.insert('files', user_id=user_id, name=name, body=body, parent_id=parent_id, created_date=web.SQLLiteral('NOW()'))
		except Exception as inst:
			pass
		return result
	else:
		# check has user_id file file_id
		r = db.select('files',
			vars=dict(user_id=user_id, id=file_id),
			what='id',
			where='user_id=$user_id AND id=$id',
			limit=1)
		if len(r) == 1:
			return db.update('files', vars=dict(id=file_id), name=name, body=body, parent_id=parent_id, where='id=$id')
Exemplo n.º 52
0
def update_password(uid, password):
    val = dict(uid = uid)
    result = db.select('Users', val, where='uSerial = $uid')
    user = None
    try:
        user = result[0]
    except IndexError:
        return False
    t = db.transaction()
    try:
        ret = db.update('Users', vars=val, where = 'uSerial = $uid', uPasswd = generate_password(password)) 
    except:
        t.rollback()
        return False
    else:
        t.commit()
    return True
Exemplo n.º 53
0
def update_category(model, id=None, where=None, vars=None, **values):
    category_setting = get_category_setting(model)

    if category_setting is None:
        return False

    fields = ['name', 'slug', 'parent_id', 'descrption']
    keys = values.keys()
    for field in keys:
        if field not in fields:
            del values[field]
            continue

        if field == 'parent_id':
            values['parent_id'] = web.intget(values['parent_id'], 0)
            if id is not None and id == values['parent_id'] or category_setting['hierarchical'] is False:
                values['parent_id'] = 0

    if id is not None:
        where = 'id=$id'
        vars = {'id': id}

    return db.update('categories', where=where, vars=vars, **values)
Exemplo n.º 54
0
def update_valid(token, valid=1):
    db.update('PasswordResetToken', vars=dict(token=token), where='token = $token', valid=1)
Exemplo n.º 55
0
def closeBreak(break_id):
    # Find out if it's a foul break
    foul_entries = list(
        db.query("""
                SELECT count(*) as fouls
                FROM tball b, tbreakpot bp
                WHERE b.ball_id=bp.ball_id AND
                    bp.break_id=$break_id AND
                    b.foul='Y'
            """,
                 vars={'break_id': break_id}))

    # Get break score
    score = list(
        db.query("""
                    SELECT IFNULL(SUM(b.points), 0) as score
                    FROM tball b, tbreakpot bp
                    WHERE b.ball_id=bp.ball_id AND bp.break_id=$break_id
            """,
                 vars={'break_id': break_id}))[0]['score']

    # Get break length
    length = list(
        db.query("""
                    SELECT count(*) as length
                    FROM tbreakpot bp
                    WHERE bp.break_id=$break_id
            """,
                 vars={'break_id': break_id}))[0]['length']

    # Get current frame score (doesn't make much sense for fouls, but oh well...)
    breakx = list(
        db.query("""
                    SELECT *
                    FROM tbreak
                    WHERE break_id=$break_id
            """,
                 vars={'break_id': break_id}))[0]
    frame_score, foul_points = tframe.getCurrentFrameScore(
        breakx['frame_id'], breakx['player_id'])
    opp_frame_score, opp_foul_points = tframe.getCurrentFrameScore(
        breakx['frame_id'], breakx['player_id'], opponent=True)

    rowcount = 0
    if foul_entries[0]['fouls'] > 0:
        # Update tbreak entry with score and incremented foul_num

        foul_num = list(
            db.query("""
                    SELECT IFNULL(MAX(b2.foul_num)+1, 1) as foul_num
                    FROM tbreak b1, tbreak b2
                    WHERE b1.break_id=$break_id AND
                        b1.frame_id=b2.frame_id AND
                        b1.break_num=b2.break_num
            """,
                     vars={'break_id': break_id}))[0]['foul_num']

        rowcount = db.update('tbreak',
                             where='break_id=$break_id',
                             vars={'break_id': break_id},
                             score=score,
                             foul_num=foul_num,
                             length=length,
                             frame_score=frame_score,
                             opp_frame_score=opp_frame_score)

    else:
        frame_score += score  # add on score to frame score because it doesn't exist in tbreak yet

        # Update tbreak entry with score
        rowcount = db.update('tbreak',
                             where='break_id=$break_id',
                             vars={'break_id': break_id},
                             score=score,
                             length=length,
                             frame_score=frame_score,
                             opp_frame_score=opp_frame_score)

    if rowcount != 1:
        error = "Uh oh"
Exemplo n.º 56
0
 def update(account):
     doc = db.update('account', account)
     if not doc:
         return Response({})
     return Response(_id=doc['_id'])
Exemplo n.º 57
0
def email_subscribe(user_id, action):
    if action == 'True':
        email_subscribe = 1
    elif action == 'False':
        email_subscribe = 0
    db.update('UserProfile', email_subscribe = email_subscribe, vars = dict(user_id=user_id,),where = 'user_id = $user_id')
Exemplo n.º 58
0
 def setLastTime(self, user):
     import time
     db.update('accounts',
               where="UserName=\'%s\'" % user,
               LastTime="%s" %
               time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
Exemplo n.º 59
0
def update_confirm_email_by_douban_id(douban_id, email, token, time):
    db.update('_confirm_email', vars=dict(douban_id=douban_id), where='douban_id = $douban_id', email=email, token=token,  confirmed=0, creation_ts=time)