text
stringlengths
78
104k
score
float64
0
0.18
def _AlignDecodedDataOffset(self, decoded_data_offset): """Aligns the encoded file with the decoded data offset. Args: decoded_data_offset (int): decoded data offset. """ self._file_object.seek(0, os.SEEK_SET) self._decoder = self._GetDecoder() self._decoded_data = b'' encoded_data_...
0.007792
def _base_request(self, method): """Factory method for generating the base XML requests.""" request = E.Element(method) request.set('xmlns', 'AnetApi/xml/v1/schema/AnetApiSchema.xsd') request.append(self.client_auth) return request
0.00738
def _setDeviceID(self, value, device, message): """ Set the hardware device number. This is only needed if more that one device is on the same serial buss. :Parameters: value : `int` The device ID to set in the range of 0 - 127. device : `int` ...
0.001747
def django_logging_dict(log_dir, handlers=['file'], filename='debug.log'): """Extends :func:`logthing.utils.default_logging_dict` with django specific values. """ d = default_logging_dict(log_dir, handlers, filename) d['handlers'].update({ 'mail_admins':{ 'level':'ERROR', ...
0.00641
def save_attribute(elements, module_path): """ Recursively save attributes with module name and signature. """ for elem, signature in elements.items(): if isinstance(signature, dict): # Submodule case save_attribute(signature, module_path + (elem,)) elif signature.isattribute(): ...
0.001835
def filter_by(lookup_dict, grain='os_family', merge=None, default='default', base=None): ''' .. versionadded:: 0.17.0 Look up the given grain in a given dictionary for the current OS and return the result Although this may occasionally be use...
0.001221
def _instantiate(cls, params): """ Helper to instantiate Attention classes from parameters. Warns in log if parameter is not supported by class constructor. :param cls: Attention class. :param params: configuration parameters. :return: instance of `cls` type. """ sig_params = inspect.si...
0.004831
def unhide_selected(): '''Unhide the selected objects''' hidden_state = current_representation().hidden_state selection_state = current_representation().selection_state res = {} # Take the hidden state and flip the selected atoms bits. for k in selection_state: visible = hidden_sta...
0.009634
def check_video(video, languages=None, age=None, undefined=False): """Perform some checks on the `video`. All the checks are optional. Return `False` if any of this check fails: * `languages` already exist in `video`'s :attr:`~subliminal.video.Video.subtitle_languages`. * `video` is older than...
0.002304
def _do_api_call(self, endpoint_info, json): """ Utility function to perform an API call with retries :param endpoint_info: Tuple of method and endpoint :type endpoint_info: tuple[string, string] :param json: Parameters for this API call. :type json: dict :return...
0.001732
def processGif(searchStr): ''' This function returns the url of the gif searched for with the given search parameters using the Giphy API. Thanks! Fails gracefully when it can't find a gif by returning an appropriate image url with the failure message on it. ''' # Sanitizing searc...
0.002327
def umi_below_threshold(umi_quals, quality_encoding, quality_filter_threshold): ''' return true if any of the umi quals is below the threshold''' below_threshold = get_below_threshold( umi_quals, quality_encoding, quality_filter_threshold) return any(below_threshold)
0.006944
def import_agent(self, parent, agent_uri=None, agent_content=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ ...
0.002858
def delete(self, path=None, method='DELETE', **options): """ Equals :meth:`route` with a ``DELETE`` method parameter. """ return self.route(path, method, **options)
0.011111
def strip_accents(x): u"""Strip accents in the input phrase X. Strip accents in the input phrase X (assumed in UTF-8) by replacing accented characters with their unaccented cousins (e.g. é by e). :param x: the input phrase to strip. :type x: string :return: Return such a stripped X. """ ...
0.000415
def spawn(self, url, force_spawn=False): """use the url for creation of domain and fetch cookies - init cache dir by the url domain as ``<base>/domain`` - save the cookies to file ``<base>/domain/cookie.txt`` - init ``headers.get/post/json`` with response info - init ``site_dir/...
0.001185
def get_variables_substitution_dictionaries(self, lhs_graph, rhs_graph): """ Looks for sub-isomorphisms of rhs into lhs :param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph) :param rhs_graph: The smaller graph :return: The list of matching names ""...
0.005017
def _compute_sorted_indices(self): """ The smoothers need sorted data. This sorts it from the perspective of each column. if self._x[0][3] is the 9th-smallest value in self._x[0], then _xi_sorted[3] = 8 We only have to sort the data once. """ sorted_indices = [] ...
0.005822
def ComputeFortranSuffixes(suffixes, ppsuffixes): """suffixes are fortran source files, and ppsuffixes the ones to be pre-processed. Both should be sequences, not strings.""" assert len(suffixes) > 0 s = suffixes[0] sup = s.upper() upper_suffixes = [_.upper() for _ in suffixes] if SCons.Util...
0.002247
def didLastExecutedUpgradeSucceeded(self) -> bool: """ Checks last record in upgrade log to find out whether it is about scheduling upgrade. If so - checks whether current version is equals to the one in that record :returns: upgrade execution result """ lastEven...
0.003472
def _get_qvm_qc(name: str, qvm_type: str, device: AbstractDevice, noise_model: NoiseModel = None, requires_executable: bool = False, connection: ForestConnection = None) -> QuantumComputer: """Construct a QuantumComputer backed by a QVM. This is a minimal wrapper over the Quantu...
0.003474
def require_setting(self, name, feature='this feature'): """Raises an exception if the given app setting is not defined. As a generalization, this method should called from a Consumer's :py:meth:`~rejected.consumer.Consumer.initialize` method. If a required setting is not found, this me...
0.002301
def interconnect_link_topologies(self): """ Gets the InterconnectLinkTopologies API client. Returns: InterconnectLinkTopologies: """ if not self.__interconnect_link_topologies: self.__interconnect_link_topologies = InterconnectLinkTopologies(self.__connec...
0.007979
def set_hostname(hostname=None): ''' Sets the hostname on the server. .. versionadded:: 2019.2.0 Args: hostname(str): The new hostname to set. CLI Example: .. code-block:: bash salt '*' cimc.set_hostname foobar ''' if not hostname: raise salt.exceptions.Comm...
0.003886
def url_join(base, *args): """ Helper function to join an arbitrary number of url segments together. """ scheme, netloc, path, query, fragment = urlsplit(base) path = path if len(path) else "/" path = posixpath.join(path, *[('%s' % x) for x in args]) return urlunsplit([scheme, netloc, path, ...
0.002967
def query(self, query): """Q.query(query string) -> category string -- return the matched category for any user query """ self.query = query self.process_query() matching_corpus_index = self.match_query_to_corpus() return self.category_list[matching_corpus_index].strip()
0.034965
def round_f1(y_true, y_predicted): """ Calculates F1 (binary) measure. Args: y_true: list of true values y_predicted: list of predicted values Returns: F1 score """ try: predictions = [np.round(x) for x in y_predicted] except TypeError: predictions =...
0.002674
def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,z INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z) ...
0.015291
def get_root_graph(self,root): """Return back a graph containing just the root and children""" children = self.get_children(root) g = Graph() nodes = [root]+children for node in nodes: g.add_node(node) node_ids = [x.id for x in nodes] edges = [x for x in self._edges.values() if...
0.035545
def add_key_filters(self, key_filters): """ Adds key filters to the inputs. :param key_filters: a list of filters :type key_filters: list :rtype: :class:`RiakMapReduce` """ if self._input_mode == 'query': raise ValueError('Key filters are not supporte...
0.004975
def delete_refresh_token(self, refresh_token): """ Deletes a refresh token after use :param refresh_token: The refresh token to delete. """ access_token = self.fetch_by_refresh_token(refresh_token) self.mc.delete(self._generate_cache_key(access_token.token)) self....
0.005405
async def execute_filter(filter_: FilterObj, args): """ Helper for executing filter :param filter_: :param args: :return: """ if filter_.is_async: return await filter_.filter(*args, **filter_.kwargs) else: return filter_.filter(*args, **filter_.kwargs)
0.003322
def get_password(entry=None, username=None, prompt=None, always_ask=False): """ Prompt the user for a password on stdin. :param username: The username to get the password for. Default is the current user. :param entry: The entry in the keychain. This is a caller specific key. :param prompt:...
0.002944
def get_data_sharing_consent(username, enterprise_customer_uuid, course_id=None, program_uuid=None): """ Get the data sharing consent object associated with a certain user, enterprise customer, and other scope. :param username: The user that grants consent :param enterprise_customer_uuid: The consent r...
0.006958
def ProcessListDirectory(self, responses): """Processes the results of the ListDirectory client action. Args: responses: a flow Responses object. """ if not responses.success: raise flow.FlowError("Unable to list directory.") with data_store.DB.GetMutationPool() as pool: for resp...
0.00566
def get_ntp_stats(self): """Implementation of get_ntp_stats for IOS.""" ntp_stats = [] command = "show ntp associations" output = self._send_command(command) for line in output.splitlines(): # Skip first two lines and last line of command output if line ...
0.002635
def rooms(self): """ :rtype: twilio.rest.video.v1.room.RoomList """ if self._rooms is None: self._rooms = RoomList(self) return self._rooms
0.010471
def parse_file(self, sls_path): ''' Given a typical Salt SLS path (e.g.: apache.vhosts.standard), find the file on the file system and parse it ''' config = self.state.document.settings.env.config formulas_dirs = config.formulas_dirs fpath = sls_path.replace('.', ...
0.004878
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(Pre...
0.00612
def _set_stream_parameters(self, **kwargs): """ Sets the stream parameters which are expected to be declared constant. """ with util.disable_constant(self): self.param.set_param(**kwargs)
0.008368
def dateparser(self, dformat='%d/%m/%Y'): """ Returns a date parser for pandas """ def dateparse(dates): return [pd.datetime.strptime(d, dformat) for d in dates] return dateparse
0.008621
def read_packets(self): """Read packets from the socket and parse them""" while self.running: packet_length = self.client.recv(2) if len(packet_length) < 2: self.stop() continue packet_length = struct.unpack("<h", packet_length)[0] - 2 ...
0.003881
def create_data_dir(): """ Creates the DATA_DIR. :return: """ from django_productline.context import PRODUCT_CONTEXT if not os.path.exists(PRODUCT_CONTEXT.DATA_DIR): os.mkdir(PRODUCT_CONTEXT.DATA_DIR) print('*** Created DATA_DIR in %s' % PRODUCT_CONTEXT.DATA_DIR) else: ...
0.002793
def click(self, force_no_call=False, milis=None): """ Call when the button is pressed. This start the callback function in a thread If :milis is given, will release the button after :milis miliseconds """ if self.clicked: return False if not force_no_call an...
0.004862
def _tryMatch(self, textToMatchObject): """Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match """ for rule in self.context.rules: ruleTryMatchResult = rule.tryMatch(textToMatchObject) if ruleTryMatchResult is not None...
0.004225
def _merge_files(windows, nb_cpu): # type: (Iterable[pd.DataFrame], int) -> pd.DataFrame """Merge lists of chromosome bin df chromosome-wise. windows is an OrderedDict where the keys are files, the values are lists of dfs, one per chromosome. Returns a list of dataframes, one per chromosome, with ...
0.002339
def is_time_valid(self, timestamp): """Check if time is valid for this Timerange If sec_from_morning is not provided, get the value. :param timestamp: time to check :type timestamp: int :return: True if time is valid (in interval), False otherwise :rtype: bool "...
0.003578
def extract_urls(url, data, unescape=HTMLParser.HTMLParser().unescape): """Extracts the URLs from an HTML document.""" parts = urlparse.urlparse(url) prefix = '%s://%s' % (parts.scheme, parts.netloc) accessed_dir = os.path.dirname(parts.path) if not accessed_dir.endswith('/'): accessed_dir ...
0.00119
def grant_winsta_and_desktop(th): ''' Grant the token's user access to the current process's window station and desktop. ''' current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0] # Add permissions for the sid to the current windows station and thread id. # This prev...
0.003442
def setup_handler(context): """Generic setup handler """ if context.readDataFile('senaite.lims.txt') is None: return logger.info("SENAITE setup handler [BEGIN]") portal = context.getSite() # noqa # Custom setup handlers setup_html_filter(portal) logger.info("SENAITE setup ha...
0.002994
def log(self, facility, level, text, pid=False): """Send the message text to all registered hosts. The facility and level will be used to create the packet's PRI part. The HEADER will be automatically determined from the current time and hostname. The MSG will be set from the ru...
0.001797
def enable_servicegroup_host_checks(self, servicegroup): """Enable host checks for a servicegroup Format of the line that triggers function call:: ENABLE_SERVICEGROUP_HOST_CHECKS;<servicegroup_name> :param servicegroup: servicegroup to enable :type servicegroup: alignak.objects...
0.003241
def build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: """Build an edge predicate that pass for relations for which one of the given nodes is the object.""" nodes = set(nodes) def upstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: """Pass for r...
0.010373
def query_metric_stats(self, metric_type, metric_id=None, start=None, end=None, bucketDuration=None, **query_options): """ Query for metric aggregates from the server. This is called buckets in the Hawkular-Metrics documentation. :param metric_type: MetricType to be matched (required) :...
0.005482
def doTranslate(option, urlOrPaths, serverEndpoint=ServerEndpoint, verbose=Verbose, tikaServerJar=TikaServerJar, responseMimeType='text/plain', services={'all': '/translate/all'}): ''' Translate the file from source language to destination language. :param option: :param...
0.006182
async def discover_slave(self, service, timeout, **kwargs): """Perform Slave discovery for specified service.""" # TODO: use kwargs to change how slaves are picked up # (eg: round-robin, priority, random, etc) idle_timeout = timeout pools = self._pools[:] for sentinel i...
0.001324
def clean(source): """ Clean up the source: * Replace use of Fn::Join with Fn::Sub """ if isinstance(source, dict): for key, value in source.items(): if key == "Fn::Join": return convert_join(value) else: source[key] = clean(value) ...
0.002387
def validate_maildirs(ctx, param, value): """ Check that folders are maildirs. """ for path in value: for subdir in MD_SUBDIRS: if not os.path.isdir(os.path.join(path, subdir)): raise click.BadParameter( '{} is not a maildir (missing {!r} sub-directory).'....
0.002611
def hasFeature(self, prop, check_softs=False): """Return if there is a property with that name.""" return prop in self.props or (check_softs and any([fs.hasFeature(prop) for fs in self.props.get(SoftFeatures.SOFT, [])]))
0.010909
def path_total_size(path_: str) -> int: """Compute total size of the given file/dir.""" if path.isfile(path_): return path.getsize(path_) total_size = 0 for root_dir, _, files in os.walk(path_): for file_ in files: total_size += path.getsize(path.join(root_dir, file_)) re...
0.002985
def match_regex(self, regex: Pattern, required: bool = False, meaning: str = "") -> str: """Parse input based on a regular expression . Args: regex: Compiled regular expression object. required: Should the exception be raised on unexpected input? ...
0.004412
def _raise_error_if_not_of_type(arg, expected_type, arg_name=None): """ Check if the input is of expected type. Parameters ---------- arg : Input argument. expected_type : A type OR a list of types that the argument is expected to be. arg_name : The n...
0.002893
def encrypt_email(email): """ The default encryption function for storing emails in the database. This uses AES and the encryption key defined in the applications configuration. :param email: The email address. """ aes = SimpleAES(flask.current_app.config["AES_KEY"]) return aes.enc...
0.003021
def dumppickle(obj, fname, protocol=-1): """ Pickle object `obj` to file `fname`. """ with open(fname, 'wb') as fout: # 'b' for binary, needed on Windows pickle.dump(obj, fout, protocol=protocol)
0.004545
def create_content_if_changed(self, page, language, ctype, body): """Create a :class:`Content <pages.models.Content>` for a particular page and language only if the content has changed from the last time. :param page: the concerned page object. :param language: the wanted langua...
0.001704
def load(data_path): """ Extract data from provided file and return it as a string. """ with open(data_path, "r") as data_file: raw_data = data_file.read() data_file.close() return raw_data
0.008
def load_module_from_name(dotted_name, path=None, use_sys=True): """Load a Python module from its name. :type dotted_name: str :param dotted_name: python name of a module or package :type path: list or None :param path: optional list of path where the module or package should be search...
0.001437
def is_dicteq(dict1_, dict2_, almosteq_ok=True, verbose_err=True): """ Checks to see if dicts are the same. Performs recursion. Handles numpy """ import utool as ut assert len(dict1_) == len(dict2_), 'dicts are not of same length' try: for (key1, val1), (key2, val2) in zip(dict1_.items(), dict2_...
0.004533
def run_ansible(playbooks, inventory_path=None, roles=None, extra_vars=None, tags=None, on_error_continue=False, basedir='.'): """Run Ansible. Args: playbooks (list): list of paths to the playbooks to run inventory_path (str): path to the hosts file (inventory) extra_var (dict):...
0.000862
def listcomprehension_walk2(self, node): """List comprehensions the way they are done in Python 2 and sometimes in Python 3. They're more other comprehensions, e.g. set comprehensions See if we can combine code. """ p = self.prec self.prec = 27 code = Cod...
0.001013
def parse_timedelta(value): """ Parses a string and return a datetime.timedelta. :param value: string to parse :type value: str :return: timedelta object or None if value is None :rtype: timedelta/None :raise: TypeError when value is not string :raise: ValueError when value is not proper...
0.001267
def ichunks_list(list_, chunksize): """ input must be a list. SeeAlso: ichunks References: http://stackoverflow.com/questions/434287/iterate-over-a-list-in-chunks """ return (list_[ix:ix + chunksize] for ix in range(0, len(list_), chunksize))
0.003521
def refresh(self): """Refresh reloads data from the server. It raises an error if it fails to get the object's metadata""" self.metadata = self.db.read(self.path).json()
0.016043
def previous_session_label(self, session_label): """ Given a session label, returns the label of the previous session. Parameters ---------- session_label: pd.Timestamp A session whose previous session is desired. Returns ------- pd.Timestamp...
0.002574
def lt(self, event_property, value): """A less-than filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.lt('elapsed_ms', 500) >>> print(filtered) request(elapsed_ms).lt(elapsed_ms, 500) """ c = self.copy() ...
0.005141
def get_grouped_psf_model(template_psf_model, star_group, pars_to_set): """ Construct a joint PSF model which consists of a sum of PSF's templated on a specific model, but whose parameters are given by a table of objects. Parameters ---------- template_psf_model : `astropy.modeling.Fittable2DMo...
0.00084
def defaultcolour(self, colour): """ Auxiliary method to choose a default colour. Give me a user provided colour : if it is None, I change it to the default colour, respecting negative. Plus, if the image is in RGB mode and you give me 128 for a gray, I translate this to the expected (12...
0.015625
def actnorm_3d(name, x, logscale_factor=3.): """Applies actnorm to each time-step independently. There are a total of 2*n_channels*n_steps parameters learnt. Args: name: variable scope. x: 5-D Tensor, (NTHWC) logscale_factor: Increases the learning rate of the scale by logscale_...
0.006702
def init_kernel(self): ''' Initializes the covariance matrix with a guess at the GP kernel parameters. ''' if self.kernel_params is None: X = self.apply_mask(self.fpix / self.flux.reshape(-1, 1)) y = self.apply_mask(self.flux) - np.dot(X, np.linalg.solve...
0.002703
def by_location(self, location, cc=None, radius=None, term=None, num_biz_requested=None, category=None): """ Perform a Yelp Review Search based on a location specifier. Args: location - textual location specifier of form: "address, neighborhood, city, state or zip, optional country" ...
0.018709
def get_sigla(self, work): """Returns a list of all of the sigla for `work`. :param work: name of work :type work: `str` :rtype: `list` of `str` """ return [os.path.splitext(os.path.basename(path))[0] for path in glob.glob(os.path.join(self._path, work, ...
0.006061
def delete_subtrie(self, key): """ Given a key prefix, delete the whole subtrie that starts with the key prefix. Key will be encoded into binary array format first. It will call `_set` with `if_delete_subtrie` set to True. """ validate_is_bytes(key) self.root_h...
0.006452
def _merge_doc(original, to_merge): # type: (str, str) -> str """Merge two usage strings together. Args: original: The source of headers and initial section lines. to_merge: The source for the additional section lines to append. Returns: A new usage string that contains informa...
0.001372
def digest_chunks(chunks, algorithms=(hashlib.md5, hashlib.sha1)): """ returns a base64 rep of the given digest algorithms from the chunks of data """ hashes = [algorithm() for algorithm in algorithms] for chunk in chunks: for h in hashes: h.update(chunk) return [_b64e...
0.00277
def _get_service_endpoint(context, svc, region=None, public=True): """ Parses the services dict to get the proper endpoint for the given service. """ region = _safe_region(region) # If a specific context is passed, use that. Otherwise, use the global # identity reference. context = context o...
0.001473
def change_volume(self, increment): """调整音量大小""" if increment == 1: self.volume += 5 else: self.volume -= 5 self.volume = max(min(self.volume, 100), 0)
0.009662
def wait(self, timeout=None): """ Wait for the job to complete, or a timeout to happen. This is more efficient than the version in the base Job class, in that we can use a call that blocks for the poll duration rather than a sleep. That means we shouldn't block unnecessarily long and can also pol...
0.008876
def pushd(path): """ A context that enters a given directory and restores the old state on exit. The original directory is returned as the context variable. """ saved = os.getcwd() os.chdir(path) try: yield saved finally: os.chdir(saved)
0.006993
def _get_path_entry_from_list(self, query_path): """ Returns the config entry at query path :param query_path: list(str), config header path to follow for entry :return: (list, str, dict, OrderedDict), config entry requested :raises: exceptions.ResourceNotFoundError """ ...
0.004367
def add_bgp_error_metadata(code, sub_code, def_desc='unknown'): """Decorator for all exceptions that want to set exception class meta-data. """ # Check registry if we already have an exception with same code/sub-code if _EXCEPTION_REGISTRY.get((code, sub_code)) is not None: raise ValueError('BGP...
0.001136
def accuracy(mod_y, ref_y, summary=True, name="accuracy"): """Accuracy computation op. Parameters ---------- mod_y : tf.Tensor Model output tensor. ref_y : tf.Tensor Reference input tensor. summary : bool, optional (default = True) ...
0.002601
def to_strings(self, use_colors=True): """Convert an edit script to a pair of strings representing the operation in a human readable way. :param use_colors: Boolean indicating whether to use terminal color codes to color the output. :return: Tuple with text corresponding to the first pronunciat...
0.007189
def ParseOptions(cls, options, output_module): """Parses and validates options. Args: options (argparse.Namespace): parser options. output_module (OutputModule): output module to configure. Raises: BadConfigObject: when the output module object does not have the SetCredentials ...
0.00271
def _new_packet_cb(self, packet): """Callback for newly arrived packets for the memory port""" chan = packet.channel cmd = packet.data[0] payload = packet.data[1:] if chan == CHAN_INFO: if cmd == CMD_INFO_NBR: self.nbr_of_mems = payload[0] ...
0.000247
def group(self): "Group inherited from main element" if self.main and self.main.group != type(self.main).__name__: return self.main.group else: return 'AdjointLayout'
0.014019
def _new_wire(self, source, sinks=None): """Create a new :py:class:`._Wire` with a unique routing key.""" # Assign sequential routing key to new nets. wire = _Wire(source, sinks if sinks is not None else [], len(self._wires)) self._wires.append(wire) return wire
0.009901
def __fetch_1_27(self, from_date=None): """Fetch the pages from the backend url for MediaWiki >=1.27 The method retrieves, from a MediaWiki url, the wiki pages. :returns: a generator of pages """ logger.info("Looking for pages at url '%s'", self.url) npages = ...
0.004182
def _IsDirectory(parent, item): """Helper that returns if parent/item is a directory.""" return tf.io.gfile.isdir(os.path.join(parent, item))
0.02069
def mse(test, ref, mask=None): """Mean Squared Error (MSE) Calculate the MSE between a test image and a reference image. Parameters ---------- ref : np.ndarray the reference image test : np.ndarray the tested image mask : np.ndarray, optional the mask for the ROI ...
0.001555
def get_diff_str(self, element, length): '''get_diff_str High-level api: Produce a string that indicates the difference between two models. Parameters ---------- element : `Element` A node in model tree. length : `int` String length tha...
0.003509