github ui url https://github.com/limberest/limberest-demo OR... github api contents https://api.github.com/repos/limberest/limberest-demo
7202
function(url, branch) {
  this.url = url;
  if (url.startsWith('https://api.github.com/repos/')) {
    this.path = url.substring(29);
    this.apiUrl = url;
  }
  else if (url.startsWith('https://github.com/')) {
    this.path = url.substring(19);
    this.apiUrl = 'https://api.github.com/repos/' + this.path;
  }
  else {
    throw new Error('Unsupported URL format: ' + url);
  }
  
  this.branch = branch ? branch : 'master';
  
  if (typeof window === 'undefined') {
    this.request = require('request');
    this.requestOptions = {headers: {'User-Agent': 'limberest'}};
  } 
  else {
    this.request = require('browser-request');
    this.requestOptions = {};
  }
}
1205235
def github_repos(organization, github_url, github_token):
    """"""
    # Get github repos
    headers = {"Authorization": "token {}".format(github_token)}
    next_cursor = None

    while next_cursor is not False:
        params = {'query': query, 'variables': {
            'organization': organization, 'cursor': next_cursor}}
        response = requests.post(github_url, headers=headers, json=params)
        result = response.json()
        if response.status_code != 200 or 'errors' in result:
            raise ValueError("Github api error %s" % (
                response.content.decode('utf8'),))

        repos = jmespath.search(
            'data.organization.repositories.edges[].node', result)
        for r in repos:
            yield r
        page_info = jmespath.search(
            'data.organization.repositories.pageInfo', result)
        if page_info:
            next_cursor = (page_info['hasNextPage'] and
                           page_info['endCursor'] or False)
        else:
            next_cursor = False
314432
def get_labels(self):
        
        return github.PaginatedList.PaginatedList(
            github.Label.Label,
            self._requester,
            self.url + "/labels",
            None
        )
1224751
def get_public_url(self, doc_id, branch='master'):
        
        name, path_frag = self.get_repo_and_path_fragment(doc_id)
        return 'https://raw.githubusercontent.com/OpenTreeOfLife/' + name + '/' + branch + '/' + path_frag
151852
def _query(profile,
           action=None,
           command=None,
           args=None,
           method='GET',
           header_dict=None,
           data=None,
           url='https://api.github.com/',
           per_page=None):
    '''
    
    '''
    if not isinstance(args, dict):
        args = {}

    if action:
        url += action

    if command:
        url += '/{0}'.format(command)

    log.debug('GitHub URL: %s', url)

    if 'access_token' not in args.keys():
        args['access_token'] = _get_config_value(profile, 'token')
    if per_page and 'per_page' not in args.keys():
        args['per_page'] = per_page

    if header_dict is None:
        header_dict = {}

    if method != 'POST':
        header_dict['Accept'] = 'application/json'

    decode = True
    if method == 'DELETE':
        decode = False

    # GitHub paginates all queries when returning many items.
    # Gather all data using multiple queries and handle pagination.
    complete_result = []
    next_page = True
    page_number = ''
    while next_page is True:
        if page_number:
            args['page'] = page_number
        result = salt.utils.http.query(url,
                                       method,
                                       params=args,
                                       data=data,
                                       header_dict=header_dict,
                                       decode=decode,
                                       decode_type='json',
                                       headers=True,
                                       status=True,
                                       text=True,
                                       hide_fields=['access_token'],
                                       opts=__opts__,
                                       )
        log.debug('GitHub Response Status Code: %s',
                  result['status'])

        if result['status'] == 200:
            if isinstance(result['dict'], dict):
                # If only querying for one item, such as a single issue
                # The GitHub API returns a single dictionary, instead of
                # A list of dictionaries. In that case, we can return.
                return result['dict']

            complete_result = complete_result + result['dict']
        else:
            raise CommandExecutionError(
                'GitHub Response Error: {0}'.format(result.get('error'))
            )

        try:
            link_info = result.get('headers').get('Link').split(',')[0]
        except AttributeError:
            # Only one page of data was returned; exit the loop.
            next_page = False
            continue

        if 'next' in link_info:
            # Get the 'next' page number from the Link header.
            page_number = link_info.split('>')[0].split('&page=')[1]
        else:
            # Last page already processed; break the loop.
            next_page = False

    return complete_result
21666
def get_owner_repos_url(owner, token):
    
    url_org = GITHUB_API_URL + "/orgs/" + owner + "/repos"
    url_user = GITHUB_API_URL + "/users/" + owner + "/repos"

    url_owner = url_org  # Use org by default

    try:
        r = requests.get(url_org,
                         params=get_payload(),
                         headers=get_headers(token))
        r.raise_for_status()

    except requests.exceptions.HTTPError as e:
        if r.status_code == 403:
            rate_limit_reset_ts = datetime.fromtimestamp(int(r.headers['X-RateLimit-Reset']))
            seconds_to_reset = (rate_limit_reset_ts - datetime.utcnow()).seconds + 1
            logging.info("GitHub rate limit exhausted. Waiting %i secs for rate limit reset." % (seconds_to_reset))
            sleep(seconds_to_reset)
        else:
            # owner is not an org, try with a user
            url_owner = url_user
    return url_owner
163766
def _get_part_url(api, url, upload, part):
    
    try:
        response = api.get(url.format(upload_id=upload, part_number=part))
        return response.json()['url']
    except Exception:
        raise SbgError(
            'Unable to get upload url for part number {}'.format(part)
        )
1288192
function createMiddleware(options, archiveFormat) {
  /**
   * Express middleware handling GitHub API archive link requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/repos/contents/#get-archive-link
   */
  return (req, res) => {
    // GET /repos/:owner/:repo/:archive_format/:ref
    const { owner } = req.params;
    const repoName = req.params.repo;
    const refName = req.params.ref || 'master';

    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;
    const location = `${req.protocol}://${host}/codeload/${owner}/${repoName}/${archiveFormat}/${refName}`;

    res.writeHead(302, {
      Location: location,
    });
    res.end();
  };
}
94577
def view_links(obj):
    ''' '''
    result=format_html('')
    result+=format_html('<a href="%s" style="white-space: nowrap">Show duplicates</a><br/>'%reverse('duplicates', args=(obj.pk,)))
    result+=format_html('<a href="%s" style="white-space: nowrap">Show submissions</a><br/>'%obj.grading_url())
    result+=format_html('<a href="%s" style="white-space: nowrap">Download submissions</a>'%reverse('assarchive', args=(obj.pk,)))
    return result
429103
function parseGitUrl(giturl) {
    var ref, uri, fileParts, filepath;

    if (!checkGitUrl(giturl)) return null;
    giturl = giturl.slice(GIT_PREFIX.length);

    uri = new URI(giturl);
    ref = uri.fragment() || 'master';
    uri.fragment(null);

    // Extract file inside the repo (after the .git)
    fileParts =uri.path().split('.git');
    filepath = fileParts.length > 1? fileParts.slice(1).join('.git') : '';
    if (filepath[0] == '/') filepath = filepath.slice(1);

    // Recreate pathname without the real filename
    uri.path(_.first(fileParts)+'.git');

    return {
        host: uri.toString(),
        ref: ref || 'master',
        filepath: filepath
    };
}
221382
def download_api(branch=None) -> str:
    """"""
    habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica'
    if not branch:
        branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name']
    curl = local['curl']['-sL', habitica_github_api + '/tarball/{}'.format(branch)]
    tar = local['tar'][
        'axzf', '-', '--wildcards', '*/website/server/controllers/api-v3/*', '--to-stdout']
    grep = local['grep']['@api']
    sed = local['sed']['-e', 's/^[ */]*//g', '-e', 's/  / /g', '-']
    return (curl | tar | grep | sed)()
946190
function githubRepo (options) {
  try {
    const url = options.data.root.package.repository.url
    const match = url.match(/.*?(:\/\/|@)github\.com[/:](.*?)(#.*?)?$/)
    if (match) {
      return match[2].replace(/\.git$/, '')
    } else {
      return null
    }
  } catch (e) {
    // No repositor-url exists
    return null
  }
}
356512
function(req, res, next) {
    var accessTokenUrl = 'https://github.com/login/oauth/access_token';
    var params = {
      code: req.body.code,
      client_id: req.body.clientId,
      client_secret: config.GITHUB_SECRET,
      redirect_uri: req.body.redirectUri
    };

    request.get({ url: accessTokenUrl, qs: params }, function(err, response, accessToken) {
      if (err) {
        res.status(500).send(err);
        return;
      }
      req.accessToken = qs.parse(accessToken);
      next();
    });
  }
209170
def list(self):
        
        # Define the basic request. The per_page parameter is set to 100, which
        # is the maximum github allows. If the user has more than one page of
        # gists, this request object will be modified to retrieve each
        # successive page of gists.
        request = requests.Request(
                'GET',
                'https://api.github.com/gists',
                headers={
                    'Accept-Encoding': 'identity, deflate, compress, gzip',
                    'User-Agent': 'python-requests/1.2.0',
                    'Accept': 'application/vnd.github.v3.base64',
                    },
                params={
                    'access_token': self.token,
                    'per_page': 100,
                    },
                )

        # Github provides a 'link' header that contains information to
        # navigate through a users page of gists. This regex is used to
        # extract the URLs contained in this header, and to find the next page
        # of gists.
        pattern = re.compile(r'<([^>]*)>; rel="([^"]*)"')

        gists = []
        while True:

            # Retrieve the next page of gists
            try:
                response = self.send(request).json()

            except Exception:
                break

            # Extract the list of gists
            for gist in response:
                try:
                    gists.append(
                            GistInfo(
                                gist['id'],
                                gist['public'],
                                gist['description'],
                                )
                            )

                except KeyError:
                    continue

            try:
                link = response.headers['link']

                # Search for the next page of gist. If a 'next' page is found,
                # the URL is set to this new page and the iteration continues.
                # If there is no next page, return the list of gists.
                for result in pattern.finditer(link):
                    url = result.group(1)
                    rel = result.group(2)
                    if rel == 'next':
                        request.url = url
                        break
                else:
                    return gists

            except Exception:
                break

        return gists
257542
def get_github_hostname_user_repo_from_url(url):
    
    parsed = parse.urlparse(url)
    if parsed.netloc == '':
        # Probably ssh
        host, sep, path = parsed.path.partition(":")
        if "@" in host:
            username, sep, host = host.partition("@")
    else:
        path = parsed.path[1:].rstrip('/')
        host = parsed.netloc
    user, repo = path.split("/", 1)
    return host, user, repo[:-4] if repo.endswith('.git') else repo
1229289
def get_repos(self):
        
        url_parameters = dict()

        return github.PaginatedList.PaginatedList(
            contentClass=github.Repository.Repository,
            requester=self._requester,
            firstUrl="/installation/repositories",
            firstParams=url_parameters,
            headers=INTEGRATION_PREVIEW_HEADERS,
            list_item='repositories'
        )
50441
function gh(repo, project) {
  var base = 'https://github.com/'

  if (project) {
    repo = {user: repo, project: project}
  }

  if (repo) {
    base += repo.user + '/' + repo.project + '/'
  }

  return base
}