Python re.I() Examples

The following are code examples for showing how to use re.I(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: parsechain   Author: Suor   File: chains.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def duration(text):
        regexes = [
            r'()(?:(\d\d):)?(\d\d):(\d\d)(?:\s|$)',
            re.compile(r'''\s* (?:(\d+)\s*д[еньяй.]*)?
                           \s* (?:(\d+)\s*ч[ас.]*)?
                           \s* (?:(\d+)\s*м[инуты.]*)?
                           ()''', re.I | re.X)
        ]
        for regex in regexes:
            m = re_find(regex, text)
            if m:
                days, hours, minutes, seconds = [silent(int)(p) or 0 for p in m]
                if days == hours == minutes == 0:
                    return None
                return (days * 24 + hours * 60 + minutes) * 60 + seconds
                # return datetime.timedelta(days=days, hours=hours, minutes=minutes)


# Chain.register('float', _list_first(float))
# @Chain.register
# def func(...):
#     pass


# Advanced introspection 
Example 2
Project: pyblish-win   Author: pyblish   File: urllib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, proxies=None, context=None, **x509):
        if proxies is None:
            proxies = getproxies()
        assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
        self.proxies = proxies
        self.key_file = x509.get('key_file')
        self.cert_file = x509.get('cert_file')
        self.context = context
        self.addheaders = [('User-Agent', self.version)]
        self.__tempfiles = []
        self.__unlink = os.unlink # See cleanup()
        self.tempcache = None
        # Undocumented feature: if you assign {} to tempcache,
        # it is used to cache files retrieved with
        # self.retrieve().  This is not enabled by default
        # since it does not work for changing documents (and I
        # haven't got the logic to check expiration headers
        # yet).
        self.ftpcache = ftpcache
        # Undocumented feature: you can use a different
        # ftp cache by assigning to the .ftpcache member;
        # in case you want logically independent URL openers
        # XXX This is not threadsafe.  Bah. 
Example 3
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_ignore_case(self):
        self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
        self.assertEqual(re.match("abc", u"ABC", re.I).group(0), "ABC")
        self.assertEqual(re.match(r"(a\s[^a])", "a b", re.I).group(1), "a b")
        self.assertEqual(re.match(r"(a\s[^a]*)", "a bb", re.I).group(1), "a bb")
        self.assertEqual(re.match(r"(a\s[abc])", "a b", re.I).group(1), "a b")
        self.assertEqual(re.match(r"(a\s[abc]*)", "a bb", re.I).group(1), "a bb")
        self.assertEqual(re.match(r"((a)\s\2)", "a a", re.I).group(1), "a a")
        self.assertEqual(re.match(r"((a)\s\2*)", "a aa", re.I).group(1), "a aa")
        self.assertEqual(re.match(r"((a)\s(abc|a))", "a a", re.I).group(1), "a a")
        self.assertEqual(re.match(r"((a)\s(abc|a)*)", "a aa", re.I).group(1), "a aa")

        if have_unicode:
            assert u(r'\u212a').lower() == u'k' # 'K'
            self.assertTrue(re.match(ur'K', u(r'\u212a'), re.U | re.I))
            self.assertTrue(re.match(ur'k', u(r'\u212a'), re.U | re.I))
            self.assertTrue(re.match(u(r'\u212a'), u'K', re.U | re.I))
            self.assertTrue(re.match(u(r'\u212a'), u'k', re.U | re.I))
            assert u(r'\u017f').upper() == u'S' # 'ſ'
            self.assertTrue(re.match(ur'S', u(r'\u017f'), re.U | re.I))
            self.assertTrue(re.match(ur's', u(r'\u017f'), re.U | re.I))
            self.assertTrue(re.match(u(r'\u017f'), u'S', re.U | re.I))
            self.assertTrue(re.match(u(r'\u017f'), u's', re.U | re.I)) 
Example 4
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_ignore_case_set(self):
        self.assertTrue(re.match(r'[19A]', 'A', re.I))
        self.assertTrue(re.match(r'[19a]', 'a', re.I))
        self.assertTrue(re.match(r'[19a]', 'A', re.I))
        self.assertTrue(re.match(r'[19A]', 'a', re.I))
        if have_unicode:
            self.assertTrue(re.match(ur'[19A]', u'A', re.U | re.I))
            self.assertTrue(re.match(ur'[19a]', u'a', re.U | re.I))
            self.assertTrue(re.match(ur'[19a]', u'A', re.U | re.I))
            self.assertTrue(re.match(ur'[19A]', u'a', re.U | re.I))
            assert u(r'\u212a').lower() == u'k' # 'K'
            self.assertTrue(re.match(u(r'[19K]'), u(r'\u212a'), re.U | re.I))
            self.assertTrue(re.match(u(r'[19k]'), u(r'\u212a'), re.U | re.I))
            self.assertTrue(re.match(u(r'[19\u212a]'), u'K', re.U | re.I))
            self.assertTrue(re.match(u(r'[19\u212a]'), u'k', re.U | re.I))
            assert u(r'\u017f').upper() == u'S' # 'ſ'
            self.assertTrue(re.match(ur'[19S]', u(r'\u017f'), re.U | re.I))
            self.assertTrue(re.match(ur'[19s]', u(r'\u017f'), re.U | re.I))
            self.assertTrue(re.match(u(r'[19\u017f]'), u'S', re.U | re.I))
            self.assertTrue(re.match(u(r'[19\u017f]'), u's', re.U | re.I)) 
Example 5
Project: pyblish-win   Author: pyblish   File: test_cookielib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_url_encoding(self):
        # Try some URL encodings of the PATHs.
        # (the behaviour here has changed from libwww-perl)
        from cookielib import CookieJar, DefaultCookiePolicy

        c = CookieJar(DefaultCookiePolicy(rfc2965=True))
        interact_2965(c, "http://www.acme.com/foo%2f%25/%3c%3c%0Anew%E5/%E5",
                      "foo  =   bar; version    =   1")

        cookie = interact_2965(
            c, "http://www.acme.com/foo%2f%25/<<%0anew�/���",
            'bar=baz; path="/foo/"; version=1');
        version_re = re.compile(r'^\$version=\"?1\"?', re.I)
        self.assertIn("foo=bar", cookie)
        self.assertRegexpMatches(cookie, version_re)

        cookie = interact_2965(
            c, "http://www.acme.com/foo/%25/<<%0anew�/���")
        self.assertFalse(cookie)

        # unicode URL doesn't raise exception
        cookie = interact_2965(c, u"http://www.acme.com/\xfc") 
Example 6
Project: claxon   Author: vanatteveldt   File: views.py    GNU General Public License v3.0 6 votes vote down vote up
def get_context_data(self, **kwargs):
        kwargs = super().get_context_data(**kwargs)

        done = self.state.session.annotation_set.all()
        label = self.state.session.label
        if 'next' in self.request.GET:
            docid = int(self.request.GET['next'])
            doc = self.project.document_set.get(pk=docid)
        else:
            doc = self.state.get_doc(trigger=settings.N_TRIGGER)
        score = self.state.scores.get(doc.id)
        ntodo = len(self.state.get_todo())
        text = doc.text.replace("\n", "<br/>")
        if self.state.session.query:
            text = re.sub("({})".format(self.state.session.query), "<b>\\1</b>", text, flags=re.I)
        base_url = reverse("actcode:code-learn",  kwargs=dict(project=self.project.id, session=self.state.session.id))
        accept_url = "{base_url}?doc={doc.id}&accept=1".format(**locals())
        reject_url = "{base_url}?doc={doc.id}&accept=0".format(**locals())
        state = self.state
        kwargs.update(**locals())
        return kwargs 
Example 7
Project: JI-Live-Danmu-Client   Author: SJTU-UMJI-Tech   File: DanmuManager.py    MIT License 6 votes vote down vote up
def parseText(self, text):
        textColor = QColor(240, 240, 240)
        style = 'fly'
        matchObject = re.search(
            r'\#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})', text)
        if matchObject:
            textColor = QColor(
                int(matchObject.group(1), 16), int(matchObject.group(2), 16),
                int(matchObject.group(3), 16))
            text = re.sub(r'\#[0-9a-fA-F]{6}', '', text)
        if re.search(r'\#top', text, re.I):
            style = 'top'
            text = re.sub(r'\#top', '', text, re.I)
        elif re.search(r'\#btm', text, re.I):
            style = 'btm'
            text = re.sub(r'\#btm', '', text, re.I)
        return text, textColor, style 
Example 8
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: locators.py    MIT License 6 votes vote down vote up
def __init__(self, url, timeout=None, num_workers=10, **kwargs):
        """
        Initialise an instance.
        :param url: The root URL to use for scraping.
        :param timeout: The timeout, in seconds, to be applied to requests.
                        This defaults to ``None`` (no timeout specified).
        :param num_workers: The number of worker threads you want to do I/O,
                            This defaults to 10.
        :param kwargs: Passed to the superclass.
        """
        super(SimpleScrapingLocator, self).__init__(**kwargs)
        self.base_url = ensure_slash(url)
        self.timeout = timeout
        self._page_cache = {}
        self._seen = set()
        self._to_fetch = queue.Queue()
        self._bad_hosts = set()
        self.skip_externals = False
        self.num_workers = num_workers
        self._lock = threading.RLock()
        # See issue #45: we need to be resilient when the locator is used
        # in a thread, e.g. with concurrent.futures. We can't use self._lock
        # as it is for coordinating our internal threads - the ones created
        # in _prepare_threads.
        self._gplock = threading.RLock() 
Example 9
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 6 votes vote down vote up
def get_encodings_from_content(content):
    """Returns encodings from given content string.

    :param content: bytestring to extract encodings from.
    """
    warnings.warn((
        'In requests 3.0, get_encodings_from_content will be removed. For '
        'more information, please see the discussion on issue #2266. (This'
        ' warning should only appear once.)'),
        DeprecationWarning)

    charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
    pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
    xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')

    return (charset_re.findall(content) +
            pragma_re.findall(content) +
            xml_re.findall(content)) 
Example 10
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: enos_facts.py    MIT License 6 votes vote down vote up
def parse_ipaddresses(self, data4):
        parsed = list()
        for line in data4:
            if len(line) == 0:
                continue
            else:
                line = line.strip()
                if len(line) == 0:
                    continue
                match = re.search(r'IP4', line, re.M | re.I)
                if match:
                    key = match.group()
                    parsed.append(line)
                match = re.search(r'IP6', line, re.M | re.I)
                if match:
                    key = match.group()
                    parsed.append(line)
        return parsed 
Example 11
Project: flasky   Author: RoseOu   File: locators.py    MIT License 6 votes vote down vote up
def __init__(self, url, timeout=None, num_workers=10, **kwargs):
        """
        Initialise an instance.
        :param url: The root URL to use for scraping.
        :param timeout: The timeout, in seconds, to be applied to requests.
                        This defaults to ``None`` (no timeout specified).
        :param num_workers: The number of worker threads you want to do I/O,
                            This defaults to 10.
        :param kwargs: Passed to the superclass.
        """
        super(SimpleScrapingLocator, self).__init__(**kwargs)
        self.base_url = ensure_slash(url)
        self.timeout = timeout
        self._page_cache = {}
        self._seen = set()
        self._to_fetch = queue.Queue()
        self._bad_hosts = set()
        self.skip_externals = False
        self.num_workers = num_workers
        self._lock = threading.RLock() 
Example 12
Project: elsbot   Author: Praisebetoscience   File: elsbot.py    MIT License 6 votes vote down vote up
def _build(archives, quote, subreddit):

        # Header
        comment = quote + "\n\nSnapshots:\n\n"

        # List of snapshots
        for ac in archives:
            comment += "* {} - ".format(ac.text)
            i = 1
            for a in ac:
                if a.archived:
                    comment += "[{}]({}), ".format(i, a.archived)
                elif a.archived is None:
                    continue
                else:
                    comment += "[{}]({}), ".format('Error', a.error_link)
                i += 1
            comment = comment.strip(', ') + '\n'

        # Footer
        comment += "\n\n*I am a bot. ([Info](/r/{0}) | [Contact](/r/{0}/submit?selftext=true))*".format(subreddit)

        return comment 
Example 13
Project: plugin.program.steam.streaming   Author: Drakulix   File: wake.py    MIT License 6 votes vote down vote up
def wake(params):
    mac = params.get('mac', None).replace("-", ":")
    if mac:
        xbmc.executebuiltin("WakeOnLan("+mac+")") #this is very easy, thanks kodi
    else:
        keyboard = xbmc.Keyboard('', utils.translation(32035))
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            mac = keyboard.getText()
            if re.match(r'^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$', mac, re.I) == None: #verify mac
                dialog = xbmcgui.Dialog()
                ok = dialog.ok(utils.translation(32036), utils.translation(32037))
                import wakeIndex
                return wakeIndex.wakeIndex()
            else:
                xbmc.executebuiltin("WakeOnLan("+mac+")")
                macs = pickle.load(open(os.path.join(utils.USER_DATA, "macs.pickle"), "r"))
                macs.add(mac)
                pickle.dump(macs, open(os.path.join(utils.USER_DATA, "macs.pickle"), "w+")) 
Example 14
Project: sic   Author: Yanixos   File: locators.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, url, timeout=None, num_workers=10, **kwargs):
        """
        Initialise an instance.
        :param url: The root URL to use for scraping.
        :param timeout: The timeout, in seconds, to be applied to requests.
                        This defaults to ``None`` (no timeout specified).
        :param num_workers: The number of worker threads you want to do I/O,
                            This defaults to 10.
        :param kwargs: Passed to the superclass.
        """
        super(SimpleScrapingLocator, self).__init__(**kwargs)
        self.base_url = ensure_slash(url)
        self.timeout = timeout
        self._page_cache = {}
        self._seen = set()
        self._to_fetch = queue.Queue()
        self._bad_hosts = set()
        self.skip_externals = False
        self.num_workers = num_workers
        self._lock = threading.RLock()
        # See issue #45: we need to be resilient when the locator is used
        # in a thread, e.g. with concurrent.futures. We can't use self._lock
        # as it is for coordinating our internal threads - the ones created
        # in _prepare_threads.
        self._gplock = threading.RLock() 
Example 15
Project: sic   Author: Yanixos   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def get_encodings_from_content(content):
    """Returns encodings from given content string.

    :param content: bytestring to extract encodings from.
    """
    warnings.warn((
        'In requests 3.0, get_encodings_from_content will be removed. For '
        'more information, please see the discussion on issue #2266. (This'
        ' warning should only appear once.)'),
        DeprecationWarning)

    charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
    pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
    xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')

    return (charset_re.findall(content) +
            pragma_re.findall(content) +
            xml_re.findall(content)) 
Example 16
Project: sic   Author: Yanixos   File: warnings.py    GNU General Public License v3.0 6 votes vote down vote up
def filterwarnings(action, message="", category=Warning, module="", lineno=0,
                   append=False):
    """Insert an entry into the list of warnings filters (at the front).

    'action' -- one of "error", "ignore", "always", "default", "module",
                or "once"
    'message' -- a regex that the warning message must match
    'category' -- a class that the warning must be a subclass of
    'module' -- a regex that the module name must match
    'lineno' -- an integer line number, 0 matches all warnings
    'append' -- if true, append to the list of filters
    """
    import re
    assert action in ("error", "ignore", "always", "default", "module",
                      "once"), "invalid action: %r" % (action,)
    assert isinstance(message, str), "message must be a string"
    assert isinstance(category, type), "category must be a class"
    assert issubclass(category, Warning), "category must be a Warning subclass"
    assert isinstance(module, str), "module must be a string"
    assert isinstance(lineno, int) and lineno >= 0, \
           "lineno must be an int >= 0"
    _add_filter(action, re.compile(message, re.I), category,
            re.compile(module), lineno, append=append) 
Example 17
Project: bigquerylayers   Author: smandaric   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def get_encodings_from_content(content):
    """Returns encodings from given content string.

    :param content: bytestring to extract encodings from.
    """
    warnings.warn((
        'In requests 3.0, get_encodings_from_content will be removed. For '
        'more information, please see the discussion on issue #2266. (This'
        ' warning should only appear once.)'),
        DeprecationWarning)

    charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
    pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
    xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')

    return (charset_re.findall(content) +
            pragma_re.findall(content) +
            xml_re.findall(content)) 
Example 18
Project: AshsSDK   Author: thehappydinoa   File: locators.py    MIT License 6 votes vote down vote up
def __init__(self, url, timeout=None, num_workers=10, **kwargs):
        """
        Initialise an instance.
        :param url: The root URL to use for scraping.
        :param timeout: The timeout, in seconds, to be applied to requests.
                        This defaults to ``None`` (no timeout specified).
        :param num_workers: The number of worker threads you want to do I/O,
                            This defaults to 10.
        :param kwargs: Passed to the superclass.
        """
        super(SimpleScrapingLocator, self).__init__(**kwargs)
        self.base_url = ensure_slash(url)
        self.timeout = timeout
        self._page_cache = {}
        self._seen = set()
        self._to_fetch = queue.Queue()
        self._bad_hosts = set()
        self.skip_externals = False
        self.num_workers = num_workers
        self._lock = threading.RLock()
        # See issue #45: we need to be resilient when the locator is used
        # in a thread, e.g. with concurrent.futures. We can't use self._lock
        # as it is for coordinating our internal threads - the ones created
        # in _prepare_threads.
        self._gplock = threading.RLock() 
Example 19
Project: AshsSDK   Author: thehappydinoa   File: utils.py    MIT License 6 votes vote down vote up
def get_encodings_from_content(content):
    """Returns encodings from given content string.

    :param content: bytestring to extract encodings from.
    """
    warnings.warn((
        'In requests 3.0, get_encodings_from_content will be removed. For '
        'more information, please see the discussion on issue #2266. (This'
        ' warning should only appear once.)'),
        DeprecationWarning)

    charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
    pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
    xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')

    return (charset_re.findall(content) +
            pragma_re.findall(content) +
            xml_re.findall(content)) 
Example 20
Project: AshsSDK   Author: thehappydinoa   File: utils.py    MIT License 6 votes vote down vote up
def get_encodings_from_content(content):
    """Returns encodings from given content string.

    :param content: bytestring to extract encodings from.
    """
    warnings.warn((
        'In requests 3.0, get_encodings_from_content will be removed. For '
        'more information, please see the discussion on issue #2266. (This'
        ' warning should only appear once.)'),
        DeprecationWarning)

    charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
    pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
    xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')

    return (charset_re.findall(content) +
            pragma_re.findall(content) +
            xml_re.findall(content)) 
Example 21
Project: parsechain   Author: Suor   File: chains.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def html_to_text(html):
        """Cleans html preserving newlines"""
        if isinstance(html, lxml.html.HtmlElement):
            html = Ops.inner_html(html)

        html = re.sub(r'\s+', ' ', html).strip()
        html = re.sub(r'<br[^>]*>|</li>', '\n', html, flags=re.I)
        html = re.sub(r'</p>', '\n\n', html, flags=re.I)
        if not html or html.isspace():
            return ''
        return lxml.html.tostring(lxml.html.fromstring(html), encoding='unicode', method='text')

    # Text utils
    # TODO: make these two work with bytes? 
Example 22
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def iso2time(text):
    """
    As for http2time, but parses the ISO 8601 formats:

    1994-02-03 14:15:29 -0100    -- ISO 8601 format
    1994-02-03 14:15:29          -- zone is optional
    1994-02-03                   -- only date
    1994-02-03T14:15:29          -- Use T as separator
    19940203T141529Z             -- ISO 8601 compact format
    19940203                     -- only date

    """
    # clean up
    text = text.lstrip()

    # tz is time zone specifier string
    day, mon, yr, hr, min, sec, tz = [None]*7

    # loose regexp parse
    m = ISO_DATE_RE.search(text)
    if m is not None:
        # XXX there's an extra bit of the timezone I'm ignoring here: is
        #   this the right thing to do?
        yr, mon, day, hr, min, sec, tz, _ = m.groups()
    else:
        return None  # bad format

    return _str2time(day, mon, yr, hr, min, sec, tz)


# Header parsing
# ----------------------------------------------------------------------------- 
Example 23
Project: pyblish-win   Author: pyblish   File: warnings.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def filterwarnings(action, message="", category=Warning, module="", lineno=0,
                   append=0):
    """Insert an entry into the list of warnings filters (at the front).

    'action' -- one of "error", "ignore", "always", "default", "module",
                or "once"
    'message' -- a regex that the warning message must match
    'category' -- a class that the warning must be a subclass of
    'module' -- a regex that the module name must match
    'lineno' -- an integer line number, 0 matches all warnings
    'append' -- if true, append to the list of filters
    """
    import re
    assert action in ("error", "ignore", "always", "default", "module",
                      "once"), "invalid action: %r" % (action,)
    assert isinstance(message, basestring), "message must be a string"
    assert isinstance(category, (type, types.ClassType)), \
           "category must be a class"
    assert issubclass(category, Warning), "category must be a Warning subclass"
    assert isinstance(module, basestring), "module must be a string"
    assert isinstance(lineno, int) and lineno >= 0, \
           "lineno must be an int >= 0"
    item = (action, re.compile(message, re.I), category,
            re.compile(module), lineno)
    if append:
        filters.append(item)
    else:
        filters.insert(0, item) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bug_1661(self):
        # Verify that flags do not get silently ignored with compiled patterns
        pattern = re.compile('.')
        self.assertRaises(ValueError, re.match, pattern, 'A', re.I)
        self.assertRaises(ValueError, re.search, pattern, 'A', re.I)
        self.assertRaises(ValueError, re.findall, pattern, 'A', re.I)
        self.assertRaises(ValueError, re.compile, pattern, re.I) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_getlower(self):
        import _sre
        self.assertEqual(_sre.getlower(ord('A'), 0), ord('a'))
        self.assertEqual(_sre.getlower(ord('A'), re.LOCALE), ord('a'))
        if have_unicode:
            self.assertEqual(_sre.getlower(ord('A'), re.UNICODE), ord('a'))

        self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
        self.assertEqual(re.match("abc", u"ABC", re.I).group(0), "ABC") 
Example 26
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_flags(self):
        for flag in [re.I, re.M, re.X, re.S, re.L]:
            self.assertTrue(re.compile('^pattern$', flag)) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_inline_flags(self):
        # Bug #1700
        upper_char = unichr(0x1ea0) # Latin Capital Letter A with Dot Bellow
        lower_char = unichr(0x1ea1) # Latin Small Letter A with Dot Bellow

        p = re.compile(upper_char, re.I | re.U)
        q = p.match(lower_char)
        self.assertTrue(q)

        p = re.compile(lower_char, re.I | re.U)
        q = p.match(upper_char)
        self.assertTrue(q)

        p = re.compile('(?i)' + upper_char, re.U)
        q = p.match(lower_char)
        self.assertTrue(q)

        p = re.compile('(?i)' + lower_char, re.U)
        q = p.match(upper_char)
        self.assertTrue(q)

        p = re.compile('(?iu)' + upper_char)
        q = p.match(lower_char)
        self.assertTrue(q)

        p = re.compile('(?iu)' + lower_char)
        q = p.match(upper_char)
        self.assertTrue(q) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def check_en_US_iso88591(self):
        locale.setlocale(locale.LC_CTYPE, 'en_US.iso88591')
        self.assertTrue(re.match(b'\xc5\xe5', b'\xc5\xe5', re.L|re.I))
        self.assertTrue(re.match(b'\xc5', b'\xe5', re.L|re.I))
        self.assertTrue(re.match(b'\xe5', b'\xc5', re.L|re.I))
        self.assertTrue(re.match(b'(?Li)\xc5\xe5', b'\xc5\xe5'))
        self.assertTrue(re.match(b'(?Li)\xc5', b'\xe5'))
        self.assertTrue(re.match(b'(?Li)\xe5', b'\xc5')) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def check_en_US_utf8(self):
        locale.setlocale(locale.LC_CTYPE, 'en_US.utf8')
        self.assertTrue(re.match(b'\xc5\xe5', b'\xc5\xe5', re.L|re.I))
        self.assertIsNone(re.match(b'\xc5', b'\xe5', re.L|re.I))
        self.assertIsNone(re.match(b'\xe5', b'\xc5', re.L|re.I))
        self.assertTrue(re.match(b'(?Li)\xc5\xe5', b'\xc5\xe5'))
        self.assertIsNone(re.match(b'(?Li)\xc5', b'\xe5'))
        self.assertIsNone(re.match(b'(?Li)\xe5', b'\xc5')) 
Example 30
Project: drydock   Author: airshipit   File: hostname_validity.py    Apache License 2.0 5 votes vote down vote up
def run_validation(self, site_design, orchestrator=None):
        # Check FQDN length is <= 255 characters per RFC 1035

        node_list = site_design.baremetal_nodes or []
        invalid_nodes = [
            n for n in node_list if len(n.get_fqdn(site_design)) > 255
        ]

        for n in invalid_nodes:
            msg = "FQDN %s is invalid, greater than 255 characters." % n.get_fqdn(
                site_design)
            self.report_error(
                msg, [n.doc_ref],
                "RFC 1035 requires full DNS names to be < 256 characters.")

        # Check each label in the domain name is <= 63 characters per RFC 1035
        # and only contains A-Z,a-z,0-9,-

        valid_label = re.compile('[a-z0-9-]{1,63}', flags=re.I)

        for n in node_list:
            domain_labels = n.get_fqdn(site_design).split('.')
            for l in domain_labels:
                if not valid_label.fullmatch(l):
                    msg = "FQDN %s is invalid - label '%s' is invalid." % (
                        n.get_fqdn(site_design), l)
                    self.report_error(
                        msg, [n.doc_ref],
                        "RFC 1035 requires each label in a DNS name to be <= 63 characters and contain "
                        "only A-Z, a-z, 0-9, and hyphens.") 
Example 31
Project: drydock   Author: airshipit   File: middleware.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        # Setup validation pattern for external marker
        UUIDv4_pattern = '^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$'
        self.marker_re = re.compile(UUIDv4_pattern, re.I) 
Example 32
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: useragents.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.platforms = [(b, re.compile(a, re.I)) for a, b in self.platforms]
        self.browsers = [(b, re.compile(self._browser_version_re % a))
                         for a, b in self.browsers] 
Example 33
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: useragents.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.platforms = [(b, re.compile(a, re.I)) for a, b in self.platforms]
        self.browsers = [(b, re.compile(self._browser_version_re % a))
                         for a, b in self.browsers] 
Example 34
Project: fortran_input_reader   Author: miroi   File: docopt.py    MIT License 5 votes vote down vote up
def parse(class_, source):
        name = re.findall('(<\S*?>)', source)[0]
        value = re.findall('\[default: (.*)\]', source, flags=re.I)
        return class_(name, value[0] if value else None) 
Example 35
Project: fortran_input_reader   Author: miroi   File: docopt.py    MIT License 5 votes vote down vote up
def parse(class_, option_description):
        short, long, argcount, value = None, None, 0, False
        options, _, description = option_description.strip().partition('  ')
        options = options.replace(',', ' ').replace('=', ' ')
        for s in options.split():
            if s.startswith('--'):
                long = s
            elif s.startswith('-'):
                short = s
            else:
                argcount = 1
        if argcount:
            matched = re.findall('\[default: (.*)\]', description, flags=re.I)
            value = matched[0] if matched else None
        return class_(short, long, argcount, value) 
Example 36
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: locators.py    MIT License 5 votes vote down vote up
def _prepare_threads(self):
        """
        Threads are created only when get_project is called, and terminate
        before it returns. They are there primarily to parallelise I/O (i.e.
        fetching web pages).
        """
        self._threads = []
        for i in range(self.num_workers):
            t = threading.Thread(target=self._fetch)
            t.setDaemon(True)
            t.start()
            self._threads.append(t) 
Example 37
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 5 votes vote down vote up
def proxy_bypass_registry(host):
        if is_py3:
            import winreg
        else:
            import _winreg as winreg
        try:
            internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
            proxyEnable = winreg.QueryValueEx(internetSettings,
                                              'ProxyEnable')[0]
            proxyOverride = winreg.QueryValueEx(internetSettings,
                                                'ProxyOverride')[0]
        except OSError:
            return False
        if not proxyEnable or not proxyOverride:
            return False

        # make a check value list from the registry entry: replace the
        # '<local>' string by the localhost entry and the corresponding
        # canonical entry.
        proxyOverride = proxyOverride.split(';')
        # now check if we match one of the registry values.
        for test in proxyOverride:
            if test == '<local>':
                if '.' not in host:
                    return True
            test = test.replace(".", r"\.")     # mask dots
            test = test.replace("*", r".*")     # change glob sequence
            test = test.replace("?", r".")      # change glob char
            if re.match(test, host, re.I):
                return True
        return False 
Example 38
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 5 votes vote down vote up
def dotted_netmask(mask):
    """Converts mask from /xx format to xxx.xxx.xxx.xxx

    Example: if mask is 24 function returns 255.255.255.0

    :rtype: str
    """
    bits = 0xffffffff ^ (1 << 32 - mask) - 1
    return socket.inet_ntoa(struct.pack('>I', bits)) 
Example 39
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: misc.py    MIT License 5 votes vote down vote up
def is_svn_page(html):
    """
    Returns true if the page appears to be the index page of an svn repository
    """
    return (re.search(r'<title>[^<]*Revision \d+:', html) and
            re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I)) 
Example 40
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: enos_facts.py    MIT License 5 votes vote down vote up
def parse_version(self, data):
        match = re.search(r'^Software Version (.*?) ', data, re.M | re.I)
        if match:
            return match.group(1) 
Example 41
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: enos_facts.py    MIT License 5 votes vote down vote up
def parse_hostname(self, data_run):
        for line in data_run.split('\n'):
            line = line.strip()
            match = re.match(r'hostname (.*?)', line, re.M | re.I)
            if match:
                hosts = line.split()
                hostname = hosts[1].strip('\"')
                return hostname
        return "NA" 
Example 42
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: enos_facts.py    MIT License 5 votes vote down vote up
def parse_model(self, data):
        match = re.search(r'^Lenovo RackSwitch (\S+)', data, re.M | re.I)
        if match:
            return match.group(1) 
Example 43
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: enos_facts.py    MIT License 5 votes vote down vote up
def parse_serialnum(self, data):
        match = re.search(r'^Switch Serial No:  (\S+)', data, re.M | re.I)
        if match:
            return match.group(1) 
Example 44
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: enos_facts.py    MIT License 5 votes vote down vote up
def parse_memtotal(self, data):
        match = re.search(r'^MemTotal:\s*(.*) kB', data, re.M | re.I)
        if match:
            return int(match.group(1)) / 1024 
Example 45
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: enos_facts.py    MIT License 5 votes vote down vote up
def parse_memfree(self, data):
        match = re.search(r'^MemFree:\s*(.*) kB', data, re.M | re.I)
        if match:
            return int(match.group(1)) / 1024 
Example 46
Project: flasky   Author: RoseOu   File: base.py    MIT License 5 votes vote down vote up
def _re_compile(regex):
    """Compile a string to regex, I and UNICODE."""

    return re.compile(regex, re.I | re.UNICODE) 
Example 47
Project: flasky   Author: RoseOu   File: web.py    MIT License 5 votes vote down vote up
def analyse_text(text):
        rv = 0.0
        if 'bin/lasso9' in text:
            rv += 0.8
        if re.search(r'<\?(=|lasso)', text, re.I):
            rv += 0.4
        if re.search(r'local\(', text, re.I):
            rv += 0.4
        if re.search(r'\[\n|\?>', text):
            rv += 0.4
        return rv 
Example 48
Project: flasky   Author: RoseOu   File: templates.py    MIT License 5 votes vote down vote up
def analyse_text(text):
        rv = LassoLexer.analyse_text(text)
        if re.search(r'<\w+>', text, re.I):
            rv += 0.2
        if html_doctype_matches(text):
            rv += 0.5
        return rv 
Example 49
Project: flasky   Author: RoseOu   File: dotnet.py    MIT License 5 votes vote down vote up
def analyse_text(text):
        if re.search(r'Page\s*Language="C#"', text, re.I) is not None:
            return 0.2
        elif re.search(r'script[^>]+language=["\']C#', text, re.I) is not None:
            return 0.15 
Example 50
Project: flasky   Author: RoseOu   File: dotnet.py    MIT License 5 votes vote down vote up
def analyse_text(text):
        if re.search(r'Page\s*Language="Vb"', text, re.I) is not None:
            return 0.2
        elif re.search(r'script[^>]+language=["\']vb', text, re.I) is not None:
            return 0.15


# Very close to functional.OcamlLexer