Python os.path.strip() Examples

The following are code examples for showing how to use os.path.strip(). 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: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: amalgamation.py    Apache License 2.0 6 votes vote down vote up
def get_sources(def_file):
    sources = []
    files = []
    visited = set()
    mxnet_path = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
    for line in open(def_file):
        files = files + line.strip().split(' ')

    for f in files:
        f = f.strip()
        if not f or f.endswith('.o:') or f == '\\': continue
        f = os.path.realpath(f)
        fn = os.path.relpath(f)
        if f.startswith(mxnet_path) and fn not in visited:
            sources.append(fn)
            visited.add(fn)
    return sources 
Example 2
Project: qt_moc_generator   Author: davidc604   File: qt_moc_generator.py    MIT License 6 votes vote down vote up
def which(program):
    import os
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None 
Example 3
Project: LMS   Author: RRZE-HPC   File: influxdbHandlerNative.py    GNU General Public License v3.0 6 votes vote down vote up
def which(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None 
Example 4
Project: LMS   Author: RRZE-HPC   File: influxdbHandlerNative.py    GNU General Public License v3.0 6 votes vote down vote up
def read_tags(self):
        tags = {}
        if loggedin_users(self.userblacklist) == 0 and os.path.exists(self.tagfile):
            os.remove(self.tagfile)
            return tags
        if os.path.exists(self.tagfile):
            finput = None
            try:
                f = open(self.tagfile)
                finput = f.read().strip()
                f.close()
            except:
                self.log.error("Cannot open tag file %s" % (self.tagfile,))
                return tags
            for line in finput.split("\n"):
                if line.startswith("#") or not line.strip():
                    continue
                if not ":" in line:
                    continue
                linelist = [ i.strip() for i in line.split(":") ]
                if len(linelist):
                    tags.update({linelist[0] : linelist[1]})
        return tags 
Example 5
Project: neo4j-social-network   Author: bestvibes   File: easy_install.py    MIT License 6 votes vote down vote up
def run(self):
        if self.verbose != self.distribution.verbose:
            log.set_verbosity(self.verbose)
        try:
            for spec in self.args:
                self.easy_install(spec, not self.no_deps)
            if self.record:
                outputs = self.outputs
                if self.root:               # strip any package prefix
                    root_len = len(self.root)
                    for counter in xrange(len(outputs)):
                        outputs[counter] = outputs[counter][root_len:]
                from distutils import file_util
                self.execute(
                    file_util.write_file, (self.record, outputs),
                    "writing list of installed files to '%s'" %
                    self.record
                )
            self.warn_deprecated_options()
        finally:
            log.set_verbosity(self.distribution.verbose) 
Example 6
Project: centreon-discovery   Author: Centreon-Community   File: easy_install.py    GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        if self.verbose!=self.distribution.verbose:
            log.set_verbosity(self.verbose)
        try:
            for spec in self.args:
                self.easy_install(spec, not self.no_deps)
            if self.record:
                outputs = self.outputs
                if self.root:               # strip any package prefix
                    root_len = len(self.root)
                    for counter in xrange(len(outputs)):
                        outputs[counter] = outputs[counter][root_len:]
                from distutils import file_util
                self.execute(
                    file_util.write_file, (self.record, outputs),
                    "writing list of installed files to '%s'" %
                    self.record
                )
            self.warn_deprecated_options()
        finally:
            log.set_verbosity(self.distribution.verbose) 
Example 7
Project: centreon-discovery   Author: Centreon-Community   File: easy_install.py    GNU General Public License v2.0 6 votes vote down vote up
def get_script_header(script_text, executable=sys_executable, wininst=False):
    """Create a #! line, getting options (if any) from script_text"""
    from distutils.command.build_scripts import first_line_re
    first = (script_text+'\n').splitlines()[0]
    match = first_line_re.match(first)
    options = ''
    if match:
        options = match.group(1) or ''
        if options: options = ' '+options
    if wininst:
        executable = "python.exe"
    else:
        executable = nt_quote_arg(executable)
    hdr = "#!%(executable)s%(options)s\n" % locals()
    if unicode(hdr,'ascii','ignore').encode('ascii') != hdr:
        # Non-ascii path to sys.executable, use -x to prevent warnings
        if options:
            if options.strip().startswith('-'):
                options = ' -x'+options.strip()[1:]
            # else: punt, we can't do it, let the warning happen anyway
        else:
            options = ' -x'
    executable = fix_jython_executable(executable, options)
    hdr = "#!%(executable)s%(options)s\n" % locals()
    return hdr 
Example 8
Project: ProjectEuler   Author: DestructHub   File: stats.py    MIT License 6 votes vote down vote up
def get_problem_hashes():
    """
    Function: get_problem_hashes
    Summary: Walking from each problem and return a tuple
            (problem_name, hash_content)
    Returns: list of tuples <problem_name: string, hash_content: string>
    """
    hash_pattern = re.compile("./Problem[0-9]{3}")
    hashes = {}
    for file_tuple in os.walk("."):
        if hash_pattern.match(file_tuple[0]) and ".hash" in file_tuple[-1]:
            problem = file_tuple[0]
            hash_path = path.join(problem, '.hash')
            hash_content = read_hashfile(hash_path)
            hashes[problem.strip('./')] = hash_content

    return hashes 
Example 9
Project: portia   Author: hetanglinlin   File: backends.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def listdir(self, path):
        path = '{}/'.format(self.path(path))
        # All paths should be relative to the project directory
        path_parts = len(path.strip('/').split('/'))
        if path == '/':
            path = ''
        if path:
            path_parts += 1
        dirs, files = set(), set()
        for p in self._working_tree:
            if not p.startswith(path):
                continue
            split = p.split('/')
            try:
                section = split[path_parts - 1]
            except IndexError:
                # File in parent directory with similar name to directory
                continue
            if len(split) == path_parts:
                files.add(section)
            else:
                dirs.add(section)
        return sorted(dirs), sorted(files) 
Example 10
Project: httpwatcher   Author: thanethomson   File: server.py    MIT License 6 votes vote down vote up
def validate_path(self, url_path, abspath):
        if ".." in url_path or "~" in url_path:
            raise tornado.web.HTTPError(403, "Invalid request URI")

        # if it's an existing directory
        if os.path.exists(abspath) and os.path.isdir(abspath):
            if not url_path.endswith("/"):
                self.redirect(
                    "%s%s/" % (self.server_base_path, url_path.strip('/')),
                    permanent=True
                )
                return

            abspath = self.find_first_default_file(abspath)

        if not os.path.exists(abspath):
            raise tornado.web.HTTPError(404)

        if not os.path.isfile(abspath):
            raise tornado.web.HTTPError(403, "%s is not a file", url_path)

        return abspath 
Example 11
Project: georef_imageregistration   Author: nasa   File: miscUtilities.py    Apache License 2.0 6 votes vote down vote up
def which(program):
    '''Tests if a given command line tool is available, replicating the "which" function'''
    import os
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None 
Example 12
Project: Commander   Author: Keeper-Security   File: importer.py    MIT License 6 votes vote down vote up
def path_components(path, delimiter=PathDelimiter):
    # type: (str, str) -> collections.Iterable[str]
    p = path.strip()
    pos = 0
    while pos < len(p):
        idx = p.find(delimiter, pos)
        if idx >= 0:
            if idx+1 < len(p):
                if p[idx+1] == delimiter:
                    pos = idx + 2
                    continue
            comp = p[:idx].strip()
            p = p[idx+1:].strip()
            pos = 0
            if len(comp) > 0:
                yield comp.replace(2*delimiter, delimiter)
        else:
            p = strip_path_delimiter(p, delimiter=delimiter)
            if len(p) > 0:
                yield p.replace(2*delimiter, delimiter)
                p = '' 
Example 13
Project: incubator-mxnet   Author: apache   File: amalgamation.py    Apache License 2.0 6 votes vote down vote up
def get_sources(def_file):
    sources = []
    files = []
    visited = set()
    mxnet_path = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
    for line in open(def_file):
        files = files + line.strip().split(' ')

    for f in files:
        f = f.strip()
        if not f or f.endswith('.o:') or f == '\\': continue
        f = os.path.realpath(f)
        fn = os.path.relpath(f)
        if f.startswith(mxnet_path) and fn not in visited:
            sources.append(fn)
            visited.add(fn)
    return sources 
Example 14
Project: validator.vim   Author: maralla   File: utils.py    MIT License 6 votes vote down vote up
def exe_exist(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return True
    else:
        try_paths = []
        is_win = platform.system() == 'Windows'

        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            full_path = os.path.join(path, program)
            try_paths.append(full_path)
            if is_win:
                try_paths.append(full_path + '.exe')

        if any(map(is_exe, try_paths)):
            return True
    return False 
Example 15
Project: chewBBACA   Author: B-UMMI   File: CreateSchema.py    GNU General Public License v3.0 6 votes vote down vote up
def which(program):
    import os
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return True
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return True

    return "Not found" 
Example 16
Project: pipa-pay-server   Author: davidvon   File: easy_install.py    Apache License 2.0 6 votes vote down vote up
def run(self):
        if self.verbose != self.distribution.verbose:
            log.set_verbosity(self.verbose)
        try:
            for spec in self.args:
                self.easy_install(spec, not self.no_deps)
            if self.record:
                outputs = self.outputs
                if self.root:               # strip any package prefix
                    root_len = len(self.root)
                    for counter in xrange(len(outputs)):
                        outputs[counter] = outputs[counter][root_len:]
                from distutils import file_util
                self.execute(
                    file_util.write_file, (self.record, outputs),
                    "writing list of installed files to '%s'" %
                    self.record
                )
            self.warn_deprecated_options()
        finally:
            log.set_verbosity(self.distribution.verbose) 
Example 17
Project: Emacs-theme-creator   Author: habedi   File: easy_install.py    GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        if self.verbose != self.distribution.verbose:
            log.set_verbosity(self.verbose)
        try:
            for spec in self.args:
                self.easy_install(spec, not self.no_deps)
            if self.record:
                outputs = self.outputs
                if self.root:               # strip any package prefix
                    root_len = len(self.root)
                    for counter in xrange(len(outputs)):
                        outputs[counter] = outputs[counter][root_len:]
                from distutils import file_util
                self.execute(
                    file_util.write_file, (self.record, outputs),
                    "writing list of installed files to '%s'" %
                    self.record
                )
            self.warn_deprecated_options()
        finally:
            log.set_verbosity(self.distribution.verbose) 
Example 18
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 19
Project: arma-project-template   Author: acemod   File: make.py    MIT License 5 votes vote down vote up
def find_depbo_tools():
    """Use registry entries to find DePBO-based tools."""
    requiredToolPaths = {"pboProject": None, "rapify": None, "MakePbo": None}
    failed = False

    for tool in requiredToolPaths:
        try:
            try:
                k = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Mikero\{}".format(tool))
                path = winreg.QueryValueEx(k, "exe")[0]
            except FileNotFoundError:
                k = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Software\Mikero\{}".format(tool))
                path = winreg.QueryValueEx(k, "exe")[0]
        except FileNotFoundError:
            print_error("Could not find {}".format(tool))
            failed = True
        else:
            #Strip any quotations from the path due to a MikeRo tool bug which leaves a trailing space in some of its registry paths.
            requiredToolPaths[tool] = path.strip('"')
            print_green("Found {}.".format(tool))
        finally:
            winreg.CloseKey(k)

    if failed:
        raise Exception("BadDePBO", "DePBO tools not installed correctly")

    return requiredToolPaths 
Example 20
Project: LMS   Author: RRZE-HPC   File: influxdbHandlerNative.py    GNU General Public License v3.0 5 votes vote down vote up
def loggedin_users(blacklist):
    systemusers = blacklist
    users = []
    f = open("/etc/passwd")
    finput = f.read().strip()
    f.close()
    for line in finput.split("\n"):
        if re.match("^\s*$", line): continue
        linelist = re.split(":", line)
        if linelist[1] == "x":
            if len(linelist[0]) <= 8:
                systemusers.append(linelist[0])
            else:
                systemusers.append(linelist[0])
                systemusers.append(linelist[0][:7]+"+")
        else:
            uid = None
            try:
                uid = int(linelist[2])
                if uid < 1024:
                    if len(linelist[0]) <= 8:
                        systemusers.append(linelist[0])
                    else:
                        systemusers.append(linelist[0])
                        systemusers.append(linelist[0][:7]+"+")
            except:
                pass
    cmd = ["ps -ef"]
    try:
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (out, err) = p.communicate()
    except subprocess.CalledProcessError, e:
        return -1 
Example 21
Project: aws-cfn-plex   Author: lordmuffin   File: __init__.py    MIT License 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 22
Project: neo4j-social-network   Author: bestvibes   File: easy_install.py    MIT License 5 votes vote down vote up
def get_exe_prefixes(exe_filename):
    """Get exe->egg path translations for a given .exe file"""

    prefixes = [
        ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''),
        ('PLATLIB/', ''),
        ('SCRIPTS/', 'EGG-INFO/scripts/'),
        ('DATA/LIB/site-packages', ''),
    ]
    z = zipfile.ZipFile(exe_filename)
    try:
        for info in z.infolist():
            name = info.filename
            parts = name.split('/')
            if len(parts)==3 and parts[2]=='PKG-INFO':
                if parts[1].endswith('.egg-info'):
                    prefixes.insert(0,('/'.join(parts[:2]), 'EGG-INFO/'))
                    break
            if len(parts)<>2 or not name.endswith('.pth'):
                continue
            if name.endswith('-nspkg.pth'):
                continue
            if parts[0].upper() in ('PURELIB','PLATLIB'):
                for pth in yield_lines(z.read(name)):
                    pth = pth.strip().replace('\\','/')
                    if not pth.startswith('import'):
                        prefixes.append((('%s/%s/' % (parts[0],pth)), ''))
    finally:
        z.close()
    prefixes = [(x.lower(),y) for x, y in prefixes]
    prefixes.sort(); prefixes.reverse()
    return prefixes 
Example 23
Project: neo4j-social-network   Author: bestvibes   File: easy_install.py    MIT License 5 votes vote down vote up
def _load(self):
        self.paths = []
        saw_import = False
        seen = dict.fromkeys(self.sitedirs)
        if os.path.isfile(self.filename):
            f = open(self.filename,'rt')
            for line in f:
                if line.startswith('import'):
                    saw_import = True
                    continue
                path = line.rstrip()
                self.paths.append(path)
                if not path.strip() or path.strip().startswith('#'):
                    continue
                # skip non-existent paths, in case somebody deleted a package
                # manually, and duplicate paths as well
                path = self.paths[-1] = normalize_path(
                    os.path.join(self.basedir,path)
                )
                if not os.path.exists(path) or path in seen:
                    self.paths.pop()    # skip it
                    self.dirty = True   # we cleaned up, so we're dirty now :)
                    continue
                seen[path] = 1
            f.close()

        if self.paths and not saw_import:
            self.dirty = True   # ensure anything we touch has import wrappers
        while self.paths and not self.paths[-1].strip():
            self.paths.pop() 
Example 24
Project: neo4j-social-network   Author: bestvibes   File: easy_install.py    MIT License 5 votes vote down vote up
def get_script_header(script_text, executable=sys_executable, wininst=False):
    """Create a #! line, getting options (if any) from script_text"""
    from distutils.command.build_scripts import first_line_re

    # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
    if not isinstance(first_line_re.pattern, str):
        first_line_re = re.compile(first_line_re.pattern.decode())

    first = (script_text+'\n').splitlines()[0]
    match = first_line_re.match(first)
    options = ''
    if match:
        options = match.group(1) or ''
        if options: options = ' '+options
    if wininst:
        executable = "python.exe"
    else:
        executable = nt_quote_arg(executable)
    hdr = "#!%(executable)s%(options)s\n" % locals()
    if not isascii(hdr):
        # Non-ascii path to sys.executable, use -x to prevent warnings
        if options:
            if options.strip().startswith('-'):
                options = ' -x'+options.strip()[1:]
            # else: punt, we can't do it, let the warning happen anyway
        else:
            options = ' -x'
    executable = fix_jython_executable(executable, options)
    hdr = "#!%(executable)s%(options)s\n" % locals()
    return hdr 
Example 25
Project: centreon-discovery   Author: Centreon-Community   File: easy_install.py    GNU General Public License v2.0 5 votes vote down vote up
def get_exe_prefixes(exe_filename):
    """Get exe->egg path translations for a given .exe file"""

    prefixes = [
        ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''),
        ('PLATLIB/', ''),
        ('SCRIPTS/', 'EGG-INFO/scripts/')
    ]
    z = zipfile.ZipFile(exe_filename)
    try:
        for info in z.infolist():
            name = info.filename
            parts = name.split('/')
            if len(parts)==3 and parts[2]=='PKG-INFO':
                if parts[1].endswith('.egg-info'):
                    prefixes.insert(0,('/'.join(parts[:2]), 'EGG-INFO/'))
                    break
            if len(parts)!=2 or not name.endswith('.pth'):
                continue
            if name.endswith('-nspkg.pth'):
                continue
            if parts[0].upper() in ('PURELIB','PLATLIB'):
                for pth in yield_lines(z.read(name)):
                    pth = pth.strip().replace('\\','/')
                    if not pth.startswith('import'):
                        prefixes.append((('%s/%s/' % (parts[0],pth)), ''))
    finally:
        z.close()
    prefixes = [(x.lower(),y) for x, y in prefixes]
    prefixes.sort(); prefixes.reverse()
    return prefixes 
Example 26
Project: centreon-discovery   Author: Centreon-Community   File: easy_install.py    GNU General Public License v2.0 5 votes vote down vote up
def _load(self):
        self.paths = []
        saw_import = False
        seen = dict.fromkeys(self.sitedirs)
        if os.path.isfile(self.filename):
            for line in open(self.filename,'rt'):
                if line.startswith('import'):
                    saw_import = True
                    continue
                path = line.rstrip()
                self.paths.append(path)
                if not path.strip() or path.strip().startswith('#'):
                    continue
                # skip non-existent paths, in case somebody deleted a package
                # manually, and duplicate paths as well
                path = self.paths[-1] = normalize_path(
                    os.path.join(self.basedir,path)
                )
                if not os.path.exists(path) or path in seen:
                    self.paths.pop()    # skip it
                    self.dirty = True   # we cleaned up, so we're dirty now :)
                    continue
                seen[path] = 1

        if self.paths and not saw_import:
            self.dirty = True   # ensure anything we touch has import wrappers
        while self.paths and not self.paths[-1].strip():
            self.paths.pop() 
Example 27
Project: grand_central   Author: amiracle   File: __init__.py    MIT License 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 28
Project: rpi-people-counter   Author: AlexNaga   File: wifi.py    MIT License 5 votes vote down vote up
def which(self, program):
        """Determines whether program exists"""
        def is_exe(fpath):
            return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

        fpath, fname = os.path.split(program)
        if fpath:
            if is_exe(program):
                return program
        else:
            for path in os.environ["PATH"].split(os.pathsep):
                path = path.strip('"')
                exe_file = os.path.join(path, program)
                if is_exe(exe_file):
                    return exe_file 
Example 29
Project: sx   Author: sbradley7777   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def generateBaseImportPath():
        pathToBaseDir = ""
        # #######################################################################
        # Search for user defined paths to modules such as for devel.
        # #######################################################################
        for path in sys.path:
            result = path.find("sx/lib")
            if (result >= 0) :
                # Found a user defined path for sx, so that is base
                # path that will be used.
                pathToBaseDir = path
                break;

        # #######################################################################
        # If no user path is defined for sx then the python paths will
        # be searched.
        # #######################################################################
        if (not len(pathToBaseDir) > 0):
            for path in sys.path :
                # Find the first occurance
                if (((path.strip()[-len("site-packages"):]) == "site-packages") and
                    (os.path.isdir(path + "/sx/reports") or
                     os.path.isdir(path + "/sx/plugins"))) :
                    pathToBaseDir = path
                    break;
        return pathToBaseDir 
Example 30
Project: ProjectEuler   Author: DestructHub   File: stats.py    MIT License 5 votes vote down vote up
def read_hashfile(fpath):
    """Read .hash based on fpath and clean the weird chars"""
    return open(fpath).read().strip(' -\n') 
Example 31
Project: ProjectEuler   Author: DestructHub   File: stats.py    MIT License 5 votes vote down vote up
def digest_answer(answer):
    clean_answer = answer.strip(' \n')
    return hashlib.md5(clean_answer.encode('utf-8')).hexdigest() 
Example 32
Project: ProjectEuler   Author: DestructHub   File: stats.py    MIT License 5 votes vote down vote up
def split_problem_language(path):
    """
    Function: split_problem_language
    Summary: Get a path and split into problem and language
    Examples:
        >>> split_problem_language("./Problem001/Python")
        ["Problem001", "Python]

    Attributes:
        @param (path): path like ./Folder/Language
    Returns: [Problem, Language] <(string, string)>
    """
    return path.strip("./").split("/") 
Example 33
Project: ProjectEuler   Author: DestructHub   File: stats.py    MIT License 5 votes vote down vote up
def execute_builder(b):
    out, err, t = b.execute()
    answer = out.decode("utf-8").strip("\n")
    if err:
        print(err)
        os._exit(1)
    sys.stdout.write(ERASE_LINE)
    building = "\rBuilt {}: Answer: {}: {:.2f}s\n".format(b.path, answer, t)
    sys.stdout.write(building)
    sys.stdout.flush()

    return answer, t

# need docs 
Example 34
Project: firebase-live-data   Author: heston   File: data.py    MIT License 5 votes vote down vote up
def get_path_list(path):
    path = path.strip('/')

    if path == '':
        return []

    return path.split('/') 
Example 35
Project: maze-builder   Author: kcsaff   File: processor.py    MIT License 5 votes vote down vote up
def process_pov(self, filename):
        if not self.args or not self.args.pov:
            if self.verbose > 0:
                print('No POV handler registered, pipeline stopping')
            return

        pov_args = [
            self.args.pov,
        ]
        if self.args.ini:
            ini = random.choice(self.args.ini.split(',')).strip()
            if ini.endswith('[]'):
                section = random.choice(read_ini_sections(ini[:-2]))
                ini = '{}[{}]'.format(ini[:-2], section)
            pov_args.append(ini)
        else:
            # Default size
            pov_args.extend(['+W1024', '+H768'])
        if self.args.include_path:
            pov_args.extend('+L{}'.format(path.strip()) for path in self.args.include_path.split(','))
        pov_args.extend([
            '+I{}'.format(filename),
            '+O{}'.format(OUT_FILENAME),
            '-P', '-D', '-V', '+FN8'
        ])

        with timed(is_verbose(1), 'POV-Ray is rendering maze...', 'Maze rendered in {0:.3f}s'):
            subprocess.check_call(pov_args)

        if self.args.keys:
            self.tweet(filename=OUT_FILENAME) 
Example 36
Project: pycfn-elasticsearch   Author: elelsee   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 37
Project: cidr-house-rules   Author: trulia   File: __init__.py    MIT License 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 38
Project: portia   Author: hetanglinlin   File: backends.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_valid_filename(s):
        # based on Django's Storage.get_valid_filename
        if s.strip() != s:
            return False
        if re.sub(r'(?u)[^- \w.]', '', s) != s:
            return False
        return True 
Example 39
Project: portia   Author: hetanglinlin   File: backends.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def path(self, path):
        path = path.lstrip('.').strip('/')
        if path:
            path = os.path.relpath(path)
            # Handle paths for mysql repo where there is no project name
            if path.startswith(getattr(self.repo._repo, '_name', '\0')):
                path = os.path.join(*(path.split('/')[1:]))
        try:
            return path.encode('utf-8')
        except AttributeError:
            return path 
Example 40
Project: httpwatcher   Author: thanethomson   File: server.py    MIT License 5 votes vote down vote up
def parse_url_path(cls, path):
        return os.path.join(*(path.strip("/").split("/"))) 
Example 41
Project: Rovers   Author: RIT-Space-Exploration   File: __init__.py    MIT License 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 42
Project: Commander   Author: Keeper-Security   File: importer.py    MIT License 5 votes vote down vote up
def strip_path_delimiter(name, delimiter=PathDelimiter):
    folder = name.strip()
    if folder == delimiter:
        return ''
    if len(folder) > 1:
        if folder[:1] == delimiter and folder[:2] != delimiter*2:
            folder = folder[1:].strip()
    if len(folder) > 1:
        if folder[-1:] == delimiter and folder[-2:] != delimiter*2:
            folder = folder[:-1].strip()
    return folder 
Example 43
Project: splunk-for-securityHub   Author: splunk   File: __init__.py    MIT License 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 44
Project: splunk-for-securityHub   Author: splunk   File: __init__.py    MIT License 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 45
Project: aws-alfred-workflow   Author: maxrothman   File: __init__.py    MIT License 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 46
Project: AmazonConnectSalesforceLambda   Author: AmazonConnectSalesforceIntegration   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 47
Project: bash-lambda-layer   Author: gkrizek   File: __init__.py    MIT License 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 48
Project: Backend   Author: LockScreen   File: __init__.py    MIT License 5 votes vote down vote up
def get_stylesheet_list(settings):
    """
    Retrieve list of stylesheet references from the settings object.
    """
    assert not (settings.stylesheet and settings.stylesheet_path), (
            'stylesheet and stylesheet_path are mutually exclusive.')
    stylesheets = settings.stylesheet_path or settings.stylesheet or []
    # programmatically set default can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 49
Project: MoeDownloader   Author: KanagiMiss   File: catch.py    MIT License 5 votes vote down vote up
def StripIllegalChar(self, path):
        return path.strip('>').strip('<').strip('*').strip('|').strip('?').strip(':').strip('"').strip('/') 
Example 50
Project: MoeDownloader   Author: KanagiMiss   File: catch.py    MIT License 5 votes vote down vote up
def LoadTags(self):
        if os.path.exists(self.tag_file):
            tagsfile = open(self.tag_file, 'r')
        else:
            return error('No tags file.')

        tags = []
        for tag in tagsfile:
            tags.append(tag.strip('\n').strip(';').decode('utf-8').replace(' ', '-').lower())
        self.InternalPrint('Loaded %s tags.' % len(tags), True)
        return success(tags)