• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sublime.decode_value函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sublime.decode_value函数的典型用法代码示例。如果您正苦于以下问题:Python decode_value函数的具体用法?Python decode_value怎么用?Python decode_value使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了decode_value函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: reload_settings

 def reload_settings(self):
     self.settings_default = sublime.decode_value(sublime.load_resource(from_package('Mediawiker.sublime-settings')))
     self.settings = sublime.load_settings('Mediawiker.sublime-settings')
     try:
         self.settings_user = sublime.decode_value(sublime.load_resource(from_package('Mediawiker.sublime-settings', name='User')))
     except IOError:
         self.settings_user = {}
开发者ID:tosher,项目名称:Mediawiker,代码行数:7,代码来源:mw_properties.py


示例2: __init__

    def __init__(self):
        self.client_key = "40af22476e380eadfef5"
        self.client_secret = "ec5cfba3fb9fb063d0d4"

        self.settings = tools.load_settings("LaTeXing",
                                            zotero_user_key="",
                                            zotero_user_id="",
                                            zotero_cite_key_pattern="{Author}{year}"
                                            )

        # Load map
        self.map = sublime.decode_value(sublime.load_resource("Packages/LaTeXing/latexing/api/zotero.map"))

        # bibtex: zotero type
        self.type_map = self.map["types"]

        # bibtex: zotero field
        self.field_map = self.map["fields"]

        # Check for user maps
        try:
            self.user_map = sublime.decode_value(sublime.load_resource("Packages/User/LaTeXing/zotero.map"))
            self.type_map.update(self.user_map["types"] if "types" in self.user_map else {})
            self.field_map.update(self.user_map["fields"] if "fields" in self.user_map else {})
        except:
            pass

        self.status = "Ok"
        self.items = []
        self.items_no_key = {}
开发者ID:LaTeXing,项目名称:LaTeXing,代码行数:30,代码来源:zotero.py


示例3: __init__

    def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.legacy = not scheme_file.lower().endswith('.sublime-color-scheme')
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)
        if self.legacy:
            self.scheme_obj = color_filter(
                readPlistFromBytes(
                    re.sub(
                        br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'',
                        sublime.load_binary_resource(sublime_format_path(self.color_scheme))
                    )
                )
            )
        else:
            sublime.decode_value(
                sublime.load_resource(sublime_format_path(self.color_scheme)),
                preserve_lines=True
            )
        self.scheme_file = scheme_file
        self.matched = {}
        self.variables = {}

        self.parse_scheme()
开发者ID:arnedesmedt,项目名称:dotfiles,代码行数:26,代码来源:st_color_scheme_matcher.py


示例4: __init__

    def __init__(self):
        self.client_id = "141"
        self.client_secret = "4*ic:5WfF;LxE534"

        self.settings = tools.load_settings("LaTeXing", mendeley_oauth_token="", mendeley_internal_cite_key=False, mendeley_cite_key_pattern="{Author}{year}")

        # Load map
        self.map = sublime.decode_value(sublime.load_resource("Packages/LaTeXing/latexing/api/mendeley.map"))

        # bibtex: zotero type
        self.type_map = self.map["types"]

        # bibtex: zotero field
        self.field_map = self.map["fields"]

        # Check for user maps
        try:
            self.user_map = sublime.decode_value(sublime.load_resource("Packages/User/LaTeXing/mendeley.map"))
            self.type_map.update(self.user_map["types"] if "types" in self.user_map else {})
            self.field_map.update(self.user_map["fields"] if "fields" in self.user_map else {})
        except:
            pass

        self.status = "Ok"
        self.items = []
        self.items_no_key = {}
开发者ID:LaTeXing,项目名称:LaTeXing,代码行数:26,代码来源:mendeley.py


示例5: run

    def run(self, cmd, code):
        """
        Attempt to parse code as JSON.

        Returns '' if it succeeds, the error message if it fails.
        Use ST's loose parser for its setting files, or when specified.
        """
        is_sublime_file = os.path.splitext(self.filename)[1].startswith('.sublime-')

        if self.get_view_settings().get('strict') and not is_sublime_file:
            strict = True
        else:
            strict = False

        try:
            if strict:
                self.regex = self.strict_regex
                json.loads(code)
            else:
                self.regex = self.loose_regex
                sublime.decode_value(code)

            return ''
        except ValueError as err:
            return str(err)
开发者ID:SublimeLinter,项目名称:SublimeLinter-json,代码行数:25,代码来源:linter.py


示例6: decodeEntity

def decodeEntity(xml, category='iso'):
    global entities
    if not isinstance(xml, str):
        return xml
    if entities[category]:
        forward, reverse = entities[category]
    else:
        if category == 'iso':
            forward = sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/IsoEntities.json'))
        elif category == 'html':
            forward = sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/HtmlEntities.json'))
        reverse = dict((v, k) for k, v in forward.items())
        entities[category] = (forward, reverse)

    def parseEntity(match):
        entity = match.group(1)
        try:
            if entity.isdigit():
                return reverse[int(entity)]
            else:
                return chr(forward[entity])
        except:
            return match.group(0)
    xml = re.sub('&([a-zA-Z0-9]+);', parseEntity, xml)
    return xml
开发者ID:john1688,项目名称:docphp,代码行数:25,代码来源:docphp.py


示例7: run

    def run(self, cmd, code):
        """Attempt to parse code as JSON, return '' if it succeeds, the error message if it fails."""

        # Use ST's loose parser for its setting files.
        strict = os.path.splitext(self.filename)[1] not in self.extensions

        try:
            if strict:
                self.__class__.regex = self.strict_regex

                # establish basic JSON compliance with in built python JSON library
                template = json.loads(code)

                # now validate against the AWS api
                cfn = boto3.client('cloudformation')
                template = cfn.validate_template(TemplateBody=code)
                print(template)
            else:
                self.__class__.regex = self.loose_regex
                sublime.decode_value(code)

            return ''

        except ValueError as err:
            return str(err)
开发者ID:claytonbrown,项目名称:SublimeLinter-contrib-AWS-Cloudformation-JSON,代码行数:25,代码来源:linter.py


示例8: _parse_snippet_xml

  def _parse_snippet_xml(self, name, xml):
    snippet = {}

    for node in xml.childNodes:
      if node.nodeType == node.ELEMENT_NODE:
        value_node = node.firstChild
        if value_node == None:
          continue
        snippet[node.tagName] = value_node.data

    if len(snippet) == 0:
      return None

    if 'content' not in snippet:
      return None

    if 'context' in snippet:
      snippet['context'] = sublime.decode_value(snippet['context'])

    if 'commands' in snippet:
      snippet['commands'] = sublime.decode_value(snippet['commands'])

    if snippet['content'][0] == "\n":
      snippet['content'] = snippet['content'][1:]

    if snippet['content'][len(snippet['content']) - 1] == "\n":
      snippet['content'] = snippet['content'][:len(snippet['content']) - 1]

    if len(snippet['content']) == 0:
      return None

    if 'scope' in snippet:
      # load old snippets
      snippet['_scope'] = snippet['scope']

      is_old = (
        re.search(r'^\(?([\w\+]+\.[\w\+]+,?\s*)*$', snippet['scope']) != None or
        '++' in snippet['scope']
      )

      if is_old:
        snippet['scope'] = (
          '((?:\W|^)' + snippet['scope'].
            replace(', ', '(?:\W|$)|(?:\W|^)').
            replace('+', '\\+').replace('.', '\\.') + '(?:\W|$))'
        )

      snippet['scope'] = re.compile(snippet['scope'])

    snippet['name'], _ = os.path.splitext(os.path.basename(name))
    snippet['path'] = name

    if 'order' in snippet:
      snippet['order'] = int(snippet['order'])

    return snippet
开发者ID:dinfekted,项目名称:sublime-snippet-caller,代码行数:56,代码来源:snippet_caller.py


示例9: library

    def library(self):
        url = "/documents?limit=500&reverse=false&order=asc&view=all"
        json_documents = sublime.decode_value(self.client.get(url))

        documents = json_documents
        while len(json_documents) == 500:
            json_documents = sublime.decode_value(self.client.get(url + "&marker=" + json_documents[-1]['id']))
            documents += json_documents

        return documents
开发者ID:LaTeXing,项目名称:LaTeXing,代码行数:10,代码来源:mendeley.py


示例10: merge_overrides

    def merge_overrides(self):
        """Merge override schemes."""

        package_overrides = []
        user_overrides = []
        if self.scheme_file.endswith('.hidden-color-scheme'):
            pattern = '%s.hidden-color-scheme'
        else:
            pattern = '%s.sublime-color-scheme'
        for override in sublime.find_resources(pattern % path.splitext(self.scheme_file)[0]):
            if override.startswith('Packages/User/'):
                user_overrides.append(override)
            else:
                package_overrides.append(override)
        for override in (package_overrides + user_overrides):
            try:
                ojson = sublime.decode_value(sublime.load_resource(override))
            except IOError:
                # Fallback if file was created manually and not yet found in resources
                # Though it is unlikely this would ever get executed as `find_resources`
                # probably wouldn't have seen it either.
                with codecs.open(packages_path(override), 'r', encoding='utf-8') as f:
                    ojson = sublime.decode_value(sanitize_json(f.read()))

            for k, v in ojson.get('variables', {}).items():
                self.scheme_obj['variables'][k] = v

            for k, v in ojson.get(GLOBAL_OPTIONS, {}).items():
                self.scheme_obj[GLOBAL_OPTIONS][k] = v

            for item in ojson.get('rules', []):
                self.scheme_obj['rules'].append(item)

            self.overrides.append(override)

        # Rare case of being given a file but sublime hasn't indexed the files and can't find it
        if (
            not self.overrides and
            self.color_scheme.endswith(('.sublime-color-scheme', '.hidden-color-scheme')) and
            self.color_scheme.startswith('Packages/')
        ):
            with codecs.open(packages_path(self.color_scheme), 'r', encoding='utf-8') as f:
                ojson = sublime.decode_value(sanitize_json(f.read()))

                for k, v in ojson.get('variables', {}).items():
                    self.scheme_obj['variables'][k] = v

                for k, v in ojson.get(GLOBAL_OPTIONS, {}).items():
                    self.scheme_obj[GLOBAL_OPTIONS][k] = v

                for item in ojson.get('rules', []):
                    self.scheme_obj['rules'].append(item)

                self.overrides.append(self.color_scheme)
开发者ID:PwnArt1st,项目名称:dotfiles,代码行数:54,代码来源:color_scheme_matcher.py


示例11: decodeEntity

def decodeEntity(xml, category="iso"):
    global entities
    if not isinstance(xml, str):
        return xml
    if entities[category]:
        forward, reverse = entities[category]
    else:
        resourceMap = {"iso": "IsoEntities.json", "html": "HtmlEntities.json"}
        forward = sublime.decode_value(sublime.load_resource("Packages/" + package_name + "/" + resourceMap[category]))

        reverse = dict((v, k) for k, v in forward.items())
        entities[category] = (forward, reverse)

    def parseEntity(match):
        entity = match.group(1)
        try:
            if entity.isdigit():
                return reverse[int(entity)]
            else:
                return chr(forward[entity])
        except:
            return match.group(0)

    xml = re.sub("&([a-zA-Z0-9]+);", parseEntity, xml)
    return xml
开发者ID:garveen,项目名称:docphp,代码行数:25,代码来源:docphp.py


示例12: manage_package

    def manage_package(self, package):
        self.done = False
        file_list = list_package_files(package)
        platform_keymap = "default (%s).sublime-keymap" % (PLATFORM.lower())
        for filename in file_list:

            if filename.lower().endswith("default.sublime-keymap")or \
            filename.lower().endswith(platform_keymap):
                content = get_resource(package, filename)
                if content == None:
                    continue

                try:
                    if VERSION < 3013:
                        minified_content = json_minify(content)
                        minified_content = strip_dangling_commas(minified_content)
                        minified_content = minified_content.replace("\n", "\\\n")
                        if self.debug:
                            self.debug_minified[package] = minified_content
                        key_map = json.loads(minified_content)
                    else:
                        key_map = sublime.decode_value(content)
                except:
                    if not self.prev_error:
                        traceback.print_exc()
                        self.prev_error = True
                        sublime.error_message("Could not parse a keymap file. See console for details")
                    #error_path = os.path.join(os.path.basename(orig_path), filename)
                    logger.warning("FindKeyConflicts[Warning]: An error " + "occured while parsing '" + package + "'")
                    continue
                self.handle_key_map(package, key_map)
        self.done = True
开发者ID:Mondego,项目名称:pyreco,代码行数:32,代码来源:allPythonContent.py


示例13: run

	def run(self, edit, type="", text="", region=None, dest=None):
		if type == "insert":
			self.view.insert(edit, 0, text)
		elif type == "add":
			self.view.insert(edit, self.view.size(), text)
		elif type == "replace":
			self.view.insert(edit, region, text)
		elif type == "set_read_only":
			self.view.set_read_only(True)
		elif type == "test":
			if not isStable():
				self.view.show_popup_menu(["A", "B"], self.nothing)
		elif type == "remote_hash":
			if not isStable():
				sublime.active_window().show_input_panel("URL:", "", self.remote_hash, None, None)
		elif type == "hash":
			if not isStable():
				print(hashlib.sha256(self.view.substr(sublime.Region(0,self.view.size())).encode("utf-8")).hexdigest())
		elif type == "tojson":
			if not isStable():
				jsonObj = sublime.decode_value(self.view.substr(sublime.Region(0,self.view.size())))
				self.view.replace(edit, sublime.Region(0,self.view.size()), sublime.encode_value(jsonObj, True));
		elif type == "reload":
			if isDebug():
				getAction().addAction("javatar.command.utils.reload", "Reload Javatar")
				print("Reloading Javatar...")
				import sys
				from imp import reload
				for mod in sys.modules:
					if mod.lower().startswith("javatar") and not mod.lower().endswith("_utils") and sys.modules[mod] is not None:
						print("Reloading module " + mod + "...")
						reload(sys.modules[mod])
				from ..Javatar import plugin_loaded
				plugin_loaded()
开发者ID:xiamizy,项目名称:Javatar,代码行数:34,代码来源:javatar_utils.py


示例14: allFunctions

	def allFunctions(self):
		"""retorna todas las funciones"""
		modulos=sublime.decode_value(open(RutasPython.funciones()).read())
		lista=[]
		for modulo in modulos:
			lista+=[ (funcion+"\t•"+modulo, self.ponerCursor(modulo+"."+funcion)) for funcion in modulos[modulo]]
		return sorted(lista)
开发者ID:programadorsito,项目名称:Packages,代码行数:7,代码来源:completion.py


示例15: getBowerPackages

	def getBowerPackages(self):
		if (self._bowerComponents is not None):
			return
			
		cacheFile = self.getCachePath() + "\\bower-component-list.json"

		if not os.path.isfile(cacheFile):
			apiUrl = 'https://bower-component-list.herokuapp.com'

			## TODO: do it async
			urllib.request.urlretrieve(apiUrl, cacheFile)
		
		content = self.file_get_contents(cacheFile)

		self._bowerComponents = []

		for idx, val in enumerate(sublime.decode_value(content)):

			name = val.get('name')
			desc = val.get('description', "Description not provided")
			updated = val.get('updated', "Last updated not provided")
			stars = 0 if not val['stars'] else val['stars']

			if ((not name) or (not desc) or (not updated) or stars < 1):
				continue

			component = [name, desc, updated]

			self._bowerComponents.append(component)
开发者ID:hajnalben,项目名称:SublimeAngularTools,代码行数:29,代码来源:Bower.py


示例16: load_tag_list

def load_tag_list():
    tags_to_filter = [
        'abort',
        'admin',
        'case',
        'catch',
        'component',
        'continue',
        'defaultcase',
        'else',
        'elseif',
        'exit',
        'finally',
        'function',
        'if',
        'interface',
        'rethrow',
        'retry',
        'return',
        'script',
        'servlet',
        'servletparam',
        'set',
        'sleep',
        'switch',
        'try',
        'while',
    ]
    tags = sublime.load_resource(
        "Packages/CFML/src/basecompletions/json/cfml_tags.json"
    )
    tags = sublime.decode_value(tags).keys()
    return [t.lower()[2:] for t in tags if t.lower()[2:] not in tags_to_filter]
开发者ID:thomasrotter,项目名称:sublimetext-cfml,代码行数:33,代码来源:cfml_syntax.py


示例17: analyse_package

    def analyse_package(self, filepath):
        add_action(
            "javatar.util.collection.analyse_import",
            "Analyse package [file=" + filepath + "]"
        )

        try:
            imports = sublime.decode_value(sublime.load_resource(filepath))

        except ValueError:
            sublime.error_message("Invalid JSON format")

        else:
            if "experiment" in imports and imports["experiment"]:
                return None
            filename = basename(filepath)
            if "name" in imports:
                filename = imports["name"]
            count = self.count_classes(imports)
            self.installed_packages.append({"name": filename, "path": filepath})
            print(
                'Javatar package "{}" loaded with {} classes in {} packages'
                .format(
                    filename,
                    count[1],
                    count[0]
                )
            )
            return imports

        return None
开发者ID:Mause,项目名称:Javatar,代码行数:31,代码来源:javatar_collections.py


示例18: process_message

    def process_message(self):
        """Called when a full line has been read from the socket
        """

        message = b''.join(self.rbuffer)
        self.rbuffer = []

        try:
            data = sublime.decode_value(message.decode('utf8'))
        except NameError:
            data = json.loads(message.decode('utf8'))

        callback = self.callbacks.pop(data.pop('uid'))
        if callback is None:
            logger.error(
                'Received {} from the JSONServer but there is not callback '
                'to handle it. Aborting....'.format(message)
            )

        try:
            callback(data)
        except Exception as error:
            logging.error(error)
            for traceback_line in traceback.format_exc().splitlines():
                logging.error(traceback_line)
开发者ID:NorthIsUp,项目名称:anaconda,代码行数:25,代码来源:jsonclient.py


示例19: on_pre_close

    def on_pre_close(self, view):
        if not view.settings().get('rust_environment_editor'):
            return
        settings = view.settings().get('rust_environment_editor_settings')

        contents = view.substr(sublime.Region(0, view.size()))
        try:
            result = sublime.decode_value(contents)
        except:
            sublime.error_message('Value was not valid JSON, try again.')
            view.window().run_command('cargo_set_environment_editor', {
                'package': settings.get('package'),
                'which': settings['which'],
                'variant': settings.get('variant'),
                'target': settings.get('target'),
                'contents': contents,
            })
            return

        view.window().run_command('cargo_set_environment', {
            'package': settings.get('package'),
            'which': settings['which'],
            'variant': settings.get('variant'),
            'target': settings.get('target'),
            'env': result,
        })
开发者ID:rust-lang,项目名称:sublime-rust,代码行数:26,代码来源:cargo_config.py


示例20: getConnections

    def getConnections():
        connections = {}
        directory = os.path.join(sublime.packages_path(), 'User', global_settings.get('configs_folder'))
        if not os.path.isdir(directory):
            try:
                os.makedirs(directory)
            except OSError as exc: # Python >2.5
                if exc.errno == errno.EEXIST and os.path.isdir(directory):
                    pass
                else: raise
        for name in os.listdir(directory):
            if name[:1] == '.':
                continue

            json = None

            with open(os.path.join(directory, name)) as f:
                try:
                    json = sublime.decode_value(f.read())
                except Exception as e:
                    debug('could not load config file(%s): %s' % (name, e))
                    continue
            json['name'] = name
            connections[name] = json
        return collections.OrderedDict(sorted(connections.items(), key=lambda k: k))
开发者ID:alexgalletti,项目名称:sublime-ftp-plugin,代码行数:25,代码来源:FTP.py



注:本文中的sublime.decode_value函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sublime.encode_value函数代码示例发布时间:2022-05-27
下一篇:
Python sublime.cache_path函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap