Example #1
0
    def run(self, server=SERVER):
        """ Connects to Homeassistant, listen for changes and update led """
        led = Led()
        rainbow = Rainbow()

        c = MQTTClient(CLIENT_ID, server)
        c.set_callback(self.sub_callback)
        c.connect()
        c.subscribe(TOPIC)
        print("Connected to %s, subscribed to %s topic" % (server, TOPIC))

        try:
            while True:
                c.check_msg()
                if self.updated == True:
                    led.update_colors(self.red, self.green, self.blue)
                    self.updated = False

                if ure.match('OFF', self.ledstate): 
                    led.turn_off()
                elif ure.match('rainbow', self.effect):
                    rainbow.show(60)
                elif ure.match('rainbow_slow', self.effect):
                    rainbow.show(100)
                elif ure.match('rainbow_fast', self.effect):
                    rainbow.show(30)
                else:
                    led.change_nyance()
                    time.sleep_ms(10)

        finally:
            c.disconnect()
Example #2
0
def process_json(file):
    obss = []

    data = file.read(500).decode('utf-8')
    m = None

    week = []
    daily = []
    currently = []

    r = {}

    m = ure.match('^{(.*?),"daily":{(.+?),"data":\[(.*?$)', data)
    if m:
        wdata = [ujson.loads('{' + m.group(2) + '}')]
        week = process_data(wdata)
        rest = m.group(3)
        data = rest + file.read(1000).decode('utf-8')
        m = ure.match('^({.+?})', data)
        wdata = [ujson.loads(m.group(1))]
        daily = process_data(wdata)
        return {'week': week, 'daily': daily, 'currently': None}

    m = ure.match('^{(.*?),"currently":{(.+?)}', data)
    if m:
        wdata = [ujson.loads('{' + m.group(2) + '}')]
        currently = process_data(wdata)
        return {'currently': currently, 'week': None, 'daily': None}

    return None
Example #3
0
    async def _handle_request(self, reader, writer, remote_addr):
        line0 = None

        while True:
            line = (await reader.readline())

            # read until we reach the end of the headers
            # (or the end of data)
            if not line or line == b'\r\n':
                break

            if line0 is None:
                line0 = line.decode().strip().split(' ')

        try:
            verb, uri = line0[:2]
        except (TypeError, ValueError):
            print('! invalid request from', remote_addr)
            return

        print('* %s %s %s' % (remote_addr, verb, uri))

        for route in self.routes:
            match = re.match(route[0], uri)

            if match and route[1] == verb:
                handler = route[2]
                await handler(reader, writer, match)
                break
        else:
            await self.send_response(writer,
                                     status=404,
                                     status_text='Not found')
Example #4
0
    def resolve(self, request):
        """
        Return a tuple of (route, methods, callback, arguments) matching the given request.
        """
        endpoints = sorted(
            item for item in self.endpoints.items(),
            key=lambda l: len(l[0][0]),
            reverse=True)

        for endpoint, callback in endpoints:
            route, methods = endpoint
            if request.method in methods:
                pattern = '/'.join(c.replace(':%s'%c[1:], '[^/].*') for c in route.split('/'))
                pattern = '^%s$' % pattern
                log.debug('Matching %s %s against %s %s (regex: %s)' % (request.method, request.path, methods, route, pattern))
                if ure.match(pattern, request.path):
                    log.debug('Matched %s %s with %s %s', request.method, request.path, methods, route)
                    arguments = {}
                    for i, component in enumerate(route.split('/')):
                        if component.startswith(':'):
                            value = request.path.split('/')[i]
                            if len(value):
                                argument = component.lstrip(':')
                                arguments[argument] = value
                    return route, methods, callback, arguments
        raise HTTPException('No route found for request %s' % request, status=404)
Example #5
0
def problem_file_line(exc):
    # return a string of just the filename.py and line number where
    # an exception occured. Best used on AssertionError.
    import uio, sys, ure

    tmp = uio.StringIO()
    sys.print_exception(exc, tmp)
    lines = tmp.getvalue().split('\n')[-3:]
    del tmp

    # convert:
    #   File "main.py", line 63, in interact
    #    into just:
    #   main.py:63
    #
    # on simulator, huge path is included, remove that too

    rv = None
    for ln in lines:
        mat = ure.match(r'.*"(/.*/|)(.*)", line (.*), ', ln)
        if mat:
            try:
                rv = mat.group(2) + ':' + mat.group(3)
            except:
                pass

    return rv or str(exc) or 'Exception'
Example #6
0
def zz(xx, str):
    print(str)
    nn = ure.match("(%s)(\d+)+" % xx, str)
    if nn:
        return nn.group(2)
    else:
        return 0
Example #7
0
    def get_player_id(self, player_name):
        """
        Retrieve the player's ID as defined by LMS. Most likely this is the
        player's MAC address.
        """
        player_count = 0
        player_id = None

        # Retrieve player count.
        player_count = int(self.sb_query('player count'))

        # Retrieve the complete players information.
        players = ure.compile(r' playerindex%3A[0-9]+ ').split(
            self.sb_command(self.sock_queries, 'players 0 {}', player_count))

        # The first item will be the command we just sent.
        players.pop(0)

        # Prepare lookup expression.
        player_name_regex = ure.compile('name%s%s ' %
                                        (r'%3A', urlencode.quote(player_name)))

        for player in players:
            if player_name_regex.search(player):
                player_id = urlencode.unquote(
                    ure.match(r'playerid%3A([^ ]+) ', player).group(1))
                break

        return player_id
Example #8
0
def get(conn, path):
    match = ure.match(r'^/edit/(.+)', path)
    if match:
        room_name = match.group(1)
        room = Room.load(room_name)
        if room:
            response = room_form(room_name, room)
        else:
            response = room_form(room_name)
        conn.send('HTTP/1.1 200 OK\n')
        conn.send('Content-Type: text/html\n')
    else:
        room_name = name(path)
        room = Room.load(room_name)
        if room:
            response = room_page(room)
            conn.send('HTTP/1.1 200 OK\n')
            conn.send('Content-Type: text/html\n')
        else:
            response = ''
            conn.send('HTTP/1.1 302 Redirect\n')
            conn.send('Location: /edit/' + room_name + '\n')

    try:
        conn.send('Connection: close\n\n')
        conn.sendall(response)
    except OSError:
        print("ERR: Timeout")
    finally:
        conn.close()
 def setValue(self, key, value):
     utils.printDebug('ANIMATOR', 'SET %s=%s' % (key, value))
     try:
         value = int(value)
     except:
         pass
     if key == 'SPEED' and value in range(1, _MAX_SPEED + 1):
         self.config['speed'] = value
     elif key == 'ANIMATION' and value in range(-1, len(self.animations)):
         self.config['animation'] = value
         if value == -1:
             self.config['current_animation'] = uos.urandom(1)[0] % len(
                 self.animations)
         else:
             self.config['current_animation'] = value
     elif key == 'LEDS' and 2 <= value and value <= _MAX_LEDS and self.config[
             'leds'] != value:
         tmp = self.config['leds']
         self.config['leds'] = value
         self.forceRefreshLeds = tmp
     elif key == 'SECONDS_PER_ANIMATION' and value > 0:
         self.config['seconds_per_animation'] = value
     elif key == 'POWERED_ON' and (value == 0 or value == 1):
         self.config['powered_on'] = value
         self.forceRefreshColor = True
         self.powerOffIfNeeded()
     elif key == 'USE_COLOR' and (value == 0 or value == 1):
         self.config['use_color'] = value
         self.forceRefreshColor = True
     elif key == 'COLOR' and ure.match(
             "^[0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F]$", value):
         self.config['color'] = value
         self.forceRefreshColor = True
Example #10
0
 def is_match(self, path):
     """
     Accept current path from HTTP request and looking for match with current route.
     :param path: Incoming path from HTTP request.
     :return: Boolean of match
     """
     log.debug("Looking for route match.\n Path: {p}\n Regex: {r}".format(
         p=path, r=self.regex_str))
     return ure.match(self.regex, path) is not None
 def unpack_status_line(status_line):
     res = ure.match(r'^(GET|POST|PUT|DELETE|OPTION)\s(.+)\s(.*)', status_line)
     method = res.group(1)
     url = res.group(2)
     try:
       version = res.group(3)
     except:
       version = None
     return method, url, version
Example #12
0
File: uIoD.py Project: ponyatov/IoD
 def token(self):
     if not self.src: return None
     token = ''
     def sym(): self.src = self.src[1:]
     while self.src[0] in ' \t\r\n':
         sym()
     while self.src and self.src[0] not in ' \t\r\n':
         token += self.src[0] ; sym()
     if re.match(r'[+\-]?[0-9]+',token): return Int(token)
     return Sym(token)
Example #13
0
 def get_mac(self):
     cmd = "AT+CIFSR"
     ack = self._cmd(cmd, ["OK"], ["ERROR"], timeout=2)
     print(ack)
     # 'AT+CIFSR\r\n+CIFSR:STAIP,"0.0.0.0"\r\n+CIFSR:STAMAC,"18:fe:34:de:a6:00"\r\n\r\nOK\r\n'
     mat = ure.match('.*CIFSR:STAMAC\,"(.*)"\r\n.*', ack)
     if mat:
         mac = mat.group(1)
         return mac
     return ""
Example #14
0
 def getdata(self):
     while self.port.any() > 0:
         try:
             dataline = self.port.readline()
             out = dataline.decode('UTF8')
             split = ure.match("^(\w*)(\s*)(\w*)", out)
             #self.data[split.group(1)] = split.group(3)
         except Exception as e:
             pass
         return self.data
Example #15
0
 def next_token(self):
     "Return the next token, reading new text into line buffer if needed."
     while True:
         if self.line == '': self.line = self._file.readline()
         if self.line == '': return eof_object
         self.line = self.line.strip()
         m = ure.match(InPort.tokenizer, self.line)
         token = m.group(1)
         self.line = m.group(2)
         if token != '' and not token.startswith(';'):
             return token
Example #16
0
def webserver_serve(s):
    """Process one query to the webserver"""
    cl, addr = s.accept()
    cl.setblocking(True)
    print('client connected from', addr)
    respond_in_badge_format = False
    cl_file = cl.makefile('rwb', 0)
    while True:
        line = cl_file.readline()
        if not line or line == b'\r\n':
            break

        # Scan the header for a GET command
        match = ure.match('GET (.+) ', line)
        if match:
            query = match.group(1).decode('ascii')
            if query == '/BadgeLife':
                respond_in_badge_format = True
                print("Responding to a badge query!")
            else:
                try:
                    if os.stat(web_root + '/' + query):
                        print('Responding with a file!')
                except OSError:
                    query = None
                    print('No match, give the default response.')

    if respond_in_badge_format:
        # Header with interface version number and badge ID in hex
        response = 'Badge 0.1 %s\r\n' % hex_id

        # A line with each filename
        for fn in dir_walk():
            response += '%s\r\n' % fn

        # Terminate list with a slash
        response += '/\r\n'

    elif query:
        try:
            response = open(web_root + '/' + query, 'rb').read()
        except Exception:
            response = "Error reading file!\r\n"

    else:  # Send the default response
        rows = [
            '<tr><td><a href="/%s">%s</a></td>'
            '<td align="right">%d</td></tr>' %
            (fn, fn, os.stat(web_root + '/' + fn)[6]) for fn in dir_walk()
        ]
        response = html % '\n'.join(rows)

    cl.sendall(response)  # blocks until it sends all of the response
    cl.close()
Example #17
0
    def parse(url):

        regex = r"(?:https?://)?(?:www\.)?([^:/]*)((?::\d+)?)(\/?.*)"

        if re.match(regex, url):
            m = re.search(regex, url)
            port = m.group(2) or ':80'
            addr = socket.getaddrinfo(m.group(1), int(port[1:]))[0][-1]
            return (None, m.group(3) or '/', addr[0], addr[1])

        else:
            return ('Invalid URL String', None, None)
Example #18
0
    def find_header_matching(self, search_string, index=0):
        if isinstance(search_string, str):
            search_string = bytes(search_string, 'utf-8')

        while index < len(self.headers):
            # print("find_item_containing: '%s' in '%s'" % (search_string, string_list[index]))
            if re.match(search_string, self.headers[index]):
                return index
            else:
                index = index + 1

        # No match found
        return None
Example #19
0
 def _build_inbox(self):
     #ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
     #inbox_id = ''.join(self._random_choice(ascii_lowercase) for i in range(13))
     inbox_id = 'AAA666'
     while True:
         inbox_id = ure.match(r'\(?([a-zA-Z0-9]+)',
                              ubinascii.b2a_base64(uos.urandom(16)).strip())
         if inbox_id is not None:
             inbox_id = inbox_id.group(1).upper()[2:8]
             if inbox_id and len(inbox_id) == 6:
                 break
     if self._debug:
         print('Inbox ID : _INBOX.{}'.format(inbox_id))
     return "_INBOX.%s" % inbox_id
Example #20
0
def read_from_file_list():
  while(True):
    target_list=uos.listdir()
    
    for target in target_list:
      if (ure.match('.*bmp$', target)):
        try:
          send_image(target)
    
        except:
          send_image(IMAGE_ERROR)
          raise

        utime.sleep(DEFAULT_SLEEP)
Example #21
0
def cleanup_deriv_path(bin_path, allow_star=False):
    # Clean-up path notation as string.
    # - raise exceptions on junk
    # - standardize on 'prime' notation (34' not 34p, or 34h)
    # - assume 'm' prefix, so '34' becomes 'm/34', etc
    # - do not assume /// is m/0/0/0
    # - if allow_star, then final position can be * or *' (wildcard)
    import ure
    from public_constants import MAX_PATH_DEPTH
    try:
        s = str(bin_path, 'ascii').lower()
    except UnicodeError:
        raise AssertionError('must be ascii')

    # empty string is valid
    if s == '': return 'm'

    s = s.replace('p', "'").replace('h', "'")
    mat = ure.match(
        r"(m|m/|)[0-9/']*" + ('' if not allow_star else r"(\*'|\*|)"), s)
    assert mat.group(0) == s, "invalid characters"

    parts = s.split('/')

    # the m/ prefix is optional
    if parts and parts[0] == 'm':
        parts = parts[1:]

    if not parts:
        # rather than: m/
        return 'm'

    assert len(parts) <= MAX_PATH_DEPTH, "too deep"

    for p in parts:
        assert p != '' and p != "'", "empty path component"
        if allow_star and '*' in p:
            # - star or star' can be last only (checked by regex above)
            assert p == '*' or p == "*'", "bad wildcard"
            continue
        if p[-1] == "'":
            p = p[0:-1]
        try:
            ip = int(p, 10)
        except:
            ip = -1
        assert 0 <= ip < 0x80000000 and p == str(ip), "bad component: " + p

    return 'm/' + '/'.join(parts)
Example #22
0
 def get_ip(self):
     cmd = "AT+CIFSR"
     try:
         ack = self._cmd(cmd, ["OK"], ["ERROR"], timeout=2)
     except Exception as e:
         print("--[ERROR] AT ack erro:", e)
         return ""
     # 'AT+CIFSR\r\n+CIFSR:STAIP,"0.0.0.0"\r\n+CIFSR:STAMAC,"18:fe:34:de:a6:00"\r\n\r\nOK\r\n'
     mat = ure.match('.*CIFSR:STAIP\,"(.*)".*CIFSR.*', ack)
     if mat:
         ip = mat.group(1)
         if "0.0.0.0" in ip:
             return ""
         return ip
     return ""
Example #23
0
    def sb_parse_result(self, regex, string, group=1):
        """
        Parses an LMS command result by using a regex.
        """
        try:
            if isinstance(regex, str):
                result = ure.match(regex, string).group(group).strip()
            else:
                result = regex.match(string).group(group).strip()
        except AttributeError as err:
            print('Invalid result: ', err)
            print('String {}, regex {}'.format(string, regex))
            result = None

        return result
Example #24
0
    def find_body_matching(self, search_string, index=0):
        if isinstance(search_string, str):
            search_string = bytes(search_string, 'utf-8')

        eol = 0
        while eol >= 0:
            # print("find_body_matching: %s at %d" % (search_string, index))
            line, eol = self.body_line_at(index)

            if re.match(search_string, line):
                return index
            elif eol >= 0:
                index = eol + 2

        # No match found
        return None
Example #25
0
 def __post(self):
     try:
         s = socket.socket()
         s.connect(self.addr)
         h = "POST %s HTTP/1.1\r\nHost: %s:%s\r\n" % (
             self.uri, self.host, self.port) + self.header
         s.send(
             bytes(
                 h + '\r\nContent-Length:%s\r\n\r\n' % len(self.payload) +
                 self.payload + '\r\n', 'utf8'))
         while True:
             r = s.recv(768).decode('utf-8')
             s.close()
             self.resp = r.split('\n')[-1]
             return ure.match(r'HTTP\/1\.1\s(\d+)\s', r).group(1)
     except OSError as e:
         s.close()
         raise ConnectionFailed
Example #26
0
 def run(self):
     if len(self.data_changed_keys) > 0:
         data = {}
         for key in self.data_changed_keys:
             if type(key) == list:
                 data0 = {}
                 for key0 in key:
                     data0[key0] = self.data[key0]
                 if data0:
                     print("--report:", data0)
                     self.report_(data0)
                     print("--report success")
             else:
                 data[key] = self.data[key]
         if data:
             print("--report:", data)
             self.report_(data)
             print("--report success")
         self.data_changed_keys = []
     msg = self.uart.read()
     if msg:
         self.msg += msg
         idx = self.msg.find(b"+TCMQTTRCVPUB:")
         if idx >= 0:
             self.msg = self.msg[idx:]
             print("--msg:", self.msg)
             idx = self.msg.find(b'}"\r\n') + 2
             if idx >= 0:
                 pub_msg = self.msg
                 try:
                     mat = ure.match('.*"{(.*)}".*', pub_msg.decode())
                     if mat:
                         pub_msg = '{' + mat.group(1) + '}'
                         pub_msg = json.loads(pub_msg)
                 except Exception as e:
                     print(e)
                     print("--[error] pub msg decode error:{}".format(
                         pub_msg))
                     pub_msg = None
                 if pub_msg:
                     self.on_msg(pub_msg)
                 self.msg = self.msg[idx +
                                     2:]  # remove "+TCMQTTRCVPUB:...\r\n"
Example #27
0
def http_get(url):
    _, _, host, path = url.split('/', 3)
    print(path)
    addr = socket.getaddrinfo(host, 80)[0][-1]
    s = socket.socket()
    s.connect(addr)
    s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
    while Thread[0]:
        data = s.recv(100)
        if data:
            # print(str(data, 'utf8'), end='')
            result = str(data)
            print(result)
            result = ure.match('<em>(.*)</em>', result)
            if result != None:
                print(result.group())
        else:
            break
    s.close()
Example #28
0
def cleanup_deriv_path(bin_path):
    # Clean-up path notation as string.
    # - raise exceptions on junk
    # - standardize on 'prime' notation (34' not 34p, or 34h)
    # - assume 'm' prefix, so '34' becomes 'm/34', etc
    # - do not assume /// is m/0/0/0
    import ure
    from public_constants import MAX_PATH_DEPTH
    try:
        s = str(bin_path, 'ascii').lower()
    except UnicodeError:
        raise AssertionError('must be ascii')

    # empty string is valid
    if s == '': return 'm'

    s = s.replace('p', "'").replace('h', "'")
    mat = ure.match(r"(m|m/|)[0-9/']*", s)
    assert mat.group(0) == s, "invalid characters"

    parts = s.split('/')

    # the m/ prefix is optional
    if parts and parts[0] == 'm':
        parts = parts[1:]

    if not parts:
        # rather than: m/
        return 'm'

    assert len(parts) <= MAX_PATH_DEPTH, "too deep"

    for p in parts:
        assert p != '' and p != "'", "empty path component"
        if p[-1] == "'":
            p = p[0:-1]
        try:
            ip = int(p, 10)
        except:
            ip = -1
        assert 0 <= ip < 0x80000000 and p == str(ip), "bad component: " + p

    return 'm/' + '/'.join(parts)
Example #29
0
 def parse(cls, s):
     fingerprint = None
     parent_derivation = None
     address_derivation = "_"
     m = re.match("\[(.*)\](.*)", s)
     if m:
         parent_derivation = m.group(1)
         if not parent_derivation.startswith("m/"):
             arr = parent_derivation.split("/")
             fingerprint = unhexlify(arr[0])
             if len(fingerprint) != 4:
                 raise ValueError("Invalid fingerprint in derivation path")
             parent_derivation = "m/" + "/".join(arr[1:])
         parent_derivation = bip32.parse_path(parent_derivation)
         s = m.group(2)
     if "/" in s:
         arr = s.split("/")
         address_derivation = "/".join(arr[1:])
         s = arr[0]
     key = bip32.HDKey.from_base58(s)
     return cls(key, fingerprint, parent_derivation, address_derivation)
Example #30
0
def cmd_add(args):
    for fname in args.file:
        if os.path.isdir(fname):
            print("Warning: '%s' is a directory, skipping" % fname)
            continue
        try:
            hsh = hash_file(fname)
        except Exception as e:
            print("Error: unable to hash '%s', skipping: %s" % (fname, e))
            continue

        meta_fname = replace_ext(fname, ".yaml")
        if fname == meta_fname:
            print("Warning: skipping '%s'" % fname)

        d = {}
        if os.path.exists(meta_fname):
            with open(meta_fname) as f:
                d = yaml.safe_load(f)
            backup_file(meta_fname)

        d["name"] = fname
        d["md5"] = hsh
        # If fname starts with date
        m = ure.match(r"[0-9]+", fname)
        if m and len(m.group(0)) in (4, 6, 8):
            s = m.group(0)
            date = s[:4]
            s = s[4:]
            if s:
                date += "-" + s[:2]
                s = s[2:]
            if s:
                date += "-" + s[:2]
                s = s[2:]
            d["pubdate"] = date

        with open(meta_fname, "w") as metaf:
            yaml.dump(d, metaf, sort=True)
Example #31
0
def b64decode(s, altchars=None, validate=False):
    """Decode a Base64 encoded byte string.

    s is the byte string to decode.  Optional altchars must be a
    string of length 2 which specifies the alternative alphabet used
    instead of the '+' and '/' characters.

    The decoded string is returned.  A binascii.Error is raised if s is
    incorrectly padded.

    If validate is False (the default), non-base64-alphabet characters are
    discarded prior to the padding check.  If validate is True,
    non-base64-alphabet characters in the input result in a binascii.Error.
    """
    s = _bytes_from_decode_data(s)
    if altchars is not None:
        altchars = _bytes_from_decode_data(altchars)
        assert len(altchars) == 2, repr(altchars)
        s = s.translate(bytes.maketrans(altchars, b'+/'))
    if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
        raise binascii.Error('Non-base64 digit found')
    return binascii.a2b_base64(s)
Example #32
0
import ure

opmap = {}
opname = [None] * 256
op_implicit_arg = [None] * 256


with open("../../micropython/py/bc0.h") as f:
    for l in f:
        m = ure.match(r"#define +MP_BC_([A-Z_]+) +\((.+?)\)", l)
        if not m:
            continue
#        print(m.group(1), m.group(2))
        name, val = m.group(1), m.group(2)
        val = int(val)
#        print(name, val)
        opmap[name] = val
        opname[val] = name

UNARY_OP_MULTI = opmap["UNARY_OP_MULTI"]
BINARY_OP_MULTI = opmap["BINARY_OP_MULTI"]
with open("../../micropython/py/runtime0.h") as f:
    want_unary = True
    want_binary = True
    cnt = 0

    for l in f:
        if want_unary:
            m = ure.match(r" +MP_UNARY_OP_([A-Z_]+)", l)
            if m:
                op = m.group(1)
Example #33
0
m = r.match("d")
print(m.group(0))
m = r.match("A")
print(m.group(0))


r = re.compile("o+")
m = r.search("foobar")
print(m.group(0))
try:
    m.group(1)
except IndexError:
    print("IndexError")


m = re.match(".*", "foo")
print(m.group(0))

m = re.search("w.r", "hello world")
print(m.group(0))

m = re.match('a+?', 'ab');  print(m.group(0))
m = re.match('a*?', 'ab');  print(m.group(0))
m = re.match('^ab$', 'ab'); print(m.group(0))
m = re.match('a|b', 'b');   print(m.group(0))
m = re.match('a|b|c', 'c'); print(m.group(0))

# Case where anchors fail to match
r = re.compile("^b|b$")
m = r.search("abc")
print(m)
Example #34
0
# test match.groups()

try:
    import ure as re
except ImportError:
    try:
        import re
    except ImportError:
        print("SKIP")
        raise SystemExit

try:
    m = re.match(".", "a")
    m.groups
except AttributeError:
    print('SKIP')
    raise SystemExit


m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567')
print(m.groups())

m = re.match(r'([0-9]*)(([a-z]*)([0-9]*))','1234hello567')
print(m.groups())

# optional group that matches
print(re.match(r'(a)?b(c)', 'abc').groups())

# optional group that doesn't match
print(re.match(r'(a)?b(c)', 'bc').groups())
Example #35
0
print(m)
print("===")

r = re.compile("[^a-cu-z]")
m = r.match("a")
print(m)
m = r.match("z")
print(m)
m = r.match("d")
print(m.group(0))
m = r.match("A")
print(m.group(0))
print("===")

# '-' character within character class block
print(re.match("[-a]+", "-a]d").group(0))
print(re.match("[a-]+", "-a]d").group(0))
print("===")

r = re.compile("o+")
m = r.search("foobar")
print(m.group(0))
try:
    m.group(1)
except IndexError:
    print("IndexError")


m = re.match(".*", "foo")
print(m.group(0))
Example #36
0
allPWM(0)

directory = 'sequences'
sequence_cache = []
loop_read = 0

sequences = [elem for elem in os.listdir(directory) if elem[0] != '.']
sequences.sort()



for sequence in sequences:
	with open("%s/%s" % (directory,sequence)) as datatxtLine:
		for lineNumber,line in enumerate(datatxtLine):
			if ure.match('#|\n|^ *$',line) == None: 
				# Counter, this is used to select the loop, 1 when it is the first line, 2 when it is end of loop.
				if loop_read <= 1: 

					# Compile and identify the line
					# Group 1 variable detect
					# Group 2 variable name
					# Group 3 variable value
					# Group 4 sequence step (0 0 0 0 0 0 0 0)
					# Group 5 Plain text (sequence title)

					lineRead = ure.match(' *((loop|delay) *= *(\d*.\d*))?([ \.0-9]*)([ a-zA-Z0-9]*)',line)

					# If plain text this is treated as a title, the space inbetween 2 titles is treated as a sequence.
					if lineRead.group(5):
						
Example #37
0
    import ure as re
except ImportError:
    try:
        import re
    except ImportError:
        import sys
        print("SKIP")
        sys.exit()

def print_groups(match):
    print('----')
    try:
        i = 0
        while True:
            print(match.group(i))
            i += 1
    except IndexError:
        pass

m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567')
print_groups(m)

m = re.match(r'([0-9]*)(([a-z]*)([0-9]*))','1234hello567')
print_groups(m)

# optional group that matches
print_groups(re.match(r'(a)?b(c)', 'abc'))

# optional group that doesn't match
print_groups(re.match(r'(a)?b(c)', 'bc'))
Example #38
0
print(m.group(0))
try:
    m.group(1)
except IndexError:
    print("IndexError")

r = re.compile("(.+)1")
m = r.match("xyz781")
print(m.group(0))
print(m.group(1))
try:
    m.group(2)
except IndexError:
    print("IndexError")


r = re.compile("o+")
m = r.search("foobar")
print(m.group(0))
try:
    m.group(1)
except IndexError:
    print("IndexError")


m = re.match(".*", "foo")
print(m.group(0))

m = re.search("w.r", "hello world")
print(m.group(0))
Example #39
0
def do_server():
  global sock,current_nick
  collect()
  line = sock.readline()
  if len(line) < 3: print("Unexpected short line length (%d characters)" % len(line))
  if not (line[-2]==13 and line[-1]==10): # Assume all IRC messages should end in \r\n 
    print("Invalid message from server; ignoring message"); return
  if raw_server_messages and len(line)>1: print("Server sent: [%s]" % line)
  if line.find(b"PING :") == 0:
    _ = sock.send(b"PONG :%s" % line[6:])
    if raw_client_messages: print("Client sent: [%s]" % (b"PONG :%s" % line[6:]))
  elif line.find(b":Nickname is already in use") != -1:
      print("Nickname '%s' is already in use" % nick)
      if len(suffixes) > 0:
        print("Trying an alternative nick suffix")
        if   current_nick == nick             : current_nick = nick+suffixes[0]
        elif current_nick == nick+suffixes[-1]: current_nick = nick
        else:
          current_suffix = current_nick[len(nick):]
          found = False
          for suffix in suffixes:
            if found == True: break
            if suffix == current_suffix: found = True
          current_nick = nick+suffix
        print("New nickname is '%s'" % current_nick)
        join_with_nick_to_channels(current_nick, channels)
  elif line.find(b" PRIVMSG ") != -1:
    u=ure.match(user_match+"PRIVMSG\s(\S+)\s:(.+)\r\n",line)
    user,name,location,channel,message = u.group(1),u.group(2),u.group(3),u.group(4),u.group(5)
    print("User [%s] (%s) at [%s] on channel %s said [%s]" %\
          (user,name,location,channel,message))
    if channel == nick: channel = user # return message goes back to user (not bot or channel)
#    if message.find(1) != -1: # FIXME Add code for emote extensions etc like /me (escape char)
    if message[0] == actions_char or message[:len(current_nick)+1]==current_nick+":":
      command = message[1:] if message[0]==actions_char else message[len(current_nick)+1:]
      # FIXME Add check for zero size actions?
      command = command.strip() # Remove leading spaces in command
      usenotice = actions_usenotice if channel != user else False
      if len(command)==0 or command == "help": # assumed not in actions dict so check first
        send_msg_to_channel(channel, action_help, usenotice)
      elif command not in actions.keys():
        send_msg_to_channel(channel, "No command '%s'; %s" % (command,action_help), usenotice)
      else:
        if isinstance(actions[command],str): send_msg_to_channel(channel,actions[command],usenotice)
        else: send_msg_to_channel(channel,actions[command](user),usenotice)
    elif len(responses) >0 and user != current_nick: # have some responses and message not from bot
      print("Checking responses")
      for k,v in responses.items():
        print("Checking for [%s] in [%s]" % (k,message))
        u=ure.match(k,message)
        if u != None: # Found a match
          send_msg_to_channel(channel,v(user),False)
  elif line.find(b" JOIN ") != -1:
    u=ure.match(user_match+"JOIN (\S+)",line)
    user,name,location,channel=u.group(1),u.group(2),u.group(3),u.group(4)
    print("%s (%s) joined channel %s" % (user,name,channel))
  elif line.find(b" QUIT ") != -1:
    u=ure.match(user_match+"QUIT (\S+)",line)
    user,name,location,reason=u.group(1),u.group(2),u.group(3),u.group(4)
    print("%s (%s) quit due to %s" % (user,name,reason))
  elif line.find(b" PART ") != -1:
    u=ure.match(user_match+"PART\s(\S+)\s(\S+)",line)
    user,name,location,channel,reason=u.group(1),u.group(2),u.group(3),u.group(4),u.group(5)
    print("%s (%s) left %s due to %s" %(user,name,channel,reason))
  elif line.find(b" NICK ") != -1:
    u=ure.match(user_match+"NICK\s:(\S+)",line)
    user,name,location,newuser=u.group(1),u.group(2),u.group(3),u.group(4)
    print("%s changed nick from '%s' to '%s'" % (name,user,newuser))
  elif line.find(b" KICK ") != -1:
    print("KICK") # XXX MORE info?
  elif line.find(b" ERROR ") != -1:
    print("ERROR") # XXX MORE info?
  elif line.find(b" NOTICE ") != -1:
    u=ure.match(":(\S+)\sNOTICE\s(.+)\r\n",line)
    server,message = u.group(1),u.group(2)
    print("NOTICE: %s says: '%s'" % (server,message))
  else: pass # Other
Example #40
0
# test match.span(), and nested spans

try:
    import ure as re
except ImportError:
    try:
        import re
    except ImportError:
        print("SKIP")
        raise SystemExit

try:
    m = re.match(".", "a")
    m.span
except AttributeError:
    print('SKIP')
    raise SystemExit


def print_spans(match):
    print('----')
    try:
        i = 0
        while True:
            print(match.span(i), match.start(i), match.end(i))
            i += 1
    except IndexError:
        pass

m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567')
print_spans(m)
Example #41
0
    import ure as re
except ImportError:
    try:
        import re
    except ImportError:
        import sys
        print("SKIP")
        sys.exit()

def print_groups(match):
    print('----')
    try:
        i = 0
        while True:
            print(m.group(i))
            i += 1
    except IndexError:
        pass

m = re.match(r'\w+','1234hello567 abc')
print_groups(m)

m = re.match(r'(\w+)\s+(\w+)','ABC \t1234hello567 abc')
print_groups(m)

m = re.match(r'(\S+)\s+(\D+)','ABC \thello abc567 abc')
print_groups(m)

m = re.match(r'(([0-9]*)([a-z]*)\d*)','1234hello567')
print_groups(m)
Example #42
0
try:
    import ure as re
except ImportError:
    try:
        import re
    except ImportError:
        print("SKIP")
        raise SystemExit

try:
    re.match("(a*)*", "aaa")
except RuntimeError:
    print("RuntimeError")