code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def check_backend() -> bool: """Check if the backend is available.""" try: import bluepy.btle # noqa: F401 #pylint: disable=unused-import return True except ImportError as importerror: _LOGGER.error('bluepy not found: %s', str(importerror)) return False
Check if the backend is available.
Below is the the instruction that describes the task: ### Input: Check if the backend is available. ### Response: def check_backend() -> bool: """Check if the backend is available.""" try: import bluepy.btle # noqa: F401 #pylint: disable=unused-import return True except ImportError as importerror: _LOGGER.error('bluepy not found: %s', str(importerror)) return False
def angle_subtended(ell, **kwargs): """ Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to origin """ return_tangent = kwargs.pop('tangent',False) con, transform, offset = ell.projection(**kwargs) v = N.linalg.norm(N.array(con.major_axes()),axis=1) A = N.sort(v)[::-1] # Sort highest values first A = N.squeeze(A) B = N.linalg.norm(offset) if return_tangent: return A/B return N.arctan2(A,B)
Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to origin
Below is the the instruction that describes the task: ### Input: Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to origin ### Response: def angle_subtended(ell, **kwargs): """ Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to origin """ return_tangent = kwargs.pop('tangent',False) con, transform, offset = ell.projection(**kwargs) v = N.linalg.norm(N.array(con.major_axes()),axis=1) A = N.sort(v)[::-1] # Sort highest values first A = N.squeeze(A) B = N.linalg.norm(offset) if return_tangent: return A/B return N.arctan2(A,B)
def editText(self, y, x, w, record=True, **kwargs): 'Wrap global editText with `preedit` and `postedit` hooks.' v = self.callHook('preedit') if record else None if not v or v[0] is None: with EnableCursor(): v = editText(self.scr, y, x, w, **kwargs) else: v = v[0] if kwargs.get('display', True): status('"%s"' % v) self.callHook('postedit', v) if record else None return v
Wrap global editText with `preedit` and `postedit` hooks.
Below is the the instruction that describes the task: ### Input: Wrap global editText with `preedit` and `postedit` hooks. ### Response: def editText(self, y, x, w, record=True, **kwargs): 'Wrap global editText with `preedit` and `postedit` hooks.' v = self.callHook('preedit') if record else None if not v or v[0] is None: with EnableCursor(): v = editText(self.scr, y, x, w, **kwargs) else: v = v[0] if kwargs.get('display', True): status('"%s"' % v) self.callHook('postedit', v) if record else None return v
def _sign(self, certificate_request, password): """ Respond to a request to sign a CSR for a user or agent located within our domain. """ if self.service.portal is None: raise BadCertificateRequest("This agent cannot sign certificates.") subj = certificate_request.getSubject() sk = subj.keys() if 'commonName' not in sk: raise BadCertificateRequest( "Certificate requested with bad subject: %s" % (sk,)) uandd = subj.commonName.split("@") if len(uandd) != 2: raise BadCertificateRequest( "Won't sign certificates for other domains" ) domain = uandd[1] CS = self.service.certificateStorage ourCert = CS.getPrivateCertificate(domain) D = self.service.portal.login( UsernameShadowPassword(subj.commonName, password), self, ivertex.IQ2QUser) def _(ial): (iface, aspect, logout) = ial ser = CS.genSerial(domain) return dict(certificate=aspect.signCertificateRequest( certificate_request, ourCert, ser)) return D.addCallback(_)
Respond to a request to sign a CSR for a user or agent located within our domain.
Below is the the instruction that describes the task: ### Input: Respond to a request to sign a CSR for a user or agent located within our domain. ### Response: def _sign(self, certificate_request, password): """ Respond to a request to sign a CSR for a user or agent located within our domain. """ if self.service.portal is None: raise BadCertificateRequest("This agent cannot sign certificates.") subj = certificate_request.getSubject() sk = subj.keys() if 'commonName' not in sk: raise BadCertificateRequest( "Certificate requested with bad subject: %s" % (sk,)) uandd = subj.commonName.split("@") if len(uandd) != 2: raise BadCertificateRequest( "Won't sign certificates for other domains" ) domain = uandd[1] CS = self.service.certificateStorage ourCert = CS.getPrivateCertificate(domain) D = self.service.portal.login( UsernameShadowPassword(subj.commonName, password), self, ivertex.IQ2QUser) def _(ial): (iface, aspect, logout) = ial ser = CS.genSerial(domain) return dict(certificate=aspect.signCertificateRequest( certificate_request, ourCert, ser)) return D.addCallback(_)
def write(self, chunk, offset): """ Write chunk to file at specified position Return 0 if OK, else -1 """ return lib.zfile_write(self._as_parameter_, chunk, offset)
Write chunk to file at specified position Return 0 if OK, else -1
Below is the the instruction that describes the task: ### Input: Write chunk to file at specified position Return 0 if OK, else -1 ### Response: def write(self, chunk, offset): """ Write chunk to file at specified position Return 0 if OK, else -1 """ return lib.zfile_write(self._as_parameter_, chunk, offset)
def transform(self, crs): """ Transforms BBox from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Bounding box in target CRS :rtype: BBox """ new_crs = CRS(crs) return BBox((transform_point(self.lower_left, self.crs, new_crs), transform_point(self.upper_right, self.crs, new_crs)), crs=new_crs)
Transforms BBox from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Bounding box in target CRS :rtype: BBox
Below is the the instruction that describes the task: ### Input: Transforms BBox from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Bounding box in target CRS :rtype: BBox ### Response: def transform(self, crs): """ Transforms BBox from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Bounding box in target CRS :rtype: BBox """ new_crs = CRS(crs) return BBox((transform_point(self.lower_left, self.crs, new_crs), transform_point(self.upper_right, self.crs, new_crs)), crs=new_crs)
def _get_uri(self): """ Will return the uri for an existing instance. """ if not self.service.exists(): logging.warning("Service does not yet exist.") return self.service.settings.data['uri']
Will return the uri for an existing instance.
Below is the the instruction that describes the task: ### Input: Will return the uri for an existing instance. ### Response: def _get_uri(self): """ Will return the uri for an existing instance. """ if not self.service.exists(): logging.warning("Service does not yet exist.") return self.service.settings.data['uri']
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 yields each line of the command stdout. :rtype: generator iterator """ py3 = sys.version_info > (3, 0) # Make subprocess command command = self._make_vagrant_command(args) with self.err_cm() as err_fh: sp_args = dict(args=command, cwd=self.root, env=self.env, stdout=subprocess.PIPE, stderr=err_fh, bufsize=1) # Iterate over output lines. # See http://stackoverflow.com/questions/2715847/python-read-streaming-input-from-subprocess-communicate#17698359 p = subprocess.Popen(**sp_args) with p.stdout: for line in iter(p.stdout.readline, b''): yield compat.decode(line) # if PY3 decode bytestrings p.wait() # Raise CalledProcessError for consistency with _call_vagrant_command if p.returncode != 0: raise subprocess.CalledProcessError(p.returncode, command)
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 iterator
Below is the the instruction that describes the task: ### Input: 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 iterator ### Response: 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 yields each line of the command stdout. :rtype: generator iterator """ py3 = sys.version_info > (3, 0) # Make subprocess command command = self._make_vagrant_command(args) with self.err_cm() as err_fh: sp_args = dict(args=command, cwd=self.root, env=self.env, stdout=subprocess.PIPE, stderr=err_fh, bufsize=1) # Iterate over output lines. # See http://stackoverflow.com/questions/2715847/python-read-streaming-input-from-subprocess-communicate#17698359 p = subprocess.Popen(**sp_args) with p.stdout: for line in iter(p.stdout.readline, b''): yield compat.decode(line) # if PY3 decode bytestrings p.wait() # Raise CalledProcessError for consistency with _call_vagrant_command if p.returncode != 0: raise subprocess.CalledProcessError(p.returncode, command)
def start (self): ''' Starts (Subscribes) the client. ''' self.sub = rospy.Subscriber(self.topic, ImageROS, self.__callback)
Starts (Subscribes) the client.
Below is the the instruction that describes the task: ### Input: Starts (Subscribes) the client. ### Response: def start (self): ''' Starts (Subscribes) the client. ''' self.sub = rospy.Subscriber(self.topic, ImageROS, self.__callback)
def get_bank_admin_session(self): """Gets the OsidSession associated with the bank administration service. return: (osid.assessment.BankAdminSession) - a ``BankAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bank_admin() is false`` *compliance: optional -- This method must be implemented if ``supports_bank_admin()`` is true.* """ if not self.supports_bank_admin(): raise errors.Unimplemented() # pylint: disable=no-member return sessions.BankAdminSession(runtime=self._runtime)
Gets the OsidSession associated with the bank administration service. return: (osid.assessment.BankAdminSession) - a ``BankAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bank_admin() is false`` *compliance: optional -- This method must be implemented if ``supports_bank_admin()`` is true.*
Below is the the instruction that describes the task: ### Input: Gets the OsidSession associated with the bank administration service. return: (osid.assessment.BankAdminSession) - a ``BankAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bank_admin() is false`` *compliance: optional -- This method must be implemented if ``supports_bank_admin()`` is true.* ### Response: def get_bank_admin_session(self): """Gets the OsidSession associated with the bank administration service. return: (osid.assessment.BankAdminSession) - a ``BankAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bank_admin() is false`` *compliance: optional -- This method must be implemented if ``supports_bank_admin()`` is true.* """ if not self.supports_bank_admin(): raise errors.Unimplemented() # pylint: disable=no-member return sessions.BankAdminSession(runtime=self._runtime)
def connectionStats(self) -> ConnectionStats: """ Get statistics about the connection. """ if not self.isReady(): raise ConnectionError('Not connected') return ConnectionStats( self._startTime, time.time() - self._startTime, self._numBytesRecv, self.conn.numBytesSent, self._numMsgRecv, self.conn.numMsgSent)
Get statistics about the connection.
Below is the the instruction that describes the task: ### Input: Get statistics about the connection. ### Response: def connectionStats(self) -> ConnectionStats: """ Get statistics about the connection. """ if not self.isReady(): raise ConnectionError('Not connected') return ConnectionStats( self._startTime, time.time() - self._startTime, self._numBytesRecv, self.conn.numBytesSent, self._numMsgRecv, self.conn.numMsgSent)
def has_gocomics_comic(name): """Test if comic name already exists.""" cname = "Gocomics/%s" % name for scraperclass in get_scraperclasses(): lname = scraperclass.getName().lower() if lname == cname.lower(): return True return False
Test if comic name already exists.
Below is the the instruction that describes the task: ### Input: Test if comic name already exists. ### Response: def has_gocomics_comic(name): """Test if comic name already exists.""" cname = "Gocomics/%s" % name for scraperclass in get_scraperclasses(): lname = scraperclass.getName().lower() if lname == cname.lower(): return True return False
def upload_entities(namespace, workspace, entity_data): """Upload entities from tab-delimited string. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entity_data (str): TSV string describing entites Swagger: https://api.firecloud.org/#!/Entities/importEntities """ body = urlencode({"entities" : entity_data}) headers = _fiss_agent_header({ 'Content-type': "application/x-www-form-urlencoded" }) uri = "workspaces/{0}/{1}/importEntities".format(namespace, workspace) return __post(uri, headers=headers, data=body)
Upload entities from tab-delimited string. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entity_data (str): TSV string describing entites Swagger: https://api.firecloud.org/#!/Entities/importEntities
Below is the the instruction that describes the task: ### Input: Upload entities from tab-delimited string. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entity_data (str): TSV string describing entites Swagger: https://api.firecloud.org/#!/Entities/importEntities ### Response: def upload_entities(namespace, workspace, entity_data): """Upload entities from tab-delimited string. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entity_data (str): TSV string describing entites Swagger: https://api.firecloud.org/#!/Entities/importEntities """ body = urlencode({"entities" : entity_data}) headers = _fiss_agent_header({ 'Content-type': "application/x-www-form-urlencoded" }) uri = "workspaces/{0}/{1}/importEntities".format(namespace, workspace) return __post(uri, headers=headers, data=body)
def Y_less(self): """Decrease the scaling.""" self.parent.value('y_scale', self.parent.value('y_scale') / 2) self.parent.traces.display()
Decrease the scaling.
Below is the the instruction that describes the task: ### Input: Decrease the scaling. ### Response: def Y_less(self): """Decrease the scaling.""" self.parent.value('y_scale', self.parent.value('y_scale') / 2) self.parent.traces.display()
def get_weights(model_hparams, vocab_size, hidden_dim=None): """Create or get concatenated embedding or softmax variable. Args: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size Returns: a list of num_shards Tensors. """ if hidden_dim is None: hidden_dim = model_hparams.hidden_size num_shards = model_hparams.symbol_modality_num_shards shards = [] for i in range(num_shards): shard_size = (vocab_size // num_shards) + ( 1 if i < vocab_size % num_shards else 0) var_name = "weights_%d" % i shards.append( tf.get_variable( var_name, [shard_size, hidden_dim], initializer=tf.random_normal_initializer(0.0, hidden_dim**-0.5))) if num_shards == 1: ret = shards[0] else: ret = tf.concat(shards, 0) # Convert ret to tensor. if not tf.executing_eagerly(): ret = common_layers.convert_gradient_to_tensor(ret) return ret
Create or get concatenated embedding or softmax variable. Args: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size Returns: a list of num_shards Tensors.
Below is the the instruction that describes the task: ### Input: Create or get concatenated embedding or softmax variable. Args: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size Returns: a list of num_shards Tensors. ### Response: def get_weights(model_hparams, vocab_size, hidden_dim=None): """Create or get concatenated embedding or softmax variable. Args: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size Returns: a list of num_shards Tensors. """ if hidden_dim is None: hidden_dim = model_hparams.hidden_size num_shards = model_hparams.symbol_modality_num_shards shards = [] for i in range(num_shards): shard_size = (vocab_size // num_shards) + ( 1 if i < vocab_size % num_shards else 0) var_name = "weights_%d" % i shards.append( tf.get_variable( var_name, [shard_size, hidden_dim], initializer=tf.random_normal_initializer(0.0, hidden_dim**-0.5))) if num_shards == 1: ret = shards[0] else: ret = tf.concat(shards, 0) # Convert ret to tensor. if not tf.executing_eagerly(): ret = common_layers.convert_gradient_to_tensor(ret) return ret
def merge_dependency(self, item, resolve_parent, parents): """ Merge dependencies of element with further dependencies. First parent dependencies are checked, and then immediate dependencies of the current element should be added to the list, but without duplicating any entries. :param item: Item. :param resolve_parent: Function to resolve parent dependencies. :type resolve_parent: function :type parents: collections.Iterable :return: List of recursively resolved dependencies of this container. :rtype: list :raise CircularDependency: If the current element depends on one found deeper in the hierarchy. """ dep = [] for parent_key in parents: if item == parent_key: raise CircularDependency(item, True) parent_dep = resolve_parent(parent_key) if item in parent_dep: raise CircularDependency(item) merge_list(dep, parent_dep) merge_list(dep, parents) return dep
Merge dependencies of element with further dependencies. First parent dependencies are checked, and then immediate dependencies of the current element should be added to the list, but without duplicating any entries. :param item: Item. :param resolve_parent: Function to resolve parent dependencies. :type resolve_parent: function :type parents: collections.Iterable :return: List of recursively resolved dependencies of this container. :rtype: list :raise CircularDependency: If the current element depends on one found deeper in the hierarchy.
Below is the the instruction that describes the task: ### Input: Merge dependencies of element with further dependencies. First parent dependencies are checked, and then immediate dependencies of the current element should be added to the list, but without duplicating any entries. :param item: Item. :param resolve_parent: Function to resolve parent dependencies. :type resolve_parent: function :type parents: collections.Iterable :return: List of recursively resolved dependencies of this container. :rtype: list :raise CircularDependency: If the current element depends on one found deeper in the hierarchy. ### Response: def merge_dependency(self, item, resolve_parent, parents): """ Merge dependencies of element with further dependencies. First parent dependencies are checked, and then immediate dependencies of the current element should be added to the list, but without duplicating any entries. :param item: Item. :param resolve_parent: Function to resolve parent dependencies. :type resolve_parent: function :type parents: collections.Iterable :return: List of recursively resolved dependencies of this container. :rtype: list :raise CircularDependency: If the current element depends on one found deeper in the hierarchy. """ dep = [] for parent_key in parents: if item == parent_key: raise CircularDependency(item, True) parent_dep = resolve_parent(parent_key) if item in parent_dep: raise CircularDependency(item) merge_list(dep, parent_dep) merge_list(dep, parents) return dep
def reboot(env, identifier, hard): """Reboot an active server.""" hardware_server = env.client['Hardware_Server'] mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s. ' 'Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') if hard is True: hardware_server.rebootHard(id=hw_id) elif hard is False: hardware_server.rebootSoft(id=hw_id) else: hardware_server.rebootDefault(id=hw_id)
Reboot an active server.
Below is the the instruction that describes the task: ### Input: Reboot an active server. ### Response: def reboot(env, identifier, hard): """Reboot an active server.""" hardware_server = env.client['Hardware_Server'] mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s. ' 'Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') if hard is True: hardware_server.rebootHard(id=hw_id) elif hard is False: hardware_server.rebootSoft(id=hw_id) else: hardware_server.rebootDefault(id=hw_id)
def object_exists_in_project(obj_id, proj_id): ''' :param obj_id: object ID :type obj_id: str :param proj_id: project ID :type proj_id: str Returns True if the specified data object can be found in the specified project. ''' if obj_id is None: raise ValueError("Expected obj_id to be a string") if proj_id is None: raise ValueError("Expected proj_id to be a string") if not is_container_id(proj_id): raise ValueError('Expected %r to be a container ID' % (proj_id,)) return try_call(dxpy.DXHTTPRequest, '/' + obj_id + '/describe', {'project': proj_id})['project'] == proj_id
:param obj_id: object ID :type obj_id: str :param proj_id: project ID :type proj_id: str Returns True if the specified data object can be found in the specified project.
Below is the the instruction that describes the task: ### Input: :param obj_id: object ID :type obj_id: str :param proj_id: project ID :type proj_id: str Returns True if the specified data object can be found in the specified project. ### Response: def object_exists_in_project(obj_id, proj_id): ''' :param obj_id: object ID :type obj_id: str :param proj_id: project ID :type proj_id: str Returns True if the specified data object can be found in the specified project. ''' if obj_id is None: raise ValueError("Expected obj_id to be a string") if proj_id is None: raise ValueError("Expected proj_id to be a string") if not is_container_id(proj_id): raise ValueError('Expected %r to be a container ID' % (proj_id,)) return try_call(dxpy.DXHTTPRequest, '/' + obj_id + '/describe', {'project': proj_id})['project'] == proj_id
def write(self, oprot): ''' Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage ''' oprot.write_struct_begin('OnlineDatabaseObjectDetailImage') oprot.write_field_begin(name='full_size_url', type=11, id=None) oprot.write_string(self.full_size_url) oprot.write_field_end() oprot.write_field_begin(name='mediaid', type=11, id=None) oprot.write_string(self.mediaid) oprot.write_field_end() oprot.write_field_begin(name='objectid', type=11, id=None) oprot.write_string(self.objectid) oprot.write_field_end() oprot.write_field_begin(name='src', type=11, id=None) oprot.write_string(self.src) oprot.write_field_end() oprot.write_field_begin(name='thumbnail_url', type=11, id=None) oprot.write_string(self.thumbnail_url) oprot.write_field_end() oprot.write_field_begin(name='title', type=11, id=None) oprot.write_string(self.title) oprot.write_field_end() oprot.write_field_begin(name='type', type=11, id=None) oprot.write_string(str(self.type)) oprot.write_field_end() oprot.write_field_stop() oprot.write_struct_end() return self
Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage
Below is the the instruction that describes the task: ### Input: Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage ### Response: def write(self, oprot): ''' Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage ''' oprot.write_struct_begin('OnlineDatabaseObjectDetailImage') oprot.write_field_begin(name='full_size_url', type=11, id=None) oprot.write_string(self.full_size_url) oprot.write_field_end() oprot.write_field_begin(name='mediaid', type=11, id=None) oprot.write_string(self.mediaid) oprot.write_field_end() oprot.write_field_begin(name='objectid', type=11, id=None) oprot.write_string(self.objectid) oprot.write_field_end() oprot.write_field_begin(name='src', type=11, id=None) oprot.write_string(self.src) oprot.write_field_end() oprot.write_field_begin(name='thumbnail_url', type=11, id=None) oprot.write_string(self.thumbnail_url) oprot.write_field_end() oprot.write_field_begin(name='title', type=11, id=None) oprot.write_string(self.title) oprot.write_field_end() oprot.write_field_begin(name='type', type=11, id=None) oprot.write_string(str(self.type)) oprot.write_field_end() oprot.write_field_stop() oprot.write_struct_end() return self
def security(self): """ Creates a reference to the Security operations for Portal """ url = self._url + "/security" return _Security(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
Creates a reference to the Security operations for Portal
Below is the the instruction that describes the task: ### Input: Creates a reference to the Security operations for Portal ### Response: def security(self): """ Creates a reference to the Security operations for Portal """ url = self._url + "/security" return _Security(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
def fillna( self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs ): """Fill NA/NaN values using the specified method. Args: value: Value to use to fill holes. This value cannot be a list. method: Method to use for filling holes in reindexed Series pad. ffill: propagate last valid observation forward to next valid backfill. bfill: use NEXT valid observation to fill gap. axis: 0 or 'index', 1 or 'columns'. inplace: If True, fill in place. Note: this will modify any other views on this object. limit: If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. downcast: A dict of item->dtype of what to downcast if possible, or the string 'infer' which will try to downcast to an appropriate equal type. Returns: filled: DataFrame """ # TODO implement value passed as DataFrame/Series if isinstance(value, BasePandasDataset): new_query_compiler = self._default_to_pandas( "fillna", value=value._to_pandas(), method=method, axis=axis, inplace=False, limit=limit, downcast=downcast, **kwargs )._query_compiler return self._create_or_update_from_compiler(new_query_compiler, inplace) inplace = validate_bool_kwarg(inplace, "inplace") axis = self._get_axis_number(axis) if axis is not None else 0 if isinstance(value, (list, tuple)): raise TypeError( '"value" parameter must be a scalar or dict, but ' 'you passed a "{0}"'.format(type(value).__name__) ) if value is None and method is None: raise ValueError("must specify a fill method or value") if value is not None and method is not None: raise ValueError("cannot specify both a fill method and value") if method is not None and method not in ["backfill", "bfill", "pad", "ffill"]: expecting = "pad (ffill) or backfill (bfill)" msg = "Invalid fill method. Expecting {expecting}. Got {method}".format( expecting=expecting, method=method ) raise ValueError(msg) new_query_compiler = self._query_compiler.fillna( value=value, method=method, axis=axis, inplace=False, limit=limit, downcast=downcast, **kwargs ) return self._create_or_update_from_compiler(new_query_compiler, inplace)
Fill NA/NaN values using the specified method. Args: value: Value to use to fill holes. This value cannot be a list. method: Method to use for filling holes in reindexed Series pad. ffill: propagate last valid observation forward to next valid backfill. bfill: use NEXT valid observation to fill gap. axis: 0 or 'index', 1 or 'columns'. inplace: If True, fill in place. Note: this will modify any other views on this object. limit: If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. downcast: A dict of item->dtype of what to downcast if possible, or the string 'infer' which will try to downcast to an appropriate equal type. Returns: filled: DataFrame
Below is the the instruction that describes the task: ### Input: Fill NA/NaN values using the specified method. Args: value: Value to use to fill holes. This value cannot be a list. method: Method to use for filling holes in reindexed Series pad. ffill: propagate last valid observation forward to next valid backfill. bfill: use NEXT valid observation to fill gap. axis: 0 or 'index', 1 or 'columns'. inplace: If True, fill in place. Note: this will modify any other views on this object. limit: If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. downcast: A dict of item->dtype of what to downcast if possible, or the string 'infer' which will try to downcast to an appropriate equal type. Returns: filled: DataFrame ### Response: def fillna( self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs ): """Fill NA/NaN values using the specified method. Args: value: Value to use to fill holes. This value cannot be a list. method: Method to use for filling holes in reindexed Series pad. ffill: propagate last valid observation forward to next valid backfill. bfill: use NEXT valid observation to fill gap. axis: 0 or 'index', 1 or 'columns'. inplace: If True, fill in place. Note: this will modify any other views on this object. limit: If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. downcast: A dict of item->dtype of what to downcast if possible, or the string 'infer' which will try to downcast to an appropriate equal type. Returns: filled: DataFrame """ # TODO implement value passed as DataFrame/Series if isinstance(value, BasePandasDataset): new_query_compiler = self._default_to_pandas( "fillna", value=value._to_pandas(), method=method, axis=axis, inplace=False, limit=limit, downcast=downcast, **kwargs )._query_compiler return self._create_or_update_from_compiler(new_query_compiler, inplace) inplace = validate_bool_kwarg(inplace, "inplace") axis = self._get_axis_number(axis) if axis is not None else 0 if isinstance(value, (list, tuple)): raise TypeError( '"value" parameter must be a scalar or dict, but ' 'you passed a "{0}"'.format(type(value).__name__) ) if value is None and method is None: raise ValueError("must specify a fill method or value") if value is not None and method is not None: raise ValueError("cannot specify both a fill method and value") if method is not None and method not in ["backfill", "bfill", "pad", "ffill"]: expecting = "pad (ffill) or backfill (bfill)" msg = "Invalid fill method. Expecting {expecting}. Got {method}".format( expecting=expecting, method=method ) raise ValueError(msg) new_query_compiler = self._query_compiler.fillna( value=value, method=method, axis=axis, inplace=False, limit=limit, downcast=downcast, **kwargs ) return self._create_or_update_from_compiler(new_query_compiler, inplace)
def append(self, item): """ append a single item to the array, growing the wrapped numpy array if necessary """ try: self._data[self._position] = item except IndexError: self._grow() self._data[self._position] = item self._position += 1 return self
append a single item to the array, growing the wrapped numpy array if necessary
Below is the the instruction that describes the task: ### Input: append a single item to the array, growing the wrapped numpy array if necessary ### Response: def append(self, item): """ append a single item to the array, growing the wrapped numpy array if necessary """ try: self._data[self._position] = item except IndexError: self._grow() self._data[self._position] = item self._position += 1 return self
def sort_points(self, points): """Take points (z,x,q) and sort by increasing z""" new_points = [] z_lookup = {} for z, x, Q in points: z_lookup[z] = (z, x, Q) z_keys = z_lookup.keys() z_keys.sort() for key in z_keys: new_points.append(z_lookup[key]) return new_points
Take points (z,x,q) and sort by increasing z
Below is the the instruction that describes the task: ### Input: Take points (z,x,q) and sort by increasing z ### Response: def sort_points(self, points): """Take points (z,x,q) and sort by increasing z""" new_points = [] z_lookup = {} for z, x, Q in points: z_lookup[z] = (z, x, Q) z_keys = z_lookup.keys() z_keys.sort() for key in z_keys: new_points.append(z_lookup[key]) return new_points
def p_sens_empty(self, p): 'senslist : empty' p[0] = SensList( (Sens(None, 'all', lineno=p.lineno(1)),), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
senslist : empty
Below is the the instruction that describes the task: ### Input: senslist : empty ### Response: def p_sens_empty(self, p): 'senslist : empty' p[0] = SensList( (Sens(None, 'all', lineno=p.lineno(1)),), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
def extract_attributes(element, prefix_key_char='@', dict_constructor=dict): """ Given an XML node, extract a dictionary of attribute key-value pairs. Optional arguments: - prefix_key_char: if a character is given, the attributes keys in the resulting dictionary are prefixed with that character. - dict_constructor: the class used to create the resulting dictionary. Default is 'dict', but in DINGO, also DingoObjDict may be used. """ result = dict_constructor() if element.properties: for prop in element.properties: if not prop: break if prop.type == 'attribute': try: # First try with namespace. If no namespace exists, # an exception is raised result["%s%s:%s" % (prefix_key_char, prop.ns().name, prop.name)] = prop.content except: result["%s%s" % (prefix_key_char, prop.name)] = prop.content return result
Given an XML node, extract a dictionary of attribute key-value pairs. Optional arguments: - prefix_key_char: if a character is given, the attributes keys in the resulting dictionary are prefixed with that character. - dict_constructor: the class used to create the resulting dictionary. Default is 'dict', but in DINGO, also DingoObjDict may be used.
Below is the the instruction that describes the task: ### Input: Given an XML node, extract a dictionary of attribute key-value pairs. Optional arguments: - prefix_key_char: if a character is given, the attributes keys in the resulting dictionary are prefixed with that character. - dict_constructor: the class used to create the resulting dictionary. Default is 'dict', but in DINGO, also DingoObjDict may be used. ### Response: def extract_attributes(element, prefix_key_char='@', dict_constructor=dict): """ Given an XML node, extract a dictionary of attribute key-value pairs. Optional arguments: - prefix_key_char: if a character is given, the attributes keys in the resulting dictionary are prefixed with that character. - dict_constructor: the class used to create the resulting dictionary. Default is 'dict', but in DINGO, also DingoObjDict may be used. """ result = dict_constructor() if element.properties: for prop in element.properties: if not prop: break if prop.type == 'attribute': try: # First try with namespace. If no namespace exists, # an exception is raised result["%s%s:%s" % (prefix_key_char, prop.ns().name, prop.name)] = prop.content except: result["%s%s" % (prefix_key_char, prop.name)] = prop.content return result
def dump(obj): "Recursive convert a live GUI object to a resource list/dict" from .spec import InitSpec, DimensionSpec, StyleSpec, InternalSpec import decimal, datetime from .font import Font from .graphic import Bitmap, Color from . import registry ret = {'type': obj.__class__.__name__} for (k, spec) in obj._meta.specs.items(): if k == "index": # index is really defined by creation order continue # also, avoid infinite recursion v = getattr(obj, k, "") if (not isinstance(spec, InternalSpec) and v != spec.default and (k != 'id' or v > 0) and isinstance(v, (basestring, int, long, float, bool, dict, list, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, Font, Color)) and repr(v) != 'None' and k != 'parent' ): ret[k] = v for ctl in obj: if ret['type'] in registry.MENU: ret.setdefault('items', []).append(dump(ctl)) else: res = dump(ctl) if 'menubar' in res: ret.setdefault('menubar', []).append(res.pop('menubar')) else: ret.setdefault('components', []).append(res) return ret
Recursive convert a live GUI object to a resource list/dict
Below is the the instruction that describes the task: ### Input: Recursive convert a live GUI object to a resource list/dict ### Response: def dump(obj): "Recursive convert a live GUI object to a resource list/dict" from .spec import InitSpec, DimensionSpec, StyleSpec, InternalSpec import decimal, datetime from .font import Font from .graphic import Bitmap, Color from . import registry ret = {'type': obj.__class__.__name__} for (k, spec) in obj._meta.specs.items(): if k == "index": # index is really defined by creation order continue # also, avoid infinite recursion v = getattr(obj, k, "") if (not isinstance(spec, InternalSpec) and v != spec.default and (k != 'id' or v > 0) and isinstance(v, (basestring, int, long, float, bool, dict, list, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, Font, Color)) and repr(v) != 'None' and k != 'parent' ): ret[k] = v for ctl in obj: if ret['type'] in registry.MENU: ret.setdefault('items', []).append(dump(ctl)) else: res = dump(ctl) if 'menubar' in res: ret.setdefault('menubar', []).append(res.pop('menubar')) else: ret.setdefault('components', []).append(res) return ret
def inspect(self, w): """ Get the value of a wirevector in the last simulation cycle. :param w: the name of the WireVector to inspect (passing in a WireVector instead of a name is deprecated) :return: value of w in the current step of simulation Will throw KeyError if w is not being tracked in the simulation. """ try: return self.context[self._to_name(w)] except AttributeError: raise PyrtlError("No context available. Please run a simulation step in " "order to populate values for wires")
Get the value of a wirevector in the last simulation cycle. :param w: the name of the WireVector to inspect (passing in a WireVector instead of a name is deprecated) :return: value of w in the current step of simulation Will throw KeyError if w is not being tracked in the simulation.
Below is the the instruction that describes the task: ### Input: Get the value of a wirevector in the last simulation cycle. :param w: the name of the WireVector to inspect (passing in a WireVector instead of a name is deprecated) :return: value of w in the current step of simulation Will throw KeyError if w is not being tracked in the simulation. ### Response: def inspect(self, w): """ Get the value of a wirevector in the last simulation cycle. :param w: the name of the WireVector to inspect (passing in a WireVector instead of a name is deprecated) :return: value of w in the current step of simulation Will throw KeyError if w is not being tracked in the simulation. """ try: return self.context[self._to_name(w)] except AttributeError: raise PyrtlError("No context available. Please run a simulation step in " "order to populate values for wires")
def _signature_hash(self, tx_out_script, unsigned_txs_out_idx, hash_type): """ Return the canonical hash for a transaction. We need to remove references to the signature, since it's a signature of the hash before the signature is applied. :param tx_out_script: the script the coins for unsigned_txs_out_idx are coming from :param unsigned_txs_out_idx: where to put the tx_out_script :param hash_type: one of SIGHASH_NONE, SIGHASH_SINGLE, SIGHASH_ALL, optionally bitwise or'ed with SIGHASH_ANYONECANPAY """ # In case concatenating two scripts ends up with two codeseparators, # or an extra one at the end, this prevents all those possible incompatibilities. tx_out_script = self.delete_subscript(tx_out_script, self.ScriptTools.compile("OP_CODESEPARATOR")) # blank out other inputs' signatures txs_in = [self._tx_in_for_idx(i, tx_in, tx_out_script, unsigned_txs_out_idx) for i, tx_in in enumerate(self.tx.txs_in)] txs_out = self.tx.txs_out # Blank out some of the outputs if (hash_type & 0x1f) == SIGHASH_NONE: # Wildcard payee txs_out = [] # Let the others update at will for i in range(len(txs_in)): if i != unsigned_txs_out_idx: txs_in[i].sequence = 0 elif (hash_type & 0x1f) == SIGHASH_SINGLE: # This preserves the ability to validate existing legacy # transactions which followed a buggy path in Satoshi's # original code. if unsigned_txs_out_idx >= len(txs_out): # This should probably be moved to a constant, but the # likelihood of ever getting here is already really small # and getting smaller return (1 << 248) # Only lock in the txout payee at same index as txin; delete # any outputs after this one and set all outputs before this # one to "null" (where "null" means an empty script and a # value of -1) txs_out = [self.tx.TxOut(0xffffffffffffffff, b'')] * unsigned_txs_out_idx txs_out.append(self.tx.txs_out[unsigned_txs_out_idx]) # Let the others update at will for i in range(len(txs_in)): if i != unsigned_txs_out_idx: txs_in[i].sequence = 0 # Blank out other inputs completely, not recommended for open transactions if hash_type & SIGHASH_ANYONECANPAY: txs_in = [txs_in[unsigned_txs_out_idx]] tmp_tx = self.tx.__class__(self.tx.version, txs_in, txs_out, self.tx.lock_time) return from_bytes_32(tmp_tx.hash(hash_type=hash_type))
Return the canonical hash for a transaction. We need to remove references to the signature, since it's a signature of the hash before the signature is applied. :param tx_out_script: the script the coins for unsigned_txs_out_idx are coming from :param unsigned_txs_out_idx: where to put the tx_out_script :param hash_type: one of SIGHASH_NONE, SIGHASH_SINGLE, SIGHASH_ALL, optionally bitwise or'ed with SIGHASH_ANYONECANPAY
Below is the the instruction that describes the task: ### Input: Return the canonical hash for a transaction. We need to remove references to the signature, since it's a signature of the hash before the signature is applied. :param tx_out_script: the script the coins for unsigned_txs_out_idx are coming from :param unsigned_txs_out_idx: where to put the tx_out_script :param hash_type: one of SIGHASH_NONE, SIGHASH_SINGLE, SIGHASH_ALL, optionally bitwise or'ed with SIGHASH_ANYONECANPAY ### Response: def _signature_hash(self, tx_out_script, unsigned_txs_out_idx, hash_type): """ Return the canonical hash for a transaction. We need to remove references to the signature, since it's a signature of the hash before the signature is applied. :param tx_out_script: the script the coins for unsigned_txs_out_idx are coming from :param unsigned_txs_out_idx: where to put the tx_out_script :param hash_type: one of SIGHASH_NONE, SIGHASH_SINGLE, SIGHASH_ALL, optionally bitwise or'ed with SIGHASH_ANYONECANPAY """ # In case concatenating two scripts ends up with two codeseparators, # or an extra one at the end, this prevents all those possible incompatibilities. tx_out_script = self.delete_subscript(tx_out_script, self.ScriptTools.compile("OP_CODESEPARATOR")) # blank out other inputs' signatures txs_in = [self._tx_in_for_idx(i, tx_in, tx_out_script, unsigned_txs_out_idx) for i, tx_in in enumerate(self.tx.txs_in)] txs_out = self.tx.txs_out # Blank out some of the outputs if (hash_type & 0x1f) == SIGHASH_NONE: # Wildcard payee txs_out = [] # Let the others update at will for i in range(len(txs_in)): if i != unsigned_txs_out_idx: txs_in[i].sequence = 0 elif (hash_type & 0x1f) == SIGHASH_SINGLE: # This preserves the ability to validate existing legacy # transactions which followed a buggy path in Satoshi's # original code. if unsigned_txs_out_idx >= len(txs_out): # This should probably be moved to a constant, but the # likelihood of ever getting here is already really small # and getting smaller return (1 << 248) # Only lock in the txout payee at same index as txin; delete # any outputs after this one and set all outputs before this # one to "null" (where "null" means an empty script and a # value of -1) txs_out = [self.tx.TxOut(0xffffffffffffffff, b'')] * unsigned_txs_out_idx txs_out.append(self.tx.txs_out[unsigned_txs_out_idx]) # Let the others update at will for i in range(len(txs_in)): if i != unsigned_txs_out_idx: txs_in[i].sequence = 0 # Blank out other inputs completely, not recommended for open transactions if hash_type & SIGHASH_ANYONECANPAY: txs_in = [txs_in[unsigned_txs_out_idx]] tmp_tx = self.tx.__class__(self.tx.version, txs_in, txs_out, self.tx.lock_time) return from_bytes_32(tmp_tx.hash(hash_type=hash_type))
def reboot(name, call=None, session=None): ''' Reboot a vm .. code-block:: bash salt-cloud -a reboot xenvm01 ''' if call == 'function': raise SaltCloudException( 'The show_instnce function must be called with -a or --action.' ) if session is None: session = _get_session() log.info('Starting VM %s', name) vm = _get_vm(name, session) power_state = session.xenapi.VM.get_power_state(vm) if power_state == 'Running': task = session.xenapi.Async.VM.clean_reboot(vm) _run_async_task(task, session) return show_instance(name) else: return '{} is not running to be rebooted'.format(name)
Reboot a vm .. code-block:: bash salt-cloud -a reboot xenvm01
Below is the the instruction that describes the task: ### Input: Reboot a vm .. code-block:: bash salt-cloud -a reboot xenvm01 ### Response: def reboot(name, call=None, session=None): ''' Reboot a vm .. code-block:: bash salt-cloud -a reboot xenvm01 ''' if call == 'function': raise SaltCloudException( 'The show_instnce function must be called with -a or --action.' ) if session is None: session = _get_session() log.info('Starting VM %s', name) vm = _get_vm(name, session) power_state = session.xenapi.VM.get_power_state(vm) if power_state == 'Running': task = session.xenapi.Async.VM.clean_reboot(vm) _run_async_task(task, session) return show_instance(name) else: return '{} is not running to be rebooted'.format(name)
def fetch_sampling_rules(self): """ Use X-Ray botocore client to get the centralized sampling rules from X-Ray service. The call is proxied and signed by X-Ray Daemon. """ new_rules = [] resp = self._xray_client.get_sampling_rules() records = resp['SamplingRuleRecords'] for record in records: rule_def = record['SamplingRule'] if self._is_rule_valid(rule_def): rule = SamplingRule(name=rule_def['RuleName'], priority=rule_def['Priority'], rate=rule_def['FixedRate'], reservoir_size=rule_def['ReservoirSize'], host=rule_def['Host'], service=rule_def['ServiceName'], method=rule_def['HTTPMethod'], path=rule_def['URLPath'], service_type=rule_def['ServiceType']) new_rules.append(rule) return new_rules
Use X-Ray botocore client to get the centralized sampling rules from X-Ray service. The call is proxied and signed by X-Ray Daemon.
Below is the the instruction that describes the task: ### Input: Use X-Ray botocore client to get the centralized sampling rules from X-Ray service. The call is proxied and signed by X-Ray Daemon. ### Response: def fetch_sampling_rules(self): """ Use X-Ray botocore client to get the centralized sampling rules from X-Ray service. The call is proxied and signed by X-Ray Daemon. """ new_rules = [] resp = self._xray_client.get_sampling_rules() records = resp['SamplingRuleRecords'] for record in records: rule_def = record['SamplingRule'] if self._is_rule_valid(rule_def): rule = SamplingRule(name=rule_def['RuleName'], priority=rule_def['Priority'], rate=rule_def['FixedRate'], reservoir_size=rule_def['ReservoirSize'], host=rule_def['Host'], service=rule_def['ServiceName'], method=rule_def['HTTPMethod'], path=rule_def['URLPath'], service_type=rule_def['ServiceType']) new_rules.append(rule) return new_rules
def create_legacy_graph_tasks(): """Create tasks to recursively parse the legacy graph.""" return [ transitive_hydrated_targets, transitive_hydrated_target, hydrated_targets, hydrate_target, find_owners, hydrate_sources, hydrate_bundles, RootRule(OwnersRequest), ]
Create tasks to recursively parse the legacy graph.
Below is the the instruction that describes the task: ### Input: Create tasks to recursively parse the legacy graph. ### Response: def create_legacy_graph_tasks(): """Create tasks to recursively parse the legacy graph.""" return [ transitive_hydrated_targets, transitive_hydrated_target, hydrated_targets, hydrate_target, find_owners, hydrate_sources, hydrate_bundles, RootRule(OwnersRequest), ]
def auto(cls, syslog=None, stderr=None, level=None, extended=None, server=None): """Tries to guess a sound logging configuration. """ level = norm_level(level) or logging.INFO if syslog is None and stderr is None: if sys.stderr.isatty() or syslog_path() is None: log.info('Defaulting to STDERR logging.') syslog, stderr = None, level if extended is None: extended = (stderr or 0) <= logging.DEBUG else: log.info('Defaulting to logging with Syslog.') syslog, stderr = level, None return cls(syslog=syslog, stderr=stderr, extended=extended, server=server)
Tries to guess a sound logging configuration.
Below is the the instruction that describes the task: ### Input: Tries to guess a sound logging configuration. ### Response: def auto(cls, syslog=None, stderr=None, level=None, extended=None, server=None): """Tries to guess a sound logging configuration. """ level = norm_level(level) or logging.INFO if syslog is None and stderr is None: if sys.stderr.isatty() or syslog_path() is None: log.info('Defaulting to STDERR logging.') syslog, stderr = None, level if extended is None: extended = (stderr or 0) <= logging.DEBUG else: log.info('Defaulting to logging with Syslog.') syslog, stderr = level, None return cls(syslog=syslog, stderr=stderr, extended=extended, server=server)
def _av_weight(W1, W2): """ Function to convert from two seisan weights (0-4) to one hypoDD \ weight(0-1). :type W1: str :param W1: Seisan input weight (0-4) :type W2: str :param W2: Seisan input weight (0-4) :returns: str .. rubric:: Example >>> print(_av_weight(1, 4)) 0.3750 >>> print(_av_weight(0, 0)) 1.0000 >>> print(_av_weight(' ', ' ')) 1.0000 >>> print(_av_weight(-9, 0)) 0.5000 >>> print(_av_weight(1, -9)) 0.3750 """ if str(W1) in [' ', '']: W1 = 1 elif str(W1) in ['-9', '9', '9.0', '-9.0']: W1 = 0 elif float(W1) < 0: warnings.warn('Negative weight found, setting to zero') W1 = 0 else: W1 = 1 - (int(W1) / 4.0) if str(W2) in [' ', '']: W2 = 1 elif str(W2) in ['-9', '9', '9.0', '-9.0']: W2 = 0 elif float(W2) < 0: warnings.warn('Negative weight found, setting to zero') W2 = 0 else: W2 = 1 - (int(W2) / 4.0) W = (W1 + W2) / 2 if W < 0: print('Weight 1: ' + str(W1)) print('Weight 2: ' + str(W2)) print('Final weight: ' + str(W)) raise IOError('Negative average weight calculated, setting to zero') return _cc_round(W, 4)
Function to convert from two seisan weights (0-4) to one hypoDD \ weight(0-1). :type W1: str :param W1: Seisan input weight (0-4) :type W2: str :param W2: Seisan input weight (0-4) :returns: str .. rubric:: Example >>> print(_av_weight(1, 4)) 0.3750 >>> print(_av_weight(0, 0)) 1.0000 >>> print(_av_weight(' ', ' ')) 1.0000 >>> print(_av_weight(-9, 0)) 0.5000 >>> print(_av_weight(1, -9)) 0.3750
Below is the the instruction that describes the task: ### Input: Function to convert from two seisan weights (0-4) to one hypoDD \ weight(0-1). :type W1: str :param W1: Seisan input weight (0-4) :type W2: str :param W2: Seisan input weight (0-4) :returns: str .. rubric:: Example >>> print(_av_weight(1, 4)) 0.3750 >>> print(_av_weight(0, 0)) 1.0000 >>> print(_av_weight(' ', ' ')) 1.0000 >>> print(_av_weight(-9, 0)) 0.5000 >>> print(_av_weight(1, -9)) 0.3750 ### Response: def _av_weight(W1, W2): """ Function to convert from two seisan weights (0-4) to one hypoDD \ weight(0-1). :type W1: str :param W1: Seisan input weight (0-4) :type W2: str :param W2: Seisan input weight (0-4) :returns: str .. rubric:: Example >>> print(_av_weight(1, 4)) 0.3750 >>> print(_av_weight(0, 0)) 1.0000 >>> print(_av_weight(' ', ' ')) 1.0000 >>> print(_av_weight(-9, 0)) 0.5000 >>> print(_av_weight(1, -9)) 0.3750 """ if str(W1) in [' ', '']: W1 = 1 elif str(W1) in ['-9', '9', '9.0', '-9.0']: W1 = 0 elif float(W1) < 0: warnings.warn('Negative weight found, setting to zero') W1 = 0 else: W1 = 1 - (int(W1) / 4.0) if str(W2) in [' ', '']: W2 = 1 elif str(W2) in ['-9', '9', '9.0', '-9.0']: W2 = 0 elif float(W2) < 0: warnings.warn('Negative weight found, setting to zero') W2 = 0 else: W2 = 1 - (int(W2) / 4.0) W = (W1 + W2) / 2 if W < 0: print('Weight 1: ' + str(W1)) print('Weight 2: ' + str(W2)) print('Final weight: ' + str(W)) raise IOError('Negative average weight calculated, setting to zero') return _cc_round(W, 4)
def line_cap_type(self): """Cap type, one of `butt`, `round`, `square`.""" key = self._data.get(b'strokeStyleLineCapType').enum return self.STROKE_STYLE_LINE_CAP_TYPES.get(key, str(key))
Cap type, one of `butt`, `round`, `square`.
Below is the the instruction that describes the task: ### Input: Cap type, one of `butt`, `round`, `square`. ### Response: def line_cap_type(self): """Cap type, one of `butt`, `round`, `square`.""" key = self._data.get(b'strokeStyleLineCapType').enum return self.STROKE_STYLE_LINE_CAP_TYPES.get(key, str(key))
def _check_with_socket(self, sock_info): """Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailure. """ start = _time() try: return (sock_info.ismaster(self._pool.opts.metadata, self._topology.max_cluster_time()), _time() - start) except OperationFailure as exc: # Update max cluster time even when isMaster fails. self._topology.receive_cluster_time( exc.details.get('$clusterTime')) raise
Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailure.
Below is the the instruction that describes the task: ### Input: Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailure. ### Response: def _check_with_socket(self, sock_info): """Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailure. """ start = _time() try: return (sock_info.ismaster(self._pool.opts.metadata, self._topology.max_cluster_time()), _time() - start) except OperationFailure as exc: # Update max cluster time even when isMaster fails. self._topology.receive_cluster_time( exc.details.get('$clusterTime')) raise
def add_output(self, line): """ Appends {line} of output to the output instantly. (directly hits the database) :param line: the line of text to append :return: None """ Deployment.objects.filter(pk=self.id).update(output=CF('output')+line)
Appends {line} of output to the output instantly. (directly hits the database) :param line: the line of text to append :return: None
Below is the the instruction that describes the task: ### Input: Appends {line} of output to the output instantly. (directly hits the database) :param line: the line of text to append :return: None ### Response: def add_output(self, line): """ Appends {line} of output to the output instantly. (directly hits the database) :param line: the line of text to append :return: None """ Deployment.objects.filter(pk=self.id).update(output=CF('output')+line)
def activate(self, uid=None): """ Activate a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to activate. Optional, defaults to None. Returns: None Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input argument is invalid """ # Check input if uid is not None: if not isinstance(uid, six.string_types): raise TypeError("uid must be a string") # Activate the managed object and handle the results result = self.proxy.activate(uid) status = result.result_status.value if status == enums.ResultStatus.SUCCESS: return else: reason = result.result_reason.value message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message)
Activate a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to activate. Optional, defaults to None. Returns: None Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input argument is invalid
Below is the the instruction that describes the task: ### Input: Activate a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to activate. Optional, defaults to None. Returns: None Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input argument is invalid ### Response: def activate(self, uid=None): """ Activate a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to activate. Optional, defaults to None. Returns: None Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input argument is invalid """ # Check input if uid is not None: if not isinstance(uid, six.string_types): raise TypeError("uid must be a string") # Activate the managed object and handle the results result = self.proxy.activate(uid) status = result.result_status.value if status == enums.ResultStatus.SUCCESS: return else: reason = result.result_reason.value message = result.result_message.value raise exceptions.KmipOperationFailure(status, reason, message)
def staff_mo(I,T,N,J,S,c,b): """ staff: staff scheduling Parameters: - I: set of members in the staff - T: number of periods in a cycle - N: number of working periods required for staff's elements in a cycle - J: set of shifts in each period (shift 0 == rest) - S: subset of shifts that must be kept at least consecutive days - c[i,t,j]: cost of a shit j of staff's element i on period t - b[t,j]: number of staff elements required in period t, shift j Returns a model with no objective function. """ Ts = range(1,T+1) model = Model("staff scheduling -- multiobjective version") x,y = {},{} for t in Ts: for j in J: for i in I: x[i,t,j] = model.addVar(vtype="B", name="x(%s,%s,%s)" % (i,t,j)) y[t,j] = model.addVar(vtype="C", name="y(%s,%s)" % (t,j)) C = model.addVar(vtype="C", name="cost") U = model.addVar(vtype="C", name="uncovered") model.addCons(C >= quicksum(c[i,t,j]*x[i,t,j] for i in I for t in Ts for j in J if j != 0), "Cost") model.addCons(U >= quicksum(y[t,j] for t in Ts for j in J if j != 0), "Uncovered") for t in Ts: for j in J: if j == 0: continue model.addCons(quicksum(x[i,t,j] for i in I) >= b[t,j] - y[t,j], "Cover(%s,%s)" % (t,j)) for i in I: model.addCons(quicksum(x[i,t,j] for t in Ts for j in J if j != 0) == N, "Work(%s)"%i) for t in Ts: model.addCons(quicksum(x[i,t,j] for j in J) == 1, "Assign(%s,%s)" % (i,t)) for j in J: if j != 0: model.addCons(x[i,t,j] + quicksum(x[i,t,k] for k in J if k != j and k != 0) <= 1,\ "Require(%s,%s,%s)" % (i,t,j)) for t in range(2,T): for j in S: model.addCons(x[i,t-1,j] + x[i,t+1,j] >= x[i,t,j], "SameShift(%s,%s,%s)" % (i,t,j)) model.data = x,y,C,U return model
staff: staff scheduling Parameters: - I: set of members in the staff - T: number of periods in a cycle - N: number of working periods required for staff's elements in a cycle - J: set of shifts in each period (shift 0 == rest) - S: subset of shifts that must be kept at least consecutive days - c[i,t,j]: cost of a shit j of staff's element i on period t - b[t,j]: number of staff elements required in period t, shift j Returns a model with no objective function.
Below is the the instruction that describes the task: ### Input: staff: staff scheduling Parameters: - I: set of members in the staff - T: number of periods in a cycle - N: number of working periods required for staff's elements in a cycle - J: set of shifts in each period (shift 0 == rest) - S: subset of shifts that must be kept at least consecutive days - c[i,t,j]: cost of a shit j of staff's element i on period t - b[t,j]: number of staff elements required in period t, shift j Returns a model with no objective function. ### Response: def staff_mo(I,T,N,J,S,c,b): """ staff: staff scheduling Parameters: - I: set of members in the staff - T: number of periods in a cycle - N: number of working periods required for staff's elements in a cycle - J: set of shifts in each period (shift 0 == rest) - S: subset of shifts that must be kept at least consecutive days - c[i,t,j]: cost of a shit j of staff's element i on period t - b[t,j]: number of staff elements required in period t, shift j Returns a model with no objective function. """ Ts = range(1,T+1) model = Model("staff scheduling -- multiobjective version") x,y = {},{} for t in Ts: for j in J: for i in I: x[i,t,j] = model.addVar(vtype="B", name="x(%s,%s,%s)" % (i,t,j)) y[t,j] = model.addVar(vtype="C", name="y(%s,%s)" % (t,j)) C = model.addVar(vtype="C", name="cost") U = model.addVar(vtype="C", name="uncovered") model.addCons(C >= quicksum(c[i,t,j]*x[i,t,j] for i in I for t in Ts for j in J if j != 0), "Cost") model.addCons(U >= quicksum(y[t,j] for t in Ts for j in J if j != 0), "Uncovered") for t in Ts: for j in J: if j == 0: continue model.addCons(quicksum(x[i,t,j] for i in I) >= b[t,j] - y[t,j], "Cover(%s,%s)" % (t,j)) for i in I: model.addCons(quicksum(x[i,t,j] for t in Ts for j in J if j != 0) == N, "Work(%s)"%i) for t in Ts: model.addCons(quicksum(x[i,t,j] for j in J) == 1, "Assign(%s,%s)" % (i,t)) for j in J: if j != 0: model.addCons(x[i,t,j] + quicksum(x[i,t,k] for k in J if k != j and k != 0) <= 1,\ "Require(%s,%s,%s)" % (i,t,j)) for t in range(2,T): for j in S: model.addCons(x[i,t-1,j] + x[i,t+1,j] >= x[i,t,j], "SameShift(%s,%s,%s)" % (i,t,j)) model.data = x,y,C,U return model
async def restore_networking_configuration(self): """ Restore machine's networking configuration to its initial state. """ self._data = await self._handler.restore_networking_configuration( system_id=self.system_id)
Restore machine's networking configuration to its initial state.
Below is the the instruction that describes the task: ### Input: Restore machine's networking configuration to its initial state. ### Response: async def restore_networking_configuration(self): """ Restore machine's networking configuration to its initial state. """ self._data = await self._handler.restore_networking_configuration( system_id=self.system_id)
def conj(self, out=None): """Complex conjugate of this element. Parameters ---------- out : `DiscreteLpElement`, optional Element to which the complex conjugate is written. Must be an element of this element's space. Returns ------- out : `DiscreteLpElement` The complex conjugate element. If ``out`` is provided, the returned object is a reference to it. Examples -------- >>> discr = uniform_discr(0, 1, 4, dtype=complex) >>> x = discr.element([5+1j, 3, 2-2j, 1j]) >>> y = x.conj() >>> print(y) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] The out parameter allows you to avoid a copy: >>> z = discr.element() >>> z_out = x.conj(out=z) >>> print(z) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] >>> z_out is z True It can also be used for in-place conjugation: >>> x_out = x.conj(out=x) >>> print(x) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] >>> x_out is x True """ if out is None: return self.space.element(self.tensor.conj()) else: self.tensor.conj(out=out.tensor) return out
Complex conjugate of this element. Parameters ---------- out : `DiscreteLpElement`, optional Element to which the complex conjugate is written. Must be an element of this element's space. Returns ------- out : `DiscreteLpElement` The complex conjugate element. If ``out`` is provided, the returned object is a reference to it. Examples -------- >>> discr = uniform_discr(0, 1, 4, dtype=complex) >>> x = discr.element([5+1j, 3, 2-2j, 1j]) >>> y = x.conj() >>> print(y) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] The out parameter allows you to avoid a copy: >>> z = discr.element() >>> z_out = x.conj(out=z) >>> print(z) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] >>> z_out is z True It can also be used for in-place conjugation: >>> x_out = x.conj(out=x) >>> print(x) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] >>> x_out is x True
Below is the the instruction that describes the task: ### Input: Complex conjugate of this element. Parameters ---------- out : `DiscreteLpElement`, optional Element to which the complex conjugate is written. Must be an element of this element's space. Returns ------- out : `DiscreteLpElement` The complex conjugate element. If ``out`` is provided, the returned object is a reference to it. Examples -------- >>> discr = uniform_discr(0, 1, 4, dtype=complex) >>> x = discr.element([5+1j, 3, 2-2j, 1j]) >>> y = x.conj() >>> print(y) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] The out parameter allows you to avoid a copy: >>> z = discr.element() >>> z_out = x.conj(out=z) >>> print(z) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] >>> z_out is z True It can also be used for in-place conjugation: >>> x_out = x.conj(out=x) >>> print(x) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] >>> x_out is x True ### Response: def conj(self, out=None): """Complex conjugate of this element. Parameters ---------- out : `DiscreteLpElement`, optional Element to which the complex conjugate is written. Must be an element of this element's space. Returns ------- out : `DiscreteLpElement` The complex conjugate element. If ``out`` is provided, the returned object is a reference to it. Examples -------- >>> discr = uniform_discr(0, 1, 4, dtype=complex) >>> x = discr.element([5+1j, 3, 2-2j, 1j]) >>> y = x.conj() >>> print(y) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] The out parameter allows you to avoid a copy: >>> z = discr.element() >>> z_out = x.conj(out=z) >>> print(z) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] >>> z_out is z True It can also be used for in-place conjugation: >>> x_out = x.conj(out=x) >>> print(x) [ 5.-1.j, 3.-0.j, 2.+2.j, 0.-1.j] >>> x_out is x True """ if out is None: return self.space.element(self.tensor.conj()) else: self.tensor.conj(out=out.tensor) return out
def as_colr( self, label_args=None, type_args=None, type_val_args=None, value_args=None, spec_args=None): """ Like __str__, except it returns a colorized Colr instance. """ label_args = label_args or {'fore': 'red'} type_args = type_args or {'fore': 'yellow'} type_val_args = type_val_args or {'fore': 'grey'} value_args = value_args or {'fore': 'blue', 'style': 'bright'} spec_args = spec_args or {'fore': 'blue'} spec_repr = repr(self.spec) spec_quote = spec_repr[0] val_repr = repr(self.value) val_quote = val_repr[0] return Colr(self.default_format.format( label=Colr(':\n ').join( Colr('Bad format spec. color name/value', **label_args), ',\n '.join( '{lbl:<5} ({val})'.format( lbl=Colr(l, **type_args), val=Colr(v, **type_val_args), ) for l, v in self.accepted_values ) ), spec=Colr('=').join( Colr(v, **spec_args) for v in spec_repr[1:-1].split('=') ).join((spec_quote, spec_quote)), value=Colr( val_repr[1:-1], **value_args ).join((val_quote, val_quote)), ))
Like __str__, except it returns a colorized Colr instance.
Below is the the instruction that describes the task: ### Input: Like __str__, except it returns a colorized Colr instance. ### Response: def as_colr( self, label_args=None, type_args=None, type_val_args=None, value_args=None, spec_args=None): """ Like __str__, except it returns a colorized Colr instance. """ label_args = label_args or {'fore': 'red'} type_args = type_args or {'fore': 'yellow'} type_val_args = type_val_args or {'fore': 'grey'} value_args = value_args or {'fore': 'blue', 'style': 'bright'} spec_args = spec_args or {'fore': 'blue'} spec_repr = repr(self.spec) spec_quote = spec_repr[0] val_repr = repr(self.value) val_quote = val_repr[0] return Colr(self.default_format.format( label=Colr(':\n ').join( Colr('Bad format spec. color name/value', **label_args), ',\n '.join( '{lbl:<5} ({val})'.format( lbl=Colr(l, **type_args), val=Colr(v, **type_val_args), ) for l, v in self.accepted_values ) ), spec=Colr('=').join( Colr(v, **spec_args) for v in spec_repr[1:-1].split('=') ).join((spec_quote, spec_quote)), value=Colr( val_repr[1:-1], **value_args ).join((val_quote, val_quote)), ))
def add_cpds(self, *cpds): """ Add linear Gaussian CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : instances of LinearGaussianCPD List of LinearGaussianCPDs which will be associated with the model Examples -------- >>> from pgmpy.models import LinearGaussianBayesianNetwork >>> from pgmpy.factors.continuous import LinearGaussianCPD >>> model = LinearGaussianBayesianNetwork([('x1', 'x2'), ('x2', 'x3')]) >>> cpd1 = LinearGaussianCPD('x1', [1], 4) >>> cpd2 = LinearGaussianCPD('x2', [-5, 0.5], 4, ['x1']) >>> cpd3 = LinearGaussianCPD('x3', [4, -1], 3, ['x2']) >>> model.add_cpds(cpd1, cpd2, cpd3) >>> for cpd in model.cpds: print(cpd) P(x1) = N(1; 4) P(x2| x1) = N(0.5*x1_mu); -5) P(x3| x2) = N(-1*x2_mu); 4) """ for cpd in cpds: if not isinstance(cpd, LinearGaussianCPD): raise ValueError('Only LinearGaussianCPD can be added.') if set(cpd.variables) - set(cpd.variables).intersection( set(self.nodes())): raise ValueError('CPD defined on variable not in the model', cpd) for prev_cpd_index in range(len(self.cpds)): if self.cpds[prev_cpd_index].variable == cpd.variable: logging.warning("Replacing existing CPD for {var}".format(var=cpd.variable)) self.cpds[prev_cpd_index] = cpd break else: self.cpds.append(cpd)
Add linear Gaussian CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : instances of LinearGaussianCPD List of LinearGaussianCPDs which will be associated with the model Examples -------- >>> from pgmpy.models import LinearGaussianBayesianNetwork >>> from pgmpy.factors.continuous import LinearGaussianCPD >>> model = LinearGaussianBayesianNetwork([('x1', 'x2'), ('x2', 'x3')]) >>> cpd1 = LinearGaussianCPD('x1', [1], 4) >>> cpd2 = LinearGaussianCPD('x2', [-5, 0.5], 4, ['x1']) >>> cpd3 = LinearGaussianCPD('x3', [4, -1], 3, ['x2']) >>> model.add_cpds(cpd1, cpd2, cpd3) >>> for cpd in model.cpds: print(cpd) P(x1) = N(1; 4) P(x2| x1) = N(0.5*x1_mu); -5) P(x3| x2) = N(-1*x2_mu); 4)
Below is the the instruction that describes the task: ### Input: Add linear Gaussian CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : instances of LinearGaussianCPD List of LinearGaussianCPDs which will be associated with the model Examples -------- >>> from pgmpy.models import LinearGaussianBayesianNetwork >>> from pgmpy.factors.continuous import LinearGaussianCPD >>> model = LinearGaussianBayesianNetwork([('x1', 'x2'), ('x2', 'x3')]) >>> cpd1 = LinearGaussianCPD('x1', [1], 4) >>> cpd2 = LinearGaussianCPD('x2', [-5, 0.5], 4, ['x1']) >>> cpd3 = LinearGaussianCPD('x3', [4, -1], 3, ['x2']) >>> model.add_cpds(cpd1, cpd2, cpd3) >>> for cpd in model.cpds: print(cpd) P(x1) = N(1; 4) P(x2| x1) = N(0.5*x1_mu); -5) P(x3| x2) = N(-1*x2_mu); 4) ### Response: def add_cpds(self, *cpds): """ Add linear Gaussian CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : instances of LinearGaussianCPD List of LinearGaussianCPDs which will be associated with the model Examples -------- >>> from pgmpy.models import LinearGaussianBayesianNetwork >>> from pgmpy.factors.continuous import LinearGaussianCPD >>> model = LinearGaussianBayesianNetwork([('x1', 'x2'), ('x2', 'x3')]) >>> cpd1 = LinearGaussianCPD('x1', [1], 4) >>> cpd2 = LinearGaussianCPD('x2', [-5, 0.5], 4, ['x1']) >>> cpd3 = LinearGaussianCPD('x3', [4, -1], 3, ['x2']) >>> model.add_cpds(cpd1, cpd2, cpd3) >>> for cpd in model.cpds: print(cpd) P(x1) = N(1; 4) P(x2| x1) = N(0.5*x1_mu); -5) P(x3| x2) = N(-1*x2_mu); 4) """ for cpd in cpds: if not isinstance(cpd, LinearGaussianCPD): raise ValueError('Only LinearGaussianCPD can be added.') if set(cpd.variables) - set(cpd.variables).intersection( set(self.nodes())): raise ValueError('CPD defined on variable not in the model', cpd) for prev_cpd_index in range(len(self.cpds)): if self.cpds[prev_cpd_index].variable == cpd.variable: logging.warning("Replacing existing CPD for {var}".format(var=cpd.variable)) self.cpds[prev_cpd_index] = cpd break else: self.cpds.append(cpd)
def internal_model_from_file( self, file_name, encoding='utf-8', debug=None, pre_ref_resolution_callback=None, is_main_model=True): """ Instantiates model from the given file. :param pre_ref_resolution_callback: called before references are resolved. This can be useful to manage models distributed across files (scoping) """ model = None callback = pre_ref_resolution_callback if hasattr(self, "_tx_model_repository"): # metamodel has a global repo if not callback: def _pre_ref_resolution_callback(other_model): from textx.scoping import GlobalModelRepository filename = other_model._tx_filename assert filename # print("METAMODEL PRE-CALLBACK{}".format(filename)) other_model._tx_model_repository = GlobalModelRepository( self._tx_model_repository.all_models) self._tx_model_repository.all_models\ .filename_to_model[filename] = other_model callback = _pre_ref_resolution_callback if self._tx_model_repository.all_models.has_model(file_name): model = self._tx_model_repository.all_models\ .filename_to_model[file_name] if not model: # model not present (from global repo) -> load it model = self._parser_blueprint.clone().get_model_from_file( file_name, encoding, debug=debug, pre_ref_resolution_callback=callback, is_main_model=is_main_model) for p in self._model_processors: p(model, self) return model
Instantiates model from the given file. :param pre_ref_resolution_callback: called before references are resolved. This can be useful to manage models distributed across files (scoping)
Below is the the instruction that describes the task: ### Input: Instantiates model from the given file. :param pre_ref_resolution_callback: called before references are resolved. This can be useful to manage models distributed across files (scoping) ### Response: def internal_model_from_file( self, file_name, encoding='utf-8', debug=None, pre_ref_resolution_callback=None, is_main_model=True): """ Instantiates model from the given file. :param pre_ref_resolution_callback: called before references are resolved. This can be useful to manage models distributed across files (scoping) """ model = None callback = pre_ref_resolution_callback if hasattr(self, "_tx_model_repository"): # metamodel has a global repo if not callback: def _pre_ref_resolution_callback(other_model): from textx.scoping import GlobalModelRepository filename = other_model._tx_filename assert filename # print("METAMODEL PRE-CALLBACK{}".format(filename)) other_model._tx_model_repository = GlobalModelRepository( self._tx_model_repository.all_models) self._tx_model_repository.all_models\ .filename_to_model[filename] = other_model callback = _pre_ref_resolution_callback if self._tx_model_repository.all_models.has_model(file_name): model = self._tx_model_repository.all_models\ .filename_to_model[file_name] if not model: # model not present (from global repo) -> load it model = self._parser_blueprint.clone().get_model_from_file( file_name, encoding, debug=debug, pre_ref_resolution_callback=callback, is_main_model=is_main_model) for p in self._model_processors: p(model, self) return model
def format_error(error): """Serialise exception""" formatted = {"message": str(error)} if hasattr(error, "traceback"): fname, line_no, func, exc = error.traceback formatted.update({ "fname": fname, "line_number": line_no, "func": func, "exc": exc }) return formatted
Serialise exception
Below is the the instruction that describes the task: ### Input: Serialise exception ### Response: def format_error(error): """Serialise exception""" formatted = {"message": str(error)} if hasattr(error, "traceback"): fname, line_no, func, exc = error.traceback formatted.update({ "fname": fname, "line_number": line_no, "func": func, "exc": exc }) return formatted
def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = "%s_%s-%s" % (meta["lang"], meta["name"], meta["version"]) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides)
Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model.
Below is the the instruction that describes the task: ### Input: Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. ### Response: def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = "%s_%s-%s" % (meta["lang"], meta["name"], meta["version"]) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides)
def random(self, cascadeFetch=False): ''' Random - Returns a random record in current filterset. @param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model will be fetched immediately. If False, foreign objects will be fetched on-access. @return - Instance of Model object, or None if no items math current filters ''' matchedKeys = list(self.getPrimaryKeys()) obj = None # Loop so we don't return None when there are items, if item is deleted between getting key and getting obj while matchedKeys and not obj: key = matchedKeys.pop(random.randint(0, len(matchedKeys)-1)) obj = self.get(key, cascadeFetch=cascadeFetch) return obj
Random - Returns a random record in current filterset. @param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model will be fetched immediately. If False, foreign objects will be fetched on-access. @return - Instance of Model object, or None if no items math current filters
Below is the the instruction that describes the task: ### Input: Random - Returns a random record in current filterset. @param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model will be fetched immediately. If False, foreign objects will be fetched on-access. @return - Instance of Model object, or None if no items math current filters ### Response: def random(self, cascadeFetch=False): ''' Random - Returns a random record in current filterset. @param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model will be fetched immediately. If False, foreign objects will be fetched on-access. @return - Instance of Model object, or None if no items math current filters ''' matchedKeys = list(self.getPrimaryKeys()) obj = None # Loop so we don't return None when there are items, if item is deleted between getting key and getting obj while matchedKeys and not obj: key = matchedKeys.pop(random.randint(0, len(matchedKeys)-1)) obj = self.get(key, cascadeFetch=cascadeFetch) return obj
def vm_trace(ext, msg, compustate, opcode, pushcache, tracer=log_vm_op): """ This diverges from normal logging, as we use the logging namespace only to decide which features get logged in 'eth.vm.op' i.e. tracing can not be activated by activating a sub like 'eth.vm.op.stack' """ op, in_args, out_args, fee = opcodes.opcodes[opcode] trace_data = {} trace_data['stack'] = list(map(to_string, list(compustate.prev_stack))) if compustate.prev_prev_op in ('MLOAD', 'MSTORE', 'MSTORE8', 'SHA3', 'CALL', 'CALLCODE', 'CREATE', 'CALLDATACOPY', 'CODECOPY', 'EXTCODECOPY'): if len(compustate.prev_memory) < 4096: trace_data['memory'] = \ ''.join([encode_hex(ascii_chr(x)) for x in compustate.prev_memory]) else: trace_data['sha3memory'] = \ encode_hex(utils.sha3(b''.join([ascii_chr(x) for x in compustate.prev_memory]))) if compustate.prev_prev_op in ('SSTORE',) or compustate.steps == 0: trace_data['storage'] = ext.log_storage(msg.to) trace_data['gas'] = to_string(compustate.prev_gas) trace_data['gas_cost'] = to_string(compustate.prev_gas - compustate.gas) trace_data['fee'] = fee trace_data['inst'] = opcode trace_data['pc'] = to_string(compustate.prev_pc) if compustate.steps == 0: trace_data['depth'] = msg.depth trace_data['address'] = msg.to trace_data['steps'] = compustate.steps trace_data['depth'] = msg.depth if op[:4] == 'PUSH': print(repr(pushcache)) trace_data['pushvalue'] = pushcache[compustate.prev_pc] tracer.trace('vm', op=op, **trace_data) compustate.steps += 1 compustate.prev_prev_op = op
This diverges from normal logging, as we use the logging namespace only to decide which features get logged in 'eth.vm.op' i.e. tracing can not be activated by activating a sub like 'eth.vm.op.stack'
Below is the the instruction that describes the task: ### Input: This diverges from normal logging, as we use the logging namespace only to decide which features get logged in 'eth.vm.op' i.e. tracing can not be activated by activating a sub like 'eth.vm.op.stack' ### Response: def vm_trace(ext, msg, compustate, opcode, pushcache, tracer=log_vm_op): """ This diverges from normal logging, as we use the logging namespace only to decide which features get logged in 'eth.vm.op' i.e. tracing can not be activated by activating a sub like 'eth.vm.op.stack' """ op, in_args, out_args, fee = opcodes.opcodes[opcode] trace_data = {} trace_data['stack'] = list(map(to_string, list(compustate.prev_stack))) if compustate.prev_prev_op in ('MLOAD', 'MSTORE', 'MSTORE8', 'SHA3', 'CALL', 'CALLCODE', 'CREATE', 'CALLDATACOPY', 'CODECOPY', 'EXTCODECOPY'): if len(compustate.prev_memory) < 4096: trace_data['memory'] = \ ''.join([encode_hex(ascii_chr(x)) for x in compustate.prev_memory]) else: trace_data['sha3memory'] = \ encode_hex(utils.sha3(b''.join([ascii_chr(x) for x in compustate.prev_memory]))) if compustate.prev_prev_op in ('SSTORE',) or compustate.steps == 0: trace_data['storage'] = ext.log_storage(msg.to) trace_data['gas'] = to_string(compustate.prev_gas) trace_data['gas_cost'] = to_string(compustate.prev_gas - compustate.gas) trace_data['fee'] = fee trace_data['inst'] = opcode trace_data['pc'] = to_string(compustate.prev_pc) if compustate.steps == 0: trace_data['depth'] = msg.depth trace_data['address'] = msg.to trace_data['steps'] = compustate.steps trace_data['depth'] = msg.depth if op[:4] == 'PUSH': print(repr(pushcache)) trace_data['pushvalue'] = pushcache[compustate.prev_pc] tracer.trace('vm', op=op, **trace_data) compustate.steps += 1 compustate.prev_prev_op = op
def getaddress(self, address: str) -> dict: '''Returns information for given address.''' return cast(dict, self.ext_fetch('getaddress/' + address))
Returns information for given address.
Below is the the instruction that describes the task: ### Input: Returns information for given address. ### Response: def getaddress(self, address: str) -> dict: '''Returns information for given address.''' return cast(dict, self.ext_fetch('getaddress/' + address))
def predictor(self, (i, j, A, alpha, Bb)): "Add to chart any rules for B that could help extend this edge." B = Bb[0] if B in self.grammar.rules: for rhs in self.grammar.rewrites_for(B): self.add_edge([j, j, B, [], rhs])
Add to chart any rules for B that could help extend this edge.
Below is the the instruction that describes the task: ### Input: Add to chart any rules for B that could help extend this edge. ### Response: def predictor(self, (i, j, A, alpha, Bb)): "Add to chart any rules for B that could help extend this edge." B = Bb[0] if B in self.grammar.rules: for rhs in self.grammar.rewrites_for(B): self.add_edge([j, j, B, [], rhs])
def has(selfie, self, args, kwargs): """This is called 'has' but is called indirectly. Each Property sub-class is installed with this function which replaces their __new__. It is called 'has', because it runs during property declaration, processes the arguments and is responsible for returning an appropriate Property subclass. As such it is identical to the 'has' function in Perl's Moose. The API does not use the word, but the semantics are the same. It is responsible for picking which sub-class of 'self' to invoke. Unlike Moose, it will not dynamically create property types; if a type does not exist it will be a hard error. This function should *only* be concerned with picking the appropriate object type, because unlike in Perl, python cannot re-bless objects from one class to another. """ if args: raise exc.PositionalArgumentsProhibited() extra_traits = set(kwargs.pop('traits', tuple())) safe_unless_ro = self.__safe_unless_ro__ or any( x in kwargs for x in ("required", "isa", "check") ) # detect initializer arguments only supported by a subclass and add # them to extra_traits for argname in kwargs: if argname not in self.all_duckwargs: # initializer does not support this arg. Do any subclasses? implies_traits = set() for traits, proptype in DUCKWARGS[argname]: if isinstance(proptype, type(self)): implies_traits.add(traits) if proptype.__safe_unless_ro__: safe_unless_ro = True if len(implies_traits) > 1: raise exc.AmbiguousPropertyTraitArg( trait_arg=argname, could_be=" ".join( sorted(x.__name__ for x in implies_traits) ), matched_traits=implies_traits, ) elif not implies_traits: raise exc.PropertyArgumentNotKnown( badkwarg=argname, badkwarg_value=kwargs[argname], proptypename=self.__name__, proptype=self, ) else: extra_traits.update(list(implies_traits)[0]) all_traits = set(self.traits) | extra_traits if "unsafe" in all_traits and "safe" not in all_traits: all_traits.remove("unsafe") elif "ro" not in all_traits and safe_unless_ro: all_traits.add("safe") if "v1" not in all_traits: if 'default' in kwargs and looks_like_v1_none(kwargs['default']): all_traits.add("v1") if 'safe' not in all_traits: all_traits.add("safe") trait_set_key = tuple(sorted(all_traits)) if trait_set_key not in PROPERTY_TYPES: create_property_type_from_traits(trait_set_key) property_type = PROPERTY_TYPES[trait_set_key] if not isinstance(property_type, type(self)): raise exc.PropertyTypeMismatch( selected=type(property_type).__name__, base=type(self).__name__, ) return super(selfie, self).__new__(property_type)
This is called 'has' but is called indirectly. Each Property sub-class is installed with this function which replaces their __new__. It is called 'has', because it runs during property declaration, processes the arguments and is responsible for returning an appropriate Property subclass. As such it is identical to the 'has' function in Perl's Moose. The API does not use the word, but the semantics are the same. It is responsible for picking which sub-class of 'self' to invoke. Unlike Moose, it will not dynamically create property types; if a type does not exist it will be a hard error. This function should *only* be concerned with picking the appropriate object type, because unlike in Perl, python cannot re-bless objects from one class to another.
Below is the the instruction that describes the task: ### Input: This is called 'has' but is called indirectly. Each Property sub-class is installed with this function which replaces their __new__. It is called 'has', because it runs during property declaration, processes the arguments and is responsible for returning an appropriate Property subclass. As such it is identical to the 'has' function in Perl's Moose. The API does not use the word, but the semantics are the same. It is responsible for picking which sub-class of 'self' to invoke. Unlike Moose, it will not dynamically create property types; if a type does not exist it will be a hard error. This function should *only* be concerned with picking the appropriate object type, because unlike in Perl, python cannot re-bless objects from one class to another. ### Response: def has(selfie, self, args, kwargs): """This is called 'has' but is called indirectly. Each Property sub-class is installed with this function which replaces their __new__. It is called 'has', because it runs during property declaration, processes the arguments and is responsible for returning an appropriate Property subclass. As such it is identical to the 'has' function in Perl's Moose. The API does not use the word, but the semantics are the same. It is responsible for picking which sub-class of 'self' to invoke. Unlike Moose, it will not dynamically create property types; if a type does not exist it will be a hard error. This function should *only* be concerned with picking the appropriate object type, because unlike in Perl, python cannot re-bless objects from one class to another. """ if args: raise exc.PositionalArgumentsProhibited() extra_traits = set(kwargs.pop('traits', tuple())) safe_unless_ro = self.__safe_unless_ro__ or any( x in kwargs for x in ("required", "isa", "check") ) # detect initializer arguments only supported by a subclass and add # them to extra_traits for argname in kwargs: if argname not in self.all_duckwargs: # initializer does not support this arg. Do any subclasses? implies_traits = set() for traits, proptype in DUCKWARGS[argname]: if isinstance(proptype, type(self)): implies_traits.add(traits) if proptype.__safe_unless_ro__: safe_unless_ro = True if len(implies_traits) > 1: raise exc.AmbiguousPropertyTraitArg( trait_arg=argname, could_be=" ".join( sorted(x.__name__ for x in implies_traits) ), matched_traits=implies_traits, ) elif not implies_traits: raise exc.PropertyArgumentNotKnown( badkwarg=argname, badkwarg_value=kwargs[argname], proptypename=self.__name__, proptype=self, ) else: extra_traits.update(list(implies_traits)[0]) all_traits = set(self.traits) | extra_traits if "unsafe" in all_traits and "safe" not in all_traits: all_traits.remove("unsafe") elif "ro" not in all_traits and safe_unless_ro: all_traits.add("safe") if "v1" not in all_traits: if 'default' in kwargs and looks_like_v1_none(kwargs['default']): all_traits.add("v1") if 'safe' not in all_traits: all_traits.add("safe") trait_set_key = tuple(sorted(all_traits)) if trait_set_key not in PROPERTY_TYPES: create_property_type_from_traits(trait_set_key) property_type = PROPERTY_TYPES[trait_set_key] if not isinstance(property_type, type(self)): raise exc.PropertyTypeMismatch( selected=type(property_type).__name__, base=type(self).__name__, ) return super(selfie, self).__new__(property_type)
def _set_ldp_fec_prefix_prefix(self, v, load=False): """ Setter method for ldp_fec_prefix_prefix, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_prefix_prefix (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_prefix_prefix is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ldp_fec_prefix_prefix() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ldp_fec_prefix_prefix.ldp_fec_prefix_prefix, is_container='container', presence=False, yang_name="ldp-fec-prefix-prefix", rest_name="ldp-fec-prefix-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'mpls-ldp-fec-prefix-prefix-ldp-fec-prefix-prefix-1'}}, namespace='urn:brocade.com:mgmt:brocade-mpls-operational', defining_module='brocade-mpls-operational', yang_type='container', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """ldp_fec_prefix_prefix must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=ldp_fec_prefix_prefix.ldp_fec_prefix_prefix, is_container='container', presence=False, yang_name="ldp-fec-prefix-prefix", rest_name="ldp-fec-prefix-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'mpls-ldp-fec-prefix-prefix-ldp-fec-prefix-prefix-1'}}, namespace='urn:brocade.com:mgmt:brocade-mpls-operational', defining_module='brocade-mpls-operational', yang_type='container', is_config=False)""", }) self.__ldp_fec_prefix_prefix = t if hasattr(self, '_set'): self._set()
Setter method for ldp_fec_prefix_prefix, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_prefix_prefix (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_prefix_prefix is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ldp_fec_prefix_prefix() directly.
Below is the the instruction that describes the task: ### Input: Setter method for ldp_fec_prefix_prefix, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_prefix_prefix (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_prefix_prefix is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ldp_fec_prefix_prefix() directly. ### Response: def _set_ldp_fec_prefix_prefix(self, v, load=False): """ Setter method for ldp_fec_prefix_prefix, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_prefix_prefix (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_prefix_prefix is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ldp_fec_prefix_prefix() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ldp_fec_prefix_prefix.ldp_fec_prefix_prefix, is_container='container', presence=False, yang_name="ldp-fec-prefix-prefix", rest_name="ldp-fec-prefix-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'mpls-ldp-fec-prefix-prefix-ldp-fec-prefix-prefix-1'}}, namespace='urn:brocade.com:mgmt:brocade-mpls-operational', defining_module='brocade-mpls-operational', yang_type='container', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """ldp_fec_prefix_prefix must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=ldp_fec_prefix_prefix.ldp_fec_prefix_prefix, is_container='container', presence=False, yang_name="ldp-fec-prefix-prefix", rest_name="ldp-fec-prefix-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'mpls-ldp-fec-prefix-prefix-ldp-fec-prefix-prefix-1'}}, namespace='urn:brocade.com:mgmt:brocade-mpls-operational', defining_module='brocade-mpls-operational', yang_type='container', is_config=False)""", }) self.__ldp_fec_prefix_prefix = t if hasattr(self, '_set'): self._set()
def remaining_time(self): """ estimates the time remaining until script is finished """ elapsed_time = (datetime.datetime.now() - self.start_time).total_seconds() # safety to avoid devision by zero if self.progress == 0: self.progress = 1 estimated_total_time = 100. / self.progress * elapsed_time return datetime.timedelta(seconds = max(estimated_total_time - elapsed_time, 0))
estimates the time remaining until script is finished
Below is the the instruction that describes the task: ### Input: estimates the time remaining until script is finished ### Response: def remaining_time(self): """ estimates the time remaining until script is finished """ elapsed_time = (datetime.datetime.now() - self.start_time).total_seconds() # safety to avoid devision by zero if self.progress == 0: self.progress = 1 estimated_total_time = 100. / self.progress * elapsed_time return datetime.timedelta(seconds = max(estimated_total_time - elapsed_time, 0))
def run(self): """Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None`` """ target = getattr(self, '_Thread__target', getattr(self, '_target', None)) args = getattr(self, '_Thread__args', getattr(self, '_args', None)) kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None)) if target is not None: self._return = target(*args, **kwargs) return None
Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None``
Below is the the instruction that describes the task: ### Input: Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None`` ### Response: def run(self): """Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None`` """ target = getattr(self, '_Thread__target', getattr(self, '_target', None)) args = getattr(self, '_Thread__args', getattr(self, '_args', None)) kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None)) if target is not None: self._return = target(*args, **kwargs) return None
def unpack_bitstring(length, is_float, is_signed, bits): # type: (int, bool, bool, typing.Any) -> typing.Union[float, int] """ returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_signed: value is signed :return: """ if is_float: types = { 32: '>f', 64: '>d' } float_type = types[length] value, = struct.unpack(float_type, bytearray(int(''.join(b), 2) for b in grouper(bits, 8))) else: value = int(bits, 2) if is_signed and bits[0] == '1': value -= (1 << len(bits)) return value
returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_signed: value is signed :return:
Below is the the instruction that describes the task: ### Input: returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_signed: value is signed :return: ### Response: def unpack_bitstring(length, is_float, is_signed, bits): # type: (int, bool, bool, typing.Any) -> typing.Union[float, int] """ returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_signed: value is signed :return: """ if is_float: types = { 32: '>f', 64: '>d' } float_type = types[length] value, = struct.unpack(float_type, bytearray(int(''.join(b), 2) for b in grouper(bits, 8))) else: value = int(bits, 2) if is_signed and bits[0] == '1': value -= (1 << len(bits)) return value
def enc(self, byts, asscd=None): ''' Encrypt the given bytes and return an envelope dict in msgpack form. Args: byts (bytes): The message to be encrypted. asscd (bytes): Extra data that needs to be authenticated (but not encrypted). Returns: bytes: The encrypted message. This is a msgpacked dictionary containing the IV, ciphertext, and associated data. ''' iv = os.urandom(16) encryptor = AESGCM(self.ekey) byts = encryptor.encrypt(iv, byts, asscd) envl = {'iv': iv, 'data': byts, 'asscd': asscd} return s_msgpack.en(envl)
Encrypt the given bytes and return an envelope dict in msgpack form. Args: byts (bytes): The message to be encrypted. asscd (bytes): Extra data that needs to be authenticated (but not encrypted). Returns: bytes: The encrypted message. This is a msgpacked dictionary containing the IV, ciphertext, and associated data.
Below is the the instruction that describes the task: ### Input: Encrypt the given bytes and return an envelope dict in msgpack form. Args: byts (bytes): The message to be encrypted. asscd (bytes): Extra data that needs to be authenticated (but not encrypted). Returns: bytes: The encrypted message. This is a msgpacked dictionary containing the IV, ciphertext, and associated data. ### Response: def enc(self, byts, asscd=None): ''' Encrypt the given bytes and return an envelope dict in msgpack form. Args: byts (bytes): The message to be encrypted. asscd (bytes): Extra data that needs to be authenticated (but not encrypted). Returns: bytes: The encrypted message. This is a msgpacked dictionary containing the IV, ciphertext, and associated data. ''' iv = os.urandom(16) encryptor = AESGCM(self.ekey) byts = encryptor.encrypt(iv, byts, asscd) envl = {'iv': iv, 'data': byts, 'asscd': asscd} return s_msgpack.en(envl)
def getFilesForName(name): """Get a list of module files for a filename, a module or package name, or a directory. """ if not os.path.exists(name): # check for glob chars if containsAny(name, "*?[]"): files = glob.glob(name) list = [] for file in files: list.extend(getFilesForName(file)) return list # try to find module or package name = _get_modpkg_path(name) if not name: return [] if os.path.isdir(name): # find all python files in directory list = [] os.path.walk(name, _visit_pyfiles, list) return list elif os.path.exists(name): # a single file return [name] return []
Get a list of module files for a filename, a module or package name, or a directory.
Below is the the instruction that describes the task: ### Input: Get a list of module files for a filename, a module or package name, or a directory. ### Response: def getFilesForName(name): """Get a list of module files for a filename, a module or package name, or a directory. """ if not os.path.exists(name): # check for glob chars if containsAny(name, "*?[]"): files = glob.glob(name) list = [] for file in files: list.extend(getFilesForName(file)) return list # try to find module or package name = _get_modpkg_path(name) if not name: return [] if os.path.isdir(name): # find all python files in directory list = [] os.path.walk(name, _visit_pyfiles, list) return list elif os.path.exists(name): # a single file return [name] return []
def worker_thread(self): """ The primary worker thread--this thread pulls from the monitor queue and runs the monitor, submitting the results to the handler queue. Calls a sub method based on type of monitor. """ self.thread_debug("Starting monitor thread") while not self.thread_stopper.is_set(): mon = self.workers_queue.get() self.thread_debug("Processing {type} Monitor: {title}".format(**mon)) result = getattr(self, "_worker_" + mon['type'])(mon) self.workers_queue.task_done() self.results_queue.put({'type':mon['type'], 'result':result})
The primary worker thread--this thread pulls from the monitor queue and runs the monitor, submitting the results to the handler queue. Calls a sub method based on type of monitor.
Below is the the instruction that describes the task: ### Input: The primary worker thread--this thread pulls from the monitor queue and runs the monitor, submitting the results to the handler queue. Calls a sub method based on type of monitor. ### Response: def worker_thread(self): """ The primary worker thread--this thread pulls from the monitor queue and runs the monitor, submitting the results to the handler queue. Calls a sub method based on type of monitor. """ self.thread_debug("Starting monitor thread") while not self.thread_stopper.is_set(): mon = self.workers_queue.get() self.thread_debug("Processing {type} Monitor: {title}".format(**mon)) result = getattr(self, "_worker_" + mon['type'])(mon) self.workers_queue.task_done() self.results_queue.put({'type':mon['type'], 'result':result})
def render(self, **kwargs): """Renders the HTML representation of the element.""" self.json = json.dumps(self.data) self._parent.html.add_child(Element(Template(""" <div id="{{this.get_name()}}"></div> """).render(this=self, kwargs=kwargs)), name=self.get_name()) self._parent.script.add_child(Element(Template(""" vega_parse({{this.json}},{{this.get_name()}}); """).render(this=self)), name=self.get_name()) figure = self.get_root() assert isinstance(figure, Figure), ('You cannot render this Element ' 'if it is not in a Figure.') figure.header.add_child(Element(Template(""" <style> #{{this.get_name()}} { position : {{this.position}}; width : {{this.width[0]}}{{this.width[1]}}; height: {{this.height[0]}}{{this.height[1]}}; left: {{this.left[0]}}{{this.left[1]}}; top: {{this.top[0]}}{{this.top[1]}}; </style> """).render(this=self, **kwargs)), name=self.get_name()) figure.header.add_child( JavascriptLink('https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js'), # noqa name='d3') figure.header.add_child( JavascriptLink('https://cdnjs.cloudflare.com/ajax/libs/vega/1.4.3/vega.min.js'), # noqa name='vega') figure.header.add_child( JavascriptLink('https://code.jquery.com/jquery-2.1.0.min.js'), name='jquery') figure.script.add_child( Template("""function vega_parse(spec, div) { vg.parse.spec(spec, function(chart) { chart({el:div}).update(); });}"""), # noqa name='vega_parse')
Renders the HTML representation of the element.
Below is the the instruction that describes the task: ### Input: Renders the HTML representation of the element. ### Response: def render(self, **kwargs): """Renders the HTML representation of the element.""" self.json = json.dumps(self.data) self._parent.html.add_child(Element(Template(""" <div id="{{this.get_name()}}"></div> """).render(this=self, kwargs=kwargs)), name=self.get_name()) self._parent.script.add_child(Element(Template(""" vega_parse({{this.json}},{{this.get_name()}}); """).render(this=self)), name=self.get_name()) figure = self.get_root() assert isinstance(figure, Figure), ('You cannot render this Element ' 'if it is not in a Figure.') figure.header.add_child(Element(Template(""" <style> #{{this.get_name()}} { position : {{this.position}}; width : {{this.width[0]}}{{this.width[1]}}; height: {{this.height[0]}}{{this.height[1]}}; left: {{this.left[0]}}{{this.left[1]}}; top: {{this.top[0]}}{{this.top[1]}}; </style> """).render(this=self, **kwargs)), name=self.get_name()) figure.header.add_child( JavascriptLink('https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js'), # noqa name='d3') figure.header.add_child( JavascriptLink('https://cdnjs.cloudflare.com/ajax/libs/vega/1.4.3/vega.min.js'), # noqa name='vega') figure.header.add_child( JavascriptLink('https://code.jquery.com/jquery-2.1.0.min.js'), name='jquery') figure.script.add_child( Template("""function vega_parse(spec, div) { vg.parse.spec(spec, function(chart) { chart({el:div}).update(); });}"""), # noqa name='vega_parse')
def _matches_filters(self, obj, filter_args): """ Return a boolean indicating whether a resource object matches a set of filter arguments. This is used for client-side filtering. Depending on the properties specified in the filter arguments, this method retrieves the resource properties from the HMC. Parameters: obj (BaseResource): Resource object. filter_args (dict): Filter arguments. For details, see :ref:`Filtering`. `None` causes the resource to always match. Returns: bool: Boolean indicating whether the resource object matches the filter arguments. """ if filter_args is not None: for prop_name in filter_args: prop_match = filter_args[prop_name] if not self._matches_prop(obj, prop_name, prop_match): return False return True
Return a boolean indicating whether a resource object matches a set of filter arguments. This is used for client-side filtering. Depending on the properties specified in the filter arguments, this method retrieves the resource properties from the HMC. Parameters: obj (BaseResource): Resource object. filter_args (dict): Filter arguments. For details, see :ref:`Filtering`. `None` causes the resource to always match. Returns: bool: Boolean indicating whether the resource object matches the filter arguments.
Below is the the instruction that describes the task: ### Input: Return a boolean indicating whether a resource object matches a set of filter arguments. This is used for client-side filtering. Depending on the properties specified in the filter arguments, this method retrieves the resource properties from the HMC. Parameters: obj (BaseResource): Resource object. filter_args (dict): Filter arguments. For details, see :ref:`Filtering`. `None` causes the resource to always match. Returns: bool: Boolean indicating whether the resource object matches the filter arguments. ### Response: def _matches_filters(self, obj, filter_args): """ Return a boolean indicating whether a resource object matches a set of filter arguments. This is used for client-side filtering. Depending on the properties specified in the filter arguments, this method retrieves the resource properties from the HMC. Parameters: obj (BaseResource): Resource object. filter_args (dict): Filter arguments. For details, see :ref:`Filtering`. `None` causes the resource to always match. Returns: bool: Boolean indicating whether the resource object matches the filter arguments. """ if filter_args is not None: for prop_name in filter_args: prop_match = filter_args[prop_name] if not self._matches_prop(obj, prop_name, prop_match): return False return True
def handle(self, block, handler_name, request, suffix=''): """ Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available """ handler = getattr(block, handler_name, None) if handler and getattr(handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = handler(request, suffix) else: fallback_handler = getattr(block, "fallback_handler", None) if fallback_handler and getattr(fallback_handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = fallback_handler(handler_name, request, suffix) else: raise NoSuchHandlerError("Couldn't find handler %r for %r" % (handler_name, block)) # Write out dirty fields block.save() return results
Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available
Below is the the instruction that describes the task: ### Input: Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available ### Response: def handle(self, block, handler_name, request, suffix=''): """ Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available """ handler = getattr(block, handler_name, None) if handler and getattr(handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = handler(request, suffix) else: fallback_handler = getattr(block, "fallback_handler", None) if fallback_handler and getattr(fallback_handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = fallback_handler(handler_name, request, suffix) else: raise NoSuchHandlerError("Couldn't find handler %r for %r" % (handler_name, block)) # Write out dirty fields block.save() return results
def estimate_K_knee(self, th=.015, maxK=12): """Estimates the K using K-means and BIC, by sweeping various K and choosing the optimal BIC.""" # Sweep K-means if self.X.shape[0] < maxK: maxK = self.X.shape[0] if maxK < 2: maxK = 2 K = np.arange(1, maxK) bics = [] for k in K: means, labels = self.run_kmeans(self.X, k) bic = self.compute_bic(self.X, means, labels, K=k, R=self.X.shape[0]) bics.append(bic) diff_bics = np.diff(bics) finalK = K[-1] if len(bics) == 1: finalK = 2 else: # Normalize bics = np.asarray(bics) bics -= bics.min() #bics /= bics.max() diff_bics -= diff_bics.min() #diff_bics /= diff_bics.max() #print bics, diff_bics # Find optimum K for i in range(len(K[:-1])): #if bics[i] > diff_bics[i]: if diff_bics[i] < th and K[i] != 1: finalK = K[i] break #print "Estimated K: ", finalK if self.plot: plt.subplot(2, 1, 1) plt.plot(K, bics, label="BIC") plt.plot(K[:-1], diff_bics, label="BIC diff") plt.legend(loc=2) plt.subplot(2, 1, 2) plt.scatter(self.X[:, 0], self.X[:, 1]) plt.show() return finalK
Estimates the K using K-means and BIC, by sweeping various K and choosing the optimal BIC.
Below is the the instruction that describes the task: ### Input: Estimates the K using K-means and BIC, by sweeping various K and choosing the optimal BIC. ### Response: def estimate_K_knee(self, th=.015, maxK=12): """Estimates the K using K-means and BIC, by sweeping various K and choosing the optimal BIC.""" # Sweep K-means if self.X.shape[0] < maxK: maxK = self.X.shape[0] if maxK < 2: maxK = 2 K = np.arange(1, maxK) bics = [] for k in K: means, labels = self.run_kmeans(self.X, k) bic = self.compute_bic(self.X, means, labels, K=k, R=self.X.shape[0]) bics.append(bic) diff_bics = np.diff(bics) finalK = K[-1] if len(bics) == 1: finalK = 2 else: # Normalize bics = np.asarray(bics) bics -= bics.min() #bics /= bics.max() diff_bics -= diff_bics.min() #diff_bics /= diff_bics.max() #print bics, diff_bics # Find optimum K for i in range(len(K[:-1])): #if bics[i] > diff_bics[i]: if diff_bics[i] < th and K[i] != 1: finalK = K[i] break #print "Estimated K: ", finalK if self.plot: plt.subplot(2, 1, 1) plt.plot(K, bics, label="BIC") plt.plot(K[:-1], diff_bics, label="BIC diff") plt.legend(loc=2) plt.subplot(2, 1, 2) plt.scatter(self.X[:, 0], self.X[:, 1]) plt.show() return finalK
def multiple_replace(d: Dict[str, str], text: str) -> str: """ Performs string replacement from dict in a single pass. Taken from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html """ # Create a regular expression from all of the dictionary keys regex = re.compile("|".join(map(re.escape, d.keys()))) # For each match, look up the corresponding value in the dictionary return regex.sub(lambda match: d[match.group(0)], text)
Performs string replacement from dict in a single pass. Taken from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html
Below is the the instruction that describes the task: ### Input: Performs string replacement from dict in a single pass. Taken from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html ### Response: def multiple_replace(d: Dict[str, str], text: str) -> str: """ Performs string replacement from dict in a single pass. Taken from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html """ # Create a regular expression from all of the dictionary keys regex = re.compile("|".join(map(re.escape, d.keys()))) # For each match, look up the corresponding value in the dictionary return regex.sub(lambda match: d[match.group(0)], text)
def list(self, bank): ''' Lists entries stored in the specified bank. :param bank: The name of the location inside the cache which will hold the key and its associated data. :return: An iterable object containing all bank entries. Returns an empty iterator if the bank doesn't exists. :raises SaltCacheError: Raises an exception if cache driver detected an error accessing data in the cache backend (auth, permissions, etc). ''' fun = '{0}.list'.format(self.driver) return self.modules[fun](bank, **self._kwargs)
Lists entries stored in the specified bank. :param bank: The name of the location inside the cache which will hold the key and its associated data. :return: An iterable object containing all bank entries. Returns an empty iterator if the bank doesn't exists. :raises SaltCacheError: Raises an exception if cache driver detected an error accessing data in the cache backend (auth, permissions, etc).
Below is the the instruction that describes the task: ### Input: Lists entries stored in the specified bank. :param bank: The name of the location inside the cache which will hold the key and its associated data. :return: An iterable object containing all bank entries. Returns an empty iterator if the bank doesn't exists. :raises SaltCacheError: Raises an exception if cache driver detected an error accessing data in the cache backend (auth, permissions, etc). ### Response: def list(self, bank): ''' Lists entries stored in the specified bank. :param bank: The name of the location inside the cache which will hold the key and its associated data. :return: An iterable object containing all bank entries. Returns an empty iterator if the bank doesn't exists. :raises SaltCacheError: Raises an exception if cache driver detected an error accessing data in the cache backend (auth, permissions, etc). ''' fun = '{0}.list'.format(self.driver) return self.modules[fun](bank, **self._kwargs)
def set_content(self, data): """ handle the content from the data :param data: contains the data from the provider :type data: dict :rtype: string """ content = self._get_content(data, 'content') if content == '': content = self._get_content(data, 'summary_detail') if content == '': if data.get('description'): content = data.get('description') return content
handle the content from the data :param data: contains the data from the provider :type data: dict :rtype: string
Below is the the instruction that describes the task: ### Input: handle the content from the data :param data: contains the data from the provider :type data: dict :rtype: string ### Response: def set_content(self, data): """ handle the content from the data :param data: contains the data from the provider :type data: dict :rtype: string """ content = self._get_content(data, 'content') if content == '': content = self._get_content(data, 'summary_detail') if content == '': if data.get('description'): content = data.get('description') return content
def validate_options(self, k, v): """Validate options.""" super().validate_options(k, v) if k == 'charset_size': if v not in (1, 2, 4): raise ValueError("{}: '{}' is an unsupported charset size".format(self.__class__.__name__, v)) elif k == 'wide_charset_size': if v not in (2, 4): raise ValueError("{}: '{}' is an unsupported wide charset size".format(self.__class__.__name__, v)) elif k in ('exec_charset', 'wide_exec_charset'): # See if parsing fails. self.get_encoding_name(v) elif k == 'string_types': if RE_VALID_STRING_TYPES.match(v) is None: raise ValueError("{}: '{}' does not define valid string types".format(self.__class__.__name__, v))
Validate options.
Below is the the instruction that describes the task: ### Input: Validate options. ### Response: def validate_options(self, k, v): """Validate options.""" super().validate_options(k, v) if k == 'charset_size': if v not in (1, 2, 4): raise ValueError("{}: '{}' is an unsupported charset size".format(self.__class__.__name__, v)) elif k == 'wide_charset_size': if v not in (2, 4): raise ValueError("{}: '{}' is an unsupported wide charset size".format(self.__class__.__name__, v)) elif k in ('exec_charset', 'wide_exec_charset'): # See if parsing fails. self.get_encoding_name(v) elif k == 'string_types': if RE_VALID_STRING_TYPES.match(v) is None: raise ValueError("{}: '{}' does not define valid string types".format(self.__class__.__name__, v))
def waitForOSState(rh, userid, desiredState, maxQueries=90, sleepSecs=5): """ Wait for the virtual OS to go into the indicated state. Input: Request Handle userid whose state is to be monitored Desired state, 'up' or 'down', case sensitive Maximum attempts to wait for desired state before giving up Sleep duration between waits Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure rc - RC returned from execCmdThruIUCV if overallRC = 0. rs - RS returned from execCmdThruIUCV if overallRC = 0. errno - Errno returned from execCmdThruIUCV if overallRC = 0. response - Updated with an error message if wait times out. Note: """ rh.printSysLog("Enter vmUtils.waitForOSState, userid: " + userid + " state: " + desiredState + " maxWait: " + str(maxQueries) + " sleepSecs: " + str(sleepSecs)) results = {} strCmd = "echo 'ping'" stateFnd = False for i in range(1, maxQueries + 1): results = execCmdThruIUCV(rh, rh.userid, strCmd) if results['overallRC'] == 0: if desiredState == 'up': stateFnd = True break else: if desiredState == 'down': stateFnd = True break if i < maxQueries: time.sleep(sleepSecs) if stateFnd is True: results = { 'overallRC': 0, 'rc': 0, 'rs': 0, } else: maxWait = maxQueries * sleepSecs rh.printLn("ES", msgs.msg['0413'][1] % (modId, userid, desiredState, maxWait)) results = msgs.msg['0413'][0] rh.printSysLog("Exit vmUtils.waitForOSState, rc: " + str(results['overallRC'])) return results
Wait for the virtual OS to go into the indicated state. Input: Request Handle userid whose state is to be monitored Desired state, 'up' or 'down', case sensitive Maximum attempts to wait for desired state before giving up Sleep duration between waits Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure rc - RC returned from execCmdThruIUCV if overallRC = 0. rs - RS returned from execCmdThruIUCV if overallRC = 0. errno - Errno returned from execCmdThruIUCV if overallRC = 0. response - Updated with an error message if wait times out. Note:
Below is the the instruction that describes the task: ### Input: Wait for the virtual OS to go into the indicated state. Input: Request Handle userid whose state is to be monitored Desired state, 'up' or 'down', case sensitive Maximum attempts to wait for desired state before giving up Sleep duration between waits Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure rc - RC returned from execCmdThruIUCV if overallRC = 0. rs - RS returned from execCmdThruIUCV if overallRC = 0. errno - Errno returned from execCmdThruIUCV if overallRC = 0. response - Updated with an error message if wait times out. Note: ### Response: def waitForOSState(rh, userid, desiredState, maxQueries=90, sleepSecs=5): """ Wait for the virtual OS to go into the indicated state. Input: Request Handle userid whose state is to be monitored Desired state, 'up' or 'down', case sensitive Maximum attempts to wait for desired state before giving up Sleep duration between waits Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure rc - RC returned from execCmdThruIUCV if overallRC = 0. rs - RS returned from execCmdThruIUCV if overallRC = 0. errno - Errno returned from execCmdThruIUCV if overallRC = 0. response - Updated with an error message if wait times out. Note: """ rh.printSysLog("Enter vmUtils.waitForOSState, userid: " + userid + " state: " + desiredState + " maxWait: " + str(maxQueries) + " sleepSecs: " + str(sleepSecs)) results = {} strCmd = "echo 'ping'" stateFnd = False for i in range(1, maxQueries + 1): results = execCmdThruIUCV(rh, rh.userid, strCmd) if results['overallRC'] == 0: if desiredState == 'up': stateFnd = True break else: if desiredState == 'down': stateFnd = True break if i < maxQueries: time.sleep(sleepSecs) if stateFnd is True: results = { 'overallRC': 0, 'rc': 0, 'rs': 0, } else: maxWait = maxQueries * sleepSecs rh.printLn("ES", msgs.msg['0413'][1] % (modId, userid, desiredState, maxWait)) results = msgs.msg['0413'][0] rh.printSysLog("Exit vmUtils.waitForOSState, rc: " + str(results['overallRC'])) return results
def search(self): """Return list of cells to be removed.""" matches = [] for index, cell in enumerate(self.cells): for pattern in Config.patterns: if ismatch(cell, pattern): matches.append(index) break return matches
Return list of cells to be removed.
Below is the the instruction that describes the task: ### Input: Return list of cells to be removed. ### Response: def search(self): """Return list of cells to be removed.""" matches = [] for index, cell in enumerate(self.cells): for pattern in Config.patterns: if ismatch(cell, pattern): matches.append(index) break return matches
def check_slice_perms(self, slice_id): """ Check if user can access a cached response from slice_json. This function takes `self` since it must have the same signature as the the decorated method. """ form_data, slc = get_form_data(slice_id, use_slice_data=True) datasource_type = slc.datasource.type datasource_id = slc.datasource.id viz_obj = get_viz( datasource_type=datasource_type, datasource_id=datasource_id, form_data=form_data, force=False, ) security_manager.assert_datasource_permission(viz_obj.datasource)
Check if user can access a cached response from slice_json. This function takes `self` since it must have the same signature as the the decorated method.
Below is the the instruction that describes the task: ### Input: Check if user can access a cached response from slice_json. This function takes `self` since it must have the same signature as the the decorated method. ### Response: def check_slice_perms(self, slice_id): """ Check if user can access a cached response from slice_json. This function takes `self` since it must have the same signature as the the decorated method. """ form_data, slc = get_form_data(slice_id, use_slice_data=True) datasource_type = slc.datasource.type datasource_id = slc.datasource.id viz_obj = get_viz( datasource_type=datasource_type, datasource_id=datasource_id, form_data=form_data, force=False, ) security_manager.assert_datasource_permission(viz_obj.datasource)
def determine_metadata(self, request, view): """Adds `properties` and `features` to the metadata response.""" metadata = super( DynamicMetadata, self).determine_metadata( request, view) metadata['features'] = getattr(view, 'features', []) if hasattr(view, 'get_serializer'): serializer = view.get_serializer(dynamic=False) if hasattr(serializer, 'get_name'): metadata['resource_name'] = serializer.get_name() if hasattr(serializer, 'get_plural_name'): metadata['resource_name_plural'] = serializer.get_plural_name() metadata['properties'] = self.get_serializer_info(serializer) return metadata
Adds `properties` and `features` to the metadata response.
Below is the the instruction that describes the task: ### Input: Adds `properties` and `features` to the metadata response. ### Response: def determine_metadata(self, request, view): """Adds `properties` and `features` to the metadata response.""" metadata = super( DynamicMetadata, self).determine_metadata( request, view) metadata['features'] = getattr(view, 'features', []) if hasattr(view, 'get_serializer'): serializer = view.get_serializer(dynamic=False) if hasattr(serializer, 'get_name'): metadata['resource_name'] = serializer.get_name() if hasattr(serializer, 'get_plural_name'): metadata['resource_name_plural'] = serializer.get_plural_name() metadata['properties'] = self.get_serializer_info(serializer) return metadata
def filename_command(): """ Executor for `globus config filename` """ try: config = get_config_obj(file_error=True) except IOError as e: safeprint(e, write_to_stderr=True) click.get_current_context().exit(1) else: safeprint(config.filename)
Executor for `globus config filename`
Below is the the instruction that describes the task: ### Input: Executor for `globus config filename` ### Response: def filename_command(): """ Executor for `globus config filename` """ try: config = get_config_obj(file_error=True) except IOError as e: safeprint(e, write_to_stderr=True) click.get_current_context().exit(1) else: safeprint(config.filename)
def actor(fn=None, *, actor_class=Actor, actor_name=None, queue_name="default", priority=0, broker=None, **options): """Declare an actor. Examples: >>> import dramatiq >>> @dramatiq.actor ... def add(x, y): ... print(x + y) ... >>> add Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add') >>> add(1, 2) 3 >>> add.send(1, 2) Message( queue_name='default', actor_name='add', args=(1, 2), kwargs={}, options={}, message_id='e0d27b45-7900-41da-bb97-553b8a081206', message_timestamp=1497862448685) Parameters: fn(callable): The function to wrap. actor_class(type): Type created by the decorator. Defaults to :class:`Actor` but can be any callable as long as it returns an actor and takes the same arguments as the :class:`Actor` class. actor_name(str): The name of the actor. queue_name(str): The name of the queue to use. priority(int): The actor's global priority. If two tasks have been pulled on a worker concurrently and one has a higher priority than the other then it will be processed first. Lower numbers represent higher priorities. broker(Broker): The broker to use with this actor. **options(dict): Arbitrary options that vary with the set of middleware that you use. See ``get_broker().actor_options``. Returns: Actor: The decorated function. """ def decorator(fn): nonlocal actor_name, broker actor_name = actor_name or fn.__name__ if not _queue_name_re.fullmatch(queue_name): raise ValueError( "Queue names must start with a letter or an underscore followed " "by any number of letters, digits, dashes or underscores." ) broker = broker or get_broker() invalid_options = set(options) - broker.actor_options if invalid_options: invalid_options_list = ", ".join(invalid_options) raise ValueError(( "The following actor options are undefined: %s. " "Did you forget to add a middleware to your Broker?" ) % invalid_options_list) return actor_class( fn, actor_name=actor_name, queue_name=queue_name, priority=priority, broker=broker, options=options, ) if fn is None: return decorator return decorator(fn)
Declare an actor. Examples: >>> import dramatiq >>> @dramatiq.actor ... def add(x, y): ... print(x + y) ... >>> add Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add') >>> add(1, 2) 3 >>> add.send(1, 2) Message( queue_name='default', actor_name='add', args=(1, 2), kwargs={}, options={}, message_id='e0d27b45-7900-41da-bb97-553b8a081206', message_timestamp=1497862448685) Parameters: fn(callable): The function to wrap. actor_class(type): Type created by the decorator. Defaults to :class:`Actor` but can be any callable as long as it returns an actor and takes the same arguments as the :class:`Actor` class. actor_name(str): The name of the actor. queue_name(str): The name of the queue to use. priority(int): The actor's global priority. If two tasks have been pulled on a worker concurrently and one has a higher priority than the other then it will be processed first. Lower numbers represent higher priorities. broker(Broker): The broker to use with this actor. **options(dict): Arbitrary options that vary with the set of middleware that you use. See ``get_broker().actor_options``. Returns: Actor: The decorated function.
Below is the the instruction that describes the task: ### Input: Declare an actor. Examples: >>> import dramatiq >>> @dramatiq.actor ... def add(x, y): ... print(x + y) ... >>> add Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add') >>> add(1, 2) 3 >>> add.send(1, 2) Message( queue_name='default', actor_name='add', args=(1, 2), kwargs={}, options={}, message_id='e0d27b45-7900-41da-bb97-553b8a081206', message_timestamp=1497862448685) Parameters: fn(callable): The function to wrap. actor_class(type): Type created by the decorator. Defaults to :class:`Actor` but can be any callable as long as it returns an actor and takes the same arguments as the :class:`Actor` class. actor_name(str): The name of the actor. queue_name(str): The name of the queue to use. priority(int): The actor's global priority. If two tasks have been pulled on a worker concurrently and one has a higher priority than the other then it will be processed first. Lower numbers represent higher priorities. broker(Broker): The broker to use with this actor. **options(dict): Arbitrary options that vary with the set of middleware that you use. See ``get_broker().actor_options``. Returns: Actor: The decorated function. ### Response: def actor(fn=None, *, actor_class=Actor, actor_name=None, queue_name="default", priority=0, broker=None, **options): """Declare an actor. Examples: >>> import dramatiq >>> @dramatiq.actor ... def add(x, y): ... print(x + y) ... >>> add Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add') >>> add(1, 2) 3 >>> add.send(1, 2) Message( queue_name='default', actor_name='add', args=(1, 2), kwargs={}, options={}, message_id='e0d27b45-7900-41da-bb97-553b8a081206', message_timestamp=1497862448685) Parameters: fn(callable): The function to wrap. actor_class(type): Type created by the decorator. Defaults to :class:`Actor` but can be any callable as long as it returns an actor and takes the same arguments as the :class:`Actor` class. actor_name(str): The name of the actor. queue_name(str): The name of the queue to use. priority(int): The actor's global priority. If two tasks have been pulled on a worker concurrently and one has a higher priority than the other then it will be processed first. Lower numbers represent higher priorities. broker(Broker): The broker to use with this actor. **options(dict): Arbitrary options that vary with the set of middleware that you use. See ``get_broker().actor_options``. Returns: Actor: The decorated function. """ def decorator(fn): nonlocal actor_name, broker actor_name = actor_name or fn.__name__ if not _queue_name_re.fullmatch(queue_name): raise ValueError( "Queue names must start with a letter or an underscore followed " "by any number of letters, digits, dashes or underscores." ) broker = broker or get_broker() invalid_options = set(options) - broker.actor_options if invalid_options: invalid_options_list = ", ".join(invalid_options) raise ValueError(( "The following actor options are undefined: %s. " "Did you forget to add a middleware to your Broker?" ) % invalid_options_list) return actor_class( fn, actor_name=actor_name, queue_name=queue_name, priority=priority, broker=broker, options=options, ) if fn is None: return decorator return decorator(fn)
def _list_images(self, root): """ Description : generate list for lip images """ self.labels = [] self.items = [] valid_unseen_sub_idx = [1, 2, 20, 22] skip_sub_idx = [21] if self._mode == 'train': sub_idx = ['s' + str(i) for i in range(1, 35) \ if i not in valid_unseen_sub_idx + skip_sub_idx] elif self._mode == 'valid': sub_idx = ['s' + str(i) for i in valid_unseen_sub_idx] folder_path = [] for i in sub_idx: folder_path.extend(glob.glob(os.path.join(root, i, "*"))) for folder in folder_path: filename = glob.glob(os.path.join(folder, "*")) if len(filename) != self._seq_len: continue filename.sort() label = os.path.split(folder)[-1] self.items.append((filename, label))
Description : generate list for lip images
Below is the the instruction that describes the task: ### Input: Description : generate list for lip images ### Response: def _list_images(self, root): """ Description : generate list for lip images """ self.labels = [] self.items = [] valid_unseen_sub_idx = [1, 2, 20, 22] skip_sub_idx = [21] if self._mode == 'train': sub_idx = ['s' + str(i) for i in range(1, 35) \ if i not in valid_unseen_sub_idx + skip_sub_idx] elif self._mode == 'valid': sub_idx = ['s' + str(i) for i in valid_unseen_sub_idx] folder_path = [] for i in sub_idx: folder_path.extend(glob.glob(os.path.join(root, i, "*"))) for folder in folder_path: filename = glob.glob(os.path.join(folder, "*")) if len(filename) != self._seq_len: continue filename.sort() label = os.path.split(folder)[-1] self.items.append((filename, label))
def joinpath(self, *args): """ Join two or more path components, adding a separator character (os.sep) if needed. Returns a new path object. """ return self.__class__(os.path.join(self, *args))
Join two or more path components, adding a separator character (os.sep) if needed. Returns a new path object.
Below is the the instruction that describes the task: ### Input: Join two or more path components, adding a separator character (os.sep) if needed. Returns a new path object. ### Response: def joinpath(self, *args): """ Join two or more path components, adding a separator character (os.sep) if needed. Returns a new path object. """ return self.__class__(os.path.join(self, *args))
def write(self, data): """Write data. Args: data: actual data yielded from handler. Type is writer-specific. """ ctx = context.get() if len(data) != 2: logging.error("Got bad tuple of length %d (2-tuple expected): %s", len(data), data) try: key = str(data[0]) value = str(data[1]) except TypeError: logging.error("Expecting a tuple, but got %s: %s", data.__class__.__name__, data) file_index = key.__hash__() % len(self._filehandles) # Work-around: Since we don't have access to the context in the to_json() # function, but we need to flush each pool before we serialize the # filehandle, we rely on a member variable instead of using context for # pool management. pool = self._pools[file_index] if pool is None: filehandle = self._filehandles[file_index] pool = output_writers.GCSRecordsPool(filehandle=filehandle, ctx=ctx) self._pools[file_index] = pool proto = kv_pb.KeyValue() proto.set_key(key) proto.set_value(value) pool.append(proto.Encode())
Write data. Args: data: actual data yielded from handler. Type is writer-specific.
Below is the the instruction that describes the task: ### Input: Write data. Args: data: actual data yielded from handler. Type is writer-specific. ### Response: def write(self, data): """Write data. Args: data: actual data yielded from handler. Type is writer-specific. """ ctx = context.get() if len(data) != 2: logging.error("Got bad tuple of length %d (2-tuple expected): %s", len(data), data) try: key = str(data[0]) value = str(data[1]) except TypeError: logging.error("Expecting a tuple, but got %s: %s", data.__class__.__name__, data) file_index = key.__hash__() % len(self._filehandles) # Work-around: Since we don't have access to the context in the to_json() # function, but we need to flush each pool before we serialize the # filehandle, we rely on a member variable instead of using context for # pool management. pool = self._pools[file_index] if pool is None: filehandle = self._filehandles[file_index] pool = output_writers.GCSRecordsPool(filehandle=filehandle, ctx=ctx) self._pools[file_index] = pool proto = kv_pb.KeyValue() proto.set_key(key) proto.set_value(value) pool.append(proto.Encode())
def ArchiveProcessedFile(filePath, archiveDir): """ Move file from given file path to archive directory. Note the archive directory is relative to the file path directory. Parameters ---------- filePath : string File path archiveDir : string Name of archive directory """ targetDir = os.path.join(os.path.dirname(filePath), archiveDir) goodlogging.Log.Info("UTIL", "Moving file to archive directory:") goodlogging.Log.IncreaseIndent() goodlogging.Log.Info("UTIL", "FROM: {0}".format(filePath)) goodlogging.Log.Info("UTIL", "TO: {0}".format(os.path.join(targetDir, os.path.basename(filePath)))) goodlogging.Log.DecreaseIndent() os.makedirs(targetDir, exist_ok=True) try: shutil.move(filePath, targetDir) except shutil.Error as ex4: err = ex4.args[0] goodlogging.Log.Info("UTIL", "Move to archive directory failed - Shutil Error: {0}".format(err))
Move file from given file path to archive directory. Note the archive directory is relative to the file path directory. Parameters ---------- filePath : string File path archiveDir : string Name of archive directory
Below is the the instruction that describes the task: ### Input: Move file from given file path to archive directory. Note the archive directory is relative to the file path directory. Parameters ---------- filePath : string File path archiveDir : string Name of archive directory ### Response: def ArchiveProcessedFile(filePath, archiveDir): """ Move file from given file path to archive directory. Note the archive directory is relative to the file path directory. Parameters ---------- filePath : string File path archiveDir : string Name of archive directory """ targetDir = os.path.join(os.path.dirname(filePath), archiveDir) goodlogging.Log.Info("UTIL", "Moving file to archive directory:") goodlogging.Log.IncreaseIndent() goodlogging.Log.Info("UTIL", "FROM: {0}".format(filePath)) goodlogging.Log.Info("UTIL", "TO: {0}".format(os.path.join(targetDir, os.path.basename(filePath)))) goodlogging.Log.DecreaseIndent() os.makedirs(targetDir, exist_ok=True) try: shutil.move(filePath, targetDir) except shutil.Error as ex4: err = ex4.args[0] goodlogging.Log.Info("UTIL", "Move to archive directory failed - Shutil Error: {0}".format(err))
def stop(self): """ Stop the monitoring thread of the plugin. The super-class will send the stop signal on the monitor-IP queue, which prompts the loop to stop. """ super(Multi, self).stop() self.monitor_thread.join() logging.info("Multi-plugin health monitor: Stopping plugins") for p in self.plugins: p.stop() logging.info("Multi-plugin health monitor: Stopped")
Stop the monitoring thread of the plugin. The super-class will send the stop signal on the monitor-IP queue, which prompts the loop to stop.
Below is the the instruction that describes the task: ### Input: Stop the monitoring thread of the plugin. The super-class will send the stop signal on the monitor-IP queue, which prompts the loop to stop. ### Response: def stop(self): """ Stop the monitoring thread of the plugin. The super-class will send the stop signal on the monitor-IP queue, which prompts the loop to stop. """ super(Multi, self).stop() self.monitor_thread.join() logging.info("Multi-plugin health monitor: Stopping plugins") for p in self.plugins: p.stop() logging.info("Multi-plugin health monitor: Stopped")
def val2dzn(val, wrap=True): """Serializes a value into its dzn representation. The supported types are ``bool``, ``int``, ``float``, ``set``, ``array``. Parameters ---------- val The value to serialize wrap : bool Whether to wrap the serialized value. Returns ------- str The serialized dzn representation of the given value. """ if _is_value(val): dzn_val = _dzn_val(val) elif _is_set(val): dzn_val = _dzn_set(val) elif _is_array_type(val): dzn_val =_dzn_array_nd(val) else: raise TypeError( 'Unsupported serialization of value: {}'.format(repr(val)) ) if wrap: wrapper = _get_wrapper() dzn_val = wrapper.fill(dzn_val) return dzn_val
Serializes a value into its dzn representation. The supported types are ``bool``, ``int``, ``float``, ``set``, ``array``. Parameters ---------- val The value to serialize wrap : bool Whether to wrap the serialized value. Returns ------- str The serialized dzn representation of the given value.
Below is the the instruction that describes the task: ### Input: Serializes a value into its dzn representation. The supported types are ``bool``, ``int``, ``float``, ``set``, ``array``. Parameters ---------- val The value to serialize wrap : bool Whether to wrap the serialized value. Returns ------- str The serialized dzn representation of the given value. ### Response: def val2dzn(val, wrap=True): """Serializes a value into its dzn representation. The supported types are ``bool``, ``int``, ``float``, ``set``, ``array``. Parameters ---------- val The value to serialize wrap : bool Whether to wrap the serialized value. Returns ------- str The serialized dzn representation of the given value. """ if _is_value(val): dzn_val = _dzn_val(val) elif _is_set(val): dzn_val = _dzn_set(val) elif _is_array_type(val): dzn_val =_dzn_array_nd(val) else: raise TypeError( 'Unsupported serialization of value: {}'.format(repr(val)) ) if wrap: wrapper = _get_wrapper() dzn_val = wrapper.fill(dzn_val) return dzn_val
def delete_by_field(self, field_name, field_value, **options): """ Deletes first record to match provided ``field_name`` and ``field_value``. >>> record = airtable.delete_by_field('Employee Id', 'DD13332454') Args: field_name (``str``): Name of field to match (column name). field_value (``str``): Value of field to match. Keyword Args: view (``str``, optional): The name or ID of a view. See :any:`ViewParam`. sort (``list``, optional): List of fields to sort by. Default order is ascending. See :any:`SortParam`. Returns: record (``dict``): Deleted Record """ record = self.match(field_name, field_value, **options) record_url = self.record_url(record['id']) return self._delete(record_url)
Deletes first record to match provided ``field_name`` and ``field_value``. >>> record = airtable.delete_by_field('Employee Id', 'DD13332454') Args: field_name (``str``): Name of field to match (column name). field_value (``str``): Value of field to match. Keyword Args: view (``str``, optional): The name or ID of a view. See :any:`ViewParam`. sort (``list``, optional): List of fields to sort by. Default order is ascending. See :any:`SortParam`. Returns: record (``dict``): Deleted Record
Below is the the instruction that describes the task: ### Input: Deletes first record to match provided ``field_name`` and ``field_value``. >>> record = airtable.delete_by_field('Employee Id', 'DD13332454') Args: field_name (``str``): Name of field to match (column name). field_value (``str``): Value of field to match. Keyword Args: view (``str``, optional): The name or ID of a view. See :any:`ViewParam`. sort (``list``, optional): List of fields to sort by. Default order is ascending. See :any:`SortParam`. Returns: record (``dict``): Deleted Record ### Response: def delete_by_field(self, field_name, field_value, **options): """ Deletes first record to match provided ``field_name`` and ``field_value``. >>> record = airtable.delete_by_field('Employee Id', 'DD13332454') Args: field_name (``str``): Name of field to match (column name). field_value (``str``): Value of field to match. Keyword Args: view (``str``, optional): The name or ID of a view. See :any:`ViewParam`. sort (``list``, optional): List of fields to sort by. Default order is ascending. See :any:`SortParam`. Returns: record (``dict``): Deleted Record """ record = self.match(field_name, field_value, **options) record_url = self.record_url(record['id']) return self._delete(record_url)
def bbox_str(bbox, pad=4, sep=', '): r""" makes a string from an integer bounding box """ if bbox is None: return 'None' fmtstr = sep.join(['%' + six.text_type(pad) + 'd'] * 4) return '(' + fmtstr % tuple(bbox) + ')'
r""" makes a string from an integer bounding box
Below is the the instruction that describes the task: ### Input: r""" makes a string from an integer bounding box ### Response: def bbox_str(bbox, pad=4, sep=', '): r""" makes a string from an integer bounding box """ if bbox is None: return 'None' fmtstr = sep.join(['%' + six.text_type(pad) + 'd'] * 4) return '(' + fmtstr % tuple(bbox) + ')'
def results_decorator(func): """ Helper for constructing simple decorators around Lookup.results. func is a function which takes a request as the first parameter. If func returns an HttpReponse it is returned otherwise the original Lookup.results is returned. """ # Wrap function to maintian the original doc string, etc @wraps(func) def decorator(lookup_cls): # Construct a class decorator from the original function original = lookup_cls.results def inner(self, request): # Wrap lookup_cls.results by first calling func and checking the result result = func(request) if isinstance(result, HttpResponse): return result return original(self, request) # Replace original lookup_cls.results with wrapped version lookup_cls.results = inner return lookup_cls # Return the constructed decorator return decorator
Helper for constructing simple decorators around Lookup.results. func is a function which takes a request as the first parameter. If func returns an HttpReponse it is returned otherwise the original Lookup.results is returned.
Below is the the instruction that describes the task: ### Input: Helper for constructing simple decorators around Lookup.results. func is a function which takes a request as the first parameter. If func returns an HttpReponse it is returned otherwise the original Lookup.results is returned. ### Response: def results_decorator(func): """ Helper for constructing simple decorators around Lookup.results. func is a function which takes a request as the first parameter. If func returns an HttpReponse it is returned otherwise the original Lookup.results is returned. """ # Wrap function to maintian the original doc string, etc @wraps(func) def decorator(lookup_cls): # Construct a class decorator from the original function original = lookup_cls.results def inner(self, request): # Wrap lookup_cls.results by first calling func and checking the result result = func(request) if isinstance(result, HttpResponse): return result return original(self, request) # Replace original lookup_cls.results with wrapped version lookup_cls.results = inner return lookup_cls # Return the constructed decorator return decorator
def paginate_index(self, bucket, index, startkey, endkey=None, max_results=1000, return_terms=None, continuation=None, timeout=None, term_regex=None): """ Iterates over a paginated index query. This is equivalent to calling :meth:`get_index` and then successively calling :meth:`~riak.client.index_page.IndexPage.next_page` until all results are exhausted. Because limiting the result set is necessary to invoke pagination, the ``max_results`` option has a default of ``1000``. :param bucket: the bucket whose index will be queried :type bucket: RiakBucket :param index: the index to query :type index: string :param startkey: the sole key to query, or beginning of the query range :type startkey: string, integer :param endkey: the end of the query range (optional if equality) :type endkey: string, integer :param return_terms: whether to include the secondary index value :type return_terms: boolean :param max_results: the maximum number of results to return (page size), defaults to 1000 :type max_results: integer :param continuation: the opaque continuation returned from a previous paginated request :type continuation: string :param timeout: a timeout value in milliseconds, or 'infinity' :type timeout: int :param term_regex: a regular expression used to filter index terms :type term_regex: string :rtype: generator over instances of :class:`~riak.client.index_page.IndexPage` """ page = self.get_index(bucket, index, startkey, endkey=endkey, max_results=max_results, return_terms=return_terms, continuation=continuation, timeout=timeout, term_regex=term_regex) yield page while page.has_next_page(): page = page.next_page() yield page
Iterates over a paginated index query. This is equivalent to calling :meth:`get_index` and then successively calling :meth:`~riak.client.index_page.IndexPage.next_page` until all results are exhausted. Because limiting the result set is necessary to invoke pagination, the ``max_results`` option has a default of ``1000``. :param bucket: the bucket whose index will be queried :type bucket: RiakBucket :param index: the index to query :type index: string :param startkey: the sole key to query, or beginning of the query range :type startkey: string, integer :param endkey: the end of the query range (optional if equality) :type endkey: string, integer :param return_terms: whether to include the secondary index value :type return_terms: boolean :param max_results: the maximum number of results to return (page size), defaults to 1000 :type max_results: integer :param continuation: the opaque continuation returned from a previous paginated request :type continuation: string :param timeout: a timeout value in milliseconds, or 'infinity' :type timeout: int :param term_regex: a regular expression used to filter index terms :type term_regex: string :rtype: generator over instances of :class:`~riak.client.index_page.IndexPage`
Below is the the instruction that describes the task: ### Input: Iterates over a paginated index query. This is equivalent to calling :meth:`get_index` and then successively calling :meth:`~riak.client.index_page.IndexPage.next_page` until all results are exhausted. Because limiting the result set is necessary to invoke pagination, the ``max_results`` option has a default of ``1000``. :param bucket: the bucket whose index will be queried :type bucket: RiakBucket :param index: the index to query :type index: string :param startkey: the sole key to query, or beginning of the query range :type startkey: string, integer :param endkey: the end of the query range (optional if equality) :type endkey: string, integer :param return_terms: whether to include the secondary index value :type return_terms: boolean :param max_results: the maximum number of results to return (page size), defaults to 1000 :type max_results: integer :param continuation: the opaque continuation returned from a previous paginated request :type continuation: string :param timeout: a timeout value in milliseconds, or 'infinity' :type timeout: int :param term_regex: a regular expression used to filter index terms :type term_regex: string :rtype: generator over instances of :class:`~riak.client.index_page.IndexPage` ### Response: def paginate_index(self, bucket, index, startkey, endkey=None, max_results=1000, return_terms=None, continuation=None, timeout=None, term_regex=None): """ Iterates over a paginated index query. This is equivalent to calling :meth:`get_index` and then successively calling :meth:`~riak.client.index_page.IndexPage.next_page` until all results are exhausted. Because limiting the result set is necessary to invoke pagination, the ``max_results`` option has a default of ``1000``. :param bucket: the bucket whose index will be queried :type bucket: RiakBucket :param index: the index to query :type index: string :param startkey: the sole key to query, or beginning of the query range :type startkey: string, integer :param endkey: the end of the query range (optional if equality) :type endkey: string, integer :param return_terms: whether to include the secondary index value :type return_terms: boolean :param max_results: the maximum number of results to return (page size), defaults to 1000 :type max_results: integer :param continuation: the opaque continuation returned from a previous paginated request :type continuation: string :param timeout: a timeout value in milliseconds, or 'infinity' :type timeout: int :param term_regex: a regular expression used to filter index terms :type term_regex: string :rtype: generator over instances of :class:`~riak.client.index_page.IndexPage` """ page = self.get_index(bucket, index, startkey, endkey=endkey, max_results=max_results, return_terms=return_terms, continuation=continuation, timeout=timeout, term_regex=term_regex) yield page while page.has_next_page(): page = page.next_page() yield page
def _create_network_adapters(network_interfaces, parent=None): ''' Returns a list of vim.vm.device.VirtualDeviceSpec objects representing the interfaces to be created for a virtual machine network_interfaces List of network interfaces and properties parent Parent object reference .. code-block: bash interfaces: adapter: 'Network adapter 1' name: vlan100 switch_type: distributed or standard adapter_type: vmxnet3 or vmxnet, vmxnet2, vmxnet3, e1000, e1000e mac: '00:11:22:33:44:55' ''' network_specs = [] nics_settings = [] keys = range(-4000, -4050, -1) if network_interfaces: devs = [inter['adapter'] for inter in network_interfaces] log.trace('Creating network interfaces %s', devs) for interface, key in zip(network_interfaces, keys): network_spec = _apply_network_adapter_config( key, interface['name'], interface['adapter_type'], interface['switch_type'], network_adapter_label=interface['adapter'], operation='add', connectable=interface['connectable'] if 'connectable' in interface else None, mac=interface['mac'], parent=parent) network_specs.append(network_spec) if 'mapping' in interface: adapter_mapping = _set_network_adapter_mapping( interface['mapping']['domain'], interface['mapping']['gateway'], interface['mapping']['ip_addr'], interface['mapping']['subnet_mask'], interface['mac']) nics_settings.append(adapter_mapping) return (network_specs, nics_settings)
Returns a list of vim.vm.device.VirtualDeviceSpec objects representing the interfaces to be created for a virtual machine network_interfaces List of network interfaces and properties parent Parent object reference .. code-block: bash interfaces: adapter: 'Network adapter 1' name: vlan100 switch_type: distributed or standard adapter_type: vmxnet3 or vmxnet, vmxnet2, vmxnet3, e1000, e1000e mac: '00:11:22:33:44:55'
Below is the the instruction that describes the task: ### Input: Returns a list of vim.vm.device.VirtualDeviceSpec objects representing the interfaces to be created for a virtual machine network_interfaces List of network interfaces and properties parent Parent object reference .. code-block: bash interfaces: adapter: 'Network adapter 1' name: vlan100 switch_type: distributed or standard adapter_type: vmxnet3 or vmxnet, vmxnet2, vmxnet3, e1000, e1000e mac: '00:11:22:33:44:55' ### Response: def _create_network_adapters(network_interfaces, parent=None): ''' Returns a list of vim.vm.device.VirtualDeviceSpec objects representing the interfaces to be created for a virtual machine network_interfaces List of network interfaces and properties parent Parent object reference .. code-block: bash interfaces: adapter: 'Network adapter 1' name: vlan100 switch_type: distributed or standard adapter_type: vmxnet3 or vmxnet, vmxnet2, vmxnet3, e1000, e1000e mac: '00:11:22:33:44:55' ''' network_specs = [] nics_settings = [] keys = range(-4000, -4050, -1) if network_interfaces: devs = [inter['adapter'] for inter in network_interfaces] log.trace('Creating network interfaces %s', devs) for interface, key in zip(network_interfaces, keys): network_spec = _apply_network_adapter_config( key, interface['name'], interface['adapter_type'], interface['switch_type'], network_adapter_label=interface['adapter'], operation='add', connectable=interface['connectable'] if 'connectable' in interface else None, mac=interface['mac'], parent=parent) network_specs.append(network_spec) if 'mapping' in interface: adapter_mapping = _set_network_adapter_mapping( interface['mapping']['domain'], interface['mapping']['gateway'], interface['mapping']['ip_addr'], interface['mapping']['subnet_mask'], interface['mac']) nics_settings.append(adapter_mapping) return (network_specs, nics_settings)
def __cqt_filter_fft(sr, fmin, n_bins, bins_per_octave, tuning, filter_scale, norm, sparsity, hop_length=None, window='hann'): '''Generate the frequency domain constant-Q filter basis.''' basis, lengths = filters.constant_q(sr, fmin=fmin, n_bins=n_bins, bins_per_octave=bins_per_octave, tuning=tuning, filter_scale=filter_scale, norm=norm, pad_fft=True, window=window) # Filters are padded up to the nearest integral power of 2 n_fft = basis.shape[1] if (hop_length is not None and n_fft < 2.0**(1 + np.ceil(np.log2(hop_length)))): n_fft = int(2.0 ** (1 + np.ceil(np.log2(hop_length)))) # re-normalize bases with respect to the FFT window length basis *= lengths[:, np.newaxis] / float(n_fft) # FFT and retain only the non-negative frequencies fft = get_fftlib() fft_basis = fft.fft(basis, n=n_fft, axis=1)[:, :(n_fft // 2)+1] # sparsify the basis fft_basis = util.sparsify_rows(fft_basis, quantile=sparsity) return fft_basis, n_fft, lengths
Generate the frequency domain constant-Q filter basis.
Below is the the instruction that describes the task: ### Input: Generate the frequency domain constant-Q filter basis. ### Response: def __cqt_filter_fft(sr, fmin, n_bins, bins_per_octave, tuning, filter_scale, norm, sparsity, hop_length=None, window='hann'): '''Generate the frequency domain constant-Q filter basis.''' basis, lengths = filters.constant_q(sr, fmin=fmin, n_bins=n_bins, bins_per_octave=bins_per_octave, tuning=tuning, filter_scale=filter_scale, norm=norm, pad_fft=True, window=window) # Filters are padded up to the nearest integral power of 2 n_fft = basis.shape[1] if (hop_length is not None and n_fft < 2.0**(1 + np.ceil(np.log2(hop_length)))): n_fft = int(2.0 ** (1 + np.ceil(np.log2(hop_length)))) # re-normalize bases with respect to the FFT window length basis *= lengths[:, np.newaxis] / float(n_fft) # FFT and retain only the non-negative frequencies fft = get_fftlib() fft_basis = fft.fft(basis, n=n_fft, axis=1)[:, :(n_fft // 2)+1] # sparsify the basis fft_basis = util.sparsify_rows(fft_basis, quantile=sparsity) return fft_basis, n_fft, lengths
def json2space(in_x, name=ROOT): """ Change json to search space in hyperopt. Parameters ---------- in_x : dict/list/str/int/float The part of json. name : str name could be ROOT, TYPE, VALUE or INDEX. """ out_y = copy.deepcopy(in_x) if isinstance(in_x, dict): if TYPE in in_x.keys(): _type = in_x[TYPE] name = name + '-' + _type _value = json2space(in_x[VALUE], name=name) if _type == 'choice': out_y = eval('hp.hp.'+_type)(name, _value) else: if _type in ['loguniform', 'qloguniform']: _value[:2] = np.log(_value[:2]) out_y = eval('hp.hp.' + _type)(name, *_value) else: out_y = dict() for key in in_x.keys(): out_y[key] = json2space(in_x[key], name+'[%s]' % str(key)) elif isinstance(in_x, list): out_y = list() for i, x_i in enumerate(in_x): out_y.append(json2space(x_i, name+'[%d]' % i)) else: logger.info('in_x is not a dict or a list in json2space fuinction %s', str(in_x)) return out_y
Change json to search space in hyperopt. Parameters ---------- in_x : dict/list/str/int/float The part of json. name : str name could be ROOT, TYPE, VALUE or INDEX.
Below is the the instruction that describes the task: ### Input: Change json to search space in hyperopt. Parameters ---------- in_x : dict/list/str/int/float The part of json. name : str name could be ROOT, TYPE, VALUE or INDEX. ### Response: def json2space(in_x, name=ROOT): """ Change json to search space in hyperopt. Parameters ---------- in_x : dict/list/str/int/float The part of json. name : str name could be ROOT, TYPE, VALUE or INDEX. """ out_y = copy.deepcopy(in_x) if isinstance(in_x, dict): if TYPE in in_x.keys(): _type = in_x[TYPE] name = name + '-' + _type _value = json2space(in_x[VALUE], name=name) if _type == 'choice': out_y = eval('hp.hp.'+_type)(name, _value) else: if _type in ['loguniform', 'qloguniform']: _value[:2] = np.log(_value[:2]) out_y = eval('hp.hp.' + _type)(name, *_value) else: out_y = dict() for key in in_x.keys(): out_y[key] = json2space(in_x[key], name+'[%s]' % str(key)) elif isinstance(in_x, list): out_y = list() for i, x_i in enumerate(in_x): out_y.append(json2space(x_i, name+'[%d]' % i)) else: logger.info('in_x is not a dict or a list in json2space fuinction %s', str(in_x)) return out_y
def find_common_beginning(string_list, boundary_char = None): """Given a list of strings, finds finds the longest string that is common to the *beginning* of all strings in the list. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char. """ common='' # by definition there is nothing common to 1 item... if len(string_list) > 1: shortestLen = min([len(el) for el in string_list]) for idx in range(shortestLen): chars = [s[idx] for s in string_list] if chars.count(chars[0]) != len(chars): # test if any chars differ break common+=chars[0] if boundary_char is not None: try: end_idx = common.rindex(boundary_char) common = common[0:end_idx+1] except ValueError: common = '' return common
Given a list of strings, finds finds the longest string that is common to the *beginning* of all strings in the list. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char.
Below is the the instruction that describes the task: ### Input: Given a list of strings, finds finds the longest string that is common to the *beginning* of all strings in the list. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char. ### Response: def find_common_beginning(string_list, boundary_char = None): """Given a list of strings, finds finds the longest string that is common to the *beginning* of all strings in the list. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char. """ common='' # by definition there is nothing common to 1 item... if len(string_list) > 1: shortestLen = min([len(el) for el in string_list]) for idx in range(shortestLen): chars = [s[idx] for s in string_list] if chars.count(chars[0]) != len(chars): # test if any chars differ break common+=chars[0] if boundary_char is not None: try: end_idx = common.rindex(boundary_char) common = common[0:end_idx+1] except ValueError: common = '' return common
def redirect(location, code=302): """Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302. """ from werkzeug.wrappers import Response display_location = escape(location) if isinstance(location, text_type): from werkzeug.urls import iri_to_uri location = iri_to_uri(location) response = Response( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' '<title>Redirecting...</title>\n' '<h1>Redirecting...</h1>\n' '<p>You should be redirected automatically to target URL: ' '<a href="%s">%s</a>. If not click the link.' % (escape(location), display_location), code, mimetype='text/html') response.headers['Location'] = location return response
Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302.
Below is the the instruction that describes the task: ### Input: Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302. ### Response: def redirect(location, code=302): """Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302. """ from werkzeug.wrappers import Response display_location = escape(location) if isinstance(location, text_type): from werkzeug.urls import iri_to_uri location = iri_to_uri(location) response = Response( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' '<title>Redirecting...</title>\n' '<h1>Redirecting...</h1>\n' '<p>You should be redirected automatically to target URL: ' '<a href="%s">%s</a>. If not click the link.' % (escape(location), display_location), code, mimetype='text/html') response.headers['Location'] = location return response
def __extend_with_api_ref(raw_testinfo): """ extend with api reference Raises: exceptions.ApiNotFound: api not found """ api_name = raw_testinfo["api"] # api maybe defined in two types: # 1, individual file: each file is corresponding to one api definition # 2, api sets file: one file contains a list of api definitions if not os.path.isabs(api_name): # make compatible with Windows/Linux api_path = os.path.join(tests_def_mapping["PWD"], *api_name.split("/")) if os.path.isfile(api_path): # type 1: api is defined in individual file api_name = api_path try: block = tests_def_mapping["api"][api_name] # NOTICE: avoid project_mapping been changed during iteration. raw_testinfo["api_def"] = utils.deepcopy_dict(block) except KeyError: raise exceptions.ApiNotFound("{} not found!".format(api_name))
extend with api reference Raises: exceptions.ApiNotFound: api not found
Below is the the instruction that describes the task: ### Input: extend with api reference Raises: exceptions.ApiNotFound: api not found ### Response: def __extend_with_api_ref(raw_testinfo): """ extend with api reference Raises: exceptions.ApiNotFound: api not found """ api_name = raw_testinfo["api"] # api maybe defined in two types: # 1, individual file: each file is corresponding to one api definition # 2, api sets file: one file contains a list of api definitions if not os.path.isabs(api_name): # make compatible with Windows/Linux api_path = os.path.join(tests_def_mapping["PWD"], *api_name.split("/")) if os.path.isfile(api_path): # type 1: api is defined in individual file api_name = api_path try: block = tests_def_mapping["api"][api_name] # NOTICE: avoid project_mapping been changed during iteration. raw_testinfo["api_def"] = utils.deepcopy_dict(block) except KeyError: raise exceptions.ApiNotFound("{} not found!".format(api_name))
def database_remove_types(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /database-xxxx/removeTypes API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FremoveTypes """ return DXHTTPRequest('/%s/removeTypes' % object_id, input_params, always_retry=always_retry, **kwargs)
Invokes the /database-xxxx/removeTypes API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FremoveTypes
Below is the the instruction that describes the task: ### Input: Invokes the /database-xxxx/removeTypes API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FremoveTypes ### Response: def database_remove_types(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /database-xxxx/removeTypes API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FremoveTypes """ return DXHTTPRequest('/%s/removeTypes' % object_id, input_params, always_retry=always_retry, **kwargs)
def vsearch_dereplicate_exact_seqs( fasta_filepath, output_filepath, output_uc=False, working_dir=None, strand="both", maxuniquesize=None, minuniquesize=None, sizein=False, sizeout=True, log_name="derep.log", HALT_EXEC=False): """ Generates clusters and fasta file of dereplicated subsequences Parameters ---------- fasta_filepath : string input filepath of fasta file to be dereplicated output_filepath : string write the dereplicated sequences to output_filepath working_dir : string, optional directory path for storing intermediate output output_uc : boolean, optional uutput dereplication results in a file using a uclust-like format strand : string, optional when searching for strictly identical sequences, check the 'strand' only (default: both) or check the plus strand only maxuniquesize : integer, optional discard sequences with an abundance value greater than maxuniquesize minuniquesize : integer, optional discard sequences with an abundance value smaller than integer sizein : boolean, optional take into account the abundance annotations present in the input fasta file, (search for the pattern "[>;]size=integer[;]" in sequence headers) sizeout : boolean, optional add abundance annotations to the output fasta file (add the pattern ";size=integer;" to sequence headers) log_name : string, optional specifies log filename HALT_EXEC : boolean, optional used for debugging app controller Return ------ output_filepath : string filepath to dereplicated fasta file uc_filepath : string filepath to dereplication results in uclust-like format log_filepath : string filepath to log file """ # write all vsearch output files to same directory # as output_filepath if working_dir is not specified if not working_dir: working_dir = dirname(abspath(output_filepath)) app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC) log_filepath = join(working_dir, log_name) uc_filepath = None if output_uc: root_name = splitext(abspath(output_filepath))[0] uc_filepath = join(working_dir, '%s.uc' % root_name) app.Parameters['--uc'].on(uc_filepath) if maxuniquesize: app.Parameters['--maxuniquesize'].on(maxuniquesize) if minuniquesize: app.Parameters['--minuniquesize'].on(minuniquesize) if sizein: app.Parameters['--sizein'].on() if sizeout: app.Parameters['--sizeout'].on() if (strand == "both" or strand == "plus"): app.Parameters['--strand'].on(strand) else: raise ValueError("Option --strand accepts only 'both'" "or 'plus' values") app.Parameters['--derep_fulllength'].on(fasta_filepath) app.Parameters['--output'].on(output_filepath) app.Parameters['--log'].on(log_filepath) app_result = app() return output_filepath, uc_filepath, log_filepath
Generates clusters and fasta file of dereplicated subsequences Parameters ---------- fasta_filepath : string input filepath of fasta file to be dereplicated output_filepath : string write the dereplicated sequences to output_filepath working_dir : string, optional directory path for storing intermediate output output_uc : boolean, optional uutput dereplication results in a file using a uclust-like format strand : string, optional when searching for strictly identical sequences, check the 'strand' only (default: both) or check the plus strand only maxuniquesize : integer, optional discard sequences with an abundance value greater than maxuniquesize minuniquesize : integer, optional discard sequences with an abundance value smaller than integer sizein : boolean, optional take into account the abundance annotations present in the input fasta file, (search for the pattern "[>;]size=integer[;]" in sequence headers) sizeout : boolean, optional add abundance annotations to the output fasta file (add the pattern ";size=integer;" to sequence headers) log_name : string, optional specifies log filename HALT_EXEC : boolean, optional used for debugging app controller Return ------ output_filepath : string filepath to dereplicated fasta file uc_filepath : string filepath to dereplication results in uclust-like format log_filepath : string filepath to log file
Below is the the instruction that describes the task: ### Input: Generates clusters and fasta file of dereplicated subsequences Parameters ---------- fasta_filepath : string input filepath of fasta file to be dereplicated output_filepath : string write the dereplicated sequences to output_filepath working_dir : string, optional directory path for storing intermediate output output_uc : boolean, optional uutput dereplication results in a file using a uclust-like format strand : string, optional when searching for strictly identical sequences, check the 'strand' only (default: both) or check the plus strand only maxuniquesize : integer, optional discard sequences with an abundance value greater than maxuniquesize minuniquesize : integer, optional discard sequences with an abundance value smaller than integer sizein : boolean, optional take into account the abundance annotations present in the input fasta file, (search for the pattern "[>;]size=integer[;]" in sequence headers) sizeout : boolean, optional add abundance annotations to the output fasta file (add the pattern ";size=integer;" to sequence headers) log_name : string, optional specifies log filename HALT_EXEC : boolean, optional used for debugging app controller Return ------ output_filepath : string filepath to dereplicated fasta file uc_filepath : string filepath to dereplication results in uclust-like format log_filepath : string filepath to log file ### Response: def vsearch_dereplicate_exact_seqs( fasta_filepath, output_filepath, output_uc=False, working_dir=None, strand="both", maxuniquesize=None, minuniquesize=None, sizein=False, sizeout=True, log_name="derep.log", HALT_EXEC=False): """ Generates clusters and fasta file of dereplicated subsequences Parameters ---------- fasta_filepath : string input filepath of fasta file to be dereplicated output_filepath : string write the dereplicated sequences to output_filepath working_dir : string, optional directory path for storing intermediate output output_uc : boolean, optional uutput dereplication results in a file using a uclust-like format strand : string, optional when searching for strictly identical sequences, check the 'strand' only (default: both) or check the plus strand only maxuniquesize : integer, optional discard sequences with an abundance value greater than maxuniquesize minuniquesize : integer, optional discard sequences with an abundance value smaller than integer sizein : boolean, optional take into account the abundance annotations present in the input fasta file, (search for the pattern "[>;]size=integer[;]" in sequence headers) sizeout : boolean, optional add abundance annotations to the output fasta file (add the pattern ";size=integer;" to sequence headers) log_name : string, optional specifies log filename HALT_EXEC : boolean, optional used for debugging app controller Return ------ output_filepath : string filepath to dereplicated fasta file uc_filepath : string filepath to dereplication results in uclust-like format log_filepath : string filepath to log file """ # write all vsearch output files to same directory # as output_filepath if working_dir is not specified if not working_dir: working_dir = dirname(abspath(output_filepath)) app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC) log_filepath = join(working_dir, log_name) uc_filepath = None if output_uc: root_name = splitext(abspath(output_filepath))[0] uc_filepath = join(working_dir, '%s.uc' % root_name) app.Parameters['--uc'].on(uc_filepath) if maxuniquesize: app.Parameters['--maxuniquesize'].on(maxuniquesize) if minuniquesize: app.Parameters['--minuniquesize'].on(minuniquesize) if sizein: app.Parameters['--sizein'].on() if sizeout: app.Parameters['--sizeout'].on() if (strand == "both" or strand == "plus"): app.Parameters['--strand'].on(strand) else: raise ValueError("Option --strand accepts only 'both'" "or 'plus' values") app.Parameters['--derep_fulllength'].on(fasta_filepath) app.Parameters['--output'].on(output_filepath) app.Parameters['--log'].on(log_filepath) app_result = app() return output_filepath, uc_filepath, log_filepath
def hardware_connector_sfp_breakout(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") connector = ET.SubElement(hardware, "connector") name_key = ET.SubElement(connector, "name") name_key.text = kwargs.pop('name') sfp = ET.SubElement(connector, "sfp") breakout = ET.SubElement(sfp, "breakout") callback = kwargs.pop('callback', self._callback) return callback(config)
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def hardware_connector_sfp_breakout(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") connector = ET.SubElement(hardware, "connector") name_key = ET.SubElement(connector, "name") name_key.text = kwargs.pop('name') sfp = ET.SubElement(connector, "sfp") breakout = ET.SubElement(sfp, "breakout") callback = kwargs.pop('callback', self._callback) return callback(config)
def enqueue_command(self, command_name, args, options): """Enqueue a new command into this pipeline.""" assert_open(self) promise = Promise() self.commands.append((command_name, args, options, promise)) return promise
Enqueue a new command into this pipeline.
Below is the the instruction that describes the task: ### Input: Enqueue a new command into this pipeline. ### Response: def enqueue_command(self, command_name, args, options): """Enqueue a new command into this pipeline.""" assert_open(self) promise = Promise() self.commands.append((command_name, args, options, promise)) return promise
def create_package_level_rst_index_file( package_name, max_depth, modules, inner_packages=None): """Function for creating text for index for a package. :param package_name: name of the package :type package_name: str :param max_depth: Value for max_depth in the index file. :type max_depth: int :param modules: list of module in the package. :type modules: list :return: A text for the content of the index file. :rtype: str """ if inner_packages is None: inner_packages = [] return_text = 'Package::' + package_name dash = '=' * len(return_text) return_text += '\n' + dash + '\n\n' return_text += '.. toctree::' + '\n' return_text += ' :maxdepth: ' + str(max_depth) + '\n\n' upper_package = package_name.split('.')[-1] for module in modules: if module in EXCLUDED_PACKAGES: continue return_text += ' ' + upper_package + os.sep + module[:-3] + '\n' for inner_package in inner_packages: if inner_package in EXCLUDED_PACKAGES: continue return_text += ' ' + upper_package + os.sep + inner_package + '\n' return return_text
Function for creating text for index for a package. :param package_name: name of the package :type package_name: str :param max_depth: Value for max_depth in the index file. :type max_depth: int :param modules: list of module in the package. :type modules: list :return: A text for the content of the index file. :rtype: str
Below is the the instruction that describes the task: ### Input: Function for creating text for index for a package. :param package_name: name of the package :type package_name: str :param max_depth: Value for max_depth in the index file. :type max_depth: int :param modules: list of module in the package. :type modules: list :return: A text for the content of the index file. :rtype: str ### Response: def create_package_level_rst_index_file( package_name, max_depth, modules, inner_packages=None): """Function for creating text for index for a package. :param package_name: name of the package :type package_name: str :param max_depth: Value for max_depth in the index file. :type max_depth: int :param modules: list of module in the package. :type modules: list :return: A text for the content of the index file. :rtype: str """ if inner_packages is None: inner_packages = [] return_text = 'Package::' + package_name dash = '=' * len(return_text) return_text += '\n' + dash + '\n\n' return_text += '.. toctree::' + '\n' return_text += ' :maxdepth: ' + str(max_depth) + '\n\n' upper_package = package_name.split('.')[-1] for module in modules: if module in EXCLUDED_PACKAGES: continue return_text += ' ' + upper_package + os.sep + module[:-3] + '\n' for inner_package in inner_packages: if inner_package in EXCLUDED_PACKAGES: continue return_text += ' ' + upper_package + os.sep + inner_package + '\n' return return_text
def client_args_for_bank(bank_info, ofx_version): """ Return the client arguments to use for a particular Institution, as found from ofxhome. This provides us with an extension point to override or augment ofxhome data for specific institutions, such as those that require specific User-Agent headers (or no User-Agent header). :param bank_info: OFXHome bank information for the institution, as returned by ``OFXHome.lookup()`` :type bank_info: dict :param ofx_version: OFX Version argument specified on command line :type ofx_version: str :return: Client arguments for a specific institution :rtype: dict """ client_args = {'ofx_version': str(ofx_version)} if 'ofx.discovercard.com' in bank_info['url']: # Discover needs no User-Agent and no Accept headers client_args['user_agent'] = False client_args['accept'] = False if 'www.accountonline.com' in bank_info['url']: # Citi needs no User-Agent header client_args['user_agent'] = False return client_args
Return the client arguments to use for a particular Institution, as found from ofxhome. This provides us with an extension point to override or augment ofxhome data for specific institutions, such as those that require specific User-Agent headers (or no User-Agent header). :param bank_info: OFXHome bank information for the institution, as returned by ``OFXHome.lookup()`` :type bank_info: dict :param ofx_version: OFX Version argument specified on command line :type ofx_version: str :return: Client arguments for a specific institution :rtype: dict
Below is the the instruction that describes the task: ### Input: Return the client arguments to use for a particular Institution, as found from ofxhome. This provides us with an extension point to override or augment ofxhome data for specific institutions, such as those that require specific User-Agent headers (or no User-Agent header). :param bank_info: OFXHome bank information for the institution, as returned by ``OFXHome.lookup()`` :type bank_info: dict :param ofx_version: OFX Version argument specified on command line :type ofx_version: str :return: Client arguments for a specific institution :rtype: dict ### Response: def client_args_for_bank(bank_info, ofx_version): """ Return the client arguments to use for a particular Institution, as found from ofxhome. This provides us with an extension point to override or augment ofxhome data for specific institutions, such as those that require specific User-Agent headers (or no User-Agent header). :param bank_info: OFXHome bank information for the institution, as returned by ``OFXHome.lookup()`` :type bank_info: dict :param ofx_version: OFX Version argument specified on command line :type ofx_version: str :return: Client arguments for a specific institution :rtype: dict """ client_args = {'ofx_version': str(ofx_version)} if 'ofx.discovercard.com' in bank_info['url']: # Discover needs no User-Agent and no Accept headers client_args['user_agent'] = False client_args['accept'] = False if 'www.accountonline.com' in bank_info['url']: # Citi needs no User-Agent header client_args['user_agent'] = False return client_args
def get_namespace(fn: Callable, namespace: Optional[str]) -> str: """ Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace Args: fn: a function namespace: an optional namespace, which can be of any type but is normally a ``str``; if not ``None``, ``str(namespace)`` will be added to the result. See https://dogpilecache.readthedocs.io/en/latest/api.html#dogpile.cache.region.CacheRegion.cache_on_arguments """ # noqa # See hidden attributes with dir(fn) # noinspection PyUnresolvedReferences return "{module}:{name}{extra}".format( module=fn.__module__, name=fn.__qualname__, # __qualname__ includes class name, if present extra="|{}".format(namespace) if namespace is not None else "", )
Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace Args: fn: a function namespace: an optional namespace, which can be of any type but is normally a ``str``; if not ``None``, ``str(namespace)`` will be added to the result. See https://dogpilecache.readthedocs.io/en/latest/api.html#dogpile.cache.region.CacheRegion.cache_on_arguments
Below is the the instruction that describes the task: ### Input: Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace Args: fn: a function namespace: an optional namespace, which can be of any type but is normally a ``str``; if not ``None``, ``str(namespace)`` will be added to the result. See https://dogpilecache.readthedocs.io/en/latest/api.html#dogpile.cache.region.CacheRegion.cache_on_arguments ### Response: def get_namespace(fn: Callable, namespace: Optional[str]) -> str: """ Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace Args: fn: a function namespace: an optional namespace, which can be of any type but is normally a ``str``; if not ``None``, ``str(namespace)`` will be added to the result. See https://dogpilecache.readthedocs.io/en/latest/api.html#dogpile.cache.region.CacheRegion.cache_on_arguments """ # noqa # See hidden attributes with dir(fn) # noinspection PyUnresolvedReferences return "{module}:{name}{extra}".format( module=fn.__module__, name=fn.__qualname__, # __qualname__ includes class name, if present extra="|{}".format(namespace) if namespace is not None else "", )
def reset(self): """ Kills old session and creates a new one with no proxies or headers """ # Kill old connection self.quit() # Clear proxy data self.driver_args['service_args'] = self.default_service_args # Clear headers self.dcap = dict(webdriver.DesiredCapabilities.PHANTOMJS) # Create new web driver self._create_session()
Kills old session and creates a new one with no proxies or headers
Below is the the instruction that describes the task: ### Input: Kills old session and creates a new one with no proxies or headers ### Response: def reset(self): """ Kills old session and creates a new one with no proxies or headers """ # Kill old connection self.quit() # Clear proxy data self.driver_args['service_args'] = self.default_service_args # Clear headers self.dcap = dict(webdriver.DesiredCapabilities.PHANTOMJS) # Create new web driver self._create_session()
def search_observations(self, search): """ Search for :class:`meteorpi_model.Observation` entities :param search: an instance of :class:`meteorpi_model.ObservationSearch` used to constrain the observations returned from the DB :return: a structure of {count:int total rows of an unrestricted search, observations:list of :class:`meteorpi_model.Observation`} """ b = search_observations_sql_builder(search) sql = b.get_select_sql(columns='l.publicId AS obstory_id, l.name AS obstory_name, ' 'o.obsTime, s.name AS obsType, o.publicId, o.uid', skip=search.skip, limit=search.limit, order='o.obsTime DESC') obs = list(self.generators.observation_generator(sql=sql, sql_args=b.sql_args)) rows_returned = len(obs) total_rows = rows_returned + search.skip if (rows_returned == search.limit > 0) or (rows_returned == 0 and search.skip > 0): self.con.execute(b.get_count_sql(), b.sql_args) total_rows = self.con.fetchone()['COUNT(*)'] return {"count": total_rows, "obs": obs}
Search for :class:`meteorpi_model.Observation` entities :param search: an instance of :class:`meteorpi_model.ObservationSearch` used to constrain the observations returned from the DB :return: a structure of {count:int total rows of an unrestricted search, observations:list of :class:`meteorpi_model.Observation`}
Below is the the instruction that describes the task: ### Input: Search for :class:`meteorpi_model.Observation` entities :param search: an instance of :class:`meteorpi_model.ObservationSearch` used to constrain the observations returned from the DB :return: a structure of {count:int total rows of an unrestricted search, observations:list of :class:`meteorpi_model.Observation`} ### Response: def search_observations(self, search): """ Search for :class:`meteorpi_model.Observation` entities :param search: an instance of :class:`meteorpi_model.ObservationSearch` used to constrain the observations returned from the DB :return: a structure of {count:int total rows of an unrestricted search, observations:list of :class:`meteorpi_model.Observation`} """ b = search_observations_sql_builder(search) sql = b.get_select_sql(columns='l.publicId AS obstory_id, l.name AS obstory_name, ' 'o.obsTime, s.name AS obsType, o.publicId, o.uid', skip=search.skip, limit=search.limit, order='o.obsTime DESC') obs = list(self.generators.observation_generator(sql=sql, sql_args=b.sql_args)) rows_returned = len(obs) total_rows = rows_returned + search.skip if (rows_returned == search.limit > 0) or (rows_returned == 0 and search.skip > 0): self.con.execute(b.get_count_sql(), b.sql_args) total_rows = self.con.fetchone()['COUNT(*)'] return {"count": total_rows, "obs": obs}
def uncancel_confirmation(self, confirmation_id): """ Uncancelles an confirmation :param confirmation_id: the confirmation id """ return self._create_put_request( resource=CONFIRMATIONS, billomat_id=confirmation_id, command=UNCANCEL, )
Uncancelles an confirmation :param confirmation_id: the confirmation id
Below is the the instruction that describes the task: ### Input: Uncancelles an confirmation :param confirmation_id: the confirmation id ### Response: def uncancel_confirmation(self, confirmation_id): """ Uncancelles an confirmation :param confirmation_id: the confirmation id """ return self._create_put_request( resource=CONFIRMATIONS, billomat_id=confirmation_id, command=UNCANCEL, )
def Descargar(self, url=URL, filename="padron.txt", proxy=None): "Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado" proxies = {} if proxy: proxies['http'] = proxy proxies['https'] = proxy proxy_handler = urllib2.ProxyHandler(proxies) print "Abriendo URL %s ..." % url req = urllib2.Request(url) if os.path.exists(filename): http_date = formatdate(timeval=os.path.getmtime(filename), localtime=False, usegmt=True) req.add_header('If-Modified-Since', http_date) try: web = urllib2.urlopen(req) except urllib2.HTTPError, e: if e.code == 304: print "No modificado desde", http_date return 304 else: raise # leer info del request: meta = web.info() lenght = float(meta['Content-Length']) date = meta['Last-Modified'] tmp = open(filename + ".zip", "wb") print "Guardando" size = 0 p0 = None while True: p = int(size / lenght * 100) if p0 is None or p>p0: print "Leyendo ... %0d %%" % p p0 = p data = web.read(1024*100) size = size + len(data) if not data: print "Descarga Terminada!" break tmp.write(data) print "Abriendo ZIP..." tmp.close() web.close() uf = open(filename + ".zip", "rb") zf = zipfile.ZipFile(uf) for fn in zf.namelist(): print "descomprimiendo", fn tf = open(filename, "wb") tf.write(zf.read(fn)) tf.close() return 200
Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado
Below is the the instruction that describes the task: ### Input: Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado ### Response: def Descargar(self, url=URL, filename="padron.txt", proxy=None): "Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado" proxies = {} if proxy: proxies['http'] = proxy proxies['https'] = proxy proxy_handler = urllib2.ProxyHandler(proxies) print "Abriendo URL %s ..." % url req = urllib2.Request(url) if os.path.exists(filename): http_date = formatdate(timeval=os.path.getmtime(filename), localtime=False, usegmt=True) req.add_header('If-Modified-Since', http_date) try: web = urllib2.urlopen(req) except urllib2.HTTPError, e: if e.code == 304: print "No modificado desde", http_date return 304 else: raise # leer info del request: meta = web.info() lenght = float(meta['Content-Length']) date = meta['Last-Modified'] tmp = open(filename + ".zip", "wb") print "Guardando" size = 0 p0 = None while True: p = int(size / lenght * 100) if p0 is None or p>p0: print "Leyendo ... %0d %%" % p p0 = p data = web.read(1024*100) size = size + len(data) if not data: print "Descarga Terminada!" break tmp.write(data) print "Abriendo ZIP..." tmp.close() web.close() uf = open(filename + ".zip", "rb") zf = zipfile.ZipFile(uf) for fn in zf.namelist(): print "descomprimiendo", fn tf = open(filename, "wb") tf.write(zf.read(fn)) tf.close() return 200
def unregister_service(self, registration): # type: (ServiceRegistration) -> bool """ Unregisters the given service :param registration: A ServiceRegistration to the service to unregister :raise BundleException: Invalid reference """ # Get the Service Reference reference = registration.get_reference() # Remove the service from the registry svc_instance = self._registry.unregister(reference) # Keep a track of the unregistering reference self.__unregistering_services[reference] = svc_instance # Call the listeners event = ServiceEvent(ServiceEvent.UNREGISTERING, reference) self._dispatcher.fire_service_event(event) # Update the bundle registration information bundle = reference.get_bundle() bundle._unregistered_service(registration) # Remove the unregistering reference del self.__unregistering_services[reference] return True
Unregisters the given service :param registration: A ServiceRegistration to the service to unregister :raise BundleException: Invalid reference
Below is the the instruction that describes the task: ### Input: Unregisters the given service :param registration: A ServiceRegistration to the service to unregister :raise BundleException: Invalid reference ### Response: def unregister_service(self, registration): # type: (ServiceRegistration) -> bool """ Unregisters the given service :param registration: A ServiceRegistration to the service to unregister :raise BundleException: Invalid reference """ # Get the Service Reference reference = registration.get_reference() # Remove the service from the registry svc_instance = self._registry.unregister(reference) # Keep a track of the unregistering reference self.__unregistering_services[reference] = svc_instance # Call the listeners event = ServiceEvent(ServiceEvent.UNREGISTERING, reference) self._dispatcher.fire_service_event(event) # Update the bundle registration information bundle = reference.get_bundle() bundle._unregistered_service(registration) # Remove the unregistering reference del self.__unregistering_services[reference] return True
def handle_args(args): """ Handle command line arguments Raises: Exception if the config path wasn't explicitly state and dead reckoning based on script location fails """ parser = argparse.ArgumentParser() parser.add_argument("configpath", default=None, nargs="?", help="/path/to/configs (always a directory; if omitted, all /configs are checked") parser.add_argument("--verbose", action="store_true", default=False) parsed_args = vars(parser.parse_args(args)) # If a config path wasn't given, calculate it based on location of the script if parsed_args["configpath"] is None: script_dir = os.path.abspath(os.path.dirname(sys.argv[0])) parsed_args["configpath"] = os.path.normpath("{}/{}".format(script_dir, CONFIGS_RELATIVE_PATH_FROM_SCRIPT_DIR)) else: parsed_args["configpath"] = os.path.normpath(parsed_args["configpath"]) # If the path is a directory, all good. if it's a file, find the directory the file is in and check that instead if os.path.isdir(parsed_args["configpath"]): parsed_args["configdir"] = parsed_args["configpath"] else: parsed_args["configdir"] = os.path.dirname(parsed_args["configpath"]) return parsed_args
Handle command line arguments Raises: Exception if the config path wasn't explicitly state and dead reckoning based on script location fails
Below is the the instruction that describes the task: ### Input: Handle command line arguments Raises: Exception if the config path wasn't explicitly state and dead reckoning based on script location fails ### Response: def handle_args(args): """ Handle command line arguments Raises: Exception if the config path wasn't explicitly state and dead reckoning based on script location fails """ parser = argparse.ArgumentParser() parser.add_argument("configpath", default=None, nargs="?", help="/path/to/configs (always a directory; if omitted, all /configs are checked") parser.add_argument("--verbose", action="store_true", default=False) parsed_args = vars(parser.parse_args(args)) # If a config path wasn't given, calculate it based on location of the script if parsed_args["configpath"] is None: script_dir = os.path.abspath(os.path.dirname(sys.argv[0])) parsed_args["configpath"] = os.path.normpath("{}/{}".format(script_dir, CONFIGS_RELATIVE_PATH_FROM_SCRIPT_DIR)) else: parsed_args["configpath"] = os.path.normpath(parsed_args["configpath"]) # If the path is a directory, all good. if it's a file, find the directory the file is in and check that instead if os.path.isdir(parsed_args["configpath"]): parsed_args["configdir"] = parsed_args["configpath"] else: parsed_args["configdir"] = os.path.dirname(parsed_args["configpath"]) return parsed_args