Beispiel #1
0
def setting_project():
    # 表格信息区
    projects = db.engine.execute(SQL['PROJECT_INFO'])
    project_choices = [(p.id, p.project_name) for p in Project.query.order_by('id')]
    user_choices = [(p.id, p.user_name) for p in User.query.filter(User.enable == 1).order_by('id')]
    # 增加项目区
    add_form = ProjectForm()
    add_form.project_manager.choices = user_choices
    if add_form.validate_on_submit():
        if g.user.role == 0:
            try:
                new_project = Project(add_form.project_name.data, add_form.project_manager.data,
                                      add_form.build_year.data, add_form.status.data)
                db.session.add(new_project)
                db.session.commit()
                log('project', '增加项目', new_project.id, new_project.project_name, '成功')
                flash("项目添加成功!")
            except Exception, e:
                flash("无法添加项目!")
                print Exception, e
                return render_template('setting-project.html', data=projects, user_choices=user_choices,
                                       status_choices=PROJECT_STATUS, add_form=add_form,
                                       project_choices=project_choices, atr='show')
        else:
            flash("无权限操作!")
def create_ios_splash(path):

    tool.log('开始配置 iOS Splash')

    # 创建启动图文件夹
    if os.path.exists(iosSplashOutPutPath) is False:
        os.makedirs(iosSplashOutPutPath)
        # print '创建 ios LaunchImage.launchimage 文件夹'

    # 获取所有文件
    files = os.listdir(path)

    # 遍历所有文件
    for file_name in files:
        file_path = os.path.join(path, file_name)
        img_type = imghdr.what(file_path)
        # 找出png格式的图片
        if img_type == "png" or img_type == "jpeg":
            image = Image.open(file_path)
            if image.size in iosSplashSize:
                w = image.size[0]
                h = image.size[1]
                # 图片完整名称
                name = "launch%dx%d.png" % (w, h)
                # print name
                # 保存到路径
                image.save(iosSplashOutPutPath + name, "png")

    # 打开文件,写入json数据
    f = open(iosSplashOutPutPath + 'Contents.json', 'w')
    f.write(json.dumps(splash_content))

    tool.log('iOS Splash 配置完成')
Beispiel #3
0
 def __init__(self, args):
     asyncore.dispatcher_with_send.__init__(self)
     self.args = args
     self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
     self.connect(to_addr(args.cupid))
     self.send('upipe.register.%s'%args.name)
     log( 'Register girl %s. Cupid at: %s'%(args.name, args.cupid) )
Beispiel #4
0
def _modify_experience():
    req_data = json.loads(request.get_data())
    id = req_data['id']
    title = nvl(req_data['title']).encode('utf8')
    summary = nvl(req_data['summary']).encode('utf8')
    experience_type = req_data['type'].encode('utf8')
    url = nvl(req_data['url']).encode('utf8')
    project = nvl(req_data['project']).encode('utf8')
    application = nvl(req_data['application']).encode('utf8')
    detail = nvl(req_data['markupStr']).encode('utf8')
    print detail
    if len(detail) < 13:
        detail = None
    try:
        modify_counts = Experience.query.get(int(id)).modify_counts
        db.session.query(Experience).filter(Experience.id == int(id)).update({'title': title,
                                                                              'summary': summary,
                                                                              'type': experience_type,
                                                                              'url': url,
                                                                              'related_project_id': project,
                                                                              'related_application_id': application,
                                                                              'detail': detail,
                                                                              'modify_person_id': g.user.id,
                                                                              'modify_time': time.strftime(
                                                                                  '%Y-%m-%d %H:%M:%S',
                                                                                  time.localtime(time.time())),
                                                                              'modify_counts': modify_counts + 1
                                                                              }, synchronize_session='evaluate')
        db.session.commit()
        log('experience', '修改知识', id, title, '成功')
    except Exception, e:
        print Exception, e
        flash('出现未知错误!')
        return 'false'
Beispiel #5
0
def _update_task():
    req_data = json.loads(request.get_data())
    commit_time = None
    if req_data['status'] == '已完成':
        commit_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    modify_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    status_index = 1
    for i in range(len(TASK_STATUS_LIST)):
        if TASK_STATUS_LIST[i][1] == req_data['status']:
            status_index = TASK_STATUS_LIST[i][0]
            break
    try:
        db.session.query(Task).filter(Task.id == req_data['id']).update(
            {
                'real_start_time': req_data['startdate'],
                'real_finish_time': req_data['finishdate'],
                'processing_progress': int(req_data['progress']) / 100.0,
                'status': status_index,
                'comment': req_data['comment'],
                'modify_time': modify_time,
                'commit_time': commit_time,
                'modify_person_id': g.user.id
            }, synchronize_session='evaluate')
        db.session.commit()
        taskObj = Task.query.filter(Task.id == req_data['id']).first()
        log('task', '更新任务', req_data['id'], taskObj.stage_name + '-' + taskObj.task_name + '-' + taskObj.task_detail,
            '成功')
        return 'ok'
    except Exception, e:
        print Exception, e
        return 'false'
Beispiel #6
0
def setting_application():
    # 表格信息区
    applications = db.engine.execute(SQL['APPLICATION_INFO'])
    application_choices = [(p.id, p.application_name) for p in Application.query.order_by('id')]
    user_choices = [(p.id, p.user_name) for p in User.query.filter(User.enable == 1).order_by('id')]
    status_choices = APPLICATION_STATUS
    # 增加项目区
    add_form = ApplicationForm()
    add_form.product_manger_id.choices = user_choices
    if add_form.validate_on_submit():
        if g.user.role == 0:
            try:
                new_application = Application(add_form.application_name.data, add_form.product_manger_id.data,
                                              add_form.current_version.data, add_form.status.data)
                db.session.add(new_application)
                db.session.commit()
                log('application', '增加系统', new_application.id, new_application.application_name, '成功')
                flash("系统添加成功!")
            except Exception, e:
                flash("无法添加系统!")
                print Exception, e
                return render_template('setting-application.html', data=applications, user_choices=user_choices,
                                       status_choices=status_choices, add_form=add_form,
                                       application_choices=application_choices, atr='show')
        else:
            flash("无权限操作!")
Beispiel #7
0
async def checkRequiredData(uid=None,
                            bid=None,
                            from_public=True,
                            cookies=None):
    if uid:
        user = await checkExistence(uid=uid)
        if not user:
            message = '用户不存在'
            log(message + ':' + uid)
            return CheckState(code=1, message=message)
    if bid:
        blog = await checkExistence(bid=bid)
        if not blog:
            message = '博客不存在'
            log(message + ':' + bid)
            return CheckState(code=2, message=message)
        if from_public and not blog.public:
            return CheckState(code=2)
    if not from_public:
        if bid:
            uid = blog.user_id
        login = await checkLogin(cookies)
        if not login.success:
            return login
    return CheckState(success=True)
Beispiel #8
0
def update_version():
    command = '/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString %s" "%s"' % (
        version, info_plist_path)
    code = os.system(command)
    if code != 0:
        tool.log("修改 iOS 工程 Version 失败")
        quit()
Beispiel #9
0
async def do_signin_post(email, password, headers):
    u = await User.findAll(email=email)
    if not u:
        dic = {
            '__template__': pages['sign_up_in'],
            'user_not_exist': True,
            'message': 'User not exists.'
        }
        return app.wrapAsResponse(dic)
    u = u[0]
    passwd = tool.encrypt(u.id, password)
    if u.passwd != passwd:
        log('expected user:'******' ', u.passwd)
        dic = {
            '__template__': pages['sign_up_in'],
            'wrong_password': True,
            'message': 'Wrong password.'
        }
        return app.wrapAsResponse(dic)
    import time
    key = str(int(time.time())) + u.id + u.passwd
    key = hashlib.sha1(key.encode('utf-8')).hexdigest()
    await u.setKey(key)
    r = web.Response(status=303)
    r.set_cookie('key', key, max_age=86400 * 15)
    r.set_cookie('user_id', u.id, max_age=86400 * 15)
    r.set_cookie('mode', 'normal', max_age=86400 * 15)
    redir = headers['referer']
    print('redir:%s' % redir)
    r.headers['location'] = '/me'
    return r
Beispiel #10
0
def writeFile(fn,content):
    import chardet
    f=open(fn,'wb')
    content1=bytes(content,encoding='utf-8')
    log(chardet.detect(content1))
    f.write(content1)
    f.close()
    return True
Beispiel #11
0
def mq_put(q, v):
    try:
        queue = pymqi.Queue(qmgr, q)
        queue.put(v)
        queue.close()

        log(q, "mq put", v)
    except Exception as e:
        log(q, "mq put error", e)
Beispiel #12
0
 def log(self, message, log_file_name='db.log'):
     # 获取调用者的方法名
     curframe = inspect.currentframe()
     calframe = inspect.getouterframes(curframe, 2)
     caller_name = calframe[1][3]
     tool.log(message,
              log_file_name=log_file_name,
              class_name=__class__.__name__,
              caller_name=caller_name)
Beispiel #13
0
 def __init__(self, args):
     asyncore.dispatcher.__init__(self)
     self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
     self.bind(to_addr(args.local))      
     self.cupid = to_addr(args.cupid)
     self.name = args.name
     log( 'Start boy at %s. Cupid at: %s'%(args.local, args.cupid) )
     self.sendto('upipe.boy.invite.%s'%self.name, self.cupid)
     log('Invitation sent')
Beispiel #14
0
async def init():
    a=await User.deleteAll(email='*****@*****.**')
    uid=admin['id']
    name=admin['name']
    passwd=admin['password']
    email=admin['email']
    user=User(id=uid,name=name,passwd=encrypt(uid,passwd),email=email)
    await user.save()
    log('Create user successfully %s : %s '%(name,user))
Beispiel #15
0
 def __init__(self, args):
     asyncore.dispatcher.__init__(self)
     self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
     self.set_reuse_addr()
     self.bind(to_addr(args.local))      
     self.cupid_addr = to_addr(args.cupid)
     self.name = args.name
     log( 'Start girl at %s. Cupid at: %s'%(args.local, self.cupid_addr) )
     self.sendto('upipe.girl.ready.%s'%self.name, self.cupid_addr)
Beispiel #16
0
def _del_experience():
    req_data = json.loads(request.get_data())
    id = req_data['id']
    try:
        title = db.session.query(Experience).filter(Experience.id == id[0]).first().title
        db.session.query(Experience).filter(Experience.id == id[0]).delete(synchronize_session='evaluate')
        db.session.commit()
        log('experience', '删除知识', id, title, '成功')
        return 'ok'
    except Exception, e:
        print Exception, e
        return 'false'
Beispiel #17
0
def _upload_task():
    req_data = json.loads(request.get_data())
    task_data = req_data['data']
    del_row = req_data['del']
    del_row = list(set(del_row))  # 去重
    status_list_dict = {'未开始': '1', '执行中': '2', '已暂停': '3', '已作废': '4', '已完成': '5'}
    try:
        for row in task_data:
            if row[1] is None and row[2] is None and row[3] is None:  # 过滤空行
                continue
            row[4] = db.session.query(User.id).filter(User.user_name == row[4]).first()[0]  # 转换人员名称到编码
            row[10] = status_list_dict.get(str(row[10]))  # 转换状态到编码
            row[12] = db.session.query(Need.id).filter(Need.need_name == row[12]).first()[0]  # 转换需求名称到编码
            if row[0] is None:  # 新增
                row = nvl(row)
                insert_sql = SQL['NEW_TASK'].format(row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8],
                                                    row[9],
                                                    row[10], row[11], row[12], g.user.id,
                                                    time.strftime('%Y-%m-%d', time.localtime(time.time())))
                db.engine.execute(insert_sql)
                print "new:" + insert_sql
                log('task', '增加任务', None, row[1] + '-' + row[2] + '-' + row[3], '成功')
                continue
            # 修改
            row = nvl(row)
            for i in del_row:  # 去除撤销的删除
                if i == row[0]:
                    del_row.remove(i)
            if row[9] == 1 or row[10] == '5':
                commit_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
            else:
                commit_time = ''
            update_sql = SQL['UPDATE_TASK'].format(row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8],
                                                   row[9],
                                                   row[10], row[11], row[12], g.user.id,
                                                   time.strftime('%Y-%m-%d', time.localtime(time.time())), commit_time,
                                                   row[0])
            print "update:" + update_sql
            db.engine.execute(update_sql)
            # log('task', '修改任务', row[0], row[1] + '-' + row[2] + '-' + row[3], '成功')

        # 删除
        if len(del_row) > 0:
            delete_sql = SQL['DELETE_TASK'].format(join(del_row))
            print "delete:" + delete_sql
            db.engine.execute(delete_sql)
            for i in del_row:
                if i is not None and i > 0:
                    log('task', '删除任务', i, '', '成功')
    except Exception, e:
        print Exception, e
        return '服务异常!'
Beispiel #18
0
async def do_file_edit(filename):
    log(filename)
    filename=decodePath(filename)
    content=loadText(filename)
    name=os.path.basename(filename)
    return  app.wrapAsResponse({
        '__template__':'file.html',
        'file':{
            'name':name,
            'content':content,
            'url':filename
        }
    })
Beispiel #19
0
def _quick_add_share():
    req_data = json.loads(request.get_data())
    try:
        new_experience = Experience(req_data['title'], req_data['summary'], req_data['url'], 1, None, None, None,
                                    g.user.id,
                                    time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        db.session.add(new_experience)
        db.session.commit()
        log('experience', '增加知识', new_experience.id, new_experience.title, '成功')
        return 'ok'
    except Exception, e:
        print Exception, e
        return 'false'
Beispiel #20
0
def _modify_project():
    if g.user.role == 0:
        try:
            db.session.query(Project).filter(Project.id == request.form['modify_project_id']). \
                update({'project_name': request.form['modify_project_name'], \
                        'project_manager_id': request.form['modify_project_manager_selector'], \
                        'build_year': request.form['modify_project_build_year'], \
                        'status': request.form['modify_project_status']}, synchronize_session='evaluate')
            db.session.commit()
            log('project', '修改项目', request.form['modify_project_id'], request.form['modify_project_name'], '成功')
            flash("项目修改成功!")
        except Exception, e:
            flash("项目修改失败!")
            print Exception, e
Beispiel #21
0
def mq_get(client, q):
    try:
        queue = pymqi.Queue(qmgr, q)
        ret = queue.get()
        queue.close()

        log(q, "mq get", ret)

        ret = xml2json(client, ret)

        return ret
    except Exception as e:
        log(q, "mq get error", e)
        return None
def create_android_splash(path):

    tool.log('开始配置 Android Splash')

    # 获取文件夹下所有图片
    files = os.listdir(path)

    # 遍历文件图片
    for file_name in files:

        file_path = os.path.join(path, file_name)
        img_type = imghdr.what(file_path)
        # 找出png格式的图片
        if img_type == "png" or img_type == "jpeg":
            image = Image.open(file_path)
            # 找出指定文件的位置
            if image.size in androidSplashSize:
                w = image.size[0]
                h = image.size[1]
                index = androidSplashSize.index(image.size)
                # 创建不同分辨率文件夹
                dir_path = "%sdrawable-%s" % (androidSplashOutPutPath,
                                              androidNames[index])
                if os.path.exists(dir_path) is False:
                    os.makedirs(dir_path)
                    # print '创建 %s' % dir_path

                # 保存图片到路径
                file_path = "%s/launch_screen.png" % dir_path
                image.save(file_path, "png")
                # print file_path

                # 图片尺寸缩小一半,在尺寸列表中
                if (w / 2, h / 2) in androidSplashSize:
                    index = androidSplashSize.index((w / 2, h / 2))
                    # 创建不同分辨率文件夹
                    dir_path = "%sdrawable-%s" % (androidSplashOutPutPath,
                                                  androidNames[index])
                    if os.path.exists(dir_path) is False:
                        os.makedirs(dir_path)
                        # print '创建 %s' % dir_path

                    # 保存图片到路径
                    file_path = "%s/launch_screen.png" % dir_path
                    # 生成图片
                    im = image.resize((w / 2, h / 2), Image.BILINEAR)
                    im.save(file_path, "png")
                    # print file_path

    tool.log('Android Splash 配置完成')
Beispiel #23
0
def register():
    data = request.json
    log("in register", data)
    if check_register_data(data):
        try:
            u = Users(data)
            u.register()
        except Exception as e:
            log("exceptino")
            return url_for("user.get_register")
        else:
            return url_for("user.get_login")
    else:
        return url_for("user.get_register")
Beispiel #24
0
def login():
    if session.get("username", None) is not None:
        return url_for("index.index")
    data = request.json
    username = data.get("username", None)
    password = data.get("password", None)
    if username and password:
        res = Users.login(username, password)
        log("before update", res)
        if res is not None:
            session.update(res)
        else:
            return url_for("index.index")
        log("login ok", session)
    return url_for("index.index")
Beispiel #25
0
def _modify_application():
    if not g.user.role:
        try:
            db.session.query(Application).filter(Application.id == request.form['modify_application_id']). \
                update({'application_name': request.form['modify_application_name'], \
                        'product_manager_id': request.form['modify_product_manager_selector'], \
                        'current_version': request.form['modify_version'], \
                        'status': request.form['modify_status']}, synchronize_session='evaluate')
            db.session.commit()
            log('application', '修改系统', request.form['modify_application_id'], request.form['modify_application_name'],
                '成功')
            flash("系统修改成功!")
        except Exception, e:
            flash("系统修改失败!")
            print Exception, e
Beispiel #26
0
def _modify_password():
    req_data = json.loads(request.get_data())
    old_pwd = req_data['old_pwd']
    new_pwd = req_data['new_pwd']
    try:
        user = db.session.query(User).filter(User.id == g.user.id, User.password == old_pwd).first()
        if user is None:
            return '密码错误!'
        db.session.query(User).filter(User.id == int(g.user.id)).update({'password': new_pwd},
                                                                        synchronize_session='evaluate')
        db.session.commit()
        log('system', '修改密码', user.id, user.user_name, '成功')
        return 'ok'
    except Exception, e:
        print Exception, e
        return '数据库服务异常!'
Beispiel #27
0
def create_ios_icon(image_path):

    tool.log('开始配置 iOS 的 icon')

    # 创建icon文件夹
    if os.path.exists(iosIconOutPutPath) is False:
        os.makedirs(iosIconOutPutPath)
        # print '创建 ios 项目的 AppIcon.appiconset 文件夹'

    # 获取图片
    icon = Image.open(image_path).convert("RGBA")

    # 保存图片信息的列表
    image_list = []

    # 生成iOS图片,并保存到指定路径
    for size in iosIconSize:
        # 原始尺寸
        original_size = int(size.split('@')[0])
        # 图片倍数
        multiply = int(size.split('@')[1][0:1])
        # 生成图片
        im = icon.resize((original_size * multiply, original_size * multiply),
                         Image.BILINEAR)
        # 图片完整名称
        name = "icon%s.png" % size
        # 保存到路径
        im.save(iosIconOutPutPath + name, "png")
        # 加入JSON文件
        image_list.append({
            "idiom": ("ios-marketing" if original_size == 1024 else "iphone"),
            "size":
            "%dx%d" % (original_size, original_size),
            "filename":
            name,
            "scale":
            "%dx" % multiply
        })

    # 创建 content 文件
    content = {"images": image_list, "info": {"version": 1, "author": "xcode"}}

    # 打开文件,写入json数据
    f = open(iosIconOutPutPath + 'Contents.json', 'w')
    f.write(json.dumps(content))

    tool.log('iOS icon 配置完成')
Beispiel #28
0
def modify_need(need_id):
    form = ModifyNeedForm()
    project_choices = [(u.id, u.project_name) for u in Project.query.order_by('id')]
    project_choices.insert(0, (-1, '无'))
    application_choices = [(u.id, u.application_name) for u in Application.query.order_by('id')]
    application_choices.insert(0, (-1, '无'))
    person_choices = [(u.id, u.user_name) for u in User.query.filter(User.enable == 1).order_by('staff_id')]
    need_choices = [(u.id, u.need_name) for u in Need.query.filter(Need.level_id == 1).all()]
    need_choices.insert(0, (-1, '无'))
    form.project_id.choices = project_choices
    form.charge_person_id.choices = person_choices
    form.application_id.choices = application_choices
    form.parent_need_id.choices = need_choices

    if form.validate_on_submit():
        if g.user.role == 0 or g.user.id == int(form.create_person_id.data) or g.user.id == int(
                form.charge_person_id.data):
            try:
                auto_level_id = 2
                if form.parent_need_id.data == -1:
                    auto_level_id = 1
                db.session.query(Need).filter(Need.id == request.form['need_id']). \
                    update({'need_name': request.form['need_name'], \
                            'outer_sponsor': request.form['outer_sponsor'], \
                            'inner_sponsor': request.form['inner_sponsor'], \
                            'itsm_id': request.form['itsm_id'], \
                            'need_desc': request.form['need_desc'], \
                            'work_load': request.form['work_load'], \
                            'project_id': request.form['project_id'], \
                            'application_id': request.form['application_id'], \
                            'charge_person_id': request.form['charge_person_id'], \
                            'plan_commit_time': request.form['plan_commit_time'], \
                            'real_commit_time': request.form['real_commit_time'], \
                            'status': request.form['status'], \
                            'parent_need_id': request.form['parent_need_id'], \
                            'level_id': auto_level_id
                            }, synchronize_session='evaluate')
                db.session.commit()
                log('need', '修改需求', request.form['need_id'], request.form['need_name'], '成功')
                flash("需求修改成功!")
                return redirect(url_for('needs'))
            except Exception, e:
                flash("需求修改失败!")
                print Exception, e
        else:
            flash("权限不足!只有需求创建人拥有修改权限!")
Beispiel #29
0
def update_ios_staging():
    tool.log("开始更新 iOS Staging,版本号为:" + version)
    command = "code-push release-react %s ios -t %s" % (codePushIOS, version)
    tool.log("执行:" + command)
    code = os.system(command)
    if code == 0:
        tool.log("iOS 更新完成")
    else:
        tool.log("iOS 更新失败")
        exit()
Beispiel #30
0
def update_android_staging():
    tool.log("开始更新 Android Staging,版本号为:" + version)
    command = "code-push release-react %s android -t %s" % (codePushAndroid,
                                                            version)
    tool.log("执行:" + command)
    code = os.system(command)
    if code == 0:
        tool.log("Android 更新完成")
    else:
        tool.log("Android 更新失败")
        exit()
Beispiel #31
0
def update_ios_release():
    tool.log("开始更新 iOS Release,版本号为:" + version)
    command = "code-push release-react %s ios -t %s -d Production" % (
        codePushIOS, version)
    tool.log("执行:" + command)
    code = os.system(command)
    if code == 0:
        tool.log("iOS 更新完成")
    else:
        tool.log("iOS 更新失败")
        exit()
Beispiel #32
0
def update_android_release():
    tool.log("开始更新 Android Release,版本号为:" + version)
    command = "code-push release-react %s android -t %s -d Production" % (
        codePushAndroid, version)
    tool.log("执行:" + command)
    code = os.system(command)
    if code == 0:
        tool.log("Android 更新完成")
    else:
        tool.log("Android 更新失败")
        exit()
Beispiel #33
0
def create_android_icon(image_path):

    tool.log('开始配置 Android 的 icon')

    # 获取图片
    icon = Image.open(image_path).convert("RGBA")

    # 生成Android圆形icon
    circle_icon = tool.circle_corner(icon, radii=1024 / 2)
    index = 0
    for size in androidIconSize:
        # 压缩图片
        circle_im = circle_icon.resize((size, size), Image.BILINEAR)
        # 创建不同分辨率文件夹
        dir_path = "%s/mipmap-%s" % (androidIconOutPutPath,
                                     androidNames[index])
        if os.path.exists(dir_path) is False:
            os.makedirs(dir_path)
            # print '创建 %s' % dir_path

        # 保存到路径
        file_path = "%s/ic_launcher_round.png" % dir_path
        circle_im.save(file_path, "png")
        index = index + 1

    # 生成Android圆角矩形icon
    round_icon = tool.circle_corner(icon, radii=180)
    index = 0
    for size in androidIconSize:
        # 压缩图片
        round_im = round_icon.resize((size, size), Image.BILINEAR)
        # 创建不同分辨率文件夹
        dir_path = "%s/mipmap-%s" % (androidIconOutPutPath,
                                     androidNames[index])
        if os.path.exists(dir_path) is False:
            os.makedirs(dir_path)
            # print '创建 %s' % dir_path

        # 保存到路径
        file_path = "%s/ic_launcher.png" % dir_path
        round_im.save(file_path, "png")
        index = index + 1

    tool.log('Android icon 配置完成')
Beispiel #34
0
 def __init__(self,
              success=False,
              code=3,
              message=None,
              result=None,
              errorResponse=True,
              log_message=True):
     self.success = success
     self.code = code
     self.message = message
     self.result = result
     if self.success:
         self.code = 0
     if not self.message:
         self.autoFillMessage()
     if errorResponse:
         self.autoErrorResponse()
     if log_message:
         log('CheckState:' + self.message)
Beispiel #35
0
def main(firstparam):
    logger = log()

    file_path, task = find_file(firstparam)

    prepare_dir(task)

    trainX, validateX, testX, trainY, validateY, testY = data_split(file_path)
    logger.info('Finished randomly splitting data set'+'\n')

    random_compare(testY)
Beispiel #36
0
def add_need():
    form = NeedForm()
    project_choices = [(u.id, u.project_name) for u in Project.query.order_by('id')]
    project_choices.append((-1, '无'))
    application_choices = [(u.id, u.application_name) for u in Application.query.order_by('id')]
    application_choices.append((-1, '无'))
    person_choices = [(u.id, u.user_name) for u in User.query.filter(User.enable == 1).order_by('staff_id')]
    need_choices = [(u.id, u.need_name) for u in Need.query.filter(Need.level_id == 1).all()]
    need_choices.insert(0, (-1, '无'))
    form.charge_person_id.choices = person_choices
    form.project_id.choices = project_choices
    form.application_id.choices = application_choices
    form.parent_need_id.choices = need_choices
    if form.validate_on_submit():
        auto_level_id = 2
        if form.parent_need_id.data == -1:
            auto_level_id = 1
        try:
            new_need = Need(form.need_name.data.strip(),
                            form.outer_sponsor.data.strip(),
                            form.inner_sponsor.data.strip(),
                            form.itsm_id.data.strip(),
                            form.need_desc.data,
                            form.project_id.data,
                            form.application_id.data,
                            g.user.id,
                            form.charge_person_id.data,
                            form.plan_commit_time.data,
                            None,
                            form.status.data,
                            form.parent_need_id.data,
                            auto_level_id,
                            form.work_load.data)
            db.session.add(new_need)
            db.session.commit()
            log('need', '增加需求', new_need.id, new_need.need_name, '成功')
            flash("需求添加成功!")
            return redirect(url_for('needs'))
        except Exception, e:
            print Exception, e
            flash("需求添加失败!")
Beispiel #37
0
def login():
    if g.user is not None and g.user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        input_staff_id = form.staff_id.data
        input_password = form.password.data
        user = User.query.filter(User.staff_id == input_staff_id, User.enable == 1).first()
        if user is None:
            flash("用户不存在!")
        elif user.verify_pwd(input_password):
            login_user(user)
            session.permanent = True
            app.permanent_session_lifetime = timedelta(minutes=30)
            log('login', '登陆', g.user.id, user.user_name, '成功')
            flash("登录成功!")
            next_page = request.args.get("next")
            return redirect(next_page or url_for("index"))
        else:
            flash("密码错误!")
    return render_template('login.html', form=form)
Beispiel #38
0
def _del_user():
    req_data = json.loads(request.get_data())
    user_id = int(req_data['id'][0])
    if not g.user.role:
        try:
            if Project.query.filter(Project.project_manager_id == user_id, Project.status != 3).count():
                return '该用户所负责的项目未结项!'
            if Application.query.filter(Application.product_manager_id == user_id).count():
                return '该用户是系统的负责人!'
            if Need.query.filter(Need.charge_person_id == user_id, Need.status != 6).count():
                return '该用户有未完成的需求!'
            if Task.query.filter(Task.charge_person_id == user_id, Task.status != 4, Task.status != 5).count():
                return '该用户有未完成的任务!'
            user_name = db.session.query(User).filter(User.id == user_id).first().user_name
            db.session.query(User).filter(User.id == user_id).update({'enable': 0}, synchronize_session='evaluate')
            db.session.commit()
            log('system', '删除用户', user_id, user_name, '成功')
            return 'ok'
        except Exception, e:
            print Exception, e
            return '删除用户失败!'
Beispiel #39
0
def update_ios_push():
    input_str = raw_input("确定发布 iOS 更新(y/n)?")
    if input_str == "y":
        command = "code-push promote %s Staging Production" % codePushIOS
        tool.log("执行:" + command)
        code = os.system(command)
        if code == 0:
            tool.log("iOS 发布完成")
        else:
            tool.log("iOS 发布失败")
            exit()
    else:
        tool.log("取消发布")
        exit()
Beispiel #40
0
def update_ios_back():
    input_str = raw_input("是否将 iOS 回滚到上个版本 (y/n)?")
    if input_str == "y":
        command = "code-push rollback %s Production" % codePushIOS
        tool.log("执行:" + command)
        code = os.system(command)
        if code == 0:
            tool.log("iOS 回滚完成")
        else:
            tool.log("iOS 回滚失败")
            exit()
    else:
        tool.log("取消操作")
        exit()
Beispiel #41
0
def pack_android_staging():
    tool.log("Android Staging 开始打包...")
    os.system("cd android && ./gradlew clean")
    code = os.system("cd android && ./gradlew assembleStaging")
    if code == 0:
        tool.log("Android Staging 打包成功")
    else:
        tool.log("Android Staging 打包失败")
        quit()
Beispiel #42
0
def pack_android_release():
    tool.log("Android Release 开始打包...")
    os.system("cd android && ./gradlew clean")
    code = os.system("cd android && ./gradlew assembleRelease")
    if code == 0:
        tool.log("Android Release 打包成功")
    else:
        tool.log("Android Release 打包失败")
        quit()
Beispiel #43
0
def pack_android_debug():
    tool.log("Android Debug 开始打包...")
    os.system("cd android && ./gradlew clean")
    code = os.system("cd android && ./gradlew assembleDebug")
    if code == 0:
        tool.log("Android Debug 打包成功")
    else:
        tool.log("Android Debug 打包失败")
        quit()
Beispiel #44
0
async def do_editor_post(blog_id, blog_heading, blog_summary, blog_content,
                         is_public, type, label, cookies):
    chk = await checkRequiredData(bid=blog_id,
                                  from_public=False,
                                  cookies=cookies)
    if not chk.success:
        return chk.errorJsonResponse
    b = await Blog.find(blog_id)
    u = await User.find(b.user_id)
    if blog_heading.strip() == '':
        return apiError(message='文章标题不能为空')
    if blog_summary.strip() == '':
        blog_summary = blog_content[:200] if len(
            blog_content) >= 200 else blog_content
    r = await b.update(name=blog_heading,
                       summary=blog_summary,
                       content=blog_content,
                       public=is_public,
                       type=type,
                       label=label)
    if not r:
        log('failed to update blog %s' % blog_id)
        return apiError(message='更新失败')
    return jsonResponse(message='更新成功,<a href="/me">前往主页?</a>')
Beispiel #45
0
def _add_experience():
    req_data = json.loads(request.get_data())
    title = req_data['title'].encode('utf8')
    summary = req_data['summary'].encode('utf8')
    experience_type = req_data['type'].encode('utf8')
    url = req_data['url'].encode('utf8')
    project = req_data['project'].encode('utf8')
    application = req_data['application'].encode('utf8')
    print type(req_data['markupStr'])
    print req_data['markupStr']
    detail = req_data['markupStr'].encode('utf8')
    print detail
    if len(detail) < 13:
        detail = None
    try:
        new_experience = Experience(title, summary, url, experience_type, project, application, detail, g.user.id,
                                    time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        db.session.add(new_experience)
        db.session.commit()
        log('experience', '增加知识', new_experience.id, new_experience.title, '成功')
    except Exception, e:
        print Exception, e
        flash('出现未知错误!')
        return 'false'
Beispiel #46
0
async def checkLogin(cookies, user_id=None):
    uid, key = cookies.get('user_id'), cookies.get('key')
    log('cookies:', cookies)
    if not uid:
        return CheckState(code=3)
    u = await User.find(uid)
    if not u:
        message = '用户不存在'
        log(message + ':' + uid)
        return CheckState(code=1, message=message)
    if not u.key == key:
        message = '用户尚未登录或登录已过期'
        log(message)
        return CheckState(code=3, message=message)
    if user_id and (not user_id == u.id):
        chk = CheckState(code=5)
        log(chk.message)
        return chk
    else:
        return CheckState(success=True, code=0)
Beispiel #47
0
 def handle_read(self):
     data, addr = self.recvfrom(8192)
     if data:
         log("GOT: %s"%data)
         if data.startswith('upipe.love.'):
             self.peer_addr = to_addr(data[len('upipe.love.'):])
             self.sendto('upipe.hello', self.peer_addr)
             log("Hello to: %s"%(self.peer_addr,))
         elif data.startswith('upipe.hello.done'):
             self.peer_addr = addr
             self.established(self.peer_addr)
         elif data.startswith('upipe.hello'):
             self.peer_addr = addr
             self.sendto('upipe.hello.done', self.peer_addr)
             log("Hello.done to: %s"%(self.peer_addr,))
             self.established(self.peer_addr)
Beispiel #48
0
def _operate_user():
    req_data = json.loads(request.get_data())
    user_name = req_data['user_name']
    staff_id = req_data['staff_id']
    email = req_data['email']
    phone_number = req_data['phone_number']
    operate_type = req_data['operate_type']

    if not g.user.role:
        try:
            if operate_type == 'add':
                if db.session.query(User).filter(User.staff_id == staff_id, User.enable == 0).count():
                    db.session.query(User).filter(User.staff_id == staff_id, User.enable == 0).update(
                        {'user_name': user_name,
                         'email': email,
                         'phone_number': phone_number,
                         'enable': 1,
                         'password': 123456
                         }, synchronize_session='evaluate')
                    db.session.commit()
                    log('system', '解禁用户', -1, user_name, '成功')
                else:
                    if db.session.query(User).filter(
                                                    (User.user_name == user_name) |
                                                    (User.staff_id == staff_id) |
                                            (User.email == email) | (User.phone_number == phone_number)).count():
                        return '姓名、工号、邮箱、手机等信息重复!'
                    new_user = User(user_name, staff_id, email, phone_number)
                    db.session.add(new_user)
                    db.session.commit()
                    log('system', '增加用户', new_user.id, user_name, '成功')
            else:
                user_id = int(req_data['user_id'])
                db.session.query(User).filter(User.id == user_id).update({'user_name': user_name,
                                                                          'staff_id': staff_id,
                                                                          'email': email,
                                                                          'phone_number': phone_number},
                                                                         synchronize_session='evaluate')
                db.session.commit()
                log('system', '增加用户', user_id, user_name, '成功')
            return 'ok'
        except Exception, e:
            print Exception, e
            if operate_type == 'add':
                return '数据库服务异常!'
            else:
                return '更新失败!'
def main(firstparam):
    logger = log()

    file_path, task = find_file(firstparam)

    prepare_dir(task)

    # trainX, validateX, testX, trainY, validateY, testY = data_split(file_path)
    trainX, testX, trainY, testY = data_split(file_path)
    logger.info('Finished randomly splitting data set' + '\n')

    gnb, dt, lr, rfc, vc, AdaDT, bagging_lr = classifiers()

    # Result
    results = []
    for clf, name in (
        (gnb, 'Gaussian Naive Bayes'),
        (dt, 'Decision Tree'),
        (lr, 'Logistic Regression'),
        (rfc, 'Random Forest'),
        (vc, 'Voting Classifier'),
        (AdaDT, 'Adaboosting classifier'),
            # (svc, 'SVM  classifier'),
        (bagging_lr, 'Bagging')):
        results.append(
            benchmark(clf, trainX, trainY, testX, testY, logger, task))
        # if clf == lr:
        #     print(clf.coef_)

    drawModelComparison(results, task)

    y_test = []
    y_score = []

    for classifier in (gnb, dt, lr, rfc, vc, AdaDT, bagging_lr):
        y_test.append(ROCplot(classifier, trainX, testX, trainY, testY)[0])
        y_score.append(ROCplot(classifier, trainX, testX, trainY, testY)[1])

    draw_roc(y_test, y_score, task)
Beispiel #50
0
def check_icon_path(path):

    if os.path.exists(path) is False:
        tool.log('输入路径无效: %s' % path)
        quit()

    # 检查icon输入路径是文件夹
    if os.path.isdir(path) is False:
        tool.log('请输入资源所在文件夹的路径')
        quit()

    # 获取图片地址
    image_path = tool.image_size_exist(path, 1024, 1024)
    if len(image_path) <= 0:
        tool.log('未找到尺寸 1024x1024 的 icon 图片')
        quit()

    # 返回图片完整地址
    return image_path
Beispiel #51
0
 def established(self, addr):
     self.close()
     log("Established!")
     subprocess.Popen('openvpn --config girl.ovpn'.split()).pid
     log("UDP part finished - close")
Beispiel #52
0
 def established(self, peer_addr):
     log("Established connection with %s"%(peer_addr,))
     self.close()
Beispiel #53
0
 def handle_close(self):
     log('Girl tcp closed')