Read setup token from filesystem or create if missing
339413
function readSetupToken (cb) {
  var token
  var write = false

  try {
    // try to read setup token from filesystem
    token = keygen.loadSetupToken()
    // if token is blank, try to generate a new token and save it
    if (!token.trim()) {
      write = true
    }
  } catch (err) {
    // if unable to read, try to generate a new token and save it
    write = true
  }

  if (write) {
    try {
      token = keygen.generateSetupToken()
    } catch (err) {
      // if we can't write the token to disk, something is very wrong
      return cb(err)
    }
  }

  // return the token
  cb(null, token)
}
378765
def get_token(opts, tok):
    '''
    
    '''
    t_path = os.path.join(opts['token_dir'], tok)
    if not os.path.isfile(t_path):
        return {}
    serial = salt.payload.Serial(opts)
    try:
        with salt.utils.files.fopen(t_path, 'rb') as fp_:
            tdata = serial.loads(fp_.read())
            return tdata
    except (IOError, OSError):
        log.warning(
            'Authentication failure: can not read token file "%s".', t_path)
        return {}
623495
def read_config(self):
        
        section = "pypitools"
        # read setup.cfg config file
        config = configparser.ConfigParser()
        homedir_filename = os.path.expanduser("~/.setup.cfg")
        if os.path.isfile(homedir_filename):
            config.read(homedir_filename)
        local_filename = "setup.cfg"
        if os.path.isfile(local_filename):
            config.read(local_filename)
        self.upload_method = config.get(section, "upload_method")
        assert self.upload_method in ["setup", "twine", "gemfury"]
        self.clean_before = config.getboolean(section, "clean_before")
        self.clean_after = config.getboolean(section, "clean_after")
        self.install_in_user_folder = config.getboolean(section, "install_in_user_folder")
        self.use_sudo = config.getboolean(section, "use_sudo")
        self.pip_quiet = config.getboolean(section, "pip_quiet")
        self.setup_quiet = config.getboolean(section, "setup_quiet")
        self.pip = config.get(section, "pip")
        self.gemfury_user = config.get(section, "gemfury_user")
        self.python = config.get(section, "python")
        self.register_method = config.get(section, "register_method")
        assert self.register_method in ["setup", "twine", "upload"]
1006659
def _init(creds, bucket, multiple_env, environment, prefix, s3_cache_expire):
    '''
    
    '''

    cache_file = _get_buckets_cache_filename(bucket, prefix)
    exp = time.time() - s3_cache_expire

    # check if cache_file exists and its mtime
    if os.path.isfile(cache_file):
        cache_file_mtime = os.path.getmtime(cache_file)
    else:
        # file does not exists then set mtime to 0 (aka epoch)
        cache_file_mtime = 0

    expired = (cache_file_mtime <= exp)

    log.debug(
        'S3 bucket cache file %s is %sexpired, mtime_diff=%ss, expiration=%ss',
        cache_file,
        '' if expired else 'not ',
        cache_file_mtime - exp,
        s3_cache_expire
    )

    if expired:
        pillars = _refresh_buckets_cache_file(creds, cache_file, multiple_env,
                                           environment, prefix)
    else:
        pillars = _read_buckets_cache_file(cache_file)

    log.debug('S3 bucket retrieved pillars %s', pillars)
    return pillars
692708
def save_setup_command(argv, build_path):
    
    file_name = os.path.join(build_path, 'setup_command')
    with open(file_name, 'w') as f:
        f.write(' '.join(argv[:]) + '\n')
985817
function setupConfigurationFile(configFilePath) {
    const fileName = '.wistrc.json';

    try {
        let contents = require(configFilePath);
        fs.writeFileSync(fileName, JSON.stringify(contents, null, 2));
        log.info(`Initialized directory with a ${fileName}`)
    } catch (e) {
        console.error(e.message);
        return 1;
    }
    return 0;
}
643913
def _create_slack_with_env_var(env_var: EnvVar) -> SlackClient:
    
    token = os.getenv(env_var)
    if token:
        return SlackClient(token=token)
    raise MissingToken(f"Could not acquire token from {env_var}")
324233
private static Optional<Token<?>> getTokenFromSeqFile(String authPath, String proxyUserName) throws IOException {
    try (Closer closer = Closer.create()) {
      FileSystem localFs = FileSystem.getLocal(new Configuration());
      SequenceFile.Reader tokenReader =
          closer.register(new SequenceFile.Reader(localFs, new Path(authPath), localFs.getConf()));
      Text key = new Text();
      Token<?> value = new Token<>();
      while (tokenReader.next(key, value)) {
        LOG.info("Found token for " + key);
        if (key.toString().equals(proxyUserName)) {
          return Optional.<Token<?>> of(value);
        }
      }
    }
    return Optional.absent();
  }
164287
def _setup_program(self):
        
        filename = self._get_program_filename()
        path = os.path.join(self.get_temp_dir(), filename)
        self.program_fp = open(path, 'wb')
        self.program_fp.write(self._get_program())
        self.program_fp.flush()
        os.chmod(self.program_fp.name, int('0700', 8))
        reopen_readonly(self.program_fp)
21289
def get_upload_token(mail, pwd):
    '''
    
    '''
    try:
        params = urllib.urlencode({"email": mail, "password": pwd})
        response = urllib.urlopen(LOGIN_URL, params)
    except:
        return None
    resp = json.loads(response.read())
    if not resp or 'token' not in resp:
        return None
    return resp['token']
688315
private function loadToken()
	{
		if (file_exists($this->cacheFolder."/token.txt"))
		{
			$fd = fopen($this->cacheFolder."/token.txt", 'r');
			$this->token = fgets($fd);
			fclose($fd);
		} else {
			$this->connect();
		}
	}
165003
def upload(path, token, folder):
    
    config = _load_config(CFG_FILE)
    token = _resolve_input(token, 'token', 'token', config)
    folder = _resolve_input(folder, 'folder', 'prod_folder', config)

    update_databricks(
        logger,
        path,
        token,
        folder,
        update_jobs=False,
        cleanup=False
    )
181386
function storeToken(token) {
    const file = {
        name: path.join(constants.GLOBAL_DIR, constants.GLOBAL_TOKEN),
        source: JSON.stringify(token),
    };
    createFile(file);
    return;
}
293307
async function saveToken (url, token) {
  let tokens
  try {
    const data = await readFile(credentialsPath)
    tokens = JSON.parse(data)
  } catch (err) {}

  // if it was empty or contained `null` for some reason
  if (typeof tokens !== 'object' || !tokens) {
    tokens = {}
  }

  tokens[url] = token

  await writeFile(credentialsPath, JSON.stringify(tokens, null, 2))
}
568636
def list_tokens(opts):
    '''
    
    '''
    ret = []
    for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(opts['token_dir']):
        for token in filenames:
            ret.append(token)
    return ret
1339920
function installed(){
    findUp('README.*')
    .then(function(filepath){
        if(filepath === null){
            return process.cwd();
        }else{
            return path.resolve(filepath[0], '../');
        }
    })
    .then(function(parent){
        return config.readLocal(parent);
    })
    .then(data => {
        if(data.installed.length === 0){
            console.log(chalk.bold('No badges installed.'));
        }else{
            // console.log(chalk.bold.underline(`Installed(${data.installed.length}):`));
            _.each(data.installed, i => { console.log(i) });
            console.log(chalk.bgBlue.bold(`Total: ${data.installed.length} `))
        }
    });
}
1114853
def do_setup():
    """"""
    root = get_root()
    try:
        cfg = get_config_from_root(root)
    except (EnvironmentError, configparser.NoSectionError,
            configparser.NoOptionError) as e:
        if isinstance(e, (EnvironmentError, configparser.NoSectionError)):
            print("Adding sample versioneer config to setup.cfg",
                  file=sys.stderr)
            with open(os.path.join(root, "setup.cfg"), "a") as f:
                f.write(SAMPLE_CONFIG)
        print(CONFIG_ERROR, file=sys.stderr)
        return 1

    print(" creating %s" % cfg.versionfile_source)
    with open(cfg.versionfile_source, "w") as f:
        LONG = LONG_VERSION_PY[cfg.VCS]
        f.write(LONG % {"DOLLAR": "$",
                        "STYLE": cfg.style,
                        "TAG_PREFIX": cfg.tag_prefix,
                        "PARENTDIR_PREFIX": cfg.parentdir_prefix,
                        "VERSIONFILE_SOURCE": cfg.versionfile_source,
                        })

    ipy = os.path.join(os.path.dirname(cfg.versionfile_source),
                       "__init__.py")
    if os.path.exists(ipy):
        try:
            with open(ipy, "r") as f:
                old = f.read()
        except EnvironmentError:
            old = ""
        if INIT_PY_SNIPPET_RE.search(old) is None:
            print(" appending to %s" % ipy)
            with open(ipy, "a") as f:
                f.write(INIT_PY_SNIPPET)
        else:
            print(" %s unmodified" % ipy)
    else:
        print(" %s doesn't exist, ok" % ipy)
        ipy = None

    # Make sure both the top-level "versioneer.py" and versionfile_source
    # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so
    # they'll be copied into source distributions. Pip won't be able to
    # install the package without this.
    manifest_in = os.path.join(root, "MANIFEST.in")
    simple_includes = set()
    try:
        with open(manifest_in, "r") as f:
            for line in f:
                if line.startswith("include "):
                    for include in line.split()[1:]:
                        simple_includes.add(include)
    except EnvironmentError:
        pass
    # That doesn't cover everything MANIFEST.in can do
    # (http://docs.python.org/2/distutils/sourcedist.html#commands), so
    # it might give some false negatives. Appending redundant 'include'
    # lines is safe, though.
    if "versioneer.py" not in simple_includes:
        print(" appending 'versioneer.py' to MANIFEST.in")
        with open(manifest_in, "a") as f:
            f.write("include versioneer.py\n")
    else:
        print(" 'versioneer.py' already in MANIFEST.in")
    if cfg.versionfile_source not in simple_includes:
        print(" appending versionfile_source ('%s') to MANIFEST.in" %
              cfg.versionfile_source)
        with open(manifest_in, "a") as f:
            f.write("include %s\n" % cfg.versionfile_source)
    else:
        print(" versionfile_source already in MANIFEST.in")

    # Make VCS-specific changes. For git, this means creating/changing
    # .gitattributes to mark _version.py for export-subst keyword
    # substitution.
    do_vcs_install(manifest_in, cfg.versionfile_source, ipy)
    return 0