Esempio n. 1
0
    def run(self):
        src_name = self.module_name.split('.')[-1]
        self.class_name = util.to_class_name(src_name)

        name_format = util.to_utf8(self.generator_info.get("name_format"))
        if name_format:
            self.class_name = name_format % self.class_name

        self.file_path = os.path.join(self.output_path,
                                      self.class_name + ".java")

        path = os.path.dirname(self.file_path)
        util.safe_makedirs(path)

        self.write_line(0, "// 此文件由导表工具自动生成,禁止手动修改。")
        self.write_line()

        package = util.to_utf8(
            self.generator_info.get("package", xlsconfig.DEFAULT_JAVA_PACKAGE))

        self.write_line(0, "package %s;" % package)
        self.write_line()

        imports = self.generator_info.get("imports")
        if imports:
            for imp in imports:
                self.write_line(0, "import %s;" % imp.encode("utf-8"))
            self.write_line()

        items = self.collect_members(self.module)

        self.gen_class(items, 0)

        self.save_to_file(self.file_path)
Esempio n. 2
0
 def check_marked(self, user_id):
     """检查该用户是否已经签到 4:00 - 12:00 是签到时间, 4:00前或12:00后是总结时间"""
     now = datetime.now()
     # 获取当前是签到时间还是总结时间
     current_block = self.get_current_time_block()
     if current_block == 1:
         start_time = to_utf8(datetime.now())[:10] + " 04:00:00"
     elif now.hour < 4:
         start_time = to_utf8(now - timedelta(days=1))[:10] + " 12:00:00"
     else:
         start_time = to_utf8(now)[:10] + " 12:00:00"
     if marker_ctrl.check_user_marked(user_id, start_time):
         return True
     else:
         return False
Esempio n. 3
0
    def display(self):
        self.log.debug("Displaying file: %s  mime-type: %s" %
                       (self.filename, self.mime_type))
        # We don't have to guess if the charset is specified in the
        # svn:mime-type property
        ctpos = self.mime_type.find('charset=')
        if ctpos >= 0:
            charset = self.mime_type[ctpos + 8:]
            self.log.debug("Charset %s selected" % charset)
        else:
            charset = self.env.get_config('trac', 'default_charset',
                                          'iso-8859-15')
        data = util.to_utf8(self.read_func(self.DISP_MAX_FILE_SIZE), charset)

        if len(data) == self.DISP_MAX_FILE_SIZE:
            self.req.hdf.setValue('file.max_file_size_reached', '1')
            self.req.hdf.setValue('file.max_file_size',
                                  str(self.DISP_MAX_FILE_SIZE))
            vdata = ' '
        else:
            vdata = self.env.mimeview.display(data,
                                              filename=self.filename,
                                              rev=self.rev,
                                              mimetype=self.mime_type)
        self.req.hdf.setValue('file.highlighted_html', vdata)
        self.req.display('file.cs')
Esempio n. 4
0
 def render(self):
     user_id = self.current_user
     greeting = ""
     if user_id:
         user_info = user_ctrl.get_user(user_id)
         greeting = self.gen_greeting(to_utf8(user_info["nickname"]))
     return self.render_string("ui_module/nav.html", result={"user_id": user_id, "greeting": greeting})
Esempio n. 5
0
 def to_json(model):
     """将datetime类型转化成str"""
     if isinstance(model, list):
         return [to_json(submodel) for submodel in model]
     for key, value in model.iteritems():
         if isinstance(value, datetime):
             model[key] = to_utf8(value)
     return model
Esempio n. 6
0
def _app_save_file(upload_file, app_id):
    if not upload_file: return ''
    upload_path = os.path.join(UPLOAD_PATH, str(app_id))
    if not os.path.exists(upload_path):
        os.makedirs(upload_path)
    file = upload_file
    file.save(os.path.join(upload_path, file.filename))
    return to_utf8(file.filename)
Esempio n. 7
0
    def print_diff(self, old_path, new_path, pool):
        if not old_path or not new_path:
            return

        old_rev = svn.fs.node_created_rev(self.old_root, old_path, pool)
        new_rev = svn.fs.node_created_rev(self.new_root, new_path, pool)

        options = Diff.get_options(self.env, self.req, self.args, 1)

        # Make sure we have permission to view this diff
        if not self.authzperm.has_permission(new_path):
            return

        # Try to figure out the charset used. We assume that both the old
        # and the new version uses the same charset, not always the case
        # but that's all we can do...
        mime_type = svn.fs.node_prop(self.new_root, new_path,
                                     svn.util.SVN_PROP_MIME_TYPE, pool)
        # We don't have to guess if the charset is specified in the
        # svn:mime-type property
        ctpos = mime_type and mime_type.find('charset=') or -1
        if ctpos >= 0:
            charset = mime_type[ctpos + 8:]
            self.log.debug("Charset %s selected" % charset)
        else:
            charset = self.env.get_config('trac', 'default_charset',
                                          'iso-8859-15')

        # Start up the diff process
        differ = svn.fs.FileDiff(self.old_root, old_path, self.new_root,
                                 new_path, pool, options)
        differ.get_files()
        pobj = differ.get_pipe()
        prefix = 'changeset.diff.files.%d' % (self.fileno)
        self.req.hdf.setValue(prefix + '.browser_href.old',
                              self.env.href.file(old_path, old_rev))
        self.req.hdf.setValue(prefix + '.browser_href.new',
                              self.env.href.file(new_path, new_rev))
        tabwidth = int(self.env.get_config('diff', 'tab_width', '8'))
        builder = Diff.HDFBuilder(self.req.hdf, prefix, tabwidth)
        self.fileno += 1
        builder.writeline('header %s %s | %s %s redaeh' %
                          (old_path, old_rev, new_path, new_rev))
        while 1:
            line = pobj.readline()
            if not line:
                break
            builder.writeline(util.to_utf8(line, charset))
        builder.close()
        pobj.close()
        # svn.fs.FileDiff creates a child process and there is no waitpid()
        # calls to eliminate zombies (this is a problem especially when
        # mod_python is used.
        if sys.platform[:3] != "win" and sys.platform != "os2emx":
            try:
                os.waitpid(-1, 0)
            except OSError:
                pass
Esempio n. 8
0
    def __init__ (self, html='', js=''):
        Widget.__init__ (self)

        html = to_utf8(html)
        js   = to_utf8(js)

        # Since the information contained in this widget will most
        # probably go through a few variable replacement processes,
        # the % characters are converted to %% in order to avoid
        # potential issues during the process. The HTML code might
        # contain strings such as 'style: 100%;', which aren't meant
        # to be variable replacement.
        #
        html = html.replace ('%', '%%')
        js   =   js.replace ('%', '%%')

        self.html = html
        self.js   = js
Esempio n. 9
0
 def __get_input_props(self):
     render = ''
     for prop in self._props:
         render += " %s" % (prop)
         value = self._props[prop]
         if value:
             val = to_utf8(value)
             render += '="%s"' % (val)
     return render
Esempio n. 10
0
 def __call__ (self, xmlrpc_func, format_func, debug):
     try:
         raw = util.to_utf8 (xmlrpc_func ())
         fmt = format_func (raw)
         return fmt
     except:
         if debug:
             util.print_exception()
         return ''
Esempio n. 11
0
 def __get_input_props (self):
     render = ''
     for prop in self._props:
         render += " %s" %(prop)
         value = self._props[prop]
         if value:
             val = to_utf8(value)
             render += '="%s"' %(val)
     return render
Esempio n. 12
0
 def __call__(self, xmlrpc_func, format_func, debug):
     try:
         raw = util.to_utf8(xmlrpc_func())
         fmt = format_func(raw)
         return fmt
     except:
         if debug:
             util.print_exception()
         return ''
Esempio n. 13
0
    def __init__(self, html='', js=''):
        Widget.__init__(self)

        html = to_utf8(html)
        js = to_utf8(js)

        # Since the information contained in this widget will most
        # probably go through a few variable replacement processes,
        # the % characters are converted to %% in order to avoid
        # potential issues during the process. The HTML code might
        # contain strings such as 'style: 100%;', which aren't meant
        # to be variable replacement.
        #
        html = html.replace('%', '%%')
        js = js.replace('%', '%%')

        self.html = html
        self.js = js
    def run(self):
        file_path = util.resolve_path(self.generator_info["file_path"])
        util.ensure_folder_exist(file_path)
        print "生成文件列表", file_path

        only_name = os.path.splitext(os.path.basename(file_path))[0]

        wt = JsonWriter(file_path, None)
        wt.begin_write()

        package = to_utf8(
            self.generator_info.get("package", xlsconfig.DEFAULT_JAVA_PACKAGE))
        wt.write_value("package", to_utf8(package))

        class_name_format = to_utf8(
            self.generator_info.get("class_name_format"))
        enum_name_format = to_utf8(self.generator_info.get("enum_name_format"))

        keys = self.exporter.data_modules.keys()
        keys.sort()

        ret = []
        for key in keys:
            data_module = self.exporter.data_modules[key]
            converter_name = data_module.info["parser"]

            file_name = os.path.splitext(key)[0]

            enum_name = file_name.replace('\\', '_').replace('/', '_').upper()
            if enum_name_format: enum_name = enum_name_format % enum_name

            fpath, fname = os.path.split(file_name)
            file_name = os.path.join(only_name, fpath, "%s.wg" % fname)
            file_name = format_slash(file_name)

            class_name = to_class_name(converter_name.split('.')[-1])
            if class_name_format: class_name = class_name_format % class_name

            ret.append([enum_name, file_name, class_name])

        wt.write_value(only_name, ret)

        wt.end_write()
        wt.close()
Esempio n. 15
0
def handle_voice_msg(voiceMsg):
	userid = voiceMsg.source
	content = voiceMsg.recognition
	logger.info("revice voice message from %s, recognition content: %s" % (userid,to_utf8(content)))
	if content is None:
		return u"无法识别语音"
	reply = translate(userid, content)
	if type(reply) == unicode:
		return "%s\n-----\n%s" % (content, reply)
	return reply
Esempio n. 16
0
def register_member(member_id, access_token):
    r = redis_member(member_id)
    if not r:
        logger.error('Can not access member redis')
        return False

    pipe = r.pipeline()
    pipe.set(member_id, to_utf8(access_token))
    pipe.expire(member_id, app.EXPIRE_TIME)
    pipe.execute()
    return True
Esempio n. 17
0
def handle_voice_msg(voiceMsg):
    userid = voiceMsg.source
    content = voiceMsg.recognition
    logger.info("revice voice message from %s, recognition content: %s" %
                (userid, to_utf8(content)))
    if content is None:
        return u"无法识别语音"
    reply = translate(userid, content)
    if type(reply) == unicode:
        return "%s\n-----\n%s" % (content, reply)
    return reply
Esempio n. 18
0
def _generate_access_token(request, member_id):
    if not member_id:
        _error(request, 'Member is not exist;{member_id:%d}' % (member_id), 404)

    member = {'member_id': member_id}
    access_token = to_utf8(_serializer.dumps(member))

    if not models.register_member(member_id, access_token):
        _error(request, 'Register member failed;{member_id:%d}' % (member_id), 404)

    return access_token
Esempio n. 19
0
def send_message(gcm_url, server_api_key, token, message):
  data = '{"to":"%s","data":%s}' % (token, message)
  r = requests.post(gcm_url, headers=_headers(server_api_key), data=to_utf8(data))
  logger.debug(r.content)
  if r.status_code != 200:
    logger.error('Error to GCM Message')
  else:
    response = json.loads(r.content)
    if response['success'] == 1:
      logger.info('Success to GCM Message')
    else:
      logger.error('Failed to GCM Message')
Esempio n. 20
0
def build(root, dest):
    dest = os.path.join(dest, 'rbnf')
    shutil.rmtree(dest)
    makedirs(dest)
    path = os.path.join(root, 'common/rbnf')
    names = [os.path.splitext(n)[0] for n in os.listdir(path)]
    for name in names:
        tree = readxml(os.path.join(path, '%s.xml' % name))
        rbnf = convert(tree)
        rbnf = to_utf8(rbnf)
        out = os.path.join(dest, '%s.json' % name)
        save(out, rbnf)
Esempio n. 21
0
def apps_new(form):
    app_key = _hash_app_key(form.app_name.data)
    app_secret = _hash_app_secret(app_key)
    app_name = set_default(form.app_name.data)
    support_android = set_support(form.support_android.data)
    support_ios = set_support(form.support_ios.data)
    support_playstore = set_support(form.support_playstore.data)
    support_appstore = set_support(form.support_appstore.data)
    support_gameflier = set_support(form.support_gameflier.data)
    playstore_url = set_default(form.playstore_url.data)
    appstore_url = set_default(form.appstore_url.data)
    gameflier_url = set_default(form.gameflier_url.data)
    gcm_sender_id = set_default(form.gcm_sender_id.data)
    gcm_server_api_key = set_default(form.gcm_server_api_key.data)
    gcm_config_path = ''
    if form.gcm_config_path.data:
        gcm_config_path = to_utf8(form.gcm_config_path.data.filename)
    facebook_app_name = set_default(form.facebook_app_name.data)
    facebook_app_id = set_default(form.facebook_app_id.data)
    facebook_app_secret = set_default(form.facebook_app_secret.data)
    facebook_api_version = facebook_api_version_value(form.facebook_api_version.data)
    status = form.status.data

    con, cur = sqlrelay_client_cursor()
    cur.prepareQuery('CALL create_app(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)')
    cur.inputBind("1", app_key)
    cur.inputBind("2", app_secret)
    cur.inputBind("3", app_name)
    cur.inputBind("4", support_android)
    cur.inputBind("5", support_ios)
    cur.inputBind("6", support_playstore)
    cur.inputBind("7", support_appstore)
    cur.inputBind("8", support_gameflier)
    cur.inputBind("9", playstore_url)
    cur.inputBind("10", appstore_url)
    cur.inputBind("11", gameflier_url)
    cur.inputBind("12", gcm_sender_id)
    cur.inputBind("13", gcm_server_api_key)
    cur.inputBind("14", gcm_config_path)
    cur.inputBind("15", facebook_app_id)
    cur.inputBind("16", facebook_app_name)
    cur.inputBind("17", facebook_app_secret)
    cur.inputBind("18", facebook_api_version)
    cur.inputBind("19", status)
    cur.executeQuery()
    app_id = cur.getField(0,0)
    sqlrelay_client_close(cur, con)

    if form.gcm_config_path.data:
        # GCM Config 파일저장
        _app_save_file(form.gcm_config_path.data, app_id)
Esempio n. 22
0
    def run(self):
        src_name = self.module_name.split('.')[-1]
        self.class_name = util.to_class_name(src_name)

        generator_info = self.generator_info
        name_format = util.to_utf8(generator_info.get("name_format"))
        if name_format:
            self.class_name = name_format % self.class_name

        ns = {
            "FILE_PATH": self.class_name,
        }
        self.file_path = util.resolve_path(generator_info["file_path"], (
            ns,
            xlsconfig,
        ))
        util.ensure_folder_exist(self.file_path)

        self.write_line(0, "// 此文件由导表工具自动生成,禁止手动修改。")
        self.write_line()

        package = util.to_utf8(
            generator_info.get("package", xlsconfig.DEFAULT_JAVA_PACKAGE))

        self.write_line(0, "package %s;" % package)
        self.write_line()

        imports = generator_info.get("imports")
        if imports:
            for imp in imports:
                self.write_line(0, "import %s;" % imp.encode("utf-8"))
            self.write_line()

        items = self.collect_members(self.module)

        self.gen_class(items, 0)

        self.save_to_file(self.file_path)
Esempio n. 23
0
 def viewer(self, user_id={"atype": int, "adef": 0}):
     """总体情况"""
     sql = "select * from mark where user_id = %s" % user_id
     data = mysql_conn.query(sql)
     sight_ctrl = top.api.TripScenicGetRequest()
     for i in xrange(0, len(data)):
         data[i]["create_on"] = str(data[i]["create_on"])
         data[i]["mark_time"] = "时间:" + data[i]["create_on"]
         sight_id = data[i]["sight_id"]
         sight_ctrl.scenic_id = sight_id
         res = sight_ctrl.getResponse()
         sight_name = res["trip_scenic_get_response"]["travel_scenic"]["name"]
         data[i]["address"] = to_utf8(sight_name)
     return self._html_render("viewer.html", {"markers": data, "user_id": user_id})
Esempio n. 24
0
def change_nickname(user_id, nickname):
  nickname = to_utf8(nickname)

  con, cur = sqlrelay.client_cursor()
  cur.prepareQuery("""
BEGIN
  ARPG.CHANGE_NICKNAME(
    :user_id,
    :nickname
  );
END;
""")
  cur.inputBind("user_id", user_id)
  cur.inputBind("nickname", nickname)
  cur.executeQuery()

  sqlrelay.client_close(cur, con)
  return True
Esempio n. 25
0
def handle_text_msg(txtMsg):
	userid = txtMsg.source
	content = txtMsg.content
	if content.startswith("@"):
		content = content[1:]
		return get_notations_result(userid, content)
	if "#" == content or u"#" == content:
		return get_last_msg_audio(userid)
	need_translation_content = content
	in_chat_mode = check_and_refresh_user_chat_mode(userid)
	if in_chat_mode:
		ret, response = tuling_robot.send_msg(userid, content)
		if ret:
			need_translation_content = response
		else:
			return response

	logger.info("revice text message from %s, content: %s" % (userid,to_utf8(content)))
	return translate(userid, need_translation_content, in_chat_mode, content)
Esempio n. 26
0
def handle_text_msg(txtMsg):
    userid = txtMsg.source
    content = txtMsg.content
    if content.startswith("@"):
        content = content[1:]
        return get_notations_result(userid, content)
    if "#" == content or u"#" == content:
        return get_last_msg_audio(userid)
    need_translation_content = content
    in_chat_mode = check_and_refresh_user_chat_mode(userid)
    if in_chat_mode:
        ret, response = tuling_robot.send_msg(userid, content)
        if ret:
            need_translation_content = response
        else:
            return response

    logger.info("revice text message from %s, content: %s" %
                (userid, to_utf8(content)))
    return translate(userid, need_translation_content, in_chat_mode, content)
    def run(self):
        file_path = util.resolve_path(self.generator_info["file_path"])
        util.ensure_folder_exist(file_path)
        print "生成枚举类", file_path

        wt = BaseWriter(file_path, None)

        indent = 0
        wt._output_line(indent, "// 此文件由导表工具自动生成,禁止手动修改。")
        wt._output_line()

        package = util.to_utf8(
            self.generator_info.get("package", xlsconfig.DEFAULT_JAVA_PACKAGE))
        wt._output_line(indent, "package %s;" % package)
        wt._output_line()

        class_name = os.path.splitext(os.path.basename(file_path))[0]
        wt._output_line(indent, "public enum %s {" % class_name)
        indent += 1

        value_pairs = []
        for outfile, data_module in self.exporter.data_modules.iteritems():
            enume_name = to_enum_name(outfile)
            comment = data_module.info["arguments"].get("describe")
            value_pairs.append((enume_name, comment))

        value_pairs.sort(key=lambda v: v[0])

        for enum_name, comment in value_pairs:
            if comment:
                wt._output_line(indent,
                                "%-20s // %s" % (enum_name + ",", comment))
            else:
                wt._output_line(indent, enum_name, ",")

        indent -= 1
        wt._output_line(indent, "};")

        wt.close()
Esempio n. 28
0
 def search(self,
            latitude={"atype": float, "adef": 0},
            longitude={"atype": float, "adef": 0},
            category_id={"atype": int, "adef": 0},
            distance={"atype": int, "adef": 1000},
 ):
     """
         查找消息
     """
     cond = {}
     if category_id:
         cond["category_id"] = category_id
     message_list = mongo.message.find({"loc": SON([("$near", [longitude, latitude]), ("$maxDistance", distance)])})
     data = []
     for message in message_list:
         message_id = message["id"]
         message_t = MessageModel.table()
         message_obj = MessageModel.object()
         cond = message_t.id == message_id
         if not message_obj.find(cond):
             continue
         message_info = {}
         message_info["id"] = message_obj.id
         message_info["user_id"] = message_obj.user_id
         message_info["latitude"] = message_obj.latitude
         message_info["longitude"] = message_obj.longitude
         message_info["content"] = message_obj.content
         message_info["with_sku_id"] = message_obj.with_sku_id
         message_info["with_sku_type"] = message_obj.with_sku_type
         message_info["category_id"] = message_obj.category_id
         message_info["tags"] = message_obj.tags
         message_info["create_on"] = to_utf8(message_obj.create_on)
         message_info["nice"] = message_obj.nice
         point_user = (longitude, latitude)
         point_message = (message_info["longitude"], message_info["latitude"])
         message_info["distance"] = calculate_distance(point_user, point_message)
         data.append(message_info)
     return self._response(PyobjectList(Error.success, data))
Esempio n. 29
0
def member_info(udid, 
                device_platform, 
                service_platform, 
                gcm_token = '',
                facebook_id = 0, 
                facebook_email = ''):
    con, cur = sqlrelay_client_cursor(app.DEBUG)
    cur.prepareQuery('CALL member_info(?, ?, ?, ?, ?, ?, ?, ?)')
    cur.inputBind('1', app.APP_ID)
    cur.inputBind('2', to_utf8(udid))
    cur.inputBind('3', device_platform)
    cur.inputBind('4', service_platform)
    cur.inputBind('5', gcm_token)
    cur.inputBind('6', facebook_id)
    cur.inputBind('7', to_utf8(facebook_email))
    cur.inputBind('8', membership_pb2.MEMBER_STATUS_NORMAL)
    cur.executeQuery()
    member_id = cur.getFieldAsInteger(0, 0)
    if member_id <= 0: 
        sqlrelay_client_close(cur, con)
        return None

    cur.clearBinds()

    # 로그인 로그저장
    cur.sendQuery("""
INSERT INTO ms_member_history (
   app_id
 , member_id
 , category
 , `int0`
 , `int1`
 , `int2`
 , str0 
) VALUES (
   %d
 , %d
 , %d
 , %d
 , %d
 , %d
 , '%s'
)""" % (app.APP_ID, member_id, membership_pb2.HISTORY_MEMBER_ACCESS,
        device_platform, service_platform, facebook_id, udid))

    # 미완료 결제정보
    cur.sendQuery("""
SELECT
   service_platform
 , payment_id
 , inapp_order_id
 , inapp_developer_payload
 , inapp_purchase_token
 , inapp_product_sku 
FROM
   ms_app_payment 
WHERE 
   member_id = %d AND app_id = %d AND status = %d
""" % (member_id, app.APP_ID, membership_pb2.PAYMENT_STATUS_PURCHASED))
    sqlrelay_client_close(cur, con)

    payments = []
    for row in range(0, cur.rowCount()):
        payments.append({
           'service_platform': cur.getFieldAsInteger(row, 0),
           'payment_id': cur.getFieldAsInteger(row, 1),
           'order_id': cur.getField(row, 2),
           'developer_payload': cur.getField(row, 3),
           'purchase_token': cur.getField(row, 4),
           'inapp_id': cur.getField(row, 5)
        })
    return member_id, payments
Esempio n. 30
0
 def __get_error_div_props (self):
     render = 'id="error_%s"' % (self.id)
     name = to_utf8 (self._props.get('name'))
     if name:
         render += ' key="%s"' %(name)
     return render
Esempio n. 31
0
 def __get_error_div_props(self):
     render = 'id="error_%s"' % (self.id)
     name = to_utf8(self._props.get('name'))
     if name:
         render += ' key="%s"' % (name)
     return render
Esempio n. 32
0
 def __init__ (self, html='', js=''):
     Widget.__init__ (self)
     self.html = to_utf8(html)
     self.js   = to_utf8(js)