output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Returns all public repositories from an user.
Explain what the following Python 3 code does def public(self, username=None): username = username or self.bitbucket.username or '' url = self.bitbucket.url('GET_USER', username=username) response = self.bitbucket.dispatch('GET', url) try: return (response[0], response[1]['re...
You are a Python code analyst, evaluating scripts for potential improvements.
Creates a new repository on own Bitbucket account and returns it.
Can you tell what is the following Python 3 function doing def create(self, repo_name, scm='git', private=True, **kwargs): url = self.bitbucket.url('CREATE_REPO') return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, name=repo_name, scm=scm, is_private=private, **kwargs)
You are a Python code generator, capable of creating scripts from specifications.
def archive(self, repo_slug=None, format='zip', prefix=''): """ Get one of your repositories and compress it as an archive. Return the path of the archive. format parameter is curently not supported. """ prefix = '%s'.lstrip('/') % prefix self._get_files_in_dir(r...
Write a Python 3 script to get one of your repositories and compress it as an archive.
As a Python code composer, you craft elegant and concise scripts.
def create(self, issue_id=None, repo_slug=None, **kwargs): """ Add an issue comment to one of your repositories. Each issue comment require only the content data field the system autopopulate the rest. """ issue_id = issue_id or self.issue_id repo_slug = repo_slug...
Implement a Python 3 function for creating a new issue comment.
You are a Python code analyst, evaluating scripts for potential improvements.
Delete an issue from one of your repositories.
Can you generate the documentation for the following Python 3 function def delete(self, comment_id, issue_id=None, repo_slug=None): issue_id = issue_id or self.issue_id repo_slug = repo_slug or self.bitbucket.repo_slug or '' url = self.bitbucket.url('DELETE_COMMENT', ...
As a Python code composer, you craft elegant and concise scripts.
def all(self): """ Get all ssh keys associated with your account. """ url = self.bitbucket.url('GET_SSH_KEYS') return self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth)
Create a Python 3 function to get all SSH keys associated with your account.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get one of the ssh keys associated with your account.
Can you generate a brief explanation for the following Python 3 code def get(self, key_id=None): url = self.bitbucket.url('GET_SSH_KEY', key_id=key_id) return self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth)
As a Python code analyst, you investigate and solve complex coding mysteries
Associate an ssh key with your account and return it.
Given the following Python 3 function, write the documentation def create(self, key=None, label=None): key = '%s' % key url = self.bitbucket.url('SET_SSH_KEY') return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, key=key, label=label)
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete one of the ssh keys associated with your account.
Given the following Python 3 function, write the documentation def delete(self, key_id=None): url = self.bitbucket.url('DELETE_SSH_KEY', key_id=key_id) return self.bitbucket.dispatch('DELETE', url, auth=self.bitbucket.auth)
As a python code expert, you are capable of creating scripts from specifications.
def which(program): ''' Emulate unix 'which' command. If program is a path to an executable file (i.e. it contains any directory components, like './myscript'), return program. Otherwise, if an executable file matching program is found in one of the directories in the PATH environment variable, re...
Write a Python 3 function that can emulate unix which command.
You are a Python code analyst, evaluating scripts for potential improvements.
def make_file_cm(filename, mode='a'): ''' Open a file for appending and yield the open filehandle. Close the filehandle after yielding it. This is useful for creating a context manager for logging the output of a `Vagrant` instance. filename: a path to a file mode: The mode in which to open ...
How would you code a function in Python 3 to create a contextmanager that opens a file for appending and yield the open filehandle after yielding it.
You are a Python code generator, capable of creating scripts from specifications.
Return the installed vagrant version as a string e. g. 1. 5. 0
Given the following Python 3 function, write the documentation def version(self): ''' Return the installed vagrant version, as a string, e.g. '1.5.0' ''' output = self._run_vagrant_command(['--version']) m = re.search(r'^Vagrant (?P<version>.+)$', output) if m is None: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Start a box or boxes with the specified provider.
Here you have a function in Python 3, explain what it does def up(self, no_provision=False, provider=None, vm_name=None, provision=None, provision_with=None, stream_output=False): ''' Invoke `vagrant up` to start a box or boxes, possibly streaming the command output. vm_name=N...
As a Python code translator, you convert algorithms and pseudocode into Python.
def provision(self, vm_name=None, provision_with=None): ''' Runs the provisioners defined in the Vagrantfile. vm_name: optional VM name string. provision_with: optional list of provisioners to enable. e.g. ['shell', 'chef_solo'] ''' prov_with_arg = None if provi...
Implement a Python 3 function for running the provisioners defined in the Vagrantfile.
As a Python code translator, you convert algorithms and pseudocode into Python.
def reload(self, vm_name=None, provision=None, provision_with=None, stream_output=False): ''' Quoting from Vagrant docs: > The equivalent of running a halt followed by an up. > This command is usually required for changes made in the Vagrantfile to take effect. A...
Can you write a function in Python 3 where it reloads the configuration of a Vagrantfile.
As a python code expert, you are capable of creating scripts from specifications.
Halt the Vagrant box.
Given the following Python 3 function, write the documentation def halt(self, vm_name=None, force=False): ''' Halt the Vagrant box. force: If True, force shut down. ''' force_opt = '--force' if force else None self._call_vagrant_command(['halt', vm_name, force_opt]) ...
As a Python code composer, you craft elegant and concise scripts.
Return the results of a vagrant status call.
How would you explain what the following Python 3 function does def status(self, vm_name=None): ''' Return the results of a `vagrant status` call as a list of one or more Status objects. A Status contains the following attributes: - name: The VM name in a multi-vm environment. 'defaul...
As a Python code analyst, you investigate and solve complex coding mysteries
Parse the status output from the Vagrant status command.
Given the following Python 3 function, write the documentation def _parse_status(self, output): ''' Unit testing is so much easier when Vagrant is removed from the equation. ''' parsed = self._parse_machine_readable_output(output) statuses = [] # group tuples by t...
As a Python code analyst, you investigate and solve complex coding mysteries
Parse the ssh config into a dictionary containing the keys defined in ssh_config and the values defined in vm_name.
Explain what the following Python 3 code does def conf(self, ssh_config=None, vm_name=None): ''' Parse ssh_config into a dict containing the keys defined in ssh_config, which should include these keys (listed with example values): 'User' (e.g. 'vagrant'), 'HostName' (e.g. 'localhost'), ...
As a Python code analyst, you investigate and solve complex coding mysteries
Return a string combining user and hostname e. g. vagrant@127. 0. 1.
Given the following Python 3 function, write the documentation def user_hostname(self, vm_name=None): ''' Return a string combining user and hostname, e.g. 'vagrant@127.0.0.1'. This string is suitable for use in an ssh commmand. If user is None or empty, it will be left out of the strin...
You are a Python code architect, reviewing and designing scalable and efficient code
Return a string combining user hostname and port.
Can you generate a brief explanation for the following Python 3 code def user_hostname_port(self, vm_name=None): ''' Return a string combining user, hostname and port, e.g. 'vagrant@127.0.0.1:2222'. This string is suitable for use with Fabric, in env.hosts. If user or port is None or e...
You are a Python code generator, capable of creating scripts from specifications.
def box_add(self, name, url, provider=None, force=False): ''' Adds a box with given name, from given url. force: If True, overwrite an existing box if it exists. ''' force_opt = '--force' if force else None cmd = ['box', 'add', name, url, force_opt] if provider i...
Write a Python 3 script for adding a box with given name from given url.
As a Python code analyst, you investigate and solve complex coding mysteries
Packages a running vagrant environment into a virtualbox.
Can you generate a brief explanation for the following Python 3 code def package(self, vm_name=None, base=None, output=None, vagrantfile=None): ''' Packages a running vagrant environment into a box. vm_name=None: name of VM. base=None: name of a VM in virtualbox to package as a base box...
As a Python code translator, you convert algorithms and pseudocode into Python.
This command will pop the pushed state of the current resource.
How would you explain what the following Python 3 function does def snapshot_pop(self): ''' This command is the inverse of vagrant snapshot push: it will restore the pushed state. ''' NO_SNAPSHOTS_PUSHED = 'No pushed snapshot found!' output = self._run_vagrant_command(['snapshot'...
You are a Python code analyst, evaluating scripts for potential improvements.
def ssh(self, vm_name=None, command=None, extra_ssh_args=None): ''' Execute a command via ssh on the vm specified. command: The command to execute via ssh. extra_ssh_args: Corresponds to '--' option in the vagrant ssh command Returns the output of running the command. '''...
Write a Python 3 function for executing a command via ssh on the vm specified.
As a python code expert, you are capable of creating scripts from specifications.
def _parse_box_list(self, output): ''' Remove Vagrant usage for unit testing ''' # Parse box list output boxes = [] # initialize box values name = provider = version = None for timestamp, target, kind, data in self._parse_machine_readable_output(output): ...
Implement a function in Python 3 to parse the output of the box list command.
As a Python code composer, you craft elegant and concise scripts.
def _parse_plugin_list(self, output): ''' Remove Vagrant from the equation for unit testing. ''' ENCODED_COMMA = '%!(VAGRANT_COMMA)' plugins = [] # initialize plugin values name = None version = None system = False for timestamp, target, k...
Create a Python 3 function for parsing the output of the plugin list command.
You are a Python code generator, capable of creating scripts from specifications.
def _parse_machine_readable_output(self, output): ''' param output: a string containing the output of a vagrant command with the `--machine-readable` option. returns: a dict mapping each 'target' in the machine readable output to a dict. The dict of each target, maps each target line t...
Write a Python 3 script to parse the output of the vagrant machine - readable command.
As a python code expert, you are capable of creating scripts from specifications.
This lame parser does not parse the full grammar of an ssh config file. It does not parse the full grammar of an ssh config file.
Can you generate the documentation for the following Python 3 function def _parse_config(self, ssh_config): ''' This lame parser does not parse the full grammar of an ssh config file. It makes assumptions that are (hopefully) correct for the output of `vagrant ssh-config [vm-name]`. Sp...
As a Python code analyst, you investigate and solve complex coding mysteries
def _call_vagrant_command(self, args): ''' Run a vagrant command. Return None. args: A sequence of arguments to a vagrant command line. ''' # Make subprocess command command = self._make_vagrant_command(args) with self.out_cm() as out_fh, self.err_cm() as err_fh...
Implement a Python 3 function for running a vagrant command. Return None.
As a Python code analyst, you investigate and solve complex coding mysteries
def _run_vagrant_command(self, args): ''' Run a vagrant command and return its stdout. args: A sequence of arguments to a vagrant command line. e.g. ['up', 'my_vm_name', '--no-provision'] or ['up', None, '--no-provision'] for a non-Multi-VM environment. ''' # Make...
Write a Python 3 function for running a vagrant command and return its stdout.
You are a Python code analyst, evaluating scripts for potential improvements.
def _stream_vagrant_command(self, args): """ Execute a vagrant command, returning a generator of the output lines. Caller should consume the entire generator to avoid the hanging the subprocess. :param args: Arguments for the Vagrant command. :return: generator that yiel...
How would you implement a function in Python 3 that executes a vagrant command and return a generator of the output lines.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the status of the sandbox mode.
How would you explain what the following Python 3 function does def sandbox_status(self, vm_name=None): ''' Returns the status of the sandbox mode. Possible values are: - on - off - unknown - not installed ''' vagrant_sandbox_output = self._run_sa...
As a Python code composer, you craft elegant and concise scripts.
Parses the vagrant sandbox status output from vagrant sandbox status.
Explain what the following Python 3 code does def _parse_vagrant_sandbox_status(self, vagrant_output): ''' Returns the status of the sandbox mode given output from 'vagrant sandbox status'. ''' # typical output # [default] - snapshot mode is off # or # [de...
As a Python code translator, you convert algorithms and pseudocode into Python.
def deserialize(obj): """Convert JSON dicts back into objects.""" # Be careful of shallow copy here target = dict(obj) class_name = None if '__class__' in target: class_name = target.pop('__class__') if '__module__' in obj: obj.pop('__module__') # Use getattr(module, class_na...
Write a Python 3 script for converting JSON dicts back into objects.
As a Python code composer, you craft elegant and concise scripts.
Convert an object into a dictionary representation based on the object s type.
Can you tell what is the following Python 3 function doing def serialize(obj): # Record class and module information for deserialization result = {'__class__': obj.__class__.__name__} try: result['__module__'] = obj.__module__ except AttributeError: pass # Convert objects to dictiona...
As a python code expert, you are capable of creating scripts from specifications.
Serialize obj as a JSON formatted stream to fp.
Given the following Python 3 function, write the documentation def _serialize_json(obj, fp): json.dump(obj, fp, indent=4, default=serialize)
As a Python code analyst, you investigate and solve complex coding mysteries
Get the serializer for a specific format
Can you generate the documentation for the following Python 3 function def get_serializer(serializer_format): if serializer_format == Format.JSON: return _serialize_json if serializer_format == Format.PICKLE: return _serialize_pickle
You are a Python code architect, reviewing and designing scalable and efficient code
Get the deserializer for a specific format
How would you explain what the following Python 3 function does def get_deserializer(serializer_format): if serializer_format == Format.JSON: return _deserialize_json if serializer_format == Format.PICKLE: return _deserialize_pickle
As a python code expert, you are capable of creating scripts from specifications.
def _set_logger(logger_name, level=logging.INFO): """ Convenience function to quickly configure full debug output to go to the console. """ log = logging.getLogger(logger_name) log.setLevel(level) ch = logging.StreamHandler(None) ch.setLevel(level) ...
Write a Python 3 function for setting the logger to be debug.
As a Python code translator, you convert algorithms and pseudocode into Python.
Find the file format and the file path and format of the given file name.
Can you generate the documentation for the following Python 3 function def find_file_format(file_name): for file_format in Format.ALLOWED: file_path = '.'.join((file_name, file_format)) if os.path.exists(file_path): return file_path, file_format return None, None
As a python code expert, you are capable of creating scripts from specifications.
Returns the next file to read and the serializer for the current entry.
How would you explain what the following Python 3 function does def get_next_file_path(self, service, operation): base_name = '{0}.{1}'.format(service, operation) if self.prefix: base_name = '{0}.{1}'.format(self.prefix, base_name) LOG.debug('get_next_file_path: %s', base_name) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Save a response to the data directory.
Can you generate the documentation for the following Python 3 function def save_response(self, service, operation, response_data, http_response=200): """ Store a response to the data directory. The ``operation`` should be the name of the operation in the service API (e.g. ...
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_authentication_request(self, request_body, http_headers=None): # type: (str, Optional[Mapping[str, str]]) -> oic.oic.message.AuthorizationRequest """ Parses and verifies an authentication request. :param request_body: urlencoded authentication request :param http_heade...
Write a Python 3 script for parsing and verifies an authentication request.
As a Python code composer, you craft elegant and concise scripts.
def authorize(self, authentication_request, # type: oic.oic.message.AuthorizationRequest user_id, # type: str extra_id_token_claims=None # type: Optional[Union[Mapping[str, Union[str, List[str]]], Callable[[str, str], Mapping[str, Union[str, List[str]]]]] ...
Can you implement a function in Python 3 that creates an Authorization Response for the specified authentication request and local identifier of the authenticated user.
You are a Python code generator, capable of creating scripts from specifications.
def _add_access_token_to_response(self, response, access_token): # type: (oic.message.AccessTokenResponse, se_leg_op.access_token.AccessToken) -> None """ Adds the Access Token and the associated parameters to the Token Response. """ response['access_token'] = access_token.value ...
Can you implement a function in Python 3 that adds the Access Token and associated parameters to the Token Response.
You are a Python code analyst, evaluating scripts for potential improvements.
def _create_subject_identifier(self, user_id, client_id, redirect_uri): # type (str, str, str) -> str """ Creates a subject identifier for the specified client and user see <a href="http://openid.net/specs/openid-connect-core-1_0.html#Terminology"> "OpenID Connect Core 1.0", Sect...
How would you implement a function in Python 3 that creates a subject identifier for the specified user and client.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _get_requested_claims_in(self, authentication_request, response_method): # type (oic.oic.message.AuthorizationRequest, str) -> Mapping[str, Optional[Mapping[str, Union[str, List[str]]]] """ Parses any claims requested using the 'claims' request parameter, see <a href="http://openid.n...
Create a Python 3 function to parse any claims requested using the claims request parameter see
You are a Python code architect, reviewing and designing scalable and efficient code
Create a signed ID Token.
Here you have a function in Python 3, explain what it does def _create_signed_id_token(self, client_id, # type: str sub, # type: str user_claims=None, # type: Optional[Mapping[str, Union[str, List[str]]]] ...
As a python code expert, you are capable of creating scripts from specifications.
def _check_subject_identifier_matches_requested(self, authentication_request, sub): # type (oic.message.AuthorizationRequest, str) -> None """ Verifies the subject identifier against any requested subject identifier using the claims request parameter. :param authentication_request: authe...
Can you write a function in Python 3 where it checks that the subject identifier matches the requested one.
You are a Python code architect, reviewing and designing scalable and efficient code
def handle_token_request(self, request_body, # type: str http_headers=None, # type: Optional[Mapping[str, str]] extra_id_token_claims=None # type: Optional[Union[Mapping[str, Union[str, List[str]]], Callable[[str, str], Mapping[str...
Write a Python 3 function for handling a token request.
You are a Python code analyst, evaluating scripts for potential improvements.
Handles an authorization code request for an access token and returns a token response containing a signed ID Token an Access Token and a Refresh Token.
Here you have a function in Python 3, explain what it does def _do_code_exchange(self, request, # type: Dict[str, str] extra_id_token_claims=None # type: Optional[Union[Mapping[str, Union[str, List[str]]], Callable[[str, str], Mapping[str, Union[str, List[str]]]]] ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _do_token_refresh(self, request): # type: (Mapping[str, str]) -> oic.oic.message.AccessTokenResponse """ Handles a token request for refreshing an access token (grant_type=refresh_token). :param request: parsed http request parameters :return: a token response containing a ne...
How would you implement a function in Python 3 that handles a request for refreshing an access token
You are a Python code analyst, evaluating scripts for potential improvements.
def _verify_client_authentication(self, request_body, http_headers=None): # type (str, Optional[Mapping[str, str]] -> Mapping[str, str] """ Verifies the client authentication. :param request_body: urlencoded token request :param http_headers: :return: The parsed request b...
How would you code a function in Python 3 to verify the client authentication.
You are a Python code analyst, evaluating scripts for potential improvements.
def handle_userinfo_request(self, request=None, http_headers=None): # type: (Optional[str], Optional[Mapping[str, str]]) -> oic.oic.message.OpenIDSchema """ Handles a userinfo request. :param request: urlencoded request (either query string or POST body) :param http_headers: http...
Write a Python 3 function that can handle a userinfo request.
You are a Python code architect, reviewing and designing scalable and efficient code
Match client preferences with provider capabilities.
Given the following Python 3 function, write the documentation def match_client_preferences_with_provider_capabilities(self, client_preferences): # type: (oic.message.RegistrationRequest) -> Mapping[str, Union[str, List[str]]] """ Match as many as of the client preferences as possible. :...
You are a Python code generator, capable of creating scripts from specifications.
def handle_client_registration_request(self, request, http_headers=None): # type: (Optional[str], Optional[Mapping[str, str]]) -> oic.oic.message.RegistrationResponse """ Handles a client registration request. :param request: JSON request from POST body :param http_headers: http ...
Write a Python 3 function that can handle a client registration request.
As a Python code translator, you convert algorithms and pseudocode into Python.
Extracts a Bearer token from an HTTP request.
How would you explain what the following Python 3 function does def extract_bearer_token_from_http_request(parsed_request=None, authz_header=None): # type (Optional[Mapping[str, str]], Optional[str] -> str """ Extracts a Bearer token from an http request :param parsed_request: parsed request (URL query ...
As a Python code composer, you craft elegant and concise scripts.
Reconstructs a MongoDB URI from a parsed dict.
Can you generate a brief explanation for the following Python 3 code def _format_mongodb_uri(parsed_uri): user_pass = '' if parsed_uri.get('username') and parsed_uri.get('password'): user_pass = '{username!s}:{password!s}@'.format(**parsed_uri) _nodes = [] for host, port in parsed_uri.get('node...
As a Python code composer, you craft elegant and concise scripts.
def sanitized_uri(self): """ Return the database URI we're using in a format sensible for logging etc. :return: db_uri """ if self._sanitized_uri is None: _parsed = copy.copy(self._parsed_uri) if 'username' in _parsed: _parsed['password'] ...
Write a Python 3 function for returning the database URI we re using in a format sensible for logging etc.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a pymongo database handle after authenticating.
Can you tell what is the following Python 3 function doing def get_database(self, database_name=None, username=None, password=None): if database_name is None: database_name = self._database_name if database_name is None: raise ValueError('No database_name supplied, and no default...
As a Python code composer, you craft elegant and concise scripts.
def get_collection(self, collection, database_name=None, username=None, password=None): """ Get a pymongo collection handle. :param collection: Name of collection :param database_name: (optional) Name of database :param username: (optional) Username to login with :param ...
How would you code a function in Python 3 to get a pymongo collection handle.
You are a Python code generator, capable of creating scripts from specifications.
Create a balanced binary tree.
Given the following Python 3 function, write the documentation def balanced_binary_tree(n_leaves): def _balanced_subtree(leaves): if len(leaves) == 1: return leaves[0] elif len(leaves) == 2: return (leaves[0], leaves[1]) else: split = len(leaves) // 2 ...
You are a Python code generator, capable of creating scripts from specifications.
Create a decision list of n_leaves elements.
Given the following Python 3 function, write the documentation def decision_list(n_leaves): def _list(leaves): if len(leaves) == 2: return (leaves[0], leaves[1]) else: return (leaves[0], _list(leaves[1:])) return _list(np.arange(n_leaves))
As a Python code translator, you convert algorithms and pseudocode into Python.
Randomly partition the nodes into n_leaves nodes
Make a summary of the following Python 3 code def random_tree(n_leaves): def _random_subtree(leaves): if len(leaves) == 1: return leaves[0] elif len(leaves) == 2: return (leaves[0], leaves[1]) else: split = npr.randint(1, len(leaves)-1) return ...
As a Python code composer, you craft elegant and concise scripts.
Return the leaves in this subtree.
Can you generate a brief explanation for the following Python 3 code def leaves(tree): lvs = [] def _leaves(node): if np.isscalar(node): lvs.append(node) elif isinstance(node, tuple) and len(node) == 2: _leaves(node[0]) _leaves(node[1]) else: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def choices(tree): """ Get the 'address' of each leaf node in terms of internal node choices """ n = len(leaves(tree)) addr = np.nan * np.ones((n, n-1)) def _addresses(node, index, choices): # index is the index of the current internal node # choices is a list of (indice, 0/1...
Implement a function in Python 3 to get the address of each leaf node in terms of internal node choices
You are a Python code generator, capable of creating scripts from specifications.
def adjacency(tree): """ Construct the adjacency matrix of the tree :param tree: :return: """ dd = ids(tree) N = len(dd) A = np.zeros((N, N)) def _adj(node): if np.isscalar(node): return elif isinstance(node, tuple) and len(node) == 2: A[dd[no...
Implement a Python 3 function for constructing the adjacency matrix of the tree
As a Python code composer, you craft elegant and concise scripts.
This method calculates the maximum likelihood of a set of data.
Explain what the following Python 3 code does def max_likelihood(self, data, weights=None, stats=None, lmbda=0.1): import autograd.numpy as anp from autograd import value_and_grad, hessian_vector_product from scipy.optimize import minimize assert weights is None assert stats is ...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_claims_for(self, user_id, requested_claims): # type: (str, Mapping[str, Optional[Mapping[str, Union[str, List[str]]]]) -> Dict[str, Union[str, List[str]]] """ Filter the userinfo based on which claims where requested. :param user_id: user identifier :param requested_claim...
Write a Python 3 script to return a dictionary of claims that are available for the given user_id.
As a Python code analyst, you investigate and solve complex coding mysteries
def create_authorization_code(self, authorization_request, subject_identifier, scope=None): # type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> str """ Creates an authorization code bound to the authorization request and the authenticated user identified by the su...
How would you code a function in Python 3 to create an authorization code bound to the authorization request and the authenticated user identified by the subject identifier.
As a Python code translator, you convert algorithms and pseudocode into Python.
Creates an access token bound to the given authorization request and the authenticated user identified by the subject identifier.
Here you have a function in Python 3, explain what it does def create_access_token(self, authorization_request, subject_identifier, scope=None): # type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> se_leg_op.access_token.AccessToken """ Creates an access token bound to the...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None): # type: (str, Mapping[str, Union[str, List[str]]], str, Optional[str]) -> se_leg_op.access_token.AccessToken """ Creates an access token bound to the subject identifier, client id and requested scope...
Write a Python 3 script to create an access token bound to the subject identifier client id and requested scope.
As a Python code composer, you craft elegant and concise scripts.
Returns an access token object for the given authorization code.
Make a summary of the following Python 3 code def exchange_code_for_token(self, authorization_code): # type: (str) -> se_leg_op.access_token.AccessToken """ Exchanges an authorization code for an access token. """ if authorization_code not in self.authorization_codes: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the Introspection data associated with the access token.
Make a summary of the following Python 3 code def introspect_access_token(self, access_token_value): # type: (str) -> Dict[str, Union[str, List[str]]] """ Returns authorization data associated with the access token. See <a href="https://tools.ietf.org/html/rfc7662">"Token Introspection",...
As a Python code analyst, you investigate and solve complex coding mysteries
def create_refresh_token(self, access_token_value): # type: (str) -> str """ Creates an refresh token bound to the specified access token. """ if access_token_value not in self.access_tokens: raise InvalidAccessToken('{} unknown'.format(access_token_value)) i...
Implement a Python 3 function for creating a new refresh token bound to the specified access token.
As a Python code translator, you convert algorithms and pseudocode into Python.
Creates a new access token and a new refresh token based on the supplied refresh token.
How would you explain what the following Python 3 function does def use_refresh_token(self, refresh_token, scope=None): # type (str, Optional[List[str]]) -> Tuple[se_leg_op.access_token.AccessToken, Optional[str]] """ Creates a new access token, and refresh token, based on the supplied refresh t...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_subject_identifier(self, subject_type, user_id, sector_identifier=None): # type: (str, str, str) -> str """ Returns a subject identifier for the local user identifier. :param subject_type: 'pairwise' or 'public', see <a href="http://openid.net/specs/openid-connect-cor...
How would you code a function in Python 3 to return the subject identifier for the given user identifier.
As a Python code translator, you convert algorithms and pseudocode into Python.
Verifies that all required parameters and correct values are included in the authentication request.
Explain what the following Python 3 code does def authorization_request_verify(authentication_request): try: authentication_request.verify() except MessageException as e: raise InvalidAuthenticationRequest(str(e), authentication_request, oauth_error='invalid_request') from e
As a Python code composer, you craft elegant and concise scripts.
Verifies the client identifier is known.
Can you generate the documentation for the following Python 3 function def client_id_is_known(provider, authentication_request): if authentication_request['client_id'] not in provider.clients: logger.error('Unknown client_id \'{}\''.format(authentication_request['client_id'])) raise InvalidAuthentic...
As a Python code composer, you craft elegant and concise scripts.
Verifies that the redirect uri is registered for the client making the request.
Make a summary of the following Python 3 code def redirect_uri_is_in_registered_redirect_uris(provider, authentication_request): error = InvalidAuthenticationRequest('Redirect uri is not registered', authentication_request, oauth_erro...
As a python code expert, you are capable of creating scripts from specifications.
def response_type_is_in_registered_response_types(provider, authentication_request): """ Verifies that the requested response type is allowed for the client making the request. :param provider: provider instance :param authentication_request: authentication request to verify :raise InvalidAuthentica...
Can you write a function in Python 3 where it verifies that the requested response type is allowed for the client making the request.
You are a Python code generator, capable of creating scripts from specifications.
def userinfo_claims_only_specified_when_access_token_is_issued(authentication_request): """ According to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter"> "OpenID Connect Core 1.0", Section 5.5</a>: "When the userinfo member is used, the request MUST also use a response_typ...
Write a Python 3 function for according to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter"> "OpenID Connect Core 1.0", Section 5.5</a>: "When the userinfo member is used, the request MUST also use a response_type value that results in an Access Token being issued to the Client for use at ...
As a python code expert, you are capable of creating scripts from specifications.
def registration_request_verify(registration_request): """ Verifies that all required parameters and correct values are included in the client registration request. :param registration_request: the authentication request to verify :raise InvalidClientRegistrationRequest: if the registration is incorrect...
Implement a function in Python 3 to verify that all required parameters and correct values are included in the client registration request.
You are a Python code generator, capable of creating scripts from specifications.
def client_preferences_match_provider_capabilities(provider, registration_request): """ Verifies that all requested preferences in the client metadata can be fulfilled by this provider. :param registration_request: the authentication request to verify :raise InvalidClientRegistrationRequest: if the regi...
Implement a function in Python 3 to verify that all requested preferences in the client metadata can be fulfilled by this provider.
You are a Python code architect, reviewing and designing scalable and efficient code
def _psi_n(x, n, b): """ Compute the n-th term in the infinite sum of the Jacobi density. """ return 2**(b-1) / gamma(b) * (-1)**n * \ np.exp(gammaln(n+b) - gammaln(n+1) + np.log(2*n+b) - 0.5 * np.log(2*np.pi*x**3) - (2*n+b)**2 / (8.*x))
Create a Python 3 function to compute the n - th term in the infinite sum of the Jacobi density.
As a Python code translator, you convert algorithms and pseudocode into Python.
Compute the tilt of the PG density for value omega and tilt psi.
Can you generate the documentation for the following Python 3 function def _tilt(omega, b, psi): return np.cosh(psi/2.0)**b * np.exp(-psi**2/2.0 * omega)
You are a Python code generator, capable of creating scripts from specifications.
def pgpdf(omega, b, psi, trunc=200): """ Approximate the density log PG(omega | b, psi) using a truncation of the density written as an infinite sum. :param omega: point at which to evaluate density :param b: first parameter of PG :param psi: tilting of PG :param trunc: number of terms in...
Write a Python 3 script for computing the density log PG of omega | b psi
You are a Python code analyst, evaluating scripts for potential improvements.
def psi_to_pi(psi, axis=None): """ Convert psi to a probability vector pi :param psi: Length K-1 vector :return: Length K normalized probability vector """ if axis is None: if psi.ndim == 1: K = psi.size + 1 pi = np.zeros(K) # Set pi[1..K-1...
Can you write a function in Python 3 where it converts a psi array to a probability vector pi.
You are a Python code generator, capable of creating scripts from specifications.
Verifies the client authentication at the token endpoint.
Explain what the following Python 3 code does def verify_client_authentication(clients, parsed_request, authz_header=None): # type: (Mapping[str, str], Mapping[str, Mapping[str, Any]], Optional[str]) -> bool """ Verifies client authentication at the token endpoint, see <a href="https://tools.ietf.org/ht...
You are a Python code analyst, evaluating scripts for potential improvements.
Adds a visualization to the dashboard.
Make a summary of the following Python 3 code def add_visualization(self, visualization, size_x=6, size_y=3, col=0, row=0): new_panel_index = self.get_max_index()+1 if col and row: new_panel = { 'col': col, 'row': row, 'size_x': size_x, 'size_y': size_y, ...
You are a Python code analyst, evaluating scripts for potential improvements.
def remove_visualization(self, visualization_id): """ Removes all visualizations with the specified id from the dashboard :param visualization_id: :return: """ for i, panel in enumerate(self.panels): if panel['id'] == visualization_id: del self...
Write a Python 3 script to remove all visualizations with the specified id from the dashboard.
As a python code expert, you are capable of creating scripts from specifications.
def get_all(self): """ Returns a list of all visualizations :return: list of the Visualization instances """ res = self.es.search(index=self.index, doc_type=self.doc_type, body={'query': {'match_all': {}}}) if not res['hits']['total']: return [] return...
Implement a Python 3 function for returning a list of all visualizations
As a Python code composer, you craft elegant and concise scripts.
def add(self, visualization): """ Creates a new visualization :param visualization: instance of Visualization :return: """ res = self.es.create(index=self.index, id=visualization.id or str(uuid.uuid1()), doc_type=s...
Write a Python 3 script for adding a new visualization to the index
As a Python code translator, you convert algorithms and pseudocode into Python.
Updates existing visualization with new data
Given the following Python 3 function, write the documentation def update(self, visualization): res = self.es.update(index=self.index, id=visualization.id, doc_type=self.doc_type, body={'doc': visualization.to_kibana()}, refresh=True) return res
You are a Python code generator, capable of creating scripts from specifications.
def remove(self, visualization): """ Deletes the visualization :param visualization: instance of Visualization that was previously loaded :return: """ res = self.es.delete(index=self.index, id=visualization.id, doc_type=self.doc_type, refresh=True) return res
Can you implement a function in Python 3 that deletes the visualization s related items from the index
As a python code expert, you are capable of creating scripts from specifications.
def bottoms(panels): """ Finds bottom lines of all panels :param panels: :return: sorted by row list of tuples representing lines (col, row , col + len, row) """ bottom_lines = [(p['col'], p['row'] + p['size_y'], p['col'] + p['size_x'], p['row'] + p['size_y']) for p in panels] return sorted(...
Write a Python 3 script for finding bottom lines of all panels in a
As a Python code analyst, you investigate and solve complex coding mysteries
Find a shape of lowest horizontal lines with step = 1
Make a summary of the following Python 3 code def find_shape(bottom_lines, max_len): shape = [1] * max_len for i in range(max_len): for line in bottom_lines: if line[0] <= i + 1 < line[2]: shape[i] = line[1] break return shape
As a python code expert, you are capable of creating scripts from specifications.
Creates lines from shape containing longest available data.
Explain what the following Python 3 code does def longest_lines(shape): lines = [] for level in set(shape): count = 0 for i in range(len(shape)): if shape[i] <= level: count += 1 elif count: lines.append({'row': level, 'col': i - count + 1,...
You are a Python code architect, reviewing and designing scalable and efficient code
def append_panel(panels, size_x, size_y, max_col=12): """ Appends a panel to the list of panels. Finds the highest palce at the left for the new panel. :param panels: :param size_x: :param size_y: :param max_col: :return: a new panel or None if it is not possible to place a panel with such s...
Implement a function in Python 3 to append a panel to the list of panels.
As a Python code analyst, you investigate and solve complex coding mysteries