Ejemplo n.º 1
0
 def _extract_container_names_from(self, outtext):
     use_prj_name = self.project_name \
         if self.project_name \
         else '[A-Za-z0-9]+'
     matcher = recomp('({}_(.+)_[0-9]+)'.format(use_prj_name))
     lines = list(map(lambda x: x.strip(), outtext.split("\n")))
     lines = list(filter(lambda x: matcher.search(x) is not None, lines))
     run_containers = []
     for line in lines:
         match = matcher.search(line)
         run_containers.append((match.groups()[0], match.groups()[1]))
     return run_containers
Ejemplo n.º 2
0
 def _extract_container_names_from(self, outtext):
     use_prj_name = self.project_name \
         if self.project_name \
         else '[A-Za-z0-9]+'
     matcher = recomp('({}_(.+)_[0-9]+)'.format(use_prj_name))
     lines = list(map(lambda x: x.strip(), outtext.split("\n")))
     lines = list(filter(lambda x: matcher.search(x) is not None, lines))
     run_containers = []
     for line in lines:
         match = matcher.search(line)
         run_containers.append((match.groups()[0], match.groups()[1]))
     return run_containers
Ejemplo n.º 3
0
 def get_chan_name(self, grep_str):
     from re import compile as recomp
     prog = recomp(grep_str, flags = re.I)
     try:
         while True:
             chan_indx = self.next_chan()
             chan_name = self.chan_name(chan_indx)
             result = prog.search(chan_name)
             if (result):
                 return chan_indx
     except StopIteration:
         return 'name not found'
Ejemplo n.º 4
0
 def get_chan_name(self, grep_str):
     import re
     from re import compile as recomp
     prog = recomp(grep_str, flags = re.I)
     has_name = []
     self._chan_holder = -1
     try:
         while True:
             chan_indx = self.next_chan()
             chan_name = self.chan_name(chan_indx)
             result = prog.search(chan_name)
             if (result):
                 has_name.append(chan_indx)
     except StopIteration:
         self._chan_holder = -1
         return has_name
Ejemplo n.º 5
0
def generatechecknumbergen(location):
    for filename in listdir(location):
        appname = open(location+filename) 
        for line in appname:
            if "Name=" in line:
                name = line.rstrip().replace('Name=', '')
                regex = recomp('[^a-zA-Z]')
                nospacename = regex.sub('', name)
            if "Exec=" in line:
                    pexec = line.rstrip().replace('Exec=', '')
        # Create function
        with open("checknumbergen.py", "a") as myfile:
            myfile.write('    '+nospacename+' = "'+name+'"\n')
            myfile.write("    if userinput in "+nospacename+":\n")
            myfile.write("        print('"+pexec+"')\n")
            myfile.write(r"        print('\n')")
            myfile.write("\n")
Ejemplo n.º 6
0
def addToCheckInput(location):
    for filename in listdir(location):
        appname = open(location+filename) 
        for line in appname:
            if "Name=" in line:
                name = line.rstrip().replace('Name=', '')
                regex = recomp('[^a-zA-Z]')
                nospacename = regex.sub('', name)
            if "Exec=" in line:
                    pexec = line.rstrip().replace('Exec=', '')
        # Create function
        with open("checkinput.py", "a") as myfile:
            myfile.write('    '+nospacename+' = "'+name+'"\n')
            myfile.write("    if userinput in "+nospacename+":\n")
            myfile.write("        print('Program number: ', i)\n")
            myfile.write("        print('Program name: "+name+"')\n")
            myfile.write("        print('Exec command: "+pexec+"')\n")
            myfile.write("        i = i+1\n")
            myfile.write(r"        print('\n')")
            myfile.write("\n")
        print(name)
Ejemplo n.º 7
0
class EnvReader:
    PATHS = (".env", "~/.{}.cfg", "/etc/{}.cfg")
    PATTERN = recomp(r"([^\s=]+)\s*=\s*([^=]+)")
    def __new__(self, name):
        assert name
        value = dict()
        for place in EnvReader.PATHS:
            fname = expanduser(place.format(name))
            if isfile(fname):
                with open(fname, "r") as fh:
                    lineno = 1
                    for line in fh:
                        line = line.strip()
                        if line.startswith("#") or line.isspace() or not line:
                            continue
                        match = EnvReader.PATTERN.match(line)
                        if match is None:
                            raise ValueError("Malformed syntax at line {} in {}".format(lineno, fname))
                        lineno += 1
                        key, val = match.group(1), match.group(2)
                        value[key] = val
                    break
        value.update(environ)
        return value
Ejemplo n.º 8
0
Makes the following transformations:
  <pattern> `=>` <action>
    -> __match[<pattern>] = <action>
  <pattern> `=>` { <code> }
    -> __match[<pattern>] = MatchScope.new(function (__match)
           <code>
       end)
"""

from re import MULTILINE, compile as recomp
from itertools import takewhile
from typing import List
import sys

WS_RX = recomp(r"^[\t ]*")
OP_RX = recomp(
    r"(^|(--)?\[=*\[|(--)?\]=*\]|--|\"(?:[^\"\\]|\\.)*\"|'(?:[^'\\]|\\.)*'|=>|{|})",
    MULTILINE)
CMNT_BEGIN_RX = recomp(r"(--)?\[(=*)\[")
CMNT_END_RX = recomp(r"(--)?\](=*)\]")


class ParseException(Exception):
    """Parse exception"""


def tokenize(hwk_code: str) -> List[str]:
    """Tokenize `hwk_code` according to `OP_RX`"""
    last = 0
    segments = []
Ejemplo n.º 9
0
                result = builder.article(
                    "© @SedenUserBot",
                    text="""@SedenUserBot'u kullanmayı deneyin!
Hesabınızı bot'a çevirebilirsiniz ve bunları kullanabilirsiniz. Unutmayın, siz başkasının botunu yönetemezsiniz! Alttaki GitHub adresinden tüm kurulum detayları anlatılmıştır.""",
                    buttons=[
                        [custom.Button.url("Kanala Katıl", "https://t.me/SedenUserBot"), custom.custom.Button.url(
                            "Gruba Katıl", "https://t.me/SedenUserBotSupport")],
                        [custom.Button.url(
                            "GitHub", "https://github.com/TeamDerUntergang/Telegram-UserBot")]
                    ],
                    link_preview=False
                )
            await event.answer([result] if result else None)

        @tgbot.on(events.callbackquery.CallbackQuery(  # pylint:disable=E0602
            data=recomp(b"helpme_next\((.+?)\)")
        ))
        async def on_plug_in_callback_query_handler(event):
            if event.query.user_id == uid:  # pylint:disable=E0602
                current_page_number = int(
                    event.data_match.group(1).decode("UTF-8"))
                buttons = paginate_help(
                    current_page_number + 1, dugmeler, "helpme")
                # https://t.me/TelethonChat/115200
                await event.edit(buttons=buttons)
            else:
                reply_pop_up_alert = "Lütfen kendine bir @SedenUserBot aç, benim mesajlarımı düzenlemeye çalışma!"
                await event.answer(reply_pop_up_alert, cache_time=0, alert=True)

        @tgbot.on(events.callbackquery.CallbackQuery(  # pylint:disable=E0602
            data=recomp(b"helpme_prev\((.+?)\)")
Ejemplo n.º 10
0
    def __init__(self, *args, **kw):
        """base database class for underlying subpackages like cat, gbl, lbl, etc.
        This class can also be used directly.

        :param args: list of additional arguments: table_prefix, stmt_factory, error_tolerance

        :keyword db_connection: The database connection to be used
        :type db_connection: str, cx_oracle.Connection, pydodbc.Connection, sqlite3.Connection, sqlce.Connection
        :param args: list of additional arguments: table_prefix, stmt_factory, error_tolerance
        :keyword table_prefix: The table name prefix which is usually master schema name
        :type table_prefix: str
        :keyword stmt_factory: The SQL statement factory to be used
        :type stmt_factory: GenericSQLStatementFactory
        :keyword strIdent: string identifier used from subclass for identification
        :type strIdent: str
        :keyword error_tolerance: set log level for debugging purposes
        :type error_tolerance: int
        :keyword loglevel: being able to reduce logging, especially with scripts
        :type loglevel: Integer, see logging class for reference
        :keyword autocommit: boolean value to determine wether to commit after an insert or update automatically
        :type autocommit: bool
        :keyword foreign_keys: set to True when sqlite DB connection should take care of foreign key relations
        :type foreign_keys: bool
        :keyword arraysize: only for cxoracle: '...This read-write attribute specifies the number of rows to fetch
                            at a time internally...', default is 50, a good value should be about 500
        :type arraysize: int
        """
        opts = arg_trans(["db_connection", ("table_prefix", None), ("sql_factory", GenericSQLStatementFactory()),
                          ("error_tolerance", ERROR_TOLERANCE_NONE), ("strIdent", "")], *args, **kw)
        # self._log = Logger(self.__class__.__name__, kw.pop("loglevel", INFO))
        self._table_prefix = "" if opts["table_prefix"] is None else opts["table_prefix"].rstrip('.')
        self._sql_factory = opts["sql_factory"]
        self._ident = opts["strIdent"]
        self.error_tolerance = opts["error_tolerance"]
        self._enable_fks = opts.pop("foreign_keys", False)
        self._arraysize = None

        self._db_type = None
        self.db_func_map = {}
        self.role = None
        self.sync_slave_reload_all = False

        self._connstr = [None, self._table_prefix]
        self._func_params = recomp(r"(\(.*\))")
        self._auto_commit = opts.pop("autocommit", False)
        self._direct_conn = False

        self._db_connection = None

        # connect to DB and configure some DB specifics like role, date, time, etc.
        db_connection = opts["db_connection"]
        if type(db_connection) in StringTypes:
            self._connstr[0] = db_connection
            self._direct_conn = True
            cslower = db_connection.lower()
            if db_connection in CONN_STRING:
                self._table_prefix = CONN_STRING[db_connection][1]
                db_connection = CONN_STRING[db_connection][0]
                cslower = db_connection.lower()

            if any(cslower.endswith(ext) for ext in SQLITE_FILE_EXT) and path.isfile(cslower) or cslower == ":memory:":
                try:
                    if not stat(db_connection)[ST_MODE] & S_IWRITE:
                        chmod(db_connection, S_IWRITE)
                except:
                    pass

                self._db_connection = sqconnect(db_connection)
                self._db_connection.text_factory = str
                register_adapter(long, lambda l: str(l) if long(l) > maxint else l)
                register_converter("long", lambda l: long(l))

            elif any(cslower.endswith(ext) for ext in SDF_FILE_EXT):
                if cslower.startswith('data source='):
                    fname = db_connection[cslower.find("data source=") + 12:].partition(";")[0].strip()
                else:
                    fname = cslower
                    db_connection = 'data source=' + db_connection
                if not stat(fname)[ST_MODE] & S_IWRITE:
                    chmod(fname, S_IWRITE)
                if "provider=" not in cslower:
                    db_connection += (";Provider=%s" % DEFAULT_SLAVE_DATA_PROVIDER)
                self._db_connection = adoconnect(db_connection)
                self._db_connection.adoConn.CursorLocation = adUseServer
            else:
                # ex: DBQ=racadmpe;Uid=DEV_MFC31X_ADMIN;Pwd=MFC31X_ADMIN
                # init argument part, split up and use it for cxconnect

                # try:
                if cxconnect is not None and "uid" in cslower and "pwd" in cslower:
                    args = {}
                    for arg in db_connection.split(';'):
                        part = arg.split('=', 2)
                        args[part[0].strip().lower()] = part[1].strip()
                    self._db_connection = cxconnect(args['uid'], args['pwd'], args.pop('dbq', 'racadmpe'),
                                                    threaded=opts.pop('threaded', False))
                else:
                    self.db_connection = pyconnect(db_connection)
                # except:
                #     raise AdasDBError("couldn't open database")
                self._arraysize = opts.pop("arraysize", None)

            self._db_type = DBTYPE.index(str(self._db_connection)[1:].split('.')[0])
        else:
            self._db_connection = db_connection
            self._connstr[0] = str(db_connection)
            self._db_type = DBTYPE.index(str(self._db_connection)[1:].split('.')[0])

        self.db_func_map[DB_FUNC_NAME_MIN] = "MIN"
        self.db_func_map[DB_FUNC_NAME_MAX] = "MAX"
        self.db_func_map[DB_FUNC_NAME_LOWER] = "LOWER"
        self.db_func_map[DB_FUNC_NAME_UPPER] = "UPPER"
        self.db_func_map[DB_FUNC_NAME_GETDATE] = "GETDATE()"

        if self._db_type >= 2:
            self._db_type = -1
            if self._table_prefix != "":
                self.execute("ALTER SESSION SET CURRENT_SCHEMA = %s" % self._table_prefix)
            username = self._table_prefix if len(self._table_prefix) > 0 else "SELECT USER FROM DUAL"
            self._tablequery = SQL_TABLENAMES[-1].replace("$NM", username).replace("$TS", self._ident[2:])
            self._columnquery = SQL_COLUMNS[-1][1].replace("$NM", username)
            # username = self.execute("SELECT sys_context('USERENV', 'SESSION_USER') FROM dual")#[0][0]
            # username = '******'
            # print "username --> ", username
            self.role = ROLE_DB_ADMIN if ROLE_DB_ADMIN in username.upper() else ROLE_DB_USER

            self.execute("ALTER SESSION SET NLS_COMP=LINGUISTIC")
            self.execute("ALTER SESSION SET NLS_SORT=BINARY_CI")
        else:
            self.role = ROLE_DB_ADMIN
            self._tablequery = SQL_TABLENAMES[self._db_type].replace("$TS", self._table_prefix)
            self._columnquery = SQL_COLUMNS[self._db_type][1]

        if self._enable_fks and self._db_type == 0:  # off per default to keep unittests running
            self.execute("PRAGMA FOREIGN_KEYS = ON")

        self.date_time_format = DEFAULT_DATETIME_FORMAT
        # retrieve the sub schema version
        try:
            self._sub_versions = {i[0]: i[1] for i in self.execute("SELECT SUBSCHEMEPREF, SUBSCHEMEVERSION "
                                                                   "FROM VERSIONS")}
        except:
            self._sub_versions = {}

        # retrieve the who is the current user gbl_user table
        try:
            self.current_gbluserid = self.execute("SELECT USERID FROM GBL_USERS WHERE LOGINNAME = $CU")[0][0]
        except:
            self.current_gbluserid = None
Ejemplo n.º 11
0
#!/usr/bin/evn python

from re import compile as recomp
import os

pattern = recomp("[a-zA-Z][a-zA-Z0-9]*")


def fileIndex(inputfile, window, overlap):
    #print 'Index starting on %s <br>' % inputfile
    jump = window - overlap
    with open(inputfile, 'r') as f:
        #print 'File opened successfully<br>'
        content = pattern.findall(f.read())
    filestring = ''
    for i in content:
        if i[0].lower() <= 'f': filestring += 'A'
        elif i[0].lower() <= 'l': filestring += 'C'
        elif i[0].lower() <= 'r': filestring += 'G'
        else: filestring += 'T'
    a = len(filestring)
    keylist = []
    for i in range(0, a - window + 1, jump):
        key = filestring[i:i + window]
        if key not in keylist:
            keylist.append(filestring[i:i + window])
    keylist = sorted(keylist)
    #print 'Index finished'
    return keylist