organize all resource paths into N-ary tree
326593
function applyResource(resource, isMethod) {
      let root;
      let parent;
      let currentPath;
      const path = resource.path.replace(/^\//, '').replace(/\/$/, '');
      const pathParts = path.split('/');

      function applyNodeResource(node, parts, index) {
        const n = node;
        if (index === parts.length - 1) {
          n.name = resource.name;
          if (resource.resourceId) {
            n.resourceId = resource.resourceId;
            if (_.every(predefinedResourceNodes, (iter) => iter.path !== n.path)) {
              predefinedResourceNodes.push(node);
            }
          }
          if (isMethod && !node.hasMethod) {
            n.hasMethod = true;
            if (_.every(methodNodes, (iter) => iter.path !== n.path)) {
              methodNodes.push(node);
            }
          }
        }

        parent = node;
      }

      pathParts.forEach((pathPart, index) => {
        currentPath = currentPath ? `${currentPath}/${pathPart}` : pathPart;
        root = root || _.find(trees, (node) => node.path === currentPath);
        parent = parent || root;

        let node;
        if (parent) {
          if (parent.path === currentPath) {
            applyNodeResource(parent, pathParts, index);
            return;
          } else if (parent.children.length > 0) {
            node = _.find(parent.children, (n) => n.path === currentPath);
            if (node) {
              applyNodeResource(node, pathParts, index);
              return;
            }
          }
        }

        node = {
          path: currentPath,
          pathPart,
          parent,

          level: index,
          children: [],
        };

        if (parent) {
          parent.children.push(node);
        }

        if (!root) {
          root = node;
          trees.push(root);
        }

        applyNodeResource(node, pathParts, index);
      });
    }
1226873
function _expandNestedPaths(paths) {
  var expandedPaths = [];

  _pathsArray(paths).forEach(function (p) {
    if (p.indexOf('.') !== -1) {
      var pathsWithRoots = p.split('.').map(function (value, index, array) {
        return array.slice(0, index + 1).join('.');
      });

      expandedPaths = expandedPaths.concat(pathsWithRoots);
    } else {
      expandedPaths.push(p);
    }
  });

  return expandedPaths;
}
679749
def build_dir_tree(self, files):
        

        def helper(split_files):
            this_dir = {'files' : {}, 'dirs' : {}}
            dirs = defaultdict(list)

            for fle in split_files:
                index = fle[0]; fileinfo = fle[1]
                if len(index)  == 1:
                    fileinfo['path'] = index[0] # store only the file name instead of the whole path
                    this_dir['files'][fileinfo['path']] = fileinfo
                elif len(index) > 1:
                    dirs[index[0]].append((index[1:], fileinfo))

            for name,info in dirs.iteritems():
                this_dir['dirs'][name] = helper(info)
            return this_dir
        return helper([(name.split('/')[1:], file_info) for name, file_info in files.iteritems()])
967236
def build_tree_raxml(self,
                   new_path    = None,
                   seq_type    = 'nucl' or 'prot',
                   num_threads = None,
                   free_cores  = 2,
                   keep_dir    = False):
        """"""
        # Check output #
        if new_path is None: new_path = self.prefix_path + '.tree'
        # What model to choose #
        if seq_type == 'nucl': model = "GTRGAMMA"
        if seq_type == 'prot': model = "PROTGAMMAJTTF"
        # Threads #
        if num_threads is None: num_threads = multiprocessing.cpu_count() - free_cores
        else:                   num_threads = int(num_threads) - free_cores
        num_threads = max(1, num_threads)
        # Run it #
        temp_dir = new_temp_dir()
        sh.raxml811('-m', model, "-T", num_threads, '-p', 1, '-s', self.path, '-n', 'tree', '-w', temp_dir, '-f', 'a', '-x', 1, '-N', 'autoMR')
        # Move into place #
        if keep_dir:
            shutil.rmtree(new_path)
            shutil.move(temp_dir, new_path)
        if not keep_dir:
            shutil.move(temp_dir + 'RAxML_bestTree.tree', new_path)
        # Return #
        return FilePath(new_path)
577300
private List<Resource> resourcesOf(JsonNode resourceNodes) {
        List<Resource> resources = new LinkedList<Resource>();

        if (resourceNodes.isArray()) {
            for (JsonNode resource : resourceNodes) {
                resources.add(new Resource(resource.asText()));
            }
        } else {
            resources.add(new Resource(resourceNodes.asText()));
        }

        return resources;
    }
1168661
def dirtree(path):
    
    results = []
    for name in glob.glob(os.path.join(path, '*')):
        results.append(name)
        if os.path.isdir(name):
            results.extend(dirtree(name))
    return results
265026
def _enumerate_paths(self, prefix_path):
        
        for branch in self.branches:
            path = [prefix_path, branch]
            if branch.child_branchset is not None:
                for subpath in branch.child_branchset._enumerate_paths(path):
                    yield subpath
            else:
                yield path
107620
def index(**params)
      params.stringify_keys!
      path = nest_path_within_parent(plural_resource_path, params)
      api_request(:get, path, params: params)
    end
834815
public void consolidateMultiplePaths() {
        Map<String, Set<ResourceMethod>> oldResources = resources;
        resources = new HashMap<>();

        oldResources.keySet().forEach(s -> consolidateMultipleMethodsForSamePath(s, oldResources.get(s)));
    }
539691
def rmtree(path, ignore_errors=False, onerror=None):
    """"""
    if ignore_errors:
        def onerror(*args):
            pass
    elif onerror is None:
        def onerror(*args):
            raise
    for root, dirs, unused_files in os.walk(path):
        for directory in dirs:
            try:
                abs_directory = os.path.join(root, directory)
                os.chmod(abs_directory, stat.S_IRWXU)
            except EnvironmentError as e:
                onerror(os.chmod, abs_directory, e)
    shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror)
718885
def walk_resources(package_or_requirement, resource_name, recurse=True, base=''):
    
    base = base.rstrip('/') + '/'
    resource_base = (resource_name.rstrip('/') + '/' + base.strip('/')).rstrip('/')

    # Create default configuration files
    for filename in pymagic.resource_listdir(package_or_requirement, resource_base):
        # Skip hidden and other trashy names
        if filename.startswith('.') or any(filename.endswith(i) for i in (".pyc", ".pyo", "~")):
            continue

        # Handle subdirectories
        if pymagic.resource_isdir(package_or_requirement, resource_base + '/' + filename):
            if recurse:
                for i in walk_resources(package_or_requirement, resource_name, recurse, base=base + filename):
                    yield i
        else:
            yield base + filename
180436
def rmdir(path, recursive=True, **kwargs):
    """"""
    if recursive:
        import shutil
        return shutil.rmtree(path, **kwargs)
    else:
        import os
        return os.remdir(path, **kwargs)
729752
def map_tree(visitor, tree):
    """"""
    newn = [map_tree(visitor, node) for node in tree.nodes]
    return visitor(tree, newn)
632173
def iter_tree(jottapath, JFS):
    """"""
    filedirlist = JFS.getObject('%s?mode=list' % jottapath)
    log.debug("got tree: %s", filedirlist)
    if not isinstance(filedirlist, JFSFileDirList):
        yield ( '', tuple(), tuple() )
    for path in filedirlist.tree:
        yield path
112069
def recurse_tree(rootpath, excludes, opts):
    # type: (unicode, List[unicode], Any) -> List[unicode]
    
    if INITPY in os.listdir(rootpath):
        path_prefix = path.sep.join(rootpath.split(path.sep)[:-1])
    else:
        path_prefix = rootpath

    toplevels = []
    followlinks = getattr(opts, 'followlinks', False)
    includeprivate = getattr(opts, 'includeprivate', False)
    implicit_namespaces = getattr(opts, 'implicit_namespaces', False)
    for root, subs, files in walk(rootpath, followlinks=followlinks):
        # document only Python module files (that aren't excluded)
        py_files = sorted(f for f in files
                          if path.splitext(f)[1] in PY_SUFFIXES and
                          not is_excluded(path.join(root, f), excludes))
        is_pkg = INITPY in py_files
        if is_pkg:
            py_files.remove(INITPY)
            py_files.insert(0, INITPY)
        elif root != rootpath:
            # only accept non-package at toplevel unless using implicit
            # namespaces
            if not implicit_namespaces:
                del subs[:]
                continue
        # remove hidden ('.') and private ('_') directories, as well as
        # excluded dirs
        if includeprivate:
            exclude_prefixes = ('.',)  # type: Tuple[unicode, ...]
        else:
            exclude_prefixes = ('.', '_')
        subs[:] = sorted(sub for sub in subs
                         if not sub.startswith(exclude_prefixes) and
                         not is_excluded(path.join(root, sub), excludes))

        pkg = root[len(path_prefix):].lstrip(path.sep).replace(path.sep, '.')
        for py_file in py_files:
            if not shall_skip(path.join(root, py_file), opts):
                if py_file == INITPY:
                    module = ''
                else:
                    module = path.splitext(py_file)[0]
                toplevels.append(makename(pkg, module))

    return toplevels
566945
def get_resource_siblings(raml_resource):
    
    path = raml_resource.path
    return [res for res in raml_resource.root.resources
            if res.path == path]
194209
def update_resources(Cnt):
    '''
    '''

    # list of path names which will be saved
    key_list = ['PATHTOOLS', 'RESPATH', 'REGPATH', 'DCM2NIIX', 'HMUDIR']

    # get the local path to NiftyPET resources.py
    path_resources = cs.path_niftypet_local()
    resources_file = os.path.join(path_resources,'resources.py')

    # update resources.py
    if os.path.isfile(resources_file):
        f = open(resources_file, 'r')
        rsrc = f.read()
        f.close()
        # get the region of keeping in synch with Python
        i0 = rsrc.find('### start NiftyPET tools ###')
        i1 = rsrc.find('### end NiftyPET tools ###')
        pth_list = []
        for k in key_list:
            if k in Cnt:
                pth_list.append('\'' + Cnt[k].replace("\\","/") + '\'')
            else:
                pth_list.append('\'\'')

        # modify resources.py with the new paths
        strNew = '### start NiftyPET tools ###\n'
        for i in range(len(key_list)):
            if pth_list[i] != '\'\'':
                strNew += key_list[i]+' = '+pth_list[i] + '\n'
        rsrcNew = rsrc[:i0] + strNew + rsrc[i1:]
        f = open(resources_file, 'w')
        f.write(rsrcNew)
        f.close()

    return Cnt