star any gist by providing gistID or gistname(for authenticated user)
771391
def star(self, **args):
		'''
		
		'''
		if 'name' in args:
			self.gist_name = args['name']
			self.gist_id = self.getMyID(self.gist_name)
		elif 'id' in args:
			self.gist_id = args['id']
		else:
			raise Exception('Either provide authenticated user\'s Unambigious Gistname or any unique Gistid to be starred')

		r = requests.put(
			'%s'%BASE_URL+'/gists/%s/star' % self.gist_id,
			headers=self.gist.header
			)
		if (r.status_code == 204):
			response = {
				'id': self.gist_id
			}
			return response

		raise Exception('Gist can\'t be starred')
1013330
def su(user)
      if defined?(Etc)
        pw = Etc.getpwnam(user)
        Process::initgroups(user, pw.gid)
        Process::Sys::setgid(pw.gid)
        Process::Sys::setuid(pw.uid)
      else
        warn("WEBrick::Utils::su doesn't work on this platform")
      end
    end
359627
def _authenticate_ssh(org):
    """"""
    # Try to get username from git config
    username = os.environ.get(f"{org.upper()}_USERNAME")
    # Require ssh-agent
    child = pexpect.spawn("ssh -T git@github.com", encoding="utf8")
    # GitHub prints 'Hi {username}!...' when attempting to get shell access
    i = child.expect(["Hi (.+)! You've successfully authenticated",
                      "Enter passphrase for key",
                      "Permission denied",
                      "Are you sure you want to continue connecting"])
    child.close()

    if i == 0:
        if username is None:
            username = child.match.groups()[0]
    else:
        return None

    return User(name=username,
                repo=f"git@github.com:{org}/{username}")
1307632
def chgid(name, gid):
    '''
    
    '''
    if not isinstance(gid, int):
        raise SaltInvocationError('gid must be an integer')
    pre_info = info(name)
    if not pre_info:
        raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
    if gid == pre_info['gid']:
        return True
    _dscl(
        ['/Users/{0}'.format(name), 'PrimaryGroupID', pre_info['gid'], gid],
        ctype='change'
    )
    # dscl buffers changes, sleep 1 second before checking if new value
    # matches desired value
    time.sleep(1)
    return info(name).get('gid') == gid
1156736
def ReadGRRUser(self, username):
    """"""
    try:
      return self.users[username].Copy()
    except KeyError:
      raise db.UnknownGRRUserError(username)
1191375
def github_authenticated(cls, func):
        
        def inner(func_cls, *args, **kwargs):
            if not cls._gh_module:
                logger.warning('PyGithub not installed, skipping Github auth procedures.')
            elif not func_cls._user:
                # authenticate user, possibly also creating authentication for future use
                login = kwargs['login'].encode(utils.defenc) if not six.PY3 else kwargs['login']
                func_cls._user = cls._get_github_user(login, kwargs['ui'])
                if func_cls._user is None:
                    msg = 'Github authentication failed, skipping Github command.'
                    logger.warning(msg)
                    return (False, msg)
                # create an ssh key for pushing if we don't have one
                if not cls._github_ssh_key_exists():
                    cls._github_create_ssh_key()
                # next, create ~/.ssh/config entry for the key, if system username != GH login
                if cls._ssh_key_needs_config_entry():
                    cls._create_ssh_config_entry()
            return func(func_cls, *args, **kwargs)

        return inner
780289
def fetch_gist(gist_id, filename=None):
    """"""
    import requests

    url = gist_url(gist_id, filename)
    response = requests.get(url)

    if response.status_code != 200:
        raise Exception('Got a bad status looking up gist.')
    body = response.text
    if not body:
        raise Exception('Unable to get the gist contents.')

    return body
710754
def user_stars(self, user_id, extra_query_params={}):
        
        return self.do("GET", "users/{user_id}/stars",
                       url_params={"user_id": user_id},
                       query_params=extra_query_params)
490060
def tidy_ssh_user(url=None, user=None):
    """"""
    if url and url.startswith('ssh://'):
        # is there a user already ?
        match = re.compile('ssh://([^@]+)@.+').match(url)
        if match:
            ssh_user = match.group(1)
            if user and ssh_user != user:
                # assume prevalence of argument
                url = url.replace(re.escape(ssh_user) + '@',
                                  user + '@')
        elif user:
            url = 'ssh://' + \
                  user + '@' + \
                  url[len('ssh://'):]
    return url
423973
def links(self,**args):
		'''
		
		'''
		if 'name' in args:
			self.gist_name = args['name']
			self.gist_id = self.getMyID(self.gist_name)
		elif 'id' in args:
			self.gist_id = args['id']
		else:
			raise Exception('Gist Name/ID must be provided')
		if self.gist_id:
			r = requests.get(
				'%s/gists/%s'%(BASE_URL,self.gist_id),
				headers=self.gist.header,
				)
			if (r.status_code == 200):

				content = {
				'Github-User': r.json()['user']['login'],
				'GistID': r.json()['id'],
				'Gist-Link': '%s/%s/%s' %(GIST_URL,self.gist.username,r.json()['id']),
				'Clone-Link': '%s/%s.git' %(GIST_URL,r.json()['id']),
				'Embed-Script': '<script src="%s/%s/%s.js"</script>' %(GIST_URL,self.gist.username,r.json()['id'])
				}
				return content

		raise Exception('No such gist found')
262810
def chgid(name, gid):
    '''
    
    '''
    pre_info = info(name)
    if not pre_info:
        raise CommandExecutionError(
            'User \'{0}\' does not exist'.format(name)
        )
    if gid == pre_info['gid']:
        return True
    cmd = ['usermod', '-g', gid, name]
    __salt__['cmd.run'](cmd, python_shell=False)
    return info(name).get('gid') == gid
1244198
def _auth(url, user, passwd, realm):
    '''
    
    '''

    basic = _HTTPBasicAuthHandler()
    basic.add_password(realm=realm, uri=url, user=user, passwd=passwd)
    digest = _HTTPDigestAuthHandler()
    digest.add_password(realm=realm, uri=url, user=user, passwd=passwd)
    return _build_opener(basic, digest)
889478
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except UPSError:
            _login(*args)
            return function(*args)
    return wrapped
830010
function authenticatedAction(data, socketSend) {
		var type = data.type
		switch(type) {
		case 'getApps':
			socketSend(godModel.getApps()) // does not fail and has no callback
			break
		case 'reload':
			godModel.reload(result)
			break
		case 'nodebug':
			type = 'run'
		case 'run':
		case 'stop':
		case 'debug':
		case 'restart':
			godModel.write(data.app, type, result)
			break
		default:
			log('Unknown command:', data)
			socketSend({err: 'unknown command'})
		}

		function result(err) {
			if (err) socketSend({err: err.message})
		}
	}
752036
def authenticate(self):
        """"""
        endpoint = os.path.join(self.config.get('napps', 'api'), 'auth', '')
        username = self.config.get('auth', 'user')
        password = getpass("Enter the password for {}: ".format(username))
        response = requests.get(endpoint, auth=(username, password))
        if response.status_code != 201:
            LOG.error(response.content)
            LOG.error('ERROR: %s: %s', response.status_code, response.reason)
            sys.exit(1)
        else:
            data = response.json()
            KytosConfig().save_token(username, data.get('hash'))
            return data.get('hash')
562513
def star(self, login, repo):
        
        resp = False
        if login and repo:
            url = self._build_url('user', 'starred', login, repo)
            resp = self._boolean(self._put(url), 204, 404)
        return resp
1033048
def authenticate_storage(client_secrets, read_only=False):
    """"""
    if read_only:
        scopes = ['https://www.googleapis.com/auth/devstorage.read_only']
    else:
        scopes = ['https://www.googleapis.com/auth/devstorage.read_write']

    credentials = service_account.Credentials.from_service_account_info(
            client_secrets)
    
    scoped_credentials = credentials.with_scopes(scopes)
    
    return scoped_credentials