Get EBNF template from Github belbio/bel_specifications repo
487453
def get_ebnf_template():
    """"""

    spec_dir = config["bel"]["lang"]["specifications"]
    local_fp = f"{spec_dir}/bel.ebnf.j2"

    repo_url = (
        "https://api.github.com/repos/belbio/bel_specifications/contents/resources/bel.ebnf.j2"
    )

    params = {}
    github_access_token = os.getenv("GITHUB_ACCESS_TOKEN", "")
    if github_access_token:
        params = {"access_token": github_access_token}

    try:
        # Get download url for template file
        r = requests.get(repo_url, params=params)

        if r.status_code == 200:
            template_url = r.json()["download_url"]
        else:
            log.warning("Could not get EBNF file download url from Github")

        # Get template file
        try:
            r = requests.get(template_url, params=params, allow_redirects=True)
            if r.status_code == 200:
                open(local_fp, "wt").write(r.text)
            else:
                log.warning(
                    f"Could not download EBNF file from Github -- Status: {r.status_code}  Msg: {r.text}"
                )

        except Exception as e:
            log.warning(
                f"Could not download EBNF file from Github -- Status: {r.status_code}  Msg: {e}"
            )

    except Exception as e:
        log.warning("Could not download BEL EBNF template file")
        if not os.path.exists(f"{spec_dir}/local_fp"):
            log.error("No BEL EBNF template file available")

    return local_fp
999093
def gitignore_templates(self):
        
        url = self._build_url('gitignore', 'templates')
        return self._json(self._get(url), 200) or []
1132825
def get_belbio_conf_files():
    

    home = os.path.expanduser("~")
    cwd = os.getcwd()

    belbio_conf_fp, belbio_secrets_fp = "", ""

    env_conf_dir = os.getenv("BELBIO_CONF", "").rstrip("/")

    conf_paths = [
        f"{cwd}/belbio_conf.yaml",
        f"{cwd}/belbio_conf.yml",
        f"{env_conf_dir}/belbio_conf.yaml",
        f"{env_conf_dir}/belbio_conf.yml",
        f"{home}/.belbio/conf",
    ]
    secret_paths = [
        f"{cwd}/belbio_secrets.yaml",
        f"{cwd}/belbio_secrets.yml",
        f"{env_conf_dir}/belbio_secrets.yaml",
        f"{env_conf_dir}/belbio_secrets.yml",
        f"{home}/.belbio/secrets",
    ]

    for fn in conf_paths:
        if os.path.exists(fn):
            belbio_conf_fp = fn
            break
    else:
        log.error(
            "No BELBio configuration file found - please add one (see http://bel.readthedocs.io/en/latest/configuration.html)"
        )

    for fn in secret_paths:
        if os.path.exists(fn):
            belbio_secrets_fp = fn
            break

    return (belbio_conf_fp, belbio_secrets_fp)
190988
def template(self):
        """"""
        r = fapi.get_config_template(self.namespace, self.name,
                                        self.snapshot_id, self.api_url)
        fapi._check_response_code(r, 200)
        return r.json()
154461
def sbatch_template(self):
        """"""
        template = self.sbatch_template_str
        if template.startswith('#!'):
            # script is embedded in YAML
            return jinja_environment.from_string(template)
        return jinja_environment.get_template(template)
341957
def get_template(self, template_name):
        """"""
        try:
            return self.loader.load(template_name, encoding=self.encoding)
        except self.not_found_exception, e:
            # catch the exception raised by Genshi, convert it into a werkzeug
            # exception (for the sake of consistency)
            raise TemplateNotFound(template_name)
689767
def load_configuration():
    """"""

    (belbio_conf_fp, belbio_secrets_fp) = get_belbio_conf_files()
    log.info(f"Using conf: {belbio_conf_fp} and secrets files: {belbio_secrets_fp} ")

    config = {}
    if belbio_conf_fp:
        with open(belbio_conf_fp, "r") as f:
            config = yaml.load(f, Loader=yaml.SafeLoader)
            config["source_files"] = {}
            config["source_files"]["conf"] = belbio_conf_fp

    if belbio_secrets_fp:
        with open(belbio_secrets_fp, "r") as f:
            secrets = yaml.load(f, Loader=yaml.SafeLoader)
            config["secrets"] = copy.deepcopy(secrets)
            if "source_files" in config:
                config["source_files"]["secrets"] = belbio_secrets_fp

    get_versions(config)

    # TODO - needs to be completed
    # add_environment_vars(config)

    return config
280993
def _get_mod_ns(name, fullname, includeprivate):
    """"""
    ns = {  # template variables
        'name': name, 'fullname': fullname, 'members': [], 'functions': [],
        'classes': [], 'exceptions': [], 'subpackages': [], 'submodules': [],
        'doc': None}
    p = 0
    if includeprivate:
        p = 1
    mod = importlib.import_module(fullname)
    ns['members'] = _get_members(mod)[p]
    ns['functions'] = _get_members(mod, typ='function')[p]
    ns['classes'] = _get_members(mod, typ='class')[p]
    ns['exceptions'] = _get_members(mod, typ='exception')[p]
    ns['data'] = _get_members(mod, typ='data')[p]
    ns['doc'] = mod.__doc__
    return ns
1127326
def get_template_dir():
    """"""
    try:
        template_dir = os.path.expanduser(os.environ["NET_TEXTFSM"])
        index = os.path.join(template_dir, "index")
        if not os.path.isfile(index):
            # Assume only base ./ntc-templates specified
            template_dir = os.path.join(template_dir, "templates")
    except KeyError:
        # Construct path ~/ntc-templates/templates
        home_dir = os.path.expanduser("~")
        template_dir = os.path.join(home_dir, "ntc-templates", "templates")

    index = os.path.join(template_dir, "index")
    if not os.path.isdir(template_dir) or not os.path.isfile(index):
        msg = """
Valid ntc-templates not found, please install https://github.com/networktocode/ntc-templates
and then set the NET_TEXTFSM environment variable to point to the ./ntc-templates/templates
directory."""
        raise ValueError(msg)
    return os.path.abspath(template_dir)
336037
def get_template_schema(template_id, opts = {})
      data, _status_code, _headers = get_template_schema_with_http_info(template_id, opts)
      data
    end
230248
def binder_spec_from_github_url(github_url):
    
    tokens = re.split(r'/|:', github_url.replace('.git', ''))
    # The username and reponame are the last two tokens
    return '{}/{}/master'.format(tokens[-2], tokens[-1])
530143
function fetchRepo(fullName) {
  return {
    [CALL_API]: {
      types: [REPO_REQUEST, REPO_SUCCESS, REPO_FAILURE],
      endpoint: `repos/${fullName}`,
      schema: Schemas.REPO
    }
  };
}
308245
def get_or_create_environment(self, repo: str, branch: str,
                                  git_repo: Repo, repo_path: Path) -> str:  # pragma: no cover
        
        raise NotImplementedError
611565
function getEnvsListForTemplate(){
		var envsList = [];
		var keys = Object.keys(allEnvs).sort();
		for(var j = 0; j < keys.length; j++) {
			var key = keys[j];
			if(key !== 'builtin'){
				envsList.push(key);
			}
		}
		var templateList = {
			type: "link", //$NON-NLS-0$
			values: envsList,
			title: 'ESLint Environments',
			style: 'no_emphasis' //$NON-NLS-1$
		};
		return JSON.stringify(templateList).replace("}", "\\}");
	}
1267092
function downloadAndGenerate (template, cb) {
  var spinner = ora('downloading template')
  spinner.start()
  download(template, tmp, { clone: clone }, function (err) {
    spinner.stop()
    if (err) logger.fatal('Failed to download repo ' + template + ': ' + err.message.trim())
    generate(name, tmp, to, cb)
  })
}
220255
def get_base_templates():
    "  "

    return sorted(filter(
                  lambda x: op.isdir(op.join(TPL_DIR, x)),
                  listdir(TPL_DIR)))
1321299
function bemBHLoader(source) {
  const options = {
    beautify: true,
    name: '[name].html',
    client: false, // or true or 'static'
    bhFilename: require.resolve('bh'),
    bhOptions: {
      jsAttrName: 'data-bem',
      jsAttrScheme: 'json',
      xhtml: false,
    },
  };
  Object.assign(options, loaderUtils.getOptions(this));

  const self = this;
  let bemFS = nodeEval(source);

  // Extract templates
  const bhTemplates = bemFS.filter((fileName) => {
    return /\.bh\.js$/i.test(fileName);
  }).map((fileName) => {
    return path.resolve(fileName);
  });

  // Prepare BH engine
  const engine = new (require(options.bhFilename)).BH;
  engine.setOptions(options.bhOptions);

  // Apply templates to engine
  bhTemplates.forEach((fileName) => {
    try {
      delete require.cache[fileName];
    } catch (e) {
      throw new Error('Template file not found ' + fileName);
    }

    try {
      require(fileName)(engine);
      self.addDependency(fileName);
    } catch (e) {
      throw new Error('Error processing BH template ' + fileName);
    }
  });

  // Load BemJson and transform with BH engine
  const callback = this.async();
  const request = '!@intervolga/eval-loader!' + this.resourcePath;
  this.loadModule(request, (err, source) => {
    if (err) {
      callback(err);
      return;
    }

    const bemJson = nodeEval(source);
    // TODO: replace images,
    // maybe https://github.com/webpack-contrib/html-loader

    let html;
    try {
      html = engine.apply(bemJson);
    } catch (e) {
      callback(e);
      return;
    }

    if (options.beautify) {
      html = beautifyHtml(html, {});
      // .replace(/\s*\/\* beautify preserve:start \*\//g, '')
      // .replace(/\/\* beautify preserve:end \*\/\s*/g, '');
    }

    const newName = loaderUtils.interpolateName(this, options.name, {
      content: html,
    });
    self.emitFile(newName, html);

    // Remove BH templates from pipe
    bemFS = bemFS.filter((fileName) => {
      return !(/\.bh\.js$/i.test(fileName));
    }).map((fileName) => {
      return {'require': fileName};
    });

    if (options.client) {
      // Stringify engine path and options
      const bhClientEngine = loaderUtils.stringifyRequest(
        self, options.bhFilename);
      const bhClientOptions = JSON.stringify(options.bhOptions);

      let bhClientSource;
      if (options.client == 'static') {
        // Stringify templates
        const bhClientTemplates = bhTemplates.map((fileName) => {
          let safeTemplate = loaderUtils.stringifyRequest(self, fileName);
          return `require(${safeTemplate})(BH);`;
        }).join('\n');


        // Static BH for client
        bhClientSource = `
          (function(){
            const BH = new (require(${bhClientEngine})).BH;
            BH.setOptions(${bhClientOptions});
            ${bhClientTemplates}
    
            window.getBH = (cb) => {
              cb(BH);
            };
          })();`;
      } else {
        const bhClientTemplates = bhTemplates.map((fileName) => {
          let safeTemplate = loaderUtils.stringifyRequest(self, fileName);
          return `import(${safeTemplate})`;
        }).join(', ');

        bhClientSource = `
          window.getBH = (cb) => {
            const requireBH = import(${bhClientEngine})
              .then((bhModule) => {
                const BH = new bhModule.BH;
                BH.setOptions(${bhClientOptions});
                return BH;
              });
            
            const requireTemplates = [${bhClientTemplates}];
          
            Promise.all([
              requireBH,
              Promise.all(requireTemplates)
            ]).then((results) => {
              const BH = results[0];
              const templates = results[1];
          
              templates.forEach((template) => {
                template.default(BH);
              });
          
              cb(BH);
            });
          };`;
      }

      bemFS.splice(0, 0, {'raw': bhClientSource});
    }

    callback(null, 'module.exports = ' + JSON.stringify(bemFS) + ';');
  });
}