str: FoldX folder
195090
def foldx_dir(self):
        """"""
        if self.root_dir:
            return op.join(self.root_dir, self._foldx_dirname)
        else:
            log.warning('Root directory not set')
            return None
585842
def casefold_parts(self, parts):
        """"""
        if self.filesystem.is_windows_fs:
            return [p.lower() for p in parts]
        return parts
1244896
def create_existing_folder(help_string=NO_HELP, default=NO_DEFAULT, suffixes=None):
        # type: (str, Union[str, NO_DEFAULT_TYPE], Union[List[str], None]) -> str
        
        # noinspection PyTypeChecker
        return ParamFilename(
            help_string=help_string,
            default=default,
            type_name="existing_folder",
            suffixes=suffixes,
        )
1309899
def stratified_kfold(df, n_folds):
    
    sessions = pd.DataFrame.from_records(list(df.index.unique())).groupby(0).apply(lambda x: x[1].unique())
    sessions.apply(lambda x: np.random.shuffle(x))
    folds = []
    for i in range(n_folds):
        idx = sessions.apply(lambda x: pd.Series(x[i * (len(x) / n_folds):(i + 1) * (len(x) / n_folds)]))
        idx = pd.DataFrame(idx.stack().reset_index(level=1, drop=True)).set_index(0, append=True).index.values
        folds.append(df.loc[idx])
    return folds
957820
function(path) {
        if (typeof path !== 'string') {
            throw 'Input path must be a valid string';
        }
        var _folderName;
        var _folderPath;
        var _subFolders = [];

        _folderName = _path.basename(path);
        _folderPath = _path.join(_path.dirname(path), _folderName) + '/';

        var folderObj = {
            /*
             * Returns the name of the folder.
             */
            getName: function() {
                return _folderName;
            },

            /*
             * Returns the path of the folder.
             */
            getPath: function() {
                return _folderPath;
            },

            /*
             * Returns the absolute path of the folder.
             */
            getAbsolutePath: function() {
                return _path.resolve(_folderPath);
            },

            /*
             * Adds a sub folder to the current folder.
             */
            addSubFolder: function(folderName) {
                if (typeof folderName !== 'string' || folderName.match(/[\\\/]/)) {
                    throw 'Sub folder name must be a valid string without delimiters.';
                }
                var subFolderPath = _path.join(_folderPath, folderName);
                var subFolder = mod.createFolder(subFolderPath);
                _subFolders[folderName] = subFolder;

                return subFolder;
            },

            /*
             * Returns a reference to an existing sub folder, provided it
             * has been created via the addSubFolder method.
             */
            getSubFolder: function(folderName) {
                return _subFolders[folderName];
            },

            /*
             * Returns the path of the specified child item, relative to the
             * current folder.
             */
            getChildPath: function(subPath, tokenMap, ignoreRegex) {
                if (typeof subPath !== 'string' || subPath.length === 0) {
                    return _folderPath;
                }
                tokenMap = tokenMap || {};
                ignoreRegex = !! ignoreRegex;

                var transform = _utils.getTransformer(tokenMap, ignoreRegex);
                subPath = transform(subPath);
                return _path.join(_folderPath, subPath);
            },

            /*
             * Gets a string glob that can be used to match all
             * folders/files in the current folder and all sub folders,
             * optionally filtered by file extension.
             */
            allFilesPattern: function(extension) {
                extension = (extension && '*.' + extension) || '*';
                return _folderPath + '**/' + extension;
            },

            /* 
             * Returns a string representation of the current state of the
             * folder (exists, symbolic link, does not exist, etc.
             */
            getStatus: function() {
                var absPath = _path.resolve(_folderPath);
                if (!_fs.existsSync(absPath)) {
                    return '[DOES NOT EXIST]';
                } else {
                    var stats = _fs.lstatSync(absPath);
                    if (stats.isDirectory()) {
                        return '[DIR]';
                    } else if (stats.isSymbolicLink()) {
                        return '[LINK]';
                    } else {
                        return '[FILE]';
                    }
                }
            },

            /*
             * Ensures that a physical copy of the folder exists at the path
             * represented by this folder.
             */
            ensureFolder: function() {
                var def = _promise.deferred();

                _fs.exists(_folderPath, function(exists) {
                    if (exists) {
                        def.resolve();
                    } else {
                        _fs.mkdir(_folderPath, function(err) {
                            if (!err) {
                                def.resolve();
                            } else {
                                def.reject();
                            }
                        });
                    }
                });

                return def.promise();
            },

            /*
             * Ensures that the current folder and all of its defined subtrees
             * exist on the file system.
             */
            ensureFolderTree: function() {
                var def = _promise.deferred();

                folderObj.ensureFolder().success(function() {
                    var subFolderCount = 0;
                    for (var folderName in _subFolders) {
                        subFolderCount++;
                    }

                    if (subFolderCount > 0) {
                        var resolver = def.getMultiStepResolver(subFolderCount);
                        for (var folderName in _subFolders) {
                            _subFolders[folderName].ensureFolderTree()
                                .success(function() {
                                    resolver.stepComplete();
                                }).fail(function() {
                                    resolver.reject();
                                });
                        }
                    } else {
                        def.resolve();
                    }
                });

                return def.promise();
            }
        };

        return folderObj;
    }
218163
def flatten_dir_tree(self, tree):
        

        result = {}

        def helper(tree, leading_path = ''):
            dirs  = tree['dirs']; files = tree['files']
            for name, file_info in files.iteritems():
                file_info['path'] = leading_path + '/'  + name
                result[file_info['path']] = file_info

            for name, contents in dirs.iteritems():
                helper(contents, leading_path +'/'+ name)
        helper(tree); return result
111629
def expand_folder(files):
    """"""
    expfiles = []
    for file in files:
        if os.path.isdir(file):
            for dirpath, dirnames, filenames in os.walk(file):
                for filename in filenames:
                    expfiles.append(os.path.join(dirpath, filename))
        else:
            expfiles.append(file)

    for path in expfiles:
        if not os.path.exists(path):
            sys.stderr.write('%s: No such file or directory\n' % path)

    return expfiles
790173
def df2chucks(din,chunksize,outd,fn,return_fmt='\t',force=False):
    
    from os.path import exists#,splitext,dirname,splitext,basename,realpath
    from os import makedirs
    din.index=range(0,len(din),1)

    chunkrange=list(np.arange(0,len(din),chunksize))
    chunkrange=list(zip([c+1 if ci!=0 else 0 for ci,c in enumerate(chunkrange)],chunkrange[1:]+[len(din)-1]))

    chunk2range={}
    for ri,r in enumerate(chunkrange):    
        chunk2range[ri+1]=r

    if not exists(outd):
        makedirs(outd)
    chunks=[]
    chunkps=[]
    for chunk in chunk2range:
        chunkp='{}/{}_chunk{:08d}.tsv'.format(outd,fn,chunk)
        rnge=chunk2range[chunk]
        din_=din.loc[rnge[0]:rnge[1],:]
        if not exists(chunkp) or force:
            if return_fmt=='list':
                chunks.append(din_)
            else:
                din_.to_csv(chunkp,sep=return_fmt)
            del din_
        chunkps.append(chunkp)
    if return_fmt=='list':
        return chunks
    else:
        return chunkps
1237315
def do_ls(self, subcmd, opts, folder=""):
        
        client = MdClient(self.maildir, filesystem=self.filesystem)
        client.ls(
            foldername = folder, 
            stream = self.stdout, 
            reverse = getattr(opts, "reverse", False),
            grep = getattr(opts, "grep", None),
            field = getattr(opts, "field", None),
            since = float(getattr(opts, "since", -1))
            )
289965
def dir():
        
        dir = [
            'access', 'chdir', 'chmod', 'chown', 'close', 'fstat', 'fsync',
            'getcwd', 'lchmod', 'link', 'listdir', 'lstat', 'makedirs',
            'mkdir', 'mknod', 'open', 'read', 'readlink', 'remove',
            'removedirs', 'rename', 'rmdir', 'stat', 'symlink', 'umask',
            'unlink', 'utime', 'walk', 'write'
        ]
        if IS_PY2:
            dir += ['getcwdu']
        else:
            dir += ['getcwdb', 'replace']
            if sys.platform.startswith('linux'):
                dir += [
                    'fdatasync', 'getxattr', 'listxattr',
                    'removexattr', 'setxattr'
                ]
        if use_scandir:
            dir += ['scandir']
        return dir
1166073
def _get_folds(n_rows, n_folds, use_stored):
        
        # n_folds = self._n_folds
        # use_stored = self._use_stored_folds
        # n_rows = self._n_rows

        if use_stored is not None:
            # path = '~/concise/data-offline/lw-pombe/cv_folds_5.json'
            with open(os.path.expanduser(use_stored)) as json_file:
                json_data = json.load(json_file)

            # check if we have the same number of rows and folds:
            if json_data['N_rows'] != n_rows:
                raise Exception('N_rows from folds doesnt match the number of rows of X_seq, X_feat, y')

            if json_data['N_folds'] != n_folds:
                raise Exception('n_folds dont match', json_data['N_folds'], n_folds)

            kf = [(np.array(train), np.array(test)) for (train, test) in json_data['folds']]
        else:
            kf = KFold(n_splits=n_folds).split(np.zeros((n_rows, 1)))

        # store in a list
        i = 1
        folds = []
        for train, test in kf:
            fold = "fold_" + str(i)
            folds.append((fold, train, test))
            i = i + 1
        return folds
1129242
def put_str(content, path, share='C$', conn=None, host=None, username=None, password=None):
    '''
    
    '''
    if HAS_SMBPROTOCOL:
        return _put_str_smbprotocol(
            content, path, share, conn=conn, host=host,
            username=username, password=password
        )
    elif HAS_IMPACKET:
        return _put_str_impacket(
            content, path, share, conn=conn, host=host, username=username, password=password
        )
    raise MissingSmb("SMB library required (impacket or smbprotocol)")
1053939
def space_to_folders(self, current_result_list, current_query, param_space,
                         runs, current_directory):
        
        # Base case: we iterate over the runs and copy files in the final
        # directory.
        if not param_space:
            for run, r in enumerate(current_result_list[:runs]):
                files = self.db.get_result_files(r)
                new_dir = os.path.join(current_directory, "run=%s" % run)
                os.makedirs(new_dir, exist_ok=True)
                for filename, filepath in files.items():
                    shutil.copyfile(filepath, os.path.join(new_dir, filename))
            return

        [key, value] = list(param_space.items())[0]
        # Iterate over dictionary values
        for v in value:
            next_query = deepcopy(current_query)
            temp_query = deepcopy(current_query)

            # For each list, recur 'fixing' that dimension.
            next_query[key] = v  # Update query

            # Create folder
            folder_name = ("%s=%s" % (key, v)).replace('/', '_')
            new_dir = os.path.join(current_directory, folder_name)
            os.makedirs(new_dir, exist_ok=True)

            next_param_space = deepcopy(param_space)
            del(next_param_space[key])

            temp_query[key] = v
            temp_result_list = [r for r in current_result_list if
                                self.satisfies_query(r, temp_query)]

            self.space_to_folders(temp_result_list, next_query,
                                  next_param_space, runs, new_dir)
611676
def foldl(list, &block)
      return '' if list.empty?
      list[1..-1].inject(list.first, &block)
    end
178628
def _normalize_dir(string_):
    '''
    
    '''
    return os.path.normpath(salt.utils.stringutils.to_unicode(string_))
430183
def _commonprefix(files):
    
    out = os.path.commonprefix(files)
    out = out.rstrip("_R")
    out = out.rstrip("_I")
    out = out.rstrip("_")
    return out
1324354
def generate_dir_rst(dir, fhindex, example_dir, root_dir, plot_gallery):
    
    if not dir == '.':
        target_dir = os.path.join(root_dir, dir)
        src_dir = os.path.join(example_dir, dir)
    else:
        target_dir = root_dir
        src_dir = example_dir
    if not os.path.exists(os.path.join(src_dir, 'README.txt')):
        print('Example directory %s does not have a README.txt file' % src_dir)
        print('Skipping this directory')
        print(80 * '_')
        return
    fhindex.write("""


%s


""" % file(os.path.join(src_dir, 'README.txt')).read())
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    def sort_key(a):
        # put last elements without a plot
        if not a.startswith('plot') and a.endswith('.py'):
            return 'zz' + a
        return a

    fhindex.write("""

.. toctree::

""")
    for fname in sorted(os.listdir(src_dir), key=sort_key):
        if fname.endswith('py'):
            generate_file_rst(fname, target_dir, src_dir, plot_gallery)
            #thumb = os.path.join(dir, 'images', 'thumb', fname[:-3] + '.png')
            link_name = os.path.join(dir, fname).replace(os.path.sep, '_')
            #fhindex.write('.. figure:: %s\n' % thumb)
            #if link_name.startswith('._'):
            #    link_name = link_name[2:]
            #if dir != '.':
            #    fhindex.write('   :target: ./%s/%s.html\n\n' % (dir,
            #                                                   fname[:-3]))
            #else:
            #    fhindex.write('   :target: ./%s.html\n\n' % link_name[:-3])
            fhindex.write("""
   %s/%s
""" % (dir, fname[:-3]))
    fhindex.write("""

.. raw:: html

    <div style="clear: both"></div>
    """)