sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _set_results_dir(self): """Create results directory if not exists.""" if self.running_instance_id: self.results_dir = os.path.join( self.results_dir, self.cloud, self.image_id, self.running_instance_id ) ...
Create results directory if not exists.
entailment
def _collect_vm_info(self): """ Gather basic info about VM """ self.logger.info('Collecting basic info about VM') client = self._get_ssh_client() out = self.distro.get_vm_info(client) self._write_to_log(out)
Gather basic info about VM
entailment
def _update_history(self): """Save the current test information to history json.""" ipa_utils.update_history_log( self.history_log, description=self.description, test_log=self.log_file )
Save the current test information to history json.
entailment
def _wait_on_instance(self, state, timeout=600, wait_period=10): """Wait until instance is in given state.""" current_state = 'Undefined' start = time.time() end = start + timeout while time.time() < end: current_state = self._get_instance_state() if sta...
Wait until instance is in given state.
entailment
def execute_ssh_command(self, client, command): """Execute the provided command and log output.""" try: out = ipa_utils.execute_ssh_command(client, command) except Exception as error: raise IpaCloudException( 'Command: "{0}", failed execution: {1}.'.format...
Execute the provided command and log output.
entailment
def extract_archive(self, client, archive_path, extract_path=None): """Extract the archive files using the client in the current path.""" try: out = ipa_utils.extract_archive(client, archive_path, extract_path) except Exception as error: raise IpaCloudException( ...
Extract the archive files using the client in the current path.
entailment
def hard_reboot_instance(self): """Stop then start the instance.""" self._stop_instance() self._start_instance() self._set_instance_ip() self.logger.debug('IP of instance: %s' % self.instance_ip) ipa_utils.clear_cache()
Stop then start the instance.
entailment
def install_package(self, client, package): """ Install package using distro specific install method. """ try: out = self.distro.install_package(client, package) except Exception as error: raise IpaCloudException( 'Failed installing package...
Install package using distro specific install method.
entailment
def process_injection_file(self, client): """ Load yaml file and process injection configuration. There are 5 injection options: :inject_packages: an rpm path or list of rpm paths which will be copied and installed on the test instance. :inject_archive...
Load yaml file and process injection configuration. There are 5 injection options: :inject_packages: an rpm path or list of rpm paths which will be copied and installed on the test instance. :inject_archives: an archive or list of archives which will ...
entailment
def put_file(self, client, source_file): """ Put file on instance in default SSH directory. """ try: file_name = os.path.basename(source_file) ipa_utils.put_file(client, source_file, file_name) except Exception as error: raise IpaCloudException...
Put file on instance in default SSH directory.
entailment
def build_transgenic_lines(self): """ init class | "transgenic_line_source_name":"stock_number" a Class add superClass | rdfs:subClassOf ilxtr:transgenicLine add *order* | ilxtr:useObjectProperty ilxtr:<order> add name | rdfs:label "name" add def |...
init class | "transgenic_line_source_name":"stock_number" a Class add superClass | rdfs:subClassOf ilxtr:transgenicLine add *order* | ilxtr:useObjectProperty ilxtr:<order> add name | rdfs:label "name" add def | definition: "description" add transtype | ...
entailment
def decodeIlxResp(resp): """ We need this until we can get json back directly and this is SUPER nasty""" lines = [_ for _ in resp.text.split('\n') if _] # strip empties if 'successfull' in lines[0]: return [(_.split('"')[1], ilxIdFix(_.split(': ')[-1])) for _ in li...
We need this until we can get json back directly and this is SUPER nasty
entailment
def getSubOrder(existing): """ Alpha sort by the full chain of parents. """ alpha = list(zip(*sorted(((k, v['rec']['label']) for k, v in existing.items()), key=lambda a: a[1])))[0] depths = {} def getDepth(id_): if id_ in depths: return depths[id_] else: if id_ in...
Alpha sort by the full chain of parents.
entailment
def clean(string): ''' Begining of the string can sometimes have odd noise ''' # manual fixes in the source # 24/1.png # 9/1.png # 3/1.png #if ')' in string: # fix in the source data #string = string.split(')')[0] + ')' # remove trailing garbage return (string .replace(...
Begining of the string can sometimes have odd noise
entailment
def loadData(cls): """ Sigh, this was indeed a poorly conceived approach since it hard blocks when the files are not in the source so you can't easily bootstrap from another source and the cognitive overhead is way, way too high :/ Adding dry_run/bootstrap to __new__ sort of he...
Sigh, this was indeed a poorly conceived approach since it hard blocks when the files are not in the source so you can't easily bootstrap from another source and the cognitive overhead is way, way too high :/ Adding dry_run/bootstrap to __new__ sort of helps?
entailment
def ilx_conv(graph, prefix, ilx_start): """ convert a set of temporary identifiers to ilx and modify the graph in place """ to_sub = set() for subject in graph.subjects(rdflib.RDF.type, rdflib.OWL.Class): if PREFIXES[prefix] in subject: to_sub.add(subject) ilx_base = 'ilx_{:0>7}' ...
convert a set of temporary identifiers to ilx and modify the graph in place
entailment
def alreadyHasEntry(oldClassString, og): """ Return true if there is already an owl:Class with the old id""" namespace = oldClassString.split(':')[0] if namespace == 'http': target = rdflib.URIRef(oldClassString) print('OLD CLASS ID IS A URL', oldClassString) else: try: ...
Return true if there is already an owl:Class with the old id
entailment
def config(remote_base= 'https://raw.githubusercontent.com/SciCrunch/NIF-Ontology/', local_base= None, # devconfig.ontology_local_repo by default branch= devconfig.neurons_branch, core_graph_paths= ['ttl/phenotype-core.ttl', 'ttl/ph...
Wraps graphBase.configGraphIO to provide a set of sane defaults for input ontologies and output files.
entailment
def add_version_iri(graph, epoch): """ Also remove the previous versionIRI if there was one.""" for ont in graph.subjects(rdf.type, owl.Ontology): for versionIRI in graph.objects(ont, owl.versionIRI): graph.remove((ont, owl.versionIRI, versionIRI)) t = ont, owl.versionIRI, make_versi...
Also remove the previous versionIRI if there was one.
entailment
def auth(self): """ Return credentials for current Bitbucket user. """ if self.oauth: return self.oauth return (self.username, self.password)
Return credentials for current Bitbucket user.
entailment
def authorize(self, consumer_key, consumer_secret, callback_url=None, access_token=None, access_token_secret=None): """ Call this with your consumer key, secret and callback URL, to generate a token for verification. """ self.consumer_key = consumer_key ...
Call this with your consumer key, secret and callback URL, to generate a token for verification.
entailment
def verify(self, verifier, consumer_key=None, consumer_secret=None, access_token=None, access_token_secret=None): """ After converting the token into verifier, call this to finalize the authorization. """ # Stored values can be supplied to verify self.consu...
After converting the token into verifier, call this to finalize the authorization.
entailment
def finalize_oauth(self, access_token, access_token_secret): """ Called internally once auth process is complete. """ self.access_token = access_token self.access_token_secret = access_token_secret # Final OAuth object self.oauth = OAuth1( self.consumer_key, ...
Called internally once auth process is complete.
entailment
def dispatch(self, method, url, auth=None, params=None, **kwargs): """ Send HTTP request, with given method, credentials and data to the given URL, and return the success and the result on success. """ r = Request( method=method, url=url, ...
Send HTTP request, with given method, credentials and data to the given URL, and return the success and the result on success.
entailment
def url(self, action, **kwargs): """ Construct and return the URL for a specific API service. """ # TODO : should be static method ? return self.URLS['BASE'] % self.URLS[action] % kwargs
Construct and return the URL for a specific API service.
entailment
def get_user(self, username=None): """ Returns user informations. If username is not defined, tries to return own informations. """ username = username or self.username or '' url = self.url('GET_USER', username=username) response = self.dispatch('GET', url) tr...
Returns user informations. If username is not defined, tries to return own informations.
entailment
def get_tags(self, repo_slug=None): """ Get a single repository on Bitbucket and return its tags.""" repo_slug = repo_slug or self.repo_slug or '' url = self.url('GET_TAGS', username=self.username, repo_slug=repo_slug) return self.dispatch('GET', url, auth=self.auth)
Get a single repository on Bitbucket and return its tags.
entailment
def get_branches(self, repo_slug=None): """ Get a single repository on Bitbucket and return its branches.""" repo_slug = repo_slug or self.repo_slug or '' url = self.url('GET_BRANCHES', username=self.username, repo_slug=repo_slug) return self...
Get a single repository on Bitbucket and return its branches.
entailment
def get_privileges(self): """ Get privledges for this user. """ url = self.url('GET_USER_PRIVILEGES') return self.dispatch('GET', url, auth=self.auth)
Get privledges for this user.
entailment
def create(self, repo_slug=None, key=None, label=None): """ Associate an ssh key with your repo and return it. """ key = '%s' % key repo_slug = repo_slug or self.bitbucket.repo_slug or '' url = self.bitbucket.url('SET_DEPLOY_KEY', username=self.bi...
Associate an ssh key with your repo and return it.
entailment
def public(self, username=None): """ Returns all public repositories from an user. If username is not defined, tries to return own public repos. """ username = username or self.bitbucket.username or '' url = self.bitbucket.url('GET_USER', username=username) response =...
Returns all public repositories from an user. If username is not defined, tries to return own public repos.
entailment
def all(self): """ Return own repositories.""" url = self.bitbucket.url('GET_USER', username=self.bitbucket.username) response = self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth) try: return (response[0], response[1]['repositories']) except TypeError: ...
Return own repositories.
entailment
def create(self, repo_name, scm='git', private=True, **kwargs): """ Creates a new repository on own Bitbucket account and return it.""" url = self.bitbucket.url('CREATE_REPO') return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, name=repo_name, scm=scm, is_private=private, **kwa...
Creates a new repository on own Bitbucket account and return it.
entailment
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...
Get one of your repositories and compress it as an archive. Return the path of the archive. format parameter is curently not supported.
entailment
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...
Add an issue comment to one of your repositories. Each issue comment require only the content data field the system autopopulate the rest.
entailment
def delete(self, comment_id, issue_id=None, repo_slug=None): """ Delete an issue from one of your repositories. """ issue_id = issue_id or self.issue_id repo_slug = repo_slug or self.bitbucket.repo_slug or '' url = self.bitbucket.url('DELETE_COMMENT', ...
Delete an issue from one of your repositories.
entailment
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)
Get all ssh keys associated with your account.
entailment
def get(self, key_id=None): """ Get one of the ssh keys associated with your account. """ url = self.bitbucket.url('GET_SSH_KEY', key_id=key_id) return self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth)
Get one of the ssh keys associated with your account.
entailment
def create(self, key=None, label=None): """ Associate an ssh key with your account and return it. """ key = '%s' % key url = self.bitbucket.url('SET_SSH_KEY') return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, key=key, label=label)
Associate an ssh key with your account and return it.
entailment
def delete(self, key_id=None): """ Delete one of the ssh keys associated with your account. Please use with caution as there is NO confimation and NO undo. """ url = self.bitbucket.url('DELETE_SSH_KEY', key_id=key_id) return self.bitbucket.dispatch('DELETE', url, auth=self.bi...
Delete one of the ssh keys associated with your account. Please use with caution as there is NO confimation and NO undo.
entailment
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...
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, return the first match found. ...
entailment
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 ...
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 the file. Defaults to 'a', append Usage exam...
entailment
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: raise Exception('Failed to parse vagrant --version ou...
Return the installed vagrant version, as a string, e.g. '1.5.0'
entailment
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=None: name of VM. provision_with: optional list of p...
Invoke `vagrant up` to start a box or boxes, possibly streaming the command output. vm_name=None: name of VM. provision_with: optional list of provisioners to enable. provider: Back the machine with a specific provider no_provision: if True, disable provisioning. Same as 'provis...
entailment
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...
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']
entailment
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...
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. After making any modifications to the Vagrantfile, a reload should be called. > The configured provisioners ...
entailment
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]) self._cached_conf[vm_name] = None
Halt the Vagrant box. force: If True, force shut down.
entailment
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. 'default' otherwise. - state: The state of the underlying guest...
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. 'default' otherwise. - state: The state of the underlying guest machine (i.e. VM). - provider: the name of ...
entailment
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 target name # assuming tuples are sorted by target name,...
Unit testing is so much easier when Vagrant is removed from the equation.
entailment
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'), 'Port' (e.g. '2222'), 'IdentityFile' (...
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'), 'Port' (e.g. '2222'), 'IdentityFile' (e.g. '/home/todd/.ssh/id_dsa'). Cache the parsed configura...
entailment
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 string, e.g. 'localhost'. If hostname is None, have bigger ...
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 string, e.g. 'localhost'. If hostname is None, have bigger problems. Raises an Exception if the Vagrant box h...
entailment
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 empty, they will be left out of the string. E.g. 'vagrant@loc...
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 empty, they will be left out of the string. E.g. 'vagrant@localhost', or 'localhost:2222' or 'localhost'. If hostnam...
entailment
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...
Adds a box with given name, from given url. force: If True, overwrite an existing box if it exists.
entailment
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 output=None: name of the file to output vagrantfile=...
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 output=None: name of the file to output vagrantfile=None: Vagrantfile to package with this box
entailment
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', 'pop']) if NO_SNAPSHOTS_PUSHED in output: ...
This command is the inverse of vagrant snapshot push: it will restore the pushed state.
entailment
def snapshot_list(self): ''' This command will list all the snapshots taken. ''' NO_SNAPSHOTS_TAKEN = 'No snapshots have been taken yet!' output = self._run_vagrant_command(['snapshot', 'list']) if NO_SNAPSHOTS_TAKEN in output: return [] else: ...
This command will list all the snapshots taken.
entailment
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. '''...
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.
entailment
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): ...
Remove Vagrant usage for unit testing
entailment
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...
Remove Vagrant from the equation for unit testing.
entailment
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...
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 type/kind to its data. Machine-readable output is a co...
entailment
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]`. Specifically it assumes that there is only one Host section, the ...
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]`. Specifically it assumes that there is only one Host section, the default vagrant host. It assumes that the parame...
entailment
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...
Run a vagrant command. Return None. args: A sequence of arguments to a vagrant command line.
entailment
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...
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.
entailment
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...
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 yields each line of the command stdout. :rtype: generator...
entailment
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_sandbox_command(['status', vm_name]) return self._parse_va...
Returns the status of the sandbox mode. Possible values are: - on - off - unknown - not installed
entailment
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 # [default] - machine not created # if the ...
Returns the status of the sandbox mode given output from 'vagrant sandbox status'.
entailment
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...
Convert JSON dicts back into objects.
entailment
def serialize(obj): """Convert objects into JSON structures.""" # Record class and module information for deserialization result = {'__class__': obj.__class__.__name__} try: result['__module__'] = obj.__module__ except AttributeError: pass # Convert objects to dictionary represen...
Convert objects into JSON structures.
entailment
def _serialize_json(obj, fp): """ Serialize ``obj`` as a JSON formatted stream to ``fp`` """ json.dump(obj, fp, indent=4, default=serialize)
Serialize ``obj`` as a JSON formatted stream to ``fp``
entailment
def get_serializer(serializer_format): """ Get the serializer for a specific format """ if serializer_format == Format.JSON: return _serialize_json if serializer_format == Format.PICKLE: return _serialize_pickle
Get the serializer for a specific format
entailment
def get_deserializer(serializer_format): """ Get the deserializer for a specific format """ if serializer_format == Format.JSON: return _deserialize_json if serializer_format == Format.PICKLE: return _deserialize_pickle
Get the deserializer for a specific format
entailment
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) ...
Convenience function to quickly configure full debug output to go to the console.
entailment
def find_file_format(file_name): """ Returns a tuple with the file path and format found, or (None, None) """ for file_format in Format.ALLOWED: file_path = '.'.join((file_name, file_format)) if os.path.exists(file_path): return file_path, file_for...
Returns a tuple with the file path and format found, or (None, None)
entailment
def get_next_file_path(self, service, operation): """ Returns a tuple with the next file to read and the serializer format used """ base_name = '{0}.{1}'.format(service, operation) if self.prefix: base_name = '{0}.{1}'.format(self.prefix, base_name) LO...
Returns a tuple with the next file to read and the serializer format used
entailment
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. DescribeInstances), the ``response_data`` should a value you wa...
Store a response to the data directory. The ``operation`` should be the name of the operation in the service API (e.g. DescribeInstances), the ``response_data`` should a value you want to return from a placebo call and the ``http_response`` should be the HTTP status code returned from t...
entailment
def _mock_request(self, **kwargs): """ A mocked out make_request call that bypasses all network calls and simply returns any mocked responses defined. """ model = kwargs.get('model') service = model.service_model.endpoint_prefix operation = model.name LOG....
A mocked out make_request call that bypasses all network calls and simply returns any mocked responses defined.
entailment
def placebo_session(function): """ Decorator to help do testing with placebo. Simply wrap the function you want to test and make sure to add a "session" argument so the decorator can pass the placebo session. Accepts the following environment variables to configure placebo: PLACEBO_MODE: set to ...
Decorator to help do testing with placebo. Simply wrap the function you want to test and make sure to add a "session" argument so the decorator can pass the placebo session. Accepts the following environment variables to configure placebo: PLACEBO_MODE: set to "record" to record AWS calls and save them ...
entailment
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...
Parses and verifies an authentication request. :param request_body: urlencoded authentication request :param http_headers: http headers
entailment
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]]]]] ...
Creates an Authentication Response for the specified authentication request and local identifier of the authenticated user.
entailment
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 ...
Adds the Access Token and the associated parameters to the Token Response.
entailment
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...
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", Section 1.2</a>. :param user_id: local user identifier :param client_id: which client to generate a subject identifier...
entailment
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...
Parses any claims requested using the 'claims' request parameter, see <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter"> "OpenID Connect Core 1.0", Section 5.5</a>. :param authentication_request: the authentication request :param response_method: 'id_token' o...
entailment
def _create_signed_id_token(self, client_id, # type: str sub, # type: str user_claims=None, # type: Optional[Mapping[str, Union[str, List[str]]]] nonce=None, # type: Optional[str] ...
Creates a signed ID Token. :param client_id: who the ID Token is intended for :param sub: who the ID Token is regarding :param user_claims: any claims about the user to be included :param nonce: nonce from the authentication request :param authorization_code: the authorization co...
entailment
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...
Verifies the subject identifier against any requested subject identifier using the claims request parameter. :param authentication_request: authentication request :param sub: subject identifier :raise AuthorizationError: if the subject identifier does not match the requested one
entailment
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...
Handles a token request, either for exchanging an authorization code or using a refresh token. :param request_body: urlencoded token request :param http_headers: http headers :param extra_id_token_claims: extra claims to include in the signed ID Token
entailment
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]]]]] ): # type: (...) -> oic.mes...
Handles a token request for exchanging an authorization code for an access token (grant_type=authorization_code). :param request: parsed http request parameters :param extra_id_token_claims: any extra parameters to include in the signed ID Token, either as a dict-like object or as a ...
entailment
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...
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 new Access Token and possibly a new Refresh Token :raise InvalidTokenRequest: if the token request is invalid
entailment
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...
Verifies the client authentication. :param request_body: urlencoded token request :param http_headers: :return: The parsed request body.
entailment
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...
Handles a userinfo request. :param request: urlencoded request (either query string or POST body) :param http_headers: http headers
entailment
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. :param client_preferences: requested preferences from client reg...
Match as many as of the client preferences as possible. :param client_preferences: requested preferences from client registration request :return: the matched preferences selected by the provider
entailment
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 ...
Handles a client registration request. :param request: JSON request from POST body :param http_headers: http headers
entailment
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 part of request body) :param authz_header: HTTP Authorizatio...
Extracts a Bearer token from an http request :param parsed_request: parsed request (URL query part of request body) :param authz_header: HTTP Authorization header :return: Bearer access token, if found :raise BearerTokenError: if no Bearer token could be extracted from the request
entailment
def _format_mongodb_uri(parsed_uri): """ Painstakingly reconstruct a MongoDB URI parsed using pymongo.uri_parser.parse_uri. :param parsed_uri: Result of pymongo.uri_parser.parse_uri :type parsed_uri: dict :return: New URI :rtype: str | unicode """ user_pass = '' if parsed_uri.get('...
Painstakingly reconstruct a MongoDB URI parsed using pymongo.uri_parser.parse_uri. :param parsed_uri: Result of pymongo.uri_parser.parse_uri :type parsed_uri: dict :return: New URI :rtype: str | unicode
entailment
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'] ...
Return the database URI we're using in a format sensible for logging etc. :return: db_uri
entailment
def get_database(self, database_name=None, username=None, password=None): """ Get a pymongo database handle, after authenticating. Authenticates using the username/password in the DB URI given to __init__() unless username/password is supplied as arguments. :param database_name...
Get a pymongo database handle, after authenticating. Authenticates using the username/password in the DB URI given to __init__() unless username/password is supplied as arguments. :param database_name: (optional) Name of database :param username: (optional) Username to login with ...
entailment
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 ...
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 password: (optional) Password to login with :return: Pymongo collection object
entailment
def balanced_binary_tree(n_leaves): """ Create a balanced binary tree """ 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 retur...
Create a balanced binary tree
entailment
def decision_list(n_leaves): """ Create a decision list """ 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))
Create a decision list
entailment
def random_tree(n_leaves): """ Randomly partition the nodes """ 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) retu...
Randomly partition the nodes
entailment
def leaves(tree): """ Return the leaves in this subtree. """ 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: raise Excep...
Return the leaves in this subtree.
entailment