code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def derive_coordinates(self): """ Depending on the compilation source, some members of the SourceRef object may be incomplete. Calling this function performs the necessary derivations to complete the object. """ if self._coordinates_resolved: # Coordi...
Depending on the compilation source, some members of the SourceRef object may be incomplete. Calling this function performs the necessary derivations to complete the object.
Below is the the instruction that describes the task: ### Input: Depending on the compilation source, some members of the SourceRef object may be incomplete. Calling this function performs the necessary derivations to complete the object. ### Response: def derive_coordinates(self): ...
def create(cls, object_type=None, object_uuid=None, **kwargs): """Create a new record identifier. Note: if the object_type and object_uuid values are passed, then the PID status will be automatically setted to :attr:`invenio_pidstore.models.PIDStatus.REGISTERED`. :param object_...
Create a new record identifier. Note: if the object_type and object_uuid values are passed, then the PID status will be automatically setted to :attr:`invenio_pidstore.models.PIDStatus.REGISTERED`. :param object_type: The object type. (Default: None.) :param object_uuid: The ob...
Below is the the instruction that describes the task: ### Input: Create a new record identifier. Note: if the object_type and object_uuid values are passed, then the PID status will be automatically setted to :attr:`invenio_pidstore.models.PIDStatus.REGISTERED`. :param object_type:...
def to_gds(self, multiplier): """ Convert this object to a series of GDSII elements. Parameters ---------- multiplier : number A number that multiplies all dimensions written in the GDSII elements. Returns ------- out : string ...
Convert this object to a series of GDSII elements. Parameters ---------- multiplier : number A number that multiplies all dimensions written in the GDSII elements. Returns ------- out : string The GDSII binary string that represents t...
Below is the the instruction that describes the task: ### Input: Convert this object to a series of GDSII elements. Parameters ---------- multiplier : number A number that multiplies all dimensions written in the GDSII elements. Returns ------- ...
def get(self, name, typ): """ Gets a counter specified by its name. It counter does not exist or its type doesn't match the specified type it creates a new one. :param name: a counter name to retrieve. :param typ: a counter type. :return: an existing or newly c...
Gets a counter specified by its name. It counter does not exist or its type doesn't match the specified type it creates a new one. :param name: a counter name to retrieve. :param typ: a counter type. :return: an existing or newly created counter of the specified type.
Below is the the instruction that describes the task: ### Input: Gets a counter specified by its name. It counter does not exist or its type doesn't match the specified type it creates a new one. :param name: a counter name to retrieve. :param typ: a counter type. :return:...
def start(self): """Starts the delayed execution""" if self._timer: self._timer.cancel() self._timer = Timer(self._timeout, self._fire) self._timer.start()
Starts the delayed execution
Below is the the instruction that describes the task: ### Input: Starts the delayed execution ### Response: def start(self): """Starts the delayed execution""" if self._timer: self._timer.cancel() self._timer = Timer(self._timeout, self._fire) self._timer.start()
def percentile(self, p): """ Computes the percentile of a specific value in [0,100]. """ if not (0 <= p <= 100): raise ValueError("p must be between 0 and 100, inclusive.") p = float(p)/100. p *= self.n c_i = None t = 0 if p == 0: ...
Computes the percentile of a specific value in [0,100].
Below is the the instruction that describes the task: ### Input: Computes the percentile of a specific value in [0,100]. ### Response: def percentile(self, p): """ Computes the percentile of a specific value in [0,100]. """ if not (0 <= p <= 100): raise ValueError("p mu...
def _ConvertStructMessage(value, message): """Convert a JSON representation into Struct message.""" if not isinstance(value, dict): raise ParseError( 'Struct must be in a dict which is {0}.'.format(value)) for key in value: _ConvertValueMessage(value[key], message.fields[key]) return
Convert a JSON representation into Struct message.
Below is the the instruction that describes the task: ### Input: Convert a JSON representation into Struct message. ### Response: def _ConvertStructMessage(value, message): """Convert a JSON representation into Struct message.""" if not isinstance(value, dict): raise ParseError( 'Struct must be in ...
def _plot_rprof_list(sdat, lovs, rprofs, metas, stepstr, rads=None): """Plot requested profiles""" if rads is None: rads = {} for vfig in lovs: fig, axes = plt.subplots(ncols=len(vfig), sharey=True) axes = [axes] if len(vfig) == 1 else axes fname = 'rprof_' for iplt, ...
Plot requested profiles
Below is the the instruction that describes the task: ### Input: Plot requested profiles ### Response: def _plot_rprof_list(sdat, lovs, rprofs, metas, stepstr, rads=None): """Plot requested profiles""" if rads is None: rads = {} for vfig in lovs: fig, axes = plt.subplots(ncols=len(vfig)...
def unescape(value): """ Inverse of escape. """ pattern = ESCAPE_FMT.replace('%02X', '(?P<code>[0-9A-Fa-f]{2})') # the pattern must be bytes to operate on bytes pattern_bytes = pattern.encode('ascii') re_esc = re.compile(pattern_bytes) return re_esc.sub(_unescape_code, value.encode('asci...
Inverse of escape.
Below is the the instruction that describes the task: ### Input: Inverse of escape. ### Response: def unescape(value): """ Inverse of escape. """ pattern = ESCAPE_FMT.replace('%02X', '(?P<code>[0-9A-Fa-f]{2})') # the pattern must be bytes to operate on bytes pattern_bytes = pattern.encode('...
def _getFromDate(l, date): ''' returns the index of given or best fitting date ''' try: date = _toDate(date) i = _insertDateIndex(date, l) - 1 if i == -1: return l[0] return l[i] except (ValueError, TypeError): # ValueError: date invalid...
returns the index of given or best fitting date
Below is the the instruction that describes the task: ### Input: returns the index of given or best fitting date ### Response: def _getFromDate(l, date): ''' returns the index of given or best fitting date ''' try: date = _toDate(date) i = _insertDateIndex(date, l) - 1 ...
def validate_clabe(clabe: str) -> bool: """ Validate CLABE according to https://es.wikipedia.org/wiki/CLABE#D.C3.ADgito_control """ return (clabe.isdigit() and len(clabe) == CLABE_LENGTH and clabe[:3] in BANKS.keys() and clabe[-1] == compute_control_digit(clabe))
Validate CLABE according to https://es.wikipedia.org/wiki/CLABE#D.C3.ADgito_control
Below is the the instruction that describes the task: ### Input: Validate CLABE according to https://es.wikipedia.org/wiki/CLABE#D.C3.ADgito_control ### Response: def validate_clabe(clabe: str) -> bool: """ Validate CLABE according to https://es.wikipedia.org/wiki/CLABE#D.C3.ADgito_control """ ...
def get_kind(self): """ Return the 'kind' argument of the instruction :rtype: int """ if self.OP > 0xff: if self.OP >= 0xf2ff: return DALVIK_OPCODES_OPTIMIZED[self.OP][1][1] return DALVIK_OPCODES_EXTENDED_WIDTH[self.OP][1][1] retur...
Return the 'kind' argument of the instruction :rtype: int
Below is the the instruction that describes the task: ### Input: Return the 'kind' argument of the instruction :rtype: int ### Response: def get_kind(self): """ Return the 'kind' argument of the instruction :rtype: int """ if self.OP > 0xff: if self.OP ...
def cancel(self, job_ids): ''' Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False. ''' for job in job_ids: logger.debug("Terminating ...
Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False.
Below is the the instruction that describes the task: ### Input: Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False. ### Response: def cancel(self, job_ids): ...
def geometrize_stops(stops: List[str], *, use_utm: bool = False) -> DataFrame: """ Given a stops DataFrame, convert it to a GeoPandas GeoDataFrame and return the result. Parameters ---------- stops : DataFrame A GTFS stops table use_utm : boolean If ``True``, then convert th...
Given a stops DataFrame, convert it to a GeoPandas GeoDataFrame and return the result. Parameters ---------- stops : DataFrame A GTFS stops table use_utm : boolean If ``True``, then convert the output to local UTM coordinates; otherwise use WGS84 coordinates Returns ...
Below is the the instruction that describes the task: ### Input: Given a stops DataFrame, convert it to a GeoPandas GeoDataFrame and return the result. Parameters ---------- stops : DataFrame A GTFS stops table use_utm : boolean If ``True``, then convert the output to local UTM ...
def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': po...
List all floating IP pools .. versionadded:: 2016.3.0
Below is the the instruction that describes the task: ### Input: List all floating IP pools .. versionadded:: 2016.3.0 ### Response: def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn poo...
def authorization_url(self, client_id, redirect_uri, approval_prompt='auto', scope=None, state=None): """ Get the URL needed to authorize your application to access a Strava user's information. :param client_id: The numeric developer client id. :type client_id:...
Get the URL needed to authorize your application to access a Strava user's information. :param client_id: The numeric developer client id. :type client_id: int :param redirect_uri: The URL that Strava will redirect to after successful (or failed) authorization. :type redirect_uri: str ...
Below is the the instruction that describes the task: ### Input: Get the URL needed to authorize your application to access a Strava user's information. :param client_id: The numeric developer client id. :type client_id: int :param redirect_uri: The URL that Strava will redirect to after s...
def mapper(class_, local_table=None, id_attribute='id', slug_expression=None, *args, **kwargs): """ Convenience wrapper around the SA mapper which will set up the hybrid "id" and "slug" attributes required by everest after calling the SA mapper. If you (e.g., for testing purposes) want t...
Convenience wrapper around the SA mapper which will set up the hybrid "id" and "slug" attributes required by everest after calling the SA mapper. If you (e.g., for testing purposes) want to clear mappers created with this function, use the :func:`clear_mappers` function in this module. :param str ...
Below is the the instruction that describes the task: ### Input: Convenience wrapper around the SA mapper which will set up the hybrid "id" and "slug" attributes required by everest after calling the SA mapper. If you (e.g., for testing purposes) want to clear mappers created with this function, us...
def _match(self, p, value): """ Calls either _match_operator or _match_operand depending on the pattern (p) provided. """ if self._is_operator(p): return self._match_operator(p, value) else: try: if self._is_value_filter(p): ...
Calls either _match_operator or _match_operand depending on the pattern (p) provided.
Below is the the instruction that describes the task: ### Input: Calls either _match_operator or _match_operand depending on the pattern (p) provided. ### Response: def _match(self, p, value): """ Calls either _match_operator or _match_operand depending on the pattern (p) provided. """ ...
def get_standard_dicomdir_info(self): """ Read DICOMDIR, crate if necessary. :return: """ dicomdir_filepath = os.path.join(self.dirpath, self.standard_dicomdir_filename) if not os.path.exists(dicomdir_filepath): self.create_standard_dicomdir() return s...
Read DICOMDIR, crate if necessary. :return:
Below is the the instruction that describes the task: ### Input: Read DICOMDIR, crate if necessary. :return: ### Response: def get_standard_dicomdir_info(self): """ Read DICOMDIR, crate if necessary. :return: """ dicomdir_filepath = os.path.join(self.dirpath, self.st...
def reflect_db(self): """ No-op to reflect db info. This is available as a method so the database can be reflected outside initialization (such bootstrapping unihan during CLI usage). """ self.metadata.reflect(views=True, extend_existing=True) self.base = automap...
No-op to reflect db info. This is available as a method so the database can be reflected outside initialization (such bootstrapping unihan during CLI usage).
Below is the the instruction that describes the task: ### Input: No-op to reflect db info. This is available as a method so the database can be reflected outside initialization (such bootstrapping unihan during CLI usage). ### Response: def reflect_db(self): """ No-op to reflect db...
def retrieve(payment, refund_id): """ Retrieve a refund from a payment and the refund id. :param payment: The payment id or the payment object :type payment: resources.Payment|string :param refund_id: The refund id :type refund_id: string :return: The refund res...
Retrieve a refund from a payment and the refund id. :param payment: The payment id or the payment object :type payment: resources.Payment|string :param refund_id: The refund id :type refund_id: string :return: The refund resource :rtype: resources.Refund
Below is the the instruction that describes the task: ### Input: Retrieve a refund from a payment and the refund id. :param payment: The payment id or the payment object :type payment: resources.Payment|string :param refund_id: The refund id :type refund_id: string :return:...
def make_new_subdomain_history(self, cursor, subdomain_rec): """ Recalculate the history for this subdomain from genesis up until this record. Returns the list of subdomain records we need to save. """ # what's the subdomain's history up until this subdomain record? hist ...
Recalculate the history for this subdomain from genesis up until this record. Returns the list of subdomain records we need to save.
Below is the the instruction that describes the task: ### Input: Recalculate the history for this subdomain from genesis up until this record. Returns the list of subdomain records we need to save. ### Response: def make_new_subdomain_history(self, cursor, subdomain_rec): """ Recalculate th...
def has_segment_tables(xmldoc, name = None): """ Return True if the document contains a complete set of segment tables. Returns False otherwise. If name is given and not None then the return value is True only if the document's segment tables, if present, contain a segment list by that name. """ try: names =...
Return True if the document contains a complete set of segment tables. Returns False otherwise. If name is given and not None then the return value is True only if the document's segment tables, if present, contain a segment list by that name.
Below is the the instruction that describes the task: ### Input: Return True if the document contains a complete set of segment tables. Returns False otherwise. If name is given and not None then the return value is True only if the document's segment tables, if present, contain a segment list by that name. ##...
def kalman_filter(cls, p_A, p_Q, p_H, p_R, Y, index=None, m_init=None, P_init=None, p_kalman_filter_type='regular', calc_log_likelihood=False, calc_grad_log_likelihood=False, grad_params_no=None, grad_calc_params=None): """ ...
This function implements the basic Kalman Filter algorithm These notations for the State-Space model are assumed: x_{k} = A_{k} * x_{k-1} + q_{k-1}; q_{k-1} ~ N(0, Q_{k-1}) y_{k} = H_{k} * x_{k} + r_{k}; r_{k-1} ~ N(0, R_{k}) Returns estimated filter distributi...
Below is the the instruction that describes the task: ### Input: This function implements the basic Kalman Filter algorithm These notations for the State-Space model are assumed: x_{k} = A_{k} * x_{k-1} + q_{k-1}; q_{k-1} ~ N(0, Q_{k-1}) y_{k} = H_{k} * x_{k} + r_{k}; ...
def _parse_edge_weight(f, nodes): """Parse TSPLIB EDGE_WEIGHT_SECTION from file f Supports only FULL_MATRIX for now """ matrix = [] n = 0 for line in f: line = strip(line) regex = re.compile(r'\s+') row = regex.split(line) matrix.append(row) n = n +...
Parse TSPLIB EDGE_WEIGHT_SECTION from file f Supports only FULL_MATRIX for now
Below is the the instruction that describes the task: ### Input: Parse TSPLIB EDGE_WEIGHT_SECTION from file f Supports only FULL_MATRIX for now ### Response: def _parse_edge_weight(f, nodes): """Parse TSPLIB EDGE_WEIGHT_SECTION from file f Supports only FULL_MATRIX for now """ matrix = [] ...
def before(self): """Run This Middleware Before The Route Executes.""" user = self.request.user() if user and user.verified_at is None: self.request.redirect('/email/verify')
Run This Middleware Before The Route Executes.
Below is the the instruction that describes the task: ### Input: Run This Middleware Before The Route Executes. ### Response: def before(self): """Run This Middleware Before The Route Executes.""" user = self.request.user() if user and user.verified_at is None: self.request.red...
def logging_from_debugplot(debugplot): """Set debugging level based on debugplot value. Parameters ---------- debugplot : int Debugging level for messages and plots. For details see 'numina.array.display.pause_debugplot.py'. """ if isinstance(debugplot, int): if...
Set debugging level based on debugplot value. Parameters ---------- debugplot : int Debugging level for messages and plots. For details see 'numina.array.display.pause_debugplot.py'.
Below is the the instruction that describes the task: ### Input: Set debugging level based on debugplot value. Parameters ---------- debugplot : int Debugging level for messages and plots. For details see 'numina.array.display.pause_debugplot.py'. ### Response: def logging_from...
def static_checker(workflow_inputs, workflow_outputs, step_inputs, step_outputs, param_to_step): # type: (List[Dict[Text, Any]], List[Dict[Text, Any]], List[Dict[Text, Any]], List[Dict[Text, Any]], Dict[Text, Dict[Text, Any]]) -> None """Check if all source and sink types of a workflow are compatible before run...
Check if all source and sink types of a workflow are compatible before run time.
Below is the the instruction that describes the task: ### Input: Check if all source and sink types of a workflow are compatible before run time. ### Response: def static_checker(workflow_inputs, workflow_outputs, step_inputs, step_outputs, param_to_step): # type: (List[Dict[Text, Any]], List[Dict[Text, Any]],...
def create_snappy_message(message_set): """ Construct a Snappy-compressed message containing multiple messages The given messages will be encoded, compressed, and sent as a single atomic message to Kafka. :param list message_set: a list of :class:`Message` instances """ encoded_message_set...
Construct a Snappy-compressed message containing multiple messages The given messages will be encoded, compressed, and sent as a single atomic message to Kafka. :param list message_set: a list of :class:`Message` instances
Below is the the instruction that describes the task: ### Input: Construct a Snappy-compressed message containing multiple messages The given messages will be encoded, compressed, and sent as a single atomic message to Kafka. :param list message_set: a list of :class:`Message` instances ### Response: ...
def _tmp_html_file( self, content): """*create a tmp html file with some content used for the header or footer of the ebook* **Key Arguments:** - ``content`` -- the content to include in the HTML file. """ self.log.debug('starting the ``_tmp_html_file...
*create a tmp html file with some content used for the header or footer of the ebook* **Key Arguments:** - ``content`` -- the content to include in the HTML file.
Below is the the instruction that describes the task: ### Input: *create a tmp html file with some content used for the header or footer of the ebook* **Key Arguments:** - ``content`` -- the content to include in the HTML file. ### Response: def _tmp_html_file( self, co...
def primitive_structure_from_cif(cif, parse_engine, symprec, site_tolerance): """ This calcfunction will take a CifData node, attempt to create a StructureData object from it using the 'parse_engine' and pass it through SeeKpath to try and get the primitive cell. Finally, it will store several keys from...
This calcfunction will take a CifData node, attempt to create a StructureData object from it using the 'parse_engine' and pass it through SeeKpath to try and get the primitive cell. Finally, it will store several keys from the SeeKpath output parameters dictionary directly on the structure data as attributes, ...
Below is the the instruction that describes the task: ### Input: This calcfunction will take a CifData node, attempt to create a StructureData object from it using the 'parse_engine' and pass it through SeeKpath to try and get the primitive cell. Finally, it will store several keys from the SeeKpath output ...
def avg_pool(self, block_size): """ Resize the heatmap(s) array using average pooling of a given block/kernel size. Parameters ---------- block_size : int or tuple of int Size of each block of values to pool, aka kernel size. See :func:`imgaug.pool` for details. ...
Resize the heatmap(s) array using average pooling of a given block/kernel size. Parameters ---------- block_size : int or tuple of int Size of each block of values to pool, aka kernel size. See :func:`imgaug.pool` for details. Returns ------- imgaug.Heatmaps...
Below is the the instruction that describes the task: ### Input: Resize the heatmap(s) array using average pooling of a given block/kernel size. Parameters ---------- block_size : int or tuple of int Size of each block of values to pool, aka kernel size. See :func:`imgaug.pool` ...
def load_yaml(yaml_file: str) -> Any: """ Load YAML from file. :param yaml_file: path to YAML file :return: content of the YAML as dict/list """ with open(yaml_file, 'r') as file: return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader)
Load YAML from file. :param yaml_file: path to YAML file :return: content of the YAML as dict/list
Below is the the instruction that describes the task: ### Input: Load YAML from file. :param yaml_file: path to YAML file :return: content of the YAML as dict/list ### Response: def load_yaml(yaml_file: str) -> Any: """ Load YAML from file. :param yaml_file: path to YAML file :return: con...
def get_consistent_edges(graph: BELGraph) -> Iterable[Tuple[BaseEntity, BaseEntity]]: """Yield pairs of (source node, target node) for which all of their edges have the same type of relation. :return: An iterator over (source, target) node pairs corresponding to edges with many inconsistent relations """ ...
Yield pairs of (source node, target node) for which all of their edges have the same type of relation. :return: An iterator over (source, target) node pairs corresponding to edges with many inconsistent relations
Below is the the instruction that describes the task: ### Input: Yield pairs of (source node, target node) for which all of their edges have the same type of relation. :return: An iterator over (source, target) node pairs corresponding to edges with many inconsistent relations ### Response: def get_consistent...
def graph_draw(self, mode): """ Draws grid graph using networkx This method is for debugging purposes only. Use ding0.tools.plots.plot_mv_topology() for advanced plotting. Parameters ---------- mode : str Mode selection 'MV' or 'LV'. Not...
Draws grid graph using networkx This method is for debugging purposes only. Use ding0.tools.plots.plot_mv_topology() for advanced plotting. Parameters ---------- mode : str Mode selection 'MV' or 'LV'. Notes ----- The geo coords ...
Below is the the instruction that describes the task: ### Input: Draws grid graph using networkx This method is for debugging purposes only. Use ding0.tools.plots.plot_mv_topology() for advanced plotting. Parameters ---------- mode : str Mode selection 'MV' or '...
def tail(self, stream='stdout', num_lines=10): """ Tail a specified stream (stdout or stderr) by num_lines. """ target = self._map_string_to_file(stream) if not target: # no current temp file last_run = self.backend.get_latest_run_log(self.parent_job.job_id, ...
Tail a specified stream (stdout or stderr) by num_lines.
Below is the the instruction that describes the task: ### Input: Tail a specified stream (stdout or stderr) by num_lines. ### Response: def tail(self, stream='stdout', num_lines=10): """ Tail a specified stream (stdout or stderr) by num_lines. """ target = self._map_string_to_file(stream) i...
def gen_csv(sc, filename, field_list, source, filters): '''csv SecurityCenterObj, AssetListName, CSVFields, EmailAddress ''' # First thing we need to do is initialize the csvfile and build the header # for the file. datafile = open(filename, 'wb') csvfile = csv.writer(datafile) header = [] ...
csv SecurityCenterObj, AssetListName, CSVFields, EmailAddress
Below is the the instruction that describes the task: ### Input: csv SecurityCenterObj, AssetListName, CSVFields, EmailAddress ### Response: def gen_csv(sc, filename, field_list, source, filters): '''csv SecurityCenterObj, AssetListName, CSVFields, EmailAddress ''' # First thing we need to do is initi...
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True): """Evaluates by creating an Index containing evaluated data. See `LazyResult` Returns ------- Index Index with evaluated data. """ evaluated_data = ...
Evaluates by creating an Index containing evaluated data. See `LazyResult` Returns ------- Index Index with evaluated data.
Below is the the instruction that describes the task: ### Input: Evaluates by creating an Index containing evaluated data. See `LazyResult` Returns ------- Index Index with evaluated data. ### Response: def evaluate(self, verbose=False, decode=True, passes=None, num_th...
def _add_options_to_parser(self, opts_dict, parser): """Add options to a parser.""" store_bool = ('store_true', 'store_false') for opt, sct in opts_dict.items(): meta = self._conf[sct].def_[opt] kwargs = copy.deepcopy(meta.cmd_kwargs) action = kwargs.get('acti...
Add options to a parser.
Below is the the instruction that describes the task: ### Input: Add options to a parser. ### Response: def _add_options_to_parser(self, opts_dict, parser): """Add options to a parser.""" store_bool = ('store_true', 'store_false') for opt, sct in opts_dict.items(): meta = self._...
def initialize(self, cfg_file=None, mode=None): """Initialize the model for simulation, possibly given a config file. Parameters ---------- cfg_file : Optional[str] The name of the configuration file to load, optional. """ self.sim = ScipyOdeSimulator(self.mo...
Initialize the model for simulation, possibly given a config file. Parameters ---------- cfg_file : Optional[str] The name of the configuration file to load, optional.
Below is the the instruction that describes the task: ### Input: Initialize the model for simulation, possibly given a config file. Parameters ---------- cfg_file : Optional[str] The name of the configuration file to load, optional. ### Response: def initialize(self, cfg_file=N...
def surfdens(self,R,z,phi=0.,t=0.,forcepoisson=False): """ NAME: surfdens PURPOSE: evaluate the surface density :math:`\\Sigma(R,z,\\phi,t) = \\int_{-z}^{+z} dz' \\rho(R,z',\\phi,t)` INPUT: R - Cylindrical Galactocentric radius (can be Quantity) ...
NAME: surfdens PURPOSE: evaluate the surface density :math:`\\Sigma(R,z,\\phi,t) = \\int_{-z}^{+z} dz' \\rho(R,z',\\phi,t)` INPUT: R - Cylindrical Galactocentric radius (can be Quantity) z - vertical height (can be Quantity) phi - azimuth (op...
Below is the the instruction that describes the task: ### Input: NAME: surfdens PURPOSE: evaluate the surface density :math:`\\Sigma(R,z,\\phi,t) = \\int_{-z}^{+z} dz' \\rho(R,z',\\phi,t)` INPUT: R - Cylindrical Galactocentric radius (can be Quantity) ...
def _verify_field_spec(self, spec, path): """Verifies a given field specification is valid, recursing into nested schemas if required.""" # Required should be a boolean if 'required' in spec and not isinstance(spec['required'], bool): raise SchemaFormatException("{} required declara...
Verifies a given field specification is valid, recursing into nested schemas if required.
Below is the the instruction that describes the task: ### Input: Verifies a given field specification is valid, recursing into nested schemas if required. ### Response: def _verify_field_spec(self, spec, path): """Verifies a given field specification is valid, recursing into nested schemas if required.""" ...
def clean(self): """Remove services without host object linked to Note that this should not happen! :return: None """ to_del = [] for serv in self: if not serv.host: to_del.append(serv.uuid) for service_uuid in to_del: del...
Remove services without host object linked to Note that this should not happen! :return: None
Below is the the instruction that describes the task: ### Input: Remove services without host object linked to Note that this should not happen! :return: None ### Response: def clean(self): """Remove services without host object linked to Note that this should not happen! ...
def main(): """ Setup consumer """ config = loader.load_config() if config.version: show_version() if config.show_rules: show_rules() if not config.configfile and not (hasattr(config, "status") or hasattr(config, "stop")): show_configfile_warning() # Check if we ...
Setup consumer
Below is the the instruction that describes the task: ### Input: Setup consumer ### Response: def main(): """ Setup consumer """ config = loader.load_config() if config.version: show_version() if config.show_rules: show_rules() if not config.configfile and not (hasattr(c...
def simulate_to_target_signal_to_noise(cls, array, pixel_scale, target_signal_to_noise, exposure_time_map, psf=None, background_sky_map=None, seed=-1): """ Create a realistic simulated image by applying effects to a plain simulated image. Parameters ...
Create a realistic simulated image by applying effects to a plain simulated image. Parameters ---------- target_signal_to_noise array : ndarray The image before simulating (e.g. the lens and source galaxies before optics blurring and CCD read-out). pixel_scale: float...
Below is the the instruction that describes the task: ### Input: Create a realistic simulated image by applying effects to a plain simulated image. Parameters ---------- target_signal_to_noise array : ndarray The image before simulating (e.g. the lens and source galaxies...
def reset(self, mode=InputMode.INSERT): """ Reset state, go back to the given mode. INSERT by default. """ # Go back to insert mode. self.input_mode = mode self.waiting_for_digraph = False self.operator_func = None self.operator_arg = None
Reset state, go back to the given mode. INSERT by default.
Below is the the instruction that describes the task: ### Input: Reset state, go back to the given mode. INSERT by default. ### Response: def reset(self, mode=InputMode.INSERT): """ Reset state, go back to the given mode. INSERT by default. """ # Go back to insert mode. self...
def create(self): """Create the widget layout with all the information.""" b0 = QGroupBox('Dataset') form = QFormLayout() b0.setLayout(form) open_rec = QPushButton('Open Dataset...') open_rec.clicked.connect(self.open_dataset) open_rec.setToolTip('Click here to o...
Create the widget layout with all the information.
Below is the the instruction that describes the task: ### Input: Create the widget layout with all the information. ### Response: def create(self): """Create the widget layout with all the information.""" b0 = QGroupBox('Dataset') form = QFormLayout() b0.setLayout(form) ope...
def generate_nhs_number_from_first_9_digits(first9digits: str) -> Optional[int]: """ Returns a valid NHS number, as an ``int``, given the first 9 digits. The particular purpose is to make NHS numbers that *look* fake (rather than truly random NHS numbers which might accidentally be real). For examp...
Returns a valid NHS number, as an ``int``, given the first 9 digits. The particular purpose is to make NHS numbers that *look* fake (rather than truly random NHS numbers which might accidentally be real). For example: .. code-block:: none 123456789_ : no; checksum 10 987654321_ : yes,...
Below is the the instruction that describes the task: ### Input: Returns a valid NHS number, as an ``int``, given the first 9 digits. The particular purpose is to make NHS numbers that *look* fake (rather than truly random NHS numbers which might accidentally be real). For example: .. code-block::...
def ConvertFromWireFormat(self, value, container=None): """The wire format is an AnyValue message.""" result = AnyValue() ReadIntoObject(value[2], 0, result) if self._type is not None: converted_value = self._type(container) else: converted_value = self._TypeFromAnyValue(result) # I...
The wire format is an AnyValue message.
Below is the the instruction that describes the task: ### Input: The wire format is an AnyValue message. ### Response: def ConvertFromWireFormat(self, value, container=None): """The wire format is an AnyValue message.""" result = AnyValue() ReadIntoObject(value[2], 0, result) if self._type is not N...
def _construct_field_operator_expression_dict(expression_list): """Construct a mapping from local fields to specified operators, and corresponding expressions. Args: expression_list: list of expressions to analyze Returns: local_field_to_expressions: dict mapping local field na...
Construct a mapping from local fields to specified operators, and corresponding expressions. Args: expression_list: list of expressions to analyze Returns: local_field_to_expressions: dict mapping local field names to "operator -> list of BinaryComposition" dictionaries, ...
Below is the the instruction that describes the task: ### Input: Construct a mapping from local fields to specified operators, and corresponding expressions. Args: expression_list: list of expressions to analyze Returns: local_field_to_expressions: dict mapping local field name...
def WideResnet(num_blocks=3, hidden_size=64, num_output_classes=10, mode='train'): """WideResnet from https://arxiv.org/pdf/1605.07146.pdf. Args: num_blocks: int, number of blocks in a group. hidden_size: the size of the first hidden layer (multiplied later). num_output_classes: int, num...
WideResnet from https://arxiv.org/pdf/1605.07146.pdf. Args: num_blocks: int, number of blocks in a group. hidden_size: the size of the first hidden layer (multiplied later). num_output_classes: int, number of classes to distinguish. mode: is it training or eval. Returns: The WideResnet model w...
Below is the the instruction that describes the task: ### Input: WideResnet from https://arxiv.org/pdf/1605.07146.pdf. Args: num_blocks: int, number of blocks in a group. hidden_size: the size of the first hidden layer (multiplied later). num_output_classes: int, number of classes to distinguish. ...
def create_method(self): """ Build the estimator method or function. Returns ------- :return : string The built method as string. """ temp_method = self.temp('method', skipping=True, n_indents=1) return temp_method.format(class_name=self.class...
Build the estimator method or function. Returns ------- :return : string The built method as string.
Below is the the instruction that describes the task: ### Input: Build the estimator method or function. Returns ------- :return : string The built method as string. ### Response: def create_method(self): """ Build the estimator method or function. Retu...
def replace_note(self, player, text): """Replace note text with text. (Overwrites previous note!)""" note = self._find_note(player) note.text = text
Replace note text with text. (Overwrites previous note!)
Below is the the instruction that describes the task: ### Input: Replace note text with text. (Overwrites previous note!) ### Response: def replace_note(self, player, text): """Replace note text with text. (Overwrites previous note!)""" note = self._find_note(player) note.text = text
def get_ns2goids(self, goids): """Group GO IDs by namespace.""" ns2goids = cx.defaultdict(set) go2nt = self.go2nt for goid in goids: ns2goids[go2nt[goid].NS].add(goid) return {ns:gos for ns, gos in ns2goids.items()}
Group GO IDs by namespace.
Below is the the instruction that describes the task: ### Input: Group GO IDs by namespace. ### Response: def get_ns2goids(self, goids): """Group GO IDs by namespace.""" ns2goids = cx.defaultdict(set) go2nt = self.go2nt for goid in goids: ns2goids[go2nt[goid].NS].add(goi...
def get_proficiency_query_session_for_objective_bank(self, objective_bank_id, proxy): """Gets the ``OsidSession`` associated with the proficiency query service for the given objective bank. :param objective_bank_id: the ``Id`` of the obective bank :type objective_bank_id: ``osid.id.Id`` ...
Gets the ``OsidSession`` associated with the proficiency query service for the given objective bank. :param objective_bank_id: the ``Id`` of the obective bank :type objective_bank_id: ``osid.id.Id`` :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: a ``Proficiency...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the proficiency query service for the given objective bank. :param objective_bank_id: the ``Id`` of the obective bank :type objective_bank_id: ``osid.id.Id`` :param proxy: a proxy ...
def increment(self): "increment the counter, and wake anyone waiting for the new value" self._count += 1 waiters = self._waiters.pop(self._count, []) if waiters: scheduler.state.awoken_from_events.update(waiters)
increment the counter, and wake anyone waiting for the new value
Below is the the instruction that describes the task: ### Input: increment the counter, and wake anyone waiting for the new value ### Response: def increment(self): "increment the counter, and wake anyone waiting for the new value" self._count += 1 waiters = self._waiters.pop(self._count, [...
def keys(self, full_grid=False): """Returns the keys of the GridSpace Args: full_grid (bool, optional): Return full cross-product of keys Returns: List of keys """ keys = super(GridSpace, self).keys() if self.ndims == 1 or not full_grid: ...
Returns the keys of the GridSpace Args: full_grid (bool, optional): Return full cross-product of keys Returns: List of keys
Below is the the instruction that describes the task: ### Input: Returns the keys of the GridSpace Args: full_grid (bool, optional): Return full cross-product of keys Returns: List of keys ### Response: def keys(self, full_grid=False): """Returns the keys of the Gr...
def add(self, obj): """ Add an instance of :class:`SubComponent <hl7apy.core.SubComponent>` to the list of children :param obj: an instance of :class:`SubComponent <hl7apy.core.SubComponent>` >>> c = Component('CX_10') >>> s = SubComponent(name='CWE_1', value='EXAMPLE_ID') ...
Add an instance of :class:`SubComponent <hl7apy.core.SubComponent>` to the list of children :param obj: an instance of :class:`SubComponent <hl7apy.core.SubComponent>` >>> c = Component('CX_10') >>> s = SubComponent(name='CWE_1', value='EXAMPLE_ID') >>> s2 = SubComponent(name='CWE_4', ...
Below is the the instruction that describes the task: ### Input: Add an instance of :class:`SubComponent <hl7apy.core.SubComponent>` to the list of children :param obj: an instance of :class:`SubComponent <hl7apy.core.SubComponent>` >>> c = Component('CX_10') >>> s = SubComponent(name='CWE...
def accept_connection(self, name=None, alias=None, timeout=0): """Accepts a connection to server identified by `name` or the latest server if `name` is empty. If given an `alias`, the connection is named and can be later referenced with that name. If `timeout` is > 0, the conne...
Accepts a connection to server identified by `name` or the latest server if `name` is empty. If given an `alias`, the connection is named and can be later referenced with that name. If `timeout` is > 0, the connection times out after the time specified. `timeout` defaults to 0 ...
Below is the the instruction that describes the task: ### Input: Accepts a connection to server identified by `name` or the latest server if `name` is empty. If given an `alias`, the connection is named and can be later referenced with that name. If `timeout` is > 0, the connection...
def get_range(self, address=None): """ Returns a Range instance from whitin this worksheet :param str address: Optional, the range address you want :return: a Range instance """ url = self.build_url(self._endpoints.get('get_range')) if address is not None: ...
Returns a Range instance from whitin this worksheet :param str address: Optional, the range address you want :return: a Range instance
Below is the the instruction that describes the task: ### Input: Returns a Range instance from whitin this worksheet :param str address: Optional, the range address you want :return: a Range instance ### Response: def get_range(self, address=None): """ Returns a Range instance from ...
def _calcEnergyStretchTwist(self, diff, es, which): r"""Calculate energy for ``estype='ST'`` using a difference vector. It is called in :meth:`dnaEY.getGlobalDeformationEnergy` for energy calculation of each frame. Parameters ---------- diff : numpy.ndarray Array of...
r"""Calculate energy for ``estype='ST'`` using a difference vector. It is called in :meth:`dnaEY.getGlobalDeformationEnergy` for energy calculation of each frame. Parameters ---------- diff : numpy.ndarray Array of difference between minimum and current parameter values. ...
Below is the the instruction that describes the task: ### Input: r"""Calculate energy for ``estype='ST'`` using a difference vector. It is called in :meth:`dnaEY.getGlobalDeformationEnergy` for energy calculation of each frame. Parameters ---------- diff : numpy.ndarray ...
def sort(self, column, order=Qt.AscendingOrder): """Reimplement Qt method""" self.sourceModel().sort(column, order)
Reimplement Qt method
Below is the the instruction that describes the task: ### Input: Reimplement Qt method ### Response: def sort(self, column, order=Qt.AscendingOrder): """Reimplement Qt method""" self.sourceModel().sort(column, order)
def g_reuss(self): """ returns the G_r shear modulus """ return 15. / (8. * self.compliance_tensor.voigt[:3, :3].trace() - 4. * np.triu(self.compliance_tensor.voigt[:3, :3]).sum() + 3. * self.compliance_tensor.voigt[3:, 3:].trace())
returns the G_r shear modulus
Below is the the instruction that describes the task: ### Input: returns the G_r shear modulus ### Response: def g_reuss(self): """ returns the G_r shear modulus """ return 15. / (8. * self.compliance_tensor.voigt[:3, :3].trace() - 4. * np.triu(self.compliance_...
def tsqr(a): """Perform a QR decomposition of a tall-skinny matrix. Args: a: A distributed matrix with shape MxN (suppose K = min(M, N)). Returns: A tuple of q (a DistArray) and r (a numpy array) satisfying the following. - If q_full = ray.get(DistArray, q).assemble...
Perform a QR decomposition of a tall-skinny matrix. Args: a: A distributed matrix with shape MxN (suppose K = min(M, N)). Returns: A tuple of q (a DistArray) and r (a numpy array) satisfying the following. - If q_full = ray.get(DistArray, q).assemble(), then ...
Below is the the instruction that describes the task: ### Input: Perform a QR decomposition of a tall-skinny matrix. Args: a: A distributed matrix with shape MxN (suppose K = min(M, N)). Returns: A tuple of q (a DistArray) and r (a numpy array) satisfying the following. ...
def _build_dummy_calls(self): """ Generate false if branch with dummy calls Requires kerncraft.h to be included, which defines dummy(...) and var_false. :return: dummy statement """ # Make sure nothing gets removed by inserting dummy calls dummy_calls = [] ...
Generate false if branch with dummy calls Requires kerncraft.h to be included, which defines dummy(...) and var_false. :return: dummy statement
Below is the the instruction that describes the task: ### Input: Generate false if branch with dummy calls Requires kerncraft.h to be included, which defines dummy(...) and var_false. :return: dummy statement ### Response: def _build_dummy_calls(self): """ Generate false if branch...
def create_function(self, func, name=None, database=None): """ Creates a function within Impala Parameters ---------- func : ImpalaUDF or ImpalaUDA Created with wrap_udf or wrap_uda name : string (optional) database : string (optional) """ ...
Creates a function within Impala Parameters ---------- func : ImpalaUDF or ImpalaUDA Created with wrap_udf or wrap_uda name : string (optional) database : string (optional)
Below is the the instruction that describes the task: ### Input: Creates a function within Impala Parameters ---------- func : ImpalaUDF or ImpalaUDA Created with wrap_udf or wrap_uda name : string (optional) database : string (optional) ### Response: def create_f...
def de_duplicate(items): """Remove any duplicate item, preserving order >>> de_duplicate([1, 2, 1, 2]) [1, 2] """ result = [] for item in items: if item not in result: result.append(item) return result
Remove any duplicate item, preserving order >>> de_duplicate([1, 2, 1, 2]) [1, 2]
Below is the the instruction that describes the task: ### Input: Remove any duplicate item, preserving order >>> de_duplicate([1, 2, 1, 2]) [1, 2] ### Response: def de_duplicate(items): """Remove any duplicate item, preserving order >>> de_duplicate([1, 2, 1, 2]) [1, 2] """ result = [...
def risearch(self): "Instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials" if self._risearch is None: self._risearch = ResourceIndex(self.api.base_url, self.api.username, self.api.password) return self._risearch
Instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials
Below is the the instruction that describes the task: ### Input: Instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials ### Response: def risearch(self): "Instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials" if self._risearch is...
def save_data(self, trigger_id, **data): """ let's save the data :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the sav...
let's save the data :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the save statement :rtype: boolean
Below is the the instruction that describes the task: ### Input: let's save the data :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the...
def write(self): """Write the configuration.""" if self.dirty: with open(self._cache_path, "w") as output_file: self._config.write(output_file)
Write the configuration.
Below is the the instruction that describes the task: ### Input: Write the configuration. ### Response: def write(self): """Write the configuration.""" if self.dirty: with open(self._cache_path, "w") as output_file: self._config.write(output_file)
def _set_pos(self, pos): """ Set current position for scroll bar. """ if self._h < len(self._options): pos *= len(self._options) - self._h pos = int(round(max(0, pos), 0)) self._start_line = pos
Set current position for scroll bar.
Below is the the instruction that describes the task: ### Input: Set current position for scroll bar. ### Response: def _set_pos(self, pos): """ Set current position for scroll bar. """ if self._h < len(self._options): pos *= len(self._options) - self._h pos ...
def reset(self): """Resets references.""" self.indchar = None self.comments = {} self.refs = [] self.set_skips([]) self.docstring = "" self.ichain_count = 0 self.tre_store_count = 0 self.case_check_count = 0 self.stmt_lambdas = [] i...
Resets references.
Below is the the instruction that describes the task: ### Input: Resets references. ### Response: def reset(self): """Resets references.""" self.indchar = None self.comments = {} self.refs = [] self.set_skips([]) self.docstring = "" self.ichain_count = 0 ...
def run_container(image, name=None, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, client_timeout=salt.utils.docker.CLIENT_TIMEOUT, bg=False, replace=False, ...
.. versionadded:: 2018.3.0 Equivalent to ``docker run`` on the Docker CLI. Runs the container, waits for it to exit, and returns the container's logs when complete. .. note:: Not to be confused with :py:func:`docker.run <salt.modules.dockermod.run>`, which provides a :py:func:`cmd.run ...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2018.3.0 Equivalent to ``docker run`` on the Docker CLI. Runs the container, waits for it to exit, and returns the container's logs when complete. .. note:: Not to be confused with :py:func:`docker.run <...
def AddToLayout(self, layout): """ Arguments: layout -- a QFormLayout instance """ for param in self.params: widget = param.RenderWidget() layout.addRow(param.caption, widget)
Arguments: layout -- a QFormLayout instance
Below is the the instruction that describes the task: ### Input: Arguments: layout -- a QFormLayout instance ### Response: def AddToLayout(self, layout): """ Arguments: layout -- a QFormLayout instance """ for param in self.params: widget = par...
def add_option(self, name, *args, **kwargs): """add an option to the namespace. This can take two forms: 'name' is a string representing the name of an option and the kwargs are its parameters, or 'name' is an instance of an Option object """ if isinst...
add an option to the namespace. This can take two forms: 'name' is a string representing the name of an option and the kwargs are its parameters, or 'name' is an instance of an Option object
Below is the the instruction that describes the task: ### Input: add an option to the namespace. This can take two forms: 'name' is a string representing the name of an option and the kwargs are its parameters, or 'name' is an instance of an Option object ### Response: d...
async def disconnect(self, sid, namespace=None): """Disconnect a client. :param sid: Session ID of the client. :param namespace: The Socket.IO namespace to disconnect. If this argument is omitted the default namespace is used. Note: this method is a coroutine....
Disconnect a client. :param sid: Session ID of the client. :param namespace: The Socket.IO namespace to disconnect. If this argument is omitted the default namespace is used. Note: this method is a coroutine.
Below is the the instruction that describes the task: ### Input: Disconnect a client. :param sid: Session ID of the client. :param namespace: The Socket.IO namespace to disconnect. If this argument is omitted the default namespace is used. Note: this method is a c...
def update(self, sample_sid=values.unset, status=values.unset): """ Update the QueryInstance :param unicode sample_sid: The SID of an optional reference to the Sample created from the query :param unicode status: The new status of the resource :returns: Updated QueryInstance ...
Update the QueryInstance :param unicode sample_sid: The SID of an optional reference to the Sample created from the query :param unicode status: The new status of the resource :returns: Updated QueryInstance :rtype: twilio.rest.autopilot.v1.assistant.query.QueryInstance
Below is the the instruction that describes the task: ### Input: Update the QueryInstance :param unicode sample_sid: The SID of an optional reference to the Sample created from the query :param unicode status: The new status of the resource :returns: Updated QueryInstance :rtype: t...
def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' rais...
Copies a file from the local files or master depending on implementation
Below is the the instruction that describes the task: ### Input: Copies a file from the local files or master depending on implementation ### Response: def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip...
def get_alter_table_sql(self, diff): """ Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: orator.dbal.table_diff.TableDiff :rtype: list """ sql = self._get_simple_alter_table_sql(diff) if sql is not False: return sql ...
Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: orator.dbal.table_diff.TableDiff :rtype: list
Below is the the instruction that describes the task: ### Input: Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: orator.dbal.table_diff.TableDiff :rtype: list ### Response: def get_alter_table_sql(self, diff): """ Get the ALTER TABLE SQL statement...
def HasWarnings(self): """Determines if a store contains extraction warnings. Returns: bool: True if the store contains extraction warnings. """ # To support older storage versions, check for the now deprecated # extraction errors. has_errors = self._HasAttributeContainers( self._...
Determines if a store contains extraction warnings. Returns: bool: True if the store contains extraction warnings.
Below is the the instruction that describes the task: ### Input: Determines if a store contains extraction warnings. Returns: bool: True if the store contains extraction warnings. ### Response: def HasWarnings(self): """Determines if a store contains extraction warnings. Returns: bool: Tr...
def percentile(sorted_values, p): """Calculate the percentile using the nearest rank method. >>> percentile([15, 20, 35, 40, 50], 50) 35 >>> percentile([15, 20, 35, 40, 50], 40) 20 >>> percentile([], 90) Traceback (most recent call last): ... ValueError: Too few data points (0...
Calculate the percentile using the nearest rank method. >>> percentile([15, 20, 35, 40, 50], 50) 35 >>> percentile([15, 20, 35, 40, 50], 40) 20 >>> percentile([], 90) Traceback (most recent call last): ... ValueError: Too few data points (0) for 90th percentile
Below is the the instruction that describes the task: ### Input: Calculate the percentile using the nearest rank method. >>> percentile([15, 20, 35, 40, 50], 50) 35 >>> percentile([15, 20, 35, 40, 50], 40) 20 >>> percentile([], 90) Traceback (most recent call last): ... ValueE...
def _set_id_from_xml_frameid(self, xml, xmlpath, var): ''' Set a single variable with the frameids of matching entity ''' e = xml.find(xmlpath) if e is not None: setattr(self, var, e.attrib['frameid'])
Set a single variable with the frameids of matching entity
Below is the the instruction that describes the task: ### Input: Set a single variable with the frameids of matching entity ### Response: def _set_id_from_xml_frameid(self, xml, xmlpath, var): ''' Set a single variable with the frameids of matching entity ''' e = xml.find(xmlpath) ...
def pad(self, minibatch): """Pad a batch of examples using this field. If ``self.nesting_field.sequential`` is ``False``, each example in the batch must be a list of string tokens, and pads them as if by a ``Field`` with ``sequential=True``. Otherwise, each example must be a list of lis...
Pad a batch of examples using this field. If ``self.nesting_field.sequential`` is ``False``, each example in the batch must be a list of string tokens, and pads them as if by a ``Field`` with ``sequential=True``. Otherwise, each example must be a list of list of tokens. Using ``self.nes...
Below is the the instruction that describes the task: ### Input: Pad a batch of examples using this field. If ``self.nesting_field.sequential`` is ``False``, each example in the batch must be a list of string tokens, and pads them as if by a ``Field`` with ``sequential=True``. Otherwise, ea...
def get_custom_views(name=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attrib...
function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views.
Below is the the instruction that describes the task: ### Input: function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictio...
def comment(self, format, *args): """ Add a comment to hash table before saving to disk. You can add as many comment lines as you like. These comment lines are discarded when loading the file. If you use a null format, all comments are deleted. """ return lib.zhashx_comment(self._as_para...
Add a comment to hash table before saving to disk. You can add as many comment lines as you like. These comment lines are discarded when loading the file. If you use a null format, all comments are deleted.
Below is the the instruction that describes the task: ### Input: Add a comment to hash table before saving to disk. You can add as many comment lines as you like. These comment lines are discarded when loading the file. If you use a null format, all comments are deleted. ### Response: def comment(self, format, *ar...
def calculate_timeout(http_date): """Extract request timeout from e.g. ``Retry-After`` header. Notes: Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can be either an integer number of seconds or an HTTP date. This function can handle either. Arguments: ...
Extract request timeout from e.g. ``Retry-After`` header. Notes: Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can be either an integer number of seconds or an HTTP date. This function can handle either. Arguments: http_date (:py:class:`str`): The da...
Below is the the instruction that describes the task: ### Input: Extract request timeout from e.g. ``Retry-After`` header. Notes: Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can be either an integer number of seconds or an HTTP date. This function can handle eith...
def port_ranges(): """ Returns a list of ephemeral port ranges for current machine. """ try: return _linux_ranges() except (OSError, IOError): # not linux, try BSD try: ranges = _bsd_ranges() if ranges: return ranges except (OSError, IO...
Returns a list of ephemeral port ranges for current machine.
Below is the the instruction that describes the task: ### Input: Returns a list of ephemeral port ranges for current machine. ### Response: def port_ranges(): """ Returns a list of ephemeral port ranges for current machine. """ try: return _linux_ranges() except (OSError, IOError): # no...
def Wilke(ys, mus, MWs): r'''Calculates viscosity of a gas mixture according to mixing rules in [1]_. .. math:: \eta_{mix} = \sum_{i=1}^n \frac{y_i \eta_i}{\sum_{j=1}^n y_j \phi_{ij}} \phi_{ij} = \frac{(1 + \sqrt{\eta_i/\eta_j}(MW_j/MW_i)^{0.25})^2} {\sqrt{8(1+MW_i/MW_j)}} Par...
r'''Calculates viscosity of a gas mixture according to mixing rules in [1]_. .. math:: \eta_{mix} = \sum_{i=1}^n \frac{y_i \eta_i}{\sum_{j=1}^n y_j \phi_{ij}} \phi_{ij} = \frac{(1 + \sqrt{\eta_i/\eta_j}(MW_j/MW_i)^{0.25})^2} {\sqrt{8(1+MW_i/MW_j)}} Parameters ---------- ys...
Below is the the instruction that describes the task: ### Input: r'''Calculates viscosity of a gas mixture according to mixing rules in [1]_. .. math:: \eta_{mix} = \sum_{i=1}^n \frac{y_i \eta_i}{\sum_{j=1}^n y_j \phi_{ij}} \phi_{ij} = \frac{(1 + \sqrt{\eta_i/\eta_j}(MW_j/MW_i)^{0.25})^2} ...
def set_bookmark(self, slot_num): """Bookmark current position to given slot.""" if self.data: editor = self.get_current_editor() editor.add_bookmark(slot_num)
Bookmark current position to given slot.
Below is the the instruction that describes the task: ### Input: Bookmark current position to given slot. ### Response: def set_bookmark(self, slot_num): """Bookmark current position to given slot.""" if self.data: editor = self.get_current_editor() editor.add_bookmark(s...
def clean(args): """ %prog clean fastafile Remove irregular chars in FASTA seqs. """ p = OptionParser(clean.__doc__) p.add_option("--fancy", default=False, action="store_true", help="Pretty print the sequence [default: %default]") p.add_option("--canonical", default=False, ...
%prog clean fastafile Remove irregular chars in FASTA seqs.
Below is the the instruction that describes the task: ### Input: %prog clean fastafile Remove irregular chars in FASTA seqs. ### Response: def clean(args): """ %prog clean fastafile Remove irregular chars in FASTA seqs. """ p = OptionParser(clean.__doc__) p.add_option("--fancy", defau...
def search(self, q, language=None, current_site_only=True): """Simple search function Plugins can define a 'search_fields' tuple similar to ModelAdmin classes """ from cms.plugin_pool import plugin_pool qs = self.get_queryset() qs = qs.public() if current_site_...
Simple search function Plugins can define a 'search_fields' tuple similar to ModelAdmin classes
Below is the the instruction that describes the task: ### Input: Simple search function Plugins can define a 'search_fields' tuple similar to ModelAdmin classes ### Response: def search(self, q, language=None, current_site_only=True): """Simple search function Plugins can define a 'search...
def download_image(self, img_url): """ Downloads a single image. Downloads img_url using self.page_url as base. Also, raises the appropriate exception if required. """ img_request = None try: img_request = requests.request( 'get', img_...
Downloads a single image. Downloads img_url using self.page_url as base. Also, raises the appropriate exception if required.
Below is the the instruction that describes the task: ### Input: Downloads a single image. Downloads img_url using self.page_url as base. Also, raises the appropriate exception if required. ### Response: def download_image(self, img_url): """ Downloads a single image. ...
def nodes_to_object(self, node, object): "Map all child nodes to one object's attributes" for n in list(node): self.node_to_object(n, object)
Map all child nodes to one object's attributes
Below is the the instruction that describes the task: ### Input: Map all child nodes to one object's attributes ### Response: def nodes_to_object(self, node, object): "Map all child nodes to one object's attributes" for n in list(node): self.node_to_object(n, object)
def validate_signature(filename): """ Remove invalid signatures from a binary file If the file signature is missing or valid then it will be ignored Invalid signatures are replaced with an ad-hoc signature. This is the closest you can get to removing a signature on MacOS Parameters ---------...
Remove invalid signatures from a binary file If the file signature is missing or valid then it will be ignored Invalid signatures are replaced with an ad-hoc signature. This is the closest you can get to removing a signature on MacOS Parameters ---------- filename : str Filepath to a...
Below is the the instruction that describes the task: ### Input: Remove invalid signatures from a binary file If the file signature is missing or valid then it will be ignored Invalid signatures are replaced with an ad-hoc signature. This is the closest you can get to removing a signature on MacOS ...
def buildASNList(rootnames, asnname, check_for_duplicates=True): """ Return the list of filenames for a given set of rootnames """ # Recognize when multiple valid inputs with the same rootname are present # this would happen when both CTE-corrected (_flc) and non-CTE-corrected (_flt) # products...
Return the list of filenames for a given set of rootnames
Below is the the instruction that describes the task: ### Input: Return the list of filenames for a given set of rootnames ### Response: def buildASNList(rootnames, asnname, check_for_duplicates=True): """ Return the list of filenames for a given set of rootnames """ # Recognize when multiple vali...
def _get_response(**kwargs): """Get a template response Use kwargs to add things to the dictionary """ if 'code' not in kwargs: kwargs['code'] = 200 if 'headers' not in kwargs: kwargs['headers'] = dict() if 'version' not in kwargs: kwargs['version'] = 'HTTP/1.1' ret...
Get a template response Use kwargs to add things to the dictionary
Below is the the instruction that describes the task: ### Input: Get a template response Use kwargs to add things to the dictionary ### Response: def _get_response(**kwargs): """Get a template response Use kwargs to add things to the dictionary """ if 'code' not in kwargs: kwargs['cod...
def get_session_data(self, request): """ Return a tuple ``(user, profile, client)`` from the session. """ user = request.session['%suser' % SESSION_KEY] profile = request.session['%sprofile' % SESSION_KEY] client = request.session['%sclient' % SESSION_KEY] return ...
Return a tuple ``(user, profile, client)`` from the session.
Below is the the instruction that describes the task: ### Input: Return a tuple ``(user, profile, client)`` from the session. ### Response: def get_session_data(self, request): """ Return a tuple ``(user, profile, client)`` from the session. """ user = request.session['%suser' % SES...
def link(self, link, title, text): """Rendering a given link with content and title. :param link: href link for ``<a>`` tag. :param title: title content for `title` attribute. :param text: text content for description. """ link = escape_link(link) if not title: ...
Rendering a given link with content and title. :param link: href link for ``<a>`` tag. :param title: title content for `title` attribute. :param text: text content for description.
Below is the the instruction that describes the task: ### Input: Rendering a given link with content and title. :param link: href link for ``<a>`` tag. :param title: title content for `title` attribute. :param text: text content for description. ### Response: def link(self, link, title, te...
def are_cmddicts_same(dict1, dict2): """ Checks to see if two cmddicts are the same. Two cmddicts are defined to be the same if they have the same callbacks/ helptexts/children/summaries for all nodes. """ # If the set of all keys are not the same, they must not be the same. if set(dict1.keys()) != s...
Checks to see if two cmddicts are the same. Two cmddicts are defined to be the same if they have the same callbacks/ helptexts/children/summaries for all nodes.
Below is the the instruction that describes the task: ### Input: Checks to see if two cmddicts are the same. Two cmddicts are defined to be the same if they have the same callbacks/ helptexts/children/summaries for all nodes. ### Response: def are_cmddicts_same(dict1, dict2): """ Checks to see if two cmdd...
def add(key, value): """Adds context to the currently executing request. :key: Any String identifying the request context. Example: "user_ip", "plan", "alert_count" :value: Any json-serializable type. Example: "1.1.1.1", "free", 100 :returns: nothing. ...
Adds context to the currently executing request. :key: Any String identifying the request context. Example: "user_ip", "plan", "alert_count" :value: Any json-serializable type. Example: "1.1.1.1", "free", 100 :returns: nothing.
Below is the the instruction that describes the task: ### Input: Adds context to the currently executing request. :key: Any String identifying the request context. Example: "user_ip", "plan", "alert_count" :value: Any json-serializable type. Example: "1.1.1.1", "free", 1...