positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._status is not None: return F...
:rtype: bool
def reset_from_xml_string(self, xml_string): """Reloads the environment from an XML description of the environment.""" # if there is an active viewer window, destroy it self.close() # load model from xml self.mjpy_model = load_model_from_xml(xml_string) self.sim = MjSi...
Reloads the environment from an XML description of the environment.
def submit(self, **kwargs): """ Submit a job script that will run the schedulers with `abirun.py`. Args: verbose: Verbosity level dry_run: Don't submit the script if dry_run. Default: False Returns: namedtuple with attributes: retcode...
Submit a job script that will run the schedulers with `abirun.py`. Args: verbose: Verbosity level dry_run: Don't submit the script if dry_run. Default: False Returns: namedtuple with attributes: retcode: Return code as returned by the submission scri...
def merge_vertices(self): """call reduce_vertex on all vertices with identical values.""" # groupby expects sorted data sorted_vertices = sorted(list(self.vertices.items()), key=lambda v: hash(v[1])) groups = [] for k, g in groupby(sorted_vertices, lambda v: hash(v[1])): ...
call reduce_vertex on all vertices with identical values.
def list_all_brands(cls, **kwargs): """List Brands Return a list of Brands This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_brands(async=True) >>> result = thread.get() ...
List Brands Return a list of Brands This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_brands(async=True) >>> result = thread.get() :param async bool :param int page: pa...
def parse_xml(self, node): """ Parse an Image Layer from ElementTree xml node :param node: ElementTree xml node :return: self """ self._set_properties(node) self.name = node.get('name', None) self.opacity = node.get('opacity', self.opacity) self.visible =...
Parse an Image Layer from ElementTree xml node :param node: ElementTree xml node :return: self
def _minigui_report_search_status(self, leaves): """Prints the current MCTS search status to stderr. Reports the current search path, root node's child_Q, root node's child_N, the most visited path in a format that can be parsed by one of the STDERR_HANDLERS in minigui.ts. Args...
Prints the current MCTS search status to stderr. Reports the current search path, root node's child_Q, root node's child_N, the most visited path in a format that can be parsed by one of the STDERR_HANDLERS in minigui.ts. Args: leaves: list of leaf MCTSNodes returned by tree_...
def get_collection_filename(self, language): """ Returns the filename containing the stop words collection for a specific language. """ filename = os.path.join(self.data_directory, '%s.txt' % language) return filename
Returns the filename containing the stop words collection for a specific language.
def _check_running_services(services): """Check that the services dict provided is actually running and provide a list of (service, boolean) tuples for each service. Returns both a zipped list of (service, boolean) and a list of booleans in the same order as the services. @param services: OrderedD...
Check that the services dict provided is actually running and provide a list of (service, boolean) tuples for each service. Returns both a zipped list of (service, boolean) and a list of booleans in the same order as the services. @param services: OrderedDict of strings: [ports], one for each service ...
def tabulate(self, format='html', syntax=''): ''' a function to create a table from the class model keyMap :param format: string with format for table output :param syntax: [optional] string with linguistic syntax :return: string with table ''' from tabulate import tabulate as _tabula...
a function to create a table from the class model keyMap :param format: string with format for table output :param syntax: [optional] string with linguistic syntax :return: string with table
def get_releasenotes(project_dir=os.curdir, bugtracker_url=''): """ Retrieves the release notes, from the RELEASE_NOTES file (if in a package) or generates it from the git history. Args: project_dir(str): Path to the git repo of the project. bugtracker_url(str): Url to the bug tracker f...
Retrieves the release notes, from the RELEASE_NOTES file (if in a package) or generates it from the git history. Args: project_dir(str): Path to the git repo of the project. bugtracker_url(str): Url to the bug tracker for the issues. Returns: str: release notes Raises: ...
def count(self) -> "CountQuery": """ Return count of objects in queryset instead of objects. """ return CountQuery( db=self._db, model=self.model, q_objects=self._q_objects, annotations=self._annotations, custom_filters=self._cu...
Return count of objects in queryset instead of objects.
def move(self, path, raise_if_exists=False): """ Alias for ``rename()`` """ self.rename(path, raise_if_exists=raise_if_exists)
Alias for ``rename()``
def _validate_config(self, folder, validate_folder=True): ''' validate config is the primary validation function that checks for presence and format of required fields. Parameters ========== :folder: full path to folder with config.json :name: if provided, the folder...
validate config is the primary validation function that checks for presence and format of required fields. Parameters ========== :folder: full path to folder with config.json :name: if provided, the folder name to check against exp_id
def get_shape_mask(self, shape_obj): """ Return full mask where True marks pixels within the given shape. """ wd, ht = self.get_size() yi = np.mgrid[:ht].reshape(-1, 1) xi = np.mgrid[:wd].reshape(1, -1) pts = np.asarray((xi, yi)).T contains = shape_obj.con...
Return full mask where True marks pixels within the given shape.
def geom_length(geom): """ Calculates the length of coordinates in a shapely geometry. """ if geom.geom_type == 'Point': return 1 if hasattr(geom, 'exterior'): geom = geom.exterior if not geom.geom_type.startswith('Multi') and hasattr(geom, 'array_interface_base'): return...
Calculates the length of coordinates in a shapely geometry.
def remove_root_family(self, family_id): """Removes a root family. arg: family_id (osid.id.Id): the ``Id`` of a family raise: NotFound - ``family_id`` not a root raise: NullArgument - ``family_id`` is ``null`` raise: OperationFailed - unable to complete request rai...
Removes a root family. arg: family_id (osid.id.Id): the ``Id`` of a family raise: NotFound - ``family_id`` not a root raise: NullArgument - ``family_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure ...
def submissions(self): """List job submissions in workspace.""" r = fapi.get_submissions(self.namespace, self.name, self.api_url) fapi._check_response_code(r, 200) return r.json()
List job submissions in workspace.
def _dms_formatter(latitude, longitude, mode, unistr=False): """Generate a human readable DM/DMS location string. Args: latitude (float): Location's latitude longitude (float): Location's longitude mode (str): Coordinate formatting system to use unistr (bool): Whether to use ext...
Generate a human readable DM/DMS location string. Args: latitude (float): Location's latitude longitude (float): Location's longitude mode (str): Coordinate formatting system to use unistr (bool): Whether to use extended character set
def _train(self, trial): """Start one iteration of training and save remote id.""" assert trial.status == Trial.RUNNING, trial.status remote = trial.runner.train.remote() # Local Mode if isinstance(remote, dict): remote = _LocalWrapper(remote) self._running...
Start one iteration of training and save remote id.
def main_bigg(args=None, urlopen=urlopen): """Entry point for BiGG import program. If the ``args`` are provided, these should be a list of strings that will be used instead of ``sys.argv[1:]``. This is mostly useful for testing. """ parser = argparse.ArgumentParser( description='Import from...
Entry point for BiGG import program. If the ``args`` are provided, these should be a list of strings that will be used instead of ``sys.argv[1:]``. This is mostly useful for testing.
def convert_to_file(cgi_input, output_file, twobit_ref, twobit_name, var_only=False): """Convert a CGI var file and output VCF-formatted data to file""" if isinstance(output_file, str): output_file = auto_zip_open(output_file, 'w') conversion = convert(cgi_input=cgi_input, twobit_ref=twobit_ref, t...
Convert a CGI var file and output VCF-formatted data to file
def _match(self, x, op, y): """Compare the given `x` and `y` based on `op` :@param x, y, op :@type x, y: mixed :@type op: string :@return bool :@throws ValueError """ if (op not in self.condition_mapper): raise ValueError('Invalid where condi...
Compare the given `x` and `y` based on `op` :@param x, y, op :@type x, y: mixed :@type op: string :@return bool :@throws ValueError
def _unfiltered_jvm_dependency_map(self, fully_transitive=False): """Jvm dependency map without filtering out non-JvmTarget keys, exposed for testing. Unfiltered because the keys in the resulting map include non-JvmTargets. See the explanation in the jvm_dependency_map() docs for what this method produces...
Jvm dependency map without filtering out non-JvmTarget keys, exposed for testing. Unfiltered because the keys in the resulting map include non-JvmTargets. See the explanation in the jvm_dependency_map() docs for what this method produces. :param fully_transitive: if true, the elements of the map will be ...
def ref_context_from_geoloc(geoloc): """Return a RefContext object given a geoloc entry.""" text = geoloc.get('text') geoid = geoloc.get('geoID') rc = RefContext(name=text, db_refs={'GEOID': geoid}) return rc
Return a RefContext object given a geoloc entry.
def accountSummary(self, account: str = '') -> List[AccountValue]: """ List of account values for the given account, or of all accounts if account is left blank. This method is blocking on first run, non-blocking after that. Args: account: If specified, filter for t...
List of account values for the given account, or of all accounts if account is left blank. This method is blocking on first run, non-blocking after that. Args: account: If specified, filter for this account name.
def agm(x, y, context=None): """ Return the arithmetic geometric mean of x and y. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_agm, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return the arithmetic geometric mean of x and y.
async def close(self) -> None: """ Explicit exit. If so configured, populate cache to prove for any creds on schemata, cred defs, and rev regs marked of interest in configuration at initialization, archive cache, and purge prior cache archives. :return: current object ""...
Explicit exit. If so configured, populate cache to prove for any creds on schemata, cred defs, and rev regs marked of interest in configuration at initialization, archive cache, and purge prior cache archives. :return: current object
def get_known_host_entries(user, hostname, config=None, port=None, fingerprint_hash_type=None): ''' .. versionadded:: 2018.3.0 Return information about known host entries from the configfile, if any....
.. versionadded:: 2018.3.0 Return information about known host entries from the configfile, if any. If there are no entries for a matching hostname, return None. CLI Example: .. code-block:: bash salt '*' ssh.get_known_host_entries <user> <hostname>
def setup_versioned_routes(routes, version=None): """Set up routes with a version prefix.""" prefix = '/' + version if version else "" for r in routes: path, method = r route(prefix + path, method, routes[r])
Set up routes with a version prefix.
def control(self): """ control : 'if' ctrl_exp block ('elif' ctrl_exp block)* ('else' block) """ self.eat(TokenTypes.IF) ctrl = self.expression() block = self.block() ifs = [If(ctrl, block)] else_block = Block() while self.cur_token.type == Toke...
control : 'if' ctrl_exp block ('elif' ctrl_exp block)* ('else' block)
def _try_to_clean_garbage(self, writer_spec, exclude_list=()): """Tries to remove any files created by this shard that aren't needed. Args: writer_spec: writer_spec for the MR. exclude_list: A list of filenames (strings) that should not be removed. """ # Try to remove garbage (if an...
Tries to remove any files created by this shard that aren't needed. Args: writer_spec: writer_spec for the MR. exclude_list: A list of filenames (strings) that should not be removed.
def remove_line_breaks(text): """Remove line breaks from input. Including unicode 'line separator', 'paragraph separator', and 'next line' characters. """ return unicode(text, 'utf-8').replace('\f', '').replace('\n', '') \ .replace('\r', '').replace(u'\xe2\x80\xa8', '') \ .replace(u...
Remove line breaks from input. Including unicode 'line separator', 'paragraph separator', and 'next line' characters.
def populateFromFile(self, dataUrl): """ Populates the instance variables of this RnaQuantificationSet from the specified data URL. """ self._dbFilePath = dataUrl self._db = SqliteRnaBackend(self._dbFilePath) self.addRnaQuants()
Populates the instance variables of this RnaQuantificationSet from the specified data URL.
def doActionFor(instance, action_id, idxs=None): """Tries to perform the transition to the instance. Object is reindexed after the transition takes place, but only if succeeds. If idxs is set, only these indexes will be reindexed. Otherwise, will try to use the indexes defined in ACTIONS_TO_INDEX mappin...
Tries to perform the transition to the instance. Object is reindexed after the transition takes place, but only if succeeds. If idxs is set, only these indexes will be reindexed. Otherwise, will try to use the indexes defined in ACTIONS_TO_INDEX mapping if any. :param instance: Object to be transitioned...
def assert_has_permission(self, scope_required): """ Warn that the required scope is not found in the scopes granted to the currently authenticated user. :: # The admin user should have client admin permissions uaa.assert_has_permission('admin', 'clients.admin')...
Warn that the required scope is not found in the scopes granted to the currently authenticated user. :: # The admin user should have client admin permissions uaa.assert_has_permission('admin', 'clients.admin')
def cache_makedirs(self, subdir=None): ''' Make necessary directories to hold cache value ''' if subdir is not None: dirname = self.cache_path if subdir: dirname = os.path.join(dirname, subdir) else: dirname = os.path.dirname(se...
Make necessary directories to hold cache value
def extract(self, item, list_article_candidate): """Compares the extracted publish dates. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely publish date ...
Compares the extracted publish dates. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely publish date
def agenda_changed(self): """True if any rule activation changes have occurred.""" value = bool(lib.EnvGetAgendaChanged(self._env)) lib.EnvSetAgendaChanged(self._env, int(False)) return value
True if any rule activation changes have occurred.
def _get_controller_type(self): """Returns the current node's controller type""" if self.node_type == self.NODE_CONTROLLER_ROOT and self.name in self.CONTROLLERS: return self.name elif self.parent: return self.parent.controller_type else: return None
Returns the current node's controller type
def ancestor_paths(start=None, limit={}): """ All paths above you """ import utool as ut limit = ut.ensure_iterable(limit) limit = {expanduser(p) for p in limit}.union(set(limit)) if start is None: start = os.getcwd() path = start prev = None while path != prev and prev n...
All paths above you
def fit_predict(training_data, fitting_data, tau=1, samples_per_job=0, save_results=True, show=False): from disco.worker.pipeline.worker import Worker, Stage from disco.core import Job, result_iterator from disco.core import Disco """ training_data - training samples fitting_data - dataset to b...
training_data - training samples fitting_data - dataset to be fitted to training data. tau - controls how quickly the weight of a training sample falls off with distance of its x(i) from the query point x. samples_per_job - define a number of samples that will be processed in single mapreduce job. If 0, alg...
def new(self, fname=None, editorstack=None, text=None): """ Create a new file - Untitled fname=None --> fname will be 'untitledXX.py' but do not create file fname=<basestring> --> create file """ # If no text is provided, create default content empty = Fa...
Create a new file - Untitled fname=None --> fname will be 'untitledXX.py' but do not create file fname=<basestring> --> create file
def _poly_eval_0(self, u, ids): """Evaluate internal polynomial.""" return u * (u * (self._a[ids] * u + self._b[ids]) + self._c[ids]) + self._d[ids]
Evaluate internal polynomial.
def from_gff3(path, attributes=None, region=None, score_fill=-1, phase_fill=-1, attributes_fill='.', dtype=None): """Read a feature table from a GFF3 format file. Parameters ---------- path : string File path. attributes : list of strings, optional ...
Read a feature table from a GFF3 format file. Parameters ---------- path : string File path. attributes : list of strings, optional List of columns to extract from the "attributes" field. region : string, optional Genome region to extract. If ...
def confdate(self): """Date range of the conference the abstract belongs to represented by two tuples in the form (YYYY, MM, DD). """ date = self._confevent.get('confdate', {}) if len(date) > 0: start = {k: int(v) for k, v in date['startdate'].items()} end...
Date range of the conference the abstract belongs to represented by two tuples in the form (YYYY, MM, DD).
def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value
Verifies that the heat setting is between 0 and 3.
def encode_7or8bit(msg): """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" orig = msg.get_payload() if orig is None: # There's no payload. For backwards compatibility we use 7bit msg['Content-Transfer-Encoding'] = '7bit' return # We play a trick to make this go fas...
Set the Content-Transfer-Encoding header to 7bit or 8bit.
def compile_suffix_regex(entries): """Compile a sequence of suffix rules into a regex object. entries (tuple): The suffix rules, e.g. spacy.lang.punctuation.TOKENIZER_SUFFIXES. RETURNS (regex object): The regex object. to be used for Tokenizer.suffix_search. """ expression = "|".join([piece + "$" f...
Compile a sequence of suffix rules into a regex object. entries (tuple): The suffix rules, e.g. spacy.lang.punctuation.TOKENIZER_SUFFIXES. RETURNS (regex object): The regex object. to be used for Tokenizer.suffix_search.
def call(self, input_data=None, *args, **kwargs): """ Calls the request with input data using given configuration (retry, timeout, ...). :param input_data: :param args: :param kwargs: :return: """ self.build_request(input_data) self.caller = Reques...
Calls the request with input data using given configuration (retry, timeout, ...). :param input_data: :param args: :param kwargs: :return:
def synchronize_files(inputpaths, outpath, database=None, tqdm_bar=None, report_file=None, ptee=None, verbose=False): ''' Main function to synchronize files contents by majority vote The main job of this function is to walk through the input folders and align the files, so that we can compare every files across...
Main function to synchronize files contents by majority vote The main job of this function is to walk through the input folders and align the files, so that we can compare every files across every folders, one by one. The whole trick here is to align files, so that we don't need to memorize all the files in mem...
def channels_archive(self, room_id, **kwargs): """Archives a channel.""" return self.__call_api_post('channels.archive', roomId=room_id, kwargs=kwargs)
Archives a channel.
def get_qualifier_id(self): """Gets the ``Qualifier Id`` for this authorization. return: (osid.id.Id) - the qualifier ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id if not bo...
Gets the ``Qualifier Id`` for this authorization. return: (osid.id.Id) - the qualifier ``Id`` *compliance: mandatory -- This method must be implemented.*
def add_duplicate_analysis(self, src_analysis, destination_slot, ref_gid=None): """ Creates a duplicate of the src_analysis passed in. If the analysis passed in is not an IRoutineAnalysis, is retracted or has dependent services, returns None.If no reference...
Creates a duplicate of the src_analysis passed in. If the analysis passed in is not an IRoutineAnalysis, is retracted or has dependent services, returns None.If no reference analyses group id (ref_gid) is set, the value will be generated automatically. :param src_analysis: analysis to cr...
def get_composition(source, *fxns): """Compose several extractors together, on a source.""" val = source for fxn in fxns: val = fxn(val) return val
Compose several extractors together, on a source.
def after_websocket(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable: """Add an after websocket function. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.after_websocket def func(response): return...
Add an after websocket function. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.after_websocket def func(response): return response Arguments: func: The after websocket function itself. ...
def tablelib_binary_features(span1, span2): """ Table-/structure-related features for a pair of spans """ binary_features = settings["featurization"]["table"]["binary_features"] if span1.sentence.is_tabular() and span2.sentence.is_tabular(): if span1.sentence.table == span2.sentence.table: ...
Table-/structure-related features for a pair of spans
def file_sign( blockchain_id, hostname, input_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Sign a file with the current blockchain ID's host's public key. @config_path should be for the *client*, not blockstack-file Return {'status': True, 'sender_key_id': ..., 'sig': ...} on ...
Sign a file with the current blockchain ID's host's public key. @config_path should be for the *client*, not blockstack-file Return {'status': True, 'sender_key_id': ..., 'sig': ...} on success, and write ciphertext to output_path Return {'error': ...} on error
def next(self): """Returns the next item in the cursor.""" if self._current_index < len(self._collection): value = self._collection[self._current_index] self._current_index += 1 return value elif self._next_cursor: self.__fetch_next() r...
Returns the next item in the cursor.
def start_update(self, draw=None, queues=None): """ Conduct the formerly registered updates This method conducts the updates that have been registered via the :meth:`update` method. You can call this method if the :attr:`auto_update` attribute of this instance is True and the ...
Conduct the formerly registered updates This method conducts the updates that have been registered via the :meth:`update` method. You can call this method if the :attr:`auto_update` attribute of this instance is True and the `auto_update` parameter in the :meth:`update` method has been ...
def segwit_encode(hrp, witver, witprog): """Encode a segwit address.""" ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5)) if segwit_decode(hrp, ret) == (None, None): return None return ret
Encode a segwit address.
def _partition_all_internal(s, sep): """ Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings. :param s: The string to split. :param sep: A separator string. :return: A list of parts split by sep """ parts = list(s.partition(sep)) ...
Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings. :param s: The string to split. :param sep: A separator string. :return: A list of parts split by sep
def state_summary(value, name, state_list, helper, ok_value = 'ok', info = None): """ Always add the status to the long output, and if the status is not ok (or ok_value), we show it in the summary and set the status to critical """ # translate the value (integer) we receive to a human readable valu...
Always add the status to the long output, and if the status is not ok (or ok_value), we show it in the summary and set the status to critical
def _graphic(self): """ Adds the correct graphic options depending of the OS """ if sys.platform.startswith("win"): return [] if len(os.environ.get("DISPLAY", "")) > 0: return [] if "-nographic" not in self._options: return ["-nographi...
Adds the correct graphic options depending of the OS
def picard_sort(picard, align_bam, sort_order="coordinate", out_file=None, compression_level=None, pipe=False): """Sort a BAM file by coordinates. """ base, ext = os.path.splitext(align_bam) if out_file is None: out_file = "%s-sort%s" % (base, ext) if not file_exists(out_file...
Sort a BAM file by coordinates.
def roll_out_and_store(self, batch_info): """ Roll out environment and store result in the replay buffer """ self.model.train() if self.env_roller.is_ready_for_sampling(): rollout = self.env_roller.rollout(batch_info, self.model, self.settings.rollout_steps).to_device(self.device) ...
Roll out environment and store result in the replay buffer
def close_node(self, node_id, *args, **kwargs): """ Closes a VPCS VM. :returns: VPCSVM instance """ node = self.get_node(node_id) if node_id in self._used_mac_ids: i = self._used_mac_ids[node_id] self._free_mac_ids[node.project.id].insert(0, i) ...
Closes a VPCS VM. :returns: VPCSVM instance
def date_to_epiweek(date=datetime.date.today()) -> Epiweek: """ Convert python date to Epiweek """ year = date.year start_dates = list(map(_start_date_of_year, [year - 1, year, year + 1])) start_date = start_dates[1] if start_dates[1] > date: start_date = start_dates[0] elif da...
Convert python date to Epiweek
def impact_path(self, value): """Setter to impact path. :param value: The impact path. :type value: str """ self._impact_path = value if value is None: self.action_show_report.setEnabled(False) self.action_show_log.setEnabled(False) se...
Setter to impact path. :param value: The impact path. :type value: str
def set_rate(rate): """Defines the ideal rate at which computation is to be performed :arg rate: the frequency in Hertz :type rate: int or float :raises: TypeError: if argument 'rate' is not int or float """ if not (isinstance(rate, int) or isinstance(rate, float)): raise TypeError("a...
Defines the ideal rate at which computation is to be performed :arg rate: the frequency in Hertz :type rate: int or float :raises: TypeError: if argument 'rate' is not int or float
def classify(self, text=u''): """ Predicts the Language of a given text. :param text: Unicode text to be classified. """ result = self.calculate(doc_terms=self.tokenize(text)) #return (result['calc_id'], result) return (result['calc_id'], self.karbasa(result))
Predicts the Language of a given text. :param text: Unicode text to be classified.
def W(self,value): """ set fixed effect design """ if value is None: value = sp.zeros((self._N, 0)) assert value.shape[0]==self._N, 'Dimension mismatch' self._K = value.shape[1] self._W = value self._notify() self.clear_cache('predict_in_sample','Yres')
set fixed effect design
def render_sync(self): 'plots points and lines and text onto the Plotter' self.setZoom() bb = self.visibleBox xmin, ymin, xmax, ymax = bb.xmin, bb.ymin, bb.xmax, bb.ymax xfactor, yfactor = self.xScaler, self.yScaler plotxmin, plotymin = self.plotviewBox.xmin, self.plotvi...
plots points and lines and text onto the Plotter
def parse_featurecounts_report (self, f): """ Parse the featureCounts log file. """ file_names = list() parsed_data = dict() for l in f['f'].splitlines(): thisrow = list() s = l.split("\t") if len(s) < 2: continue if s[0] =...
Parse the featureCounts log file.
def lazy_map(initial={}, pre_size=0): ''' lazy_map is a blatant copy of the pyrsistent.pmap function, and is used to create lazy maps. ''' if is_lazy_map(initial): return initial if not initial: return _EMPTY_LMAP return _lazy_turbo_mapping(initial, pre_size)
lazy_map is a blatant copy of the pyrsistent.pmap function, and is used to create lazy maps.
def get(self, table_name): """Load table class by name, class not yet initialized""" assert table_name in self.tabs, \ "Table not avaiable. Avaiable tables: {}".format( ", ".join(self.tabs.keys()) ) return self.tabs[table_name]
Load table class by name, class not yet initialized
def process_once(self, timeout=0): """Process data from connections once. Arguments: timeout -- How long the select() call should wait if no data is available. This method should be called periodically to check and process incoming data, if there are...
Process data from connections once. Arguments: timeout -- How long the select() call should wait if no data is available. This method should be called periodically to check and process incoming data, if there are any. If that seems boring, look at t...
def _add_node(self, node): """Add a new node to node_list and give the node an ID. Args: node: An instance of Node. Returns: node_id: An integer. """ node_id = len(self.node_list) self.node_to_id[node] = node_id self.node_list.append(node) ...
Add a new node to node_list and give the node an ID. Args: node: An instance of Node. Returns: node_id: An integer.
def run(juttle, deployment_name, program_name=None, persist=False, token_manager=None, app_url=defaults.APP_URL): """ run a juttle program through the juttle streaming API and return the various events that are part of running a Juttle program which include: ...
run a juttle program through the juttle streaming API and return the various events that are part of running a Juttle program which include: * Initial job status details including information to associate multiple flowgraphs with their individual outputs (sinks): { "status":...
def _get_spyderplugins(plugin_path, is_io, modnames, modlist): """Scan the directory `plugin_path` for plugin packages and loads them.""" if not osp.isdir(plugin_path): return for name in os.listdir(plugin_path): # This is needed in order to register the spyder_io_hdf5 plugin. ...
Scan the directory `plugin_path` for plugin packages and loads them.
def make_reverse_dict(in_dict, warn=True): """ Build a reverse dictionary from a cluster dictionary Parameters ---------- in_dict : dict(int:[int,]) A dictionary of clusters. Each cluster is a source index and the list of other source in the cluster. Returns ------- ou...
Build a reverse dictionary from a cluster dictionary Parameters ---------- in_dict : dict(int:[int,]) A dictionary of clusters. Each cluster is a source index and the list of other source in the cluster. Returns ------- out_dict : dict(int:int) A single valued d...
def remove_domain_user_role(request, user, role, domain=None): """Removes a given single role for a user from a domain.""" manager = keystoneclient(request, admin=True).roles return manager.revoke(role, user=user, domain=domain)
Removes a given single role for a user from a domain.
def validate(self, value=None, model=None, context=None): """ Sequentially apply each validator to value and collect errors. :param value: a value to validate :param model: parent entity :param context: validation context, usually parent entity :return: list of errors (i...
Sequentially apply each validator to value and collect errors. :param value: a value to validate :param model: parent entity :param context: validation context, usually parent entity :return: list of errors (if any)
def gallery_section(images, title): """Create detail section with gallery. Args: title (str): Title to be displayed for detail section. images: stream of marv image files Returns One detail section. """ # pull all images imgs = [] while True: img = yield mar...
Create detail section with gallery. Args: title (str): Title to be displayed for detail section. images: stream of marv image files Returns One detail section.
def open_unknown_proxy(self, proxy, fullurl, data=None): """Overridable interface to open unknown URL type.""" type, url = splittype(fullurl) raise IOError('url error', 'invalid proxy for %s' % type, proxy)
Overridable interface to open unknown URL type.
def _get_magnitudes_from_spacing(self, magnitudes, delta_m): '''If a single magnitude spacing is input then create the bins :param numpy.ndarray magnitudes: Vector of earthquake magnitudes :param float delta_m: Magnitude bin width :returns: Vector of magnitude ...
If a single magnitude spacing is input then create the bins :param numpy.ndarray magnitudes: Vector of earthquake magnitudes :param float delta_m: Magnitude bin width :returns: Vector of magnitude bin edges (numpy.ndarray)
def force_move(source, destination): """ Force the move of the source inside the destination even if the destination has already a folder with the name inside. In the case, the folder will be replaced. :param string source: path of the source to move. :param string destination: path of the folder to mo...
Force the move of the source inside the destination even if the destination has already a folder with the name inside. In the case, the folder will be replaced. :param string source: path of the source to move. :param string destination: path of the folder to move the source to.
def toc_html(self, depth=6, lowest_level=6): """ Get TOC of currently fed HTML string in form of HTML string. :param depth: the depth of TOC :param lowest_level: the allowed lowest level of header tag :return: an HTML string """ toc = self.toc(depth=depth, lowest...
Get TOC of currently fed HTML string in form of HTML string. :param depth: the depth of TOC :param lowest_level: the allowed lowest level of header tag :return: an HTML string
def on_connect(self, connection): "Called when the socket connects" self._sock = connection._sock self._buffer = SocketBuffer(self._sock, self.socket_read_size) self.encoder = connection.encoder
Called when the socket connects
def set_document_unit(self, unit): """Use specified unit for width and height of generated SVG file. See ``SVG_UNIT_*`` enumerated values for a list of available unit values that can be used here. This function can be called at any time before generating the SVG file. However ...
Use specified unit for width and height of generated SVG file. See ``SVG_UNIT_*`` enumerated values for a list of available unit values that can be used here. This function can be called at any time before generating the SVG file. However to minimize the risk of ambiguities it's recom...
def save_state(self): """Save current state of GUI to configuration file.""" set_setting('lastSourceDir', self.source_directory.text()) set_setting('lastOutputDir', self.output_directory.text()) set_setting( 'useDefaultOutputDir', self.scenario_directory_radio.isChecked())
Save current state of GUI to configuration file.
def gen_code_api(self): """TODO: Docstring for gen_code_api.""" # edit config file conf_editor = Editor(self.conf_fpath) # insert code path for searching conf_editor.editline_with_regex(r'^# import os', 'import os') conf_editor.editline_with_regex(r'^# import sys', 'im...
TODO: Docstring for gen_code_api.
def delete_orderrun(backend, orderrun_id): """ Delete the orderrun specified by the argument. """ click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg='green') check_and_print(DKCloudCommandRunner.delete_orderrun(backend.dki, orderrun_id.strip()))
Delete the orderrun specified by the argument.
def handle_string_response(self, call_id, payload): """Handler for response `StringResponse`. This is the response for the following requests: 1. `DocUriAtPointReq` or `DocUriForSymbolReq` 2. `DebugToStringReq` """ self.log.debug('handle_string_response: in [typehint...
Handler for response `StringResponse`. This is the response for the following requests: 1. `DocUriAtPointReq` or `DocUriForSymbolReq` 2. `DebugToStringReq`
def _parse_record(data, duration_format='seconds'): """ Parse a raw data dictionary and return a Record object. """ def _map_duration(s): if s == '': return None elif duration_format.lower() == 'seconds': return int(s) else: t = time.strptime(...
Parse a raw data dictionary and return a Record object.
def subtract_months(self, months: int) -> datetime: """ Subtracts a number of months from the current value """ self.value = self.value - relativedelta(months=months) return self.value
Subtracts a number of months from the current value
def get_reaction(self, reactants, products): """ Gets a reaction from the Materials Project. Args: reactants ([str]): List of formulas products ([str]): List of formulas Returns: rxn """ return self._make_request("/reaction", ...
Gets a reaction from the Materials Project. Args: reactants ([str]): List of formulas products ([str]): List of formulas Returns: rxn
def install_gem(name, version=None, install_args=None, override_args=False): ''' Instructs Chocolatey to install a package via Ruby's Gems. name The name of the package to be installed. Only accepts a single argument. version Install a specific version of the package. Defaults to lates...
Instructs Chocolatey to install a package via Ruby's Gems. name The name of the package to be installed. Only accepts a single argument. version Install a specific version of the package. Defaults to latest version available. install_args A list of install arguments you wa...
def endpoint_show(endpoint_id): """ Executor for `globus endpoint show` """ client = get_client() res = client.get_endpoint(endpoint_id) formatted_print( res, text_format=FORMAT_TEXT_RECORD, fields=GCP_FIELDS if res["is_globus_connect"] else STANDARD_FIELDS, )
Executor for `globus endpoint show`
def query(self, url, method="GET", params=dict(), headers=dict()): """ Request a API endpoint at ``url`` with ``params`` being either the POST or GET data. """ access_token = self._get_at_from_session() oauth = OAuth1( self.consumer_key, client_sec...
Request a API endpoint at ``url`` with ``params`` being either the POST or GET data.