text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _log_response(response): """Log out information about a ``Request`` object. After calling ``requests.request`` or one of its convenience methods, the object returned can be passed to this method. If done, information about the object returned is logged. :return: Nothing is returned. """
message = u'Received HTTP {0} response: {1}'.format( response.status_code, response.text ) if response.status_code >= 400: # pragma: no cover logger.warning(message) else: logger.debug(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(method, url, **kwargs): """A wrapper for ``requests.request``."""
_set_content_type(kwargs) if _content_type_is_json(kwargs) and kwargs.get('data') is not None: kwargs['data'] = dumps(kwargs['data']) _log_request(method, url, kwargs) response = requests.request(method, url, **kwargs) _log_response(response) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def head(url, **kwargs): """A wrapper for ``requests.head``."""
_set_content_type(kwargs) if _content_type_is_json(kwargs) and kwargs.get('data') is not None: kwargs['data'] = dumps(kwargs['data']) _log_request('HEAD', url, kwargs) response = requests.head(url, **kwargs) _log_response(response) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(url, data=None, json=None, **kwargs): """A wrapper for ``requests.post``."""
_set_content_type(kwargs) if _content_type_is_json(kwargs) and data is not None: data = dumps(data) _log_request('POST', url, kwargs, data) response = requests.post(url, data, json, **kwargs) _log_response(response) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(url, data=None, **kwargs): """A wrapper for ``requests.put``. Sends a PUT request."""
_set_content_type(kwargs) if _content_type_is_json(kwargs) and data is not None: data = dumps(data) _log_request('PUT', url, kwargs, data) response = requests.put(url, data, **kwargs) _log_response(response) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_response(response, server_config, synchronous=False, timeout=None): """Handle a server's response in a typical fashion. Do the following: 1. Check the server's response for an HTTP status code indicating an error. 2. Poll the server for a foreman task to complete if an HTTP 202 (accepted) status code is returned and ``synchronous is True``. 3. Immediately return if an HTTP "NO CONTENT" response is received. 4. Determine what type of the content returned from server. Depending on the type method should return server's response, with all JSON decoded or just response content itself. :param response: A response object as returned by one of the functions in :mod:`nailgun.client` or the requests library. :param server_config: A `nailgun.config.ServerConfig` object. :param synchronous: Should this function poll the server? :param timeout: Maximum number of seconds to wait until timing out. Defaults to ``nailgun.entity_mixins.TASK_TIMEOUT``. """
response.raise_for_status() if synchronous is True and response.status_code == ACCEPTED: return ForemanTask( server_config, id=response.json()['id']).poll(timeout=timeout) if response.status_code == NO_CONTENT: return if 'application/json' in response.headers.get('content-type', '').lower(): return response.json() elif isinstance(response.content, bytes): return response.content.decode('utf-8') else: return response.content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_missing(self): """Possibly set several extra instance attributes. If ``onthefly_register`` is set and is true, set the following instance attributes: * account_password * account_firstname * account_lastname * attr_login * attr_mail """
super(AuthSourceLDAP, self).create_missing() if getattr(self, 'onthefly_register', False) is True: for field in ( 'account_password', 'attr_firstname', 'attr_lastname', 'attr_login', 'attr_mail'): if not hasattr(self, field): setattr(self, field, self._fields[field].gen_value())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Do not read the ``account_password`` attribute. Work around a bug. For more information, see `Bugzilla #1243036 <https://bugzilla.redhat.com/show_bug.cgi?id=1243036>`_. """
if attrs is None: attrs = self.update_json([]) if ignore is None: ignore = set() ignore.add('account_password') return super(AuthSourceLDAP, self).read(entity, attrs, ignore, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Work around a bug. Rename ``search`` to ``search_``. For more information on the bug, see `Bugzilla #1257255 <https://bugzilla.redhat.com/show_bug.cgi?id=1257255>`_. """
if attrs is None: attrs = self.read_json() attrs['search_'] = attrs.pop('search') # Satellite doesn't return this attribute. See BZ 1257255. attr = 'max_count' if ignore is None: ignore = set() if attr not in ignore: # We cannot call `self.update_json([])`, as an ID might not be # present on self. However, `attrs` is guaranteed to have an ID. attrs[attr] = DiscoveryRule( self._server_config, id=attrs['id'], ).update_json([])[attr] return super(DiscoveryRule, self).read(entity, attrs, ignore, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Ignore usergroup from read and alter auth_source_ldap with auth_source """
if entity is None: entity = type(self)( self._server_config, usergroup=self.usergroup, # pylint:disable=no-member ) if ignore is None: ignore = set() ignore.add('usergroup') if attrs is None: attrs = self.read_json() attrs['auth_source'] = attrs.pop('auth_source_ldap') return super(ExternalUserGroup, self).read(entity, attrs, ignore, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, synchronous=True, **kwargs): """Helper to run existing job template :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. 'data' supports next fields: required: job_template_id/feature, targeting_type, search_query/bookmark_id, inputs optional: description_format, concurrency_control scheduling, ssh, recurrence, execution_timeout_interval :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) if 'data' in kwargs: if 'job_template_id' not in kwargs['data'] and 'feature' not in kwargs['data']: raise KeyError('Provide either job_template_id or feature value') if 'search_query' not in kwargs['data'] and 'bookmark_id' not in kwargs['data']: raise KeyError('Provide either search_query or bookmark_id value') for param_name in ['targeting_type', 'inputs']: if param_name not in kwargs['data']: raise KeyError('Provide {} value'.format(param_name)) kwargs['data'] = {u'job_invocation': kwargs['data']} response = client.post(self.path('base'), **kwargs) response.raise_for_status() if synchronous is True: return ForemanTask( server_config=self._server_config, id=response.json()['task']['id']).poll() return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Ignore the template inputs when initially reading the job template. Look up each TemplateInput entity separately and afterwords add them to the JobTemplate entity."""
if attrs is None: attrs = self.read_json(params=params) if ignore is None: ignore = set() ignore.add('template_inputs') entity = super(JobTemplate, self).read(entity=entity, attrs=attrs, ignore=ignore, params=params) referenced_entities = [ TemplateInput(entity._server_config, id=entity_id, template=JobTemplate(entity._server_config, id=entity.id)) for entity_id in _get_entity_ids('template_inputs', attrs) ] setattr(entity, 'template_inputs', referenced_entities) return entity
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload(self, filepath, filename=None): """Upload content. :param filepath: path to the file that should be chunked and uploaded :param filename: name of the file on the server, defaults to the last part of the ``filepath`` if not set :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. :raises nailgun.entities.APIResponseError: If the response has a status other than "success". .. _POST a Multipart-Encoded File: http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file .. _POST Multiple Multipart-Encoded Files: http://docs.python-requests.org/en/latest/user/advanced/#post-multiple-multipart-encoded-files """
if not filename: filename = os.path.basename(filepath) content_upload = self.create() try: offset = 0 content_chunk_size = 2 * 1024 * 1024 with open(filepath, 'rb') as contentfile: chunk = contentfile.read(content_chunk_size) while len(chunk) > 0: data = {'offset': offset, 'content': chunk} content_upload.update(data) offset += len(chunk) chunk = contentfile.read(content_chunk_size) size = 0 checksum = hashlib.sha256() with open(filepath, 'rb') as contentfile: contents = contentfile.read() size = len(contents) checksum.update(contents) uploads = [{'id': content_upload.upload_id, 'name': filename, 'size': size, 'checksum': checksum.hexdigest()}] # pylint:disable=no-member json = self.repository.import_uploads(uploads) finally: content_upload.delete() return json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Do not read certain fields. Do not expect the server to return the ``content_view_filter`` attribute. This has no practical impact, as the attribute must be provided when a :class:`nailgun.entities.ContentViewFilterRule` is instantiated. Also, ignore any field that is not returned by the server. For more information, see `Bugzilla #1238408 <https://bugzilla.redhat.com/show_bug.cgi?id=1238408>`_. """
if entity is None: entity = type(self)( self._server_config, # pylint:disable=no-member content_view_filter=self.content_view_filter, ) if attrs is None: attrs = self.read_json() if ignore is None: ignore = set() ignore.add('content_view_filter') ignore.update([ field_name for field_name in entity.get_fields().keys() if field_name not in attrs ]) return super(ContentViewFilterRule, self).read( entity, attrs, ignore, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(self, synchronous=True, **kwargs): """Helper for publishing an existing content view. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() # shadow the passed-in kwargs if 'data' in kwargs and 'id' not in kwargs['data']: kwargs['data']['id'] = self.id # pylint:disable=no-member kwargs.update(self._server_config.get_client_kwargs()) response = client.post(self.path('publish'), **kwargs) return _handle_response(response, self._server_config, synchronous)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_from_environment(self, environment, synchronous=True): """Delete this content view version from an environment. This method acts much like :meth:`nailgun.entity_mixins.EntityDeleteMixin.delete`. The documentation on that method describes how the deletion procedure works in general. This method differs only in accepting an ``environment`` parameter. :param environment: A :class:`nailgun.entities.Environment` object. The environment's ``id`` parameter *must* be specified. As a convenience, an environment ID may be passed in instead of an ``Environment`` object. """
if isinstance(environment, Environment): environment_id = environment.id else: environment_id = environment response = client.delete( '{0}/environments/{1}'.format(self.path(), environment_id), **self._server_config.get_client_kwargs() ) return _handle_response(response, self._server_config, synchronous)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, synchronous=True, **kwargs): """Add provided Content View Component. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() # shadow the passed-in kwargs if 'data' not in kwargs: # data is required kwargs['data'] = dict() if 'component_ids' not in kwargs['data']: kwargs['data']['components'] = [_payload(self.get_fields(), self.get_values())] kwargs.update(self._server_config.get_client_kwargs()) response = client.put(self.path('add'), **kwargs) return _handle_response(response, self._server_config, synchronous)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Deal with different named data returned from the server """
if attrs is None: attrs = self.read_json() attrs['override'] = attrs.pop('override?') attrs['unlimited'] = attrs.pop('unlimited?') return super(Filter, self).read(entity, attrs, ignore, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll(self, poll_rate=None, timeout=None): """Return the status of a task or timeout. There are several API calls that trigger asynchronous tasks, such as synchronizing a repository, or publishing or promoting a content view. It is possible to check on the status of a task if you know its UUID. This method polls a task once every ``poll_rate`` seconds and, upon task completion, returns information about that task. :param poll_rate: Delay between the end of one task check-up and the start of the next check-up. Defaults to ``nailgun.entity_mixins.TASK_POLL_RATE``. :param timeout: Maximum number of seconds to wait until timing out. Defaults to ``nailgun.entity_mixins.TASK_TIMEOUT``. :returns: Information about the asynchronous task. :raises: ``nailgun.entity_mixins.TaskTimedOutError`` if the task completes with any result other than "success". :raises: ``nailgun.entity_mixins.TaskFailedError`` if the task finishes with any result other than "success". :raises: ``requests.exceptions.HTTPError`` If the API returns a message with an HTTP 4XX or 5XX status code. """
# See nailgun.entity_mixins._poll_task for an explanation of why a # private method is called. return _poll_task( self.id, # pylint:disable=no-member self._server_config, poll_rate, timeout )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Deal with several bugs. For more information, see: * `Bugzilla #1235377 <https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_ * `Bugzilla #1235379 <https://bugzilla.redhat.com/show_bug.cgi?id=1235379>`_ * `Bugzilla #1450379 <https://bugzilla.redhat.com/show_bug.cgi?id=1450379>`_ """
if ignore is None: ignore = set() ignore.add('root_pass') ignore.add('kickstart_repository') if attrs is None: attrs = self.read_json() attrs['parent_id'] = attrs.pop('ancestry') # either an ID or None version = _get_version(self._server_config) if version >= Version('6.1') and version < Version('6.2'): # We cannot call `self.update_json([])`, as an ID might not be # present on self. However, `attrs` is guaranteed to have an ID. attrs2 = HostGroup( self._server_config, id=attrs['id'] ).update_json([]) for attr in ('content_source_id', 'content_view_id', 'lifecycle_environment_id'): attrs[attr] = attrs2.get(attr) return super(HostGroup, self).read(entity, attrs, ignore, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_puppetclass(self, synchronous=True, **kwargs): """Remove a Puppet class from host group Here is an example of how to use this method:: hostgroup.delete_puppetclass(data={'puppetclass_id': puppet.id}) Constructs path: /api/hostgroups/:hostgroup_id/puppetclass_ids/:id :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() kwargs.update(self._server_config.get_client_kwargs()) path = "{0}/{1}".format( self.path('puppetclass_ids'), kwargs['data'].pop('puppetclass_id') ) return _handle_response( client.delete(path, **kwargs), self._server_config, synchronous)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def owner_type(self, value): """Set ``owner_type`` to the given value. In addition: * Update the internal type of the ``owner`` field. * Update the value of the ``owner`` field if a value is already set. """
self._owner_type = value if value == 'User': self._fields['owner'] = entity_fields.OneToOneField(User) if hasattr(self, 'owner'): # pylint:disable=no-member self.owner = User( self._server_config, id=self.owner.id if isinstance(self.owner, Entity) else self.owner ) elif value == 'Usergroup': self._fields['owner'] = entity_fields.OneToOneField(UserGroup) if hasattr(self, 'owner'): # pylint:disable=no-member self.owner = UserGroup( self._server_config, id=self.owner.id if isinstance(self.owner, Entity) else self.owner )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_values(self): """Correctly set the ``owner_type`` attribute."""
attrs = super(Host, self).get_values() if '_owner_type' in attrs and attrs['_owner_type'] is not None: attrs['owner_type'] = attrs.pop('_owner_type') else: attrs.pop('_owner_type') return attrs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def errata_applicability(self, synchronous=True, **kwargs): """Force regenerate errata applicability :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all content decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) response = client.put(self.path('errata/applicability'), **kwargs) return _handle_response(response, self._server_config, synchronous)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Deal with oddly named and structured data returned by the server. For more information, see `Bugzilla #1235019 <https://bugzilla.redhat.com/show_bug.cgi?id=1235019>`_ and `Bugzilla #1449749 <https://bugzilla.redhat.com/show_bug.cgi?id=1449749>`_. `content_facet_attributes` are returned only in case any of facet attributes were actually set. Also add image to the response if needed, as :meth:`nailgun.entity_mixins.EntityReadMixin.read` can't initialize image. """
if attrs is None: attrs = self.read_json() if ignore is None: ignore = set() if 'parameters' in attrs: attrs['host_parameters_attributes'] = attrs.pop('parameters') else: ignore.add('host_parameters_attributes') if 'content_facet_attributes' not in attrs: ignore.add('content_facet_attributes') ignore.add('compute_attributes') ignore.add('interfaces_attributes') ignore.add('root_pass') # Image entity requires compute_resource_id to initialize as it is # part of its path. The thing is that entity_mixins.read() initializes # entities by id only. # Workaround is to add image to ignore, call entity_mixins.read() # and then add 'manually' initialized image to the result. # If image_id is None set image to None as it is done by default. ignore.add('image') # host id is required for interface initialization ignore.add('interface') ignore.add('build_status_label') result = super(Host, self).read(entity, attrs, ignore, params) if attrs.get('image_id'): result.image = Image( server_config=self._server_config, id=attrs.get('image_id'), compute_resource=attrs.get('compute_resource_id'), ) else: result.image = None if 'interfaces' in attrs and attrs['interfaces']: result.interface = [ Interface( self._server_config, host=result.id, id=interface['id'], ) for interface in attrs['interfaces'] ] if 'build_status_label' in attrs: result.build_status_label = attrs['build_status_label'] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_payload(self): """Rename the payload key "prior_id" to "prior". For more information, see `Bugzilla #1238757 <https://bugzilla.redhat.com/show_bug.cgi?id=1238757>`_. """
payload = super(LifecycleEnvironment, self).create_payload() if (_get_version(self._server_config) < Version('6.1') and 'prior_id' in payload): payload['prior'] = payload.pop('prior_id') return payload
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_missing(self): """Automatically populate additional instance attributes. When a new lifecycle environment is created, it must either: * Reference a parent lifecycle environment in the tree of lifecycle environments via the ``prior`` field, or * have a name of "Library". Within a given organization, there can only be a single lifecycle environment with a name of 'Library'. This lifecycle environment is at the root of a tree of lifecycle environments, so its ``prior`` field is blank. This method finds the 'Library' lifecycle environment within the current organization and points to it via the ``prior`` field. This is not done if the current lifecycle environment has a name of 'Library'. """
# We call `super` first b/c it populates `self.organization`, and we # need that field to perform a search a little later. super(LifecycleEnvironment, self).create_missing() if (self.name != 'Library' and # pylint:disable=no-member not hasattr(self, 'prior')): results = self.search({'organization'}, {u'name': u'Library'}) if len(results) != 1: raise APIResponseError( u'Could not find the "Library" lifecycle environment for ' u'organization {0}. Search results: {1}' .format(self.organization, results) # pylint:disable=E1101 ) self.prior = results[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_payload(self): """Wrap submitted data within an extra dict and rename ``path_``. For more information on wrapping submitted data, see `Bugzilla #1151220 <https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_. """
payload = super(Media, self).create_payload() if 'path_' in payload: payload['path'] = payload.pop('path_') return {u'medium': payload}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_payload(self): """Remove ``smart_class_parameter_id`` or ``smart_variable_id``"""
payload = super(OverrideValue, self).create_payload() if hasattr(self, 'smart_class_parameter'): del payload['smart_class_parameter_id'] if hasattr(self, 'smart_variable'): del payload['smart_variable_id'] return payload
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Ignore path related fields as they're never returned by the server and are only added to entity to be able to use proper path. """
if entity is None: entity = type(self)( self._server_config, **{self._parent_type: self._parent_id} ) if ignore is None: ignore = set() for field_name in self._path_fields: ignore.add(field_name) return super(Parameter, self).read(entity, attrs, ignore, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, fields=None, query=None, filters=None): """Search for entities with missing attribute :param fields: A set naming which fields should be used when generating a search query. If ``None``, all values on the entity are used. If an empty set, no values are used. :param query: A dict containing a raw search query. This is melded in to the generated search query like so: ``{generated: query}.update({manual: query})``. :param filters: A dict. Used to filter search results locally. :return: A list of entities, all of type ``type(self)``. For more information, see `Bugzilla #1237283 <https://bugzilla.redhat.com/show_bug.cgi?id=1237283>`_ and `nailgun#261 <https://github.com/SatelliteQE/nailgun/issues/261>`_. """
results = self.search_json(fields, query)['results'] results = self.search_normalize(results) entities = [] for result in results: sync_plan = result.get('sync_plan') if sync_plan is not None: del result['sync_plan'] entity = type(self)(self._server_config, **result) if sync_plan: entity.sync_plan = SyncPlan( server_config=self._server_config, id=sync_plan, organization=Organization( server_config=self._server_config, id=result.get('organization') ), ) entities.append(entity) if filters is not None: entities = self.search_filter(entities, filters) return entities
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Do not read the ``password`` argument."""
if attrs is None: attrs = self.read_json() if ignore is None: ignore = set() ignore.add('password') return super(Registry, self).read(entity, attrs, ignore, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_missing(self): """Conditionally mark ``docker_upstream_name`` as required. Mark ``docker_upstream_name`` as required if ``content_type`` is "docker". """
if getattr(self, 'content_type', '') == 'docker': self._fields['docker_upstream_name'].required = True super(Repository, self).create_missing()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_content(self, synchronous=True, **kwargs): """Upload a file or files to the current repository. Here is an example of how to upload content:: with open('my_content.rpm') as content: repo.upload_content(files={'content': content}) This method accepts the same keyword arguments as Requests. As a result, the following examples can be adapted for use here: * `POST a Multipart-Encoded File`_ * `POST Multiple Multipart-Encoded Files`_ :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. :raises nailgun.entities.APIResponseError: If the response has a status other than "success". .. _POST a Multipart-Encoded File: http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file .. _POST Multiple Multipart-Encoded Files: http://docs.python-requests.org/en/latest/user/advanced/#post-multiple-multipart-encoded-files """
kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) response = client.post(self.path('upload_content'), **kwargs) json = _handle_response(response, self._server_config, synchronous) if json['status'] != 'success': raise APIResponseError( # pylint:disable=no-member 'Received error when uploading file {0} to repository {1}: {2}' .format(kwargs.get('files'), self.id, json) ) return json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_uploads(self, uploads=None, upload_ids=None, synchronous=True, **kwargs): """Import uploads into a repository It expects either a list of uploads or upload_ids (but not both). :param uploads: Array of uploads to be imported :param upload_ids: Array of upload ids to be imported :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) if uploads: data = {'uploads': uploads} elif upload_ids: data = {'upload_ids': upload_ids} response = client.put(self.path('import_uploads'), data, **kwargs) json = _handle_response(response, self._server_config, synchronous) return json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def available_repositories(self, **kwargs): """Lists available repositories for the repository set :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
if 'data' not in kwargs: kwargs['data'] = dict() kwargs['data']['product_id'] = self.product.id kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) response = client.get(self.path('available_repositories'), **kwargs) return _handle_response(response, self._server_config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable(self, synchronous=True, **kwargs): """Enables the RedHat Repository RedHat Repos needs to be enabled first, so that we can sync it. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
if 'data' not in kwargs: kwargs['data'] = dict() kwargs['data']['product_id'] = self.product.id kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) response = client.put(self.path('enable'), **kwargs) return _handle_response(response, self._server_config, synchronous)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_puppetclasses(self, synchronous=True, **kwargs): """Import puppet classes from puppet Capsule. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() kwargs.update(self._server_config.get_client_kwargs()) # Check if environment_id was sent and substitute it to the path # but do not pass it to requests if 'environment' in kwargs: if isinstance(kwargs['environment'], Environment): environment_id = kwargs.pop('environment').id else: environment_id = kwargs.pop('environment') path = '{0}/environments/{1}/import_puppetclasses'.format( self.path(), environment_id) else: path = '{0}/import_puppetclasses'.format(self.path()) return _handle_response( client.post(path, **kwargs), self._server_config, synchronous)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _org_path(self, which, payload): """A helper method for generating paths with organization IDs in them. :param which: A path such as "manifest_history" that has an organization ID in it. :param payload: A dict with an "organization_id" key in it. :returns: A string. The requested path. """
return Subscription( self._server_config, organization=payload['organization_id'], ).path(which)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def manifest_history(self, synchronous=True, **kwargs): """Obtain manifest history for subscriptions. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) response = client.get( self._org_path('manifest_history', kwargs['data']), **kwargs ) return _handle_response(response, self._server_config, synchronous)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, entity=None, attrs=None, ignore=None, params=None): """Ignore ``organization`` field as it's never returned by the server and is only added to entity to be able to use organization path dependent helpers. """
if ignore is None: ignore = set() ignore.add('organization') return super(Subscription, self).read(entity, attrs, ignore, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_manifest(self, synchronous=True, **kwargs): """Refresh previously imported manifest for Red Hat provider. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) response = client.put( self._org_path('refresh_manifest', kwargs['data']), **kwargs ) return _handle_response( response, self._server_config, synchronous, timeout=1500, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload(self, synchronous=True, **kwargs): """Upload a subscription manifest. Here is an example of how to use this method:: with open('my_manifest.zip') as manifest: sub.upload({'organization_id': org.id}, manifest) :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) response = client.post( self._org_path('upload', kwargs['data']), **kwargs ) # Setting custom timeout as manifest upload can take enormously huge # amount of time. See BZ#1339696 for more details return _handle_response( response, self._server_config, synchronous, timeout=1500, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_payload(self): """Convert ``sync_date`` to a string. The ``sync_date`` instance attribute on the current object is not affected. However, the ``'sync_date'`` key in the dict returned by ``create_payload`` is a string. """
data = super(SyncPlan, self).create_payload() if isinstance(data.get('sync_date'), datetime): data['sync_date'] = data['sync_date'].strftime('%Y-%m-%d %H:%M:%S') return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_payload(self, fields=None): """Convert ``sync_date`` to a string if datetime object provided."""
data = super(SyncPlan, self).update_payload(fields) if isinstance(data.get('sync_date'), datetime): data['sync_date'] = data['sync_date'].strftime('%Y-%m-%d %H:%M:%S') return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy_script(self, synchronous=True, **kwargs): """Helper for Config's deploy_script method. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """
kwargs = kwargs.copy() # shadow the passed-in kwargs kwargs.update(self._server_config.get_client_kwargs()) response = client.get(self.path('deploy_script'), **kwargs) return _handle_response(response, self._server_config, synchronous)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_local_net( network_name: str = DOCKER_STARCRAFT_NETWORK, subnet_cidr: str = SUBNET_CIDR ) -> None: """ Create docker local net if not found. :raises docker.errors.APIError """
logger.info(f"checking whether docker has network {network_name}") ipam_pool = docker.types.IPAMPool(subnet=subnet_cidr) ipam_config = docker.types.IPAMConfig(pool_configs=[ipam_pool]) networks = docker_client.networks.list(names=DOCKER_STARCRAFT_NETWORK) output = networks[0].short_id if networks else None if not output: logger.info("network not found, creating ...") output = docker_client.networks.create(DOCKER_STARCRAFT_NETWORK, ipam=ipam_config).short_id logger.debug(f"docker network id: {output}")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_local_image( local_image: str, parent_image: str = SC_PARENT_IMAGE, java_image: str = SC_JAVA_IMAGE, starcraft_base_dir: str = SCBW_BASE_DIR, starcraft_binary_link: str = SC_BINARY_LINK, ) -> None: """ Check if `local_image` is present locally. If it is not, pull parent images and build. This includes pulling starcraft binary. :raises docker.errors.ImageNotFound :raises docker.errors.APIError """
logger.info(f"checking if there is local image {local_image}") docker_images = docker_client.images.list(local_image) if len(docker_images) and docker_images[0].short_id is not None: logger.info(f"image {local_image} found locally.") return logger.info("image not found locally, creating...") pkg_docker_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "local_docker") base_dir = os.path.join(starcraft_base_dir, "docker") logger.info(f"copying files from {pkg_docker_dir} to {base_dir}.") distutils.dir_util.copy_tree(pkg_docker_dir, base_dir) starcraft_zip_file = f"{base_dir}/starcraft.zip" if not os.path.exists(starcraft_zip_file): logger.info(f"downloading starcraft.zip to {starcraft_zip_file}") download_file(starcraft_binary_link, starcraft_zip_file) logger.info(f"pulling image {parent_image}, this may take a while...") pulled_image = docker_client.images.pull(parent_image) pulled_image.tag(java_image) logger.info(f"building local image {local_image}, this may take a while...") docker_client.images.build(path=base_dir, dockerfile="game.dockerfile", tag=local_image) logger.info(f"successfully built image {local_image}")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_dockermachine() -> bool: """ Checks that docker-machine is available on the computer :raises FileNotFoundError if docker-machine is not present """
logger.debug("checking docker-machine presence") # noinspection PyBroadException try: out = subprocess \ .check_output(["docker-machine", "version"]) \ .decode("utf-8") \ .replace("docker-machine.exe", "") \ .replace("docker-machine", "") \ .strip() logger.debug(f"using docker machine version {out}") return True except Exception: logger.debug(f"docker machine not present") return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dockermachine_ip() -> Optional[str]: """ Gets IP address of the default docker machine Returns None if no docker-machine executable in the PATH and if there no Docker machine with name default present """
if not check_dockermachine(): return None # noinspection PyBroadException try: out = subprocess.check_output(['docker-machine', 'ip']) return out.decode("utf-8").strip() except Exception: logger.debug(f"docker machine not present") return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xoscmounts(host_mount): """ Cross OS compatible mount dirs """
callback_lower_drive_letter = lambda pat: pat.group(1).lower() host_mount = re.sub(r"^([a-zA-Z])\:", callback_lower_drive_letter, host_mount) host_mount = re.sub(r"^([a-z])", "//\\1", host_mount) host_mount = re.sub(r"\\", "/", host_mount) return host_mount
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chisquare(n_ij, weighted): """ Calculates the chisquare for a matrix of ind_v x dep_v for the unweighted and SPSS weighted case """
if weighted: m_ij = n_ij / n_ij nan_mask = np.isnan(m_ij) m_ij[nan_mask] = 0.000001 # otherwise it breaks the chi-squared test w_ij = m_ij n_ij_col_sum = n_ij.sum(axis=1) n_ij_row_sum = n_ij.sum(axis=0) alpha, beta, eps = (1, 1, 1) while eps > 10e-6: alpha = alpha * np.vstack(n_ij_col_sum / m_ij.sum(axis=1)) beta = n_ij_row_sum / (alpha * w_ij).sum(axis=0) eps = np.max(np.absolute(w_ij * alpha * beta - m_ij)) m_ij = w_ij * alpha * beta else: m_ij = (np.vstack(n_ij.sum(axis=1)) * n_ij.sum(axis=0)) / n_ij.sum().astype(float) dof = (n_ij.shape[0] - 1) * (n_ij.shape[1] - 1) chi, p_val = stats.chisquare(n_ij, f_exp=m_ij, ddof=n_ij.size - 1 - dof, axis=None) return (chi, p_val, dof)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def best_split(self, ind, dep): """ determine which splitting function to apply """
if isinstance(dep, ContinuousColumn): return self.best_con_split(ind, dep) else: return self.best_cat_heuristic_split(ind, dep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_numpy(ndarr, arr, alpha_merge=0.05, max_depth=2, min_parent_node_size=30, min_child_node_size=30, split_titles=None, split_threshold=0, weights=None, variable_types=None, dep_variable_type='categorical'): """ Create a CHAID object from numpy Parameters ndarr : numpy.ndarray non-aggregated 2-dimensional array containing independent variables on the veritcal axis and (usually) respondent level data on the horizontal axis arr : numpy.ndarray 1-dimensional array of the dependent variable associated with ndarr alpha_merge : float the threshold value in which to create a split (default 0.05) max_depth : float the threshold value for the maximum number of levels after the root node in the tree (default 2) min_parent_node_size : float the threshold value of the number of respondents that the node must contain (default 30) split_titles : array-like array of names for the independent variables in the data variable_types : array-like or dict array of variable types, or dict of column names to variable types. Supported variable types are the strings 'nominal' or 'ordinal' in lower case """
vectorised_array = [] variable_types = variable_types or ['nominal'] * ndarr.shape[1] for ind, col_type in enumerate(variable_types): title = None if split_titles is not None: title = split_titles[ind] if col_type == 'ordinal': col = OrdinalColumn(ndarr[:, ind], name=title) elif col_type == 'nominal': col = NominalColumn(ndarr[:, ind], name=title) else: raise NotImplementedError('Unknown independent variable type ' + col_type) vectorised_array.append(col) if dep_variable_type == 'categorical': observed = NominalColumn(arr, weights=weights) elif dep_variable_type == 'continuous': observed = ContinuousColumn(arr, weights=weights) else: raise NotImplementedError('Unknown dependent variable type ' + dep_variable_type) config = { 'alpha_merge': alpha_merge, 'max_depth': max_depth, 'min_parent_node_size': min_parent_node_size, 'min_child_node_size': min_child_node_size, 'split_threshold': split_threshold } return Tree(vectorised_array, observed, config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_tree(self): """ Build chaid tree """
self._tree_store = [] self.node(np.arange(0, self.data_size, dtype=np.int), self.vectorised_array, self.observed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_pandas_df(df, i_variables, d_variable, alpha_merge=0.05, max_depth=2, min_parent_node_size=30, min_child_node_size=30, split_threshold=0, weight=None, dep_variable_type='categorical'): """ Helper method to pre-process a pandas data frame in order to run CHAID analysis Parameters df : pandas.DataFrame the dataframe with the dependent and independent variables in which to slice from i_variables : dict dict of instance variable names with their variable types. Supported variable types are the strings 'nominal' or 'ordinal' in lower case d_variable : string the name of the dependent variable in the dataframe alpha_merge : float the threshold value in which to create a split (default 0.05) max_depth : float the threshold value for the maximum number of levels after the root node in the tree (default 2) split_threshold : float the variation in chi-score such that surrogate splits are created (default 0) min_parent_node_size : float the threshold value of the number of respondents that the node must contain (default 30) min_child_node_size : float the threshold value of the number of respondents that each child node must contain (default 30) weight : array-like the respondent weights. If passed, weighted chi-square calculation is run dep_variable_type : str the type of dependent variable. Supported variable types are 'categorical' or 'continuous' """
ind_df = df[list(i_variables.keys())] ind_values = ind_df.values dep_values = df[d_variable].values weights = df[weight] if weight is not None else None return Tree.from_numpy(ind_values, dep_values, alpha_merge, max_depth, min_parent_node_size, min_child_node_size, list(ind_df.columns.values), split_threshold, weights, list(i_variables.values()), dep_variable_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def node(self, rows, ind, dep, depth=0, parent=None, parent_decisions=None): """ internal method to create a node in the tree """
depth += 1 if self.max_depth < depth: terminal_node = Node(choices=parent_decisions, node_id=self.node_count, parent=parent, indices=rows, dep_v=dep) self._tree_store.append(terminal_node) self.node_count += 1 terminal_node.split.invalid_reason = InvalidSplitReason.MAX_DEPTH return self._tree_store split = self._stats.best_split(ind, dep) node = Node(choices=parent_decisions, node_id=self.node_count, indices=rows, dep_v=dep, parent=parent, split=split) self._tree_store.append(node) parent = self.node_count self.node_count += 1 if not split.valid(): return self._tree_store for index, choices in enumerate(split.splits): correct_rows = np.in1d(ind[split.column_id].arr, choices) dep_slice = dep[correct_rows] ind_slice = [vect[correct_rows] for vect in ind] row_slice = rows[correct_rows] if self.min_parent_node_size < len(dep_slice.arr): self.node(row_slice, ind_slice, dep_slice, depth=depth, parent=parent, parent_decisions=split.split_map[index]) else: terminal_node = Node(choices=split.split_map[index], node_id=self.node_count, parent=parent, indices=row_slice, dep_v=dep_slice) terminal_node.split.invalid_reason = InvalidSplitReason.MIN_PARENT_NODE_SIZE self._tree_store.append(terminal_node) self.node_count += 1 return self._tree_store
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_tree(self): """ returns a TreeLib tree """
tree = TreeLibTree() for node in self: tree.create_node(node, node.node_id, parent=node.parent) return tree
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def node_predictions(self): """ Determines which rows fall into which node """
pred = np.zeros(self.data_size) for node in self: if node.is_terminal: pred[node.indices] = node.node_id return pred
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def model_predictions(self): """ Determines the highest frequency of categorical dependent variable in the terminal node where that row fell """
if isinstance(self.observed, ContinuousColumn): return ValueError("Cannot make model predictions on a continuous scale") pred = np.zeros(self.data_size).astype('object') for node in self: if node.is_terminal: pred[node.indices] = max(node.members, key=node.members.get) return pred
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bell_set(self, collection, ordinal=False): """ Calculates the Bell set """
if len(collection) == 1: yield [ collection ] return first = collection[0] for smaller in self.bell_set(collection[1:]): for n, subset in enumerate(smaller): if not ordinal or (ordinal and is_sorted(smaller[:n] + [[ first ] + subset] + smaller[n+1:], self._nan)): yield smaller[:n] + [[ first ] + subset] + smaller[n+1:] if not ordinal or (ordinal and is_sorted([ [ first ] ] + smaller, self._nan)): yield [ [ first ] ] + smaller
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def substitute_values(self, vect): """ Internal method to substitute integers into the vector, and construct metadata to convert back to the original vector. np.nan is always given -1, all other objects are given integers in order of apperence. Parameters vect : np.array the vector in which to substitute values in """
try: unique = np.unique(vect) except: unique = set(vect) unique = [ x for x in unique if not isinstance(x, float) or not isnan(x) ] arr = np.copy(vect) for new_id, value in enumerate(unique): np.place(arr, arr==value, new_id) self.metadata[new_id] = value arr = arr.astype(np.float) np.place(arr, np.isnan(arr), -1) self.arr = arr if -1 in arr: self.metadata[-1] = self._missing_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sub_split_values(self, sub): """ Substitutes the splits with other values into the split_map """
for i, arr in enumerate(self.splits): self.split_map[i] = [sub.get(x, x) for x in arr] for split in self.surrogates: split.sub_split_values(sub)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name_columns(self, sub): """ Substitutes the split column index with a human readable string """
if self.column_id is not None and len(sub) > self.column_id: self.split_name = sub[self.column_id] for split in self.surrogates: split.name_columns(sub)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def three_partition(x): """partition a set of integers in 3 parts of same total value :param x: table of non negative values :returns: triplet of the integers encoding the sets, or None otherwise :complexity: :math:`O(2^{2n})` """
f = [0] * (1 << len(x)) for i in range(len(x)): for S in range(1 << i): f[S | (1 << i)] = f[S] + x[i] for A in range(1 << len(x)): for B in range(1 << len(x)): if A & B == 0 and f[A] == f[B] and 3 * f[A] == f[-1]: return (A, B, ((1 << len(x)) - 1) ^ A ^ B) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def freivalds(A, B, C): """Tests matrix product AB=C by Freivalds :param A: n by n numerical matrix :param B: same :param C: same :returns: False with high probability if AB != C :complexity: :math:`O(n^2)` """
n = len(A) x = [randint(0, 1000000) for j in range(n)] return mult(A, mult(B, x)) == mult(C, x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min_scalar_prod(x, y): """Permute vector to minimize scalar product :param x: :param y: x, y are vectors of same size :returns: min sum x[i] * y[sigma[i]] over all permutations sigma :complexity: O(n log n) """
x = sorted(x) # make copies y = sorted(y) # to save arguments return sum(x[i] * y[-i - 1] for i in range(len(x)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def laser_mirrors(rows, cols, mir): """Orienting mirrors to allow reachability by laser beam :param int rows: :param int cols: rows and cols are the dimension of the grid :param mir: list of mirror coordinates, except mir[0]= laser entrance, mir[-1]= laser exit. :complexity: :math:`O(2^n)` """
# build structures n = len(mir) orien = [None] * (n + 2) orien[n] = 0 # arbitrary orientations orien[n + 1] = 0 succ = [[None for direc in range(4)] for i in range(n + 2)] L = [(mir[i][0], mir[i][1], i) for i in range(n)] L.append((0, -1, n)) # enter L.append((0, cols, n + 1)) # exit last_r, last_i = None, None for (r, c, i) in sorted(L): # sweep by row if last_r == r: succ[i][LEFT] = last_i succ[last_i][RIGHT] = i last_r, last_i = r, i last_c = None for (r, c, i) in sorted(L, key=lambda rci: (rci[1], rci[0])): if last_c == c: # sweep by column succ[i][UP] = last_i succ[last_i][DOWN] = i last_c, last_i = c, i if solve(succ, orien, n, RIGHT): # exploration return orien[:n] else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve(succ, orien, i, direc): """Can a laser leaving mirror i in direction direc reach exit ? :param i: mirror index :param direc: direction leaving mirror i :param orient: orient[i]=orientation of mirror i :param succ: succ[i][direc]=succ mirror reached when leaving i in direction direc """
assert orien[i] is not None j = succ[i][direc] if j is None: # basic case return False if j == len(orien) - 1: return True if orien[j] is None: # try both orientations for x in [0, 1]: orien[j] = x if solve(succ, orien, j, reflex[direc][x]): return True orien[j] = None return False else: return solve(succ, orien, j, reflex[direc][orien[j]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dancing_links(size_universe, sets): """Exact set cover by the dancing links algorithm :param sets: list of sets :returns: list of set indices partitioning the universe, or None :complexity: huge """
header = Cell(None, None, 0, None) # building the cell structure col = [] for j in range(size_universe): col.append(Cell(header, None, 0, None)) for i in range(len(sets)): row = None for j in sets[i]: col[j].S += 1 # one more entry in this column row = Cell(row, col[j], i, col[j]) sol = [] if solve(header, sol): return sol else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def two_sat(formula): """Solving a 2-SAT boolean formula :param formula: list of clauses, a clause is pair of literals a literal is an integer, for example -1 = not X1, 3 = X3 :returns: table with boolean assignment satisfying the formula or None :complexity: linear """
# -- n is the number of variables n = max(abs(clause[p]) for p in (0, 1) for clause in formula) graph = [[] for node in range(2 * n)] for x, y in formula: # x or y graph[_vertex(-x)].append(_vertex(y)) # -x => y graph[_vertex(-y)].append(_vertex(x)) # -y => x sccp = tarjan(graph) comp_id = [None] * (2 * n) # for each node the ID of its component assignment = [None] * (2 * n) for component in sccp: rep = min(component) # representative of the component for vtx in component: comp_id[vtx] = rep if assignment[vtx] is None: assignment[vtx] = True assignment[vtx ^ 1] = False # complementary literal for i in range(n): if comp_id[2 * i] == comp_id[2 * i + 1]: return None # insatisfiable formula return assignment[::2]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rectangles_from_grid(P, black=1): """Largest area rectangle in a binary matrix :param P: matrix :param black: search for rectangles filled with value black :returns: area, left, top, right, bottom of optimal rectangle consisting of all (i,j) with left <= j < right and top <= i <= bottom :complexity: linear """
rows = len(P) cols = len(P[0]) t = [0] * cols best = None for i in range(rows): for j in range(cols): if P[i][j] == black: t[j] += 1 else: t[j] = 0 (area, left, height, right) = rectangles_from_histogram(t) alt = (area, left, i, right, i-height) if best is None or alt > best: best = alt return best
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min_mean_cycle(graph, weight, start=0): """Minimum mean cycle by Karp :param graph: directed graph in listlist or listdict format :param weight: in matrix format or same listdict graph :param int start: vertex that should be contained in cycle :returns: cycle as vertex list, average arc weights or None if there is no cycle from start :complexity: `O(|V|*|E|)` """
INF = float('inf') n = len(graph) # compute distances dist = [[INF] * n] prec = [[None] * n] dist[0][start] = 0 for ell in range(1, n + 1): dist.append([INF] * n) prec.append([None] * n) for node in range(n): for neighbor in graph[node]: alt = dist[ell - 1][node] + weight[node][neighbor] if alt < dist[ell][neighbor]: dist[ell][neighbor] = alt prec[ell][neighbor] = node # -- find the optimal value valmin = INF argmin = None for node in range(n): valmax = -INF argmax = None for k in range(n): alt = (dist[n][node] - dist[k][node]) / float(n - k) # do not divide by float(n-k) => cycle of minimal total weight if alt >= valmax: # with >= we get simple cycles valmax = alt argmax = k if argmax is not None and valmax < valmin: valmin = valmax argmin = (node, argmax) # -- extract cycle if valmin == INF: # -- there is no cycle return None C = [] node, k = argmin for l in range(n, k, -1): C.append(node) node = prec[l][node] return C[::-1], valmin
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def floyd_warshall(weight): """All pairs shortest paths by Floyd-Warshall :param weight: edge weight matrix :modifies: weight matrix to contain distances in graph :returns: True if there are negative cycles :complexity: :math:`O(|V|^3)` """
V = range(len(weight)) for k in V: for u in V: for v in V: weight[u][v] = min(weight[u][v], weight[u][k] + weight[k][v]) for v in V: if weight[v][v] < 0: # negative cycle found return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bellman_ford(graph, weight, source=0): """ Single source shortest paths by Bellman-Ford :param graph: directed graph in listlist or listdict format :param weight: can be negative. in matrix format or same listdict graph :returns: distance table, precedence table, bool :explanation: bool is True if a negative circuit is reachable from the source, circuits can have length 2. :complexity: `O(|V|*|E|)` """
n = len(graph) dist = [float('inf')] * n prec = [None] * n dist[source] = 0 for nb_iterations in range(n): changed = False for node in range(n): for neighbor in graph[node]: alt = dist[node] + weight[node][neighbor] if alt < dist[neighbor]: dist[neighbor] = alt prec[neighbor] = node changed = True if not changed: # fixed point return dist, prec, False return dist, prec, True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roman2int(s): """Decode roman number :param s: string representing a roman number between 1 and 9999 :returns: the decoded roman number :complexity: linear (if that makes sense for constant bounded input size) """
val = 0 pos10 = 1000 beg = 0 for pos in range(3, -1, -1): for digit in range(9,-1,-1): r = roman[pos][digit] if s.startswith(r, beg): # footnote 1 beg += len(r) val += digit * pos10 break pos10 //= 10 return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def int2roman(val): """Code roman number :param val: integer between 1 and 9999 :returns: the corresponding roman number :complexity: linear (if that makes sense for constant bounded input size) """
s = '' pos10 = 1000 for pos in range(3, -1, -1): digit = val // pos10 s += roman[pos][digit] val %= pos10 pos10 //= 10 return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dijkstra(graph, weight, source=0, target=None): """single source shortest paths by Dijkstra :param graph: directed graph in listlist or listdict format :param weight: in matrix format or same listdict graph :assumes: weights are non-negative :param source: source vertex :type source: int :param target: if given, stops once distance to target found :type target: int :returns: distance table, precedence table :complexity: `O(|V| + |E|log|V|)` """
n = len(graph) assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u]) prec = [None] * n black = [False] * n dist = [float('inf')] * n dist[source] = 0 heap = [(0, source)] while heap: dist_node, node = heappop(heap) # Closest node from source if not black[node]: black[node] = True if node == target: break for neighbor in graph[node]: dist_neighbor = dist_node + weight[node][neighbor] if dist_neighbor < dist[neighbor]: dist[neighbor] = dist_neighbor prec[neighbor] = node heappush(heap, (dist_neighbor, neighbor)) return dist, prec
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dijkstra_update_heap(graph, weight, source=0, target=None): """single source shortest paths by Dijkstra with a heap implementing item updates :param graph: adjacency list or adjacency dictionary of a directed graph :param weight: matrix or adjacency dictionary :assumes: weights are non-negatif and weights are infinite for non edges :param source: source vertex :type source: int :param target: if given, stops once distance to target found :type target: int :returns: distance table, precedence table :complexity: `O(|V| + |E|log|V|)` """
n = len(graph) assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u]) prec = [None] * n dist = [float('inf')] * n dist[source] = 0 heap = OurHeap([(dist[node], node) for node in range(n)]) while heap: dist_node, node = heap.pop() # Closest node from source if node == target: break for neighbor in graph[node]: old = dist[neighbor] new = dist_node + weight[node][neighbor] if new < old: dist[neighbor] = new prec[neighbor] = node heap.update((old, neighbor), (new, neighbor)) return dist, prec
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def manacher(s): """Longest palindrome in a string by Manacher :param s: string :requires: s is not empty :returns: i,j such that s[i:j] is the longest palindrome in s :complexity: O(len(s)) """
assert set.isdisjoint({'$', '^', '#'}, s) # Forbidden letters if s == "": return (0, 1) t = "^#" + "#".join(s) + "#$" c = 1 d = 1 p = [0] * len(t) for i in range(2, len(t) - 1): # -- reflect index i with respect to c mirror = 2 * c - i # = c - (i-c) p[i] = max(0, min(d - i, p[mirror])) # -- grow palindrome centered in i while t[i + 1 + p[i]] == t[i - 1 - p[i]]: p[i] += 1 # -- adjust center if necessary if i + p[i] > d: c = i d = i + p[i] (k, i) = max((p[i], i) for i in range(1, len(t) - 1)) return ((i - k) // 2, (i + k) // 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bfs(graph, start=0): """Shortest path in unweighted graph by BFS :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: distance table, precedence table :complexity: `O(|V|+|E|)` """
to_visit = deque() dist = [float('inf')] * len(graph) prec = [None] * len(graph) dist[start] = 0 to_visit.appendleft(start) while to_visit: # an empty queue is considered False node = to_visit.pop() for neighbor in graph[node]: if dist[neighbor] == float('inf'): dist[neighbor] = dist[node] + 1 prec[neighbor] = node to_visit.appendleft(neighbor) return dist, prec
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_graph(filename, directed=False, weighted=False, default_weight=None): """Read a graph from a text file :param filename: plain text file. All numbers are separated by space. Starts with a line containing n (#vertices) and m (#edges). Then m lines follow, for each edge. Vertices are numbered from 0 to n-1. Line for unweighted edge u,v contains two integers u, v. Line for weighted edge u,v contains three integers u, v, w[u,v]. :param directed: true for a directed graph, false for undirected :param weighted: true for an edge weighted graph :returns: graph in listlist format, possibly followed by weight matrix :complexity: O(n + m) for unweighted graph, :math:`O(n^2)` for weighted graph """
with open(filename, 'r') as f: while True: line = f.readline() # ignore leading comments if line[0] != '#': break nb_nodes, nb_edges = tuple(map(int, line.split())) graph = [[] for u in range(nb_nodes)] if weighted: weight = [[default_weight] * nb_nodes for v in range(nb_nodes)] for v in range(nb_nodes): weight[v][v] = 0 for _ in range(nb_edges): u, v, w = readtab(f, int) graph[u].append(v) weight[u][v] = w if not directed: graph[v].append(u) weight[v][u] = w return graph, weight else: for _ in range(nb_edges): # si le fichier contient des poids, ils seront ignorés u, v = readtab(f, int)[:2] graph[u].append(v) if not directed: graph[v].append(u) return graph
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_graph(dotfile, graph, directed=False, node_label=None, arc_label=None, comment="", node_mark=set(), arc_mark=set()): """Writes a graph to a file in the DOT format :param dotfile: the filename. :param graph: directed graph in listlist or listdict format :param directed: true if graph is directed, false if undirected :param weight: in matrix format or same listdict graph or None :param node_label: vertex label table or None :param arc_label: arc label matrix or None :param comment: comment string for the dot file or None :param node_mark: set of nodes to be shown in gray :param arc_marc: set of arcs to be shown in red :complexity: `O(|V| + |E|)` """
with open(dotfile, 'w') as f: if directed: f.write("digraph G{\n") else: f.write("graph G{\n") if comment: f.write('label="%s";\n' % comment) V = range(len(graph)) # -- vertices for u in V: if node_mark and u in node_mark: f.write('%d [style=filled, color="lightgrey", ' % u) else: f.write('%d [' % u) if node_label: f.write('label="%u [%s]"];\n' % (u, node_label[u])) else: f.write('shape=circle, label="%u"];\n' % u) # -- edges if isinstance(arc_mark, list): arc_mark = set((u, arc_mark[u]) for u in V) for u in V: for v in graph[u]: if not directed and u > v: continue # don't show twice the edge if arc_label and arc_label[u][v] == None: continue # suppress arcs with no label if directed: arc = "%d -> %d " % (u, v) else: arc = "%d -- %d " % (u, v) if arc_mark and ( (v,u) in arc_mark or (not directed and (u,v) in arc_mark) ): pen = 'color="red"' else: pen = "" if arc_label: tag = 'label="%s"' % arc_label[u][v] else: tag = "" if tag and pen: sep = ", " else: sep = "" f.write(arc + "[" + tag + sep + pen + "];\n") f.write("}")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tree_prec_to_adj(prec, root=0): """Transforms a tree given as predecessor table into adjacency list form :param prec: predecessor table representing a tree, prec[u] == v iff u is successor of v, except for the root where prec[root] == root :param root: root vertex of the tree :returns: undirected graph in listlist representation :complexity: linear """
n = len(prec) graph = [[prec[u]] for u in range(n)] # add predecessors graph[root] = [] for u in range(n): # add successors if u != root: graph[prec[u]].append(u) return graph
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matrix_to_listlist(weight): """transforms a squared weight matrix in a adjacency table of type listlist encoding the directed graph corresponding to the entries of the matrix different from None :param weight: squared weight matrix, weight[u][v] != None iff arc (u,v) exists :complexity: linear :returns: the unweighted directed graph in the listlist representation, listlist[u] contains all v for which arc (u,v) exists. """
graph = [[] for _ in range(len(weight))] for u in range(len(graph)): for v in range(len(graph)): if weight[u][v] != None: graph[u].append(v) return graph
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listlist_and_matrix_to_listdict(graph, weight=None): """Transforms the weighted adjacency list representation of a graph of type listlist + optional weight matrix into the listdict representation :param graph: in listlist representation :param weight: optional weight matrix :returns: graph in listdict representation :complexity: linear """
if weight: return [{v:weight[u][v] for v in graph[u]} for u in range(len(graph))] else: return [{v:None for v in graph[u]} for u in range(len(graph))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listdict_to_listlist_and_matrix(sparse): """Transforms the adjacency list representation of a graph of type listdict into the listlist + weight matrix representation :param sparse: graph in listdict representation :returns: couple with listlist representation, and weight matrix :complexity: linear """
V = range(len(sparse)) graph = [[] for _ in V] weight = [[None for v in V] for u in V] for u in V: for v in sparse[u]: graph[u].append(v) weight[u][v] = sparse[u][v] return graph, weight
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_path(prec, v): """extracts a path in form of vertex list from source to vertex v given a precedence table prec leading to the source :param prec: precedence table of a tree :param v: vertex on the tree :returns: path from root to v, in form of a list :complexity: linear """
L = [] while v is not None: L.append(v) v = prec[v] assert v not in L # prevent infinite loops for a bad formed table prec return L[::-1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_flow_labels(graph, flow, capac): """Generate arc labels for a flow in a graph with capacities. :param graph: adjacency list or adjacency dictionary :param flow: flow matrix or adjacency dictionary :param capac: capacity matrix or adjacency dictionary :returns: listdic graph representation, with the arc label strings """
V = range(len(graph)) arc_label = [{v:"" for v in graph[u]} for u in V] for u in V: for v in graph[u]: if flow[u][v] >= 0: arc_label[u][v] = "%s/%s" % (flow[u][v], capac[u][v]) else: arc_label[u][v] = None # do not show negative flow arcs return arc_label
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dilworth(graph): """Decompose a DAG into a minimum number of chains by Dilworth :param graph: directed graph in listlist or listdict format :assumes: graph is acyclic :returns: table giving for each vertex the number of its chains :complexity: same as matching """
n = len(graph) match = max_bipartite_matching(graph) # maximum matching part = [None] * n # partition into chains nb_chains = 0 for v in range(n - 1, -1, -1): # in inverse topological order if part[v] is None: # start of chain u = v while u is not None: # follow the chain part[u] = nb_chains # mark u = match[u] nb_chains += 1 return part
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract(code, tree, prefix=[]): """Extract Huffman code from a Huffman tree :param tree: a node of the tree :param prefix: a list with the 01 characters encoding the path from the root to the node `tree` :complexity: O(n) """
if isinstance(tree, list): l, r = tree prefix.append('0') extract(code, l, prefix) prefix.pop() prefix.append('1') extract(code, r, prefix) prefix.pop() else: code[tree] = ''.join(prefix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_permutation(tab): """find the next permutation of tab in the lexicographical order :param tab: table with n elements from an ordered set :modifies: table to next permutation :returns: False if permutation is already lexicographical maximal :complexity: O(n) """
n = len(tab) pivot = None # find pivot for i in range(n - 1): if tab[i] < tab[i + 1]: pivot = i if pivot is None: # tab is already the last perm. return False for i in range(pivot + 1, n): # find the element to swap if tab[i] > tab[pivot]: swap = i tab[swap], tab[pivot] = tab[pivot], tab[swap] i = pivot + 1 j = n - 1 # invert suffix while i < j: tab[i], tab[j] = tab[j], tab[i] i += 1 j -= 1 return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intervals_union(S): """Union of intervals :param S: list of pairs (low, high) defining intervals [low, high) :returns: ordered list of disjoint intervals with the same union as S :complexity: O(n log n) """
E = [(low, -1) for (low, high) in S] E += [(high, +1) for (low, high) in S] nb_open = 0 last = None retval = [] for x, _dir in sorted(E): if _dir == -1: if nb_open == 0: last = x nb_open += 1 else: nb_open -= 1 if nb_open == 0: retval.append((last, x)) return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _augment(graph, capacity, flow, val, u, target, visit): """Find an augmenting path from u to target with value at most val"""
visit[u] = True if u == target: return val for v in graph[u]: cuv = capacity[u][v] if not visit[v] and cuv > flow[u][v]: # reachable arc res = min(val, cuv - flow[u][v]) delta = _augment(graph, capacity, flow, res, v, target, visit) if delta > 0: flow[u][v] += delta # augment flow flow[v][u] -= delta return delta return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ford_fulkerson(graph, capacity, s, t): """Maximum flow by Ford-Fulkerson :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int s: source vertex :param int t: target vertex :returns: flow matrix, flow value :complexity: `O(|V|*|E|*max_capacity)` """
add_reverse_arcs(graph, capacity) n = len(graph) flow = [[0] * n for _ in range(n)] INF = float('inf') while _augment(graph, capacity, flow, INF, s, t, [False] * n) > 0: pass # work already done in _augment return (flow, sum(flow[s]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def windows_k_distinct(x, k): """Find all largest windows containing exactly k distinct elements :param x: list or string :param k: positive integer :yields: largest intervals [i, j) with len(set(x[i:j])) == k :complexity: `O(|x|)` """
dist, i, j = 0, 0, 0 # dist = |{x[i], ..., x[j-1]}| occ = {xi: 0 for xi in x} # number of occurrences in x[i:j] while j < len(x): while dist == k: # move start of interval occ[x[i]] -= 1 # update counters if occ[x[i]] == 0: dist -= 1 i += 1 while j < len(x) and (dist < k or occ[x[j]]): if occ[x[j]] == 0: # update counters dist += 1 occ[x[j]] += 1 j += 1 # move end of interval if dist == k: yield (i, j)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bezout(a, b): """Bezout coefficients for a and b :param a,b: non-negative integers :complexity: O(log a + log b) """
if b == 0: return (1, 0) else: u, v = bezout(b, a % b) return (v, u - (a // b) * v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predictive_text(dic): """Predictive text for mobile phones :param dic: associates weights to words from [a-z]* :returns: a dictionary associating to words from [2-9]* a corresponding word from the dictionary with highest weight :complexity: linear in total word length """
freq = {} # freq[p] = total weight of words having prefix p for word, weight in dic: prefix = "" for x in word: prefix += x if prefix in freq: freq[prefix] += weight else: freq[prefix] = weight # prop[s] = prefix to display for s prop = {} for prefix in freq: code = code_word(prefix) if code not in prop or freq[prop[code]] < freq[prefix]: prop[code] = prefix return prop
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rectangles_from_points(S): """How many rectangles can be formed from a set of points :param S: list of points, as coordinate pairs :returns: the number of rectangles :complexity: :math:`O(n^2)` """
answ = 0 pairs = {} for j in range(len(S)): for i in range(j): px, py = S[i] qx, qy = S[j] center = (px + qx, py + qy) dist = (px - qx) ** 2 + (py - qy) ** 2 sign = (center, dist) if sign in pairs: answ += len(pairs[sign]) pairs[sign].append((i, j)) else: pairs[sign] = [(i, j)] return answ
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cut_nodes_edges(graph): """Bi-connected components :param graph: undirected graph. in listlist format. Cannot be in listdict format. :returns: a tuple with the list of cut-nodes and the list of cut-edges :complexity: `O(|V|+|E|)` """
n = len(graph) time = 0 num = [None] * n low = [n] * n father = [None] * n # father[v] = None if root else father of v critical_childs = [0] * n # c_c[u] = #childs v s.t. low[v] >= num[u] times_seen = [-1] * n for start in range(n): if times_seen[start] == -1: # init DFS path times_seen[start] = 0 to_visit = [start] while to_visit: node = to_visit[-1] if times_seen[node] == 0: # start processing num[node] = time time += 1 low[node] = float('inf') children = graph[node] if times_seen[node] == len(children): # end processing to_visit.pop() up = father[node] # propagate low to father if up is not None: low[up] = min(low[up], low[node]) if low[node] >= num[up]: critical_childs[up] += 1 else: child = children[times_seen[node]] # next arrow times_seen[node] += 1 if times_seen[child] == -1: # not visited yet father[child] = node # link arrow times_seen[child] = 0 to_visit.append(child) # (below) back arrow elif num[child] < num[node] and father[node] != child: low[node] = min(low[node], num[child]) cut_edges = [] cut_nodes = [] # extract solution for node in range(n): if father[node] is None: # characteristics if critical_childs[node] >= 2: cut_nodes.append(node) else: # internal nodes if critical_childs[node] >= 1: cut_nodes.append(node) if low[node] >= num[node]: cut_edges.append((father[node], node)) return cut_nodes, cut_edges