Python six.moves() Examples

The following are 30 code examples for showing how to use six.moves(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module six , or try the search function .

Example 1
Project: neuropythy   Author: noahbenson   File: filemap.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def osf_crawl(k, *pths, **kw):
    '''
    osf_crawl(k) crawls the osf repository k and returns a lazy nested map structure of the
      repository's files. Folders have values that are maps of their contents while files have
      values that are their download links.
    osf_crawl(k1, k2, ...) is equivalent to osf_crawl(posixpath.join(k1, k2...)).

    The optional named argument base (default: 'osfstorage') may be specified to search in a
    non-standard storage position in the OSF URL; e.g. in the github storage.
    '''
    from six.moves import reduce
    base = kw.pop('base', 'osfstorage')
    root = kw.pop('root', None)
    if len(kw) > 0: raise ValueError('Unknown optional parameters: %s' % (list(kw.keys()),))
    if k.lower().startswith('osf:'): k = k[4:]
    k = k.lstrip('/')
    pths = [p.lstrip('/') for p in (k.split('/') + list(pths))]
    (bpth, pths) = (pths[0].strip('/'), [p for p in pths[1:] if p != ''])
    if root is None: root = _osf_tree(bpth, base=base)
    return reduce(lambda m,k: m[k], pths, root) 
Example 2
Project: pyeclib   Author: openstack   File: test_pyeclib_api.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_import_error_in_the_error_handling(self):
        pyeclib_drivers = self.get_pyeclib_testspec()
        self.assertGreater(len(pyeclib_drivers), 0)
        pyeclib_driver = pyeclib_drivers[0]

        from six.moves import builtins
        real_import = builtins.__import__

        def fake_import(*a, **kw):
            raise ImportError

        builtins.__import__ = fake_import
        try:
            with self.assertRaises(ImportError):  # !!
                pyeclib_driver.encode(3)
        finally:
            builtins.__import__ = real_import 
Example 3
Project: linter-pylama   Author: AtomLinter   File: raw_building.py    License: MIT License 6 votes vote down vote up
def _astroid_bootstrapping(astroid_builtin=None):
    """astroid boot strapping the builtins module"""
    # this boot strapping is necessary since we need the Const nodes to
    # inspect_build builtins, and then we can proxy Const
    if astroid_builtin is None:
        from six.moves import builtins
        astroid_builtin = Astroid_BUILDER.inspect_build(builtins)

    # pylint: disable=redefined-outer-name
    for cls, node_cls in node_classes.CONST_CLS.items():
        if cls is type(None):
            proxy = build_class('NoneType')
            proxy.parent = astroid_builtin
        elif cls is type(NotImplemented):
            proxy = build_class('NotImplementedType')
            proxy.parent = astroid_builtin
        else:
            proxy = astroid_builtin.getattr(cls.__name__)[0]
        if cls in (dict, list, set, tuple):
            node_cls._proxied = proxy
        else:
            _CONST_PROXY[cls] = proxy 
Example 4
Project: Safejumper-for-Desktop   Author: proxysh   File: package_index.py    License: GNU General Public License v2.0 6 votes vote down vote up
def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in six.moves.filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element 
Example 5
Project: ibeis   Author: Erotemic   File: IBEISControl.py    License: Apache License 2.0 6 votes vote down vote up
def __getstate__(ibs):
        """
        Example:
            >>> # ENABLE_DOCTEST
            >>> import ibeis
            >>> from six.moves import cPickle as pickle
            >>> ibs = ibeis.opendb('testdb1')
            >>> ibs_dump = pickle.dumps(ibs)
            >>> ibs2 = pickle.loads(ibs_dump)
        """
        # Hack to allow for ibeis objects to be pickled
        state = {
            'dbdir': ibs.get_dbdir(),
            'machine_name': ut.get_computer_name(),
        }
        return state 
Example 6
Project: ibeis   Author: Erotemic   File: appfuncs.py    License: Apache License 2.0 6 votes vote down vote up
def embed_image_html(imgBGR, target_width=TARGET_WIDTH, target_height=TARGET_HEIGHT):
    """ Creates an image embedded in HTML base64 format. """
    import cv2
    from PIL import Image
    if target_width is not None:
        imgBGR = _resize(imgBGR, t_width=target_width)
    elif target_height is not None:
        imgBGR = _resize(imgBGR, t_height=target_height)
    imgRGB = cv2.cvtColor(imgBGR, cv2.COLOR_BGR2RGB)
    pil_img = Image.fromarray(imgRGB)
    if six.PY2:
        from six.moves import cStringIO as StringIO
        string_buf = StringIO()
        pil_img.save(string_buf, format='jpeg')
        data = string_buf.getvalue().encode('base64').replace('\n', '')
    else:
        import io
        byte_buf = io.BytesIO()
        pil_img.save(byte_buf, format='jpeg')
        byte_buf.seek(0)
        img_bytes = base64.b64encode(byte_buf.read())
        data = img_bytes.decode('ascii')
    return 'data:image/jpeg;base64,' + data 
Example 7
Project: eclcli   Author: nttcom   File: gettextutils.py    License: Apache License 2.0 6 votes vote down vote up
def install(domain):
    """Install a _() function using the given translation domain.

    Given a translation domain, install a _() function using gettext's
    install() function.

    The main difference from gettext.install() is that we allow
    overriding the default localedir (e.g. /usr/share/locale) using
    a translation-domain-specific environment variable (e.g.
    NOVA_LOCALEDIR).

    Note that to enable lazy translation, enable_lazy must be
    called.

    :param domain: the translation domain
    """
    from six import moves
    tf = TranslatorFactory(domain)
    moves.builtins.__dict__['_'] = tf.primary 
Example 8
Project: imgaug   Author: aleju   File: parameters.py    License: MIT License 6 votes vote down vote up
def _draw_samples(self, size, random_state):
        rngs = random_state.duplicate(3)
        result = self.other_param.draw_samples(size, random_state=rngs[0])
        if result.dtype.kind != "f":
            result = result.astype(np.float32)
        activated = self.activated.draw_sample(random_state=rngs[1])
        threshold = self.threshold.draw_sample(random_state=rngs[2])
        if activated > 0.5:
            # threshold must be subtracted here, not added
            # higher threshold = move threshold of sigmoid towards the right
            #                  = make it harder to pass the threshold
            #                  = more 0.0s / less 1.0s
            # by subtracting a high value, it moves each x towards the left,
            # leading to more values being left of the threshold, leading
            # to more 0.0s
            return 1 / (1 + np.exp(-(result * self.mul + self.add - threshold)))
        return result 
Example 9
Project: glance_store   Author: openstack   File: test_swift_store_multibackend.py    License: Apache License 2.0 6 votes vote down vote up
def test_add_multi_store(self):

        conf = copy.deepcopy(SWIFT_CONF)
        conf['default_swift_reference'] = 'store_2'
        self.config(group="swift1", **conf)
        moves.reload_module(swift)
        self.mock_keystone_client()
        self.store = Store(self.conf, backend="swift1")
        self.store.configure()

        expected_swift_size = FIVE_KB
        expected_swift_contents = b"*" * expected_swift_size
        expected_image_id = str(uuid.uuid4())
        image_swift = six.BytesIO(expected_swift_contents)
        global SWIFT_PUT_OBJECT_CALLS
        SWIFT_PUT_OBJECT_CALLS = 0
        loc = 'swift+config://store_2/glance/%s'

        expected_location = loc % (expected_image_id)

        location, size, checksum, arg = self.store.add(expected_image_id,
                                                       image_swift,
                                                       expected_swift_size)
        self.assertEqual("swift1", arg['store'])
        self.assertEqual(expected_location, location) 
Example 10
Project: glance_store   Author: openstack   File: test_swift_store_multibackend.py    License: Apache License 2.0 6 votes vote down vote up
def test_delete(self):
        """
        Test we can delete an existing image in the swift store
        """
        conf = copy.deepcopy(SWIFT_CONF)
        self.config(group="swift1", **conf)
        moves.reload_module(swift)
        self.mock_keystone_client()
        self.store = Store(self.conf, backend="swift1")
        self.store.configure()

        uri = "swift://%s:key@authurl/glance/%s" % (
            self.swift_store_user, FAKE_UUID)
        loc = location.get_location_from_uri_and_backend(
            uri, "swift1", conf=self.conf)
        self.store.delete(loc)

        self.assertRaises(exceptions.NotFound, self.store.get, loc) 
Example 11
Project: glance_store   Author: openstack   File: test_swift_store_multibackend.py    License: Apache License 2.0 6 votes vote down vote up
def test_delete_slo(self, mock_del_obj):
        """
        Test we can delete an existing image stored as SLO, static large object
        """
        conf = copy.deepcopy(SWIFT_CONF)
        self.config(group="swift1", **conf)
        moves.reload_module(swift)
        self.store = Store(self.conf, backend="swift1")
        self.store.configure()

        uri = "swift://%s:key@authurl/glance/%s" % (self.swift_store_user,
                                                    FAKE_UUID2)
        loc = location.get_location_from_uri_and_backend(
            uri, "swift1", conf=self.conf)
        self.store.delete(loc)

        self.assertEqual(1, mock_del_obj.call_count)
        _, kwargs = mock_del_obj.call_args
        self.assertEqual('multipart-manifest=delete',
                         kwargs.get('query_string')) 
Example 12
Project: glance_store   Author: openstack   File: test_swift_store_multibackend.py    License: Apache License 2.0 6 votes vote down vote up
def test_delete_nonslo_not_deleted_as_slo(self, mock_del_obj):
        """
        Test that non-SLOs are not being deleted the SLO way
        """
        conf = copy.deepcopy(SWIFT_CONF)
        self.config(group="swift1", **conf)
        moves.reload_module(swift)
        self.mock_keystone_client()
        self.store = Store(self.conf, backend="swift1")
        self.store.configure()

        uri = "swift://%s:key@authurl/glance/%s" % (self.swift_store_user,
                                                    FAKE_UUID)
        loc = location.get_location_from_uri_and_backend(
            uri, "swift1", conf=self.conf)
        self.store.delete(loc)

        self.assertEqual(1, mock_del_obj.call_count)
        _, kwargs = mock_del_obj.call_args
        self.assertIsNone(kwargs.get('query_string')) 
Example 13
Project: glance_store   Author: openstack   File: test_swift_store_multibackend.py    License: Apache License 2.0 6 votes vote down vote up
def test_delete_with_reference_params(self):
        """
        Test we can delete an existing image in the swift store
        """
        conf = copy.deepcopy(SWIFT_CONF)
        self.config(group="swift1", **conf)
        moves.reload_module(swift)
        # mock client because v3 uses it to receive auth_info
        self.mock_keystone_client()
        self.store = Store(self.conf, backend="swift1")
        self.store.configure()

        uri = "swift+config://ref1/glance/%s" % (FAKE_UUID)
        loc = location.get_location_from_uri_and_backend(
            uri, "swift1", conf=self.conf)
        self.store.delete(loc)

        self.assertRaises(exceptions.NotFound, self.store.get, loc) 
Example 14
Project: glance_store   Author: openstack   File: test_swift_store_multibackend.py    License: Apache License 2.0 6 votes vote down vote up
def test_single_tenant_location(self):
        conf = copy.deepcopy(SWIFT_CONF)
        conf['swift_store_container'] = 'container'
        conf_file = "glance-swift.conf"
        self.swift_config_file = self.copy_data_file(conf_file, self.test_dir)
        conf.update({'swift_store_config_file': self.swift_config_file})
        conf['default_swift_reference'] = 'ref1'
        self.config(group="swift1", **conf)
        moves.reload_module(swift)

        store = swift.SingleTenantStore(self.conf, backend="swift1")
        store.configure()
        location = store.create_location('image-id')
        self.assertEqual('swift+https', location.scheme)
        self.assertEqual('https://example.com', location.swift_url)
        self.assertEqual('container', location.container)
        self.assertEqual('image-id', location.obj)
        self.assertEqual('tenant:user1', location.user)
        self.assertEqual('key1', location.key) 
Example 15
Project: glance_store   Author: openstack   File: test_swift_store.py    License: Apache License 2.0 6 votes vote down vote up
def test_add_multi_store(self):

        conf = copy.deepcopy(SWIFT_CONF)
        conf['default_swift_reference'] = 'store_2'
        self.config(**conf)
        moves.reload_module(swift)
        self.mock_keystone_client()
        self.store = Store(self.conf)
        self.store.configure()

        expected_swift_size = FIVE_KB
        expected_swift_contents = b"*" * expected_swift_size
        expected_image_id = str(uuid.uuid4())
        image_swift = six.BytesIO(expected_swift_contents)
        global SWIFT_PUT_OBJECT_CALLS
        SWIFT_PUT_OBJECT_CALLS = 0
        loc = 'swift+config://store_2/glance/%s'

        expected_location = loc % (expected_image_id)

        location, size, checksum, multihash, arg = self.store.add(
            expected_image_id, image_swift, expected_swift_size, HASH_ALGO)
        self.assertEqual(expected_location, location) 
Example 16
Project: glance_store   Author: openstack   File: test_swift_store.py    License: Apache License 2.0 6 votes vote down vote up
def test_delete(self):
        """
        Test we can delete an existing image in the swift store
        """
        conf = copy.deepcopy(SWIFT_CONF)
        self.config(**conf)
        moves.reload_module(swift)
        self.mock_keystone_client()
        self.store = Store(self.conf)
        self.store.configure()

        uri = "swift://%s:key@authurl/glance/%s" % (
            self.swift_store_user, FAKE_UUID)
        loc = location.get_location_from_uri(uri, conf=self.conf)
        self.store.delete(loc)

        self.assertRaises(exceptions.NotFound, self.store.get, loc) 
Example 17
Project: glance_store   Author: openstack   File: test_swift_store.py    License: Apache License 2.0 6 votes vote down vote up
def test_delete_nonslo_not_deleted_as_slo(self, mock_del_obj):
        """
        Test that non-SLOs are not being deleted the SLO way
        """
        conf = copy.deepcopy(SWIFT_CONF)
        self.config(**conf)
        moves.reload_module(swift)
        self.mock_keystone_client()
        self.store = Store(self.conf)
        self.store.configure()

        uri = "swift://%s:key@authurl/glance/%s" % (self.swift_store_user,
                                                    FAKE_UUID)
        loc = location.get_location_from_uri(uri, conf=self.conf)
        self.store.delete(loc)

        self.assertEqual(1, mock_del_obj.call_count)
        _, kwargs = mock_del_obj.call_args
        self.assertIsNone(kwargs.get('query_string')) 
Example 18
Project: glance_store   Author: openstack   File: test_swift_store.py    License: Apache License 2.0 6 votes vote down vote up
def test_delete_with_reference_params(self):
        """
        Test we can delete an existing image in the swift store
        """
        conf = copy.deepcopy(SWIFT_CONF)
        self.config(**conf)
        moves.reload_module(swift)
        # mock client because v3 uses it to receive auth_info
        self.mock_keystone_client()
        self.store = Store(self.conf)
        self.store.configure()

        uri = "swift+config://ref1/glance/%s" % (FAKE_UUID)
        loc = location.get_location_from_uri(uri, conf=self.conf)
        self.store.delete(loc)

        self.assertRaises(exceptions.NotFound, self.store.get, loc) 
Example 19
Project: pysmt   Author: pysmt   File: base.py    License: Apache License 2.0 6 votes vote down vote up
def mv(source, dest):
        """Similarly to the UNIX mv command, moves / renames source_file in
        dest (if dest is a file name) otherwise moves source_file in
        the directory dest
        """
        if os.path.isdir(dest):
            dest = os.path.join(dest, os.path.basename(source))

        if os.path.isdir(source):
            if os.path.exists(dest):
                if os.path.isdir(dest):
                    shutil.rmtree(dest, ignore_errors=True)
                else:
                    os.unlink(dest)
            shutil.copytree(source, dest, symlinks=True)
            shutil.rmtree(source, ignore_errors=True)
        else:
            shutil.copy(source, dest)
            os.unlink(source) 
Example 20
Project: ubelt   Author: Erotemic   File: util_cmd.py    License: Apache License 2.0 6 votes vote down vote up
def _proc_async_iter_stream(proc, stream, buffersize=1):
    """
    Reads output from a process in a separate thread
    """
    from six.moves import queue
    from threading import Thread
    def enqueue_output(proc, stream, stream_queue):
        while proc.poll() is None:
            line = stream.readline()
            # print('ENQUEUE LIVE {!r} {!r}'.format(stream, line))
            stream_queue.put(line)

        for line in _textio_iterlines(stream):
            # print('ENQUEUE FINAL {!r} {!r}'.format(stream, line))
            stream_queue.put(line)

        # print("STREAM IS DONE {!r}".format(stream))
        stream_queue.put(None)  # signal that the stream is finished
        # stream.close()
    stream_queue = queue.Queue(maxsize=buffersize)
    _thread = Thread(target=enqueue_output, args=(proc, stream, stream_queue))
    _thread.daemon = True  # thread dies with the program
    _thread.start()
    return stream_queue 
Example 21
Project: manila   Author: openstack   File: test_api.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Setup the Qnap API TestCase."""
        super(QnapAPITestCase, self).setUp()
        fake_parms = {}
        fake_parms['user'] = 'admin'
        fake_parms['pwd'] = base64.b64encode(
            self.fake_password.encode("utf-8"))
        fake_parms['serviceKey'] = 1
        sanitized_params = self._sanitize_params(fake_parms)
        self.login_url = ('/cgi-bin/authLogin.cgi?%s' % sanitized_params)
        self.mock_object(six.moves.http_client, 'HTTPConnection')
        self.share = fake_share.fake_share(
            share_proto='NFS',
            id='shareId',
            display_name='fakeDisplayName',
            export_locations=[{'path': '1.2.3.4:/share/fakeShareName'}],
            host='QnapShareDriver',
            size=10) 
Example 22
Project: vokativ   Author: Mimino666   File: vokativ.py    License: MIT License 5 votes vote down vote up
def _get_matching_suffix(self, name, suffixes):
        # it is important(!) to try suffixes from longest to shortest
        for suffix_length in six.moves.xrange(len(name), 0, -1):
            suffix = name[-suffix_length:]
            if suffix in suffixes:
                return (suffix, suffixes[suffix])
        return ('', suffixes.get('')) 
Example 23
Project: pyspider   Author: binux   File: run.py    License: Apache License 2.0 5 votes vote down vote up
def connect_rpc(ctx, param, value):
    if not value:
        return
    try:
        from six.moves import xmlrpc_client
    except ImportError:
        import xmlrpclib as xmlrpc_client
    return xmlrpc_client.ServerProxy(value, allow_none=True) 
Example 24
Project: linter-pylama   Author: AtomLinter   File: raw_building.py    License: MIT License 5 votes vote down vote up
def imported_member(self, node, member, name):
        """verify this is not an imported class or handle it"""
        # /!\ some classes like ExtensionClass doesn't have a __module__
        # attribute ! Also, this may trigger an exception on badly built module
        # (see http://www.logilab.org/ticket/57299 for instance)
        try:
            modname = getattr(member, '__module__', None)
        except: # pylint: disable=bare-except
            _LOG.exception('unexpected error while building '
                           'astroid from living object')
            modname = None
        if modname is None:
            if (name in ('__new__', '__subclasshook__')
                    or (name in _BUILTINS and _JYTHON)):
                # Python 2.5.1 (r251:54863, Sep  1 2010, 22:03:14)
                # >>> print object.__new__.__module__
                # None
                modname = six.moves.builtins.__name__
            else:
                attach_dummy_node(node, name, member)
                return True

        real_name = {
            'gtk': 'gtk_gtk',
            '_io': 'io',
        }.get(modname, modname)

        if real_name != self._module.__name__:
            # check if it sounds valid and then add an import node, else use a
            # dummy node
            try:
                getattr(sys.modules[modname], name)
            except (KeyError, AttributeError):
                attach_dummy_node(node, name, member)
            else:
                attach_import_node(node, modname, name)
            return True
        return False


### astroid bootstrapping ###################################################### 
Example 25
Project: linter-pylama   Author: AtomLinter   File: exceptions.py    License: MIT License 5 votes vote down vote up
def _builtin_exceptions():
    def predicate(obj):
        return isinstance(obj, type) and issubclass(obj, BaseException)

    members = inspect.getmembers(six.moves.builtins, predicate)
    return {exc.__name__ for (_, exc) in members} 
Example 26
Project: ec2-api   Author: openstack   File: cloud.py    License: Apache License 2.0 5 votes vote down vote up
def module_and_param_types(module, *args, **kwargs):
    """Decorator to check types and call function."""

    param_types = args

    def wrapped(func):

        def func_wrapped(*args, **kwargs):
            impl_func = getattr(module, func.__name__)
            context = args[1]
            params = collections.OrderedDict(six.moves.zip(
                func.__code__.co_varnames[2:], param_types))
            param_num = 0
            mandatory_params_num = (func.__code__.co_argcount - 2 -
                                    len(func.__defaults__ or []))
            for param_name, param_type in params.items():
                param_value = kwargs.get(param_name)
                if param_value is not None:
                    validator = module.Validator(param_name, func.__name__,
                                                 params)
                    validation_func = getattr(validator, param_type)
                    validation_func(param_value)
                    param_num += 1
                elif param_num < mandatory_params_num:
                    raise exception.MissingParameter(param=param_name)
            return impl_func(context, **kwargs)
        return func_wrapped

    return wrapped 
Example 27
Project: chainer-compiler   Author: pfnet-research   File: values.py    License: MIT License 5 votes vote down vote up
def try_get_obj(self, name: 'str', inst: 'Object', root_graph : 'graphs.Graph') -> 'Object':


        if self.internal_module == six.moves:
            # Calling `inspect.getmembers` for `six.moves` causes
            # eager load for potentially non-existent libraries such
            # as tkinter or gdbm. To workaround this issue, we
            # retrieve only whitelisted members in `six.moves`.
            # TODO(hamaji): Figure out a better workaround.
            safe_keys = ['range', 'xrange', 'map', 'filter', 'zip']
            members = [(k, getattr(self.internal_module, k)) for k in safe_keys]
        else:
            members = inspect.getmembers(self.internal_module)
        members_dict = {}
        for member in members:
            members_dict[member[0]] = member[1]

        if not (name in members_dict.keys()):
            if name in builtin_function_converters.keys():
                v = Object(builtin_function_converters[name])
                return v
            return None

        attr_v = members_dict[name]

        dummy_flags_members_dict = {}
        dummy_flags_members = inspect.getmembers(flags)
        for member in dummy_flags_members:
            if isinstance(member[1], types.FunctionType):
                dummy_flags_members_dict[member[0]] = member[1]

        if name in dummy_flags_members_dict.keys():
            v = Object(builtin_function_converters[name])
            return v

        v = parse_instance(inst, name, attr_v, None)
        return v 
Example 28
Project: vrequest   Author: cilame   File: pyqrcode.py    License: MIT License 5 votes vote down vote up
def map_data(self, data, mask_pattern):
        inc = -1
        row = self.modules_count - 1
        bitIndex = 7
        byteIndex = 0
        _mask_func = mask_func(mask_pattern)
        data_len = len(data)
        for col in six.moves.xrange(self.modules_count - 1, 0, -2):
            if col <= 6:
                col -= 1
            col_range = (col, col-1)
            while True:
                for c in col_range:
                    if self.modules[row][c] is None:
                        dark = False
                        if byteIndex < data_len:
                            dark = (((data[byteIndex] >> bitIndex) & 1) == 1)
                        if _mask_func(row, c):
                            dark = not dark
                        self.modules[row][c] = dark
                        bitIndex -= 1
                        if bitIndex == -1:
                            byteIndex += 1
                            bitIndex = 7
                row += inc
                if row < 0 or self.modules_count <= row:
                    row -= inc
                    inc = -inc
                    break 
Example 29
Project: Safejumper-for-Desktop   Author: proxysh   File: package_index.py    License: GNU General Public License v2.0 5 votes vote down vote up
def decode_entity(match):
    what = match.group(1)
    if what.startswith('#x'):
        what = int(what[2:], 16)
    elif what.startswith('#'):
        what = int(what[1:])
    else:
        what = six.moves.html_entities.name2codepoint.get(what, match.group(0))
    return uchr(what) 
Example 30
Project: plex-for-kodi   Author: plexinc   File: library.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getFilterOpts(self):
        if not self.filter:
            return None

        if not self.filter.get('sub'):
            util.DEBUG_LOG('Filter missing sub-filter data')
            return None

        return (self.filter['type'], six.moves.urllib.parse.unquote_plus(self.filter['sub']['val']))