code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def bfill(self, dim, limit=None): '''Fill NaN values by propogating values backward *Requires bottleneck.* Parameters ---------- dim : str Specifies the dimension along which to propagate values when filling. limit : int, default None ...
Fill NaN values by propogating values backward *Requires bottleneck.* Parameters ---------- dim : str Specifies the dimension along which to propagate values when filling. limit : int, default None The maximum number of consecutive NaN values...
Below is the the instruction that describes the task: ### Input: Fill NaN values by propogating values backward *Requires bottleneck.* Parameters ---------- dim : str Specifies the dimension along which to propagate values when filling. limit : int, ...
def apply_grad_cartesian_tensor(grad_X, zmat_dist): """Apply the gradient for transformation to cartesian space onto zmat_dist. Args: grad_X (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array. The mathematical details of the index layout is explained in :meth:`~chemcoord.Cartesi...
Apply the gradient for transformation to cartesian space onto zmat_dist. Args: grad_X (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array. The mathematical details of the index layout is explained in :meth:`~chemcoord.Cartesian.get_grad_zmat()`. zmat_dist (:class:`~chemcoord....
Below is the the instruction that describes the task: ### Input: Apply the gradient for transformation to cartesian space onto zmat_dist. Args: grad_X (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array. The mathematical details of the index layout is explained in :meth:`~chemcoo...
def insertBefore(self, node, refNode): """Insert node as a child of the current node, before refNode in the list of child nodes. Raises ValueError if refNode is not a child of the current node""" offset = self.xml_children.index(refNode) self.xml_insert(node, offset)
Insert node as a child of the current node, before refNode in the list of child nodes. Raises ValueError if refNode is not a child of the current node
Below is the the instruction that describes the task: ### Input: Insert node as a child of the current node, before refNode in the list of child nodes. Raises ValueError if refNode is not a child of the current node ### Response: def insertBefore(self, node, refNode): """Insert node as a ch...
def setDateTimeStart(self, dtime): """ Sets the starting date time for this gantt chart. :param dtime | <QDateTime> """ self._dateStart = dtime.date() self._timeStart = dtime.time() self._allDay = False
Sets the starting date time for this gantt chart. :param dtime | <QDateTime>
Below is the the instruction that describes the task: ### Input: Sets the starting date time for this gantt chart. :param dtime | <QDateTime> ### Response: def setDateTimeStart(self, dtime): """ Sets the starting date time for this gantt chart. :param ...
def info(self, action=None): """ returns cached request info for given action, or list of cached actions """ if action in self.cache: return self.cache[action]['info'] return self.cache.keys() or None
returns cached request info for given action, or list of cached actions
Below is the the instruction that describes the task: ### Input: returns cached request info for given action, or list of cached actions ### Response: def info(self, action=None): """ returns cached request info for given action, or list of cached actions """ if acti...
def write_matrix_to_tsv(net, filename=None, df=None): ''' This will export the matrix in net.dat or a dataframe (optional df in arguments) as a tsv file. Row/column categories will be saved as tuples in tsv, which can be read back into the network object. ''' import pandas as pd if df is None: df = n...
This will export the matrix in net.dat or a dataframe (optional df in arguments) as a tsv file. Row/column categories will be saved as tuples in tsv, which can be read back into the network object.
Below is the the instruction that describes the task: ### Input: This will export the matrix in net.dat or a dataframe (optional df in arguments) as a tsv file. Row/column categories will be saved as tuples in tsv, which can be read back into the network object. ### Response: def write_matrix_to_tsv(net, filen...
def timeSeries(self, tag = None, outputFile = None, giveYears = True, greatestFirst = True, limitTo = False, pandasMode = True): """Creates an pandas dict of the ordered list of all the values of _tag_, with and ranked by the year the occurred in, multiple year occurrences will create multiple entries. A list c...
Creates an pandas dict of the ordered list of all the values of _tag_, with and ranked by the year the occurred in, multiple year occurrences will create multiple entries. A list can also be returned with the the counts or years added or it can be written to a file. If no _tag_ is given the `Records` in the co...
Below is the the instruction that describes the task: ### Input: Creates an pandas dict of the ordered list of all the values of _tag_, with and ranked by the year the occurred in, multiple year occurrences will create multiple entries. A list can also be returned with the the counts or years added or it can be wri...
def path_wrapper(func): """return the given infer function wrapped to handle the path Used to stop inference if the node has already been looked at for a given `InferenceContext` to prevent infinite recursion """ @functools.wraps(func) def wrapped(node, context=None, _func=func, **kwargs): ...
return the given infer function wrapped to handle the path Used to stop inference if the node has already been looked at for a given `InferenceContext` to prevent infinite recursion
Below is the the instruction that describes the task: ### Input: return the given infer function wrapped to handle the path Used to stop inference if the node has already been looked at for a given `InferenceContext` to prevent infinite recursion ### Response: def path_wrapper(func): """return the giv...
def set_multi(self, mappings, time=0, compress_level=-1): """ Set multiple keys with it's values on server. :param mappings: A dict with keys/values :type mappings: dict :param time: Time in seconds that your key will expire. :type time: int :param compress_level...
Set multiple keys with it's values on server. :param mappings: A dict with keys/values :type mappings: dict :param time: Time in seconds that your key will expire. :type time: int :param compress_level: How much to compress. 0 = no compression, 1 = fastest, 9 = slowe...
Below is the the instruction that describes the task: ### Input: Set multiple keys with it's values on server. :param mappings: A dict with keys/values :type mappings: dict :param time: Time in seconds that your key will expire. :type time: int :param compress_level: How muc...
def text(length=None, at_least=10, at_most=15, lowercase=True, uppercase=True, digits=True, spaces=True, punctuation=False): """ Random text. If `length` is present the text will be exactly this chars long. Else the text will be something between `at_least` and `at_most` chars long. """ ...
Random text. If `length` is present the text will be exactly this chars long. Else the text will be something between `at_least` and `at_most` chars long.
Below is the the instruction that describes the task: ### Input: Random text. If `length` is present the text will be exactly this chars long. Else the text will be something between `at_least` and `at_most` chars long. ### Response: def text(length=None, at_least=10, at_most=15, lowercase=True, ...
def get_reporter_state(): """Get pep8 reporter state from stack.""" # Stack # 1. get_reporter_state (i.e. this function) # 2. putty_ignore_code # 3. QueueReport.error or pep8.StandardReport.error for flake8 -j 1 # 4. pep8.Checker.check_ast or check_physical or check_logical # locals conta...
Get pep8 reporter state from stack.
Below is the the instruction that describes the task: ### Input: Get pep8 reporter state from stack. ### Response: def get_reporter_state(): """Get pep8 reporter state from stack.""" # Stack # 1. get_reporter_state (i.e. this function) # 2. putty_ignore_code # 3. QueueReport.error or pep8.Stand...
def visible(self, request): ''' Checks the both, check_visible and apply_visible, against the owned model and it's instance set ''' return self.apply_visible(self.get_queryset(), request) if self.check_visible(self.model, request) is not False else self.get_queryset().none()
Checks the both, check_visible and apply_visible, against the owned model and it's instance set
Below is the the instruction that describes the task: ### Input: Checks the both, check_visible and apply_visible, against the owned model and it's instance set ### Response: def visible(self, request): ''' Checks the both, check_visible and apply_visible, against the owned model and it's instance ...
def reset(self): """Reset accumulated components and metric values""" if self.parallel: from pyannote.metrics import manager_ self.accumulated_ = manager_.dict() self.results_ = manager_.list() self.uris_ = manager_.dict() else: self.ac...
Reset accumulated components and metric values
Below is the the instruction that describes the task: ### Input: Reset accumulated components and metric values ### Response: def reset(self): """Reset accumulated components and metric values""" if self.parallel: from pyannote.metrics import manager_ self.accumulated_ = man...
def add_channels_to_list(self, l, add_ref=False): """Create list of channels (one for those to plot, one for ref). Parameters ---------- l : instance of QListWidget one of the two lists (chan_to_plot or ref_chan) """ l.clear() l.setSelectionMode(QAbs...
Create list of channels (one for those to plot, one for ref). Parameters ---------- l : instance of QListWidget one of the two lists (chan_to_plot or ref_chan)
Below is the the instruction that describes the task: ### Input: Create list of channels (one for those to plot, one for ref). Parameters ---------- l : instance of QListWidget one of the two lists (chan_to_plot or ref_chan) ### Response: def add_channels_to_list(self, l, add_r...
def linear_add(self, other, scale_factor=1.0): """ Method to do a linear sum of volumetric objects. Used by + and - operators as well. Returns a VolumetricData object containing the linear sum. Args: other (VolumetricData): Another VolumetricData object s...
Method to do a linear sum of volumetric objects. Used by + and - operators as well. Returns a VolumetricData object containing the linear sum. Args: other (VolumetricData): Another VolumetricData object scale_factor (float): Factor to scale the other data by. Re...
Below is the the instruction that describes the task: ### Input: Method to do a linear sum of volumetric objects. Used by + and - operators as well. Returns a VolumetricData object containing the linear sum. Args: other (VolumetricData): Another VolumetricData object ...
def add(client, name, urls, link, relative_to, target, force): """Add data to a dataset.""" try: with client.with_dataset(name=name) as dataset: target = target if target else None with progressbar(urls, label='Adding data to dataset') as bar: for url in bar: ...
Add data to a dataset.
Below is the the instruction that describes the task: ### Input: Add data to a dataset. ### Response: def add(client, name, urls, link, relative_to, target, force): """Add data to a dataset.""" try: with client.with_dataset(name=name) as dataset: target = target if target else None ...
def _read_message(self): """ 必须启动新的greenlet,否则会有内存泄漏 """ job = gevent.spawn(super(GConnection, self)._read_message) job.join()
必须启动新的greenlet,否则会有内存泄漏
Below is the the instruction that describes the task: ### Input: 必须启动新的greenlet,否则会有内存泄漏 ### Response: def _read_message(self): """ 必须启动新的greenlet,否则会有内存泄漏 """ job = gevent.spawn(super(GConnection, self)._read_message) job.join()
def iter_chunks(cls, sock, return_bytes=False, timeout_object=None): """Generates chunks from a connected socket until an Exit chunk is sent or a timeout occurs. :param sock: the socket to read from. :param bool return_bytes: If False, decode the payload into a utf-8 string. :param cls.TimeoutProvider ...
Generates chunks from a connected socket until an Exit chunk is sent or a timeout occurs. :param sock: the socket to read from. :param bool return_bytes: If False, decode the payload into a utf-8 string. :param cls.TimeoutProvider timeout_object: If provided, will be checked every iteration for a ...
Below is the the instruction that describes the task: ### Input: Generates chunks from a connected socket until an Exit chunk is sent or a timeout occurs. :param sock: the socket to read from. :param bool return_bytes: If False, decode the payload into a utf-8 string. :param cls.TimeoutProvider timeout...
def reconnect(self): '''Connected the stream if needed. Coroutine. ''' if self._connection.closed(): self._connection.reset() yield from self._connection.connect()
Connected the stream if needed. Coroutine.
Below is the the instruction that describes the task: ### Input: Connected the stream if needed. Coroutine. ### Response: def reconnect(self): '''Connected the stream if needed. Coroutine. ''' if self._connection.closed(): self._connection.reset() ...
def makeSequenceRelative(absVSequence): ''' Puts every value in a list on a continuum between 0 and 1 Also returns the min and max values (to reverse the process) ''' if len(absVSequence) < 2 or len(set(absVSequence)) == 1: raise RelativizeSequenceException(absVSequence) minV = min(ab...
Puts every value in a list on a continuum between 0 and 1 Also returns the min and max values (to reverse the process)
Below is the the instruction that describes the task: ### Input: Puts every value in a list on a continuum between 0 and 1 Also returns the min and max values (to reverse the process) ### Response: def makeSequenceRelative(absVSequence): ''' Puts every value in a list on a continuum between 0 and 1 ...
def request_xml(url, auth=None): ''' Returns an etree.XMLRoot object loaded from the url :param str url: URL for the resource to load as an XML ''' try: r = requests.get(url, auth=auth, verify=False) return r.text.encode('utf-8') except BaseException: logger.error("Skippi...
Returns an etree.XMLRoot object loaded from the url :param str url: URL for the resource to load as an XML
Below is the the instruction that describes the task: ### Input: Returns an etree.XMLRoot object loaded from the url :param str url: URL for the resource to load as an XML ### Response: def request_xml(url, auth=None): ''' Returns an etree.XMLRoot object loaded from the url :param str url: URL for ...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label._to_dict() return _dict
Return a json dictionary representing this model.
Below is the the instruction that describes the task: ### Input: Return a json dictionary representing this model. ### Response: def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['la...
def project_update_event(self, proj_info): """Process project update event. There could be change in project name. DCNM doesn't allow change in project (a.k.a tenant). This event may be received for the DCI update. If the change is for DCI, update the DCI portion of the project name ...
Process project update event. There could be change in project name. DCNM doesn't allow change in project (a.k.a tenant). This event may be received for the DCI update. If the change is for DCI, update the DCI portion of the project name and send the update event to the DCNM.
Below is the the instruction that describes the task: ### Input: Process project update event. There could be change in project name. DCNM doesn't allow change in project (a.k.a tenant). This event may be received for the DCI update. If the change is for DCI, update the DCI portion of the p...
def _pfp__restore_snapshot(self, recurse=True): """Restore the snapshotted value without triggering any events """ super(Struct, self)._pfp__restore_snapshot(recurse=recurse) if recurse: for child in self._pfp__children: child._pfp__restore_snapshot(recurse=r...
Restore the snapshotted value without triggering any events
Below is the the instruction that describes the task: ### Input: Restore the snapshotted value without triggering any events ### Response: def _pfp__restore_snapshot(self, recurse=True): """Restore the snapshotted value without triggering any events """ super(Struct, self)._pfp__restore_sna...
def pandas(self): """get a pandas dataframe of prior and posterior for all predictions Returns: pandas.DataFrame : pandas.DataFrame a dataframe with prior and posterior uncertainty estimates for all forecasts (predictions) """ names,prior,post...
get a pandas dataframe of prior and posterior for all predictions Returns: pandas.DataFrame : pandas.DataFrame a dataframe with prior and posterior uncertainty estimates for all forecasts (predictions)
Below is the the instruction that describes the task: ### Input: get a pandas dataframe of prior and posterior for all predictions Returns: pandas.DataFrame : pandas.DataFrame a dataframe with prior and posterior uncertainty estimates for all forecasts (predictio...
def set_peripheral(self, power=None, pullup=None, aux=None, chip_select=None): """ Set the peripheral config at runtime. If a parameter is None then the config will not be changed. :param power: Set to True to enable the power supply or False to disable :param pullup: Set to True to ena...
Set the peripheral config at runtime. If a parameter is None then the config will not be changed. :param power: Set to True to enable the power supply or False to disable :param pullup: Set to True to enable the internal pull-up resistors. False to disable :param aux: Set the AUX pin ou...
Below is the the instruction that describes the task: ### Input: Set the peripheral config at runtime. If a parameter is None then the config will not be changed. :param power: Set to True to enable the power supply or False to disable :param pullup: Set to True to enable the internal pull-...
def build_logging_param(logging_uri, util_class=OutputFileParamUtil): """Convenience function simplifies construction of the logging uri.""" if not logging_uri: return job_model.LoggingParam(None, None) recursive = not logging_uri.endswith('.log') oututil = util_class('') _, uri, provider = oututil.parse_...
Convenience function simplifies construction of the logging uri.
Below is the the instruction that describes the task: ### Input: Convenience function simplifies construction of the logging uri. ### Response: def build_logging_param(logging_uri, util_class=OutputFileParamUtil): """Convenience function simplifies construction of the logging uri.""" if not logging_uri: re...
def serialize_quantity(o): """ Serializes an :obj:`astropy.units.Quantity`, for JSONification. Args: o (:obj:`astropy.units.Quantity`): :obj:`Quantity` to be serialized. Returns: A dictionary that can be passed to :obj:`json.dumps`. """ return dict( _type='astropy.units...
Serializes an :obj:`astropy.units.Quantity`, for JSONification. Args: o (:obj:`astropy.units.Quantity`): :obj:`Quantity` to be serialized. Returns: A dictionary that can be passed to :obj:`json.dumps`.
Below is the the instruction that describes the task: ### Input: Serializes an :obj:`astropy.units.Quantity`, for JSONification. Args: o (:obj:`astropy.units.Quantity`): :obj:`Quantity` to be serialized. Returns: A dictionary that can be passed to :obj:`json.dumps`. ### Response: def seri...
def address(address=None, begin=None, end=None): ''' HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/address QUERY PARAMETERS Parameter Type Default Description text string n/a Address string begin int 1880 beginning year for date range, inclusive end int 2014 end ye...
HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/address QUERY PARAMETERS Parameter Type Default Description text string n/a Address string begin int 1880 beginning year for date range, inclusive end int 2014 end year for date range, inclusive api_key string DEMO_KEY api....
Below is the the instruction that describes the task: ### Input: HTTP REQUEST GET https://api.nasa.gov/planetary/earth/temperature/address QUERY PARAMETERS Parameter Type Default Description text string n/a Address string begin int 1880 beginning year for date range, inclusive end int 201...
def _audience_condition_deserializer(obj_dict): """ Deserializer defining how dict objects need to be decoded for audience conditions. Args: obj_dict: Dict representing one audience condition. Returns: List consisting of condition key with corresponding value, type and match. """ return [ obj_di...
Deserializer defining how dict objects need to be decoded for audience conditions. Args: obj_dict: Dict representing one audience condition. Returns: List consisting of condition key with corresponding value, type and match.
Below is the the instruction that describes the task: ### Input: Deserializer defining how dict objects need to be decoded for audience conditions. Args: obj_dict: Dict representing one audience condition. Returns: List consisting of condition key with corresponding value, type and match. ### Response...
def list_nodes_full(conn=None, call=None): ''' Return a list of VMs with all the information about them CLI Example .. code-block:: bash salt-cloud -f list_nodes_full myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function mus...
Return a list of VMs with all the information about them CLI Example .. code-block:: bash salt-cloud -f list_nodes_full myopenstack
Below is the the instruction that describes the task: ### Input: Return a list of VMs with all the information about them CLI Example .. code-block:: bash salt-cloud -f list_nodes_full myopenstack ### Response: def list_nodes_full(conn=None, call=None): ''' Return a list of VMs with all ...
def get_dev_interface(devid, auth, url): """ Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device interfaces :param devid: requires devid as the only input :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base u...
Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device interfaces :param devid: requires devid as the only input :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeim...
Below is the the instruction that describes the task: ### Input: Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device interfaces :param devid: requires devid as the only input :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :p...
def extra_decorators(self): """The extra decorators that this function can have. Additional decorators are considered when they are used as assignments, as in ``method = staticmethod(method)``. The property will return all the callables that are used for decoration. :ty...
The extra decorators that this function can have. Additional decorators are considered when they are used as assignments, as in ``method = staticmethod(method)``. The property will return all the callables that are used for decoration. :type: list(NodeNG)
Below is the the instruction that describes the task: ### Input: The extra decorators that this function can have. Additional decorators are considered when they are used as assignments, as in ``method = staticmethod(method)``. The property will return all the callables that are used for ...
def _listen(self, protocols, From, description): """ Implementation of L{Listen}. """ # The peer is coming from a client-side representation of the user # described by 'From', and talking *to* a server-side representation of # the user described by 'From'. self.ve...
Implementation of L{Listen}.
Below is the the instruction that describes the task: ### Input: Implementation of L{Listen}. ### Response: def _listen(self, protocols, From, description): """ Implementation of L{Listen}. """ # The peer is coming from a client-side representation of the user # described by...
def get_buy(self, account_id, buy_id, **params): """https://developers.coinbase.com/api/v2#show-a-buy""" response = self._get('v2', 'accounts', account_id, 'buys', buy_id, params=params) return self._make_api_object(response, Buy)
https://developers.coinbase.com/api/v2#show-a-buy
Below is the the instruction that describes the task: ### Input: https://developers.coinbase.com/api/v2#show-a-buy ### Response: def get_buy(self, account_id, buy_id, **params): """https://developers.coinbase.com/api/v2#show-a-buy""" response = self._get('v2', 'accounts', account_id, 'buys', buy_id...
def cluster(self, n, embed_dim=None, algo=mds.CLASSICAL, method=methods.KMEANS): """ Cluster the embedded coordinates using multidimensional scaling Parameters ---------- n: int The number of clusters to return embed_dim ...
Cluster the embedded coordinates using multidimensional scaling Parameters ---------- n: int The number of clusters to return embed_dim int The dimensionality of the underlying coordinates ...
Below is the the instruction that describes the task: ### Input: Cluster the embedded coordinates using multidimensional scaling Parameters ---------- n: int The number of clusters to return embed_dim int ...
def main(): usage = "usage: %(prog)s [options] " description = "Run gtselect and gtmktime on one or more FT1 files. " "Note that gtmktime will be skipped if no FT2 file is provided." parser = argparse.ArgumentParser(usage=usage, description=description) add_lsf_args(parser) parser.add_argumen...
Note that gtmktime will be skipped if no FT2 file is provided.
Below is the the instruction that describes the task: ### Input: Note that gtmktime will be skipped if no FT2 file is provided. ### Response: def main(): usage = "usage: %(prog)s [options] " description = "Run gtselect and gtmktime on one or more FT1 files. " "Note that gtmktime will be skipped if no...
def parse_configuration(config): ''' Parse and fix configuration: - processed file should end up being same as input - pipelines should contain CLI commands to run - add missing sections :param config: raw configuration object :type config: dict :return: configuration ready ...
Parse and fix configuration: - processed file should end up being same as input - pipelines should contain CLI commands to run - add missing sections :param config: raw configuration object :type config: dict :return: configuration ready for `diet()` :rtype: dict
Below is the the instruction that describes the task: ### Input: Parse and fix configuration: - processed file should end up being same as input - pipelines should contain CLI commands to run - add missing sections :param config: raw configuration object :type config: dict :retu...
def sum(x, weights=None): ''' sum(x) yields either a potential-sum object if x is a potential function or the sum of x if x is not. If x is not a potential-field then it must be a vector. sum(x, weights=w) uses the given weights to produce a weighted sum. ''' x = to_potential(x) if is_cons...
sum(x) yields either a potential-sum object if x is a potential function or the sum of x if x is not. If x is not a potential-field then it must be a vector. sum(x, weights=w) uses the given weights to produce a weighted sum.
Below is the the instruction that describes the task: ### Input: sum(x) yields either a potential-sum object if x is a potential function or the sum of x if x is not. If x is not a potential-field then it must be a vector. sum(x, weights=w) uses the given weights to produce a weighted sum. ### Response: ...
def patch(): """ Patch botocore client so it generates subsegments when calling AWS services. """ if hasattr(botocore.client, '_xray_enabled'): return setattr(botocore.client, '_xray_enabled', True) wrapt.wrap_function_wrapper( 'botocore.client', 'BaseClient._make_ap...
Patch botocore client so it generates subsegments when calling AWS services.
Below is the the instruction that describes the task: ### Input: Patch botocore client so it generates subsegments when calling AWS services. ### Response: def patch(): """ Patch botocore client so it generates subsegments when calling AWS services. """ if hasattr(botocore.client, '_xray_en...
def enableHook(self, msgObj): """ Enable yank-pop. This method is connected to the 'yank-qtmacs_text_edit' hook (triggered by the yank macro) to ensure that yank-pop only gets activated afterwards. """ self.killListIdx = len(qte_global.kill_list) - 2 self...
Enable yank-pop. This method is connected to the 'yank-qtmacs_text_edit' hook (triggered by the yank macro) to ensure that yank-pop only gets activated afterwards.
Below is the the instruction that describes the task: ### Input: Enable yank-pop. This method is connected to the 'yank-qtmacs_text_edit' hook (triggered by the yank macro) to ensure that yank-pop only gets activated afterwards. ### Response: def enableHook(self, msgObj): """ ...
def process_tags(inst_tags): """Create dict of instance tags as only name:value pairs.""" tag_dict = {} for k in range(len(inst_tags)): tag_dict[inst_tags[k]['Key']] = inst_tags[k]['Value'] return tag_dict
Create dict of instance tags as only name:value pairs.
Below is the the instruction that describes the task: ### Input: Create dict of instance tags as only name:value pairs. ### Response: def process_tags(inst_tags): """Create dict of instance tags as only name:value pairs.""" tag_dict = {} for k in range(len(inst_tags)): tag_dict[inst_tags[k]['Ke...
def normalize_linked_references( data: List[Dict[str, Any]] ) -> Generator[Tuple[int, str, str], None, None]: """ Return a tuple of information representing all insertions of a linked reference. (offset, type, value) """ for deployment in data: for offset in deployment["offsets"]: ...
Return a tuple of information representing all insertions of a linked reference. (offset, type, value)
Below is the the instruction that describes the task: ### Input: Return a tuple of information representing all insertions of a linked reference. (offset, type, value) ### Response: def normalize_linked_references( data: List[Dict[str, Any]] ) -> Generator[Tuple[int, str, str], None, None]: """ Ret...
def filter_nodes(graph: BELGraph, node_predicates: NodePredicates) -> Iterable[BaseEntity]: """Apply a set of predicates to the nodes iterator of a BEL graph.""" concatenated_predicate = concatenate_node_predicates(node_predicates=node_predicates) for node in graph: if concatenated_predicate(graph, ...
Apply a set of predicates to the nodes iterator of a BEL graph.
Below is the the instruction that describes the task: ### Input: Apply a set of predicates to the nodes iterator of a BEL graph. ### Response: def filter_nodes(graph: BELGraph, node_predicates: NodePredicates) -> Iterable[BaseEntity]: """Apply a set of predicates to the nodes iterator of a BEL graph.""" co...
def purge(self, name=None): """ Disconnect from the given database and remove from local cache :param name: The name of the connection :type name: str :rtype: None """ self.disconnect(name) if name in self._connections: del self._connections...
Disconnect from the given database and remove from local cache :param name: The name of the connection :type name: str :rtype: None
Below is the the instruction that describes the task: ### Input: Disconnect from the given database and remove from local cache :param name: The name of the connection :type name: str :rtype: None ### Response: def purge(self, name=None): """ Disconnect from the given data...
def dbprint(*args): """print only if app.debug is truthy""" if app and app.debug: if USING_WINDOWS: print("DEBUG: " + " ".join(args)) else: CYELLOW2 = "\33[93m" NORMAL = "\033[0m" print(CYELLOW2 + "DEBUG: " + " ".join(args) + NORMAL)
print only if app.debug is truthy
Below is the the instruction that describes the task: ### Input: print only if app.debug is truthy ### Response: def dbprint(*args): """print only if app.debug is truthy""" if app and app.debug: if USING_WINDOWS: print("DEBUG: " + " ".join(args)) else: CYELLOW2 = "\...
def code(self, text): """Return the code instead of the comments. """ comm = self.nextValidComment(text) while comm: text = text[:comm.start()] + text[comm.end():] comm = self.nextValidComment(text, comm.end(0)) return text
Return the code instead of the comments.
Below is the the instruction that describes the task: ### Input: Return the code instead of the comments. ### Response: def code(self, text): """Return the code instead of the comments. """ comm = self.nextValidComment(text) while comm: text = text[:comm.start()] + tex...
def createSubtitle(self, fps, section): """Returns a correct 'Subtitle' object from a text given in 'section'. If 'section' cannot be parsed, None is returned. By default 'section' is checked against 'subPattern' regular expression.""" matched = self._pattern.search(section) if m...
Returns a correct 'Subtitle' object from a text given in 'section'. If 'section' cannot be parsed, None is returned. By default 'section' is checked against 'subPattern' regular expression.
Below is the the instruction that describes the task: ### Input: Returns a correct 'Subtitle' object from a text given in 'section'. If 'section' cannot be parsed, None is returned. By default 'section' is checked against 'subPattern' regular expression. ### Response: def createSubtitle(self, fps, ...
def graph(networkx_graph, title='Axial Graph Visualization', scripts_mode="CDN", data_mode="directory", output_dir=".", filename="graph.html", version=this_version): """ Arguments: networkx_graph (networkx.Graph): any instance of networkx.Graph title (str): The title of the plot (to be...
Arguments: networkx_graph (networkx.Graph): any instance of networkx.Graph title (str): The title of the plot (to be embedded in the html). scripts_mode (str): Choose from [`"CDN"`, `"directory"`, `"inline"`]: - `"CDN"` compiles a single HTML page with links to scripts hosted on a C...
Below is the the instruction that describes the task: ### Input: Arguments: networkx_graph (networkx.Graph): any instance of networkx.Graph title (str): The title of the plot (to be embedded in the html). scripts_mode (str): Choose from [`"CDN"`, `"directory"`, `"inline"`]: - `"...
def read(self, output_tile, **kwargs): """ Read existing process output. Parameters ---------- output_tile : ``BufferedTile`` must be member of output ``TilePyramid`` Returns ------- NumPy array """ try: return rea...
Read existing process output. Parameters ---------- output_tile : ``BufferedTile`` must be member of output ``TilePyramid`` Returns ------- NumPy array
Below is the the instruction that describes the task: ### Input: Read existing process output. Parameters ---------- output_tile : ``BufferedTile`` must be member of output ``TilePyramid`` Returns ------- NumPy array ### Response: def read(self, output_...
def set_cdn_log_retention(self, container, enabled): """ Enables or disables whether CDN access logs for the specified container are collected and stored on Cloud Files. """ headers = {"X-Log-Retention": "%s" % enabled} self.api.cdn_request("/%s" % utils.get_name(containe...
Enables or disables whether CDN access logs for the specified container are collected and stored on Cloud Files.
Below is the the instruction that describes the task: ### Input: Enables or disables whether CDN access logs for the specified container are collected and stored on Cloud Files. ### Response: def set_cdn_log_retention(self, container, enabled): """ Enables or disables whether CDN access log...
def sonority_from_fts(self, seg): """Given a segment as features, returns the sonority on a scale of 1 to 9. Args: seg (list): collection of (value, feature) pairs representing a segment (vowel or consonant) Returns: int: sonority of `s...
Given a segment as features, returns the sonority on a scale of 1 to 9. Args: seg (list): collection of (value, feature) pairs representing a segment (vowel or consonant) Returns: int: sonority of `seg` between 1 and 9
Below is the the instruction that describes the task: ### Input: Given a segment as features, returns the sonority on a scale of 1 to 9. Args: seg (list): collection of (value, feature) pairs representing a segment (vowel or consonant) Returns: ...
def contour_canny(image, radius, mult_coarse=.40, mult_fine=.1, clip_rmin=.9, clip_rmax=1.1, maxiter=20, verbose=True): """Heuristic Canny edge detection for circular objects Two Canny-based edge detections with different filter sizes are performed to find the outmost co...
Heuristic Canny edge detection for circular objects Two Canny-based edge detections with different filter sizes are performed to find the outmost contour of an object in a phase image while keeping artifacts at a minimum. Parameters ---------- image: 2d ndarray Image containing an appr...
Below is the the instruction that describes the task: ### Input: Heuristic Canny edge detection for circular objects Two Canny-based edge detections with different filter sizes are performed to find the outmost contour of an object in a phase image while keeping artifacts at a minimum. Parameters ...
def protege_data(datas_str, sens): """ Used to crypt/decrypt data before saving locally. Override if securit is needed. bytes -> str when decrypting str -> bytes when crypting :param datas_str: When crypting, str. when decrypting bytes :param sens: True to crypt, False to decrypt """ ...
Used to crypt/decrypt data before saving locally. Override if securit is needed. bytes -> str when decrypting str -> bytes when crypting :param datas_str: When crypting, str. when decrypting bytes :param sens: True to crypt, False to decrypt
Below is the the instruction that describes the task: ### Input: Used to crypt/decrypt data before saving locally. Override if securit is needed. bytes -> str when decrypting str -> bytes when crypting :param datas_str: When crypting, str. when decrypting bytes :param sens: True to crypt, False...
def make(keyvals): """ Create new H2OTwoDimTable object from list of (key,value) tuples which are a pre-cursor to JSON dict. :param keyvals: list of (key, value) tuples :return: new H2OTwoDimTable object """ kwargs = {} for key, value in keyvals: if k...
Create new H2OTwoDimTable object from list of (key,value) tuples which are a pre-cursor to JSON dict. :param keyvals: list of (key, value) tuples :return: new H2OTwoDimTable object
Below is the the instruction that describes the task: ### Input: Create new H2OTwoDimTable object from list of (key,value) tuples which are a pre-cursor to JSON dict. :param keyvals: list of (key, value) tuples :return: new H2OTwoDimTable object ### Response: def make(keyvals): """ ...
def run_from_ufos(self, ufos, output=(), **kwargs): """Run toolchain from UFO sources. Args: ufos: List of UFO sources, as either paths or opened objects. output: List of output formats to generate. kwargs: Arguments passed along to save_otfs. """ if...
Run toolchain from UFO sources. Args: ufos: List of UFO sources, as either paths or opened objects. output: List of output formats to generate. kwargs: Arguments passed along to save_otfs.
Below is the the instruction that describes the task: ### Input: Run toolchain from UFO sources. Args: ufos: List of UFO sources, as either paths or opened objects. output: List of output formats to generate. kwargs: Arguments passed along to save_otfs. ### Response: de...
def widgets_from_abbreviations(self, seq): """Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets.""" result = [] for name, abbrev, default in seq: widget = self.widget_from_abbrev(abbrev, default) if not (isinstance(widget, ValueWidget) or is...
Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets.
Below is the the instruction that describes the task: ### Input: Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets. ### Response: def widgets_from_abbreviations(self, seq): """Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets.""" result ...
def error(args): """ %prog error version backup_folder Find all errors in ../5-consensus/*.err and pull the error unitigs into backup/ folder. """ p = OptionParser(error.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) version, backu...
%prog error version backup_folder Find all errors in ../5-consensus/*.err and pull the error unitigs into backup/ folder.
Below is the the instruction that describes the task: ### Input: %prog error version backup_folder Find all errors in ../5-consensus/*.err and pull the error unitigs into backup/ folder. ### Response: def error(args): """ %prog error version backup_folder Find all errors in ../5-consensus/*.e...
def __marshal_matches(matched): """Convert matches to JSON format. :param matched: a list of matched identities :returns json_matches: a list of matches in JSON format """ json_matches = [] for m in matched: identities = [i.uuid for i in m] if l...
Convert matches to JSON format. :param matched: a list of matched identities :returns json_matches: a list of matches in JSON format
Below is the the instruction that describes the task: ### Input: Convert matches to JSON format. :param matched: a list of matched identities :returns json_matches: a list of matches in JSON format ### Response: def __marshal_matches(matched): """Convert matches to JSON format. :...
def post_user_contact_lists_contacts(self, id, contact_list_id, **data): """ POST /users/:id/contact_lists/:contact_list_id/contacts/ Adds a new contact to the contact list. Returns ``{"created": true}``. There is no way to update entries in the list; just delete the old one and ...
POST /users/:id/contact_lists/:contact_list_id/contacts/ Adds a new contact to the contact list. Returns ``{"created": true}``. There is no way to update entries in the list; just delete the old one and add the updated version.
Below is the the instruction that describes the task: ### Input: POST /users/:id/contact_lists/:contact_list_id/contacts/ Adds a new contact to the contact list. Returns ``{"created": true}``. There is no way to update entries in the list; just delete the old one and add the updated version....
def help(self, *args): """ Can be overridden (and for example _Menu does). """ if args: self.messages.error( self.messages.command_does_not_accept_arguments) else: print(self.helpfull)
Can be overridden (and for example _Menu does).
Below is the the instruction that describes the task: ### Input: Can be overridden (and for example _Menu does). ### Response: def help(self, *args): """ Can be overridden (and for example _Menu does). """ if args: self.messages.error( self.me...
def manual_close(self): """ Close the underlying connection without returning it to the pool. """ if self.is_closed(): return False # Obtain reference to the connection in-use by the calling thread. conn = self.connection() # A connection will only b...
Close the underlying connection without returning it to the pool.
Below is the the instruction that describes the task: ### Input: Close the underlying connection without returning it to the pool. ### Response: def manual_close(self): """ Close the underlying connection without returning it to the pool. """ if self.is_closed(): return ...
def difference(iterable, func=sub): """By default, compute the first difference of *iterable* using :func:`operator.sub`. >>> iterable = [0, 1, 3, 6, 10] >>> list(difference(iterable)) [0, 1, 2, 3, 4] This is the opposite of :func:`accumulate`'s default behavior: >>> from ...
By default, compute the first difference of *iterable* using :func:`operator.sub`. >>> iterable = [0, 1, 3, 6, 10] >>> list(difference(iterable)) [0, 1, 2, 3, 4] This is the opposite of :func:`accumulate`'s default behavior: >>> from itertools import accumulate >>> ite...
Below is the the instruction that describes the task: ### Input: By default, compute the first difference of *iterable* using :func:`operator.sub`. >>> iterable = [0, 1, 3, 6, 10] >>> list(difference(iterable)) [0, 1, 2, 3, 4] This is the opposite of :func:`accumulate`'s default be...
def start_serialization(self): """ Start serialization -- open the XML document and the root element. """ if (self.root): self.xml = XmlPrinter(self.stream, self.options.get("encoding", settings.DEFAULT_CHARSET)) self.xml.startDocument() self.xml.start...
Start serialization -- open the XML document and the root element.
Below is the the instruction that describes the task: ### Input: Start serialization -- open the XML document and the root element. ### Response: def start_serialization(self): """ Start serialization -- open the XML document and the root element. """ if (self.root): sel...
def list(self): """ List the contents of the directory. """ return [File(f, parent=self) for f in os.listdir(self.path)]
List the contents of the directory.
Below is the the instruction that describes the task: ### Input: List the contents of the directory. ### Response: def list(self): """ List the contents of the directory. """ return [File(f, parent=self) for f in os.listdir(self.path)]
def is_valid_uuid (uuid): """ is_valid_uuid (uuid) -> bool returns True if uuid is a valid 128-bit UUID. valid UUIDs are always strings taking one of the following forms: XXXX XXXXXXXX XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX where each X is a hexadecimal digit (case insensitiv...
is_valid_uuid (uuid) -> bool returns True if uuid is a valid 128-bit UUID. valid UUIDs are always strings taking one of the following forms: XXXX XXXXXXXX XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX where each X is a hexadecimal digit (case insensitive)
Below is the the instruction that describes the task: ### Input: is_valid_uuid (uuid) -> bool returns True if uuid is a valid 128-bit UUID. valid UUIDs are always strings taking one of the following forms: XXXX XXXXXXXX XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX where each X is a hex...
def load(cls, path: str, password: str = None) -> 'Account': """Load an account from a keystore file. Args: path: full path to the keyfile password: the password to decrypt the key file or `None` to leave it encrypted """ with open(path) as f: keystor...
Load an account from a keystore file. Args: path: full path to the keyfile password: the password to decrypt the key file or `None` to leave it encrypted
Below is the the instruction that describes the task: ### Input: Load an account from a keystore file. Args: path: full path to the keyfile password: the password to decrypt the key file or `None` to leave it encrypted ### Response: def load(cls, path: str, password: str = None) ->...
def exec_request(self, URL): """Sends the actual request; returns response.""" ## Throttle request, if need be interval = time.time() - self.__ts_last_req if (interval < self.__min_req_interval): time.sleep( self.__min_req_interval - interval ) ## Construct ...
Sends the actual request; returns response.
Below is the the instruction that describes the task: ### Input: Sends the actual request; returns response. ### Response: def exec_request(self, URL): """Sends the actual request; returns response.""" ## Throttle request, if need be interval = time.time() - self.__ts_last_req if (...
def output(self, _filename): """ _filename is not used Args: _filename(string) """ txt = "Analyze of {}\n".format(self.slither.filename) txt += self.get_detectors_result() for contract in self.slither.contracts_derived: txt += "\nC...
_filename is not used Args: _filename(string)
Below is the the instruction that describes the task: ### Input: _filename is not used Args: _filename(string) ### Response: def output(self, _filename): """ _filename is not used Args: _filename(string) """ txt = "Analyze of ...
def flatten(inputs, scope=None): """Flattens the input while maintaining the batch_size. Assumes that the first dimension represents the batch. Args: inputs: a tensor of size [batch_size, ...]. scope: Optional scope for name_scope. Returns: a flattened tensor with shape [batch_size, k]. Raise...
Flattens the input while maintaining the batch_size. Assumes that the first dimension represents the batch. Args: inputs: a tensor of size [batch_size, ...]. scope: Optional scope for name_scope. Returns: a flattened tensor with shape [batch_size, k]. Raises: ValueError: if inputs.shape is ...
Below is the the instruction that describes the task: ### Input: Flattens the input while maintaining the batch_size. Assumes that the first dimension represents the batch. Args: inputs: a tensor of size [batch_size, ...]. scope: Optional scope for name_scope. Returns: a flattened tensor with...
def get_dataset(self, key, info, out=None): """Get a dataset from the file.""" logger.debug("Reading %s.", key.name) values = self.file_content[key.name] selected = np.array(self.selected) if key.name in ("Latitude", "Longitude"): values = values / 10000. if ...
Get a dataset from the file.
Below is the the instruction that describes the task: ### Input: Get a dataset from the file. ### Response: def get_dataset(self, key, info, out=None): """Get a dataset from the file.""" logger.debug("Reading %s.", key.name) values = self.file_content[key.name] selected = np.array(...
def from_path(path): ''' create from path. return `None` if path is not exists. ''' if os.path.isdir(path): return DirectoryInfo(path) if os.path.isfile(path): return FileInfo(path) return None
create from path. return `None` if path is not exists.
Below is the the instruction that describes the task: ### Input: create from path. return `None` if path is not exists. ### Response: def from_path(path): ''' create from path. return `None` if path is not exists. ''' if os.path.isdir(path): return Dire...
def setup(self, *args, **kwargs): """ Dynamically reset the interface to expose the services / topics / params whose names are passed as args The interface class can be specified with a module to be dynamically imported :param publishers: :param subscribers: :param servic...
Dynamically reset the interface to expose the services / topics / params whose names are passed as args The interface class can be specified with a module to be dynamically imported :param publishers: :param subscribers: :param services: :param topics: BW COMPAT ONLY ! :p...
Below is the the instruction that describes the task: ### Input: Dynamically reset the interface to expose the services / topics / params whose names are passed as args The interface class can be specified with a module to be dynamically imported :param publishers: :param subscribers: ...
def next_line(last_line, next_line_8bit): """Compute the next line based on the last line and a 8bit next line. The behaviour of the function is specified in :ref:`reqline`. :param int last_line: the last line that was processed :param int next_line_8bit: the lower 8 bits of the next line :return:...
Compute the next line based on the last line and a 8bit next line. The behaviour of the function is specified in :ref:`reqline`. :param int last_line: the last line that was processed :param int next_line_8bit: the lower 8 bits of the next line :return: the next line closest to :paramref:`last_line` ...
Below is the the instruction that describes the task: ### Input: Compute the next line based on the last line and a 8bit next line. The behaviour of the function is specified in :ref:`reqline`. :param int last_line: the last line that was processed :param int next_line_8bit: the lower 8 bits of the ne...
def anticlockwise_sort_indices(pps): """ Returns the indices that would sort a list of 2D points in anticlockwise order :param pps: List of points to be sorted :return: Indices of the sorted list of points """ angles = np.zeros(len(pps), np.float) for ipp, pp in enumerate(pps): angle...
Returns the indices that would sort a list of 2D points in anticlockwise order :param pps: List of points to be sorted :return: Indices of the sorted list of points
Below is the the instruction that describes the task: ### Input: Returns the indices that would sort a list of 2D points in anticlockwise order :param pps: List of points to be sorted :return: Indices of the sorted list of points ### Response: def anticlockwise_sort_indices(pps): """ Returns the in...
def sort_depth(vals, reverse=False): """Sort bids or asks by price """ lst = [[float(price), quantity] for price, quantity in vals.items()] lst = sorted(lst, key=itemgetter(0), reverse=reverse) return lst
Sort bids or asks by price
Below is the the instruction that describes the task: ### Input: Sort bids or asks by price ### Response: def sort_depth(vals, reverse=False): """Sort bids or asks by price """ lst = [[float(price), quantity] for price, quantity in vals.items()] lst = sorted(lst, key=itemgetter(0), ...
def namespace(self, mid: ModuleId) -> YangIdentifier: """Return the namespace corresponding to a module or submodule. Args: mid: Module identifier. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. """ try: mdata = se...
Return the namespace corresponding to a module or submodule. Args: mid: Module identifier. Raises: ModuleNotRegistered: If `mid` is not registered in the data model.
Below is the the instruction that describes the task: ### Input: Return the namespace corresponding to a module or submodule. Args: mid: Module identifier. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. ### Response: def namespace(self, mid: Mod...
def merge_dicts(*dicts, **kwargs): """Merges dicts and kwargs into one dict""" result = {} for d in dicts: result.update(d) result.update(kwargs) return result
Merges dicts and kwargs into one dict
Below is the the instruction that describes the task: ### Input: Merges dicts and kwargs into one dict ### Response: def merge_dicts(*dicts, **kwargs): """Merges dicts and kwargs into one dict""" result = {} for d in dicts: result.update(d) result.update(kwargs) return result
def role_delete(self, role_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/roles#delete-role" api_path = "/api/v2/roles/{role_id}" api_path = api_path.format(role_id=role_id) return self.call(api_path, method="DELETE", **kwargs)
https://developer.zendesk.com/rest_api/docs/chat/roles#delete-role
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/chat/roles#delete-role ### Response: def role_delete(self, role_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/roles#delete-role" api_path = "/api/v2/roles/{role_id}" ...
def is_permitted_collective(self, permission_s, logical_operator=all): """ :param permission_s: a List of authz_abcs.Permission objects :param logical_operator: indicates whether *all* or at least one permission check is true, *any* :type: any OR all ...
:param permission_s: a List of authz_abcs.Permission objects :param logical_operator: indicates whether *all* or at least one permission check is true, *any* :type: any OR all (functions from python stdlib) :returns: a Boolean
Below is the the instruction that describes the task: ### Input: :param permission_s: a List of authz_abcs.Permission objects :param logical_operator: indicates whether *all* or at least one permission check is true, *any* :type: any OR all (functions from python...
def drop_row_range( self, name, row_key_prefix=None, delete_all_data_from_table=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Permanently drop/delete a row range from...
Permanently drop/delete a row range from a specified table. The request can specify whether to delete all rows in a table, or only those that match a particular prefix. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2...
Below is the the instruction that describes the task: ### Input: Permanently drop/delete a row range from a specified table. The request can specify whether to delete all rows in a table, or only those that match a particular prefix. Example: >>> from google.cloud import bigtabl...
def load_key_bindings_for_prompt(**kw): """ Create a ``Registry`` object with the defaults key bindings for an input prompt. This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D), incremental search and auto suggestions. (Not for full screen applications.) """ kw.setdefault('e...
Create a ``Registry`` object with the defaults key bindings for an input prompt. This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D), incremental search and auto suggestions. (Not for full screen applications.)
Below is the the instruction that describes the task: ### Input: Create a ``Registry`` object with the defaults key bindings for an input prompt. This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D), incremental search and auto suggestions. (Not for full screen applications.) ### Respons...
def _resolve(self, path, migration_file): """ Resolve a migration instance from a file. :param migration_file: The migration file :type migration_file: str :rtype: eloquent.migrations.migration.Migration """ variables = {} name = '_'.join(migration_file...
Resolve a migration instance from a file. :param migration_file: The migration file :type migration_file: str :rtype: eloquent.migrations.migration.Migration
Below is the the instruction that describes the task: ### Input: Resolve a migration instance from a file. :param migration_file: The migration file :type migration_file: str :rtype: eloquent.migrations.migration.Migration ### Response: def _resolve(self, path, migration_file): ""...
async def ask(self, body, quick_replies=None, options=None, user=None): """ simple ask with predefined quick replies :param body: :param quick_replies: (optional) in form of {'title': <message>, 'payload': <any json>} :param options: :param user: :return:...
simple ask with predefined quick replies :param body: :param quick_replies: (optional) in form of {'title': <message>, 'payload': <any json>} :param options: :param user: :return:
Below is the the instruction that describes the task: ### Input: simple ask with predefined quick replies :param body: :param quick_replies: (optional) in form of {'title': <message>, 'payload': <any json>} :param options: :param user: :return: ### Response: async d...
def cisco_conf_parse_objects(cfg_section, config): """ Use CiscoConfParse to find and return a section of Cisco IOS config. Similar to "show run | section <cfg_section>" :param cfg_section: The section of the config to return eg. "router bgp" :param config: The running/startup config of the device ...
Use CiscoConfParse to find and return a section of Cisco IOS config. Similar to "show run | section <cfg_section>" :param cfg_section: The section of the config to return eg. "router bgp" :param config: The running/startup config of the device to parse
Below is the the instruction that describes the task: ### Input: Use CiscoConfParse to find and return a section of Cisco IOS config. Similar to "show run | section <cfg_section>" :param cfg_section: The section of the config to return eg. "router bgp" :param config: The running/startup config of the d...
def client_key_loader(self, f): """Registers a function to be called to find a client key. Function you set has to take a client id and return a client key:: @hawk.client_key_loader def get_client_key(client_id): if client_id == 'Alice': retu...
Registers a function to be called to find a client key. Function you set has to take a client id and return a client key:: @hawk.client_key_loader def get_client_key(client_id): if client_id == 'Alice': return 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w...
Below is the the instruction that describes the task: ### Input: Registers a function to be called to find a client key. Function you set has to take a client id and return a client key:: @hawk.client_key_loader def get_client_key(client_id): if client_id == 'Alice'...
def use_comparative_assessment_part_bank_view(self): """Pass through to provider AssessmentPartBankSession.use_comparative_assessment_part_bank_view""" self._bank_view = COMPARATIVE # self._get_provider_session('assessment_part_bank_session') # To make sure the session is tracked for ses...
Pass through to provider AssessmentPartBankSession.use_comparative_assessment_part_bank_view
Below is the the instruction that describes the task: ### Input: Pass through to provider AssessmentPartBankSession.use_comparative_assessment_part_bank_view ### Response: def use_comparative_assessment_part_bank_view(self): """Pass through to provider AssessmentPartBankSession.use_comparative_assessment_p...
def _download_image(self, imageURL): """ Downloads an image file from the given image URL Arguments: imageURL {[str]} -- [Image URL] """ # If the required count of images have been download, # refrain from downloading the remainder of the images if(s...
Downloads an image file from the given image URL Arguments: imageURL {[str]} -- [Image URL]
Below is the the instruction that describes the task: ### Input: Downloads an image file from the given image URL Arguments: imageURL {[str]} -- [Image URL] ### Response: def _download_image(self, imageURL): """ Downloads an image file from the given image URL Argument...
def generate(self, output_dir, minimum_size): """Generates sequence reports and writes them to the output directory. :param output_dir: directory to output reports to :type output_dir: `str` :param minimum_size: minimum size of n-grams to create sequences for :type minimum_size:...
Generates sequence reports and writes them to the output directory. :param output_dir: directory to output reports to :type output_dir: `str` :param minimum_size: minimum size of n-grams to create sequences for :type minimum_size: `int`
Below is the the instruction that describes the task: ### Input: Generates sequence reports and writes them to the output directory. :param output_dir: directory to output reports to :type output_dir: `str` :param minimum_size: minimum size of n-grams to create sequences for :type m...
def to_naf(self): """ Converts the object to NAF """ if self.type == 'KAF': self.type = 'NAF' for node in self.__get_wf_nodes(): node.set('id',node.get('wid')) del node.attrib['wid']
Converts the object to NAF
Below is the the instruction that describes the task: ### Input: Converts the object to NAF ### Response: def to_naf(self): """ Converts the object to NAF """ if self.type == 'KAF': self.type = 'NAF' for node in self.__get_wf_nodes(): node.set...
def get_exec_create_kwargs(self, action, container_name, exec_cmd, exec_user, kwargs=None): """ Generates keyword arguments for the Docker client to set up the HostConfig or start a container. :param action: Action configuration. :type action: ActionConfig :param container_name:...
Generates keyword arguments for the Docker client to set up the HostConfig or start a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param kwargs: Additional keyword arg...
Below is the the instruction that describes the task: ### Input: Generates keyword arguments for the Docker client to set up the HostConfig or start a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type contai...
def inv(x): ''' inv(x) yields the inverse of x, 1/x. Note that inv supports sparse matrices, but it is forced to reify them. Additionally, because inv raises an error on divide-by-zero, they are unlikely to work. For better sparse-matrix support, see zinv. ''' if sps.issparse(x): return 1.0...
inv(x) yields the inverse of x, 1/x. Note that inv supports sparse matrices, but it is forced to reify them. Additionally, because inv raises an error on divide-by-zero, they are unlikely to work. For better sparse-matrix support, see zinv.
Below is the the instruction that describes the task: ### Input: inv(x) yields the inverse of x, 1/x. Note that inv supports sparse matrices, but it is forced to reify them. Additionally, because inv raises an error on divide-by-zero, they are unlikely to work. For better sparse-matrix support, see zin...
def partitionBy(*cols): """ Creates a :class:`WindowSpec` with the partitioning defined. """ sc = SparkContext._active_spark_context jspec = sc._jvm.org.apache.spark.sql.expressions.Window.partitionBy(_to_java_cols(cols)) return WindowSpec(jspec)
Creates a :class:`WindowSpec` with the partitioning defined.
Below is the the instruction that describes the task: ### Input: Creates a :class:`WindowSpec` with the partitioning defined. ### Response: def partitionBy(*cols): """ Creates a :class:`WindowSpec` with the partitioning defined. """ sc = SparkContext._active_spark_context js...
def checkin_bundle(self, db_path, replace=True, cb=None): """Add a bundle, as a Sqlite file, to this library""" from ambry.orm.exc import NotFoundError db = Database('sqlite:///{}'.format(db_path)) db.open() if len(db.datasets) == 0: raise NotFoundError("Did not get...
Add a bundle, as a Sqlite file, to this library
Below is the the instruction that describes the task: ### Input: Add a bundle, as a Sqlite file, to this library ### Response: def checkin_bundle(self, db_path, replace=True, cb=None): """Add a bundle, as a Sqlite file, to this library""" from ambry.orm.exc import NotFoundError db = Databa...
def copy(self): """Copy the this node tree Note all references to readers are removed. This is meant to avoid tree copies accessing readers that would return incompatible (Area) data. Theoretically it should be possible for tree copies to request compositor or modifier informati...
Copy the this node tree Note all references to readers are removed. This is meant to avoid tree copies accessing readers that would return incompatible (Area) data. Theoretically it should be possible for tree copies to request compositor or modifier information as long as they don't de...
Below is the the instruction that describes the task: ### Input: Copy the this node tree Note all references to readers are removed. This is meant to avoid tree copies accessing readers that would return incompatible (Area) data. Theoretically it should be possible for tree copies to reques...
def convert_world_to_phenotype(world): """ Converts sets indicating the resources present in a single cell to binary strings (bit order is based on the order of resources in world.resources). TODO: Figure out how to handle relationship between resources and tasks Inputs: world - an EnvironmentFile...
Converts sets indicating the resources present in a single cell to binary strings (bit order is based on the order of resources in world.resources). TODO: Figure out how to handle relationship between resources and tasks Inputs: world - an EnvironmentFile object with a grid of resource sets Returns: a...
Below is the the instruction that describes the task: ### Input: Converts sets indicating the resources present in a single cell to binary strings (bit order is based on the order of resources in world.resources). TODO: Figure out how to handle relationship between resources and tasks Inputs: world - ...
def read_config(filename): """Reads and flattens a configuration file into a single dictionary for ease of use. Works with both ``.config`` and ``.yaml`` files. Files should look like this:: search_rules: from-date: 2017-06-01 to-date: 2017-09-01 01:01 pt-rule: k...
Reads and flattens a configuration file into a single dictionary for ease of use. Works with both ``.config`` and ``.yaml`` files. Files should look like this:: search_rules: from-date: 2017-06-01 to-date: 2017-09-01 01:01 pt-rule: kanye search_params: ...
Below is the the instruction that describes the task: ### Input: Reads and flattens a configuration file into a single dictionary for ease of use. Works with both ``.config`` and ``.yaml`` files. Files should look like this:: search_rules: from-date: 2017-06-01 to-date: 2017...
def azureContainerSAS(self, *args, **kwargs): """ Get Shared-Access-Signature for Azure Container Get a shared access signature (SAS) string for use with a specific Azure Blob Storage container. The `level` parameter can be `read-write` or `read-only` and determines whi...
Get Shared-Access-Signature for Azure Container Get a shared access signature (SAS) string for use with a specific Azure Blob Storage container. The `level` parameter can be `read-write` or `read-only` and determines which type of credentials are returned. If level is read-write, it w...
Below is the the instruction that describes the task: ### Input: Get Shared-Access-Signature for Azure Container Get a shared access signature (SAS) string for use with a specific Azure Blob Storage container. The `level` parameter can be `read-write` or `read-only` and determines ...
def save_image(imager, grid_data, grid_norm, output_file): """Makes an image from gridded visibilities and saves it to a FITS file. Args: imager (oskar.Imager): Handle to configured imager. grid_data (numpy.ndarray): Final visibility grid. grid_norm (float): G...
Makes an image from gridded visibilities and saves it to a FITS file. Args: imager (oskar.Imager): Handle to configured imager. grid_data (numpy.ndarray): Final visibility grid. grid_norm (float): Grid normalisation to apply. output_file (str): ...
Below is the the instruction that describes the task: ### Input: Makes an image from gridded visibilities and saves it to a FITS file. Args: imager (oskar.Imager): Handle to configured imager. grid_data (numpy.ndarray): Final visibility grid. grid_norm (float): ...
def process_tags(self, user, msg, reply, st=[], bst=[], depth=0, ignore_object_errors=True): """Post process tags in a message. :param str user: The user ID. :param str msg: The user's formatted message. :param str reply: The raw RiveScript reply for the message. :param []str st...
Post process tags in a message. :param str user: The user ID. :param str msg: The user's formatted message. :param str reply: The raw RiveScript reply for the message. :param []str st: The array of ``<star>`` matches from the trigger. :param []str bst: The array of ``<botstar>``...
Below is the the instruction that describes the task: ### Input: Post process tags in a message. :param str user: The user ID. :param str msg: The user's formatted message. :param str reply: The raw RiveScript reply for the message. :param []str st: The array of ``<star>`` matches f...