code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
async def upload_file(self, bucket, file, uploadpath=None, key=None, ContentType=None, **kw): """Upload a file to S3 possibly using the multi-part uploader Return the key uploaded """ is_filename = False if hasattr(file, 'read'): if hasattr(...
Upload a file to S3 possibly using the multi-part uploader Return the key uploaded
Below is the the instruction that describes the task: ### Input: Upload a file to S3 possibly using the multi-part uploader Return the key uploaded ### Response: async def upload_file(self, bucket, file, uploadpath=None, key=None, ContentType=None, **kw): """Upload a file ...
def spi_write(self, data): """Write a stream of bytes to a SPI device.""" data_out = array.array('B', data) data_in = array.array('B', (0,) * len(data_out)) ret = api.py_aa_spi_write(self.handle, len(data_out), data_out, len(data_in), data_in) _raise_error_if_nega...
Write a stream of bytes to a SPI device.
Below is the the instruction that describes the task: ### Input: Write a stream of bytes to a SPI device. ### Response: def spi_write(self, data): """Write a stream of bytes to a SPI device.""" data_out = array.array('B', data) data_in = array.array('B', (0,) * len(data_out)) ret = ...
def next_frame_ae(): """Conv autoencoder.""" hparams = next_frame_basic_deterministic() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.hidden_size = 256 hparams.batch_size = 8 hparams.num_hidden_layers = 4 hparams.num_compress_steps = 4 ...
Conv autoencoder.
Below is the the instruction that describes the task: ### Input: Conv autoencoder. ### Response: def next_frame_ae(): """Conv autoencoder.""" hparams = next_frame_basic_deterministic() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.hidden_s...
def transpose(a, axes=None): """Returns a view of the array with axes transposed. For a 1-D array, this has no effect. For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted Args: a (array_like): Input arr...
Returns a view of the array with axes transposed. For a 1-D array, this has no effect. For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted Args: a (array_like): Input array. axes (list of int, optiona...
Below is the the instruction that describes the task: ### Input: Returns a view of the array with axes transposed. For a 1-D array, this has no effect. For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted Args...
def add_filter(self, table, cols, condition): """ Add a filter. When reading *table*, rows in *table* will be filtered by filter_rows(). Args: table: The table the filter applies to. cols: The columns in *table* to filter on. condition: The filter fun...
Add a filter. When reading *table*, rows in *table* will be filtered by filter_rows(). Args: table: The table the filter applies to. cols: The columns in *table* to filter on. condition: The filter function.
Below is the the instruction that describes the task: ### Input: Add a filter. When reading *table*, rows in *table* will be filtered by filter_rows(). Args: table: The table the filter applies to. cols: The columns in *table* to filter on. condition: The filter ...
def next(self): """A `next` that caches the returned results. Together with the slightly different `__iter__`, these cursors can be iterated over more than once.""" if self.__tailable: return PymongoCursor.next(self) try: ret = PymongoCursor.next(self) ...
A `next` that caches the returned results. Together with the slightly different `__iter__`, these cursors can be iterated over more than once.
Below is the the instruction that describes the task: ### Input: A `next` that caches the returned results. Together with the slightly different `__iter__`, these cursors can be iterated over more than once. ### Response: def next(self): """A `next` that caches the returned results. Toget...
def fromTable(table, paramName): """ Converts a table to GPRecordSet object Inputs: table - path to the table paramName - name of the parameter """ from ..common.spatial import recordset_to_json g = GPRecordSet() g.paramName = paramName ...
Converts a table to GPRecordSet object Inputs: table - path to the table paramName - name of the parameter
Below is the the instruction that describes the task: ### Input: Converts a table to GPRecordSet object Inputs: table - path to the table paramName - name of the parameter ### Response: def fromTable(table, paramName): """ Converts a table to GPRecordSet object ...
def fuzz(p, _inplace=0): """Transform a layer into a fuzzy layer by replacing some default values by random objects""" # noqa: E501 if not _inplace: p = p.copy() q = p while not isinstance(q, NoPayload): for f in q.fields_desc: if isinstance(f, PacketListField): ...
Transform a layer into a fuzzy layer by replacing some default values by random objects
Below is the the instruction that describes the task: ### Input: Transform a layer into a fuzzy layer by replacing some default values by random objects ### Response: def fuzz(p, _inplace=0): """Transform a layer into a fuzzy layer by replacing some default values by random objects""" # noqa: E501 if not ...
def write_version(name=None, path=None): """Write the version info to ../version.json, for setup.py. Args: name (Optional[str]): this is for the ``write_version(name=__name__)`` below. That's one way to both follow the ``if __name__ == '__main__':`` convention but also allow for full ...
Write the version info to ../version.json, for setup.py. Args: name (Optional[str]): this is for the ``write_version(name=__name__)`` below. That's one way to both follow the ``if __name__ == '__main__':`` convention but also allow for full coverage without ignoring parts of the file...
Below is the the instruction that describes the task: ### Input: Write the version info to ../version.json, for setup.py. Args: name (Optional[str]): this is for the ``write_version(name=__name__)`` below. That's one way to both follow the ``if __name__ == '__main__':`` convention but al...
def ipv6_acl_ipv6_access_list_standard_seq_seq_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ipv6_acl = ET.SubElement(config, "ipv6-acl", xmlns="urn:brocade.com:mgmt:brocade-ipv6-access-list") ipv6 = ET.SubElement(ipv6_acl, "ipv6") access_li...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def ipv6_acl_ipv6_access_list_standard_seq_seq_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ipv6_acl = ET.SubElement(config, "ipv6-acl", xmlns="urn:broc...
def _cimdatetime_constructor(loader, node): """ PyYAML constructor function for CIMDateTime objects. This is needed for yaml.safe_load() to support CIMDateTime. """ cimdatetime_str = loader.construct_scalar(node) cimdatetime = CIMDateTime(cimdatetime_str) return cimdatetime
PyYAML constructor function for CIMDateTime objects. This is needed for yaml.safe_load() to support CIMDateTime.
Below is the the instruction that describes the task: ### Input: PyYAML constructor function for CIMDateTime objects. This is needed for yaml.safe_load() to support CIMDateTime. ### Response: def _cimdatetime_constructor(loader, node): """ PyYAML constructor function for CIMDateTime objects. This i...
def preview_view(self, context): """ Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context. Default implementation uses author_view if available, otherwise falls back to student_view Child classes can override this method to control thei...
Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context. Default implementation uses author_view if available, otherwise falls back to student_view Child classes can override this method to control their presentation in preview context
Below is the the instruction that describes the task: ### Input: Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context. Default implementation uses author_view if available, otherwise falls back to student_view Child classes can override this method...
def place_objects(self): """Places objects randomly until no collisions or max iterations hit.""" placed_objects = [] index = 0 # place objects by rejection sampling for _, obj_mjcf in self.mujoco_objects.items(): horizontal_radius = obj_mjcf.get_horizontal_radius() ...
Places objects randomly until no collisions or max iterations hit.
Below is the the instruction that describes the task: ### Input: Places objects randomly until no collisions or max iterations hit. ### Response: def place_objects(self): """Places objects randomly until no collisions or max iterations hit.""" placed_objects = [] index = 0 # place ...
def visualize_qual_stats_dict_single(D, dest, title): """ same as visualize_qual_stats_dict, but puts all tiles together. """ # first find out how many cycles were there. it is going to be about 101 for # hiseq runs, and 251 in miseq runs, but these values may change from run to # run. although...
same as visualize_qual_stats_dict, but puts all tiles together.
Below is the the instruction that describes the task: ### Input: same as visualize_qual_stats_dict, but puts all tiles together. ### Response: def visualize_qual_stats_dict_single(D, dest, title): """ same as visualize_qual_stats_dict, but puts all tiles together. """ # first find out how many cyc...
def enable_parallel(processnum=None): """ Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported. """ global pool, dt, cut, cut_for_search from multiprocessing import cpu_count ...
Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported.
Below is the the instruction that describes the task: ### Input: Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported. ### Response: def enable_parallel(processnum=None): """ Change th...
def from_vizier_table(cls, table_id, nside=256): """ Creates a `~mocpy.moc.MOC` object from a VizieR table. **Info**: This method is already implemented in `astroquery.cds <https://astroquery.readthedocs.io/en/latest/cds/cds.html>`__. You can ask to get a `mocpy.moc.MOC` object from a v...
Creates a `~mocpy.moc.MOC` object from a VizieR table. **Info**: This method is already implemented in `astroquery.cds <https://astroquery.readthedocs.io/en/latest/cds/cds.html>`__. You can ask to get a `mocpy.moc.MOC` object from a vizier catalog ID. Parameters ---------- tabl...
Below is the the instruction that describes the task: ### Input: Creates a `~mocpy.moc.MOC` object from a VizieR table. **Info**: This method is already implemented in `astroquery.cds <https://astroquery.readthedocs.io/en/latest/cds/cds.html>`__. You can ask to get a `mocpy.moc.MOC` object from a v...
def html_to_fc(html=None, clean_html=None, clean_visible=None, encoding=None, url=None, timestamp=None, other_features=None): '''`html` is expected to be a raw string received over the wire from a remote webserver, and `encoding`, if provided, is used to decode it. Typically, encoding comes ...
`html` is expected to be a raw string received over the wire from a remote webserver, and `encoding`, if provided, is used to decode it. Typically, encoding comes from the Content-Type header field. The :func:`~streamcorpus_pipeline._clean_html.make_clean_html` function handles character encodings.
Below is the the instruction that describes the task: ### Input: `html` is expected to be a raw string received over the wire from a remote webserver, and `encoding`, if provided, is used to decode it. Typically, encoding comes from the Content-Type header field. The :func:`~streamcorpus_pipeline._clea...
def save_list(key, *values): """Convert the given list of parameters to a JSON object. JSON object is of the form: { key: [values[0], values[1], ... ] }, where values represent the given list of parameters. """ return json.dumps({key: [_get_json(value) for value in values]})
Convert the given list of parameters to a JSON object. JSON object is of the form: { key: [values[0], values[1], ... ] }, where values represent the given list of parameters.
Below is the the instruction that describes the task: ### Input: Convert the given list of parameters to a JSON object. JSON object is of the form: { key: [values[0], values[1], ... ] }, where values represent the given list of parameters. ### Response: def save_list(key, *values): """Convert the ...
def store(self, transient_file, persistent_file): '''Makes PersistentFile from TransientFile''' #for i in range(5): # persistent_file = PersistentFile(self.persistent_root, # persistent_name, self) # if not os.path.exists(persistent_file....
Makes PersistentFile from TransientFile
Below is the the instruction that describes the task: ### Input: Makes PersistentFile from TransientFile ### Response: def store(self, transient_file, persistent_file): '''Makes PersistentFile from TransientFile''' #for i in range(5): # persistent_file = PersistentFile(self.persistent_ro...
def find_by_index(self, cls, index_name, value): """Find all rows matching index query - as per the gludb spec.""" cur = self._conn().cursor() query = 'select id,value from %s where %s = ?' % ( cls.get_table_name(), index_name ) found = [] for ro...
Find all rows matching index query - as per the gludb spec.
Below is the the instruction that describes the task: ### Input: Find all rows matching index query - as per the gludb spec. ### Response: def find_by_index(self, cls, index_name, value): """Find all rows matching index query - as per the gludb spec.""" cur = self._conn().cursor() query = ...
def _lock_fxn(direction, lock_mode, xact): """Builds a pg advisory lock function name based on various options. :direction: one of "lock" or "unlock" :lock_mode: a member of the LockMode enum :xact: a boolean, if True the lock will be automatically released at the end of the transaction and cannot be ...
Builds a pg advisory lock function name based on various options. :direction: one of "lock" or "unlock" :lock_mode: a member of the LockMode enum :xact: a boolean, if True the lock will be automatically released at the end of the transaction and cannot be manually released.
Below is the the instruction that describes the task: ### Input: Builds a pg advisory lock function name based on various options. :direction: one of "lock" or "unlock" :lock_mode: a member of the LockMode enum :xact: a boolean, if True the lock will be automatically released at the end of the trans...
def compress(bytes, target): """ Compress a list of byte values to a fixed target length. >>> bytes = [96, 173, 141, 13, 135, 27, 96, 149, 128, 130, 151] >>> HumanHasher.compress(bytes, 4) [205, 128, 156, 96] Attempting to compress a smaller number of bytes...
Compress a list of byte values to a fixed target length. >>> bytes = [96, 173, 141, 13, 135, 27, 96, 149, 128, 130, 151] >>> HumanHasher.compress(bytes, 4) [205, 128, 156, 96] Attempting to compress a smaller number of bytes to a larger number is an error: ...
Below is the the instruction that describes the task: ### Input: Compress a list of byte values to a fixed target length. >>> bytes = [96, 173, 141, 13, 135, 27, 96, 149, 128, 130, 151] >>> HumanHasher.compress(bytes, 4) [205, 128, 156, 96] Attempting to compress a smal...
def intersect(self, other, strategy=_STRATEGY.GEOMETRIC, _verify=True): """Find the common intersection with another surface. Args: other (Surface): Other surface to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorit...
Find the common intersection with another surface. Args: other (Surface): Other surface to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorithm to use. Defaults to geometric. _verify (Optional[bool]): Indicates i...
Below is the the instruction that describes the task: ### Input: Find the common intersection with another surface. Args: other (Surface): Other surface to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorithm to use. Def...
def dv(self, orb): """Computation of the velocity increment in the reference frame of the orbit Args: orb (Orbit): Return: numpy.array: Velocity increment, length 3 """ orb = orb.copy(form="cartesian") if self.frame == "QSW": mat = t...
Computation of the velocity increment in the reference frame of the orbit Args: orb (Orbit): Return: numpy.array: Velocity increment, length 3
Below is the the instruction that describes the task: ### Input: Computation of the velocity increment in the reference frame of the orbit Args: orb (Orbit): Return: numpy.array: Velocity increment, length 3 ### Response: def dv(self, orb): """Computation of the vel...
def set_sequence_to_default(self): """Set the new sequence to the default value defined in the config.""" sequence = CONF.get_default( 'shortcuts', "{}/{}".format(self.context, self.name)) self._qsequences = sequence.split(', ') self.update_warning()
Set the new sequence to the default value defined in the config.
Below is the the instruction that describes the task: ### Input: Set the new sequence to the default value defined in the config. ### Response: def set_sequence_to_default(self): """Set the new sequence to the default value defined in the config.""" sequence = CONF.get_default( 'shor...
def getSRTemplateInfo(self): """ Returns a dict with the SRTemplate infomration {'uid':'xxxx','id':'xxxx','title':'xxx','url':'xxx'} """ pc = getToolByName(api.portal.get(), 'portal_catalog') contentFilter = {'portal_type': 'SRTemplate', 'UID': se...
Returns a dict with the SRTemplate infomration {'uid':'xxxx','id':'xxxx','title':'xxx','url':'xxx'}
Below is the the instruction that describes the task: ### Input: Returns a dict with the SRTemplate infomration {'uid':'xxxx','id':'xxxx','title':'xxx','url':'xxx'} ### Response: def getSRTemplateInfo(self): """ Returns a dict with the SRTemplate infomration {'uid':'xxxx','id':'xxxx...
def approximate_cholesky(self, epsilon=1e-6): r""" Compute low-rank approximation to the Cholesky decomposition of target matrix. The decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float, optional, def...
r""" Compute low-rank approximation to the Cholesky decomposition of target matrix. The decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float, optional, default 1e-6 Cutoff for eigenvalue norms. If ...
Below is the the instruction that describes the task: ### Input: r""" Compute low-rank approximation to the Cholesky decomposition of target matrix. The decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float...
def agent_heartbeat(self, agent_id, metrics, run_states): """Notify server about agent state, receive commands. Args: agent_id (str): agent_id metrics (dict): system metrics run_states (dict): run_id: state mapping Returns: List of commands to exe...
Notify server about agent state, receive commands. Args: agent_id (str): agent_id metrics (dict): system metrics run_states (dict): run_id: state mapping Returns: List of commands to execute.
Below is the the instruction that describes the task: ### Input: Notify server about agent state, receive commands. Args: agent_id (str): agent_id metrics (dict): system metrics run_states (dict): run_id: state mapping Returns: List of commands to exe...
def get_status(self): ''' Get the status of the report and its sub-reports. :rtype: str :return: report status ('passed', 'failed' or 'error') ''' status = self.get('status') if status == Report.PASSED: for sr_name in self._sub_reports: ...
Get the status of the report and its sub-reports. :rtype: str :return: report status ('passed', 'failed' or 'error')
Below is the the instruction that describes the task: ### Input: Get the status of the report and its sub-reports. :rtype: str :return: report status ('passed', 'failed' or 'error') ### Response: def get_status(self): ''' Get the status of the report and its sub-reports. :...
def exit(self, status=EXIT_OK, message=None): """ Terminate the script. """ if not self.parser: self.parser = argparse.ArgumentParser() if self.msg_on_error_only: # if msg_on_error_only is True if status != EXIT_OK: # if we have...
Terminate the script.
Below is the the instruction that describes the task: ### Input: Terminate the script. ### Response: def exit(self, status=EXIT_OK, message=None): """ Terminate the script. """ if not self.parser: self.parser = argparse.ArgumentParser() if self.msg_on_error_only:...
def iso_reference_valid_char(c, raise_error=True): """Helper to make sure the given character is valid for a reference number""" if c in ISO_REFERENCE_VALID: return True if raise_error: raise ValueError("'%s' is not in '%s'" % (c, ISO_REFERENCE_VALID)) return False
Helper to make sure the given character is valid for a reference number
Below is the the instruction that describes the task: ### Input: Helper to make sure the given character is valid for a reference number ### Response: def iso_reference_valid_char(c, raise_error=True): """Helper to make sure the given character is valid for a reference number""" if c in ISO_REFERENCE_VALID...
def numpy_from_yaml(constructor: Constructor, data: ruamel.yaml.nodes.SequenceNode) -> np.ndarray: """ Read an array from YAML to numpy. It reads arrays registered under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.constructor.add_...
Read an array from YAML to numpy. It reads arrays registered under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.constructor.add_constructor("!numpy_array", yaml.numpy_from_yaml) Note: We cannot use ``yaml.register_class`` ...
Below is the the instruction that describes the task: ### Input: Read an array from YAML to numpy. It reads arrays registered under the tag ``!numpy_array``. Use with: .. code-block:: python >>> yaml = ruamel.yaml.YAML() >>> yaml.constructor.add_constructor("!numpy_array", yaml.numpy...
def get_minions(): ''' Return a list of minions ''' serv = _get_serv(ret=None) sql = "select distinct(id) from returns" data = serv.query(sql) ret = [] if data: for jid in data[0]['points']: ret.append(jid[1]) return ret
Return a list of minions
Below is the the instruction that describes the task: ### Input: Return a list of minions ### Response: def get_minions(): ''' Return a list of minions ''' serv = _get_serv(ret=None) sql = "select distinct(id) from returns" data = serv.query(sql) ret = [] if data: for jid i...
def logevents(self): """Iterator yielding all logevents from groups dictionary.""" for key in self.groups: for logevent in self.groups[key]: yield logevent
Iterator yielding all logevents from groups dictionary.
Below is the the instruction that describes the task: ### Input: Iterator yielding all logevents from groups dictionary. ### Response: def logevents(self): """Iterator yielding all logevents from groups dictionary.""" for key in self.groups: for logevent in self.groups[key]: ...
def values(self): """Gets the user enter max and min values of where the raster points should appear on the y-axis :returns: (float, float) -- (min, max) y-values to bound the raster plot by """ lower = float(self.lowerSpnbx.value()) upper = float(self.upperSpnbx.value(...
Gets the user enter max and min values of where the raster points should appear on the y-axis :returns: (float, float) -- (min, max) y-values to bound the raster plot by
Below is the the instruction that describes the task: ### Input: Gets the user enter max and min values of where the raster points should appear on the y-axis :returns: (float, float) -- (min, max) y-values to bound the raster plot by ### Response: def values(self): """Gets the user enter...
def _integrate(self, time_steps, capture_elements, return_timestamps): """ Performs euler integration Parameters ---------- time_steps: iterable the time steps that the integrator progresses over capture_elements: list which model elements to capt...
Performs euler integration Parameters ---------- time_steps: iterable the time steps that the integrator progresses over capture_elements: list which model elements to capture - uses pysafe names return_timestamps: which subset of 'timesteps' ...
Below is the the instruction that describes the task: ### Input: Performs euler integration Parameters ---------- time_steps: iterable the time steps that the integrator progresses over capture_elements: list which model elements to capture - uses pysafe name...
def mslike(pop, **kwargs): """ Function to establish default parameters for a single-locus simulation for standard pop-gen modeling scenarios. :params pop: An instance of :class:`fwdpy11.DiploidPopulation` :params kwargs: Keyword arguments. """ import fwdpy11 if isinstance(pop, fwdp...
Function to establish default parameters for a single-locus simulation for standard pop-gen modeling scenarios. :params pop: An instance of :class:`fwdpy11.DiploidPopulation` :params kwargs: Keyword arguments.
Below is the the instruction that describes the task: ### Input: Function to establish default parameters for a single-locus simulation for standard pop-gen modeling scenarios. :params pop: An instance of :class:`fwdpy11.DiploidPopulation` :params kwargs: Keyword arguments. ### Response: def mslik...
def var_set(session, **kwargs): """ Sets the given variables or prints the current ones. "set answer=42" """ if not kwargs: for name, value in session.variables.items(): session.write_line("{0}={1}".format(name, value)) else: for name, valu...
Sets the given variables or prints the current ones. "set answer=42"
Below is the the instruction that describes the task: ### Input: Sets the given variables or prints the current ones. "set answer=42" ### Response: def var_set(session, **kwargs): """ Sets the given variables or prints the current ones. "set answer=42" """ if not kwargs: ...
def result(self, state, action): '''Return the resulting state after moving a piece to the empty space. (the "action" parameter contains the piece to move) ''' rows = string_to_list(state) row_e, col_e = find_location(rows, 'e') row_n, col_n = find_location(rows, actio...
Return the resulting state after moving a piece to the empty space. (the "action" parameter contains the piece to move)
Below is the the instruction that describes the task: ### Input: Return the resulting state after moving a piece to the empty space. (the "action" parameter contains the piece to move) ### Response: def result(self, state, action): '''Return the resulting state after moving a piece to the empty ...
def _createGaVariantAnnotation(self): """ Convenience method to set the common fields in a GA VariantAnnotation object from this variant set. """ ret = protocol.VariantAnnotation() ret.created = self._creationTime ret.variant_annotation_set_id = self.getId() ...
Convenience method to set the common fields in a GA VariantAnnotation object from this variant set.
Below is the the instruction that describes the task: ### Input: Convenience method to set the common fields in a GA VariantAnnotation object from this variant set. ### Response: def _createGaVariantAnnotation(self): """ Convenience method to set the common fields in a GA VariantAnnotation ...
def sigfig_str(number, sigfig): """ References: http://stackoverflow.com/questions/2663612/nicely-repr-float-in-python """ assert(sigfig > 0) try: d = decimal.Decimal(number) except TypeError: d = float_to_decimal(float(number)) sign, digits, exponent = d.as_tuple() ...
References: http://stackoverflow.com/questions/2663612/nicely-repr-float-in-python
Below is the the instruction that describes the task: ### Input: References: http://stackoverflow.com/questions/2663612/nicely-repr-float-in-python ### Response: def sigfig_str(number, sigfig): """ References: http://stackoverflow.com/questions/2663612/nicely-repr-float-in-python """ ...
def cli(env, context_id, subnet_id, subnet_type, network_identifier): """Add a subnet to an IPSEC tunnel context. A subnet id may be specified to link to the existing tunnel context. Otherwise, a network identifier in CIDR notation should be specified, indicating that a subnet resource should first be...
Add a subnet to an IPSEC tunnel context. A subnet id may be specified to link to the existing tunnel context. Otherwise, a network identifier in CIDR notation should be specified, indicating that a subnet resource should first be created before associating it with the tunnel context. Note that this is...
Below is the the instruction that describes the task: ### Input: Add a subnet to an IPSEC tunnel context. A subnet id may be specified to link to the existing tunnel context. Otherwise, a network identifier in CIDR notation should be specified, indicating that a subnet resource should first be created...
def _compute_analysis_extent(self): """Compute the minimum extent between layers. This function will set the self._analysis_extent geometry using aggregation CRS or crs property. :return: A tuple with the status of the IF and an error message if needed. The stat...
Compute the minimum extent between layers. This function will set the self._analysis_extent geometry using aggregation CRS or crs property. :return: A tuple with the status of the IF and an error message if needed. The status is PREPARE_SUCCESS if everything was fine. ...
Below is the the instruction that describes the task: ### Input: Compute the minimum extent between layers. This function will set the self._analysis_extent geometry using aggregation CRS or crs property. :return: A tuple with the status of the IF and an error message if needed...
def cee_map_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map") name = ET.SubElement(cee_map, "name") name.text = kwargs.pop('name') callback = kwa...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def cee_map_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map") ...
def prune_non_existent_outputs(compound_match_query): """Remove non-existent outputs from each MatchQuery in the given CompoundMatchQuery. Each of the 2^n MatchQuery objects (except one) has been pruned to exclude some Traverse blocks, For each of these, remove the outputs (that have been implicitly pruned...
Remove non-existent outputs from each MatchQuery in the given CompoundMatchQuery. Each of the 2^n MatchQuery objects (except one) has been pruned to exclude some Traverse blocks, For each of these, remove the outputs (that have been implicitly pruned away) from each corresponding ConstructResult block. ...
Below is the the instruction that describes the task: ### Input: Remove non-existent outputs from each MatchQuery in the given CompoundMatchQuery. Each of the 2^n MatchQuery objects (except one) has been pruned to exclude some Traverse blocks, For each of these, remove the outputs (that have been implicitl...
def _get_fields(self, table_name, **kwargs): """return all the fields for the given schema""" ret = {} query_str = [] query_args = ['f', table_name] # I had to brush up on my join knowledge while writing this query # https://en.wikipedia.org/wiki/Join_(SQL) # ...
return all the fields for the given schema
Below is the the instruction that describes the task: ### Input: return all the fields for the given schema ### Response: def _get_fields(self, table_name, **kwargs): """return all the fields for the given schema""" ret = {} query_str = [] query_args = ['f', table_name] # I...
def compute_region_border(start, end): """ given the buffer start and end indices of a range, compute the border edges that should be drawn to enclose the range. this function currently assumes 0x10 length rows. the result is a dictionary from buffer index to Cell instance. the Cell instance ...
given the buffer start and end indices of a range, compute the border edges that should be drawn to enclose the range. this function currently assumes 0x10 length rows. the result is a dictionary from buffer index to Cell instance. the Cell instance has boolean properties "top", "bottom", "left", and...
Below is the the instruction that describes the task: ### Input: given the buffer start and end indices of a range, compute the border edges that should be drawn to enclose the range. this function currently assumes 0x10 length rows. the result is a dictionary from buffer index to Cell instance. ...
def size(self, units="MiB"): """ Returns the volume group size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. """ self.open() size = lvm_vg_get_size(self.handle) self.close()...
Returns the volume group size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB.
Below is the the instruction that describes the task: ### Input: Returns the volume group size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. ### Response: def size(self, units="MiB"): """ Returns the ...
def dispatch_queue(loader): # type: (DataLoader) -> None """ Given the current state of a Loader instance, perform a batch load from its current queue. """ # Take the current loader queue, replacing it with an empty queue. queue = loader._queue loader._queue = [] # If a maxBatchSize...
Given the current state of a Loader instance, perform a batch load from its current queue.
Below is the the instruction that describes the task: ### Input: Given the current state of a Loader instance, perform a batch load from its current queue. ### Response: def dispatch_queue(loader): # type: (DataLoader) -> None """ Given the current state of a Loader instance, perform a batch load ...
def _generate_base_lsid(self): """ Generates and returns a base LSID :return: """ domain = self._generate_domain() namespace = self._generate_namespace() # Return the base LSID return "urn:lsid:" + domain + ":" + namespace
Generates and returns a base LSID :return:
Below is the the instruction that describes the task: ### Input: Generates and returns a base LSID :return: ### Response: def _generate_base_lsid(self): """ Generates and returns a base LSID :return: """ domain = self._generate_domain() namespace = self._gene...
def compute_exit_code(config, exception=None): """Compute an exit code for mutmut mutation testing The following exit codes are available for mutmut: * 0 if all mutants were killed (OK_KILLED) * 1 if a fatal error occurred * 2 if one or more mutants survived (BAD_SURVIVED) * 4 if one or mor...
Compute an exit code for mutmut mutation testing The following exit codes are available for mutmut: * 0 if all mutants were killed (OK_KILLED) * 1 if a fatal error occurred * 2 if one or more mutants survived (BAD_SURVIVED) * 4 if one or more mutants timed out (BAD_TIMEOUT) * 8 if one or m...
Below is the the instruction that describes the task: ### Input: Compute an exit code for mutmut mutation testing The following exit codes are available for mutmut: * 0 if all mutants were killed (OK_KILLED) * 1 if a fatal error occurred * 2 if one or more mutants survived (BAD_SURVIVED) * ...
def delete(self): """ :: DELETE /:login/machines/:id/snapshots/:name Deletes the snapshot from the machine. """ _, r = self.machine.datacenter.request('DELETE', self.path) r.raise_for_status()
:: DELETE /:login/machines/:id/snapshots/:name Deletes the snapshot from the machine.
Below is the the instruction that describes the task: ### Input: :: DELETE /:login/machines/:id/snapshots/:name Deletes the snapshot from the machine. ### Response: def delete(self): """ :: DELETE /:login/machines/:id/snapshots/:name ...
def simxClearIntegerSignal(clientID, signalName, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' if (sys.version_info[0] == 3) and (type(signalName) is str): signalName=signalName.encode('utf-8') return c_ClearIntegerSignal(clien...
Please have a look at the function description/documentation in the V-REP user manual
Below is the the instruction that describes the task: ### Input: Please have a look at the function description/documentation in the V-REP user manual ### Response: def simxClearIntegerSignal(clientID, signalName, operationMode): ''' Please have a look at the function description/documentation in the V-REP...
def policy(self, observations): """ Calculate only action head for given state """ input_data = self.input_block(observations) policy_base_output = self.policy_backbone(input_data) policy_params = self.action_head(policy_base_output) return policy_params
Calculate only action head for given state
Below is the the instruction that describes the task: ### Input: Calculate only action head for given state ### Response: def policy(self, observations): """ Calculate only action head for given state """ input_data = self.input_block(observations) policy_base_output = self.policy_backbone(...
def create_key_file(service, key): """Create a file containing key.""" keyfile = _keyfile_path(service) if os.path.exists(keyfile): log('Keyfile exists at %s.' % keyfile, level=WARNING) return with open(keyfile, 'w') as fd: fd.write(key) log('Created new keyfile at %s.' % k...
Create a file containing key.
Below is the the instruction that describes the task: ### Input: Create a file containing key. ### Response: def create_key_file(service, key): """Create a file containing key.""" keyfile = _keyfile_path(service) if os.path.exists(keyfile): log('Keyfile exists at %s.' % keyfile, level=WARNING) ...
def load(self, model): """ Load all information from an experimental configuration file. Parameters ---------- model : cobra.Model The metabolic model under investigation. """ self.load_medium(model) self.load_essentiality(model) self...
Load all information from an experimental configuration file. Parameters ---------- model : cobra.Model The metabolic model under investigation.
Below is the the instruction that describes the task: ### Input: Load all information from an experimental configuration file. Parameters ---------- model : cobra.Model The metabolic model under investigation. ### Response: def load(self, model): """ Load all in...
def xray_driver_removed_handler(self, unused_channel, data): """Handle a notification that a driver has been removed. Args: unused_channel: The message channel. data: The message data. """ gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( ...
Handle a notification that a driver has been removed. Args: unused_channel: The message channel. data: The message data.
Below is the the instruction that describes the task: ### Input: Handle a notification that a driver has been removed. Args: unused_channel: The message channel. data: The message data. ### Response: def xray_driver_removed_handler(self, unused_channel, data): """Handle a n...
def svg_to_clipboard(string): """ Copy a SVG document to the clipboard. Parameters: ----------- string : basestring A Python string containing a SVG document. """ if isinstance(string, unicode): string = string.encode('utf-8') mime_data = QtCore.QMimeData() mime_data.se...
Copy a SVG document to the clipboard. Parameters: ----------- string : basestring A Python string containing a SVG document.
Below is the the instruction that describes the task: ### Input: Copy a SVG document to the clipboard. Parameters: ----------- string : basestring A Python string containing a SVG document. ### Response: def svg_to_clipboard(string): """ Copy a SVG document to the clipboard. Parameter...
def search_for_subject(self, subject, timeout=None, content_type=None): """ Get content of emails, sent to a specific email address. @Params email - the recipient email address to search for timeout - seconds to try beore timing out content_type - type of email string to ...
Get content of emails, sent to a specific email address. @Params email - the recipient email address to search for timeout - seconds to try beore timing out content_type - type of email string to return @Returns Content of the matched email in the given content type
Below is the the instruction that describes the task: ### Input: Get content of emails, sent to a specific email address. @Params email - the recipient email address to search for timeout - seconds to try beore timing out content_type - type of email string to return @Returns...
def _set_default_refdata(): """Default refdata set on import.""" global GRAPHTABLE, COMPTABLE, THERMTABLE, PRIMARY_AREA # Component tables are defined here. try: GRAPHTABLE = _refTable(os.path.join('mtab','*_tmg.fits')) COMPTABLE = _refTable(os.path.join('mtab','*_tmc.fits')) excep...
Default refdata set on import.
Below is the the instruction that describes the task: ### Input: Default refdata set on import. ### Response: def _set_default_refdata(): """Default refdata set on import.""" global GRAPHTABLE, COMPTABLE, THERMTABLE, PRIMARY_AREA # Component tables are defined here. try: GRAPHTABLE = _refT...
def calc_effective_diffusivity(self, inlets=None, outlets=None, domain_area=None, domain_length=None): r""" This calculates the effective diffusivity in this linear transport algorithm. Parameters ---------- inlets : array_like ...
r""" This calculates the effective diffusivity in this linear transport algorithm. Parameters ---------- inlets : array_like The pores where the inlet composition boundary conditions were applied. If not given an attempt is made to infer them from the ...
Below is the the instruction that describes the task: ### Input: r""" This calculates the effective diffusivity in this linear transport algorithm. Parameters ---------- inlets : array_like The pores where the inlet composition boundary conditions were ...
def showMessage(self, level, message): """ Logs the inputed message for the given level. This will update both the feedback label and the details widget. :param level | <int> message | <str> """ self.uiFeedbackLBL.setText(messa...
Logs the inputed message for the given level. This will update both the feedback label and the details widget. :param level | <int> message | <str>
Below is the the instruction that describes the task: ### Input: Logs the inputed message for the given level. This will update both the feedback label and the details widget. :param level | <int> message | <str> ### Response: def showMessage(self, level, me...
def cxx_loop(visit): """ Decorator for loop node (For and While) to handle "else" branching. Decorated node will save flags for a goto statement used instead of usual break and add this flag at the end of the else statements. Examples -------- >> for i in xrange(12): >> if i == 5: ...
Decorator for loop node (For and While) to handle "else" branching. Decorated node will save flags for a goto statement used instead of usual break and add this flag at the end of the else statements. Examples -------- >> for i in xrange(12): >> if i == 5: >> break >> else:...
Below is the the instruction that describes the task: ### Input: Decorator for loop node (For and While) to handle "else" branching. Decorated node will save flags for a goto statement used instead of usual break and add this flag at the end of the else statements. Examples -------- >> for i i...
def _on_response_message(self, sequence, topic, message): """Process a response message received Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself """ ...
Process a response message received Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself
Below is the the instruction that describes the task: ### Input: Process a response message received Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself ### Response: ...
def _mmc_loop(self, rounds, max_angle, max_distance, temp=298.15, stop_when=None, verbose=True): """The main Metropolis Monte Carlo loop.""" current_round = 0 while current_round < rounds: working_model = copy.deepcopy(self.polypeptide) random_vector = u...
The main Metropolis Monte Carlo loop.
Below is the the instruction that describes the task: ### Input: The main Metropolis Monte Carlo loop. ### Response: def _mmc_loop(self, rounds, max_angle, max_distance, temp=298.15, stop_when=None, verbose=True): """The main Metropolis Monte Carlo loop.""" current_round = 0 ...
def make_tophat_ee (lower, upper): """Return a ufunc-like tophat function on the defined range, left-exclusive and right-exclusive. Returns 1 if lower < x < upper, 0 otherwise. """ if not np.isfinite (lower): raise ValueError ('"lower" argument must be finite number; got %r' % lower) if not...
Return a ufunc-like tophat function on the defined range, left-exclusive and right-exclusive. Returns 1 if lower < x < upper, 0 otherwise.
Below is the the instruction that describes the task: ### Input: Return a ufunc-like tophat function on the defined range, left-exclusive and right-exclusive. Returns 1 if lower < x < upper, 0 otherwise. ### Response: def make_tophat_ee (lower, upper): """Return a ufunc-like tophat function on the defined ...
def __scale_axes(axes, ax_type, which): '''Set the axis scaling''' kwargs = dict() if which == 'x': thresh = 'linthreshx' base = 'basex' scale = 'linscalex' scaler = axes.set_xscale limit = axes.set_xlim else: thresh = 'linthreshy' base = 'basey' ...
Set the axis scaling
Below is the the instruction that describes the task: ### Input: Set the axis scaling ### Response: def __scale_axes(axes, ax_type, which): '''Set the axis scaling''' kwargs = dict() if which == 'x': thresh = 'linthreshx' base = 'basex' scale = 'linscalex' scaler = axes...
def encode_header(cls, fin, opcode, mask, length, flags): """ Encodes a WebSocket header. :param fin: Whether this is the final frame for this opcode. :param opcode: The opcode of the payload, see `OPCODE_*` :param mask: Whether the payload is masked. :param length: The ...
Encodes a WebSocket header. :param fin: Whether this is the final frame for this opcode. :param opcode: The opcode of the payload, see `OPCODE_*` :param mask: Whether the payload is masked. :param length: The length of the frame. :param flags: The RSV* flags. :return: A ...
Below is the the instruction that describes the task: ### Input: Encodes a WebSocket header. :param fin: Whether this is the final frame for this opcode. :param opcode: The opcode of the payload, see `OPCODE_*` :param mask: Whether the payload is masked. :param length: The length of...
def dict_sequence(self, node, keep_var_ambigs=False): """ For VCF-based TreeAnc objects, we do not want to store the entire sequence on every node, as they could be large. Instead, this returns the dict of variants & their positions for this sequence. This is used in place of :py...
For VCF-based TreeAnc objects, we do not want to store the entire sequence on every node, as they could be large. Instead, this returns the dict of variants & their positions for this sequence. This is used in place of :py:meth:`treetime.TreeAnc.expanded_sequence` for VCF-based objects throughou...
Below is the the instruction that describes the task: ### Input: For VCF-based TreeAnc objects, we do not want to store the entire sequence on every node, as they could be large. Instead, this returns the dict of variants & their positions for this sequence. This is used in place of :py:meth...
def estimate_threshold(in1, edge_excl=0, int_excl=0): """ This function estimates the noise using the MAD estimator. INPUTS: in1 (no default): The array from which the noise is estimated OUTPUTS: out1 An array of per-scale noise estimates. """ ...
This function estimates the noise using the MAD estimator. INPUTS: in1 (no default): The array from which the noise is estimated OUTPUTS: out1 An array of per-scale noise estimates.
Below is the the instruction that describes the task: ### Input: This function estimates the noise using the MAD estimator. INPUTS: in1 (no default): The array from which the noise is estimated OUTPUTS: out1 An array of per-scale noise estimates. ### Respon...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'enabled') and self.enabled is not None: _dict['enabled'] = self.enabled if hasattr(self, 'time_zone') and self.time_zone is not None: _dict['time_zone'] = self...
Return a json dictionary representing this model.
Below is the the instruction that describes the task: ### Input: Return a json dictionary representing this model. ### Response: def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'enabled') and self.enabled is not None: _dict...
def initialize_repo(self): """ Clones repository & sets up usernames. """ logging.info('Repo {} doesn\'t exist. Cloning...'.format(self.repo_dir)) clone_args = ['git', 'clone'] if self.depth and self.depth > 0: clone_args.extend(['--depth', str(self.depth)]) ...
Clones repository & sets up usernames.
Below is the the instruction that describes the task: ### Input: Clones repository & sets up usernames. ### Response: def initialize_repo(self): """ Clones repository & sets up usernames. """ logging.info('Repo {} doesn\'t exist. Cloning...'.format(self.repo_dir)) clone_arg...
def getrawblob(self, project_id, sha1): """ Get the raw file contents for a blob by blob SHA. :param project_id: The ID of a project :param sha1: the commit sha :return: raw blob """ request = requests.get( '{0}/{1}/repository/raw_blobs/{2}'.format(se...
Get the raw file contents for a blob by blob SHA. :param project_id: The ID of a project :param sha1: the commit sha :return: raw blob
Below is the the instruction that describes the task: ### Input: Get the raw file contents for a blob by blob SHA. :param project_id: The ID of a project :param sha1: the commit sha :return: raw blob ### Response: def getrawblob(self, project_id, sha1): """ Get the raw file...
def get_abbreviations(self): """ Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available). """ abbreviations = [] try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" ...
Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available).
Below is the the instruction that describes the task: ### Input: Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available). ### Response: def get_abbreviations(self): """ Get abbreviations of the names of the author. :retur...
def apply_function(self, func): """Apply a function to all grid_stack in the grid-stack. This is used by the *ray-tracing* module to easily apply tracing operations to all grid_stack.""" if self.blurring is not None and self.pix is not None: return GridStack(func(self.regula...
Apply a function to all grid_stack in the grid-stack. This is used by the *ray-tracing* module to easily apply tracing operations to all grid_stack.
Below is the the instruction that describes the task: ### Input: Apply a function to all grid_stack in the grid-stack. This is used by the *ray-tracing* module to easily apply tracing operations to all grid_stack. ### Response: def apply_function(self, func): """Apply a function to all gri...
def get_method_descriptor(self, class_name, method_name, descriptor): """ Return the specific method :param class_name: the class name of the method :type class_name: string :param method_name: the name of the method :type method_name: string :param descriptor: t...
Return the specific method :param class_name: the class name of the method :type class_name: string :param method_name: the name of the method :type method_name: string :param descriptor: the descriptor of the method :type descriptor: string :rtype: None or a :c...
Below is the the instruction that describes the task: ### Input: Return the specific method :param class_name: the class name of the method :type class_name: string :param method_name: the name of the method :type method_name: string :param descriptor: the descriptor of the ...
def _generate_examples(self, file_id, extracted_dirs): """Yields examples.""" filedir = os.path.join(extracted_dirs["img_align_celeba"], "img_align_celeba") img_list_path = extracted_dirs["list_eval_partition"] landmarks_path = extracted_dirs["landmarks_celeba"] attr_path ...
Yields examples.
Below is the the instruction that describes the task: ### Input: Yields examples. ### Response: def _generate_examples(self, file_id, extracted_dirs): """Yields examples.""" filedir = os.path.join(extracted_dirs["img_align_celeba"], "img_align_celeba") img_list_path = extract...
def _is_ndb(self): """Determine whether the model of the instance is an NDB model. Returns: Boolean indicating whether or not the model is an NDB or DB model. """ # issubclass will fail if one of the arguments is not a class, only # need worry about new-style classes...
Determine whether the model of the instance is an NDB model. Returns: Boolean indicating whether or not the model is an NDB or DB model.
Below is the the instruction that describes the task: ### Input: Determine whether the model of the instance is an NDB model. Returns: Boolean indicating whether or not the model is an NDB or DB model. ### Response: def _is_ndb(self): """Determine whether the model of the instance is a...
def settings(self, key=None, section=None): """The settings overridden from the wandb/settings file. Args: key (str, optional): If provided only this setting is returned section (str, optional): If provided this section of the setting file is used, defaults to "defau...
The settings overridden from the wandb/settings file. Args: key (str, optional): If provided only this setting is returned section (str, optional): If provided this section of the setting file is used, defaults to "default" Returns: A dict with the curre...
Below is the the instruction that describes the task: ### Input: The settings overridden from the wandb/settings file. Args: key (str, optional): If provided only this setting is returned section (str, optional): If provided this section of the setting file is used, defa...
def _run_lint_on_file_stamped_args(file_path, # suppress(too-many-arguments) stamp_file_path, log_technical_terms_to, linter_functions, tool_options, ...
Return tuple of args and kwargs that function would be called with.
Below is the the instruction that describes the task: ### Input: Return tuple of args and kwargs that function would be called with. ### Response: def _run_lint_on_file_stamped_args(file_path, # suppress(too-many-arguments) stamp_file_path, log...
def make_energy_bounds_hdu(self, extname="EBOUNDS"): """ Builds and returns a FITs HDU with the energy bin boundries extname : The HDU extension name """ if self._ebins is None: return None cols = [fits.Column("CHANNEL", "I", array=np.arange(1, len(self...
Builds and returns a FITs HDU with the energy bin boundries extname : The HDU extension name
Below is the the instruction that describes the task: ### Input: Builds and returns a FITs HDU with the energy bin boundries extname : The HDU extension name ### Response: def make_energy_bounds_hdu(self, extname="EBOUNDS"): """ Builds and returns a FITs HDU with the energy bin boundries ...
def to_bytes(self): """Convert the entire image to bytes. :rtype: bytes """ # grab the chunks we needs out = [PNG_SIGN] # FIXME: it's tricky to define "other_chunks". HoneyView stop the # animation if it sees chunks other than fctl or idat, so we put other # chunks to the end of the file other_...
Convert the entire image to bytes. :rtype: bytes
Below is the the instruction that describes the task: ### Input: Convert the entire image to bytes. :rtype: bytes ### Response: def to_bytes(self): """Convert the entire image to bytes. :rtype: bytes """ # grab the chunks we needs out = [PNG_SIGN] # FIXME: it's tricky to define "other_chunks...
def close(self): """ Close internal connection to AMQP if connected. """ if self.connection: logging.info("Closing connection to {}.".format(self.host)) self.connection.close() self.connection = None
Close internal connection to AMQP if connected.
Below is the the instruction that describes the task: ### Input: Close internal connection to AMQP if connected. ### Response: def close(self): """ Close internal connection to AMQP if connected. """ if self.connection: logging.info("Closing connection to {}.".format(sel...
def _convert_html_to_csv( self): """ *contert html to csv* **Key Arguments:** # - **Return:** - None .. todo:: - @review: when complete, clean _convert_html_to_csv method - @review: when complete add logging ...
*contert html to csv* **Key Arguments:** # - **Return:** - None .. todo:: - @review: when complete, clean _convert_html_to_csv method - @review: when complete add logging
Below is the the instruction that describes the task: ### Input: *contert html to csv* **Key Arguments:** # - **Return:** - None .. todo:: - @review: when complete, clean _convert_html_to_csv method - @review: when complete add logging ### ...
def get_gz_cn(offset: int) -> str: """Get n-th(0-based) GanZhi """ return TextUtils.STEMS[offset % 10] + TextUtils.BRANCHES[offset % 12]
Get n-th(0-based) GanZhi
Below is the the instruction that describes the task: ### Input: Get n-th(0-based) GanZhi ### Response: def get_gz_cn(offset: int) -> str: """Get n-th(0-based) GanZhi """ return TextUtils.STEMS[offset % 10] + TextUtils.BRANCHES[offset % 12]
def unpack_ext(ext_path): ''' Unpack the external modules. ''' modcache = os.path.join( OPTIONS.saltdir, 'running_data', 'var', 'cache', 'salt', 'minion', 'extmods') tfile = tarfile.TarFile.gzopen(ext_path) old_u...
Unpack the external modules.
Below is the the instruction that describes the task: ### Input: Unpack the external modules. ### Response: def unpack_ext(ext_path): ''' Unpack the external modules. ''' modcache = os.path.join( OPTIONS.saltdir, 'running_data', 'var', 'cache', ...
def damping_maintain_sign(x, step, damping=1.0, factor=0.5): '''Famping function which will maintain the sign of the variable being manipulated. If the step puts it at the other sign, the distance between `x` and `step` will be shortened by the multiple of `factor`; i.e. if factor is `x`, the new value...
Famping function which will maintain the sign of the variable being manipulated. If the step puts it at the other sign, the distance between `x` and `step` will be shortened by the multiple of `factor`; i.e. if factor is `x`, the new value of `x` will be 0 exactly. The provided `damping` is applie...
Below is the the instruction that describes the task: ### Input: Famping function which will maintain the sign of the variable being manipulated. If the step puts it at the other sign, the distance between `x` and `step` will be shortened by the multiple of `factor`; i.e. if factor is `x`, the new valu...
def _decode_temp(byte_1, byte_2): """Decode a signed short temperature as two bytes to a single number.""" temp = (byte_1 << 8) + byte_2 if (temp > 32767): temp = temp - 65536 temp = temp / 10 return temp
Decode a signed short temperature as two bytes to a single number.
Below is the the instruction that describes the task: ### Input: Decode a signed short temperature as two bytes to a single number. ### Response: def _decode_temp(byte_1, byte_2): """Decode a signed short temperature as two bytes to a single number.""" temp = (byte_1 << 8) + byte_2 if (temp...
def encode(self): ''' Encode and store an UNSUBCRIBE control packet @raise e: C{ValueError} if any encoded topic string exceeds 65535 bytes ''' header = bytearray(1) payload = bytearray() varHeader = encode16Int(self.msgId) header[0] = 0xA2 # packe...
Encode and store an UNSUBCRIBE control packet @raise e: C{ValueError} if any encoded topic string exceeds 65535 bytes
Below is the the instruction that describes the task: ### Input: Encode and store an UNSUBCRIBE control packet @raise e: C{ValueError} if any encoded topic string exceeds 65535 bytes ### Response: def encode(self): ''' Encode and store an UNSUBCRIBE control packet @raise e: C{ValueE...
def replies(self, tweet, recursive=False, prune=()): """ replies returns a generator of tweets that are replies for a given tweet. It includes the original tweet. If you would like to fetch the replies to the replies use recursive=True which will do a depth-first recursive walk o...
replies returns a generator of tweets that are replies for a given tweet. It includes the original tweet. If you would like to fetch the replies to the replies use recursive=True which will do a depth-first recursive walk of the replies. It also walk up the reply chain if you supply a tw...
Below is the the instruction that describes the task: ### Input: replies returns a generator of tweets that are replies for a given tweet. It includes the original tweet. If you would like to fetch the replies to the replies use recursive=True which will do a depth-first recursive walk of th...
def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``. """ for d in dict_list: ...
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``.
Below is the the instruction that describes the task: ### Input: Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``. ### Response: def dictlist_convert_to_string(dict_list: ...
def pyfs_storage_factory(fileinstance=None, default_location=None, default_storage_class=None, filestorage_class=PyFSFileStorage, fileurl=None, size=None, modified=None, clean_dir=True): """Get factory function for creating a PyFS file stora...
Get factory function for creating a PyFS file storage instance.
Below is the the instruction that describes the task: ### Input: Get factory function for creating a PyFS file storage instance. ### Response: def pyfs_storage_factory(fileinstance=None, default_location=None, default_storage_class=None, filestorage_class=PyFSFileS...
def compare_to_rm(data): """Compare final variant calls against reference materials of known calls. """ if isinstance(data, (list, tuple)) and cwlutils.is_cwl_run(utils.to_single_data(data[0])): data = _normalize_cwl_inputs(data) toval_data = _get_validate(data) toval_data = cwlutils.unpack_...
Compare final variant calls against reference materials of known calls.
Below is the the instruction that describes the task: ### Input: Compare final variant calls against reference materials of known calls. ### Response: def compare_to_rm(data): """Compare final variant calls against reference materials of known calls. """ if isinstance(data, (list, tuple)) and cwlutils....
def transform_txn_for_ledger(txn): """ Some transactions need to be transformed before they can be stored in the ledger, eg. storing certain payload in another data store and only its hash in the ledger """ if get_type(txn) == ATTRIB: txn = DomainReqHandler.tr...
Some transactions need to be transformed before they can be stored in the ledger, eg. storing certain payload in another data store and only its hash in the ledger
Below is the the instruction that describes the task: ### Input: Some transactions need to be transformed before they can be stored in the ledger, eg. storing certain payload in another data store and only its hash in the ledger ### Response: def transform_txn_for_ledger(txn): """ S...
def run_mhc_gene_assessment(job, rsem_files, rna_haplotype, univ_options, reports_options): """ A wrapper for assess_mhc_genes. :param dict rsem_files: Results from running rsem :param str rna_haplotype: The job store id for the rna haplotype file :param dict univ_options: Dict of universal options...
A wrapper for assess_mhc_genes. :param dict rsem_files: Results from running rsem :param str rna_haplotype: The job store id for the rna haplotype file :param dict univ_options: Dict of universal options used by almost all tools :param dict reports_options: Options specific to reporting modules :re...
Below is the the instruction that describes the task: ### Input: A wrapper for assess_mhc_genes. :param dict rsem_files: Results from running rsem :param str rna_haplotype: The job store id for the rna haplotype file :param dict univ_options: Dict of universal options used by almost all tools :para...
def __compress_attributes(self, dic): """ This will convert all attributes that are list with only one item string into simple string. It seems that LDAP always return lists, even when it doesn t make sense. :param dic: :return: """ result = {} for k, v i...
This will convert all attributes that are list with only one item string into simple string. It seems that LDAP always return lists, even when it doesn t make sense. :param dic: :return:
Below is the the instruction that describes the task: ### Input: This will convert all attributes that are list with only one item string into simple string. It seems that LDAP always return lists, even when it doesn t make sense. :param dic: :return: ### Response: def __compress_attribute...
def initStats(self, extras=None): """Query and parse Web Server Status Page. @param extras: Include extra metrics, which can be computationally more expensive. """ url = "%s://%s:%d/%s" % (self._proto, self._host, self._port, self._monpath) ...
Query and parse Web Server Status Page. @param extras: Include extra metrics, which can be computationally more expensive.
Below is the the instruction that describes the task: ### Input: Query and parse Web Server Status Page. @param extras: Include extra metrics, which can be computationally more expensive. ### Response: def initStats(self, extras=None): """Query and parse Web Server ...
def avgwave(self): """Calculate :ref:`pysynphot-formula-avgwv`. Returns ------- ans : float Average wavelength. """ mywaveunits = self.waveunits.name self.convert('angstroms') wave = self.wave thru = self.throughput self.conv...
Calculate :ref:`pysynphot-formula-avgwv`. Returns ------- ans : float Average wavelength.
Below is the the instruction that describes the task: ### Input: Calculate :ref:`pysynphot-formula-avgwv`. Returns ------- ans : float Average wavelength. ### Response: def avgwave(self): """Calculate :ref:`pysynphot-formula-avgwv`. Returns ------- ...
def createSomeItems(store, itemType, values, counter): """ Create some instances of a particular type in a store. """ for i in counter: itemType(store=store, **values)
Create some instances of a particular type in a store.
Below is the the instruction that describes the task: ### Input: Create some instances of a particular type in a store. ### Response: def createSomeItems(store, itemType, values, counter): """ Create some instances of a particular type in a store. """ for i in counter: itemType(store=store,...
def mkApplications(location, *atoms): """Make a sequence of applications from a list of tokens. atoms is a list of atoms, which will be handled left-associatively. E.g: ['foo', [], []] == foo()() ==> Application(Application('foo', []), []) """ atoms = list(atoms) while len(atoms) > 1: atoms[0:2] =...
Make a sequence of applications from a list of tokens. atoms is a list of atoms, which will be handled left-associatively. E.g: ['foo', [], []] == foo()() ==> Application(Application('foo', []), [])
Below is the the instruction that describes the task: ### Input: Make a sequence of applications from a list of tokens. atoms is a list of atoms, which will be handled left-associatively. E.g: ['foo', [], []] == foo()() ==> Application(Application('foo', []), []) ### Response: def mkApplications(location...