Look for linux executables in 3 ways
1. Look into CHROME_PATH env variable
2. Look into the directories where .desktop are saved on gnome based distro's
3. Look for google-chrome-stable & google-chrome executables by using the which command
351705
function linux(canary) {
  let installations = [];

  // Look into the directories where .desktop are saved on gnome based distro's
  const desktopInstallationFolders = [
    path.join(require('os').homedir(), '.local/share/applications/'),
    '/usr/share/applications/',
  ];
  desktopInstallationFolders.forEach(folder => {
    installations = installations.concat(findChromeExecutables(folder));
  });

  // Look for google-chrome(-stable) & chromium(-browser) executables by using the which command
  const executables = [
    'google-chrome-stable',
    'google-chrome',
    'chromium-browser',
    'chromium',
  ];
  executables.forEach(executable => {
    try {
      const chromePath =
          execFileSync('which', [executable], {stdio: 'pipe'}).toString().split(newLineRegex)[0];
      if (canAccess(chromePath))
        installations.push(chromePath);
    } catch (e) {
      // Not installed.
    }
  });

  if (!installations.length)
    throw new Error('The environment variable CHROME_PATH must be set to executable of a build of Chromium version 54.0 or later.');

  const priorities = [
    {regex: /chrome-wrapper$/, weight: 51},
    {regex: /google-chrome-stable$/, weight: 50},
    {regex: /google-chrome$/, weight: 49},
    {regex: /chromium-browser$/, weight: 48},
    {regex: /chromium$/, weight: 47},
  ];

  if (process.env.CHROME_PATH)
    priorities.unshift({regex: new RegExp(`${process.env.CHROME_PATH}`), weight: 101});

  return sort(uniq(installations.filter(Boolean)), priorities)[0];
}
74433
def find_command(cmd, paths = [])
      exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
      paths += ENV['PATH'].split(File::PATH_SEPARATOR)
      paths.each do |path|
        exts.each do |ext|
          exe = File.join(path, "#{cmd}#{ext}")
          if (File.executable?(exe) && File.file?(exe))
            return Shellwords.escape exe
          end
        end
      end
      nil
    end
1148531
function getNpmPath() {
    if (!_npmPath) {
        try {
            if (os.platform() === 'win32') {
                // We're on Windows
                const whereOutput = childProcess.execSync('where npm', { stdio: [] }).toString();
                const lines = whereOutput.split(os.EOL).filter((line) => !!line);
                // take the last result, we are looking for a .cmd command
                // see https://github.com/Microsoft/web-build-tools/issues/759
                _npmPath = lines[lines.length - 1];
            }
            else {
                // We aren't on Windows - assume we're on *NIX or Darwin
                _npmPath = childProcess.execSync('which npm', { stdio: [] }).toString();
            }
        }
        catch (e) {
            throw new Error(`Unable to determine the path to the NPM tool: ${e}`);
        }
        _npmPath = _npmPath.trim();
        if (!fs.existsSync(_npmPath)) {
            throw new Error('The NPM executable does not exist');
        }
    }
    return _npmPath;
}
570549
def _find_executables(self):
        
        if len(self.needs) > 0:
            return
        
        for execname, executable in list(self.module.executables.items()):
            skip = False
            #At the moment we can't handle executables that use special derived types.
            if not execname in self.module.publics or not executable.primitive:
                msg.info("Skipping {}.{} because it is not public.".format(self.module.name, execname))
                skip = True
            #Check that all the parameters have intent specified, otherwise we won't handle them well.ha
            if any([p.direction == "" for p in executable.ordered_parameters]):
                msg.warn("Some parameters in {}.{} have no intent".format(self.module.name, execname) +
                         " specified. Can't wrap that executable.")
                skip = True
    
            if not skip:
                self.uses.append(execname)
                for depmod in executable.search_dependencies():
                    if depmod not in self.needs:
                        self.needs.append(depmod)
194202
def find_executable(filename, environ=None):
    """"""
    if environ is None:
        environ = os.environ
    path = environ.get("PATH", "/usr/local/bin:/usr/bin:/bin").split(":")
    for dirpath in path:
        dirpath = os.path.abspath(dirpath.strip())
        filepath = os.path.normpath(os.path.join(dirpath, filename))
        if os.path.exists(filepath):
            return filepath
    return None
111064
def find_executable(executable):
    '''
    
    '''
    logger = logging.getLogger(__name__)
    logger.debug("Checking executable '%s'...", executable)
    executable_path = _find_executable(executable)
    found = executable_path is not None
    if found:
        logger.debug("Executable '%s' found: '%s'", executable, executable_path)
    else:
        logger.debug("Executable '%s' not found", executable)
    return executable_path
58021
def find_cygwin_executables(cls):
        
        exe_paths = glob.glob(cls.cygwin_path + r'\*.exe')
        # print cls.cygwin_path
        # list all *.exe in  cygwin path, use glob
        for c in exe_paths:
            exe = c.split('\\')
            name = exe[1].split('.')[0]
            # command['windows'][name] = "{:}\{:}.exe".format(cygwin_path, c)
            cls.command['windows'][name] = c
1041589
def find_executable(name):
    
    for pt in os.environ.get('PATH', '').split(':'):
        candidate = os.path.join(pt, name)
        if os.path.exists(candidate):
            return candidate
75060
def find_lib_path():
    
    lib_from_env = os.environ.get('MXNET_LIBRARY_PATH')
    if lib_from_env:
        if os.path.isfile(lib_from_env):
            if not os.path.isabs(lib_from_env):
                logging.warning("MXNET_LIBRARY_PATH should be an absolute path, instead of: %s",
                                lib_from_env)
            else:
                if os.name == 'nt':
                    os.environ['PATH'] = os.environ['PATH'] + ';' + os.path.dirname(lib_from_env)
                return [lib_from_env]
        else:
            logging.warning("MXNET_LIBRARY_PATH '%s' doesn't exist", lib_from_env)

    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
    api_path = os.path.join(curr_path, '../../lib/')
    cmake_build_path = os.path.join(curr_path, '../../build/')
    dll_path = [curr_path, api_path, cmake_build_path]
    if os.name == 'nt':
        dll_path.append(os.path.join(curr_path, '../../build'))
        vs_configuration = 'Release'
        if platform.architecture()[0] == '64bit':
            dll_path.append(os.path.join(curr_path, '../../build', vs_configuration))
            dll_path.append(os.path.join(curr_path, '../../windows/x64', vs_configuration))
        else:
            dll_path.append(os.path.join(curr_path, '../../build', vs_configuration))
            dll_path.append(os.path.join(curr_path, '../../windows', vs_configuration))
    elif os.name == "posix" and os.environ.get('LD_LIBRARY_PATH', None):
        dll_path[0:0] = [p.strip() for p in os.environ['LD_LIBRARY_PATH'].split(":")]
    if os.name == 'nt':
        os.environ['PATH'] = os.path.dirname(__file__) + ';' + os.environ['PATH']
        dll_path = [os.path.join(p, 'libmxnet.dll') for p in dll_path]
    elif platform.system() == 'Darwin':
        dll_path = [os.path.join(p, 'libmxnet.dylib') for p in dll_path] + \
                   [os.path.join(p, 'libmxnet.so') for p in dll_path]
    else:
        dll_path.append('../../../')
        dll_path = [os.path.join(p, 'libmxnet.so') for p in dll_path]
    lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]
    if len(lib_path) == 0:
        raise RuntimeError('Cannot find the MXNet library.\n' +
                           'List of candidates:\n' + str('\n'.join(dll_path)))
    if os.name == 'nt':
        os.environ['PATH'] = os.environ['PATH'] + ';' + os.path.dirname(lib_path[0])
    return lib_path
422368
def win_find_exe(filename, installsubdir=None, env="ProgramFiles"):
    """"""
    for fn in [filename, filename+".exe"]:
        try:
            if installsubdir is None:
                path = _where(fn)
            else:
                path = _where(fn, dirs=[os.path.join(os.environ[env], installsubdir)])
        except IOError:
            path = filename
        else:
            break        
    return path
1176070
def __find_executables(path):
    

    success = False
    progs = {
        "dot": "",
        "twopi": "",
        "neato": "",
        "circo": "",
        "fdp": "",
        "sfdp": "",
    }

    was_quoted = False
    path = path.strip()
    if path.startswith('"') and path.endswith('"'):
        path = path[1:-1]
        was_quoted = True

    if not os.path.isdir(path):
        return None

    for prg in progs:
        if progs[prg]:
            continue

        prg_path = os.path.join(path, prg)
        prg_exe_path = prg_path + ".exe"

        if os.path.exists(prg_path):
            if was_quoted:
                prg_path = "\"{}\"".format(prg_path)
            progs[prg] = prg_path
            success = True

        elif os.path.exists(prg_exe_path):
            if was_quoted:
                prg_exe_path = "\"{}\"".format(prg_exe_path)
            progs[prg] = prg_exe_path
            success = True

    if success:
        return progs

    return None
589891
def find_executables
      return enum_for(:find_executables) unless block_given?

      exts = (ENV.has_key?('PATHEXT') ? ENV.fetch('PATHEXT').split(';') : []) << ''
      paths = @path.sub('*', ENV['PATH']).split(File::PATH_SEPARATOR)
      raise ArgumentError.new('No PATH to search!') if paths.empty?
      cmds = strict? ? @executables.first(1) : @executables

      lookup_cache = Set.new
      cmds.product(paths, exts).map do |cmd, path, ext|
        exe = File.absolute_path?(cmd) ? cmd : File.expand_path("#{cmd}#{ext}", path)

        next unless lookup_cache.add?(exe) # don't yield the same exe path 2x
        next unless File.executable?(exe)
        next if File.directory?(exe)

        yield exe
      end
    end
1134388
def _findSwiplDar():
    

    # If the exec is in path
    (path, swiHome) = _findSwiplFromExec()
    if path is not None:
        return (path, swiHome)

    # If it is not, use  find_library
    path = _findSwiplPathFromFindLib()
    if path is not None:
        return (path, swiHome)

    # Last guess, searching for the file
    paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
    names = ['libswipl.dylib', 'libpl.dylib']

    for name in names:
        for path in paths:
            path = os.path.join(path, name)
            if os.path.exists(path):
                return (path, None)

    return (None, None)
721779
def which(fname):
    """"""
    if "PATH" not in os.environ or not os.environ["PATH"]:
        path = os.defpath
    else:
        path = os.environ["PATH"]

    for p in [fname] + [os.path.join(x, fname) for x in path.split(os.pathsep)]:
        p = os.path.abspath(p)
        if os.access(p, os.X_OK) and not os.path.isdir(p):
            return p

    p = sp.Popen("locate %s" % fname, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
    (stdout, stderr) = p.communicate()
    if not stderr:
        for p in stdout.decode().split("\n"):
            if (os.path.basename(p) == fname) and (
                os.access(p, os.X_OK)) and (
                not os.path.isdir(p)):
                return p
214447
def _check_apt_get():
    """"""
    check = False
    if 'TESTING' not in os.environ:
        result = exec_command(['dpkg', '-l', 'apio'])
        if result and result.get('returncode') == 0:
            match = re.findall('rc\s+apio', result.get('out')) + \
                    re.findall('ii\s+apio', result.get('out'))
            check = len(match) > 0
    return check
1034731
async function main() {
  // Initialize the application.
  process.title = 'Which.js';

  // Parse the command line arguments.
  program.name('which')
    .description('Find the instances of an executable in the system path.')
    .version(packageVersion, '-v, --version')
    .option('-a, --all', 'list all instances of executables found (instead of just the first one)')
    .option('-s, --silent', 'silence the output, just return the exit code (0 if any executable is found, otherwise 1)')
    .arguments('<command>').action(command => program.executable = command)
    .parse(process.argv);

  if (!program.executable) {
    program.outputHelp();
    process.exitCode = 64;
    return;
  }

  // Run the program.
  let executables = await which(program.executable, {all: program.all});
  if (!program.silent) {
    if (!Array.isArray(executables)) executables = [executables];
    for (const path of executables) console.log(path);
  }
}
1357623
def find_apps(name=None, name_mode='exact', category=None,
              all_versions=None, published=None,
              billed_to=None, created_by=None, developer=None,
              created_after=None, created_before=None,
              modified_after=None, modified_before=None,
              describe=False, limit=None, return_handler=False, first_page_size=100, **kwargs):
    
    return find_global_executables(dxpy.api.system_find_apps,
                                   name=name, name_mode=name_mode, category=category,
                                   all_versions=all_versions, published=published,
                                   billed_to=billed_to, created_by=created_by, developer=developer,
                                   created_after=created_after, created_before=created_before,
                                   modified_after=modified_after, modified_before=modified_before,
                                   describe=describe, limit=limit, return_handler=return_handler,
                                   first_page_size=first_page_size, **kwargs)