A candidate is viable if the `js` or the `xjs` file exists.

@param {array} candidates - Pathes of module files (without extension).
@returns {string} The first candidate if no module has been found.
12055
function getFirstViableCandidate(candidates) {
    for( const candidate of candidates) {
        const fileJS = `${candidate}.js`;
        if( Fs.existsSync(fileJS) ) return candidate;
        const fileXJS = `${candidate}.xjs`;
        if( Fs.existsSync(fileXJS) ) return candidate;
    }

    return candidates[0];
}
1258067
def candidate(cls):
        """"""
        return relationship(
            "Candidate",
            backref=backref(
                camel_to_under(cls.__name__) + "s",
                cascade="all, delete-orphan",
                cascade_backrefs=False,
            ),
            cascade_backrefs=False,
        )
574902
def find_all_candidates(self, project_name):
        # type: (str) -> List[Optional[InstallationCandidate]]
        
        index_locations = self._get_index_urls_locations(project_name)
        index_file_loc, index_url_loc = self._sort_locations(index_locations)
        fl_file_loc, fl_url_loc = self._sort_locations(
            self.find_links, expand_dir=True,
        )

        file_locations = (Link(url) for url in itertools.chain(
            index_file_loc, fl_file_loc,
        ))

        # We trust every url that the user has given us whether it was given
        #   via --index-url or --find-links.
        # We want to filter out any thing which does not have a secure origin.
        url_locations = [
            link for link in itertools.chain(
                (Link(url) for url in index_url_loc),
                (Link(url) for url in fl_url_loc),
            )
            if self._validate_secure_origin(logger, link)
        ]

        logger.debug('%d location(s) to search for versions of %s:',
                     len(url_locations), project_name)

        for location in url_locations:
            logger.debug('* %s', location)

        canonical_name = canonicalize_name(project_name)
        formats = self.format_control.get_allowed_formats(canonical_name)
        search = Search(project_name, canonical_name, formats)
        find_links_versions = self._package_versions(
            # We trust every directly linked archive in find_links
            (Link(url, '-f') for url in self.find_links),
            search
        )

        page_versions = []
        for page in self._get_pages(url_locations, project_name):
            try:
                logger.debug('Analyzing links from page %s', page.url)
            except AttributeError:
                continue
            with indent_log():
                page_versions.extend(
                    self._package_versions(page.iter_links(), search)
                )

        file_versions = self._package_versions(file_locations, search)
        if file_versions:
            file_versions.sort(reverse=True)
            logger.debug(
                'Local files found: %s',
                ', '.join([
                    url_to_path(candidate.location.url)
                    for candidate in file_versions
                ])
            )

        # This is an intentional priority ordering
        return file_versions + find_links_versions + page_versions
330078
function getScriptFromUrl(url, eligibleScripts) {
  var i,
      script = null;

  eligibleScripts = eligibleScripts || scripts;

  if (typeof url === "string" && url) {
    for (i = eligibleScripts.length; i--; ) {
      if (eligibleScripts[i].src === url) {
        // NOTE: Could check if the same script URL is used by more than one `script` element
        // here... but let's not. That would yield less useful results in "loose" detection. ;)
        script = eligibleScripts[i];
        break;
      }
    }
  }
  return script;
}
305038
function moduleExistsAtPath(modPath) {
	for (var i = 0; i < CODE_EXTENSIONS.length; i += 1) {
		var fileName = 'index' + CODE_EXTENSIONS[i];
		var filePath = path.join(modPath, fileName);

		if (fs.existsSync(filePath)) {
			return true;
		}
	}

	return false;
}
527801
function tryRequire (regexp) {
  const nodeModulesDir = getNodeModulesDir()
  const results = []

  debug(`arguments.regexp: ${regexp || 'undefined'}`)

  if (!regexp || !fs.existsSync(nodeModulesDir)) {
    debug('regexp is undefined or nodeModulesDir not exists')
    return results
  }

  const moduleList = getModulesByDir(nodeModulesDir)
    .filter(m => regexp.test(m))

  debug(`matched modules: ${moduleList.join(', ')}`)

  return moduleList
}
748626
function getArticle (candidates, $) {
  let topCandidate = null

  candidates.forEach(elem => {
    const linkDensity = getLinkDensity(elem, $)
    const siblings = elem.children('p').length
    const score = elem.data('readabilityScore')
    elem.data(
      'readabilityScore',
      Math.min(2, Math.max(siblings, 1)) * score * (1 - linkDensity)
    )
    if (
      !topCandidate ||
      elem.data('readabilityScore') > topCandidate.data('readabilityScore')
    ) {
      topCandidate = elem
    }
  })
  /**
   * If we still have no top candidate, just use the body as a last resort.
   * Should not happen.
   * */
  if (topCandidate === null) {
    return $('body')
  }

  // Perhaps the topCandidate is the parent?
  let parent
  if (
    !(parent = topCandidate.parent()) ||
    parent.length === 0 ||
    topCandidate.children('p').length > 5
  ) {
    return filterCandidates(topCandidate, topCandidate.children(), $)
  }
  return filterCandidates(topCandidate, parent.children(), $)
}
1207121
boolean match(String candidate) {
    char[] chars = candidate.toCharArray();
    int[] cursor = new int[] {0, chars.length};
    if (!checkPrefix(chars, cursor))
      return false;
    if (prefix == suffix && midClauses == null)
      // The pattern consists only of the prefix, which must exhaust the string
      return cursor[0] == cursor[1];
    if (!checkSuffix(chars, cursor))
      return false;
    return matchMiddle(chars, cursor[0], cursor[1]);
  }
1000235
def find_best_candidate(
        self,
        package_name,  # type: str
        target_package_version=None,  # type:  Union[str, None]
        allow_prereleases=False,  # type: bool
    ):  # type: (...) -> Union[Package, bool]
        
        if target_package_version:
            constraint = parse_constraint(target_package_version)
        else:
            constraint = parse_constraint("*")

        candidates = self._pool.find_packages(
            package_name, constraint, allow_prereleases=allow_prereleases
        )

        if not candidates:
            return False

        dependency = Dependency(package_name, constraint)

        # Select highest version if we have many
        package = candidates[0]
        for candidate in candidates:
            if candidate.is_prerelease() and not dependency.allows_prereleases():
                continue

            # Select highest version of the two
            if package.version < candidate.version:
                package = candidate

        return package
1121787
function() {
      this.candidates = []; // flush, if any
      for(var i=0;i<this.num_candidates;i++) {
        var cand = this.sampleCandidate();
        this.candidates.push(cand);
      }
    }
137565
function({options}, succeed, skip) {
    // Default to `options.target` if "true"
    if (typeof options.if_exists === 'boolean' && options.target) {
      options.if_exists = options.if_exists ? [options.target] : null;
    }
    return each(options.if_exists).call((if_exists, next) => {
      return this.fs.exists({
        target: if_exists
      }, (err, {exists}) => {
        if (exists) {
          this.log({
            message: `File exists ${if_exists}, continuing`,
            level: 'DEBUG',
            module: 'nikita/misc/conditions'
          });
          return next();
        } else {
          this.log({
            message: `File doesnt exists ${if_exists}, skipping`,
            level: 'INFO',
            module: 'nikita/misc/conditions'
          });
          return skip();
        }
      });
    }).next(succeed);
  }
176144
public List<StepCandidate> prioritise(String stepAsText, List<StepCandidate> candidates) {
        return prioritisingStrategy.prioritise(stepAsText, candidates);
    }
551901
public <T extends Type> T selectCandidate(T candidate, T next, T actual, Environment environment) {
		// Found a viable candidate
		boolean left = subtypeOperator.isSubtype(candidate, next, environment);
		boolean right = subtypeOperator.isSubtype(next, candidate, environment);
		if (left && !right) {
			// Yes, is better than current candidate
			return next;
		} else if (right && !left) {
			return candidate;
		}
		// Unable to distinguish options based on subtyping alone
		left = isDerivation(next, actual);
		right = isDerivation(candidate, actual);
		if (left && !right) {
			// Yes, is better than current candidate
			return next;
		} else if (right && !left) {
			return candidate;
		} else {
			return null;
		}

	}
1207573
function() {
        var candidates = this.layers || this.map.layers;
        var layers = [];
        var layer;
        for (var i=candidates.length-1; i>=0; --i) {
            layer = candidates[i];
            if (layer instanceof OpenLayers.Layer.WMTS &&
                layer.requestEncoding === this.requestEncoding &&
                (!this.queryVisible || layer.getVisibility())) {
                layers.push(layer);
                if (!this.drillDown || this.hover) {
                    break;
                }
            }
        }
        return layers;
    }
906302
function getSoleInlineScript(eligibleScripts) {
  var i, len,
      script = null;
  eligibleScripts = eligibleScripts || scripts;
  for (i = 0, len = eligibleScripts.length; i < len; i++) {
    if (!eligibleScripts[i].hasAttribute("src")) {
      if (script) {
        script = null;
        break;
      }
      script = eligibleScripts[i];
    }
  }
  return script;
}
250642
function () {
  /**
   * Get a valid file path for a template file from a set of directories
   * @param  {Object}   opts     Configurable options (see periodicjs.core.protocols for more details)
   * @param {string} [opts.extname] Periodic extension that may contain view file
   * @param {string} opts.viewname Name of the template file
   * @param {string} [opts.themefileext="periodicjs.theme.default"] Periodic theme that may contain view file
   * @param {string} [opts.viewfileext=".ejs"] File extension type
   * @param  {Function} callback Callback function
   * @return {Object}          Returns a Promise which resolves with file path if cb argument is not passed
   */
  let fn = function getPluginViewDefaultTemplate (opts = {}, callback) {
    let { extname, viewname, themefileext, viewfileext } = opts;
    let themename = this.theme;
    let fileext = (typeof themefileext === 'string') ? themefileext : viewfileext;
    return this._utility_responder.render({}, Object.assign(opts, { themename, fileext, resolve_filepath: true }), callback);
  };
  let message = 'CoreController.getPluginViewDefaultTemplate: Use CoreController.responder.render with a HTML adapter or CoreController._utility_responder.render instead';
  return wrapWithDeprecationWarning.call(this, fn, message);
}
390867
public Object findFirstMatch(Collection<?> source, Collection<?> candidates) {
		return CollectionUtils.findFirstMatch(source, candidates);
	}