code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def fit(self, X, y): """ Train a gaussian process like normal, then compute a "Probability Of Uniform selection" (POU) value. """ # first, train a gaussian process like normal super(GPEiVelocity, self).fit(X, y) # probability of uniform self.POU = 0 ...
Train a gaussian process like normal, then compute a "Probability Of Uniform selection" (POU) value.
Below is the the instruction that describes the task: ### Input: Train a gaussian process like normal, then compute a "Probability Of Uniform selection" (POU) value. ### Response: def fit(self, X, y): """ Train a gaussian process like normal, then compute a "Probability Of Uniform s...
def device_log_list(self, **kwargs): # noqa: E501 """DEPRECATED: List all device events. # noqa: E501 DEPRECATED: List all device events. Use `/v3/device-events/` instead. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, plea...
DEPRECATED: List all device events. # noqa: E501 DEPRECATED: List all device events. Use `/v3/device-events/` instead. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.device_log_...
Below is the the instruction that describes the task: ### Input: DEPRECATED: List all device events. # noqa: E501 DEPRECATED: List all device events. Use `/v3/device-events/` instead. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP reques...
def remove_local_zip(self): """ Remove our local zip file. """ if self.stage_config.get('delete_local_zip', True): try: if os.path.isfile(self.zip_path): os.remove(self.zip_path) if self.handler_path and os.path.isfile(self...
Remove our local zip file.
Below is the the instruction that describes the task: ### Input: Remove our local zip file. ### Response: def remove_local_zip(self): """ Remove our local zip file. """ if self.stage_config.get('delete_local_zip', True): try: if os.path.isfile(self.zip_p...
def find_analysis(self, family, started_at, status): """Find a single analysis.""" query = self.Analysis.query.filter_by( family=family, started_at=started_at, status=status, ) return query.first()
Find a single analysis.
Below is the the instruction that describes the task: ### Input: Find a single analysis. ### Response: def find_analysis(self, family, started_at, status): """Find a single analysis.""" query = self.Analysis.query.filter_by( family=family, started_at=started_at, ...
def fetch_items(self, category, **kwargs): """Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] latest = kwargs['latest'] logger.info("F...
Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
Below is the the instruction that describes the task: ### Input: Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items ### Response: def fetch_items(self, category, **kwargs): """Fetch the messages ...
def start(self): """Starts the Kinect v2 sensor stream. Raises ------ IOError If the Kinect v2 is not detected. """ # open packet pipeline if self._packet_pipeline_mode == Kinect2PacketPipelineMode.OPENGL: self._pipeline = lf2.OpenGLPacket...
Starts the Kinect v2 sensor stream. Raises ------ IOError If the Kinect v2 is not detected.
Below is the the instruction that describes the task: ### Input: Starts the Kinect v2 sensor stream. Raises ------ IOError If the Kinect v2 is not detected. ### Response: def start(self): """Starts the Kinect v2 sensor stream. Raises ------ IOEr...
def _extract_readnum(read_dict): """Extract read numbers from old-style fastqs. Handles read 1 and 2 specifications where naming is readname/1 readname/2 """ pat = re.compile(r"(?P<readnum>/\d+)$") parts = pat.split(read_dict["name"]) if len(parts) == 3: name, readnum, endofline = p...
Extract read numbers from old-style fastqs. Handles read 1 and 2 specifications where naming is readname/1 readname/2
Below is the the instruction that describes the task: ### Input: Extract read numbers from old-style fastqs. Handles read 1 and 2 specifications where naming is readname/1 readname/2 ### Response: def _extract_readnum(read_dict): """Extract read numbers from old-style fastqs. Handles read 1 and 2...
def service_password_encryption(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") service = ET.SubElement(config, "service", xmlns="urn:brocade.com:mgmt:brocade-aaa") password_encryption = ET.SubElement(service, "password-encryption") callback = k...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def service_password_encryption(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") service = ET.SubElement(config, "service", xmlns="urn:brocade.com:mgmt:brocade...
def get(self, uri, default_response=None, **kwargs): """ Call GET on the Gitlab server >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False) >>> gitlab.login(user='root', password='5iveL!fe') >>> gitlab.get('/users/5') :param uri: String with the URI for ...
Call GET on the Gitlab server >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False) >>> gitlab.login(user='root', password='5iveL!fe') >>> gitlab.get('/users/5') :param uri: String with the URI for the endpoint to GET from :param default_response: Return value if...
Below is the the instruction that describes the task: ### Input: Call GET on the Gitlab server >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False) >>> gitlab.login(user='root', password='5iveL!fe') >>> gitlab.get('/users/5') :param uri: String with the URI for the ...
def get_devices(self): """ Helper that retuns a dict of devices for this server. :return: Returns a tuple of two elements: - dict<tango class name : list of device names> - dict<device names : tango class name> :rtype: tuple<dict, dict> ""...
Helper that retuns a dict of devices for this server. :return: Returns a tuple of two elements: - dict<tango class name : list of device names> - dict<device names : tango class name> :rtype: tuple<dict, dict>
Below is the the instruction that describes the task: ### Input: Helper that retuns a dict of devices for this server. :return: Returns a tuple of two elements: - dict<tango class name : list of device names> - dict<device names : tango class name> :rtype: tu...
def _determine_doubled_obj_type(self): """Returns the type (class) of the target object. :return: The type (class) of the target. :rtype: type, classobj """ if isclass(self.doubled_obj) or ismodule(self.doubled_obj): return self.doubled_obj return self.doub...
Returns the type (class) of the target object. :return: The type (class) of the target. :rtype: type, classobj
Below is the the instruction that describes the task: ### Input: Returns the type (class) of the target object. :return: The type (class) of the target. :rtype: type, classobj ### Response: def _determine_doubled_obj_type(self): """Returns the type (class) of the target object. :r...
def set_active_current(self, settings): ''' Sets the amperage of each motor for when it is activated by driver. Values are initialized from the `robot_config.high_current` values, and can then be changed through this method by other parts of the API. For example, `Pipette` setti...
Sets the amperage of each motor for when it is activated by driver. Values are initialized from the `robot_config.high_current` values, and can then be changed through this method by other parts of the API. For example, `Pipette` setting the active-current of it's pipette, depending on ...
Below is the the instruction that describes the task: ### Input: Sets the amperage of each motor for when it is activated by driver. Values are initialized from the `robot_config.high_current` values, and can then be changed through this method by other parts of the API. For example, `Pipet...
def rest_call(self, url, method, data=None, sensitive=False, timeout=None, content_json=True, retry=None, max_retry=None, retry_sleep=None): """ Generic REST call worker function **Parameters:** - **url:** URL for the REST call - **method:** METHOD for the...
Generic REST call worker function **Parameters:** - **url:** URL for the REST call - **method:** METHOD for the REST call - **data:** Optional DATA for the call (for POST/PUT/etc.) - **sensitive:** Flag if content request/response should be hidden from logging functions...
Below is the the instruction that describes the task: ### Input: Generic REST call worker function **Parameters:** - **url:** URL for the REST call - **method:** METHOD for the REST call - **data:** Optional DATA for the call (for POST/PUT/etc.) - **sensitive:** Fla...
def copy_from(self, location, timeout=10 * 60): """ This method will fetch the image; the fetch will happen from the device-side using the 'copy' command. Note that the NXAPI appears to be single-threaded, so the code needs to wait until this operation has completed before attem...
This method will fetch the image; the fetch will happen from the device-side using the 'copy' command. Note that the NXAPI appears to be single-threaded, so the code needs to wait until this operation has completed before attempting another API call. Therefore the :timeout: value is se...
Below is the the instruction that describes the task: ### Input: This method will fetch the image; the fetch will happen from the device-side using the 'copy' command. Note that the NXAPI appears to be single-threaded, so the code needs to wait until this operation has completed before atte...
def main(): """This module just acts as an entry point to the bulk of the pipeline. All argument parsing is delegated to metator.sh """ metator_args = sys.argv[1:] entry_point = pkg_resources.resource_filename("metator", "bin/metator.sh") try: metator_process = subprocess.Popen((entry_...
This module just acts as an entry point to the bulk of the pipeline. All argument parsing is delegated to metator.sh
Below is the the instruction that describes the task: ### Input: This module just acts as an entry point to the bulk of the pipeline. All argument parsing is delegated to metator.sh ### Response: def main(): """This module just acts as an entry point to the bulk of the pipeline. All argument parsing is...
def close_path_traces(*args): ''' close_path_traces(pt1, pt2...) yields the path-trace formed by joining the list of path traces at their intersection points in the order given. Note that the direction in which each individual path trace's coordinates are specified is ultimately ignored by this func...
close_path_traces(pt1, pt2...) yields the path-trace formed by joining the list of path traces at their intersection points in the order given. Note that the direction in which each individual path trace's coordinates are specified is ultimately ignored by this function--the only ordering that matters...
Below is the the instruction that describes the task: ### Input: close_path_traces(pt1, pt2...) yields the path-trace formed by joining the list of path traces at their intersection points in the order given. Note that the direction in which each individual path trace's coordinates are specified is ulti...
def _func(self, volume, params): """ Pourier-Tarantola equation from PRB 70, 224107 """ e0, b0, b1, v0 = tuple(params) eta = (volume / v0) ** (1. / 3.) squiggle = -3.*np.log(eta) return e0 + b0 * v0 * squiggle ** 2 / 6. * (3. + squiggle * (b1 - 2))
Pourier-Tarantola equation from PRB 70, 224107
Below is the the instruction that describes the task: ### Input: Pourier-Tarantola equation from PRB 70, 224107 ### Response: def _func(self, volume, params): """ Pourier-Tarantola equation from PRB 70, 224107 """ e0, b0, b1, v0 = tuple(params) eta = (volume / v0) ** (1. / 3...
def get_all_tasks(self, subsystem): """ Return a generator of all PIDs currently in this cgroup for the given subsystem. """ with open(os.path.join(self.per_subsystem[subsystem], 'tasks'), 'r') as tasksFile: for line in tasksFile: yield int(line)
Return a generator of all PIDs currently in this cgroup for the given subsystem.
Below is the the instruction that describes the task: ### Input: Return a generator of all PIDs currently in this cgroup for the given subsystem. ### Response: def get_all_tasks(self, subsystem): """ Return a generator of all PIDs currently in this cgroup for the given subsystem. """ ...
def get_route53_client(agent, region, cooperator=None): """ Get a non-registration Route53 client. """ if cooperator is None: cooperator = task return region.get_client( _Route53Client, agent=agent, creds=region.creds, region=REGION_US_EAST_1, endpoint...
Get a non-registration Route53 client.
Below is the the instruction that describes the task: ### Input: Get a non-registration Route53 client. ### Response: def get_route53_client(agent, region, cooperator=None): """ Get a non-registration Route53 client. """ if cooperator is None: cooperator = task return region.get_client(...
def run(self, data, train_epochs=1000, test_epochs=1000, verbose=None, idx=0, lr=0.01, **kwargs): """Run the CGNN on a given graph.""" verbose = SETTINGS.get_default(verbose=verbose) optim = th.optim.Adam(self.parameters(), lr=lr) self.score.zero_() with trange(train_...
Run the CGNN on a given graph.
Below is the the instruction that describes the task: ### Input: Run the CGNN on a given graph. ### Response: def run(self, data, train_epochs=1000, test_epochs=1000, verbose=None, idx=0, lr=0.01, **kwargs): """Run the CGNN on a given graph.""" verbose = SETTINGS.get_default(verbose=ver...
def gff3_parse_attributes(attributes_string): """ Parse a string of GFF3 attributes ('key=value' pairs delimited by ';') and return a dictionary. """ attributes = dict() fields = attributes_string.split(';') for f in fields: if '=' in f: key, value = f.split('=')...
Parse a string of GFF3 attributes ('key=value' pairs delimited by ';') and return a dictionary.
Below is the the instruction that describes the task: ### Input: Parse a string of GFF3 attributes ('key=value' pairs delimited by ';') and return a dictionary. ### Response: def gff3_parse_attributes(attributes_string): """ Parse a string of GFF3 attributes ('key=value' pairs delimited by ';') a...
def get(self, conn_name, default=None, **kwargs): """ returns the specified connection args: conn_name: the name of the connection """ if isinstance(conn_name, RdfwConnections): return conn_name try: return self.conns[conn_name] excep...
returns the specified connection args: conn_name: the name of the connection
Below is the the instruction that describes the task: ### Input: returns the specified connection args: conn_name: the name of the connection ### Response: def get(self, conn_name, default=None, **kwargs): """ returns the specified connection args: conn_name: the n...
def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs
Helper function for building an attribute dictionary.
Below is the the instruction that describes the task: ### Input: Helper function for building an attribute dictionary. ### Response: def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(extra_attrs=None, **kw...
def _extract_mnist_labels(filename, num_labels): """Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A int64 numpy array of shape [num_labels] """ with gzip.open(filename) as bytestream: ...
Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A int64 numpy array of shape [num_labels]
Below is the the instruction that describes the task: ### Input: Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A int64 numpy array of shape [num_labels] ### Response: def _extract_mnist_lab...
def _refresh(self): """Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error on the query. """ if l...
Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error on the query.
Below is the the instruction that describes the task: ### Input: Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error ...
def destroy(name, conn=None, call=None, kwargs=None): ''' Destroy a VM CLI Examples: .. code-block:: bash salt-cloud -d myminion salt-cloud -a destroy myminion service_name=myservice ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action ...
Destroy a VM CLI Examples: .. code-block:: bash salt-cloud -d myminion salt-cloud -a destroy myminion service_name=myservice
Below is the the instruction that describes the task: ### Input: Destroy a VM CLI Examples: .. code-block:: bash salt-cloud -d myminion salt-cloud -a destroy myminion service_name=myservice ### Response: def destroy(name, conn=None, call=None, kwargs=None): ''' Destroy a VM ...
def load(path, dtype=np.float64): """ Loads an image from file. Parameters ---------- path : str Path to image file. dtype : np.dtype Defaults to ``np.float64``, which means the image will be returned as a float with values between 0 and 1. If ``np.uint8`` is specified, ...
Loads an image from file. Parameters ---------- path : str Path to image file. dtype : np.dtype Defaults to ``np.float64``, which means the image will be returned as a float with values between 0 and 1. If ``np.uint8`` is specified, the values will be between 0 and 255 a...
Below is the the instruction that describes the task: ### Input: Loads an image from file. Parameters ---------- path : str Path to image file. dtype : np.dtype Defaults to ``np.float64``, which means the image will be returned as a float with values between 0 and 1. If ``np...
def _print_token_factory(col): """Internal helper to provide color names.""" def _helper(msg): style = style_from_dict({ Token.Color: col, }) tokens = [ (Token.Color, msg) ] print_tokens(tokens, style=style) def _helper_no_terminal(msg): ...
Internal helper to provide color names.
Below is the the instruction that describes the task: ### Input: Internal helper to provide color names. ### Response: def _print_token_factory(col): """Internal helper to provide color names.""" def _helper(msg): style = style_from_dict({ Token.Color: col, }) tokens = [...
def median_grouped(data, interval=1): """"Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 >>> median_grouped([52, 52, 53, 54]) 52.5 This calculates the median as the 50th percentile, and should be used when your data is...
Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 >>> median_grouped([52, 52, 53, 54]) 52.5 This calculates the median as the 50th percentile, and should be used when your data is continuous and grouped. In the above example,...
Below is the the instruction that describes the task: ### Input: Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 >>> median_grouped([52, 52, 53, 54]) 52.5 This calculates the median as the 50th percentile, and should be ...
def _init_client(): '''Setup client and init datastore. ''' global client, path_prefix if client is not None: return etcd_kwargs = { 'host': __opts__.get('etcd.host', '127.0.0.1'), 'port': __opts__.get('etcd.port', 2379), 'protocol': __opts__.get('etcd.pr...
Setup client and init datastore.
Below is the the instruction that describes the task: ### Input: Setup client and init datastore. ### Response: def _init_client(): '''Setup client and init datastore. ''' global client, path_prefix if client is not None: return etcd_kwargs = { 'host': __opts__.get('etcd.ho...
def imagetransformer_ae_imagenet(): """For 64x64 ImageNet. ~56M trainable variables.""" hparams = imagetransformer_ae_cifar() hparams.max_length = int(64 * 64 * 3) hparams.img_len = 64 hparams.num_heads = 4 # Heads are expensive on TPUs. # Reduce architecture from 32x32 CIFAR-10 in order to fit in memory. ...
For 64x64 ImageNet. ~56M trainable variables.
Below is the the instruction that describes the task: ### Input: For 64x64 ImageNet. ~56M trainable variables. ### Response: def imagetransformer_ae_imagenet(): """For 64x64 ImageNet. ~56M trainable variables.""" hparams = imagetransformer_ae_cifar() hparams.max_length = int(64 * 64 * 3) hparams.img_len = ...
def unlock(name, zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example) identifier=None, max_concurrency=1, ephemeral_lease=False, profile=None, scheme=None, username=None, password=None,...
Remove lease from semaphore.
Below is the the instruction that describes the task: ### Input: Remove lease from semaphore. ### Response: def unlock(name, zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example) identifier=None, max_concurrency=1, ephemeral_...
def handle_callback_exception(self, callback): """This method is called whenever a callback run by the `IOLoop` throws an exception. By default simply logs the exception as an error. Subclasses may override this method to customize reporting of exceptions. The exception itself...
This method is called whenever a callback run by the `IOLoop` throws an exception. By default simply logs the exception as an error. Subclasses may override this method to customize reporting of exceptions. The exception itself is not passed explicitly, but is available in `sy...
Below is the the instruction that describes the task: ### Input: This method is called whenever a callback run by the `IOLoop` throws an exception. By default simply logs the exception as an error. Subclasses may override this method to customize reporting of exceptions. The excep...
def verifyWriteMode(files): """ Checks whether files are writable. It is up to the calling routine to raise an Exception, if desired. This function returns True, if all files are writable and False, if any are not writable. In addition, for all files found to not be writable, it will print out...
Checks whether files are writable. It is up to the calling routine to raise an Exception, if desired. This function returns True, if all files are writable and False, if any are not writable. In addition, for all files found to not be writable, it will print out the list of names of affected files.
Below is the the instruction that describes the task: ### Input: Checks whether files are writable. It is up to the calling routine to raise an Exception, if desired. This function returns True, if all files are writable and False, if any are not writable. In addition, for all files found to not be wr...
def create_from_tables(cls, norm_type='eflux', tab_s="SCANDATA", tab_e="EBOUNDS"): """Create a CastroData object from two tables Parameters ---------- norm_type : str Type of normalization to use. Valid options are: ...
Create a CastroData object from two tables Parameters ---------- norm_type : str Type of normalization to use. Valid options are: * norm : Normalization w.r.t. to test source * flux : Flux of the test source ( ph cm^-2 s^-1 ) * eflux: Energy Flu...
Below is the the instruction that describes the task: ### Input: Create a CastroData object from two tables Parameters ---------- norm_type : str Type of normalization to use. Valid options are: * norm : Normalization w.r.t. to test source * flux : Flux...
def iter_srels(self): """ Generate a 2-tuple `(source_uri, srel)` for each of the relationships in the package. """ for srel in self._pkg_srels: yield (PACKAGE_URI, srel) for spart in self._sparts: for srel in spart.srels: yield (sp...
Generate a 2-tuple `(source_uri, srel)` for each of the relationships in the package.
Below is the the instruction that describes the task: ### Input: Generate a 2-tuple `(source_uri, srel)` for each of the relationships in the package. ### Response: def iter_srels(self): """ Generate a 2-tuple `(source_uri, srel)` for each of the relationships in the package. ...
def process_shell(self, creator, entry, config): """Processing a shell entry.""" self.logger.info("Processing Bash code: start") output = [] shell = creator(entry, config) for line in shell.process(): output.append(line) self.logger.info(" | %s", line) ...
Processing a shell entry.
Below is the the instruction that describes the task: ### Input: Processing a shell entry. ### Response: def process_shell(self, creator, entry, config): """Processing a shell entry.""" self.logger.info("Processing Bash code: start") output = [] shell = creator(entry, config) ...
def get_ylabel(self): """Text for y-axis label, check if channel defines it """ units = self.units if len(units) == 1 and str(units[0]) == '': # dimensionless return '' if len(units) == 1 and self.usetex: return units[0].to_string('latex') elif l...
Text for y-axis label, check if channel defines it
Below is the the instruction that describes the task: ### Input: Text for y-axis label, check if channel defines it ### Response: def get_ylabel(self): """Text for y-axis label, check if channel defines it """ units = self.units if len(units) == 1 and str(units[0]) == '': # dimen...
def elink(db: str, dbfrom: str, ids=False, webenv=False, query_key=False, api_key=False, email=False, **kwargs) -> Optional[ElinkResult]: """Get document summaries using the Entrez ESearch API. Parameters ---------- db : str Entez database to get ids from. dbfrom : str Ent...
Get document summaries using the Entrez ESearch API. Parameters ---------- db : str Entez database to get ids from. dbfrom : str Entez database the provided ids are from. ids : list or str List of IDs to submit to the server. webenv : str An Entrez WebEnv to use ...
Below is the the instruction that describes the task: ### Input: Get document summaries using the Entrez ESearch API. Parameters ---------- db : str Entez database to get ids from. dbfrom : str Entez database the provided ids are from. ids : list or str List of IDs to su...
def run_validators(self, value): """Run the validators on the setting value.""" errors = [] for validator in self.validators: try: validator(value) except ValidationError as error: errors.extend(error.messages) if errors: ...
Run the validators on the setting value.
Below is the the instruction that describes the task: ### Input: Run the validators on the setting value. ### Response: def run_validators(self, value): """Run the validators on the setting value.""" errors = [] for validator in self.validators: try: validator(va...
def _select(self): """Fetch the elements from the browser.""" for element in self.browser.find_elements_by_xpath(self.xpath): if self.filter_displayed: if not element.is_displayed(): continue if self.filter_enabled: if not ele...
Fetch the elements from the browser.
Below is the the instruction that describes the task: ### Input: Fetch the elements from the browser. ### Response: def _select(self): """Fetch the elements from the browser.""" for element in self.browser.find_elements_by_xpath(self.xpath): if self.filter_displayed: if...
def main(): """ NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a pmag_results table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 9...
NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a pmag_results table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 90., 0. -f FILE p...
Below is the the instruction that describes the task: ### Input: NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a pmag_results table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ...
def instance_from_str(instance_str): """ Given an instance string in the form "app.Model:pk", returns a tuple of ``(model, instance)``. If the pk part is empty, ``instance`` will be ``None``. Raises ``ValueError`` on invalid model strings or missing instances. """ match = instance_str_re.mat...
Given an instance string in the form "app.Model:pk", returns a tuple of ``(model, instance)``. If the pk part is empty, ``instance`` will be ``None``. Raises ``ValueError`` on invalid model strings or missing instances.
Below is the the instruction that describes the task: ### Input: Given an instance string in the form "app.Model:pk", returns a tuple of ``(model, instance)``. If the pk part is empty, ``instance`` will be ``None``. Raises ``ValueError`` on invalid model strings or missing instances. ### Response: def ...
def assert_empty(self, class_name: str): """ Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `calling`...
Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `calling` class, the one that got extra parameters (if there a...
Below is the the instruction that describes the task: ### Input: Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `...
def to_XML(self, xml_declaration=True, xmlns=True): """ Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefix...
Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefixes. :param XML_declaration: if ``True`` (default) prints a lead...
Below is the the instruction that describes the task: ### Input: Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefixes....
def __make_response(self, data, default_renderer=None): """ Creates a Flask response object from the specified data. The appropriated encoder is taken based on the request header Accept. If there is not data to be serialized the response status code is 204. :param data: The Pyth...
Creates a Flask response object from the specified data. The appropriated encoder is taken based on the request header Accept. If there is not data to be serialized the response status code is 204. :param data: The Python object to be serialized. :return: A Flask response object.
Below is the the instruction that describes the task: ### Input: Creates a Flask response object from the specified data. The appropriated encoder is taken based on the request header Accept. If there is not data to be serialized the response status code is 204. :param data: The Python obje...
def element(self): """ Attempt to return the atomic symbol based on the VRHFIN keyword. """ element = self.keywords["VRHFIN"].split(":")[0].strip() try: return Element(element).symbol except ValueError: # VASP incorrectly gives the element symbol f...
Attempt to return the atomic symbol based on the VRHFIN keyword.
Below is the the instruction that describes the task: ### Input: Attempt to return the atomic symbol based on the VRHFIN keyword. ### Response: def element(self): """ Attempt to return the atomic symbol based on the VRHFIN keyword. """ element = self.keywords["VRHFIN"].split(":")[0]...
def load_metadata_csv(input_filepath): """ Return dict of metadata. Format is either dict (filenames are keys) or dict-of-dicts (project member IDs as top level keys, then filenames as keys). :param input_filepath: This field is the filepath of the csv file. """ with open(input_filepath) a...
Return dict of metadata. Format is either dict (filenames are keys) or dict-of-dicts (project member IDs as top level keys, then filenames as keys). :param input_filepath: This field is the filepath of the csv file.
Below is the the instruction that describes the task: ### Input: Return dict of metadata. Format is either dict (filenames are keys) or dict-of-dicts (project member IDs as top level keys, then filenames as keys). :param input_filepath: This field is the filepath of the csv file. ### Response: def lo...
def preconnect(self, size=-1): """(pre)Connects some or all redis clients inside the pool. Args: size (int): number of redis clients to build and to connect (-1 means all clients if pool max_size > -1) Raises: ClientError: when size == -1 and pool max_si...
(pre)Connects some or all redis clients inside the pool. Args: size (int): number of redis clients to build and to connect (-1 means all clients if pool max_size > -1) Raises: ClientError: when size == -1 and pool max_size == -1
Below is the the instruction that describes the task: ### Input: (pre)Connects some or all redis clients inside the pool. Args: size (int): number of redis clients to build and to connect (-1 means all clients if pool max_size > -1) Raises: ClientError: when...
def escape_queue(s): """Escapes the path to a queue, e.g. preserves ~ at the begining. """ if isinstance(s, PosixPath): s = unicode_(s) elif isinstance(s, bytes): s = s.decode('utf-8') if s.startswith('~/'): return '~/' + shell_escape(s[2:]) else: return shell_esc...
Escapes the path to a queue, e.g. preserves ~ at the begining.
Below is the the instruction that describes the task: ### Input: Escapes the path to a queue, e.g. preserves ~ at the begining. ### Response: def escape_queue(s): """Escapes the path to a queue, e.g. preserves ~ at the begining. """ if isinstance(s, PosixPath): s = unicode_(s) elif isinstan...
def construct_came_from(environ): """ The URL that the user used when the process where interupted for single-sign-on processing. """ came_from = environ.get("PATH_INFO") qstr = environ.get("QUERY_STRING", "") if qstr: came_from += "?" + qstr return came_from
The URL that the user used when the process where interupted for single-sign-on processing.
Below is the the instruction that describes the task: ### Input: The URL that the user used when the process where interupted for single-sign-on processing. ### Response: def construct_came_from(environ): """ The URL that the user used when the process where interupted for single-sign-on processing. ""...
def appendcsv(table, source=None, encoding=None, errors='strict', write_header=False, **csvargs): """ Append data rows to an existing CSV file. As :func:`petl.io.csv.tocsv` but the file is opened in append mode and the table header is not written by default. Note that no attempt is ma...
Append data rows to an existing CSV file. As :func:`petl.io.csv.tocsv` but the file is opened in append mode and the table header is not written by default. Note that no attempt is made to check that the fields or row lengths are consistent with the existing data, the data rows from the table are simpl...
Below is the the instruction that describes the task: ### Input: Append data rows to an existing CSV file. As :func:`petl.io.csv.tocsv` but the file is opened in append mode and the table header is not written by default. Note that no attempt is made to check that the fields or row lengths are cons...
async def get_key_metadata(wallet_handle: int, verkey: str) -> str: """ Retrieves the meta information for the giving key in the wallet. :param wallet_handle: Wallet handle (created by open_wallet). :param verkey: The key (verkey, key id) to retrieve metadata. :return: me...
Retrieves the meta information for the giving key in the wallet. :param wallet_handle: Wallet handle (created by open_wallet). :param verkey: The key (verkey, key id) to retrieve metadata. :return: metadata: The meta information stored with the key; Can be null if no metadata was saved for this key.
Below is the the instruction that describes the task: ### Input: Retrieves the meta information for the giving key in the wallet. :param wallet_handle: Wallet handle (created by open_wallet). :param verkey: The key (verkey, key id) to retrieve metadata. :return: metadata: The meta information stored wi...
def max_sparse_hyperplane_size(tree): """Determine the most number on non zeros in a hyperplane entry""" if tree.is_leaf: return 0 else: return max( tree.hyperplane.shape[1], max_sparse_hyperplane_size(tree.left_child), max_sparse_hyperplane_size(tree.righ...
Determine the most number on non zeros in a hyperplane entry
Below is the the instruction that describes the task: ### Input: Determine the most number on non zeros in a hyperplane entry ### Response: def max_sparse_hyperplane_size(tree): """Determine the most number on non zeros in a hyperplane entry""" if tree.is_leaf: return 0 else: return max...
def _register_numpy_extensions(self): """ Numpy extensions are builtin """ # system checks import numpy as np numpy_floating_types = (np.float16, np.float32, np.float64) if hasattr(np, 'float128'): # nocover numpy_floating_types = numpy_floating_types...
Numpy extensions are builtin
Below is the the instruction that describes the task: ### Input: Numpy extensions are builtin ### Response: def _register_numpy_extensions(self): """ Numpy extensions are builtin """ # system checks import numpy as np numpy_floating_types = (np.float16, np.float32, n...
def __reset_parser(self): """Reset parser's internal variables Restore the parser to an initial state. Useful when creating a new parser or reusing an existing one. """ self.result = [] self.hash_comments = [] self.__cstate = None self.__curcommand = Non...
Reset parser's internal variables Restore the parser to an initial state. Useful when creating a new parser or reusing an existing one.
Below is the the instruction that describes the task: ### Input: Reset parser's internal variables Restore the parser to an initial state. Useful when creating a new parser or reusing an existing one. ### Response: def __reset_parser(self): """Reset parser's internal variables Res...
def retrieveVals(self): """Retrieve values for graphs.""" opcinfo = OPCinfo(self._host, self._port, self._user, self._password, self._monpath, self._ssl) stats = opcinfo.getAllStats() if self.hasGraph('php_opc_memory') and stats: mem = stat...
Retrieve values for graphs.
Below is the the instruction that describes the task: ### Input: Retrieve values for graphs. ### Response: def retrieveVals(self): """Retrieve values for graphs.""" opcinfo = OPCinfo(self._host, self._port, self._user, self._password, self._monpath, self._ssl) sta...
def _copy_old_features(new_eopatch, old_eopatch, copy_features): """ Copy features from old EOPatch :param new_eopatch: New EOPatch container where the old features will be copied to :type new_eopatch: EOPatch :param old_eopatch: Old EOPatch container where the old features are located ...
Copy features from old EOPatch :param new_eopatch: New EOPatch container where the old features will be copied to :type new_eopatch: EOPatch :param old_eopatch: Old EOPatch container where the old features are located :type old_eopatch: EOPatch :param copy_features: List of tupl...
Below is the the instruction that describes the task: ### Input: Copy features from old EOPatch :param new_eopatch: New EOPatch container where the old features will be copied to :type new_eopatch: EOPatch :param old_eopatch: Old EOPatch container where the old features are located ...
def configure_settings(): """ Configures settings for manage.py and for run_tests.py. """ if not settings.configured: db_config = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_kittens_db.sqlite3', } settings.configure( TEST_RUNNER=...
Configures settings for manage.py and for run_tests.py.
Below is the the instruction that describes the task: ### Input: Configures settings for manage.py and for run_tests.py. ### Response: def configure_settings(): """ Configures settings for manage.py and for run_tests.py. """ if not settings.configured: db_config = { 'ENGINE': 'd...
def color_table(color, N=1, sort=False, sort_values=False, inline=False, as_html=False): """ Generates a colour table Parameters: ----------- color : string | list | dict Color representation in rgba|rgb|hex If a list of colors is passed then these ...
Generates a colour table Parameters: ----------- color : string | list | dict Color representation in rgba|rgb|hex If a list of colors is passed then these are displayed in a table N : int number of colou...
Below is the the instruction that describes the task: ### Input: Generates a colour table Parameters: ----------- color : string | list | dict Color representation in rgba|rgb|hex If a list of colors is passed then these are displayed...
def update(self, settings): """ Update object attributes from given settings Args: settings (dict): Dictionnary of elements to update settings. Returns: dict: Dictionnary of all current saved settings. """ settings = self.clean(settings) ...
Update object attributes from given settings Args: settings (dict): Dictionnary of elements to update settings. Returns: dict: Dictionnary of all current saved settings.
Below is the the instruction that describes the task: ### Input: Update object attributes from given settings Args: settings (dict): Dictionnary of elements to update settings. Returns: dict: Dictionnary of all current saved settings. ### Response: def update(self, setting...
def plot(self): """ plot the activation function """ plt.ion() plt.show() x = numpy.linspace(0, 15, 100) y = numpy.zeros(x.shape) y = self.excite(y, x) plt.plot(x, y) plt.xlabel('Input') plt.ylabel('Persistence') plt.title('Sigmoid Activation Function')
plot the activation function
Below is the the instruction that describes the task: ### Input: plot the activation function ### Response: def plot(self): """ plot the activation function """ plt.ion() plt.show() x = numpy.linspace(0, 15, 100) y = numpy.zeros(x.shape) y = self.excite(y, x) plt.plot(x, y) ...
def _model_abilities_two_components(self,beta): """ Creates the structure of the model - store abilities Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- theta : np.array ...
Creates the structure of the model - store abilities Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- theta : np.array Contains the predicted values for the time series ...
Below is the the instruction that describes the task: ### Input: Creates the structure of the model - store abilities Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- theta : np.array ...
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. ...
Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if th...
Below is the the instruction that describes the task: ### Input: Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the lin...
def get_hashtags(tweet): """ Get a list of hashtags in the Tweet Note that in the case of a quote-tweet, this does not return the hashtags in the quoted status. Args: tweet (Tweet or dict): A Tweet object or dictionary Returns: list (a list of strings): list of all of the hasht...
Get a list of hashtags in the Tweet Note that in the case of a quote-tweet, this does not return the hashtags in the quoted status. Args: tweet (Tweet or dict): A Tweet object or dictionary Returns: list (a list of strings): list of all of the hashtags in the Tweet Example: ...
Below is the the instruction that describes the task: ### Input: Get a list of hashtags in the Tweet Note that in the case of a quote-tweet, this does not return the hashtags in the quoted status. Args: tweet (Tweet or dict): A Tweet object or dictionary Returns: list (a list of st...
def resolve_memory_access(self, tb, x86_mem_operand): """Return operand memory access translation. """ size = self.__get_memory_access_size(x86_mem_operand) addr = None if x86_mem_operand.base: addr = ReilRegisterOperand(x86_mem_operand.base, size) if x86_m...
Return operand memory access translation.
Below is the the instruction that describes the task: ### Input: Return operand memory access translation. ### Response: def resolve_memory_access(self, tb, x86_mem_operand): """Return operand memory access translation. """ size = self.__get_memory_access_size(x86_mem_operand) addr...
def _seconds_have_elapsed(token, num_seconds): """Tests if 'num_seconds' have passed since 'token' was requested. Not strictly thread-safe - may log with the wrong frequency if called concurrently from multiple threads. Accuracy depends on resolution of 'timeit.default_timer()'. Always returns True on the f...
Tests if 'num_seconds' have passed since 'token' was requested. Not strictly thread-safe - may log with the wrong frequency if called concurrently from multiple threads. Accuracy depends on resolution of 'timeit.default_timer()'. Always returns True on the first call for a given 'token'. Args: token: T...
Below is the the instruction that describes the task: ### Input: Tests if 'num_seconds' have passed since 'token' was requested. Not strictly thread-safe - may log with the wrong frequency if called concurrently from multiple threads. Accuracy depends on resolution of 'timeit.default_timer()'. Always retu...
def parse_headers(lines, offset=0): """ Parse the headers in a STOMP response :param list(str) lines: the lines received in the message response :param int offset: the starting line number :rtype: dict(str,str) """ headers = {} for header_line in lines[offset:]: header_match = ...
Parse the headers in a STOMP response :param list(str) lines: the lines received in the message response :param int offset: the starting line number :rtype: dict(str,str)
Below is the the instruction that describes the task: ### Input: Parse the headers in a STOMP response :param list(str) lines: the lines received in the message response :param int offset: the starting line number :rtype: dict(str,str) ### Response: def parse_headers(lines, offset=0): """ Par...
def rebuild_cmaps(self): """Builds a color RGB image containing color bars of all the possible color maps and their labels. """ self.logger.info("building color maps image") ht, wd, sep = self._cmht, self._cmwd, self._cmsep viewer = self.p_view # put the canvas i...
Builds a color RGB image containing color bars of all the possible color maps and their labels.
Below is the the instruction that describes the task: ### Input: Builds a color RGB image containing color bars of all the possible color maps and their labels. ### Response: def rebuild_cmaps(self): """Builds a color RGB image containing color bars of all the possible color maps and their ...
def create_branch(profile, name, branch_off): """Create a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name ...
Create a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name The name of the new branch. branch_...
Below is the the instruction that describes the task: ### Input: Create a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. ...
def get_slave_managers(self, as_coro=False): """Return all slave environment manager addresses. :param bool as_coro: If ``True`` returns awaitable coroutine, otherwise runs the calls to the slave managers asynchoronously in the event loop. This method returns the addres...
Return all slave environment manager addresses. :param bool as_coro: If ``True`` returns awaitable coroutine, otherwise runs the calls to the slave managers asynchoronously in the event loop. This method returns the addresses of the true slave environment managers, i.e....
Below is the the instruction that describes the task: ### Input: Return all slave environment manager addresses. :param bool as_coro: If ``True`` returns awaitable coroutine, otherwise runs the calls to the slave managers asynchoronously in the event loop. This method retur...
def _do_submit_problems(self): """Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread. """ try: while True: # Pull as many problems as we can, block on the first one, #...
Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread.
Below is the the instruction that describes the task: ### Input: Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread. ### Response: def _do_submit_problems(self): """Pull problems from the submission queue and submit them. ...
def _validate_user_inputs(self, attributes=None, event_tags=None): """ Helper method to validate user inputs. Args: attributes: Dict representing user attributes. event_tags: Dict representing metadata associated with an event. Returns: Boolean True if inputs are valid. False otherwise. ...
Helper method to validate user inputs. Args: attributes: Dict representing user attributes. event_tags: Dict representing metadata associated with an event. Returns: Boolean True if inputs are valid. False otherwise.
Below is the the instruction that describes the task: ### Input: Helper method to validate user inputs. Args: attributes: Dict representing user attributes. event_tags: Dict representing metadata associated with an event. Returns: Boolean True if inputs are valid. False otherwise. ### Re...
def _assert_keys_match(keys1, keys2): """Ensure the two list of keys matches.""" if set(keys1) != set(keys2): raise ValueError('{} {}'.format(list(keys1), list(keys2)))
Ensure the two list of keys matches.
Below is the the instruction that describes the task: ### Input: Ensure the two list of keys matches. ### Response: def _assert_keys_match(keys1, keys2): """Ensure the two list of keys matches.""" if set(keys1) != set(keys2): raise ValueError('{} {}'.format(list(keys1), list(keys2)))
def relocated_grid_from_grid_jit(grid, border_grid): """ Relocate the coordinates of a grid to its border if they are outside the border. This is performed as \ follows: 1) Use the mean value of the grid's y and x coordinates to determine the origin of the grid. 2) Compute the radial di...
Relocate the coordinates of a grid to its border if they are outside the border. This is performed as \ follows: 1) Use the mean value of the grid's y and x coordinates to determine the origin of the grid. 2) Compute the radial distance of every grid coordinate from the origin. 3) For e...
Below is the the instruction that describes the task: ### Input: Relocate the coordinates of a grid to its border if they are outside the border. This is performed as \ follows: 1) Use the mean value of the grid's y and x coordinates to determine the origin of the grid. 2) Compute the radia...
def AAA(cpu): """ ASCII adjust after addition. Adjusts the sum of two unpacked BCD values to create an unpacked BCD result. The AL register is the implied source and destination operand for this instruction. The AAA instruction is only useful when it follows an ADD instr...
ASCII adjust after addition. Adjusts the sum of two unpacked BCD values to create an unpacked BCD result. The AL register is the implied source and destination operand for this instruction. The AAA instruction is only useful when it follows an ADD instruction that adds (binary addition)...
Below is the the instruction that describes the task: ### Input: ASCII adjust after addition. Adjusts the sum of two unpacked BCD values to create an unpacked BCD result. The AL register is the implied source and destination operand for this instruction. The AAA instruction is only useful w...
def _update(self, rect, delta_y, force_update_margins=False): """ Updates panels """ helper = TextHelper(self.editor) if not self: return for zones_id, zone in self._panels.items(): if zones_id == Panel.Position.TOP or \ zones_id == Panel.Position.B...
Updates panels
Below is the the instruction that describes the task: ### Input: Updates panels ### Response: def _update(self, rect, delta_y, force_update_margins=False): """ Updates panels """ helper = TextHelper(self.editor) if not self: return for zones_id, zone in self._panels.item...
def embedManifestDllCheck(target, source, env): """Function run by embedManifestDllCheckAction to check for existence of manifest and other conditions, and embed the manifest by calling embedManifestDllAction if so.""" if env.get('WINDOWS_EMBED_MANIFEST', 0): manifestSrc = target[0].get_abspath() + ...
Function run by embedManifestDllCheckAction to check for existence of manifest and other conditions, and embed the manifest by calling embedManifestDllAction if so.
Below is the the instruction that describes the task: ### Input: Function run by embedManifestDllCheckAction to check for existence of manifest and other conditions, and embed the manifest by calling embedManifestDllAction if so. ### Response: def embedManifestDllCheck(target, source, env): """Function run...
def authenticate(self, code: str) -> 'Preston': """Authenticates using the code from the EVE SSO. A new Preston object is returned; this object is not modified. The intended usage is: auth = preston.authenticate('some_code_here') Args: code: SSO code ...
Authenticates using the code from the EVE SSO. A new Preston object is returned; this object is not modified. The intended usage is: auth = preston.authenticate('some_code_here') Args: code: SSO code Returns: new Preston, authenticated
Below is the the instruction that describes the task: ### Input: Authenticates using the code from the EVE SSO. A new Preston object is returned; this object is not modified. The intended usage is: auth = preston.authenticate('some_code_here') Args: code: SSO code...
def send(self, subname, delta): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The time delta (time.time() - time.time()) to report :type delta: float...
Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The time delta (time.time() - time.time()) to report :type delta: float
Below is the the instruction that describes the task: ### Input: Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The time delta (time.time() - time.time()) to report ...
def run_tree_inference(self, nexus, idx): """ Write nexus to tmpfile, runs phyml tree inference, and parses and returns the resulting tree. """ ## create a tmpdir for this test tmpdir = tempfile.tempdir tmpfile = os.path.join(tempfile.NamedTemporaryFile( ...
Write nexus to tmpfile, runs phyml tree inference, and parses and returns the resulting tree.
Below is the the instruction that describes the task: ### Input: Write nexus to tmpfile, runs phyml tree inference, and parses and returns the resulting tree. ### Response: def run_tree_inference(self, nexus, idx): """ Write nexus to tmpfile, runs phyml tree inference, and parses an...
def get(self, key, default=None): """ Get item from object for given key (DataFrame column, Panel slice, etc.). Returns default value if not found. Parameters ---------- key : object Returns ------- value : same type as items contained in object ...
Get item from object for given key (DataFrame column, Panel slice, etc.). Returns default value if not found. Parameters ---------- key : object Returns ------- value : same type as items contained in object
Below is the the instruction that describes the task: ### Input: Get item from object for given key (DataFrame column, Panel slice, etc.). Returns default value if not found. Parameters ---------- key : object Returns ------- value : same type as items conta...
def open(self): """Open an existing database""" if self._table_exists(): self.mode = "open" # get table info self._get_table_info() self.types = dict([ (f[0],self.conv_func[f[1].upper()]) for f in self.fields if f[1].upper() in self...
Open an existing database
Below is the the instruction that describes the task: ### Input: Open an existing database ### Response: def open(self): """Open an existing database""" if self._table_exists(): self.mode = "open" # get table info self._get_table_info() self.typ...
def _get_bgzip_version(exe): """return bgzip version as string""" p = subprocess.Popen([exe, "-h"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output = p.communicate() version_line = output[0].splitlines()[1] version = re.match(r"(?:Version:|bgzip \(htslib\))\s+(\d+\....
return bgzip version as string
Below is the the instruction that describes the task: ### Input: return bgzip version as string ### Response: def _get_bgzip_version(exe): """return bgzip version as string""" p = subprocess.Popen([exe, "-h"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output = p.communi...
def p_debug(self, message): "Format and print debug messages" print("{}{} `{}`".format(self._debug_indent * " ", message, repr(self.p_suffix(10))))
Format and print debug messages
Below is the the instruction that describes the task: ### Input: Format and print debug messages ### Response: def p_debug(self, message): "Format and print debug messages" print("{}{} `{}`".format(self._debug_indent * " ", message, repr(self.p_suffix(10))))
def set_override_rendered(self): """ Set self.request.override_renderer if needed. """ if '' in self.request.accept: self.request.override_renderer = self._default_renderer elif 'application/json' in self.request.accept: self.request.override_renderer = 'nefertari_json' ...
Set self.request.override_renderer if needed.
Below is the the instruction that describes the task: ### Input: Set self.request.override_renderer if needed. ### Response: def set_override_rendered(self): """ Set self.request.override_renderer if needed. """ if '' in self.request.accept: self.request.override_renderer = self._defaul...
def breaks(self, frame, no_remove=False): """Return True if there's a breakpoint at frame""" for breakpoint in set(self.breakpoints): if breakpoint.breaks(frame): if breakpoint.temporary and not no_remove: self.breakpoints.remove(breakpoint) ...
Return True if there's a breakpoint at frame
Below is the the instruction that describes the task: ### Input: Return True if there's a breakpoint at frame ### Response: def breaks(self, frame, no_remove=False): """Return True if there's a breakpoint at frame""" for breakpoint in set(self.breakpoints): if breakpoint.breaks(frame): ...
def process_fastq_plain(fastq, **kwargs): """Combine metrics extracted from a fastq file.""" logging.info("Nanoget: Starting to collect statistics from plain fastq file.") inputfastq = handle_compressed_input(fastq) return ut.reduce_memory_usage(pd.DataFrame( data=[res for res in extract_from_fa...
Combine metrics extracted from a fastq file.
Below is the the instruction that describes the task: ### Input: Combine metrics extracted from a fastq file. ### Response: def process_fastq_plain(fastq, **kwargs): """Combine metrics extracted from a fastq file.""" logging.info("Nanoget: Starting to collect statistics from plain fastq file.") inputfa...
def pause(self) -> None: """Pause recording. Thread safe and UI safe.""" with self.__state_lock: if self.__state == DataChannelBuffer.State.started: self.__state = DataChannelBuffer.State.paused
Pause recording. Thread safe and UI safe.
Below is the the instruction that describes the task: ### Input: Pause recording. Thread safe and UI safe. ### Response: def pause(self) -> None: """Pause recording. Thread safe and UI safe.""" with self.__state_lock: if self.__state == DataChannelBuffer.State.started:...
def get_product_target_mappings_for_targets(self, targets): """Gets the product-target associations for the given targets, preserving the input order. :API: public :param targets: The targets to lookup products for. :returns: The ordered (product, target) tuples. """ product_target_mappings = ...
Gets the product-target associations for the given targets, preserving the input order. :API: public :param targets: The targets to lookup products for. :returns: The ordered (product, target) tuples.
Below is the the instruction that describes the task: ### Input: Gets the product-target associations for the given targets, preserving the input order. :API: public :param targets: The targets to lookup products for. :returns: The ordered (product, target) tuples. ### Response: def get_product_targe...
def precision(y, y_pred): """Precision score precision = true_positives / (true_positives + false_positives) Parameters: ----------- y : vector, shape (n_samples,) The target labels. y_pred : vector, shape (n_samples,) The predicted labels. Returns: -------- preci...
Precision score precision = true_positives / (true_positives + false_positives) Parameters: ----------- y : vector, shape (n_samples,) The target labels. y_pred : vector, shape (n_samples,) The predicted labels. Returns: -------- precision : float
Below is the the instruction that describes the task: ### Input: Precision score precision = true_positives / (true_positives + false_positives) Parameters: ----------- y : vector, shape (n_samples,) The target labels. y_pred : vector, shape (n_samples,) The predicted labels. ...
def _prepare_variables(self): """Prepare Variables for YellowFin. Returns: Grad**2, Norm, Norm**2, Mean(Norm**2) ops """ self._moving_averager = tf.train.ExponentialMovingAverage( decay=self._beta, zero_debias=self._zero_debias) # assert self._grad is not None and len(self._grad) > 0 ...
Prepare Variables for YellowFin. Returns: Grad**2, Norm, Norm**2, Mean(Norm**2) ops
Below is the the instruction that describes the task: ### Input: Prepare Variables for YellowFin. Returns: Grad**2, Norm, Norm**2, Mean(Norm**2) ops ### Response: def _prepare_variables(self): """Prepare Variables for YellowFin. Returns: Grad**2, Norm, Norm**2, Mean(Norm**2) ops """ ...
def get_user_brief(): """Retrieve brief for current user (if any).""" client = get_user_api() with catch_raise_api_exception(): data, _, headers = client.user_self_with_http_info() ratelimits.maybe_rate_limit(client, headers) return data.authenticated, data.slug, data.email, data.name
Retrieve brief for current user (if any).
Below is the the instruction that describes the task: ### Input: Retrieve brief for current user (if any). ### Response: def get_user_brief(): """Retrieve brief for current user (if any).""" client = get_user_api() with catch_raise_api_exception(): data, _, headers = client.user_self_with_http...
def remove_likely_non_central(self, candidates): # type: (List[str]) -> List[str] """ Stuff that is likely to be in find_packages(exclude...) :param candidates: :return: """ if len(candidates) > 1: for unlikely in [ "test", "te...
Stuff that is likely to be in find_packages(exclude...) :param candidates: :return:
Below is the the instruction that describes the task: ### Input: Stuff that is likely to be in find_packages(exclude...) :param candidates: :return: ### Response: def remove_likely_non_central(self, candidates): # type: (List[str]) -> List[str] """ Stuff that is likely to be in fin...
async def get_cred_infos_by_filter(self, filt: dict = None) -> str: """ Return cred-info (json list) from wallet by input filter for schema identifier and/or credential definition identifier components; return info of all credentials for no filter. Raise WalletState if the walle...
Return cred-info (json list) from wallet by input filter for schema identifier and/or credential definition identifier components; return info of all credentials for no filter. Raise WalletState if the wallet is closed. :param filt: indy-sdk filter for credentials; i.e., :: ...
Below is the the instruction that describes the task: ### Input: Return cred-info (json list) from wallet by input filter for schema identifier and/or credential definition identifier components; return info of all credentials for no filter. Raise WalletState if the wallet is closed. ...
def update_command(self, command, args=None): """ Updates the callback command which is called when the ButtonGroup changes. Setting to `None` stops the callback. :param callback command: The callback function to call. :param callback args: A li...
Updates the callback command which is called when the ButtonGroup changes. Setting to `None` stops the callback. :param callback command: The callback function to call. :param callback args: A list of arguments to pass to the widgets `command`, defaults to ...
Below is the the instruction that describes the task: ### Input: Updates the callback command which is called when the ButtonGroup changes. Setting to `None` stops the callback. :param callback command: The callback function to call. :param callback args: A...
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the RevokeResponsePayload object and decode it into its constituent parts. Args: istream (Stream): A data stream containing encoded object data, supporting a read meth...
Read the data encoding the RevokeResponsePayload object and decode it into its constituent parts. Args: istream (Stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enume...
Below is the the instruction that describes the task: ### Input: Read the data encoding the RevokeResponsePayload object and decode it into its constituent parts. Args: istream (Stream): A data stream containing encoded object data, supporting a read method; usually a Byt...
def pks(self): """Lazy-load the primary keys.""" if self._primary_keys is None: self._primary_keys = list( self.queryset.values_list('pk', flat=True)) return self._primary_keys
Lazy-load the primary keys.
Below is the the instruction that describes the task: ### Input: Lazy-load the primary keys. ### Response: def pks(self): """Lazy-load the primary keys.""" if self._primary_keys is None: self._primary_keys = list( self.queryset.values_list('pk', flat=True)) retur...
def is_entailed_by(self, other): """ Other is more specific than self. Other is bounded within self. """ other = self.coerce(other) to_i = self.to_i return to_i(other.low) >= to_i(self.low) and \ to_i(other.high) <= to_i(self.high)
Other is more specific than self. Other is bounded within self.
Below is the the instruction that describes the task: ### Input: Other is more specific than self. Other is bounded within self. ### Response: def is_entailed_by(self, other): """ Other is more specific than self. Other is bounded within self. """ other = self.coerce(other) ...
def run(self): """ Process all outgoing packets, until `stop()` is called. Intended to run in its own thread. """ while True: to_send = self._queue.get() if to_send is _SHUTDOWN: break # If we get a gateway object, connect to i...
Process all outgoing packets, until `stop()` is called. Intended to run in its own thread.
Below is the the instruction that describes the task: ### Input: Process all outgoing packets, until `stop()` is called. Intended to run in its own thread. ### Response: def run(self): """ Process all outgoing packets, until `stop()` is called. Intended to run in its own thread. ...