Determine if the link contains a sheet reference and change some of the
 parameters accordingly.
 Split the dir name and sheet name (if it exists)
967720
def analyze_link(url, absolute = nil)  # :nodoc:
    dir_long , sheet = url.split(/\#/)
    link_type = absolute ? (0x01 | absolute) : 0x0103

    if sheet
      link_type |= 0x08
      sheet_len  = [sheet.bytesize + 0x01].pack("V")
      sheet      = sheet.split('').join("\0") + "\0\0\0"
    else
      sheet_len   = ''
      sheet       = ''
    end

    [dir_long, link_type, sheet_len, sheet]
  end
434206
def merge(self, other):
        ''''''
        assert self.refnames == other.refnames
        assert self.dirs == other.dirs
        assert self.lengths == other.lengths

        for i in range(2):
            if self.pos[i] is None:
                if other.pos[i] is None:
                   raise Error('Error merging these two links:\n' + str(self) + '\n' + str(other))
                self.pos[i] = other.pos[i]
            else:
                if other.pos[i] is not None:
                   raise Error('Error merging these two links:\n' + str(self) + '\n' + str(other))
246222
def _relIndexLink(self):
        """"""
        return os.path.join("..", os.path.basename(self.pathname), "index.html")
576129
function(sheets) {
		var sheet = sheets.shift();
		if (sheet) {
			w(sheet);
			var isLess = (sheet.slice(-4) == "less");
			if (isLess && (opt.less !== undefined)) {
				sheet = sheet.slice(0, sheet.length-4) + "css";
				isLess = false;
				w(" (Substituting CSS: " + sheet + ")");
			}
			var code = fs.readFileSync(sheet, "utf8");
			if (isLess) {
				var parser = new(less.Parser)({filename:sheet, paths:[path.dirname(sheet)]});
				parser.parse(code, function (err, tree) {
					if (err) {
						console.error(err);
					} else {
						addToBlob(sheet, tree.toCSS());
					}
					readAndParse(sheets);
				});
			} else {
				addToBlob(sheet, code);
				readAndParse(sheets);
			}
		} else {
			doneCB(blob);
		}
	}
209184
def is_dir_url(link):
    # type: (Link) -> bool
    
    link_path = url_to_path(link.url_without_fragment)
    return os.path.isdir(link_path)
361119
def setuptools_install_options(local_storage_folder):
    
    if local_storage_folder is None:
        return []
    # setuptools expects its find-links parameter to contain a list of link
    # sources (either local paths, file: URLs pointing to folders or URLs
    # pointing to a file containing HTML links) separated by spaces. That means
    # that, when specifying such items, whether local paths or URLs, they must
    # not contain spaces. The problem can be worked around by using a local
    # file URL, since URLs can contain space characters encoded as '%20' (for
    # more detailed information see below).
    #
    # Any URL referencing a folder needs to be specified with a trailing '/'
    # character in order for setuptools to correctly recognize it as a folder.
    #
    # All this has been tested using Python 2.4.3/2.4.4 & setuptools 1.4/1.4.2
    # as well as Python 3.4 & setuptools 3.3.
    #
    # Supporting paths with spaces - method 1:
    # ----------------------------------------
    # One way would be to prepare a link file and pass an URL referring to that
    # link file. The link file needs to contain a list of HTML link tags
    # (<a href="..."/>), one for every item stored inside the local storage
    # folder. If a link file references a folder whose name matches the desired
    # requirement name, it will be searched recursively (as described in method
    # 2 below).
    #
    # Note that in order for setuptools to recognize a local link file URL
    # correctly, the file needs to be named with the '.html' extension. That
    # will cause the underlying urllib2.open() operation to return the link
    # file's content type as 'text/html' which is required for setuptools to
    # recognize a valid link file.
    #
    # Supporting paths with spaces - method 2:
    # ----------------------------------------
    # Another possible way is to use an URL referring to the local storage
    # folder directly. This will cause setuptools to prepare and use a link
    # file internally - with its content read from a 'index.html' file located
    # in the given local storage folder, if it exists, or constructed so it
    # contains HTML links to all top-level local storage folder items, as
    # described for method 1 above.
    if " " in local_storage_folder:
        find_links_param = utility.path_to_URL(local_storage_folder)
        if find_links_param[-1] != "/":
            find_links_param += "/"
    else:
        find_links_param = local_storage_folder
    return ["-f", find_links_param, "--allow-hosts=None"]
364657
def reference_to_path(reference):
    """"""
    # Try to pop the options off whatever they passed in.
    if isinstance(reference, basestring):
        # This is an object path name in str form.
        import re
        if not re.match(r'^[^\d\W]([a-zA-Z._]|((?<!\.)\d))+$', reference):
            raise errors.BadObjectPathError(
                'Invalid reference path, must meet Python\'s identifier '
                'requirements, passed value was "%s".', reference)
        return reference

    if callable(reference):
        # This is a function or a class.
        # Try to figure out the path to the reference.
        parts = [reference.__module__]
        if hasattr(reference, 'im_class'):
            parts.append(reference.im_class.__name__)

        if hasattr(reference, 'func_name'):
            parts.append(reference.func_name)
        elif reference.__module__ == '__builtin__':
            return reference.__name__
        elif hasattr(reference, '__name__'):
            # Probably a class
            parts.append(reference.__name__)
        else:
            raise errors.BadObjectPathError("Invalid object type.")

        return '.'.join(parts)

        raise errors.BadObjectPathError("Unable to determine path to callable.")

    elif hasattr(reference, '__package__'):
        # This is probably a module.
        return reference.__name__

    raise errors.BadObjectPathError("Must provide a reference path or reference.")
1043578
@Nullable
  private DirectoryEntry lookUpLast(
      @Nullable File dir, Name name, Set<? super LinkOption> options, int linkDepth)
      throws IOException {
    Directory directory = toDirectory(dir);
    if (directory == null) {
      return null;
    }

    DirectoryEntry entry = directory.get(name);
    if (entry == null) {
      return new DirectoryEntry(directory, name, null);
    }

    File file = entry.file();
    if (!options.contains(LinkOption.NOFOLLOW_LINKS) && file.isSymbolicLink()) {
      return followSymbolicLink(dir, (SymbolicLink) file, linkDepth);
    }

    return getRealEntry(entry);
  }
1368458
def has_split(self, split_name):
        
        if os.path.exists(os.path.join(self.split_dir, split_name)):
            return True
        return False
312261
function findPages(
  options = {},
  directory = path.resolve(__dirname, '../../../../pages'),
  pages = [],
) {
  fs.readdirSync(directory).forEach(item => {
    const itemPath = path.resolve(directory, item);
    const pathname = itemPath
      .replace(new RegExp(`\\${path.sep}`, 'g'), '/')
      .replace(/^.*\/pages/, '')
      .replace('.js', '')
      .replace(/^\/index$/, '/') // Replace `index` by `/`.
      .replace(/\/index$/, '');

    if (pathname.indexOf('.eslintrc') !== -1) {
      return;
    }

    if (
      options.front &&
      pathname.indexOf('/components') === -1 &&
      pathname.indexOf('/api') === -1
    ) {
      return;
    }

    if (fs.statSync(itemPath).isDirectory()) {
      const children = [];
      pages.push({
        pathname,
        children,
      });
      findPages(options, itemPath, children);
      return;
    }

    if (!jsRegex.test(item) || blackList.includes(pathname)) {
      return;
    }

    pages.push({
      pathname,
    });
  });

  // sort by pathnames without '-' so that e.g. card comes before card-action
  pages.sort((a, b) => {
    const pathnameA = a.pathname.replace(/-/g, '');
    const pathnameB = b.pathname.replace(/-/g, '');
    if (pathnameA < pathnameB) return -1;
    if (pathnameA > pathnameB) return 1;
    return 0;
  });

  return pages;
}
791671
function fixLink (name, str) {
  /* In 6.x some API start with `xpack.` when in master they do not. We
   * can safely ignore that for link generation. */
  name = name.replace(/^xpack\./, '')
  const override = LINK_OVERRIDES[name]
  if (override) return override
  if (!str) return ''
  /* Replace references to the guide with the attribute {ref} because
   * the json files in the Elasticsearch repo are a bit of a mess. */
  str = str.replace(/^.+guide\/en\/elasticsearch\/reference\/[^/]+\/([^./]*\.html(?:#.+)?)$/, '{ref}/$1')
  str = str.replace(/frozen\.html/, 'freeze-index-api.html')
  str = str.replace(/ml-file-structure\.html/, 'ml-find-file-structure.html')
  str = str.replace(/security-api-get-user-privileges\.html/, 'security-api-get-privileges.html')

  return str
}
285979
def updateLink(page, lnk):
    
    CheckParent(page)
    annot = getLinkText(page, lnk)
    if annot == "":
        raise ValueError("link kind not supported")

    page.parent._updateObject(lnk["xref"], annot, page = page) 
    return
1201513
def getrmlsthelper(referencefilepath, update, start):
    
    from subprocess import call
    analysistype = 'rMLST'
    # Folders are named based on the download date e.g 2016-04-26
    # Find all folders (with the trailing / in the glob search) and remove the trailing /
    lastfolder = sorted(glob('{}{}/*/'.format(referencefilepath, analysistype)))[-1].rstrip('/')
    # lastfolder = os.path.join(referencefilepath, analysistype)
    delta, foldersize, d1 = schemedate(lastfolder)
    # Extract the path of the current script from the full path + file name
    homepath = os.path.split(os.path.abspath(__file__))[0]
    # Set the path/name of the folder to contain the new alleles and profile
    newfolder = os.path.join(referencefilepath, analysistype, str(d1))
    # System call
    rmlstupdatecall = 'cd {} && perl {}/rest_auth.pl -a {}/secret.txt'.format(newfolder, homepath, homepath)
    if update:
        if delta.days > 7 or foldersize < 100:
            printtime("Last update of rMLST profile and alleles was {} days ago. Updating".format(str(delta.days)),
                      start)
            # Create the path
            make_path(newfolder)
            # Copy over the access token to be used in the authentication
            shutil.copyfile('{}/access_token'.format(homepath), '{}/access_token'.format(newfolder))
            # Run rest_auth.pl
            call(rmlstupdatecall, shell=True)
            # Get the new alleles into a list, and create the combinedAlleles file
            alleles = glob('{}/*.tfa'.format(newfolder))
            combinealleles(start, newfolder, alleles)
        # If the profile and alleles are up-to-date, set :newfolder to :lastfolder
        else:
            newfolder = lastfolder
        # Ensure that the profile/alleles updated successfully
        # Calculate the size of the folder by adding the sizes of all the files within the folder together
        newfoldersize = sum(os.path.getsize('{}/{}'.format(newfolder, f)) for f in os.listdir(newfolder)
                            if os.path.isfile('{}/{}'.format(newfolder, f)))
        # If the profile/allele failed, remove the folder, and use the most recent update
        if newfoldersize < 100:
            shutil.rmtree(newfolder)
            newfolder = sorted(glob('{}{}/*/'.format(referencefilepath, analysistype)))[-1].rstrip('/')
    # Don't update the profile/alleles if not requested
    else:
        newfolder = lastfolder
    # Return the system call and the folder containing the profile and alleles
    return rmlstupdatecall, newfolder
132469
def __getSheet(self, name):
        '''  '''
        if not self.sheetExsit(name):
            raise UfException(Errors.SHEET_NAME_INVALID, "Can't find a sheet named %s" % name)

        return self.__sheetNameDict[name]
127132
def sheet_collection(sheetarr, options)
      if options[:include].nil?; options[:include]=[]; end
      if options[:include].to_a.size>0
        sheetarr.keep_if{|item| options[:include].to_a.detect{|d| d==item}}
      end
      sheetarr=sheetarr-options[:exclude].to_a
      @sheets.keep_if{|item| sheetarr.detect{|d| d==item[:name]}}
      @sheets.uniq!
    end
571488
@Nullable
  private DirectoryEntry lookUp(
      File dir, Iterable<Name> names, Set<? super LinkOption> options, int linkDepth)
      throws IOException {
    Iterator<Name> nameIterator = names.iterator();
    Name name = nameIterator.next();
    while (nameIterator.hasNext()) {
      Directory directory = toDirectory(dir);
      if (directory == null) {
        return null;
      }

      DirectoryEntry entry = directory.get(name);
      if (entry == null) {
        return null;
      }

      File file = entry.file();
      if (file.isSymbolicLink()) {
        DirectoryEntry linkResult = followSymbolicLink(dir, (SymbolicLink) file, linkDepth);

        if (linkResult == null) {
          return null;
        }

        dir = linkResult.fileOrNull();
      } else {
        dir = file;
      }

      name = nameIterator.next();
    }

    return lookUpLast(dir, name, options, linkDepth);
  }
188715
def run_has_samplesheet(fc_dir, config, require_single=True):
    
    fc_name, _ = flowcell.parse_dirname(fc_dir)
    sheet_dirs = config.get("samplesheet_directories", [])
    fcid_sheet = {}
    for ss_dir in (s for s in sheet_dirs if os.path.exists(s)):
        with utils.chdir(ss_dir):
            for ss in glob.glob("*.csv"):
                fc_ids = _get_flowcell_id(ss, require_single)
                for fcid in fc_ids:
                    if fcid:
                        fcid_sheet[fcid] = os.path.join(ss_dir, ss)
    # difflib handles human errors while entering data on the SampleSheet.
    # Only one best candidate is returned (if any). 0.85 cutoff allows for
    # maximum of 2 mismatches in fcid

    potential_fcids = difflib.get_close_matches(fc_name, fcid_sheet.keys(), 1, 0.85)
    if len(potential_fcids) > 0 and potential_fcids[0] in fcid_sheet:
        return fcid_sheet[potential_fcids[0]]
    else:
        return None