code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def setspan(self, *args): """Sets the span of the span element anew, erases all data inside. Arguments: *args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme` """ self.data = [] for child in args: self.append(child)
Sets the span of the span element anew, erases all data inside. Arguments: *args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme`
Below is the the instruction that describes the task: ### Input: Sets the span of the span element anew, erases all data inside. Arguments: *args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme` ### Response: def setspan(self, *args): """Sets the span of the span elem...
def delete_all_rows(self): """ Deletes the contents of all rows in the DataFrame. This function is faster than delete_rows() to remove all information, and at the same time it keeps the container lists for the columns and index so if there is another object that references this DataFrame...
Deletes the contents of all rows in the DataFrame. This function is faster than delete_rows() to remove all information, and at the same time it keeps the container lists for the columns and index so if there is another object that references this DataFrame, like a ViewSeries, the reference remains in t...
Below is the the instruction that describes the task: ### Input: Deletes the contents of all rows in the DataFrame. This function is faster than delete_rows() to remove all information, and at the same time it keeps the container lists for the columns and index so if there is another object that ref...
def replace_parameters(context, nb, parameters): # Uma: This is a copy-paste from papermill papermill/execute.py:104 (execute_parameters). # Typically, papermill injects the injected-parameters cell *below* the parameters cell # but we want to *replace* the parameters cell, which is what this function does....
Assigned parameters into the appropiate place in the input notebook Args: nb (NotebookNode): Executable notebook object parameters (dict): Arbitrary keyword arguments to pass to the notebook parameters.
Below is the the instruction that describes the task: ### Input: Assigned parameters into the appropiate place in the input notebook Args: nb (NotebookNode): Executable notebook object parameters (dict): Arbitrary keyword arguments to pass to the notebook parameters. ### Response: def replace_p...
def is_possible_temp(temp: str) -> bool: """ Returns True if all characters are digits or 'M' (for minus) """ for char in temp: if not (char.isdigit() or char == 'M'): return False return True
Returns True if all characters are digits or 'M' (for minus)
Below is the the instruction that describes the task: ### Input: Returns True if all characters are digits or 'M' (for minus) ### Response: def is_possible_temp(temp: str) -> bool: """ Returns True if all characters are digits or 'M' (for minus) """ for char in temp: if not (char.isdigit() ...
def send(self, topic, *args, **kwargs): """ Appends the prefix to the topic before sendingf """ prefix_topic = self.heroku_kafka.prefix_topic(topic) return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs)
Appends the prefix to the topic before sendingf
Below is the the instruction that describes the task: ### Input: Appends the prefix to the topic before sendingf ### Response: def send(self, topic, *args, **kwargs): """ Appends the prefix to the topic before sendingf """ prefix_topic = self.heroku_kafka.prefix_topic(topic) ...
def comp_centroid(data, bounding_box, debug_plot=False, plot_reference=None, logger=None): """Detect objects in a region and return the centroid of the brightest one""" from matplotlib.patches import Ellipse if logger is None: logger = logging.getLogger(__name__) region = bounding_box.slice ...
Detect objects in a region and return the centroid of the brightest one
Below is the the instruction that describes the task: ### Input: Detect objects in a region and return the centroid of the brightest one ### Response: def comp_centroid(data, bounding_box, debug_plot=False, plot_reference=None, logger=None): """Detect objects in a region and return the centroid of the brightes...
def dbmin_stddev(self, value=None): """ Corresponds to IDD Field `dbmin_stddev` Standard deviation of extreme annual minimum dry-bulb temperature Args: value (float): value for IDD Field `dbmin_stddev` Unit: C if `value` is None it will not be checke...
Corresponds to IDD Field `dbmin_stddev` Standard deviation of extreme annual minimum dry-bulb temperature Args: value (float): value for IDD Field `dbmin_stddev` Unit: C if `value` is None it will not be checked against the specification and i...
Below is the the instruction that describes the task: ### Input: Corresponds to IDD Field `dbmin_stddev` Standard deviation of extreme annual minimum dry-bulb temperature Args: value (float): value for IDD Field `dbmin_stddev` Unit: C if `value` is None i...
def trace_method(method): """ Decorator to catch and print the exceptions that happen within async tasks. Note: this should be applied to methods of VSphereCheck only! """ def wrapper(*args, **kwargs): try: method(*args, **kwargs) except Exception: args[0].pr...
Decorator to catch and print the exceptions that happen within async tasks. Note: this should be applied to methods of VSphereCheck only!
Below is the the instruction that describes the task: ### Input: Decorator to catch and print the exceptions that happen within async tasks. Note: this should be applied to methods of VSphereCheck only! ### Response: def trace_method(method): """ Decorator to catch and print the exceptions that happen ...
def run(self, maxiter = 4, verbose = False): """ Full artillery :-) - Find saturated stars - Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found) Stops if no cosmics are found or if maxiter is reached. """ if self.satlev...
Full artillery :-) - Find saturated stars - Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found) Stops if no cosmics are found or if maxiter is reached.
Below is the the instruction that describes the task: ### Input: Full artillery :-) - Find saturated stars - Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found) Stops if no cosmics are found or if maxiter is reached. ### Response: def run(self, maxiter = 4, v...
def _update_config_location(self,directory,files=None): """Loads location and applies to all files in given files list (or if none, all files in flickr DB) google reverse GEO to figure out location lat/long file can contain things like: Australia Sydney, Australia ...
Loads location and applies to all files in given files list (or if none, all files in flickr DB) google reverse GEO to figure out location lat/long file can contain things like: Australia Sydney, Australia Holcomb Campground, California. If image already has Lat...
Below is the the instruction that describes the task: ### Input: Loads location and applies to all files in given files list (or if none, all files in flickr DB) google reverse GEO to figure out location lat/long file can contain things like: Australia Sydney, Australia ...
def reindex(args): """ %prog agpfile assume the component line order is correct, modify coordinates, this is necessary mostly due to manual edits (insert/delete) that disrupts the target coordinates. """ p = OptionParser(reindex.__doc__) p.add_option("--nogaps", default=False, action="s...
%prog agpfile assume the component line order is correct, modify coordinates, this is necessary mostly due to manual edits (insert/delete) that disrupts the target coordinates.
Below is the the instruction that describes the task: ### Input: %prog agpfile assume the component line order is correct, modify coordinates, this is necessary mostly due to manual edits (insert/delete) that disrupts the target coordinates. ### Response: def reindex(args): """ %prog agpfile ...
def is_json(self): """ Returns: bool: True if `content_type` is `application/json` """ return (self.content_type.startswith('application/json') or re.match(r'application/vnd.go.cd.v(\d+)\+json', self.content_type))
Returns: bool: True if `content_type` is `application/json`
Below is the the instruction that describes the task: ### Input: Returns: bool: True if `content_type` is `application/json` ### Response: def is_json(self): """ Returns: bool: True if `content_type` is `application/json` """ return (self.content_type.startswith(...
def publish_post(self, request, pk): """ Admin view to publish a single post :param request: request :param pk: primary key of the post to publish :return: Redirect to the post itself (if found) or fallback urls """ language = get_language_from_request(request, c...
Admin view to publish a single post :param request: request :param pk: primary key of the post to publish :return: Redirect to the post itself (if found) or fallback urls
Below is the the instruction that describes the task: ### Input: Admin view to publish a single post :param request: request :param pk: primary key of the post to publish :return: Redirect to the post itself (if found) or fallback urls ### Response: def publish_post(self, request, pk): ...
def visit_Name(self, node): """All assignments to names go through this function.""" if node.ctx == 'store': self.identifiers.declared_locally.add(node.name) elif node.ctx == 'param': self.identifiers.declared_parameter.add(node.name) elif node.ctx == 'load' and n...
All assignments to names go through this function.
Below is the the instruction that describes the task: ### Input: All assignments to names go through this function. ### Response: def visit_Name(self, node): """All assignments to names go through this function.""" if node.ctx == 'store': self.identifiers.declared_locally.add(node.name)...
def _updateKW(image, filename, exten, skyKW, Value): """update the header with the kw,value""" # Update the value in memory image.header[skyKW] = Value # Now update the value on disk if isinstance(exten,tuple): strexten = '[%s,%s]'%(exten[0],str(exten[1])) else: strexten = '[%s]...
update the header with the kw,value
Below is the the instruction that describes the task: ### Input: update the header with the kw,value ### Response: def _updateKW(image, filename, exten, skyKW, Value): """update the header with the kw,value""" # Update the value in memory image.header[skyKW] = Value # Now update the value on disk ...
def hook_wrapper(prompt): u'''Wrap a Python readline so it behaves like GNU readline.''' try: # call the Python hook res = ensure_str(readline_hook(prompt)) # make sure it returned the right sort of thing if res and not isinstance(res, str): raise TypeError, u'...
u'''Wrap a Python readline so it behaves like GNU readline.
Below is the the instruction that describes the task: ### Input: u'''Wrap a Python readline so it behaves like GNU readline. ### Response: def hook_wrapper(prompt): u'''Wrap a Python readline so it behaves like GNU readline.''' try: # call the Python hook res = ensure_str(readline_hook(...
def read_struct_file(struct_data): """Interpret a struct file defining the location of variables in memory. Parameters ---------- struct_data : :py:class:`bytes` String of :py:class:`bytes` containing data to interpret as the struct definition. Returns ------- {struct_name:...
Interpret a struct file defining the location of variables in memory. Parameters ---------- struct_data : :py:class:`bytes` String of :py:class:`bytes` containing data to interpret as the struct definition. Returns ------- {struct_name: :py:class:`~.Struct`} A dictionar...
Below is the the instruction that describes the task: ### Input: Interpret a struct file defining the location of variables in memory. Parameters ---------- struct_data : :py:class:`bytes` String of :py:class:`bytes` containing data to interpret as the struct definition. Returns ...
def lstsq(a, b, rcond=None, weighted=False, extrainfo=False): """ Least-squares solution ``x`` to ``a @ x = b`` for |GVar|\s. Here ``x`` is defined to be the solution that minimizes ``||b - a @ x||``. If ``b`` has a covariance matrix, another option is to weight the norm with the inverse covariance mat...
Least-squares solution ``x`` to ``a @ x = b`` for |GVar|\s. Here ``x`` is defined to be the solution that minimizes ``||b - a @ x||``. If ``b`` has a covariance matrix, another option is to weight the norm with the inverse covariance matrix: i.e., minimize ``|| isig @ b - isig @ a @ x||`` where ``isig`...
Below is the the instruction that describes the task: ### Input: Least-squares solution ``x`` to ``a @ x = b`` for |GVar|\s. Here ``x`` is defined to be the solution that minimizes ``||b - a @ x||``. If ``b`` has a covariance matrix, another option is to weight the norm with the inverse covariance matr...
def _getModelCheckpointFilePath(checkpointDir): """ Return the absolute path of the model's checkpoint file. :param checkpointDir: (string) Directory of where the experiment is to be or was saved :returns: (string) An absolute path. """ path = os.path.join(checkpointDir, "model.data") ...
Return the absolute path of the model's checkpoint file. :param checkpointDir: (string) Directory of where the experiment is to be or was saved :returns: (string) An absolute path.
Below is the the instruction that describes the task: ### Input: Return the absolute path of the model's checkpoint file. :param checkpointDir: (string) Directory of where the experiment is to be or was saved :returns: (string) An absolute path. ### Response: def _getModelCheckpointFilePath(che...
def unload(self, refobj): """Load the given refobject Unload in this case means, that a reference is stays in the scene but it is not in a loaded state. So there is a reference, but data is not read from it. This will call :meth:`ReftypeInterface.unload`. :param refobj...
Load the given refobject Unload in this case means, that a reference is stays in the scene but it is not in a loaded state. So there is a reference, but data is not read from it. This will call :meth:`ReftypeInterface.unload`. :param refobj: the refobject :type refobj:...
Below is the the instruction that describes the task: ### Input: Load the given refobject Unload in this case means, that a reference is stays in the scene but it is not in a loaded state. So there is a reference, but data is not read from it. This will call :meth:`ReftypeInterface...
def duration(self): """ This read-only attribute specifies the server-side duration of a query in milliseconds. """ if self._closed or \ not self._result or \ "duration" not in self._result: return -1 return self._result.get("du...
This read-only attribute specifies the server-side duration of a query in milliseconds.
Below is the the instruction that describes the task: ### Input: This read-only attribute specifies the server-side duration of a query in milliseconds. ### Response: def duration(self): """ This read-only attribute specifies the server-side duration of a query in milliseconds. ...
def add_instance(self, name, properties): # type: (str, dict) -> None """ Stores the description of a component instance. The given properties are stored as is. :param name: Instance name :param properties: Instance properties :raise NameError: Already known inst...
Stores the description of a component instance. The given properties are stored as is. :param name: Instance name :param properties: Instance properties :raise NameError: Already known instance name
Below is the the instruction that describes the task: ### Input: Stores the description of a component instance. The given properties are stored as is. :param name: Instance name :param properties: Instance properties :raise NameError: Already known instance name ### Response: def ...
def reminders_add(self, *, text: str, time: str, **kwargs) -> SlackResponse: """Creates a reminder. Args: text (str): The content of the reminder. e.g. 'eat a banana' time (str): When this reminder should happen: the Unix timestamp (up to five years from now e.g....
Creates a reminder. Args: text (str): The content of the reminder. e.g. 'eat a banana' time (str): When this reminder should happen: the Unix timestamp (up to five years from now e.g. '1602288000'), the number of seconds until the reminder (if within 24 h...
Below is the the instruction that describes the task: ### Input: Creates a reminder. Args: text (str): The content of the reminder. e.g. 'eat a banana' time (str): When this reminder should happen: the Unix timestamp (up to five years from now e.g. '1602288000'), ...
def get_max_item(self): """ Get the current maximum item number :return: The current maximum item number. """ suburl = "v0/maxitem.json" try: max_item = self._make_request(suburl) except requests.HTTPError as e: hn_logger.exception('Faulted...
Get the current maximum item number :return: The current maximum item number.
Below is the the instruction that describes the task: ### Input: Get the current maximum item number :return: The current maximum item number. ### Response: def get_max_item(self): """ Get the current maximum item number :return: The current maximum item number. """ ...
def get_hardware_info(self): """ Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for both CAN channels are returned separately. :return: Tuple with extended hardware information structure (see structure :class:`Hardware...
Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for both CAN channels are returned separately. :return: Tuple with extended hardware information structure (see structure :class:`HardwareInfoEx`) and structures with informat...
Below is the the instruction that describes the task: ### Input: Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for both CAN channels are returned separately. :return: Tuple with extended hardware information structure (see struct...
def dissolve(inlist): """ list and tuple flattening Parameters ---------- inlist: list the list with sub-lists or tuples to be flattened Returns ------- list the flattened result Examples -------- >>> dissolve([[1, 2], [3, 4]]) [1, 2, 3, 4] ...
list and tuple flattening Parameters ---------- inlist: list the list with sub-lists or tuples to be flattened Returns ------- list the flattened result Examples -------- >>> dissolve([[1, 2], [3, 4]]) [1, 2, 3, 4] >>> dissolve([(1, 2, (3, ...
Below is the the instruction that describes the task: ### Input: list and tuple flattening Parameters ---------- inlist: list the list with sub-lists or tuples to be flattened Returns ------- list the flattened result Examples -------- >>> dissolve(...
def agi_code_check(code=None, response=None, line=None): """ Check the AGI code and return a dict to help on error handling. """ code = int(code) response = response or "" result = {'status_code': code, 'result': ('', ''), 'msg': ''} if code == 100: result['msg'] = line elif code...
Check the AGI code and return a dict to help on error handling.
Below is the the instruction that describes the task: ### Input: Check the AGI code and return a dict to help on error handling. ### Response: def agi_code_check(code=None, response=None, line=None): """ Check the AGI code and return a dict to help on error handling. """ code = int(code) respon...
def protorpc_to_endpoints_error(self, status, body): """Convert a ProtoRPC error to the format expected by Google Endpoints. If the body does not contain an ProtoRPC message in state APPLICATION_ERROR the status and body will be returned unchanged. Args: status: HTTP status of the response from ...
Convert a ProtoRPC error to the format expected by Google Endpoints. If the body does not contain an ProtoRPC message in state APPLICATION_ERROR the status and body will be returned unchanged. Args: status: HTTP status of the response from the backend body: JSON-encoded error in format expecte...
Below is the the instruction that describes the task: ### Input: Convert a ProtoRPC error to the format expected by Google Endpoints. If the body does not contain an ProtoRPC message in state APPLICATION_ERROR the status and body will be returned unchanged. Args: status: HTTP status of the respo...
def on_before_publish_insert_request_id_header(headers, **kwargs): """ This function is meant to be used as signal processor for "before_task_publish". :param Dict headers: The headers of the message :param kwargs: Any extra keyword arguments """ if _CELERY_X_HEADER not in headers: reque...
This function is meant to be used as signal processor for "before_task_publish". :param Dict headers: The headers of the message :param kwargs: Any extra keyword arguments
Below is the the instruction that describes the task: ### Input: This function is meant to be used as signal processor for "before_task_publish". :param Dict headers: The headers of the message :param kwargs: Any extra keyword arguments ### Response: def on_before_publish_insert_request_id_header(headers, ...
def make_eventlogitem_log(log, condition='is', negate=False, preserve_case=False): """ Create a node for EventLogItem/log :return: A IndicatorItem represented as an Element node """ document = 'EventLogItem' search = 'EventLogItem/log' content_type = 'string' content = log ii_no...
Create a node for EventLogItem/log :return: A IndicatorItem represented as an Element node
Below is the the instruction that describes the task: ### Input: Create a node for EventLogItem/log :return: A IndicatorItem represented as an Element node ### Response: def make_eventlogitem_log(log, condition='is', negate=False, preserve_case=False): """ Create a node for EventLogItem/log ...
def assemble_common_meta(common_meta_dfs, fields_to_remove, sources, remove_all_metadata_fields, error_report_file): """ Assemble the common metadata dfs together. Both indices are sorted. Fields that are not in all the dfs are dropped. Args: common_meta_dfs (list of pandas dfs) fields_to_r...
Assemble the common metadata dfs together. Both indices are sorted. Fields that are not in all the dfs are dropped. Args: common_meta_dfs (list of pandas dfs) fields_to_remove (list of strings): fields to be removed from the common metadata because they don't agree across files ...
Below is the the instruction that describes the task: ### Input: Assemble the common metadata dfs together. Both indices are sorted. Fields that are not in all the dfs are dropped. Args: common_meta_dfs (list of pandas dfs) fields_to_remove (list of strings): fields to be removed from the ...
def get_taglist(node): """ Return a list of tags (with NRML namespace removed) representing the order of the nodes within a node """ return [re.sub(r'\{[^}]*\}', "", copy(subnode.tag)) for subnode in node.nodes]
Return a list of tags (with NRML namespace removed) representing the order of the nodes within a node
Below is the the instruction that describes the task: ### Input: Return a list of tags (with NRML namespace removed) representing the order of the nodes within a node ### Response: def get_taglist(node): """ Return a list of tags (with NRML namespace removed) representing the order of the nodes wit...
def run(users, hosts, func, **kwargs): """ Convenience function that creates an Exscript.Queue instance, adds the given accounts, and calls Queue.run() with the given hosts and function as an argument. If you also want to pass arguments to the given function, you may use util.decorator.bind() l...
Convenience function that creates an Exscript.Queue instance, adds the given accounts, and calls Queue.run() with the given hosts and function as an argument. If you also want to pass arguments to the given function, you may use util.decorator.bind() like this:: def my_callback(job, host, conn, ...
Below is the the instruction that describes the task: ### Input: Convenience function that creates an Exscript.Queue instance, adds the given accounts, and calls Queue.run() with the given hosts and function as an argument. If you also want to pass arguments to the given function, you may use util....
def add_transcription(self, gene: Gene, rna: Union[Rna, MicroRna]) -> str: """Add a transcription relation from a gene to an RNA or miRNA node. :param gene: A gene node :param rna: An RNA or microRNA node """ return self.add_unqualified_edge(gene, rna, TRANSCRIBED_TO)
Add a transcription relation from a gene to an RNA or miRNA node. :param gene: A gene node :param rna: An RNA or microRNA node
Below is the the instruction that describes the task: ### Input: Add a transcription relation from a gene to an RNA or miRNA node. :param gene: A gene node :param rna: An RNA or microRNA node ### Response: def add_transcription(self, gene: Gene, rna: Union[Rna, MicroRna]) -> str: """Add a ...
def data(self): """ Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are used, scalar values are always retur...
Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are used, scalar values are always returned as strings.
Below is the the instruction that describes the task: ### Input: Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are use...
def climatology(self, startclim, endclim, **kwargs): r""" Returns a climatology of observations at a user specified location for a specified time. Users must specify at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'gacc', or...
r""" Returns a climatology of observations at a user specified location for a specified time. Users must specify at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'gacc', or 'subgacc') to obtain observation data. Other parameters may ...
Below is the the instruction that describes the task: ### Input: r""" Returns a climatology of observations at a user specified location for a specified time. Users must specify at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'g...
def run(self, args, pipeline_command): """ Invokes the pipeline with the defined command. Command line arguments, and the command need to be set with arg_builder, and command_builder respectively before this method can be invoked. """ # output that must be moved but not ...
Invokes the pipeline with the defined command. Command line arguments, and the command need to be set with arg_builder, and command_builder respectively before this method can be invoked.
Below is the the instruction that describes the task: ### Input: Invokes the pipeline with the defined command. Command line arguments, and the command need to be set with arg_builder, and command_builder respectively before this method can be invoked. ### Response: def run(self, args, pipeline_com...
def paga_compare( adata, basis=None, edges=False, color=None, alpha=None, groups=None, components=None, projection='2d', legend_loc='on data', legend_fontsize=None, legend_fontweight='bold', color_map=None, palette=N...
Scatter and PAGA graph side-by-side. Consists in a scatter plot and the abstracted graph. See :func:`~scanpy.api.pl.paga` for all related parameters. See :func:`~scanpy.api.pl.paga_path` for visualizing gene changes along paths through the abstracted graph. Additional parameters are as follows. ...
Below is the the instruction that describes the task: ### Input: Scatter and PAGA graph side-by-side. Consists in a scatter plot and the abstracted graph. See :func:`~scanpy.api.pl.paga` for all related parameters. See :func:`~scanpy.api.pl.paga_path` for visualizing gene changes along paths throu...
def authenticate(self, retries=3): """Set API token by authenticating via username/password. :param retries: Number of authentication attempts to make before giving up as an int. :return: Learned API token :rtype: string """ username = self.username or self._getuser(sel...
Set API token by authenticating via username/password. :param retries: Number of authentication attempts to make before giving up as an int. :return: Learned API token :rtype: string
Below is the the instruction that describes the task: ### Input: Set API token by authenticating via username/password. :param retries: Number of authentication attempts to make before giving up as an int. :return: Learned API token :rtype: string ### Response: def authenticate(self, retri...
def run_selected_clicked(self): """Run the selected scenario.""" # get all selected rows rows = sorted(set(index.row() for index in self.table.selectedIndexes())) self.enable_busy_cursor() # iterate over selected rows for row in rows: ...
Run the selected scenario.
Below is the the instruction that describes the task: ### Input: Run the selected scenario. ### Response: def run_selected_clicked(self): """Run the selected scenario.""" # get all selected rows rows = sorted(set(index.row() for index in self.table.selectedIndexes(...
def force_iterable(f): """Will make any functions return an iterable objects by wrapping its result in a list.""" def wrapper(*args, **kwargs): r = f(*args, **kwargs) if hasattr(r, '__iter__'): return r else: return [r] return wrapper
Will make any functions return an iterable objects by wrapping its result in a list.
Below is the the instruction that describes the task: ### Input: Will make any functions return an iterable objects by wrapping its result in a list. ### Response: def force_iterable(f): """Will make any functions return an iterable objects by wrapping its result in a list.""" def wrapper(*args, **kwargs):...
def _getitem_normalized(self, index): """Builds the more compact fmtstrs by using fromstr( of the control sequences)""" index = normalize_slice(len(self), index) counter = 0 output = '' for fs in self.chunks: if index.start < counter + len(fs) and index.stop > counter...
Builds the more compact fmtstrs by using fromstr( of the control sequences)
Below is the the instruction that describes the task: ### Input: Builds the more compact fmtstrs by using fromstr( of the control sequences) ### Response: def _getitem_normalized(self, index): """Builds the more compact fmtstrs by using fromstr( of the control sequences)""" index = normalize_slice(...
def _next_condition_lexems(self, source_code, source_code_size): """Return condition lexem readed in source_code""" # find three lexems lexems = tuple(( self._next_lexem(LEXEM_TYPE_COMPARISON, source_code, source_code_size), self._next_lexem(LEXEM_TYPE_OPERATOR , source_...
Return condition lexem readed in source_code
Below is the the instruction that describes the task: ### Input: Return condition lexem readed in source_code ### Response: def _next_condition_lexems(self, source_code, source_code_size): """Return condition lexem readed in source_code""" # find three lexems lexems = tuple(( se...
def run(self, args): """**down** [*count*] Move the current frame down in the stack trace (to a newer frame). 0 is the most recent frame. If no count is given, move down 1. See also: --------- `up` and `frame`.""" Mframe.adjust_relative(self.proc, self.name, args, self.signum) return False
**down** [*count*] Move the current frame down in the stack trace (to a newer frame). 0 is the most recent frame. If no count is given, move down 1. See also: --------- `up` and `frame`.
Below is the the instruction that describes the task: ### Input: **down** [*count*] Move the current frame down in the stack trace (to a newer frame). 0 is the most recent frame. If no count is given, move down 1. See also: --------- `up` and `frame`. ### Response: def run(self, args): """**down** [*cou...
def parse_operand(string, location, tokens): """Parse an x86 instruction operand. """ mod = " ".join(tokens.get("modifier", "")) if "immediate" in tokens: imm = parse_immediate("".join(tokens["immediate"])) size = modifier_size.get(mod, None) oprnd = X86ImmediateOperand(imm, si...
Parse an x86 instruction operand.
Below is the the instruction that describes the task: ### Input: Parse an x86 instruction operand. ### Response: def parse_operand(string, location, tokens): """Parse an x86 instruction operand. """ mod = " ".join(tokens.get("modifier", "")) if "immediate" in tokens: imm = parse_immediate(...
def get_child(self, usage_id): """Return the child identified by ``usage_id``.""" if usage_id in self._child_cache: return self._child_cache[usage_id] child_block = self.runtime.get_block(usage_id, for_parent=self) self._child_cache[usage_id] = child_block return chi...
Return the child identified by ``usage_id``.
Below is the the instruction that describes the task: ### Input: Return the child identified by ``usage_id``. ### Response: def get_child(self, usage_id): """Return the child identified by ``usage_id``.""" if usage_id in self._child_cache: return self._child_cache[usage_id] chi...
def dark(app): """ Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication instance. """ _apply_base_theme(app) darkPalette = QPalette() # base darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180)) darkPalette.setColor(QPalet...
Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication instance.
Below is the the instruction that describes the task: ### Input: Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication instance. ### Response: def dark(app): """ Apply Dark Theme to the Qt application instance. Args: app (QApplication)...
def lookup_task(self, task): """ Looks up a task by name or by callable """ if isinstance(task, str): try: return self[task] except KeyError: pass raise TaskError('Unknown task %s' % task)
Looks up a task by name or by callable
Below is the the instruction that describes the task: ### Input: Looks up a task by name or by callable ### Response: def lookup_task(self, task): """ Looks up a task by name or by callable """ if isinstance(task, str): try: return self[task] ...
def validate_env(self, envname): """ Check the name of the environment against the black list and the whitelist. If a whitelist is specified only it is checked. """ if self.whitelist_envs and envname in self.whitelist_envs: return True elif self.whitelist_envs...
Check the name of the environment against the black list and the whitelist. If a whitelist is specified only it is checked.
Below is the the instruction that describes the task: ### Input: Check the name of the environment against the black list and the whitelist. If a whitelist is specified only it is checked. ### Response: def validate_env(self, envname): """ Check the name of the environment against the black...
async def clean(self): """ Close all the running tasks watching for a container timeout. All references to containers are removed: any attempt to was_killed after a call to clean() will return None. """ for x in self._running_asyncio_tasks: x.cancel() self._contai...
Close all the running tasks watching for a container timeout. All references to containers are removed: any attempt to was_killed after a call to clean() will return None.
Below is the the instruction that describes the task: ### Input: Close all the running tasks watching for a container timeout. All references to containers are removed: any attempt to was_killed after a call to clean() will return None. ### Response: async def clean(self): """ Close all the run...
def read_local_conf(local_conf): """Search for conf.py in any rel_source directory in CWD and if found read it and return. :param str local_conf: Path to conf.py to read. :return: Loaded conf.py. :rtype: dict """ log = logging.getLogger(__name__) # Attempt to read. log.info('Reading c...
Search for conf.py in any rel_source directory in CWD and if found read it and return. :param str local_conf: Path to conf.py to read. :return: Loaded conf.py. :rtype: dict
Below is the the instruction that describes the task: ### Input: Search for conf.py in any rel_source directory in CWD and if found read it and return. :param str local_conf: Path to conf.py to read. :return: Loaded conf.py. :rtype: dict ### Response: def read_local_conf(local_conf): """Search fo...
def get_normalized_term(term_id: str, equivalents: list, namespace_targets: dict) -> str: """Get normalized term""" if equivalents and len(equivalents) > 0: for start_ns in namespace_targets: if re.match(start_ns, term_id): for target_ns in namespace_targets[start_ns]: ...
Get normalized term
Below is the the instruction that describes the task: ### Input: Get normalized term ### Response: def get_normalized_term(term_id: str, equivalents: list, namespace_targets: dict) -> str: """Get normalized term""" if equivalents and len(equivalents) > 0: for start_ns in namespace_targets: ...
def get_all_supported_exts_for_type(self, type_to_match: Type[Any], strict: bool) -> Set[str]: """ Utility method to return the set of all supported file extensions that may be converted to objects of the given type. type=JOKER is a joker that means all types :param type_to_match: ...
Utility method to return the set of all supported file extensions that may be converted to objects of the given type. type=JOKER is a joker that means all types :param type_to_match: :param strict: :return:
Below is the the instruction that describes the task: ### Input: Utility method to return the set of all supported file extensions that may be converted to objects of the given type. type=JOKER is a joker that means all types :param type_to_match: :param strict: :return: ### Respons...
def from_str(string, max_number=9, separator="."): """Parses string :param string: Version :param max_number: Max number reachable by sub :param separator: Version numbers are separated with this split :return: Parses string and returns object """ tokens = string...
Parses string :param string: Version :param max_number: Max number reachable by sub :param separator: Version numbers are separated with this split :return: Parses string and returns object
Below is the the instruction that describes the task: ### Input: Parses string :param string: Version :param max_number: Max number reachable by sub :param separator: Version numbers are separated with this split :return: Parses string and returns object ### Response: def from_str(...
def king(surface_tilt, dhi, ghi, solar_zenith): ''' Determine diffuse irradiance from the sky on a tilted surface using the King model. King's model determines the diffuse irradiance from the sky (ground reflected irradiance is not included in this algorithm) on a tilted surface using the surfa...
Determine diffuse irradiance from the sky on a tilted surface using the King model. King's model determines the diffuse irradiance from the sky (ground reflected irradiance is not included in this algorithm) on a tilted surface using the surface tilt angle, diffuse horizontal irradiance, global hor...
Below is the the instruction that describes the task: ### Input: Determine diffuse irradiance from the sky on a tilted surface using the King model. King's model determines the diffuse irradiance from the sky (ground reflected irradiance is not included in this algorithm) on a tilted surface using ...
def _split_into_chunks(self): """Split the code object into a list of `Chunk` objects. Each chunk is only entered at its first instruction, though there can be many exits from a chunk. Returns a list of `Chunk` objects. """ # The list of chunks so far, and the one we'r...
Split the code object into a list of `Chunk` objects. Each chunk is only entered at its first instruction, though there can be many exits from a chunk. Returns a list of `Chunk` objects.
Below is the the instruction that describes the task: ### Input: Split the code object into a list of `Chunk` objects. Each chunk is only entered at its first instruction, though there can be many exits from a chunk. Returns a list of `Chunk` objects. ### Response: def _split_into_chunks(...
def parse_template(template): """returns a 2-tuple of (template_name, number_of_priors)""" m = TEMPLATE_OVERRIDE_RE.match(template) if not m: return template, 0 return m.group('template'), int(m.group('depth'))
returns a 2-tuple of (template_name, number_of_priors)
Below is the the instruction that describes the task: ### Input: returns a 2-tuple of (template_name, number_of_priors) ### Response: def parse_template(template): """returns a 2-tuple of (template_name, number_of_priors)""" m = TEMPLATE_OVERRIDE_RE.match(template) if not m: return template, 0 ...
def population(self): """Return population, N. Returns ------- int The population (N) of the confusion table Example ------- >>> ct = ConfusionTable(120, 60, 20, 30) >>> ct.population() 230 """ return self._tp + self....
Return population, N. Returns ------- int The population (N) of the confusion table Example ------- >>> ct = ConfusionTable(120, 60, 20, 30) >>> ct.population() 230
Below is the the instruction that describes the task: ### Input: Return population, N. Returns ------- int The population (N) of the confusion table Example ------- >>> ct = ConfusionTable(120, 60, 20, 30) >>> ct.population() 230 ### Resp...
def preformat_cache(cache, start=None, end=None): """Preprocess a `list` of file paths for reading. - read the cache from the file (if necessary) - sieve the cache to only include data we need Parameters ---------- cache : `list`, `str` List of file paths, or path to a LAL-format cache...
Preprocess a `list` of file paths for reading. - read the cache from the file (if necessary) - sieve the cache to only include data we need Parameters ---------- cache : `list`, `str` List of file paths, or path to a LAL-format cache file on disk. start : `~gwpy.time.LIGOTimeGPS`, `fl...
Below is the the instruction that describes the task: ### Input: Preprocess a `list` of file paths for reading. - read the cache from the file (if necessary) - sieve the cache to only include data we need Parameters ---------- cache : `list`, `str` List of file paths, or path to a LAL-...
def refresh(self, wait_for_active=False, retry_seconds=5): """ Refresh all of the fields of the Table object by calling the underlying DescribeTable request. :type wait_for_active: bool :param wait_for_active: If True, this command will not return until the table sta...
Refresh all of the fields of the Table object by calling the underlying DescribeTable request. :type wait_for_active: bool :param wait_for_active: If True, this command will not return until the table status, as returned from Amazon DynamoDB, is 'ACTIVE'. :type ...
Below is the the instruction that describes the task: ### Input: Refresh all of the fields of the Table object by calling the underlying DescribeTable request. :type wait_for_active: bool :param wait_for_active: If True, this command will not return until the table status, as re...
def set_config(self, config): """Update the component's configuration. Use the :py:meth:`get_config` method to get a copy of the component's configuration, update that copy then call :py:meth:`set_config` to update the component. This enables the configuration to be changed in a...
Update the component's configuration. Use the :py:meth:`get_config` method to get a copy of the component's configuration, update that copy then call :py:meth:`set_config` to update the component. This enables the configuration to be changed in a threadsafe manner while the comp...
Below is the the instruction that describes the task: ### Input: Update the component's configuration. Use the :py:meth:`get_config` method to get a copy of the component's configuration, update that copy then call :py:meth:`set_config` to update the component. This enables the conf...
def batch_size(self, batch_size): """Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer. .. note:: batch_size can not override MongoDB's internal limits on the ...
Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer. .. note:: batch_size can not override MongoDB's internal limits on the amount of data it will return to the client...
Below is the the instruction that describes the task: ### Input: Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer. .. note:: batch_size can not override MongoDB's internal...
def get_transcript_preferences(course_id): """ Retrieves course wide transcript preferences Arguments: course_id (str): course id """ try: transcript_preference = TranscriptPreference.objects.get(course_id=course_id) except TranscriptPreference.DoesNotExist: return ...
Retrieves course wide transcript preferences Arguments: course_id (str): course id
Below is the the instruction that describes the task: ### Input: Retrieves course wide transcript preferences Arguments: course_id (str): course id ### Response: def get_transcript_preferences(course_id): """ Retrieves course wide transcript preferences Arguments: course_id (str):...
def _coerce_state_from_string(value: Union[int, str]) -> str: """Return a proper state from a string input.""" try: return STATE_MAP[int(value)] except KeyError: _LOGGER.error('Unknown state: %s', value) return STATE_UNKNOWN
Return a proper state from a string input.
Below is the the instruction that describes the task: ### Input: Return a proper state from a string input. ### Response: def _coerce_state_from_string(value: Union[int, str]) -> str: """Return a proper state from a string input.""" try: return STATE_MAP[int(value)] except KeyEr...
def decode(code, *, max_age): """decode(code, *, max_age) Decodes the code from the registration link and returns a tuple consisting of the verified email address and the payload which was passed through to ``get_confirmation_code``. The maximum age in seconds of the link has to be specified as ``m...
decode(code, *, max_age) Decodes the code from the registration link and returns a tuple consisting of the verified email address and the payload which was passed through to ``get_confirmation_code``. The maximum age in seconds of the link has to be specified as ``max_age``. This method raises ``V...
Below is the the instruction that describes the task: ### Input: decode(code, *, max_age) Decodes the code from the registration link and returns a tuple consisting of the verified email address and the payload which was passed through to ``get_confirmation_code``. The maximum age in seconds of the...
def simDeath(self): ''' Randomly determine which consumers die, and distribute their wealth among the survivors. This method only works if there is only one period in the cycle. Parameters ---------- None Returns ------- who_dies : np.array(bool)...
Randomly determine which consumers die, and distribute their wealth among the survivors. This method only works if there is only one period in the cycle. Parameters ---------- None Returns ------- who_dies : np.array(bool) Boolean array of size Agent...
Below is the the instruction that describes the task: ### Input: Randomly determine which consumers die, and distribute their wealth among the survivors. This method only works if there is only one period in the cycle. Parameters ---------- None Returns ------- ...
def unpack_rsp(cls, rsp_pb): """Convert from PLS response to user response""" ret_type = rsp_pb.retType ret_msg = rsp_pb.retMsg if ret_type != RET_OK: return RET_ERROR, ret_msg, None raw_snapshot_list = rsp_pb.s2c.snapshotList snapshot_list = [] for...
Convert from PLS response to user response
Below is the the instruction that describes the task: ### Input: Convert from PLS response to user response ### Response: def unpack_rsp(cls, rsp_pb): """Convert from PLS response to user response""" ret_type = rsp_pb.retType ret_msg = rsp_pb.retMsg if ret_type != RET_OK: ...
def get_frameshift_lengths(num_bins): """Simple function that returns the lengths for each frameshift category if `num_bins` number of frameshift categories are requested. """ fs_len = [] i = 1 tmp_bins = 0 while(tmp_bins<num_bins): if i%3: fs_len.append(i) tm...
Simple function that returns the lengths for each frameshift category if `num_bins` number of frameshift categories are requested.
Below is the the instruction that describes the task: ### Input: Simple function that returns the lengths for each frameshift category if `num_bins` number of frameshift categories are requested. ### Response: def get_frameshift_lengths(num_bins): """Simple function that returns the lengths for each frames...
def do_verify(marfile, keyfiles=None): """Verify the MAR file.""" try: with open(marfile, 'rb') as f: with MarReader(f) as m: # Check various parts of the mar file # e.g. signature algorithms and additional block sections errors = m.get_errors(...
Verify the MAR file.
Below is the the instruction that describes the task: ### Input: Verify the MAR file. ### Response: def do_verify(marfile, keyfiles=None): """Verify the MAR file.""" try: with open(marfile, 'rb') as f: with MarReader(f) as m: # Check various parts of the mar file ...
def create_node(self, *args, **kwargs): """ Creates a new VPCS VM. :returns: VPCSVM instance """ node = yield from super().create_node(*args, **kwargs) self._free_mac_ids.setdefault(node.project.id, list(range(0, 255))) try: self._used_mac_ids[node.i...
Creates a new VPCS VM. :returns: VPCSVM instance
Below is the the instruction that describes the task: ### Input: Creates a new VPCS VM. :returns: VPCSVM instance ### Response: def create_node(self, *args, **kwargs): """ Creates a new VPCS VM. :returns: VPCSVM instance """ node = yield from super().create_node(*...
def _waitForIP(cls, instance): """ Wait until the instances has a public IP address assigned to it. :type instance: boto.ec2.instance.Instance """ logger.debug('Waiting for ip...') while True: time.sleep(a_short_time) instance.update() ...
Wait until the instances has a public IP address assigned to it. :type instance: boto.ec2.instance.Instance
Below is the the instruction that describes the task: ### Input: Wait until the instances has a public IP address assigned to it. :type instance: boto.ec2.instance.Instance ### Response: def _waitForIP(cls, instance): """ Wait until the instances has a public IP address assigned to it. ...
def add_response_headers(self, headers, **overrides): """Adds the specified response headers while keeping existing ones in-tact""" response_headers = self.route.get('response_headers', {}).copy() response_headers.update(headers) return self.where(response_headers=response_headers, **ove...
Adds the specified response headers while keeping existing ones in-tact
Below is the the instruction that describes the task: ### Input: Adds the specified response headers while keeping existing ones in-tact ### Response: def add_response_headers(self, headers, **overrides): """Adds the specified response headers while keeping existing ones in-tact""" response_headers...
def _generate_footer(notebook_object, notebook_type): """ Internal function that is used for generation of the notebooks footer. ---------- Parameters ---------- notebook_object : notebook object Object of "notebook" class where the header will be created. notebook_type : str ...
Internal function that is used for generation of the notebooks footer. ---------- Parameters ---------- notebook_object : notebook object Object of "notebook" class where the header will be created. notebook_type : str Notebook type: - "Main_Files_Signal_Samples" ...
Below is the the instruction that describes the task: ### Input: Internal function that is used for generation of the notebooks footer. ---------- Parameters ---------- notebook_object : notebook object Object of "notebook" class where the header will be created. notebook_type : str ...
def __get_search_results(self, url, limit, order_by, sort_order, filter): """ helper function for getting search results up to specified limit on the number of results. The Fred HTTP API truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data...
helper function for getting search results up to specified limit on the number of results. The Fred HTTP API truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data.
Below is the the instruction that describes the task: ### Input: helper function for getting search results up to specified limit on the number of results. The Fred HTTP API truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data. ### Response: def __ge...
def get_family_search_session(self, proxy=None): """Gets the ``OsidSession`` associated with the family search service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.FamilySearchSession) - a ``FamilySearchSession`` raise: NullArgument - ``proxy`` ...
Gets the ``OsidSession`` associated with the family search service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.FamilySearchSession) - a ``FamilySearchSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to comp...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the family search service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.FamilySearchSession) - a ``FamilySearchSession`` raise: NullArgument - `...
def create_new_process(self, create_request): """CreateNewProcess. [Preview API] Creates a process. :param :class:`<CreateProcessModel> <azure.devops.v5_0.work_item_tracking_process.models.CreateProcessModel>` create_request: CreateProcessModel. :rtype: :class:`<ProcessInfo> <azure.devop...
CreateNewProcess. [Preview API] Creates a process. :param :class:`<CreateProcessModel> <azure.devops.v5_0.work_item_tracking_process.models.CreateProcessModel>` create_request: CreateProcessModel. :rtype: :class:`<ProcessInfo> <azure.devops.v5_0.work_item_tracking_process.models.ProcessInfo>`
Below is the the instruction that describes the task: ### Input: CreateNewProcess. [Preview API] Creates a process. :param :class:`<CreateProcessModel> <azure.devops.v5_0.work_item_tracking_process.models.CreateProcessModel>` create_request: CreateProcessModel. :rtype: :class:`<ProcessInfo> ...
def quast_predicted_genes_barplot(self): """ Make a bar plot showing the number and length of predicted genes for each assembly """ # Prep the data # extract the ranges given to quast with "--gene-thresholds" prefix = '# predicted genes (>= ' suffix = ' b...
Make a bar plot showing the number and length of predicted genes for each assembly
Below is the the instruction that describes the task: ### Input: Make a bar plot showing the number and length of predicted genes for each assembly ### Response: def quast_predicted_genes_barplot(self): """ Make a bar plot showing the number and length of predicted genes for each as...
def geopotential_to_height(geopot): r"""Compute height from a given geopotential. Parameters ---------- geopotential : `pint.Quantity` Geopotential (array_like) Returns ------- `pint.Quantity` The corresponding height value(s) Examples -------- >>> from metpy.c...
r"""Compute height from a given geopotential. Parameters ---------- geopotential : `pint.Quantity` Geopotential (array_like) Returns ------- `pint.Quantity` The corresponding height value(s) Examples -------- >>> from metpy.constants import g, G, me, Re >>> imp...
Below is the the instruction that describes the task: ### Input: r"""Compute height from a given geopotential. Parameters ---------- geopotential : `pint.Quantity` Geopotential (array_like) Returns ------- `pint.Quantity` The corresponding height value(s) Examples ...
def _download(self, force_overwrite=False, verbose=False): """ Download the file if it's not already there. We shouldn't *need* to overwrite; the xml is not supposed to update. """ if not force_overwrite: # If the file is already there, we're done if os.pa...
Download the file if it's not already there. We shouldn't *need* to overwrite; the xml is not supposed to update.
Below is the the instruction that describes the task: ### Input: Download the file if it's not already there. We shouldn't *need* to overwrite; the xml is not supposed to update. ### Response: def _download(self, force_overwrite=False, verbose=False): """ Download the file if it's not alrea...
def on_train_end(self, **kwargs): "Load the best model." if self.save_model: # Adapted from fast.ai "SaveModelCallback" if self.model_path.is_file(): with self.model_path.open('rb') as model_file: self.learn.load(model_file, purge=False) ...
Load the best model.
Below is the the instruction that describes the task: ### Input: Load the best model. ### Response: def on_train_end(self, **kwargs): "Load the best model." if self.save_model: # Adapted from fast.ai "SaveModelCallback" if self.model_path.is_file(): with sel...
def print_new_versions(strict=False): """Prints new requirement versions.""" new_updates = [] same_updates = [] for req in everything_in(all_reqs): new_versions = [] same_versions = [] for ver_str in all_versions(req): if newer(ver_str_to_tuple(ver_str), min_versions[...
Prints new requirement versions.
Below is the the instruction that describes the task: ### Input: Prints new requirement versions. ### Response: def print_new_versions(strict=False): """Prints new requirement versions.""" new_updates = [] same_updates = [] for req in everything_in(all_reqs): new_versions = [] same_...
def get_repos(self, type=github.GithubObject.NotSet, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet): """ :calls: `GET /users/:user/repos <http://developer.github.com/v3/repos>`_ :param type: string :param sort: string :param direction: st...
:calls: `GET /users/:user/repos <http://developer.github.com/v3/repos>`_ :param type: string :param sort: string :param direction: string :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
Below is the the instruction that describes the task: ### Input: :calls: `GET /users/:user/repos <http://developer.github.com/v3/repos>`_ :param type: string :param sort: string :param direction: string :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository....
def last_word(text, include='alphanum_underscore'): """ Find the last word in a sentence. >>> last_word('abc') 'abc' >>> last_word(' abc') 'abc' >>> last_word('') '' >>> last_word(' ') '' >>> last_word('abc ') '' >>> last_word('abc def') 'def' >>> last_word('a...
Find the last word in a sentence. >>> last_word('abc') 'abc' >>> last_word(' abc') 'abc' >>> last_word('') '' >>> last_word(' ') '' >>> last_word('abc ') '' >>> last_word('abc def') 'def' >>> last_word('abc def ') '' >>> last_word('abc def;') '' >>> la...
Below is the the instruction that describes the task: ### Input: Find the last word in a sentence. >>> last_word('abc') 'abc' >>> last_word(' abc') 'abc' >>> last_word('') '' >>> last_word(' ') '' >>> last_word('abc ') '' >>> last_word('abc def') 'def' >>> last_wo...
def loop_getter( self ) -> typing.Optional[typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop]]: """Loop getter. :rtype: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] """ return self.__loop...
Loop getter. :rtype: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop]
Below is the the instruction that describes the task: ### Input: Loop getter. :rtype: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] ### Response: def loop_getter( self ) -> typing.Optional[typing.Union[typing.Callable[..., asyncio.AbstractEventL...
def calc_atlases(worklog, atlas_subject_id='fsaverage'): ''' cacl_atlases finds all available atlases in the possible subject directories of the given atlas subject. In order to be a template, it must either be a collection of files (either mgh/mgz or FreeSurfer curv/morph-data files) named as '<he...
cacl_atlases finds all available atlases in the possible subject directories of the given atlas subject. In order to be a template, it must either be a collection of files (either mgh/mgz or FreeSurfer curv/morph-data files) named as '<hemi>.<template>_<quantity><ending>' such as the files 'lh.wang2015...
Below is the the instruction that describes the task: ### Input: cacl_atlases finds all available atlases in the possible subject directories of the given atlas subject. In order to be a template, it must either be a collection of files (either mgh/mgz or FreeSurfer curv/morph-data files) named as '<he...
def set_runtime_value_bool(self, ihcid: int, value: bool) -> bool: """ Set bool runtime value with re-authenticate if needed""" if self.client.set_runtime_value_bool(ihcid, value): return True self.re_authenticate() return self.client.set_runtime_value_bool(ihcid, value)
Set bool runtime value with re-authenticate if needed
Below is the the instruction that describes the task: ### Input: Set bool runtime value with re-authenticate if needed ### Response: def set_runtime_value_bool(self, ihcid: int, value: bool) -> bool: """ Set bool runtime value with re-authenticate if needed""" if self.client.set_runtime_value_bool(...
def save_function_tuple(self, func): """ Pickles an actual func object. A func comprises: code, globals, defaults, closure, and dict. We extract and save these, injecting reducing functions at certain points to recreate the func object. Keep in mind that some of these pieces ...
Pickles an actual func object. A func comprises: code, globals, defaults, closure, and dict. We extract and save these, injecting reducing functions at certain points to recreate the func object. Keep in mind that some of these pieces can contain a ref to the func itself. Thus, a nai...
Below is the the instruction that describes the task: ### Input: Pickles an actual func object. A func comprises: code, globals, defaults, closure, and dict. We extract and save these, injecting reducing functions at certain points to recreate the func object. Keep in mind that some of th...
def _get_summary(self, text, **kwargs): """ Render out just the summary """ card = cards.extract_card(text, kwargs, self.search_path) return flask.Markup((card.description or '').strip())
Render out just the summary
Below is the the instruction that describes the task: ### Input: Render out just the summary ### Response: def _get_summary(self, text, **kwargs): """ Render out just the summary """ card = cards.extract_card(text, kwargs, self.search_path) return flask.Markup((card.description or '').stri...
def bbox(self): """ The minimal `~photutils.aperture.BoundingBox` for the cutout region with respect to the original (large) image. """ return BoundingBox(self.slices[1].start, self.slices[1].stop, self.slices[0].start, self.slices[0].stop)
The minimal `~photutils.aperture.BoundingBox` for the cutout region with respect to the original (large) image.
Below is the the instruction that describes the task: ### Input: The minimal `~photutils.aperture.BoundingBox` for the cutout region with respect to the original (large) image. ### Response: def bbox(self): """ The minimal `~photutils.aperture.BoundingBox` for the cutout region with...
def add_blacklisted_plugins(self, plugins): """ add blacklisted plugins. `plugins` may be a single object or iterable. """ plugins = util.return_list(plugins) self.blacklisted_plugins.extend(plugins)
add blacklisted plugins. `plugins` may be a single object or iterable.
Below is the the instruction that describes the task: ### Input: add blacklisted plugins. `plugins` may be a single object or iterable. ### Response: def add_blacklisted_plugins(self, plugins): """ add blacklisted plugins. `plugins` may be a single object or iterable. """ ...
def add_step(self, step, step_id): """ Add a step to the list. The first step added becomes the initial step. """ assert step_id not in self._steps assert step_id not in self._order assert isinstance(step, Step) self._steps[step_id] = step self._order.append(step...
Add a step to the list. The first step added becomes the initial step.
Below is the the instruction that describes the task: ### Input: Add a step to the list. The first step added becomes the initial step. ### Response: def add_step(self, step, step_id): """ Add a step to the list. The first step added becomes the initial step. """ assert step_id not ...
def estimate_assignment_probs(bitstring_prep_histograms): """ Compute the estimated assignment probability matrix for a sequence of single shot histograms obtained by running the programs generated by `basis_state_preps()`. bitstring_prep_histograms[i,j] = #number of measured outcomes j when runnin...
Compute the estimated assignment probability matrix for a sequence of single shot histograms obtained by running the programs generated by `basis_state_preps()`. bitstring_prep_histograms[i,j] = #number of measured outcomes j when running program i The assignment probability is obtained by transposing...
Below is the the instruction that describes the task: ### Input: Compute the estimated assignment probability matrix for a sequence of single shot histograms obtained by running the programs generated by `basis_state_preps()`. bitstring_prep_histograms[i,j] = #number of measured outcomes j when running...
def ForceRemoveFileObject(self, path_spec): """Forces the removal of a file-like object based on a path specification. Args: path_spec (PathSpec): path specification. Returns: bool: True if the file-like object was cached. """ cache_value = self._file_object_cache.GetCacheValue(path_sp...
Forces the removal of a file-like object based on a path specification. Args: path_spec (PathSpec): path specification. Returns: bool: True if the file-like object was cached.
Below is the the instruction that describes the task: ### Input: Forces the removal of a file-like object based on a path specification. Args: path_spec (PathSpec): path specification. Returns: bool: True if the file-like object was cached. ### Response: def ForceRemoveFileObject(self, path_s...
def _handle_response(self, zbx_answer): """ Analyze Zabbix Server response Returns a list with number of: * processed items * failed items * total items * time spent :zbx_answer: Zabbix server response as string """ zbx_answer = json.loads...
Analyze Zabbix Server response Returns a list with number of: * processed items * failed items * total items * time spent :zbx_answer: Zabbix server response as string
Below is the the instruction that describes the task: ### Input: Analyze Zabbix Server response Returns a list with number of: * processed items * failed items * total items * time spent :zbx_answer: Zabbix server response as string ### Response: def _handle_respons...
def _set_ethernet(self, v, load=False): """ Setter method for ethernet, mapped from YANG variable /interface/ethernet (list) If this variable is read-only (config: false) in the source YANG file, then _set_ethernet is considered as a private method. Backends looking to populate this variable should ...
Setter method for ethernet, mapped from YANG variable /interface/ethernet (list) If this variable is read-only (config: false) in the source YANG file, then _set_ethernet is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ethernet() direct...
Below is the the instruction that describes the task: ### Input: Setter method for ethernet, mapped from YANG variable /interface/ethernet (list) If this variable is read-only (config: false) in the source YANG file, then _set_ethernet is considered as a private method. Backends looking to populate this...
def copy_directory(src, dest, force=False): ''' Copy an entire directory recursively ''' if os.path.exists(dest) and force is True: shutil.rmtree(dest) try: shutil.copytree(src, dest) except OSError as e: # If the error was caused because the source wasn't a directory ...
Copy an entire directory recursively
Below is the the instruction that describes the task: ### Input: Copy an entire directory recursively ### Response: def copy_directory(src, dest, force=False): ''' Copy an entire directory recursively ''' if os.path.exists(dest) and force is True: shutil.rmtree(dest) try: shutil.co...
def identify_triggers( cfg, sources, sinks, lattice, nosec_lines ): """Identify sources, sinks and sanitisers in a CFG. Args: cfg(CFG): CFG to find sources, sinks and sanitisers in. sources(tuple): list of sources, a source is a (source, sanitiser) tuple. sinks(tuple...
Identify sources, sinks and sanitisers in a CFG. Args: cfg(CFG): CFG to find sources, sinks and sanitisers in. sources(tuple): list of sources, a source is a (source, sanitiser) tuple. sinks(tuple): list of sources, a sink is a (sink, sanitiser) tuple. nosec_lines(set): lines with #...
Below is the the instruction that describes the task: ### Input: Identify sources, sinks and sanitisers in a CFG. Args: cfg(CFG): CFG to find sources, sinks and sanitisers in. sources(tuple): list of sources, a source is a (source, sanitiser) tuple. sinks(tuple): list of sources, a sink...
def __install_ssh_config(self, config): """ Install the ssh configuration """ if not config.is_affirmative('use_global_ssh', default="no"): ssh_config_injection = self._build_ssh_config(config) if not os.path.exists(ssh_config_path): if self.inje...
Install the ssh configuration
Below is the the instruction that describes the task: ### Input: Install the ssh configuration ### Response: def __install_ssh_config(self, config): """ Install the ssh configuration """ if not config.is_affirmative('use_global_ssh', default="no"): ssh_config_injection =...
def parse(self, s, term_join=None): """ Parses search term to Args: s (str): string with search term. or_join (callable): function to join 'OR' terms. Returns: dict: all of the terms grouped by marker. Key is a marker, value is a term. Example: ...
Parses search term to Args: s (str): string with search term. or_join (callable): function to join 'OR' terms. Returns: dict: all of the terms grouped by marker. Key is a marker, value is a term. Example: >>> SearchTermParser().parse('table2 fro...
Below is the the instruction that describes the task: ### Input: Parses search term to Args: s (str): string with search term. or_join (callable): function to join 'OR' terms. Returns: dict: all of the terms grouped by marker. Key is a marker, value is a term. ...
def get_logs(self, stdout=True, stderr=True, timestamps=False, tail='all', since=None): """ Get container logs. This method does not support streaming, use :meth:`stream_logs` for that. """ return self.inner().logs( stdout=stdout, stderr=stde...
Get container logs. This method does not support streaming, use :meth:`stream_logs` for that.
Below is the the instruction that describes the task: ### Input: Get container logs. This method does not support streaming, use :meth:`stream_logs` for that. ### Response: def get_logs(self, stdout=True, stderr=True, timestamps=False, tail='all', since=None): """ ...