code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_configuration_dict(self, secret_attrs=False): """Overrides superclass method and renames some properties""" cd = super(TaxonomicAmendmentsShard, self).get_configuration_dict(secret_attrs=secret_attrs) # "rename" some keys in the dict provided cd['number of amendments'] = cd.pop('...
Overrides superclass method and renames some properties
Below is the the instruction that describes the task: ### Input: Overrides superclass method and renames some properties ### Response: def get_configuration_dict(self, secret_attrs=False): """Overrides superclass method and renames some properties""" cd = super(TaxonomicAmendmentsShard, self).get_c...
def disconnect(cls): """ Disconnect from the current network (if connected). Returns -------- result: future A future that resolves to true if the disconnect was successful. Will be set to None if the change network pe...
Disconnect from the current network (if connected). Returns -------- result: future A future that resolves to true if the disconnect was successful. Will be set to None if the change network permission is denied.
Below is the the instruction that describes the task: ### Input: Disconnect from the current network (if connected). Returns -------- result: future A future that resolves to true if the disconnect was successful. Will be set to None if the...
def _wire_events(self): """ Wires up the internal device events. """ self._device.on_open += self._on_open self._device.on_close += self._on_close self._device.on_read += self._on_read self._device.on_write += self._on_write self._zonetracker.on_fault += s...
Wires up the internal device events.
Below is the the instruction that describes the task: ### Input: Wires up the internal device events. ### Response: def _wire_events(self): """ Wires up the internal device events. """ self._device.on_open += self._on_open self._device.on_close += self._on_close self...
def refetch_fields(self, missing_fields): """ Refetches a list of fields from the DB """ db_fields = self.mongokat_collection.find_one({"_id": self["_id"]}, fields={k: 1 for k in missing_fields}) self._fetched_fields += tuple(missing_fields) if not db_fields: return ...
Refetches a list of fields from the DB
Below is the the instruction that describes the task: ### Input: Refetches a list of fields from the DB ### Response: def refetch_fields(self, missing_fields): """ Refetches a list of fields from the DB """ db_fields = self.mongokat_collection.find_one({"_id": self["_id"]}, fields={k: 1 for k in mi...
def _force_https(self): """Redirect any non-https requests to https. Based largely on flask-sslify. """ if self.session_cookie_secure: if not self.app.debug: self.app.config['SESSION_COOKIE_SECURE'] = True criteria = [ self.app.debug, ...
Redirect any non-https requests to https. Based largely on flask-sslify.
Below is the the instruction that describes the task: ### Input: Redirect any non-https requests to https. Based largely on flask-sslify. ### Response: def _force_https(self): """Redirect any non-https requests to https. Based largely on flask-sslify. """ if self.session_...
def create(self, dataset_id): """ Create a dataset in Google BigQuery Parameters ---------- dataset : str Name of dataset to be written """ from google.cloud.bigquery import Dataset if self.exists(dataset_id): raise DatasetCreationError( ...
Create a dataset in Google BigQuery Parameters ---------- dataset : str Name of dataset to be written
Below is the the instruction that describes the task: ### Input: Create a dataset in Google BigQuery Parameters ---------- dataset : str Name of dataset to be written ### Response: def create(self, dataset_id): """ Create a dataset in Google BigQuery Parameters...
def _create_session(self): """ Creates a fresh session with no/default headers and proxies """ logger.debug("Create new phantomjs web driver") self.driver = webdriver.PhantomJS(desired_capabilities=self.dcap, **self.driver_args) s...
Creates a fresh session with no/default headers and proxies
Below is the the instruction that describes the task: ### Input: Creates a fresh session with no/default headers and proxies ### Response: def _create_session(self): """ Creates a fresh session with no/default headers and proxies """ logger.debug("Create new phantomjs web driver") ...
def compact(self) -> str: """ Return a transaction in its compact format from the instance :return: """ """TX:VERSION:NB_ISSUERS:NB_INPUTS:NB_UNLOCKS:NB_OUTPUTS:HAS_COMMENT:LOCKTIME PUBLIC_KEY:INDEX ... INDEX:SOURCE:FINGERPRINT:AMOUNT ... PUBLIC_KEY:AMOUNT ... COMMENT """ ...
Return a transaction in its compact format from the instance :return:
Below is the the instruction that describes the task: ### Input: Return a transaction in its compact format from the instance :return: ### Response: def compact(self) -> str: """ Return a transaction in its compact format from the instance :return: """ """TX:VERSIO...
def query(url, output=True, **kwargs): ''' Query a resource, and decode the return data Passes through all the parameters described in the :py:func:`utils.http.query function <salt.utils.http.query>`: CLI Example: .. code-block:: bash salt-run http.query http://somelink.com/ ...
Query a resource, and decode the return data Passes through all the parameters described in the :py:func:`utils.http.query function <salt.utils.http.query>`: CLI Example: .. code-block:: bash salt-run http.query http://somelink.com/ salt-run http.query http://somelink.com/ method=POS...
Below is the the instruction that describes the task: ### Input: Query a resource, and decode the return data Passes through all the parameters described in the :py:func:`utils.http.query function <salt.utils.http.query>`: CLI Example: .. code-block:: bash salt-run http.query http://some...
def _parse_tree(self, node): """ Parse a <image> object """ if 'type' in node.attrib: self.kind = node.attrib['type'] if 'width' in node.attrib: self.width = int(node.attrib['width']) if 'height' in node.attrib: self.height = int(node.attrib['height'])...
Parse a <image> object
Below is the the instruction that describes the task: ### Input: Parse a <image> object ### Response: def _parse_tree(self, node): """ Parse a <image> object """ if 'type' in node.attrib: self.kind = node.attrib['type'] if 'width' in node.attrib: self.width = int(nod...
def set_data(self, adjacency_mat=None, **kwargs): """Set the data Parameters ---------- adjacency_mat : ndarray | None The adjacency matrix. **kwargs : dict Keyword arguments to pass to the arrows. """ if adjacency_mat is not None: ...
Set the data Parameters ---------- adjacency_mat : ndarray | None The adjacency matrix. **kwargs : dict Keyword arguments to pass to the arrows.
Below is the the instruction that describes the task: ### Input: Set the data Parameters ---------- adjacency_mat : ndarray | None The adjacency matrix. **kwargs : dict Keyword arguments to pass to the arrows. ### Response: def set_data(self, adjacency_mat=N...
def free(self): """Returns an amount of free space on remote WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :return: an amount of free space in bytes. """ data = WebDavXmlUtils.create_free_space_request_content() ...
Returns an amount of free space on remote WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :return: an amount of free space in bytes.
Below is the the instruction that describes the task: ### Input: Returns an amount of free space on remote WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :return: an amount of free space in bytes. ### Response: def free(self): """R...
def _on_message(channel, method, header, body): """ Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties...
Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the me...
Below is the the instruction that describes the task: ### Input: Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The p...
def generate_screenshots(self): """ Take a config file as input and generate screenshots """ headers = {'content-type': 'application/json', 'Accept': 'application/json'} resp = requests.post(self.api_url, data=json.dumps(self.config), \ headers=header...
Take a config file as input and generate screenshots
Below is the the instruction that describes the task: ### Input: Take a config file as input and generate screenshots ### Response: def generate_screenshots(self): """ Take a config file as input and generate screenshots """ headers = {'content-type': 'application/json', 'Accept': '...
def get_endpoint(self, session, **kwargs): """Get the HubiC storage endpoint uri. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for ...
Get the HubiC storage endpoint uri. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for queries. :raise...
Below is the the instruction that describes the task: ### Input: Get the HubiC storage endpoint uri. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for ...
def _create_variables_no_pretrain(self, n_features): """Create model variables (no previous unsupervised pretraining). :param n_features: number of features :return: self """ self.encoding_w_ = [] self.encoding_b_ = [] for l, layer in enumerate(self.layers): ...
Create model variables (no previous unsupervised pretraining). :param n_features: number of features :return: self
Below is the the instruction that describes the task: ### Input: Create model variables (no previous unsupervised pretraining). :param n_features: number of features :return: self ### Response: def _create_variables_no_pretrain(self, n_features): """Create model variables (no previous unsu...
def individual(self, ind_id=None): """Return a individual object Args: ind_id (str): A individual id Returns: individual (puzzle.models.individual) """ for ind_obj in self.individuals: if ind_obj.ind_id == ...
Return a individual object Args: ind_id (str): A individual id Returns: individual (puzzle.models.individual)
Below is the the instruction that describes the task: ### Input: Return a individual object Args: ind_id (str): A individual id Returns: individual (puzzle.models.individual) ### Response: def individual(self, ind_id=None): """Re...
async def request( self, method: str, endpoint: str, *, headers: dict = None, params: dict = None) -> dict: """Make a request against air-matters.com.""" url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint) if not headers: ...
Make a request against air-matters.com.
Below is the the instruction that describes the task: ### Input: Make a request against air-matters.com. ### Response: async def request( self, method: str, endpoint: str, *, headers: dict = None, params: dict = None) -> dict: """Make ...
def p_expr_BAND_expr(p): """ expr : expr BAND expr """ p[0] = make_binary(p.lineno(2), 'BAND', p[1], p[3], lambda x, y: x & y)
expr : expr BAND expr
Below is the the instruction that describes the task: ### Input: expr : expr BAND expr ### Response: def p_expr_BAND_expr(p): """ expr : expr BAND expr """ p[0] = make_binary(p.lineno(2), 'BAND', p[1], p[3], lambda x, y: x & y)
def attribute_rewrite_map(self): """ Example: long_name -> a_b :return: the rewrite map :rtype: dict """ rewrite_map = dict() token_rewrite_map = self.generate_attribute_token_rewrite_map() for attribute_name, type_instance in self.getmembers(): ...
Example: long_name -> a_b :return: the rewrite map :rtype: dict
Below is the the instruction that describes the task: ### Input: Example: long_name -> a_b :return: the rewrite map :rtype: dict ### Response: def attribute_rewrite_map(self): """ Example: long_name -> a_b :return: the rewrite map :rtype: dict """ ...
def delete(self, request, key): """Remove an email address, validated or not.""" request.DELETE = http.QueryDict(request.body) email_addr = request.DELETE.get('email') user_id = request.DELETE.get('user') if not email_addr: return http.HttpResponseBadRequest() ...
Remove an email address, validated or not.
Below is the the instruction that describes the task: ### Input: Remove an email address, validated or not. ### Response: def delete(self, request, key): """Remove an email address, validated or not.""" request.DELETE = http.QueryDict(request.body) email_addr = request.DELETE.get('email') ...
def join_room(self, room_id_or_alias): """Performs /join/$room_id Args: room_id_or_alias (str): The room ID or room alias to join. """ if not room_id_or_alias: raise MatrixError("No alias or room ID to join.") path = "/join/%s" % quote(room_id_or_alias) ...
Performs /join/$room_id Args: room_id_or_alias (str): The room ID or room alias to join.
Below is the the instruction that describes the task: ### Input: Performs /join/$room_id Args: room_id_or_alias (str): The room ID or room alias to join. ### Response: def join_room(self, room_id_or_alias): """Performs /join/$room_id Args: room_id_or_alias (str): T...
def private_download_url(self, url, expires=3600): """生成私有资源下载链接 Args: url: 私有空间资源的原始URL expires: 下载凭证有效期,默认为3600s Returns: 私有资源的下载链接 """ deadline = int(time.time()) + expires if '?' in url: url += '&' else: ...
生成私有资源下载链接 Args: url: 私有空间资源的原始URL expires: 下载凭证有效期,默认为3600s Returns: 私有资源的下载链接
Below is the the instruction that describes the task: ### Input: 生成私有资源下载链接 Args: url: 私有空间资源的原始URL expires: 下载凭证有效期,默认为3600s Returns: 私有资源的下载链接 ### Response: def private_download_url(self, url, expires=3600): """生成私有资源下载链接 Args: ...
def read(self): """Read a line of data from the input source at a time.""" line = self.trace_file.readline() if line == '': if self.loop: self._reopen_file() else: self.trace_file.close() self.trace_file = None ...
Read a line of data from the input source at a time.
Below is the the instruction that describes the task: ### Input: Read a line of data from the input source at a time. ### Response: def read(self): """Read a line of data from the input source at a time.""" line = self.trace_file.readline() if line == '': if self.loop: ...
def create(self, req, **kwargs): """ Uses POST to send a first metadata statement signing request to a signing service. :param req: The metadata statement that the entity wants signed :return: returns a dictionary with 'sms' and 'loc' as keys. """ response = req...
Uses POST to send a first metadata statement signing request to a signing service. :param req: The metadata statement that the entity wants signed :return: returns a dictionary with 'sms' and 'loc' as keys.
Below is the the instruction that describes the task: ### Input: Uses POST to send a first metadata statement signing request to a signing service. :param req: The metadata statement that the entity wants signed :return: returns a dictionary with 'sms' and 'loc' as keys. ### Response: def ...
def _to_graph(self, contexts): """This is an iterator that returns each edge of our graph with its two nodes""" prev = None for context in contexts: if prev is None: prev = context continue yield prev[0], context[1], context[0] ...
This is an iterator that returns each edge of our graph with its two nodes
Below is the the instruction that describes the task: ### Input: This is an iterator that returns each edge of our graph with its two nodes ### Response: def _to_graph(self, contexts): """This is an iterator that returns each edge of our graph with its two nodes""" prev = None for context ...
def to_igraph(self, weighted=None): '''Converts this Graph object to an igraph-compatible object. Requires the python-igraph library.''' # Import here to avoid ImportErrors when igraph isn't available. import igraph ig = igraph.Graph(n=self.num_vertices(), edges=self.pairs().tolist(), ...
Converts this Graph object to an igraph-compatible object. Requires the python-igraph library.
Below is the the instruction that describes the task: ### Input: Converts this Graph object to an igraph-compatible object. Requires the python-igraph library. ### Response: def to_igraph(self, weighted=None): '''Converts this Graph object to an igraph-compatible object. Requires the python-igraph libr...
def doi(self, doi, only_message=True): """ This method retrieve the DOI metadata related to a given DOI number. args: Crossref DOI id (String) return: JSON Example: >>> from crossref.restful import Works >>> works = Works() >>> works...
This method retrieve the DOI metadata related to a given DOI number. args: Crossref DOI id (String) return: JSON Example: >>> from crossref.restful import Works >>> works = Works() >>> works.doi('10.1590/S0004-28032013005000001') {'is-re...
Below is the the instruction that describes the task: ### Input: This method retrieve the DOI metadata related to a given DOI number. args: Crossref DOI id (String) return: JSON Example: >>> from crossref.restful import Works >>> works = Works() ...
def zonal_stats(raster, vector): """Reclassify a continuous raster layer. Issue https://github.com/inasafe/inasafe/issues/3190 The algorithm will take care about projections. We don't want to reproject the raster layer. So if CRS are different, we reproject the vector layer and then we do a lo...
Reclassify a continuous raster layer. Issue https://github.com/inasafe/inasafe/issues/3190 The algorithm will take care about projections. We don't want to reproject the raster layer. So if CRS are different, we reproject the vector layer and then we do a lookup from the reprojected layer to the o...
Below is the the instruction that describes the task: ### Input: Reclassify a continuous raster layer. Issue https://github.com/inasafe/inasafe/issues/3190 The algorithm will take care about projections. We don't want to reproject the raster layer. So if CRS are different, we reproject the vector ...
def guard_submit(analysis): """Return whether the transition "submit" can be performed or not """ # Cannot submit without a result if not analysis.getResult(): return False # Cannot submit with interims without value for interim in analysis.getInterimFields(): if not interim.get...
Return whether the transition "submit" can be performed or not
Below is the the instruction that describes the task: ### Input: Return whether the transition "submit" can be performed or not ### Response: def guard_submit(analysis): """Return whether the transition "submit" can be performed or not """ # Cannot submit without a result if not analysis.getResult(...
def get_argument_parser(): """Create the argument parser for the script. Parameters ---------- Returns ------- `argparse.ArgumentParser` The arguemnt parser. """ desc = 'Generate a sample sheet based on a GEO series matrix.' parser = cli.get_argument_parser(desc=desc) ...
Create the argument parser for the script. Parameters ---------- Returns ------- `argparse.ArgumentParser` The arguemnt parser.
Below is the the instruction that describes the task: ### Input: Create the argument parser for the script. Parameters ---------- Returns ------- `argparse.ArgumentParser` The arguemnt parser. ### Response: def get_argument_parser(): """Create the argument parser for the script. ...
def deferred(timeout=None): """ By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter specifies the maximum duration o...
By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter specifies the maximum duration of the test. The difference with time...
Below is the the instruction that describes the task: ### Input: By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter spe...
def invert(interval): """Invert an interval. Example: >>> invert(['C', 'E']) ['E', 'C'] """ interval.reverse() res = list(interval) interval.reverse() return res
Invert an interval. Example: >>> invert(['C', 'E']) ['E', 'C']
Below is the the instruction that describes the task: ### Input: Invert an interval. Example: >>> invert(['C', 'E']) ['E', 'C'] ### Response: def invert(interval): """Invert an interval. Example: >>> invert(['C', 'E']) ['E', 'C'] """ interval.reverse() res = list(interval)...
def pos_tag_sents( sentences: List[List[str]], engine: str = "perceptron", corpus: str = "orchid" ) -> List[List[Tuple[str, str]]]: """ Part of Speech tagging Sentence function. :param list sentences: a list of lists of tokenized words :param str engine: * unigram - unigram tagger *...
Part of Speech tagging Sentence function. :param list sentences: a list of lists of tokenized words :param str engine: * unigram - unigram tagger * perceptron - perceptron tagger (default) * artagger - RDR POS tagger :param str corpus: * orchid - annotated Thai academic arti...
Below is the the instruction that describes the task: ### Input: Part of Speech tagging Sentence function. :param list sentences: a list of lists of tokenized words :param str engine: * unigram - unigram tagger * perceptron - perceptron tagger (default) * artagger - RDR POS tagger ...
def can_unsubscribe_from_topic(self, topic, user): """ Given a topic, checks whether the user can remove it from their subscription list. """ # A user can unsubscribe from topics if they are authenticated and if they have the # permission to read the related forum. Of course a user can unsubscri...
Given a topic, checks whether the user can remove it from their subscription list.
Below is the the instruction that describes the task: ### Input: Given a topic, checks whether the user can remove it from their subscription list. ### Response: def can_unsubscribe_from_topic(self, topic, user): """ Given a topic, checks whether the user can remove it from their subscription list. """ ...
def discover_setup_packages(): """Summarize packages currently set up by EUPS, listing their set up directories and EUPS version names. Returns ------- packages : `dict` Dictionary with keys that are EUPS package names. Values are dictionaries with fields: - ``'dir'``: absolut...
Summarize packages currently set up by EUPS, listing their set up directories and EUPS version names. Returns ------- packages : `dict` Dictionary with keys that are EUPS package names. Values are dictionaries with fields: - ``'dir'``: absolute directory path of the set up package...
Below is the the instruction that describes the task: ### Input: Summarize packages currently set up by EUPS, listing their set up directories and EUPS version names. Returns ------- packages : `dict` Dictionary with keys that are EUPS package names. Values are dictionaries with field...
def show_help(name): """ Show help and basic usage """ print('Usage: python3 {} [OPTIONS]... '.format(name)) print('ISO8583 message client') print(' -v, --verbose\t\tRun transactions verbosely') print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default') print(' -s, --serve...
Show help and basic usage
Below is the the instruction that describes the task: ### Input: Show help and basic usage ### Response: def show_help(name): """ Show help and basic usage """ print('Usage: python3 {} [OPTIONS]... '.format(name)) print('ISO8583 message client') print(' -v, --verbose\t\tRun transactions ve...
def _back_compatible_gemini(conf_files, data): """Provide old install directory for configuration with GEMINI supplied tidy VCFs. Handles new style (bcbio installed) and old style (GEMINI installed) configuration and data locations. """ if vcfanno.is_human(data, builds=["37"]): for f in con...
Provide old install directory for configuration with GEMINI supplied tidy VCFs. Handles new style (bcbio installed) and old style (GEMINI installed) configuration and data locations.
Below is the the instruction that describes the task: ### Input: Provide old install directory for configuration with GEMINI supplied tidy VCFs. Handles new style (bcbio installed) and old style (GEMINI installed) configuration and data locations. ### Response: def _back_compatible_gemini(conf_files, data...
def fit(self, X, *args, **kwargs): """Fit scipy model to an array of values. Args: X(`np.ndarray` or `pd.DataFrame`): Datapoints to be estimated from. Must be 1-d Returns: None """ self.constant_value = self._get_constant_value(X) if self.cons...
Fit scipy model to an array of values. Args: X(`np.ndarray` or `pd.DataFrame`): Datapoints to be estimated from. Must be 1-d Returns: None
Below is the the instruction that describes the task: ### Input: Fit scipy model to an array of values. Args: X(`np.ndarray` or `pd.DataFrame`): Datapoints to be estimated from. Must be 1-d Returns: None ### Response: def fit(self, X, *args, **kwargs): """Fit scip...
def set(self, data=None): """ Sets the event """ self.__data = data self.__exception = None self.__event.set()
Sets the event
Below is the the instruction that describes the task: ### Input: Sets the event ### Response: def set(self, data=None): """ Sets the event """ self.__data = data self.__exception = None self.__event.set()
def get_permissions_for_registration(self): """ Utilised by Wagtail's 'register_permissions' hook to allow permissions for a all models grouped by this class to be assigned to Groups in settings. """ qs = Permission.objects.none() for instance in self.modeladmin_i...
Utilised by Wagtail's 'register_permissions' hook to allow permissions for a all models grouped by this class to be assigned to Groups in settings.
Below is the the instruction that describes the task: ### Input: Utilised by Wagtail's 'register_permissions' hook to allow permissions for a all models grouped by this class to be assigned to Groups in settings. ### Response: def get_permissions_for_registration(self): """ Utilised...
def _pre_analysis(self): """ Initialization work. Executed prior to the analysis. :return: None """ # Fill up self._starts for item in self._starts: callstack = None if isinstance(item, tuple): # (addr, jumpkind) i...
Initialization work. Executed prior to the analysis. :return: None
Below is the the instruction that describes the task: ### Input: Initialization work. Executed prior to the analysis. :return: None ### Response: def _pre_analysis(self): """ Initialization work. Executed prior to the analysis. :return: None """ # Fill up self._st...
def timeseries(self): """ Feed-in time series of generator It returns the actual time series used in power flow analysis. If :attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise, :meth:`timeseries` looks for generation and curtailment time series of the acco...
Feed-in time series of generator It returns the actual time series used in power flow analysis. If :attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise, :meth:`timeseries` looks for generation and curtailment time series of the according type of technology (and weather cell...
Below is the the instruction that describes the task: ### Input: Feed-in time series of generator It returns the actual time series used in power flow analysis. If :attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise, :meth:`timeseries` looks for generation and curtailment time...
def from_schema(self, schema_node): """ Creates a list of Swagger params from a colander request schema. :param schema_node: Request schema to be transformed into Swagger. :param validators: Validators used in colander with the schema. :rtype: list ...
Creates a list of Swagger params from a colander request schema. :param schema_node: Request schema to be transformed into Swagger. :param validators: Validators used in colander with the schema. :rtype: list :returns: List of Swagger parameters.
Below is the the instruction that describes the task: ### Input: Creates a list of Swagger params from a colander request schema. :param schema_node: Request schema to be transformed into Swagger. :param validators: Validators used in colander with the schema. :rtyp...
def select_candidates(config): """Select candidates to download. Parameters ---------- config: NgdConfig Runtime configuration object Returns ------- list of (<candidate entry>, <taxonomic group>) """ download_candidates = [] for group in config.group: summary...
Select candidates to download. Parameters ---------- config: NgdConfig Runtime configuration object Returns ------- list of (<candidate entry>, <taxonomic group>)
Below is the the instruction that describes the task: ### Input: Select candidates to download. Parameters ---------- config: NgdConfig Runtime configuration object Returns ------- list of (<candidate entry>, <taxonomic group>) ### Response: def select_candidates(config): """S...
def process_dividends(self, next_session, asset_finder, adjustment_reader): """Process dividends for the next session. This will earn us any dividends whose ex-date is the next session as well as paying out any dividends whose pay-date is the next session """ position_tracker = ...
Process dividends for the next session. This will earn us any dividends whose ex-date is the next session as well as paying out any dividends whose pay-date is the next session
Below is the the instruction that describes the task: ### Input: Process dividends for the next session. This will earn us any dividends whose ex-date is the next session as well as paying out any dividends whose pay-date is the next session ### Response: def process_dividends(self, next_session, ...
def reset_trial(self, trial, new_config, new_experiment_tag): """Tries to invoke `Trainable.reset_config()` to reset trial. Args: trial (Trial): Trial to be reset. new_config (dict): New configuration for Trial trainable. new_experiment_tag (str): New...
Tries to invoke `Trainable.reset_config()` to reset trial. Args: trial (Trial): Trial to be reset. new_config (dict): New configuration for Trial trainable. new_experiment_tag (str): New experiment name for trial. Returns: ...
Below is the the instruction that describes the task: ### Input: Tries to invoke `Trainable.reset_config()` to reset trial. Args: trial (Trial): Trial to be reset. new_config (dict): New configuration for Trial trainable. new_experiment_tag (str): New exp...
def RegisterTextKey(cls, key, atomid): """Register a text key. If the key you need to register is a simple one-to-one mapping of MP4 atom name to EasyMP4Tags key, then you can use this function:: EasyMP4Tags.RegisterTextKey("artist", "\xa9ART") """ def gette...
Register a text key. If the key you need to register is a simple one-to-one mapping of MP4 atom name to EasyMP4Tags key, then you can use this function:: EasyMP4Tags.RegisterTextKey("artist", "\xa9ART")
Below is the the instruction that describes the task: ### Input: Register a text key. If the key you need to register is a simple one-to-one mapping of MP4 atom name to EasyMP4Tags key, then you can use this function:: EasyMP4Tags.RegisterTextKey("artist", "\xa9ART") ### Respon...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'class_name') and self.class_name is not None: _dict['class'] = self.class_name if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.scor...
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, 'class_name') and self.class_name is not None: ...
def ticker(ctx, market): """ Show ticker of a market """ market = Market(market, bitshares_instance=ctx.bitshares) ticker = market.ticker() t = [["key", "value"]] for key in ticker: t.append([key, str(ticker[key])]) print_table(t)
Show ticker of a market
Below is the the instruction that describes the task: ### Input: Show ticker of a market ### Response: def ticker(ctx, market): """ Show ticker of a market """ market = Market(market, bitshares_instance=ctx.bitshares) ticker = market.ticker() t = [["key", "value"]] for key in ticker: ...
def worker_collectionfinish(self, node, ids): """worker has finished test collection. This adds the collection for this node to the scheduler. If the scheduler indicates collection is finished (i.e. all initial nodes have submitted their collections), then tells the scheduler t...
worker has finished test collection. This adds the collection for this node to the scheduler. If the scheduler indicates collection is finished (i.e. all initial nodes have submitted their collections), then tells the scheduler to schedule the collected items. When initiating ...
Below is the the instruction that describes the task: ### Input: worker has finished test collection. This adds the collection for this node to the scheduler. If the scheduler indicates collection is finished (i.e. all initial nodes have submitted their collections), then tells the ...
def rounding_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Rounding accuracy for L1/L2 losses: round down the predictions to ints.""" outputs = tf.squeeze(tf.to_int32(predictions)) labels = tf.squeeze(labels) weights = weights_fn(labels) ...
Rounding accuracy for L1/L2 losses: round down the predictions to ints.
Below is the the instruction that describes the task: ### Input: Rounding accuracy for L1/L2 losses: round down the predictions to ints. ### Response: def rounding_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Rounding accuracy for L1/L2 l...
def _repr_png_(self): """This is used by ipython to plot inline. """ app.process_events() QApplication.processEvents() img = read_pixels() return bytes(_make_png(img))
This is used by ipython to plot inline.
Below is the the instruction that describes the task: ### Input: This is used by ipython to plot inline. ### Response: def _repr_png_(self): """This is used by ipython to plot inline. """ app.process_events() QApplication.processEvents() img = read_pixels() return b...
def bots_create(self, bot): """ Save new bot :param bot: bot object to save :type bot: Bot """ self.client.bots(_method="POST", _json=bot.to_json(), _params=dict(userToken=self.token))
Save new bot :param bot: bot object to save :type bot: Bot
Below is the the instruction that describes the task: ### Input: Save new bot :param bot: bot object to save :type bot: Bot ### Response: def bots_create(self, bot): """ Save new bot :param bot: bot object to save :type bot: Bot """ self.client.bots...
def raise_for_execution_errors(nb, output_path): """Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object output_path : str Path to write executed notebook """ error = None for cell in nb.cel...
Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object output_path : str Path to write executed notebook
Below is the the instruction that describes the task: ### Input: Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object output_path : str Path to write executed notebook ### Response: def raise_for_execu...
def read(self, pos, size, **kwargs): """ Read a packet from the stream. :param int pos: The packet number to read from the sequence of the stream. May be None to append to the stream. :param size: The size to read. May be symbolic. :param short_reads: Whether to repla...
Read a packet from the stream. :param int pos: The packet number to read from the sequence of the stream. May be None to append to the stream. :param size: The size to read. May be symbolic. :param short_reads: Whether to replace the size with a symbolic value constrained to less tha...
Below is the the instruction that describes the task: ### Input: Read a packet from the stream. :param int pos: The packet number to read from the sequence of the stream. May be None to append to the stream. :param size: The size to read. May be symbolic. :param short_reads: Whet...
def simxGetDistanceHandle(clientID, distanceObjectName, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' handle = ct.c_int() if (sys.version_info[0] == 3) and (type(distanceObjectName) is str): distanceObjectName=distanceObjectNam...
Please have a look at the function description/documentation in the V-REP user manual
Below is the the instruction that describes the task: ### Input: Please have a look at the function description/documentation in the V-REP user manual ### Response: def simxGetDistanceHandle(clientID, distanceObjectName, operationMode): ''' Please have a look at the function description/documentation in th...
def _new_masterpassword(self, password): """ Generate a new random masterkey, encrypt it with the password and store it in the store. :param str password: Password to use for en-/de-cryption """ # make sure to not overwrite an existing key if self.config_key in s...
Generate a new random masterkey, encrypt it with the password and store it in the store. :param str password: Password to use for en-/de-cryption
Below is the the instruction that describes the task: ### Input: Generate a new random masterkey, encrypt it with the password and store it in the store. :param str password: Password to use for en-/de-cryption ### Response: def _new_masterpassword(self, password): """ Generate a n...
def has_ocsp_must_staple_extension(certificate: cryptography.x509.Certificate) -> bool: """Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066. """ has_ocsp_must_staple = False try: tls_feature_ext = certificate.extensions.get_extension_for_o...
Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066.
Below is the the instruction that describes the task: ### Input: Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066. ### Response: def has_ocsp_must_staple_extension(certificate: cryptography.x509.Certificate) -> bool: """Return True if the certificate has the OCSP Must-S...
def _fix_set_options(cls, options): """Alter the set options from None/strings to sets in place.""" optional_set_options = ('ignore', 'select') mandatory_set_options = ('add_ignore', 'add_select') def _get_set(value_str): """Split `value_str` by the delimiter `,` and return ...
Alter the set options from None/strings to sets in place.
Below is the the instruction that describes the task: ### Input: Alter the set options from None/strings to sets in place. ### Response: def _fix_set_options(cls, options): """Alter the set options from None/strings to sets in place.""" optional_set_options = ('ignore', 'select') mandatory_...
def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.s...
Update our built-in md5 registry
Below is the the instruction that describes the task: ### Input: Update our built-in md5 registry ### Response: def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] =...
def auth(name, nodes, pcsuser='hacluster', pcspasswd='hacluster', extra_args=None): ''' Ensure all nodes are authorized to the cluster name Irrelevant, not used (recommended: pcs_auth__auth) nodes a list of nodes which should be authorized to the cluster pcsuser user for com...
Ensure all nodes are authorized to the cluster name Irrelevant, not used (recommended: pcs_auth__auth) nodes a list of nodes which should be authorized to the cluster pcsuser user for communication with pcs (default: hacluster) pcspasswd password for pcsuser (default: ha...
Below is the the instruction that describes the task: ### Input: Ensure all nodes are authorized to the cluster name Irrelevant, not used (recommended: pcs_auth__auth) nodes a list of nodes which should be authorized to the cluster pcsuser user for communication with pcs (defaul...
def reaction_charge(reaction, compound_charge): """Calculate the overall charge for the specified reaction. Args: reaction: :class:`psamm.reaction.Reaction`. compound_charge: a map from each compound to charge values. """ charge_sum = 0.0 for compound, value in reaction.compounds: ...
Calculate the overall charge for the specified reaction. Args: reaction: :class:`psamm.reaction.Reaction`. compound_charge: a map from each compound to charge values.
Below is the the instruction that describes the task: ### Input: Calculate the overall charge for the specified reaction. Args: reaction: :class:`psamm.reaction.Reaction`. compound_charge: a map from each compound to charge values. ### Response: def reaction_charge(reaction, compound_charge): ...
def gen_mapname(): """ Generate a uniq mapfile pathname. """ filepath = None while (filepath is None) or (os.path.exists(os.path.join(config['mapfiles_dir'], filepath))): filepath = '%s.map' % _gen_string() return filepath
Generate a uniq mapfile pathname.
Below is the the instruction that describes the task: ### Input: Generate a uniq mapfile pathname. ### Response: def gen_mapname(): """ Generate a uniq mapfile pathname. """ filepath = None while (filepath is None) or (os.path.exists(os.path.join(config['mapfiles_dir'], filepath))): filepath = ...
def backpropagate_3d(uSin, angles, res, nm, lD=0, coords=None, weight_angles=True, onlyreal=False, padding=(True, True), padfac=1.75, padval=None, intp_order=2, dtype=None, num_cores=ncores, save_memory=False, ...
r"""3D backpropagation Three-dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave :math:`u_0(\mathbf{r}) = u_0(x,y,z)` by a dielectric object with refractive index :math:`n(x,y,z)`. This method implements the 3D backpropagation algorithm :cite:`Mueller...
Below is the the instruction that describes the task: ### Input: r"""3D backpropagation Three-dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave :math:`u_0(\mathbf{r}) = u_0(x,y,z)` by a dielectric object with refractive index :math:`n(x,y,z)`. This ...
def replace_config(config, name): '''Replace the top-level pipeline configurable object. This investigates a number of sources, including `external_stages_path` and `external_stages_modules` configuration and `streamcorpus_pipeline.stages` entry points, and uses these to find the actual :data:`sub_...
Replace the top-level pipeline configurable object. This investigates a number of sources, including `external_stages_path` and `external_stages_modules` configuration and `streamcorpus_pipeline.stages` entry points, and uses these to find the actual :data:`sub_modules` for :mod:`streamcorpus_pipel...
Below is the the instruction that describes the task: ### Input: Replace the top-level pipeline configurable object. This investigates a number of sources, including `external_stages_path` and `external_stages_modules` configuration and `streamcorpus_pipeline.stages` entry points, and uses these to ...
def _ret8(ins): """ Returns from a procedure / function an 8bits value """ output = _8bit_oper(ins.quad[1]) output.append('#pragma opt require a') output.append('jp %s' % str(ins.quad[2])) return output
Returns from a procedure / function an 8bits value
Below is the the instruction that describes the task: ### Input: Returns from a procedure / function an 8bits value ### Response: def _ret8(ins): """ Returns from a procedure / function an 8bits value """ output = _8bit_oper(ins.quad[1]) output.append('#pragma opt require a') output.append('jp ...
def children(self, p_todo, p_only_direct=False): """ Returns a list of child todos that the given todo (in)directly depends on. """ children = \ self._depgraph.outgoing_neighbors(hash(p_todo), not p_only_direct) return [self._tododict[child] for child in child...
Returns a list of child todos that the given todo (in)directly depends on.
Below is the the instruction that describes the task: ### Input: Returns a list of child todos that the given todo (in)directly depends on. ### Response: def children(self, p_todo, p_only_direct=False): """ Returns a list of child todos that the given todo (in)directly depends on. ...
def is_businessdate(in_date): """ checks whether the provided date is a date :param BusinessDate, int or float in_date: :return bool: """ # Note: if the data range has been created from pace_xl, then all the dates are bank dates # and here it remains to check the ...
checks whether the provided date is a date :param BusinessDate, int or float in_date: :return bool:
Below is the the instruction that describes the task: ### Input: checks whether the provided date is a date :param BusinessDate, int or float in_date: :return bool: ### Response: def is_businessdate(in_date): """ checks whether the provided date is a date :param BusinessDate...
def convert(self, vroot, entry_variables): """ All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. """ self.graph_info ...
All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
Below is the the instruction that describes the task: ### Input: All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. ### Response: def convert(sel...
def get_init_kwargs(self): """ Generates keyword arguments for creating a new Docker client instance. :return: Keyword arguments as defined through this configuration. :rtype: dict """ init_kwargs = {} for k in self.init_kwargs: if k in self.core_prop...
Generates keyword arguments for creating a new Docker client instance. :return: Keyword arguments as defined through this configuration. :rtype: dict
Below is the the instruction that describes the task: ### Input: Generates keyword arguments for creating a new Docker client instance. :return: Keyword arguments as defined through this configuration. :rtype: dict ### Response: def get_init_kwargs(self): """ Generates keyword argu...
def current(self, value): """set current cursor position""" current = min(max(self._min, value), self._max) self._current = current if current > self._stop : self._stop = current self._start = current-self._width elif current < self._start : ...
set current cursor position
Below is the the instruction that describes the task: ### Input: set current cursor position ### Response: def current(self, value): """set current cursor position""" current = min(max(self._min, value), self._max) self._current = current if current > self._stop : sel...
def _release_lock(self): """Release our lock if we have one""" if not self._has_lock(): return # if someone removed our file beforhand, lets just flag this issue # instead of failing, to make it more usable. lfp = self._lock_file_path() try: # on ...
Release our lock if we have one
Below is the the instruction that describes the task: ### Input: Release our lock if we have one ### Response: def _release_lock(self): """Release our lock if we have one""" if not self._has_lock(): return # if someone removed our file beforhand, lets just flag this issue ...
def trace(msg): """Print a trace message to stderr if environment variable is set. """ if os.environ.get('JARN_TRACE') == '1': print('TRACE:', msg, file=sys.stderr)
Print a trace message to stderr if environment variable is set.
Below is the the instruction that describes the task: ### Input: Print a trace message to stderr if environment variable is set. ### Response: def trace(msg): """Print a trace message to stderr if environment variable is set. """ if os.environ.get('JARN_TRACE') == '1': print('TRACE:', msg, file...
def random_variants( count, genome_name="GRCh38", deletions=True, insertions=True, random_seed=None): """ Generate a VariantCollection with random variants that overlap at least one complete coding transcript. """ rng = random.Random(random_seed) ensembl =...
Generate a VariantCollection with random variants that overlap at least one complete coding transcript.
Below is the the instruction that describes the task: ### Input: Generate a VariantCollection with random variants that overlap at least one complete coding transcript. ### Response: def random_variants( count, genome_name="GRCh38", deletions=True, insertions=True, rando...
def check_crystal_equivalence(crystal_a, crystal_b): """Function that identifies whether two crystals are equivalent""" # getting symmetry datasets for both crystals cryst_a = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_a), symprec=1e-5, angle_tolerance=-1.0, hall_number=0) cryst_b = spglib.get_...
Function that identifies whether two crystals are equivalent
Below is the the instruction that describes the task: ### Input: Function that identifies whether two crystals are equivalent ### Response: def check_crystal_equivalence(crystal_a, crystal_b): """Function that identifies whether two crystals are equivalent""" # getting symmetry datasets for both crystals ...
def simple_moving_matrix(x, n=10): """ Create simple moving matrix. Parameters ---------- x : ndarray A numpy array n : integer The number of sample points used to make average Returns ------- ndarray A n x n numpy array which will be useful for calculating ...
Create simple moving matrix. Parameters ---------- x : ndarray A numpy array n : integer The number of sample points used to make average Returns ------- ndarray A n x n numpy array which will be useful for calculating confidentail interval of simple moving ...
Below is the the instruction that describes the task: ### Input: Create simple moving matrix. Parameters ---------- x : ndarray A numpy array n : integer The number of sample points used to make average Returns ------- ndarray A n x n numpy array which will be u...
def char(i): """Get image data for the character `i` (a one character string). Returned as a list of rows. Each row is a tuple containing the packed pixels. """ i = ord(i) if i not in font: return [(0,)] * 8 return [(ord(row),) for row in font[i].decode('hex')]
Get image data for the character `i` (a one character string). Returned as a list of rows. Each row is a tuple containing the packed pixels.
Below is the the instruction that describes the task: ### Input: Get image data for the character `i` (a one character string). Returned as a list of rows. Each row is a tuple containing the packed pixels. ### Response: def char(i): """Get image data for the character `i` (a one character string). ...
def casefold_with_i_dots(text): """ Convert capital I's and capital dotted İ's to lowercase in the way that's appropriate for Turkish and related languages, then case-fold the rest of the letters. """ text = unicodedata.normalize('NFC', text).replace('İ', 'i').replace('I', 'ı') return text.c...
Convert capital I's and capital dotted İ's to lowercase in the way that's appropriate for Turkish and related languages, then case-fold the rest of the letters.
Below is the the instruction that describes the task: ### Input: Convert capital I's and capital dotted İ's to lowercase in the way that's appropriate for Turkish and related languages, then case-fold the rest of the letters. ### Response: def casefold_with_i_dots(text): """ Convert capital I's and...
def query_publishers(self, publisher_query): """QueryPublishers. [Preview API] :param :class:`<PublisherQuery> <azure.devops.v5_0.gallery.models.PublisherQuery>` publisher_query: :rtype: :class:`<PublisherQueryResult> <azure.devops.v5_0.gallery.models.PublisherQueryResult>` """ ...
QueryPublishers. [Preview API] :param :class:`<PublisherQuery> <azure.devops.v5_0.gallery.models.PublisherQuery>` publisher_query: :rtype: :class:`<PublisherQueryResult> <azure.devops.v5_0.gallery.models.PublisherQueryResult>`
Below is the the instruction that describes the task: ### Input: QueryPublishers. [Preview API] :param :class:`<PublisherQuery> <azure.devops.v5_0.gallery.models.PublisherQuery>` publisher_query: :rtype: :class:`<PublisherQueryResult> <azure.devops.v5_0.gallery.models.PublisherQueryResult>` ...
def addFilter(self, *lstFilters, **dctFilters) : "add a new filter to the query" dstF = {} if len(lstFilters) > 0 : if type(lstFilters[0]) is types.DictType : dstF = lstFilters[0] lstFilters = lstFilters[1:] if len(dctFilters) > 0 : dstF = dict(dstF, **dctFilters) filts = {} for k, v in dst...
add a new filter to the query
Below is the the instruction that describes the task: ### Input: add a new filter to the query ### Response: def addFilter(self, *lstFilters, **dctFilters) : "add a new filter to the query" dstF = {} if len(lstFilters) > 0 : if type(lstFilters[0]) is types.DictType : dstF = lstFilters[0] lstFilte...
def trigger_actions(self, subsystem): """ Refresh all modules which subscribed to the given subsystem. """ for py3_module, trigger_action in self.udev_consumers[subsystem]: if trigger_action in ON_TRIGGER_ACTIONS: self.py3_wrapper.log( "%s ...
Refresh all modules which subscribed to the given subsystem.
Below is the the instruction that describes the task: ### Input: Refresh all modules which subscribed to the given subsystem. ### Response: def trigger_actions(self, subsystem): """ Refresh all modules which subscribed to the given subsystem. """ for py3_module, trigger_action in se...
def post_status(self, body="", id="", parentid="", stashid=""): """Post a status :param username: The body of the status :param id: The id of the object you wish to share :param parentid: The parentid of the object you wish to share :param stashid: The stashid of the object you...
Post a status :param username: The body of the status :param id: The id of the object you wish to share :param parentid: The parentid of the object you wish to share :param stashid: The stashid of the object you wish to add to the status
Below is the the instruction that describes the task: ### Input: Post a status :param username: The body of the status :param id: The id of the object you wish to share :param parentid: The parentid of the object you wish to share :param stashid: The stashid of the object you wish t...
def make_clusters(span_tree, cut_value): """ Find clusters from the spanning tree Parameters ---------- span_tree : a sparse nsrcs x nsrcs array Filled with zeros except for the active edges, which are filled with the edge measures (either distances or sigmas cut_value : float ...
Find clusters from the spanning tree Parameters ---------- span_tree : a sparse nsrcs x nsrcs array Filled with zeros except for the active edges, which are filled with the edge measures (either distances or sigmas cut_value : float Value used to cluster group. All links with mea...
Below is the the instruction that describes the task: ### Input: Find clusters from the spanning tree Parameters ---------- span_tree : a sparse nsrcs x nsrcs array Filled with zeros except for the active edges, which are filled with the edge measures (either distances or sigmas cut_...
def to_netcdf(dataset, path_or_file=None, mode='w', format=None, group=None, engine=None, encoding=None, unlimited_dims=None, compute=True, multifile=False): """This function creates an appropriate datastore for writing a dataset to disk as a netCDF file See `Dataset.to_netcdf` ...
This function creates an appropriate datastore for writing a dataset to disk as a netCDF file See `Dataset.to_netcdf` for full API docs. The ``multifile`` argument is only for the private use of save_mfdataset.
Below is the the instruction that describes the task: ### Input: This function creates an appropriate datastore for writing a dataset to disk as a netCDF file See `Dataset.to_netcdf` for full API docs. The ``multifile`` argument is only for the private use of save_mfdataset. ### Response: def to_netc...
def interpret_header(self): """ Read pertinent information from the image headers, especially location and radius of the Sun to calculate the default thematic map :return: setes self.date, self.cy, self.cx, and self.sun_radius_pixel """ # handle special cases since date-...
Read pertinent information from the image headers, especially location and radius of the Sun to calculate the default thematic map :return: setes self.date, self.cy, self.cx, and self.sun_radius_pixel
Below is the the instruction that describes the task: ### Input: Read pertinent information from the image headers, especially location and radius of the Sun to calculate the default thematic map :return: setes self.date, self.cy, self.cx, and self.sun_radius_pixel ### Response: def interpret_head...
def _computeStatus(self, dfile, service): """Computes status for file, basically this means if more than one service handles the file, it will place a 'C' (for complicated) otherwise if status matches between all services, will place that status""" # If only one service request...
Computes status for file, basically this means if more than one service handles the file, it will place a 'C' (for complicated) otherwise if status matches between all services, will place that status
Below is the the instruction that describes the task: ### Input: Computes status for file, basically this means if more than one service handles the file, it will place a 'C' (for complicated) otherwise if status matches between all services, will place that status ### Response: def _compu...
def _handle_state_change_msg(self, new_helper): """Called when state change is commanded by stream manager""" assert self.my_pplan_helper is not None assert self.my_instance is not None and self.my_instance.py_class is not None if self.my_pplan_helper.get_topology_state() != new_helper.get_topology_sta...
Called when state change is commanded by stream manager
Below is the the instruction that describes the task: ### Input: Called when state change is commanded by stream manager ### Response: def _handle_state_change_msg(self, new_helper): """Called when state change is commanded by stream manager""" assert self.my_pplan_helper is not None assert self.my_ins...
def is_valid_group(group_name, nova_creds): """ Checks to see if the configuration file contains a SUPERNOVA_GROUP configuration option. """ valid_groups = [] for key, value in nova_creds.items(): supernova_groups = value.get('SUPERNOVA_GROUP', []) if hasattr(supernova_groups, 's...
Checks to see if the configuration file contains a SUPERNOVA_GROUP configuration option.
Below is the the instruction that describes the task: ### Input: Checks to see if the configuration file contains a SUPERNOVA_GROUP configuration option. ### Response: def is_valid_group(group_name, nova_creds): """ Checks to see if the configuration file contains a SUPERNOVA_GROUP configuration op...
def _draw_fold_indicator(self, top, mouse_over, collapsed, painter): """ Draw the fold indicator/trigger (arrow). :param top: Top position :param mouse_over: Whether the mouse is over the indicator :param collapsed: Whether the trigger is collapsed or not. :param painter...
Draw the fold indicator/trigger (arrow). :param top: Top position :param mouse_over: Whether the mouse is over the indicator :param collapsed: Whether the trigger is collapsed or not. :param painter: QPainter
Below is the the instruction that describes the task: ### Input: Draw the fold indicator/trigger (arrow). :param top: Top position :param mouse_over: Whether the mouse is over the indicator :param collapsed: Whether the trigger is collapsed or not. :param painter: QPainter ### Respo...
def get_spark_context(conf=None): """ Get the current active spark context and create one if no active instance :param conf: combining bigdl configs into spark conf :return: SparkContext """ if hasattr(SparkContext, "getOrCreate"): with SparkContext._lock: if SparkContext._ac...
Get the current active spark context and create one if no active instance :param conf: combining bigdl configs into spark conf :return: SparkContext
Below is the the instruction that describes the task: ### Input: Get the current active spark context and create one if no active instance :param conf: combining bigdl configs into spark conf :return: SparkContext ### Response: def get_spark_context(conf=None): """ Get the current active spark cont...
def get_distutils_display_options(): """ Returns a set of all the distutils display options in their long and short forms. These are the setup.py arguments such as --name or --version which print the project's metadata and then exit. Returns ------- opts : set The long and short form d...
Returns a set of all the distutils display options in their long and short forms. These are the setup.py arguments such as --name or --version which print the project's metadata and then exit. Returns ------- opts : set The long and short form display option arguments, including the - or -...
Below is the the instruction that describes the task: ### Input: Returns a set of all the distutils display options in their long and short forms. These are the setup.py arguments such as --name or --version which print the project's metadata and then exit. Returns ------- opts : set T...
def cluster(x, cluster='KMeans', n_clusters=3, ndims=None, format_data=True): """ Performs clustering analysis and returns a list of cluster labels Parameters ---------- x : A Numpy array, Pandas Dataframe or list of arrays/dfs The data to be clustered. You can pass a single array/df or a ...
Performs clustering analysis and returns a list of cluster labels Parameters ---------- x : A Numpy array, Pandas Dataframe or list of arrays/dfs The data to be clustered. You can pass a single array/df or a list. If a list is passed, the arrays will be stacked and the clustering w...
Below is the the instruction that describes the task: ### Input: Performs clustering analysis and returns a list of cluster labels Parameters ---------- x : A Numpy array, Pandas Dataframe or list of arrays/dfs The data to be clustered. You can pass a single array/df or a list. If a li...
def gemini_query(self, query_id): """Return a gemini query Args: name (str) """ logger.debug("Looking for query with id {0}".format(query_id)) return self.query(GeminiQuery).filter_by(id=query_id).first()
Return a gemini query Args: name (str)
Below is the the instruction that describes the task: ### Input: Return a gemini query Args: name (str) ### Response: def gemini_query(self, query_id): """Return a gemini query Args: name (str) """ logger.debug("Looking for query with id {0}".format...
def deprecated(msg=''): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. :param msg: Additional message added to the warning. """ def wrapper(func): @functools.wraps(func) de...
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. :param msg: Additional message added to the warning.
Below is the the instruction that describes the task: ### Input: This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. :param msg: Additional message added to the warning. ### Response: def deprecated(msg=''...
def template_sphere_shell(outer_radius, inner_radius=0): r""" This method generates an image array of a sphere-shell. It is useful for passing to Cubic networks as a ``template`` to make spherical shaped networks. Parameters ---------- outer_radius : int Number of nodes in the outer...
r""" This method generates an image array of a sphere-shell. It is useful for passing to Cubic networks as a ``template`` to make spherical shaped networks. Parameters ---------- outer_radius : int Number of nodes in the outer radius of the sphere. inner_radius : int Number...
Below is the the instruction that describes the task: ### Input: r""" This method generates an image array of a sphere-shell. It is useful for passing to Cubic networks as a ``template`` to make spherical shaped networks. Parameters ---------- outer_radius : int Number of nodes in t...
def get_PolyFromPolyFileObj(PolyFileObj, SavePathInp=None, units='m', comments='#', skiprows=0, shape0=2): """ Return a polygon as a np.ndarray, extracted from a txt file or from a ToFu object, with appropriate units Useful for :meth:`tofu.plugins.AUG.Ves._create()` Parameters ---------- PolyFileO...
Return a polygon as a np.ndarray, extracted from a txt file or from a ToFu object, with appropriate units Useful for :meth:`tofu.plugins.AUG.Ves._create()` Parameters ---------- PolyFileObj : str / :mod:`tofu.geom` object / np.ndarray The source where the polygon is to be found, either: ...
Below is the the instruction that describes the task: ### Input: Return a polygon as a np.ndarray, extracted from a txt file or from a ToFu object, with appropriate units Useful for :meth:`tofu.plugins.AUG.Ves._create()` Parameters ---------- PolyFileObj : str / :mod:`tofu.geom` object / np.ndar...
def get_upgrades(self, remove_applied=True): """Get upgrades (ordered according to their dependencies). :param remove_applied: Set to false to return all upgrades, otherwise already applied upgrades are removed from their graph (incl. all their dependencies. """ ...
Get upgrades (ordered according to their dependencies). :param remove_applied: Set to false to return all upgrades, otherwise already applied upgrades are removed from their graph (incl. all their dependencies.
Below is the the instruction that describes the task: ### Input: Get upgrades (ordered according to their dependencies). :param remove_applied: Set to false to return all upgrades, otherwise already applied upgrades are removed from their graph (incl. all their dependencies. ### Res...
def _upload_file(compute, project_id, file_path, path): """ Upload a file to a remote project :param file_path: File path on the controller file system :param path: File path on the remote system relative to project directory """ path = "/projects/{}/files/{}".format(project_id, path.replace("\...
Upload a file to a remote project :param file_path: File path on the controller file system :param path: File path on the remote system relative to project directory
Below is the the instruction that describes the task: ### Input: Upload a file to a remote project :param file_path: File path on the controller file system :param path: File path on the remote system relative to project directory ### Response: def _upload_file(compute, project_id, file_path, path): "...
def admeig(classname, f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau): """Compute the eigenvalues and eigenvectors for a QCD anomalous dimension matrix that is defined in `adm.adm_s_X` where X is the name of the sector. Supports memoization. Output analogous to `np.linalg.eig`.""" args = f, m_u, m_d, m_s...
Compute the eigenvalues and eigenvectors for a QCD anomalous dimension matrix that is defined in `adm.adm_s_X` where X is the name of the sector. Supports memoization. Output analogous to `np.linalg.eig`.
Below is the the instruction that describes the task: ### Input: Compute the eigenvalues and eigenvectors for a QCD anomalous dimension matrix that is defined in `adm.adm_s_X` where X is the name of the sector. Supports memoization. Output analogous to `np.linalg.eig`. ### Response: def admeig(classname, ...