code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def html_to_rgb(html): """Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither...
Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither a known color name or a hex...
Below is the the instruction that describes the task: ### Input: Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: ...
def serializeContainers(self): """Serializes the current view of open video grids (i.e. the view) """ """ each serialized container looks like this: dic={# these are used when re-instantiating the view "classname" : self.__class__.__name__, "kwargs" : {}, # ...
Serializes the current view of open video grids (i.e. the view)
Below is the the instruction that describes the task: ### Input: Serializes the current view of open video grids (i.e. the view) ### Response: def serializeContainers(self): """Serializes the current view of open video grids (i.e. the view) """ """ each serialized container looks like this...
def get_empty_ids(self): """ Get documents id with missing targeted field """ cursor = self.get_collection().find( { '_id': {'$in': self._document_ids}, self._field: {'$exists': True} }, {'_id': True} ) ...
Get documents id with missing targeted field
Below is the the instruction that describes the task: ### Input: Get documents id with missing targeted field ### Response: def get_empty_ids(self): """ Get documents id with missing targeted field """ cursor = self.get_collection().find( { '_id': {'$in':...
def print_results_adj(results, indent=False, prt=sys.stdout): """Print GOEA results.""" # Print column headers if there are results to be printed if results: prt.write("{R}\n".format(R="\t".join(GOEnrichmentStudy.get_prtflds_default(results)))) # Print the GOEA results ...
Print GOEA results.
Below is the the instruction that describes the task: ### Input: Print GOEA results. ### Response: def print_results_adj(results, indent=False, prt=sys.stdout): """Print GOEA results.""" # Print column headers if there are results to be printed if results: prt.write("{R}\n".form...
def toggle_NV(self, pt): ''' If there is not currently a selected NV within self.settings[patch_size] of pt, adds it to the selected list. If there is, removes that point from the selected list. Args: pt: the point to add or remove from the selected list Poststate: u...
If there is not currently a selected NV within self.settings[patch_size] of pt, adds it to the selected list. If there is, removes that point from the selected list. Args: pt: the point to add or remove from the selected list Poststate: updates selected list
Below is the the instruction that describes the task: ### Input: If there is not currently a selected NV within self.settings[patch_size] of pt, adds it to the selected list. If there is, removes that point from the selected list. Args: pt: the point to add or remove from the selected li...
def QA_util_getBetweenQuarter(begin_date, end_date): """ #加上每季度的起始日期、结束日期 """ quarter_list = {} month_list = QA_util_getBetweenMonth(begin_date, end_date) for value in month_list: tempvalue = value.split("-") year = tempvalue[0] if tempvalue[1] in ['01', '02', '03']: ...
#加上每季度的起始日期、结束日期
Below is the the instruction that describes the task: ### Input: #加上每季度的起始日期、结束日期 ### Response: def QA_util_getBetweenQuarter(begin_date, end_date): """ #加上每季度的起始日期、结束日期 """ quarter_list = {} month_list = QA_util_getBetweenMonth(begin_date, end_date) for value in month_list: tempval...
def set_deployment_name(self): """Sets the deployment name from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_deployment_name') self.deployment_name = self.get_value('cons3rt.deployment.name') log.info('Found deployment name: {n}...
Sets the deployment name from deployment properties :return: None
Below is the the instruction that describes the task: ### Input: Sets the deployment name from deployment properties :return: None ### Response: def set_deployment_name(self): """Sets the deployment name from deployment properties :return: None """ log = logging.getLogger(...
def require_minimum_pandas_version(): """ Raise ImportError if minimum version of Pandas is not installed """ # TODO(HyukjinKwon): Relocate and deduplicate the version specification. minimum_pandas_version = "0.19.2" from distutils.version import LooseVersion try: import pandas ...
Raise ImportError if minimum version of Pandas is not installed
Below is the the instruction that describes the task: ### Input: Raise ImportError if minimum version of Pandas is not installed ### Response: def require_minimum_pandas_version(): """ Raise ImportError if minimum version of Pandas is not installed """ # TODO(HyukjinKwon): Relocate and deduplicate the ...
def makePlot(pdf=False, png=False): """ Plot relative parallax errors as a function of distance for stars of a given spectral type. Parameters ---------- args - command line arguments """ logdistancekpc = np.linspace(-1,np.log10(20.0),100) sptVabsAndVmini=OrderedDict([('K0V',(5.58,0.87)), ('G5V',(4.78...
Plot relative parallax errors as a function of distance for stars of a given spectral type. Parameters ---------- args - command line arguments
Below is the the instruction that describes the task: ### Input: Plot relative parallax errors as a function of distance for stars of a given spectral type. Parameters ---------- args - command line arguments ### Response: def makePlot(pdf=False, png=False): """ Plot relative parallax errors as a funct...
def sync_tunables(self, vault_client): """Synchtonizes any tunables we have set""" if not self.config: return a_prefix = self.tune_prefix if self.tune_prefix: a_prefix = "%s/" % self.tune_prefix v_path = "sys/mounts/%s%s/tune" % (a_prefix, self.path) ...
Synchtonizes any tunables we have set
Below is the the instruction that describes the task: ### Input: Synchtonizes any tunables we have set ### Response: def sync_tunables(self, vault_client): """Synchtonizes any tunables we have set""" if not self.config: return a_prefix = self.tune_prefix if self.tune_pr...
def calculate_statistics(self): "Jam some data through to generate statistics" rev_ids = range(0, 100, 1) feature_values = zip(rev_ids, [0] * 100) scores = [self.score(f) for f in feature_values] labels = [s['prediction'] for s in scores] statistics = Classification(label...
Jam some data through to generate statistics
Below is the the instruction that describes the task: ### Input: Jam some data through to generate statistics ### Response: def calculate_statistics(self): "Jam some data through to generate statistics" rev_ids = range(0, 100, 1) feature_values = zip(rev_ids, [0] * 100) scores = [se...
def extract_terms(self, nb): """Extract some term values, usually set with tags or metadata""" emt = ExtractMetatabTerms() emt.preprocess(nb, {}) return emt.terms
Extract some term values, usually set with tags or metadata
Below is the the instruction that describes the task: ### Input: Extract some term values, usually set with tags or metadata ### Response: def extract_terms(self, nb): """Extract some term values, usually set with tags or metadata""" emt = ExtractMetatabTerms() emt.preprocess(nb, {}) ...
def list_inputs(self): """Return a string listing all the Step's input names and their types. The types are returned in a copy/pastable format, so if the type is `string`, `'string'` (with single quotes) is returned. Returns: str containing all input names and types. ...
Return a string listing all the Step's input names and their types. The types are returned in a copy/pastable format, so if the type is `string`, `'string'` (with single quotes) is returned. Returns: str containing all input names and types.
Below is the the instruction that describes the task: ### Input: Return a string listing all the Step's input names and their types. The types are returned in a copy/pastable format, so if the type is `string`, `'string'` (with single quotes) is returned. Returns: str containin...
def set(self, keys): """ Set new keys. Mind this will clear all attributes and keys before adding new keys >>> doc = Doc(docnum='1') >>> doc.terms = Text(multi=True, attrs={'tf': Numeric(default=1)}) >>> doc.terms.add('copmputer', tf=12) >>> doc.terms.tf.values(...
Set new keys. Mind this will clear all attributes and keys before adding new keys >>> doc = Doc(docnum='1') >>> doc.terms = Text(multi=True, attrs={'tf': Numeric(default=1)}) >>> doc.terms.add('copmputer', tf=12) >>> doc.terms.tf.values() [12] >>> doc.te...
Below is the the instruction that describes the task: ### Input: Set new keys. Mind this will clear all attributes and keys before adding new keys >>> doc = Doc(docnum='1') >>> doc.terms = Text(multi=True, attrs={'tf': Numeric(default=1)}) >>> doc.terms.add('copmputer', tf=...
def compare_seqs_leven(seqs): """ calculate Levenshtein ratio of sequences """ A, B, ignore_gaps = seqs a, b = remove_gaps(A[1], B[1]) # actual sequences if len(a) != len(b): print('# reads are not the same length', file=sys.stderr) exit() pident = lr(a, b) * 100 return A...
calculate Levenshtein ratio of sequences
Below is the the instruction that describes the task: ### Input: calculate Levenshtein ratio of sequences ### Response: def compare_seqs_leven(seqs): """ calculate Levenshtein ratio of sequences """ A, B, ignore_gaps = seqs a, b = remove_gaps(A[1], B[1]) # actual sequences if len(a) != len(...
def frames(self, skip_registration=False): """Retrieve a new frame from the Kinect and convert it to a ColorImage, a DepthImage, and an IrImage. Parameters ---------- skip_registration : bool If True, the registration step is skipped. Returns -------...
Retrieve a new frame from the Kinect and convert it to a ColorImage, a DepthImage, and an IrImage. Parameters ---------- skip_registration : bool If True, the registration step is skipped. Returns ------- :obj:`tuple` of :obj:`ColorImage`, :obj:`Dept...
Below is the the instruction that describes the task: ### Input: Retrieve a new frame from the Kinect and convert it to a ColorImage, a DepthImage, and an IrImage. Parameters ---------- skip_registration : bool If True, the registration step is skipped. Returns ...
def salt_extend(extension, name, description, salt_dir, merge): ''' Quickstart for developing on the saltstack installation .. versionadded:: 2016.11.0 ''' import salt.utils.extend salt.utils.extend.run(extension=extension, name=name, descript...
Quickstart for developing on the saltstack installation .. versionadded:: 2016.11.0
Below is the the instruction that describes the task: ### Input: Quickstart for developing on the saltstack installation .. versionadded:: 2016.11.0 ### Response: def salt_extend(extension, name, description, salt_dir, merge): ''' Quickstart for developing on the saltstack installation .. version...
def parse_panel_app_gene(app_gene, hgnc_map): """Parse a panel app formated gene Args: app_gene(dict): Dict with panel app info hgnc_map(dict): Map from hgnc_symbol to hgnc_id Returns: gene_info(dict): Scout infromation """ gene_info = {} confidence_level = app_...
Parse a panel app formated gene Args: app_gene(dict): Dict with panel app info hgnc_map(dict): Map from hgnc_symbol to hgnc_id Returns: gene_info(dict): Scout infromation
Below is the the instruction that describes the task: ### Input: Parse a panel app formated gene Args: app_gene(dict): Dict with panel app info hgnc_map(dict): Map from hgnc_symbol to hgnc_id Returns: gene_info(dict): Scout infromation ### Response: def parse_panel_app_gen...
def comicDownloaded(self, comic, filename, text=None): """Write HTML entry for downloaded comic.""" if self.lastComic != comic.name: self.newComic(comic) size = None if self.allowdownscale: size = getDimensionForImage(filename, MaxImageSize) imageUrl = sel...
Write HTML entry for downloaded comic.
Below is the the instruction that describes the task: ### Input: Write HTML entry for downloaded comic. ### Response: def comicDownloaded(self, comic, filename, text=None): """Write HTML entry for downloaded comic.""" if self.lastComic != comic.name: self.newComic(comic) size = ...
def define_log_pre_format_hooks(self): """ adds a hook to send to websocket if the run command was selected """ hooks = super(Server, self).define_log_pre_format_hooks() # NOTE enabling logs only on debug mode if self.args.func == self.run and self.args.debug: ...
adds a hook to send to websocket if the run command was selected
Below is the the instruction that describes the task: ### Input: adds a hook to send to websocket if the run command was selected ### Response: def define_log_pre_format_hooks(self): """ adds a hook to send to websocket if the run command was selected """ hooks = super(Server, self)...
def install_config(self): """ install supervisor main config file """ text = templ_config.render(**self.options) config = Configuration(self.buildout, 'supervisord.conf', { 'deployment': self.deployment_name, 'text': text}) return [config.install()...
install supervisor main config file
Below is the the instruction that describes the task: ### Input: install supervisor main config file ### Response: def install_config(self): """ install supervisor main config file """ text = templ_config.render(**self.options) config = Configuration(self.buildout, 'supervis...
def console_type(self, console_type): """ Sets the console type for this node. :param console_type: console type (string) """ if console_type != self._console_type: # get a new port if the console type change self._manager.port_manager.release_tcp_port(s...
Sets the console type for this node. :param console_type: console type (string)
Below is the the instruction that describes the task: ### Input: Sets the console type for this node. :param console_type: console type (string) ### Response: def console_type(self, console_type): """ Sets the console type for this node. :param console_type: console type (string) ...
def get_setting(self, twig=None, **kwargs): """ Filter in the 'setting' context :parameter str twig: the twig used for filtering :parameter **kwargs: any other tags to do the filter (except tag or context) :return: :class:`phoebe.parameters.parameters.ParameterSet` ...
Filter in the 'setting' context :parameter str twig: the twig used for filtering :parameter **kwargs: any other tags to do the filter (except tag or context) :return: :class:`phoebe.parameters.parameters.ParameterSet`
Below is the the instruction that describes the task: ### Input: Filter in the 'setting' context :parameter str twig: the twig used for filtering :parameter **kwargs: any other tags to do the filter (except tag or context) :return: :class:`phoebe.parameters.parameters.ParameterS...
def fit(self, X, y, cost_mat, sample_weight=None): """Build a Bagging ensemble of estimators from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape = [n_samples, n_features] The training input samples. Sparse matrices are accepted only i...
Build a Bagging ensemble of estimators from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape = [n_samples, n_features] The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. ...
Below is the the instruction that describes the task: ### Input: Build a Bagging ensemble of estimators from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape = [n_samples, n_features] The training input samples. Sparse matrices are accepted...
def get(self): """ *get the check_coverage object* **Return:** - ``check_coverage`` """ self.log.info('starting the ``get`` method') match = self._query_sdss() self.log.info('completed the ``get`` method') return match
*get the check_coverage object* **Return:** - ``check_coverage``
Below is the the instruction that describes the task: ### Input: *get the check_coverage object* **Return:** - ``check_coverage`` ### Response: def get(self): """ *get the check_coverage object* **Return:** - ``check_coverage`` """ self.log....
def set_scanner_strength(zap_helper, scanners, strength): """Set the attack strength for scanners.""" if not scanners or 'all' in scanners: scanners = _get_all_scanner_ids(zap_helper) with zap_error_handler(): zap_helper.set_scanner_attack_strength(scanners, strength) console.info('Set...
Set the attack strength for scanners.
Below is the the instruction that describes the task: ### Input: Set the attack strength for scanners. ### Response: def set_scanner_strength(zap_helper, scanners, strength): """Set the attack strength for scanners.""" if not scanners or 'all' in scanners: scanners = _get_all_scanner_ids(zap_helper...
def get_tracking_id(self): """ Returns a dictionary of tracking-id key/value pairs. """ self.assert_open() tracking = self.handle[self.global_key +'tracking_id'].attrs.items() tracking = {key: _clean(value) for key, value in tracking} return tracking
Returns a dictionary of tracking-id key/value pairs.
Below is the the instruction that describes the task: ### Input: Returns a dictionary of tracking-id key/value pairs. ### Response: def get_tracking_id(self): """ Returns a dictionary of tracking-id key/value pairs. """ self.assert_open() tracking = self.handle[self.global_key +'tra...
def calculate_score(search_string, word): """Calculate how well the search string matches the word.""" # See the module docstring for a high level description # of what we're trying to do. # * If the search string is larger than the word, we know # immediately that this can't be a match. if le...
Calculate how well the search string matches the word.
Below is the the instruction that describes the task: ### Input: Calculate how well the search string matches the word. ### Response: def calculate_score(search_string, word): """Calculate how well the search string matches the word.""" # See the module docstring for a high level description # of what ...
def xml_parser(self, scode, *args): """ args[0]: xpath args[1]: text / html / xml """ allow_method = ('text', 'html', 'xml') xpath_string, method = args assert method in allow_method, 'method allow: %s' % allow_method result = self.ensure_list( ...
args[0]: xpath args[1]: text / html / xml
Below is the the instruction that describes the task: ### Input: args[0]: xpath args[1]: text / html / xml ### Response: def xml_parser(self, scode, *args): """ args[0]: xpath args[1]: text / html / xml """ allow_method = ('text', 'html', 'xml') xpath_strin...
def peel_around(method): """ This function will be deprecated. Removes one wrap around the method (given as a parameter) and returns the wrap. If the method is not wrapped, returns None. """ _permission_to_touch_wraps.acquire() # released in finally part try: if hasattr(method,'__as...
This function will be deprecated. Removes one wrap around the method (given as a parameter) and returns the wrap. If the method is not wrapped, returns None.
Below is the the instruction that describes the task: ### Input: This function will be deprecated. Removes one wrap around the method (given as a parameter) and returns the wrap. If the method is not wrapped, returns None. ### Response: def peel_around(method): """ This function will be deprecated...
def filter_genes_dispersion(result, log=False, show=None, save=None): """Plot dispersions versus means for genes. Produces Supp. Fig. 5c of Zheng et al. (2017) and MeanVarPlot() of Seurat. Parameters ---------- result : `np.recarray` Result of :func:`~scanpy.api.pp.filter_genes_dispersion`...
Plot dispersions versus means for genes. Produces Supp. Fig. 5c of Zheng et al. (2017) and MeanVarPlot() of Seurat. Parameters ---------- result : `np.recarray` Result of :func:`~scanpy.api.pp.filter_genes_dispersion`. log : `bool` Plot on logarithmic axes. show : bool, optiona...
Below is the the instruction that describes the task: ### Input: Plot dispersions versus means for genes. Produces Supp. Fig. 5c of Zheng et al. (2017) and MeanVarPlot() of Seurat. Parameters ---------- result : `np.recarray` Result of :func:`~scanpy.api.pp.filter_genes_dispersion`. lo...
def check_dimensions(self, dataset): ''' Checks that the feature types of this dataset are consitent with a time series incomplete dataset :param netCDF4.Dataset dataset: An open netCDF dataset ''' required_ctx = TestCtx(BaseCheck.HIGH, 'All geophysical variables are time-series...
Checks that the feature types of this dataset are consitent with a time series incomplete dataset :param netCDF4.Dataset dataset: An open netCDF dataset
Below is the the instruction that describes the task: ### Input: Checks that the feature types of this dataset are consitent with a time series incomplete dataset :param netCDF4.Dataset dataset: An open netCDF dataset ### Response: def check_dimensions(self, dataset): ''' Checks that the f...
def init_login(self, from_local=False): """Display login screen. May ask for local data loading if from_local is True.""" if self.toolbar: self.removeToolBar(self.toolbar) widget_login = login.Loading(self.statusBar(), self.theory_main) self.centralWidget().addWidget(widget_l...
Display login screen. May ask for local data loading if from_local is True.
Below is the the instruction that describes the task: ### Input: Display login screen. May ask for local data loading if from_local is True. ### Response: def init_login(self, from_local=False): """Display login screen. May ask for local data loading if from_local is True.""" if self.toolbar: ...
def movingMax(requestContext, seriesList, windowSize): """ Graphs the moving maximum of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' ...
Graphs the moving maximum of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' or '5min' (See ``from / until`` in the render\_api_ for example...
Below is the the instruction that describes the task: ### Input: Graphs the moving maximum of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour...
def encode_simple(d): """Encode strings in basic python objects.""" if isinstance(d, unicode): return d.encode() if isinstance(d, list): return list(map(encode_simple, d)) if isinstance(d, dict): return dict([(encode_simple(k), encode_simple(v)) for k, v in d.items()]) return...
Encode strings in basic python objects.
Below is the the instruction that describes the task: ### Input: Encode strings in basic python objects. ### Response: def encode_simple(d): """Encode strings in basic python objects.""" if isinstance(d, unicode): return d.encode() if isinstance(d, list): return list(map(encode_simple, ...
def decrypt_file(self, filename): ''' Decrypt File Args: filename: Pass the filename to encrypt. Returns: No return. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return ...
Decrypt File Args: filename: Pass the filename to encrypt. Returns: No return.
Below is the the instruction that describes the task: ### Input: Decrypt File Args: filename: Pass the filename to encrypt. Returns: No return. ### Response: def decrypt_file(self, filename): ''' Decrypt File Args: filename: Pass the filen...
def main(): """ Command line interface. """ parser = argparse.ArgumentParser( description='monoseq: pretty-printing DNA and protein sequences', epilog='If INPUT is in FASTA format, each record is pretty-printed ' 'after printing its name and ANNOTATION (if supplied) is used by ' ...
Command line interface.
Below is the the instruction that describes the task: ### Input: Command line interface. ### Response: def main(): """ Command line interface. """ parser = argparse.ArgumentParser( description='monoseq: pretty-printing DNA and protein sequences', epilog='If INPUT is in FASTA format,...
def __flushLevel(self, level): """Merge the found objects to the required level""" objectsCount = len(self.objectsStack) while objectsCount > level: lastIndex = objectsCount - 1 if lastIndex == 0: # We have exactly one element in the stack ...
Merge the found objects to the required level
Below is the the instruction that describes the task: ### Input: Merge the found objects to the required level ### Response: def __flushLevel(self, level): """Merge the found objects to the required level""" objectsCount = len(self.objectsStack) while objectsCount > level: last...
def sort_list(items): """Sort a simple list by number of words and length.""" # Track by number of words. track = {} def by_length(word1, word2): return len(word2) - len(word1) # Loop through each item. for item in items: # Count the words. cword = utils.word_count(ite...
Sort a simple list by number of words and length.
Below is the the instruction that describes the task: ### Input: Sort a simple list by number of words and length. ### Response: def sort_list(items): """Sort a simple list by number of words and length.""" # Track by number of words. track = {} def by_length(word1, word2): return len(wor...
def get_embedded_config(filename): """ Attempt to load config data attached to file """ def check_option(self, section, name): return (self.has_section(section) and (self.has_option(section, name) or (name in self.defaults()))) try: cp = pycbc.results.load_metadata_from_f...
Attempt to load config data attached to file
Below is the the instruction that describes the task: ### Input: Attempt to load config data attached to file ### Response: def get_embedded_config(filename): """ Attempt to load config data attached to file """ def check_option(self, section, name): return (self.has_section(section) and ...
def _get_model_fields(self, field_names, declared_fields, extra_kwargs): """ Returns all the model fields that are being mapped to by fields on the serializer class. Returned as a dict of 'model field name' -> 'model field'. Used internally by `get_uniqueness_field_options`. ...
Returns all the model fields that are being mapped to by fields on the serializer class. Returned as a dict of 'model field name' -> 'model field'. Used internally by `get_uniqueness_field_options`.
Below is the the instruction that describes the task: ### Input: Returns all the model fields that are being mapped to by fields on the serializer class. Returned as a dict of 'model field name' -> 'model field'. Used internally by `get_uniqueness_field_options`. ### Response: def _get_mode...
def update_group(self, group_name, new_group_name=None, new_path=None): """ Updates name and/or path of the specified group. :type group_name: string :param group_name: The name of the new group :type new_group_name: string :param new_group_name: If provided, the name o...
Updates name and/or path of the specified group. :type group_name: string :param group_name: The name of the new group :type new_group_name: string :param new_group_name: If provided, the name of the group will be changed to this name. :type new_...
Below is the the instruction that describes the task: ### Input: Updates name and/or path of the specified group. :type group_name: string :param group_name: The name of the new group :type new_group_name: string :param new_group_name: If provided, the name of the group will be ...
def load_pyassimp(file_obj, file_type=None, resolver=None, **kwargs): """ Use the pyassimp library to load a mesh from a file object and type or file name if file_obj is a string Parameters --------- file_obj: str, or file object File ...
Use the pyassimp library to load a mesh from a file object and type or file name if file_obj is a string Parameters --------- file_obj: str, or file object File path or object containing mesh data file_type : str File extension, aka 'stl' resolver : trimesh.visual.resolvers.Resolver...
Below is the the instruction that describes the task: ### Input: Use the pyassimp library to load a mesh from a file object and type or file name if file_obj is a string Parameters --------- file_obj: str, or file object File path or object containing mesh data file_type : str File ...
def sendWebmention(sourceURL, targetURL, webmention=None, test_urls=True, vouchDomain=None, headers={}, timeout=None, debug=False): """Send to the :targetURL: a WebMention for the :sourceURL: The WebMention will be discovered if not given in the :webmention: parameter. :param source...
Send to the :targetURL: a WebMention for the :sourceURL: The WebMention will be discovered if not given in the :webmention: parameter. :param sourceURL: URL that is referencing :targetURL: :param targetURL: URL of mentioned post :param webmention: optional WebMention endpoint :param test_urls:...
Below is the the instruction that describes the task: ### Input: Send to the :targetURL: a WebMention for the :sourceURL: The WebMention will be discovered if not given in the :webmention: parameter. :param sourceURL: URL that is referencing :targetURL: :param targetURL: URL of mentioned post ...
def expected_number_of_purchases_up_to_time(self, t): """ Return expected number of repeat purchases up to time t. Calculate the expected number of repeat purchases up to time t for a randomly choose individual from the population. Parameters ---------- t: array...
Return expected number of repeat purchases up to time t. Calculate the expected number of repeat purchases up to time t for a randomly choose individual from the population. Parameters ---------- t: array_like times to calculate the expectation for. Returns...
Below is the the instruction that describes the task: ### Input: Return expected number of repeat purchases up to time t. Calculate the expected number of repeat purchases up to time t for a randomly choose individual from the population. Parameters ---------- t: array_like...
def get_db_uri(config, output_dir): """Process results_database parameters in config to format them for set database function :param dict config: project configuration dict :param str output_dir: output directory for results :return: string for db uri """ db_config = config.get("results_dat...
Process results_database parameters in config to format them for set database function :param dict config: project configuration dict :param str output_dir: output directory for results :return: string for db uri
Below is the the instruction that describes the task: ### Input: Process results_database parameters in config to format them for set database function :param dict config: project configuration dict :param str output_dir: output directory for results :return: string for db uri ### Response: def ge...
def get_slice(self, key, column_parent, predicate, consistency_level): """ Get the group of columns contained by column_parent (either a ColumnFamily name or a ColumnFamily/SuperColumn name pair) specified by the given SlicePredicate. If no matching values are found, an empty list is returned. Paramete...
Get the group of columns contained by column_parent (either a ColumnFamily name or a ColumnFamily/SuperColumn name pair) specified by the given SlicePredicate. If no matching values are found, an empty list is returned. Parameters: - key - column_parent - predicate - consistency_level
Below is the the instruction that describes the task: ### Input: Get the group of columns contained by column_parent (either a ColumnFamily name or a ColumnFamily/SuperColumn name pair) specified by the given SlicePredicate. If no matching values are found, an empty list is returned. Parameters: - key...
def py_syntax_highlight(self, s): """ :param str s: :rtype: str """ if not self.enable: return s state = 0 spaces = " \t\n" ops = ".,;:+-*/%&!=|(){}[]^<>" i = 0 cur_token = "" color_args = {0: {}, len(s): {}} # type: ty...
:param str s: :rtype: str
Below is the the instruction that describes the task: ### Input: :param str s: :rtype: str ### Response: def py_syntax_highlight(self, s): """ :param str s: :rtype: str """ if not self.enable: return s state = 0 spaces = " \t\n" op...
def recover(self, data, redis=None): ''' Retrieve this field's value from the database ''' value = data.get(self.name) if value is None or value == 'None': return None return str(value)
Retrieve this field's value from the database
Below is the the instruction that describes the task: ### Input: Retrieve this field's value from the database ### Response: def recover(self, data, redis=None): ''' Retrieve this field's value from the database ''' value = data.get(self.name) if value is None or value == 'None': ...
def _markdownify(tag, _listType=None, _blockQuote=False, _listIndex=1): """recursively converts a tag into markdown""" children = tag.find_all(recursive=False) if tag.name == '[document]': for child in children: _markdownify(child) return if tag.name not in _supportedTags or not _supportedAttrs(tag): if ...
recursively converts a tag into markdown
Below is the the instruction that describes the task: ### Input: recursively converts a tag into markdown ### Response: def _markdownify(tag, _listType=None, _blockQuote=False, _listIndex=1): """recursively converts a tag into markdown""" children = tag.find_all(recursive=False) if tag.name == '[document]': ...
def exec_file(self, path): """execute the lines in the local file 'path'""" filename = os.path.basename(path) log.info('Execute %s', filename) content = from_file(path).replace('\r', '').split('\n') res = '> ' for line in content: line = line.rstrip('\n') ...
execute the lines in the local file 'path
Below is the the instruction that describes the task: ### Input: execute the lines in the local file 'path ### Response: def exec_file(self, path): """execute the lines in the local file 'path'""" filename = os.path.basename(path) log.info('Execute %s', filename) content = from_fil...
def sendPkt(self, pkt, retry=5, sleep_time=0.01): """ Sends a packet and waits for a return. If no return is given, then it resends the packet. If an error occurs, it also resends the packet. in: pkt - command packet to send to servo cnt - how many retries should this do? default = 5 out: array of p...
Sends a packet and waits for a return. If no return is given, then it resends the packet. If an error occurs, it also resends the packet. in: pkt - command packet to send to servo cnt - how many retries should this do? default = 5 out: array of packets
Below is the the instruction that describes the task: ### Input: Sends a packet and waits for a return. If no return is given, then it resends the packet. If an error occurs, it also resends the packet. in: pkt - command packet to send to servo cnt - how many retries should this do? default = 5 out: ...
def find(self, group=None, element=None, name=None, VR=None): """ Searches for data elements in the DICOM file given the filters supplied to this method. :param group: Hex decimal for the group of a DICOM element e.g. 0x002 :param element: Hex decimal for the element value of a DICOM el...
Searches for data elements in the DICOM file given the filters supplied to this method. :param group: Hex decimal for the group of a DICOM element e.g. 0x002 :param element: Hex decimal for the element value of a DICOM element e.g. 0x0010 :param name: Name of the DICOM element, e.g. "Mo...
Below is the the instruction that describes the task: ### Input: Searches for data elements in the DICOM file given the filters supplied to this method. :param group: Hex decimal for the group of a DICOM element e.g. 0x002 :param element: Hex decimal for the element value of a DICOM element...
def get_version_list(path=None, module=None): """Return the version information as a tuple. This uses get_version and breaks the string up. Would make more sense if the version was a tuple throughout katversion. """ major = 0 minor = 0 patch = '' # PEP440 calls this prerelease, postreleas...
Return the version information as a tuple. This uses get_version and breaks the string up. Would make more sense if the version was a tuple throughout katversion.
Below is the the instruction that describes the task: ### Input: Return the version information as a tuple. This uses get_version and breaks the string up. Would make more sense if the version was a tuple throughout katversion. ### Response: def get_version_list(path=None, module=None): """Return the ...
def _get_file(self, share_name, directory_name, file_name, start_range=None, end_range=None, validate_content=False, timeout=None, _context=None): ''' Downloads a file's content, metadata, and properties. You can specify a range if you don't need to download th...
Downloads a file's content, metadata, and properties. You can specify a range if you don't need to download the file in its entirety. If no range is specified, the full file will be downloaded. See get_file_to_* for high level functions that handle the download of large files with autom...
Below is the the instruction that describes the task: ### Input: Downloads a file's content, metadata, and properties. You can specify a range if you don't need to download the file in its entirety. If no range is specified, the full file will be downloaded. See get_file_to_* for high level...
def memoize(f): """A simple memoize decorator for functions.""" cache= {} def memf(*x): if x not in cache: cache[x] = f(*x) return cache[x] return memf
A simple memoize decorator for functions.
Below is the the instruction that describes the task: ### Input: A simple memoize decorator for functions. ### Response: def memoize(f): """A simple memoize decorator for functions.""" cache= {} def memf(*x): if x not in cache: cache[x] = f(*x) return cache[x] return mem...
def setCheckedDetails(self, checked): """Sets which components are checked :param checked: dictionary of stimtype:list<attribute names> for which components and their attributes should be checked :type checked: dict """ layout = self.layout() for i in range(layout.count(...
Sets which components are checked :param checked: dictionary of stimtype:list<attribute names> for which components and their attributes should be checked :type checked: dict
Below is the the instruction that describes the task: ### Input: Sets which components are checked :param checked: dictionary of stimtype:list<attribute names> for which components and their attributes should be checked :type checked: dict ### Response: def setCheckedDetails(self, checked): ...
def secpolicy_sa_secpolicy_defined_policy_policies_member_entry_member(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") secpolicy_sa = ET.SubElement(config, "secpolicy-sa", xmlns="urn:brocade.com:mgmt:brocade-fc-auth") secpolicy = ET.SubElement(secpolicy_...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def secpolicy_sa_secpolicy_defined_policy_policies_member_entry_member(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") secpolicy_sa = ET.SubElement(config, "s...
def create_was_invalidated_by_relation(self, activity_id, entity_kind, entity_id): """ Create a was invalidated by relationship between an activity and a entity(file). :param activity_id: str: uuid of the activity :param entity_kind: str: kind of entity('dds-file') :param entity_...
Create a was invalidated by relationship between an activity and a entity(file). :param activity_id: str: uuid of the activity :param entity_kind: str: kind of entity('dds-file') :param entity_id: str: uuid of the entity :return: requests.Response containing the successful result
Below is the the instruction that describes the task: ### Input: Create a was invalidated by relationship between an activity and a entity(file). :param activity_id: str: uuid of the activity :param entity_kind: str: kind of entity('dds-file') :param entity_id: str: uuid of the entity ...
def read_sql(cls, sql, con, index_col=None, **kwargs): """Reads a SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name. con: SQLAlchemy connectable (engine/connect...
Reads a SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name. con: SQLAlchemy connectable (engine/connection) or database string URI or DBAPI2 connection (...
Below is the the instruction that describes the task: ### Input: Reads a SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name. con: SQLAlchemy connectable (engine/conn...
def get_compositions_by_query(self, composition_query): """Gets a list of ``Compositions`` matching the given composition query. arg: composition_query (osid.repository.CompositionQuery): the composition query return: (osid.repository.CompositionList) - the returned ...
Gets a list of ``Compositions`` matching the given composition query. arg: composition_query (osid.repository.CompositionQuery): the composition query return: (osid.repository.CompositionList) - the returned ``CompositionList`` raise: NullArgument - ``composi...
Below is the the instruction that describes the task: ### Input: Gets a list of ``Compositions`` matching the given composition query. arg: composition_query (osid.repository.CompositionQuery): the composition query return: (osid.repository.CompositionList) - the returned ...
def generate_templates(self, exercise_questions=False): """ Create empty .csv files with the right headers and place them in the Will place files as siblings of directory `channeldir`. """ self.generate_template(channeldir=self.channeldir, filename=...
Create empty .csv files with the right headers and place them in the Will place files as siblings of directory `channeldir`.
Below is the the instruction that describes the task: ### Input: Create empty .csv files with the right headers and place them in the Will place files as siblings of directory `channeldir`. ### Response: def generate_templates(self, exercise_questions=False): """ Create empty .csv files wit...
def bind(self, callback: typing.Union[typing.Callable, AbstractFilter], validator: typing.Optional[typing.Callable] = None, event_handlers: typing.Optional[typing.List[Handler]] = None, exclude_event_handlers: typing.Optional[typing.Iterable[Handler]] = None): """ ...
Register filter :param callback: callable or subclass of :obj:`AbstractFilter` :param validator: custom validator. :param event_handlers: list of instances of :obj:`Handler` :param exclude_event_handlers: list of excluded event handlers (:obj:`Handler`)
Below is the the instruction that describes the task: ### Input: Register filter :param callback: callable or subclass of :obj:`AbstractFilter` :param validator: custom validator. :param event_handlers: list of instances of :obj:`Handler` :param exclude_event_handlers: list of exclu...
def add_subrule(self, subrule, weight): """Add subrule to the rule. :param subrule: Subrule to add to this rule, an instance of :class:`Rule` or :class:`RuleLeaf`. :param float weight: Weight of the subrule """ if not issubclass(subrule.__class__, (Rule,...
Add subrule to the rule. :param subrule: Subrule to add to this rule, an instance of :class:`Rule` or :class:`RuleLeaf`. :param float weight: Weight of the subrule
Below is the the instruction that describes the task: ### Input: Add subrule to the rule. :param subrule: Subrule to add to this rule, an instance of :class:`Rule` or :class:`RuleLeaf`. :param float weight: Weight of the subrule ### Response: def add_subrule(self, subrule,...
def register(self, bucket, name_or_func, func=None): """ Add a function to the registry by name """ assert bucket in self, 'Bucket %s is unknown' % bucket if func is None and hasattr(name_or_func, '__name__'): name = name_or_func.__name__ func = name_or_fu...
Add a function to the registry by name
Below is the the instruction that describes the task: ### Input: Add a function to the registry by name ### Response: def register(self, bucket, name_or_func, func=None): """ Add a function to the registry by name """ assert bucket in self, 'Bucket %s is unknown' % bucket if...
def clean_key(self): """ Validate the key contains an email address. """ key = self.cleaned_data["key"] gpg = get_gpg() result = gpg.import_keys(key) if result.count == 0: raise forms.ValidationError(_("Invalid Key")) return key
Validate the key contains an email address.
Below is the the instruction that describes the task: ### Input: Validate the key contains an email address. ### Response: def clean_key(self): """ Validate the key contains an email address. """ key = self.cleaned_data["key"] gpg = get_gpg() result = gpg.import_keys...
def watch_variable(self, tid, address, size, action = None): """ Sets a hardware breakpoint at the given thread, address and size. @see: L{dont_watch_variable} @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of v...
Sets a hardware breakpoint at the given thread, address and size. @see: L{dont_watch_variable} @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of variable to watch. @type size: int @param size: Size of variable...
Below is the the instruction that describes the task: ### Input: Sets a hardware breakpoint at the given thread, address and size. @see: L{dont_watch_variable} @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of variable to w...
def set_metric_ids(self, key, metric_ids): """ Store the list of metric IDs we will want to collect for the given instance key """ with self._lock: self._metric_ids[key] = metric_ids
Store the list of metric IDs we will want to collect for the given instance key
Below is the the instruction that describes the task: ### Input: Store the list of metric IDs we will want to collect for the given instance key ### Response: def set_metric_ids(self, key, metric_ids): """ Store the list of metric IDs we will want to collect for the given instance key """ ...
def to_internal_value(self, data): """ Validate that the input is a decimal number and return a Decimal instance. """ data = smart_text(data).strip() if len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: value = decima...
Validate that the input is a decimal number and return a Decimal instance.
Below is the the instruction that describes the task: ### Input: Validate that the input is a decimal number and return a Decimal instance. ### Response: def to_internal_value(self, data): """ Validate that the input is a decimal number and return a Decimal instance. """ ...
def set_limit(self, identifier, expires_at, blocking=False): """ Set a new global trigger or response limit :param identifier: The Trigger or Response object :type identifier: parser.trigger.Trigger or parser.trigger.response.Response :param expires_at: The limit expiration as ...
Set a new global trigger or response limit :param identifier: The Trigger or Response object :type identifier: parser.trigger.Trigger or parser.trigger.response.Response :param expires_at: The limit expiration as a Unix timestamp :type expires_at: float :param blocking: When ...
Below is the the instruction that describes the task: ### Input: Set a new global trigger or response limit :param identifier: The Trigger or Response object :type identifier: parser.trigger.Trigger or parser.trigger.response.Response :param expires_at: The limit expiration as a Unix times...
def evaluate_inline(self, groups): """Evaluate inline comments on their own lines.""" # Consecutive lines with only comments with same leading whitespace # will be captured as a single block. if self.lines: if ( self.group_comments and self.li...
Evaluate inline comments on their own lines.
Below is the the instruction that describes the task: ### Input: Evaluate inline comments on their own lines. ### Response: def evaluate_inline(self, groups): """Evaluate inline comments on their own lines.""" # Consecutive lines with only comments with same leading whitespace # will be ca...
def polar_fft(im, nangle=None, radiimax=None, *, isshiftdft=False, truesize=None, logpolar=False, logoutput=False, interpolation='bilinear'): """Return dft in polar (or log-polar) units, the angle step (and the log base) Parameters ---------- im: 2d array The ima...
Return dft in polar (or log-polar) units, the angle step (and the log base) Parameters ---------- im: 2d array The image nangle: number, optional The number of angles in the polar representation radiimax: number, optional The number of radius in the polar representation ...
Below is the the instruction that describes the task: ### Input: Return dft in polar (or log-polar) units, the angle step (and the log base) Parameters ---------- im: 2d array The image nangle: number, optional The number of angles in the polar representation radiimax: numbe...
def unbuffered_write(self, buf): """Performs an unbuffered write, the default unless socket.send does not send everything, in which case an unbuffered write is done and the write method is set to be a buffered write until the buffer is empty once again. buf -- bytes to send ...
Performs an unbuffered write, the default unless socket.send does not send everything, in which case an unbuffered write is done and the write method is set to be a buffered write until the buffer is empty once again. buf -- bytes to send
Below is the the instruction that describes the task: ### Input: Performs an unbuffered write, the default unless socket.send does not send everything, in which case an unbuffered write is done and the write method is set to be a buffered write until the buffer is empty once again. ...
def optional_args_func(func) -> callable: """ Given a function or generator `func`, return a function/generator that takes any number of kwargs and calls `func` with only the args/kwargs that `func` expects. """ if getattr(func, '_optional_args_func', False): return func is_generato...
Given a function or generator `func`, return a function/generator that takes any number of kwargs and calls `func` with only the args/kwargs that `func` expects.
Below is the the instruction that describes the task: ### Input: Given a function or generator `func`, return a function/generator that takes any number of kwargs and calls `func` with only the args/kwargs that `func` expects. ### Response: def optional_args_func(func) -> callable: """ Given a func...
def status(self): '''returns rates''' counts = {} for bucket in self.buckets: for x in bucket: if not x in counts: counts[x] = 0 counts[x] += bucket[x] ret = "" mtypes = counts.keys() mtypes.sort() f...
returns rates
Below is the the instruction that describes the task: ### Input: returns rates ### Response: def status(self): '''returns rates''' counts = {} for bucket in self.buckets: for x in bucket: if not x in counts: counts[x] = 0 count...
def memory_error(): """Display an error when there is not enough memory.""" warning_heading = m.Heading( tr('Memory issue'), **WARNING_STYLE) warning_message = tr( 'There is not enough free memory to run this analysis.') suggestion_heading = m.Heading( tr('Suggestion'), **SUGGEST...
Display an error when there is not enough memory.
Below is the the instruction that describes the task: ### Input: Display an error when there is not enough memory. ### Response: def memory_error(): """Display an error when there is not enough memory.""" warning_heading = m.Heading( tr('Memory issue'), **WARNING_STYLE) warning_message = tr( ...
def update_sql(table, filter, updates): ''' >>> update_sql('tbl', {'foo': 'a', 'bar': 1}, {'bar': 2, 'baz': 'b'}) ('UPDATE tbl SET bar=$1, baz=$2 WHERE bar=$3 AND foo=$4', [2, 'b', 1, 'a']) ''' where_keys, where_vals = _split_dict(filter) up_keys, up_vals = _split_dict(updates) changes = _pa...
>>> update_sql('tbl', {'foo': 'a', 'bar': 1}, {'bar': 2, 'baz': 'b'}) ('UPDATE tbl SET bar=$1, baz=$2 WHERE bar=$3 AND foo=$4', [2, 'b', 1, 'a'])
Below is the the instruction that describes the task: ### Input: >>> update_sql('tbl', {'foo': 'a', 'bar': 1}, {'bar': 2, 'baz': 'b'}) ('UPDATE tbl SET bar=$1, baz=$2 WHERE bar=$3 AND foo=$4', [2, 'b', 1, 'a']) ### Response: def update_sql(table, filter, updates): ''' >>> update_sql('tbl', {'foo': 'a',...
def get_real_time_locate(ipAddress, auth, url): """ function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. Note: Although intended to return a single location, Multiple locations may be returned for a sing...
function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. Note: Although intended to return a single location, Multiple locations may be returned for a single host due to a partially discovered network or misconfigur...
Below is the the instruction that describes the task: ### Input: function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. Note: Although intended to return a single location, Multiple locations may be returned f...
def dim_global_size_dict(self): """ Returns a mapping of dimension name to global size """ return { d.name: d.global_size for d in self._dims.itervalues()}
Returns a mapping of dimension name to global size
Below is the the instruction that describes the task: ### Input: Returns a mapping of dimension name to global size ### Response: def dim_global_size_dict(self): """ Returns a mapping of dimension name to global size """ return { d.name: d.global_size for d in self._dims.itervalues()}
def rebuild( self ): """ Clears out all the child widgets from this widget and creates the widget that best matches the column properties for this edit. """ plugins.init() self.blockSignals(True) self.setUpdatesEnabled(False) #...
Clears out all the child widgets from this widget and creates the widget that best matches the column properties for this edit.
Below is the the instruction that describes the task: ### Input: Clears out all the child widgets from this widget and creates the widget that best matches the column properties for this edit. ### Response: def rebuild( self ): """ Clears out all the child widgets from this widget and c...
def merge(*series): """ Merge Series and/or DataFrames together. Returns a DataFrame. """ dfs = [] for s in series: if isinstance(s, pd.DataFrame): dfs.append(s) elif isinstance(s, pd.Series): tmpdf = pd.DataFrame({s.name: s}) dfs.append(tmpdf...
Merge Series and/or DataFrames together. Returns a DataFrame.
Below is the the instruction that describes the task: ### Input: Merge Series and/or DataFrames together. Returns a DataFrame. ### Response: def merge(*series): """ Merge Series and/or DataFrames together. Returns a DataFrame. """ dfs = [] for s in series: if isinstance(s, pd....
def is_tRNA(clus_obj, out_dir, args): """ Iterates through cluster precursors to predict sRNA types """ ref = os.path.abspath(args.reference) utils.safe_dirs(out_dir) for nc in clus_obj[0]: c = clus_obj[0][nc] loci = c['loci'] out_fa = "cluster_" + nc if loci[0][3...
Iterates through cluster precursors to predict sRNA types
Below is the the instruction that describes the task: ### Input: Iterates through cluster precursors to predict sRNA types ### Response: def is_tRNA(clus_obj, out_dir, args): """ Iterates through cluster precursors to predict sRNA types """ ref = os.path.abspath(args.reference) utils.safe_dirs(...
def handle_unexpected_exception(max_traceback_levels=100): """Suppress stack traces for common errors and provide hints for how to resolve them.""" exc_type, exc_msgs = sys.exc_info()[:2] if exc_type.__name__ == "SSLError": d1_cli.impl.util.print_error( """HTTPS / TLS / SSL / X.509v3...
Suppress stack traces for common errors and provide hints for how to resolve them.
Below is the the instruction that describes the task: ### Input: Suppress stack traces for common errors and provide hints for how to resolve them. ### Response: def handle_unexpected_exception(max_traceback_levels=100): """Suppress stack traces for common errors and provide hints for how to resolve th...
def to_JSON(self): """Dumps object fields into a JSON formatted string :returns: the JSON string """ return json.dumps({'id': self.id, 'external_id': self.external_id, 'name': self.name, 'created_at': time...
Dumps object fields into a JSON formatted string :returns: the JSON string
Below is the the instruction that describes the task: ### Input: Dumps object fields into a JSON formatted string :returns: the JSON string ### Response: def to_JSON(self): """Dumps object fields into a JSON formatted string :returns: the JSON string """ return json.dumps...
def get_list(self, list_id): """GetList. [Preview API] Returns a picklist. :param str list_id: The ID of the list :rtype: :class:`<PickList> <azure.devops.v5_0.work_item_tracking_process.models.PickList>` """ route_values = {} if list_id is not None: r...
GetList. [Preview API] Returns a picklist. :param str list_id: The ID of the list :rtype: :class:`<PickList> <azure.devops.v5_0.work_item_tracking_process.models.PickList>`
Below is the the instruction that describes the task: ### Input: GetList. [Preview API] Returns a picklist. :param str list_id: The ID of the list :rtype: :class:`<PickList> <azure.devops.v5_0.work_item_tracking_process.models.PickList>` ### Response: def get_list(self, list_id): ""...
def load_file(file_path, credentials=None): """Load a file from either local or gcs. Args: file_path: The target file path, which should have the prefix 'gs://' if to be loaded from gcs. credentials: Optional credential to be used to load the file from gcs. Returns: A python File obje...
Load a file from either local or gcs. Args: file_path: The target file path, which should have the prefix 'gs://' if to be loaded from gcs. credentials: Optional credential to be used to load the file from gcs. Returns: A python File object if loading file from local or a StringIO objec...
Below is the the instruction that describes the task: ### Input: Load a file from either local or gcs. Args: file_path: The target file path, which should have the prefix 'gs://' if to be loaded from gcs. credentials: Optional credential to be used to load the file from gcs. Returns: ...
def arrays_split(mask:NPArrayMask, *arrs:NPArrayableList)->SplitArrayList: "Given `arrs` is [a,b,...] and `mask`index - return[(a[mask],a[~mask]),(b[mask],b[~mask]),...]." assert all([len(arr)==len(arrs[0]) for arr in arrs]), 'All arrays should have same length' mask = array(mask) return list(zip(*[(a[m...
Given `arrs` is [a,b,...] and `mask`index - return[(a[mask],a[~mask]),(b[mask],b[~mask]),...].
Below is the the instruction that describes the task: ### Input: Given `arrs` is [a,b,...] and `mask`index - return[(a[mask],a[~mask]),(b[mask],b[~mask]),...]. ### Response: def arrays_split(mask:NPArrayMask, *arrs:NPArrayableList)->SplitArrayList: "Given `arrs` is [a,b,...] and `mask`index - return[(a[mask],a...
def ParseAccountInformation( self, parser_mediator, query, row, **unused_kwargs): """Parses account information. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. ...
Parses account information. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row with account information.
Below is the the instruction that describes the task: ### Input: Parses account information. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row...
def get_symbol_info(self, symbol): """Return information about a symbol :param symbol: required e.g BNBBTC :type symbol: str :returns: Dict if found, None if not .. code-block:: python { "symbol": "ETHBTC", "status": "TRADING", ...
Return information about a symbol :param symbol: required e.g BNBBTC :type symbol: str :returns: Dict if found, None if not .. code-block:: python { "symbol": "ETHBTC", "status": "TRADING", "baseAsset": "ETH", ...
Below is the the instruction that describes the task: ### Input: Return information about a symbol :param symbol: required e.g BNBBTC :type symbol: str :returns: Dict if found, None if not .. code-block:: python { "symbol": "ETHBTC", "s...
def to_sparse(self, format='csr', **kwargs): """Convert into a sparse matrix. Parameters ---------- format : {'coo', 'csc', 'csr', 'dia', 'dok', 'lil'} Sparse matrix format. kwargs : keyword arguments Passed through to sparse matrix constructor. ...
Convert into a sparse matrix. Parameters ---------- format : {'coo', 'csc', 'csr', 'dia', 'dok', 'lil'} Sparse matrix format. kwargs : keyword arguments Passed through to sparse matrix constructor. Returns ------- m : scipy.sparse.spmatri...
Below is the the instruction that describes the task: ### Input: Convert into a sparse matrix. Parameters ---------- format : {'coo', 'csc', 'csr', 'dia', 'dok', 'lil'} Sparse matrix format. kwargs : keyword arguments Passed through to sparse matrix construct...
def apply(self, query, data): """Filter a query.""" field = self.model_field or query.model_class._meta.fields.get(self.name) if not field or self.name not in data: return query value = self.value(data) if value is self.default: return query value ...
Filter a query.
Below is the the instruction that describes the task: ### Input: Filter a query. ### Response: def apply(self, query, data): """Filter a query.""" field = self.model_field or query.model_class._meta.fields.get(self.name) if not field or self.name not in data: return query ...
def _parse_proxmox_upid(node, vm_=None): ''' Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ''' ret = {} upid = node # Parse node response node = node.split(':') ...
Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log.
Below is the the instruction that describes the task: ### Input: Upon requesting a task that runs for a longer period of time a UPID is given. This includes information about the job and can be used to lookup information in the log. ### Response: def _parse_proxmox_upid(node, vm_=None): ''' Upon reques...
def uniform_grid_fromintv(intv_prod, shape, nodes_on_bdry=True): """Return a grid from sampling an interval product uniformly. The resulting grid will by default include ``intv_prod.min_pt`` and ``intv_prod.max_pt`` as grid points. If you want a subdivision into equally sized cells with grid points in ...
Return a grid from sampling an interval product uniformly. The resulting grid will by default include ``intv_prod.min_pt`` and ``intv_prod.max_pt`` as grid points. If you want a subdivision into equally sized cells with grid points in the middle, use `uniform_partition` instead. Parameters ---...
Below is the the instruction that describes the task: ### Input: Return a grid from sampling an interval product uniformly. The resulting grid will by default include ``intv_prod.min_pt`` and ``intv_prod.max_pt`` as grid points. If you want a subdivision into equally sized cells with grid points in the...
def draw(self, mode, selection): """ Draw program in given mode, with given selection (IndexBuffer or first, count). """ if not self._linked: raise RuntimeError('Cannot draw program if code has not been set') # Init gl.check_error('Check before draw') ...
Draw program in given mode, with given selection (IndexBuffer or first, count).
Below is the the instruction that describes the task: ### Input: Draw program in given mode, with given selection (IndexBuffer or first, count). ### Response: def draw(self, mode, selection): """ Draw program in given mode, with given selection (IndexBuffer or first, count). """ ...
def __lock_location(self) -> None: """ Attempts to lock the location used by this writer. Will raise an error if the location is already locked by another writer. Will do nothing if the location is already locked by this writer. """ if not self._is_active: if ...
Attempts to lock the location used by this writer. Will raise an error if the location is already locked by another writer. Will do nothing if the location is already locked by this writer.
Below is the the instruction that describes the task: ### Input: Attempts to lock the location used by this writer. Will raise an error if the location is already locked by another writer. Will do nothing if the location is already locked by this writer. ### Response: def __lock_location(self) -> N...
def _set_route_precedence(self, v, load=False): """ Setter method for route_precedence, mapped from YANG variable /routing_system/router/hide_pim_holder/pim/route_precedence (container) If this variable is read-only (config: false) in the source YANG file, then _set_route_precedence is considered as a p...
Setter method for route_precedence, mapped from YANG variable /routing_system/router/hide_pim_holder/pim/route_precedence (container) If this variable is read-only (config: false) in the source YANG file, then _set_route_precedence is considered as a private method. Backends looking to populate this variabl...
Below is the the instruction that describes the task: ### Input: Setter method for route_precedence, mapped from YANG variable /routing_system/router/hide_pim_holder/pim/route_precedence (container) If this variable is read-only (config: false) in the source YANG file, then _set_route_precedence is consider...
async def cluster_failover(self, node_id, option): """ Forces a slave to perform a manual failover of its master Sends to specefied node """ if not isinstance(option, str) or option.upper() not in {'FORCE', 'TAKEOVER'}: raise ClusterError('Wrong option provided') ...
Forces a slave to perform a manual failover of its master Sends to specefied node
Below is the the instruction that describes the task: ### Input: Forces a slave to perform a manual failover of its master Sends to specefied node ### Response: async def cluster_failover(self, node_id, option): """ Forces a slave to perform a manual failover of its master Sends t...
def split(x, axis=0): """ Split arrays at the specified axis. It returns a number corresponding the size of the given axis (i.e ``x.shape[axis]``) of :obj:`~nnabla.Variable` s. Args: x(~nnabla.Variable): N-D array axis(int): Axis Returns: A :obj:`tuple` of :obj:`~nnabla.Variab...
Split arrays at the specified axis. It returns a number corresponding the size of the given axis (i.e ``x.shape[axis]``) of :obj:`~nnabla.Variable` s. Args: x(~nnabla.Variable): N-D array axis(int): Axis Returns: A :obj:`tuple` of :obj:`~nnabla.Variable` s See Also: :func...
Below is the the instruction that describes the task: ### Input: Split arrays at the specified axis. It returns a number corresponding the size of the given axis (i.e ``x.shape[axis]``) of :obj:`~nnabla.Variable` s. Args: x(~nnabla.Variable): N-D array axis(int): Axis Returns: A :...
def build_filters_and_sizers(self, ppoi_value, create_on_demand): """Build the filters and sizers for a field.""" name = self.name if not name and self.field.placeholder_image_name: name = self.field.placeholder_image_name self.filters = FilterLibrary( name, ...
Build the filters and sizers for a field.
Below is the the instruction that describes the task: ### Input: Build the filters and sizers for a field. ### Response: def build_filters_and_sizers(self, ppoi_value, create_on_demand): """Build the filters and sizers for a field.""" name = self.name if not name and self.field.placeholder_...
def predict(self, x, batch_size=None, verbose=None, is_distributed=False): """Generates output predictions for the input samples, processing the samples in a batched way. # Arguments x: the input data, as a Numpy array or list of Numpy array for local mode. as RDD[Sam...
Generates output predictions for the input samples, processing the samples in a batched way. # Arguments x: the input data, as a Numpy array or list of Numpy array for local mode. as RDD[Sample] for distributed mode is_distributed: used to control run in local or ...
Below is the the instruction that describes the task: ### Input: Generates output predictions for the input samples, processing the samples in a batched way. # Arguments x: the input data, as a Numpy array or list of Numpy array for local mode. as RDD[Sample] for distribu...