text
stringlengths
78
104k
score
float64
0
0.18
def line(self, x0, y0, x1, y1, char): """Create a line on ASCII canvas. Args: x0 (int): x coordinate where the line should start. y0 (int): y coordinate where the line should start. x1 (int): x coordinate where the line should end. y1 (int): y coordinate ...
0.001416
def parameters_as_string(self): """Returns a comma-separated list of the parameters in the executable definition.""" params = ", ".join([ p.name for p in self.ordered_parameters ]) return params
0.022936
def _compute_emissions(self, corpus, order=1): """ Computes the emissions and transitions probabilities of a corpus based on word types Args: corpus: the given corpus (a corpus_entry needs to be iterable) order: the maximal Markov chain order Computes: ...
0.00293
def get_degradations(self): """Extract Degradation INDRA Statements.""" deg_events = self.tree.findall("EVENT/[type='ONT::CONSUME']") for event in deg_events: if event.attrib['id'] in self._static_events: continue affected = event.find(".//*[@role=':AFFECT...
0.001809
def get_format(self): """ Returns a QTextCharFormat that encodes the current style attributes. """ format = QtGui.QTextCharFormat() # Set foreground color qcolor = self.get_color(self.foreground_color, self.intensity) if qcolor is not None: format.setForegrou...
0.003755
def session_rollback(self, session): """Send session_rollback signal in sqlalchemy ``after_rollback``. This marks the failure of session so the session may enter commit phase. """ # this may happen when there's nothing to rollback if not hasattr(session, 'meepo_unique_id...
0.003289
def clear_face_values(self): """stub""" if (self.get_face_values_metadata().is_read_only() or self.get_face_values_metadata().is_required()): raise NoAccess() self.clear_integer_value('frontFaceValue') self.clear_integer_value('sideFaceValue') self.cle...
0.005682
def _diff(text_0, text_1): """Return a diff between two strings.""" diff = difflib.ndiff(text_0.splitlines(), text_1.splitlines()) return _diff_removed_lines(diff)
0.005714
def plot_sections(self, fout_dir=".", **kws_usr): """Plot groups of GOs which have been placed in sections.""" kws_plt, _ = self._get_kws_plt(None, **kws_usr) PltGroupedGos(self).plot_sections(fout_dir, **kws_plt)
0.008439
def run_query_segments(doc, proc_id, engine, gps_start_time, gps_end_time, included_segments_string, excluded_segments_string = None, write_segments = True, start_pad = 0, end_pad = 0): """Runs a segment query. This was originally part of ligolw_query_segments, but now is also used by ligolw_segments_from_cats...
0.012834
def _parse_tags(self, match): '''Parse hashtags.''' mat = match.group(0) # Fix problems with the regex capturing stuff infront of the # tag = None for i in '#\uff03': pos = mat.rfind(i) if pos != -1: tag = i break ...
0.002865
def get_page_break_positions(docbody): """Locate page breaks in the list of document lines and create a list positions in the document body list. @param docbody: (list) of strings - each string is a line in the document. @return: (list) of integer positions, whereby each integer represe...
0.005997
def _multi(fun, lons, lats, chunk_size, cores=1): """Work on multiple cores. """ pool = Pool(processes=cores) splits = get_scene_splits(lons.shape[0], chunk_size, cores) lons_parts = np.vsplit(lons, splits) lats_parts = np.vsplit(lats, splits) results = [pool.apply_async(fun, ...
0.001706
def potcar_spec( filename ): """ Returns a dictionary specifying the pseudopotentials contained in a POTCAR file. Args: filename (Str): The name of the POTCAR file to process. Returns: (Dict): A dictionary of pseudopotential filename: dataset pairs, e.g. { 'Fe_pv': 'PBE...
0.029158
def run_checks(self, b, compute, times=[], **kwargs): """ run any sanity checks to make sure the parameters and options are legal for this backend. If they are not, raise an error here to avoid errors within the workers. Any physics-checks that are backend-independent should be...
0.004854
def _build_search(structured_query): """Construct search statment for db execution. Produces the search statement and argument dictionary to be executed by the DBAPI v2 execute method. For example, ``cursor.execute(*_build_search(query, weights))`` :param query: containing terms, filters, and sort...
0.000126
def filesizeformat(bytes, sep=' '): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 B, 2.3 GB etc). Grabbed from Django (http://www.djangoproject.com), slightly modified. :param bytes: size in bytes (as integer) :param sep: string separator between number and a...
0.001192
def cmd(self, cmd, *args, **kwargs): """ run a terraform command, if success, will try to read state file :param cmd: command and sub-command of terraform, seperated with space refer to https://www.terraform.io/docs/commands/index.html :param args: arguments of a comm...
0.003061
def _port_add_or_delete_policy(action, name, sel_type=None, protocol=None, port=None, sel_range=None): ''' .. versionadded:: 2019.2.0 Performs the action as called from ``port_add_policy`` or ``port_delete_policy``. Returns the result of the call to semanage. ''' if action not in ['add', 'dele...
0.004525
def add_scalar(self, logger, k, v, event_name, global_step): """ Helper method to log a scalar with VisdomLogger. Args: logger (VisdomLogger): visdom logger k (str): scalar name which is used to set window title and y-axis label v (int or float): scalar value...
0.002757
def _sign(self, data): """ Compute a signature string according to the CloudStack signature method (hmac/sha1). """ # Python2/3 urlencode aren't good enough for this task. params = "&".join( "=".join((key, cs_encode(value))) for key, value in sort...
0.00349
def make_pixel_mask_from_col_row(column, row, default=0, value=1): '''Generate mask from column and row lists Parameters ---------- column : iterable, int List of colums values. row : iterable, int List of row values. default : int Value of pixels that are not ...
0.002188
def analysis_log_view(self): """Get the log view of the requested analysis """ service = self.get_analysis_or_service() if not self.can_view_logs_of(service): return None view = api.get_view("auditlog", context=service, request=self.request) view.update() ...
0.005495
def Append(self, value, timestamp): """Adds value at timestamp. Values must be added in order of increasing timestamp. Args: value: An observed value. timestamp: The timestamp at which value was observed. Raises: RuntimeError: If timestamp is smaller than the previous timstamp. ...
0.003831
def factorized_gaussian_noise(in_features, out_features, device): """ Factorised (cheaper) gaussian noise from "Noisy Networks for Exploration" by Meire Fortunato, Mohammad Gheshlaghi Azar, Bilal Piot and others """ in_noise = scaled_noise(in_features, device=device) out_noise = scaled_noise(out...
0.002551
def _to_addr(worksheet, row, col, row_fixed=False, col_fixed=False): """converts a (0,0) based coordinate to an excel address""" addr = "" A = ord('A') col += 1 while col > 0: addr = chr(A + ((col - 1) % 26)) + addr col = (col - 1) // 26 prefix = ("'%s'!" % worksheet) if workshe...
0.002028
def run_cell_magic(self, magic_name, line, cell): """Run a limited number of magics from scripts, without IPython""" if magic_name == 'bash': self.shebang("bash", cell) elif magic_name == 'metatab': self.mm.metatab(line, cell)
0.007273
def _insert_entity(entity): ''' Constructs an insert entity request. ''' _validate_entity(entity) request = HTTPRequest() request.method = 'POST' request.headers = [_DEFAULT_CONTENT_TYPE_HEADER, _DEFAULT_PREFER_HEADER, _DEFAULT_ACCEPT_HEADER] ...
0.007335
def error(self, s): """ Prints out an error message to stderr. :param s: The error string to print :return: None """ print(" ERROR: '%s', %s" % (self.src_id, s), file=sys.stderr)
0.008772
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,...
0.003236
def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False): ''' Get a WikipediaPage object for the page with title `title` or the pageid `pageid` (mutually exclusive). Keyword arguments: * title - the title of the page to load * pageid - the numeric pageid of the page to load * a...
0.009311
def get_children(self): """Return an iterator for accessing the children of this cursor.""" # FIXME: Expose iteration from CIndex, PR6125. def visitor(child, parent, children): # FIXME: Document this assertion in API. # FIXME: There should just be an isNull method. ...
0.005747
def lookup_defs(self, variable, size_threshold=32): """ Find all definitions of the varaible :param SimVariable variable: The variable to lookup for. :param int size_threshold: The maximum bytes to consider for the variable. For example, if the variable is 100 ...
0.003283
def readWindowsFile(wfile): """" reading file with windows wfile File containing window info """ window_file = wfile+'.wnd' assert os.path.exists(window_file), '%s is missing.'%window_file rv = SP.loadtxt(window_file) return rv
0.007634
def OnExpandAll(self): """ expand all nodes """ root = self.tree.GetRootItem() fn = self.tree.Expand self.traverse(root, fn) self.tree.Expand(root)
0.010695
def has_binding(api): """Safely check for PyQt4 or PySide, without importing submodules Parameters ---------- api : str [ 'pyqtv1' | 'pyqt' | 'pyside' | 'pyqtdefault'] Which module to check for Returns ------- True if the relevant module appears to be i...
0.003103
def idngram2lm(idngram_file, vocab_file, output_file, context_file=None, vocab_type=1, oov_fraction=0.5, four_byte_counts=False, min_unicount=0, zeroton_fraction=False, n=3, verbosity=2, arpa_output=True, ascii_input=False): """ Takes an idngram-file (in either binary (by default) or ASCII (if specified) fo...
0.012027
def _new_pivot_query(self): """ Create a new query builder for the pivot table. :rtype: orator.orm.Builder """ query = self.new_pivot_statement() for where_args in self._pivot_wheres: query.where(*where_args) return query.where(self._foreign_key, se...
0.005865
def GetPublicCert(self): """Download Gitkit public cert. Returns: dict of public certs. """ cert_url = self.google_api_url + 'publicKeys' resp, content = self.http.request(cert_url) if resp.status == 200: return simplejson.loads(content) else: raise errors.GitkitServerEr...
0.007407
def key(**kwargs): ''' Display system key. ''' output, err = cli_syncthing_adapter.key(device=True) click.echo("%s" % output, err=err)
0.035211
def set_mpi_procs(self, mpi_procs): """Set the number of CPUs used for MPI.""" QueueAdapter.set_mpi_procs(self, mpi_procs) num_nodes, rest_cores = self.hw.divmod_node(mpi_procs, omp_threads=1) if num_nodes == 0: self.qparams["nodes"] = 1 self.qparams["ppn"] = mpi...
0.003597
def execute(self, **minimize_options): """ Execute the fit. :param minimize_options: keyword arguments to be passed to the specified minimizer. :return: FitResults instance """ minimizer_ans = self.minimizer.execute(**minimize_options) try: # to build...
0.00715
def rollapply(data, window, fn): """ Apply a function fn over a rolling window of size window. Args: * data (Series or DataFrame): Series or DataFrame * window (int): Window size * fn (function): Function to apply over the rolling window. For a series, the return value i...
0.00146
def _pcap_service_control(action, askadmin=True): """Internal util to run pcap control command""" command = action + ' ' + pcap_service_name() res, code = _exec_cmd(_encapsulate_admin(command) if askadmin else command) if code != 0: warning(res.decode("utf8", errors="ignore")) return (code =...
0.003086
def post(self, object_type, object_id): """Add new tags to an object.""" if object_id == 0: return Response(status=404) tagged_objects = [] for name in request.get_json(force=True): if ':' in name: type_name = name.split(':', 1)[0] ...
0.003394
def release_references(self, keys): """Non-recursively indicate that an iterable of _ReferenceKey no longer exist. Unknown keys are ignored. :param Iterable[_ReferenceKey] keys: The keys to drop. """ keys = set(self.referenced_by) & set(keys) for key in keys: ...
0.005747
def GetMetadata( self, metadata_key='', recursive=True, timeout=None, retry=True): """Retrieve the contents of metadata server for a metadata key. Args: metadata_key: string, the metadata key to watch for changes. recursive: bool, True if we should recursively watch for metadata changes. ...
0.002915
def setSectionCount(self, count): """ Sets the number of editors that the serial widget should have. :param count | <int> """ # cap the sections at 10 count = max(1, min(count, 10)) # create additional editors while self.la...
0.004348
def pyramid_analysis(Gs, f, **kwargs): r"""Compute the graph pyramid transform coefficients. Parameters ---------- Gs : list of graphs A multiresolution sequence of graph structures. f : ndarray Graph signal to analyze. h_filters : list A list of filter that will be used...
0.001999
def load_instances(self, instances): """Load a set of instances into the CLIPS data base. The C equivalent of the CLIPS load-instances command. Instances can be loaded from a string, from a file or from a binary file. """ instances = instances.encode() if os.p...
0.003425
def _export_to_vcf(cur): """Convert PURPLE custom output into VCF. """ if float(cur["copyNumber"]) > 2.0: svtype = "DUP" elif float(cur["copyNumber"]) < 2.0: svtype = "DEL" else: svtype = None if svtype: info = ["END=%s" % cur["end"], "SVLEN=%s" % (int(cur["end"])...
0.006908
def omega_mixture(omegas, zs, CASRNs=None, Method=None, AvailableMethods=False): r'''This function handles the calculation of a mixture's acentric factor. Calculation is based on the omegas provided for each pure component. Will automatically select a method to use if no Method is provided...
0.00044
def symmetry_normalised_sites(self, scaled_positions): """Returns an array of same size as *scaled_positions*, containing the corresponding symmetry-equivalent sites within the unit cell of lowest indices. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> s...
0.003145
def store(self, key, value): """Add new record to cache key: entry key value: data of entry """ self.client.set(key, value, time=self.timeout)
0.010526
def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]: """Exposes the docopt command-line arguments parser. Return a dictionary of arguments. """ return docopt(__doc__, argv=argv, version=__version__)
0.008032
def private_key_managed(name, bits=2048, passphrase=None, cipher='aes_128_cbc', new=False, overwrite=False, verbose=True, **kwargs): ''' Manage ...
0.003645
def alignImageAlongLine(img, line, height=15, length=None, zoom=1, fast=False, borderValue=0): ''' return a sub image aligned along given line @param img - numpy.2darray input image to get subimage from @param line - list of 2 points [x0,y0,x1,y1]) @param height - he...
0.001161
def dt_from_http_datetime_str(http_full_datetime): """Parse HTTP Full Date formats and return as datetime. Args: http_full_datetime : str Each of the allowed formats are supported: - Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 - Sunday, 06-Nov-94 08:49:37 GMT ; ...
0.001142
def difference(self, *others): """Return the difference of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.difference(b)) ['eggs'] """ return self.copy(super(NGram, self)...
0.005865
def sequence_weights(aln, scaling='none', gap_chars='-.'): """Weight aligned sequences to emphasize more divergent members. Returns a list of floating-point numbers between 0 and 1, corresponding to the proportional weight of each sequence in the alignment. The first list is the weight of the first seq...
0.000425
def var_and_name_scope(names): """Creates a variable scope and a name scope. If a variable_scope is provided, this will reenter that variable scope. However, if none is provided then the variable scope will match the generated part of the name scope. Args: names: A tuple of name_scope, variable_scope or...
0.009768
def listen(self, callback=None, timeout=(5, 300)): """Start the &listen long poll and return immediately.""" if self._running: return False # if self.devices() is False: # return False self._queue = Queue() self._running = True self._timeout = timeo...
0.003824
def get_config_path(): """Put together the default configuration path based on OS.""" dir_path = (os.getenv('APPDATA') if os.name == "nt" else os.path.expanduser('~')) return os.path.join(dir_path, '.vtjp')
0.004274
def get(self, data_type, options=None): """ Get a single item :param data_type: str :param options: dict :return: dict|str """ if options is None: options = {} response = self._client.session.get( '{url}/{type}'.format( ...
0.004348
def format(format_string, cast=lambda x: x): """ A pre-called helper to supply a modern string format (the kind with {} instead of %s), so that it can apply to each value in the column as it is rendered. This can be useful for string padding like leading zeroes, or rounding floating point numbers to a ...
0.006574
def listdir(self, name): """ TODO collect directories """ return [], [obj.filename for obj in cloudstorage.listbucket(self.path(name))]
0.017964
def transform(self, data, mark, next): ''' Apply the appropriate transformation function on current state data, which is supposed to end at this point. It is expected transformation logic makes use of :attr:`start`, :attr:`current` and :attr:`streaming` instance attributes to ...
0.002457
def sulfide_type(structure): """ Determines if a structure is a sulfide/polysulfide Args: structure (Structure): Input structure. Returns: (str) sulfide/polysulfide/sulfate """ structure = structure.copy() structure.remove_oxidation_states() s = Element("S") comp = ...
0.000581
def close(self): """This method closes the canvas and writes contents to the associated file. Calling this procedure is optional, because Pychart calls this procedure for every open canvas on normal exit.""" for i in range(0, len(active_canvases)): if active_canvases[...
0.005089
def getMappingsOnThingType(self, thingTypeId, draft=False): """ Get all the mappings for a thing type. Parameters: - thingTypeId (string) - the thing type - draft (boolean) - draft or active Throws APIException on failure. """ if draft: ...
0.006068
def eval_hessian(self, ordered_parameters=[], **parameters): """ Hessian for log-likelihood is defined as :math:`\\nabla^2_{\\vec{p}}( \\log( L(\\vec{p} | \\vec{x})))`. :param parameters: values for the fit parameters. :return: array of length number of ``Parameter``'s in the mo...
0.003613
def clean_and_build_concat(data, samples, randomseed, ipyclient): """ STEP 6-1: Clears dirs and databases and calls 'build_input_file()' """ ## but check for new clust database name if this is a new branch cleanup_tempfiles(data) catclust = os.path.join(data.dirs.across, data.name+"_catclus...
0.00885
def _verify_state(self, resp, state_data, state): """ Will verify the state and throw and error if the state is invalid. :type resp: AuthorizationResponse :type state_data: dict[str, str] :type state: satosa.state.State :param resp: The authorization response from the AS...
0.004713
def _set_show_mpls_rsvp_session_wide(self, v, load=False): """ Setter method for show_mpls_rsvp_session_wide, mapped from YANG variable /brocade_mpls_rpc/show_mpls_rsvp_session_wide (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_mpls_rsvp_session_wide is cons...
0.006008
def similar(self, threshold, **criterias): '''Find text-based field matches with similarity (1-levenshtein/length) higher than specified threshold (0 to 1, 1 being an exact match)''' # XXX: use F from https://docs.djangoproject.com/en/1.8/ref/models/expressions/ meta = self.model._meta funcs, params = list()...
0.020074
def _checksum(in_file, block_size=65536): """sha256 checksum, thanks to: https://gist.github.com/rji/b38c7238128edf53a181 """ cs = hashlib.sha256() with open(in_file, "rb") as f: for block in iter(lambda: f.read(block_size), b''): cs.update(block) return cs.hexdigest()
0.006472
def remove_followers(self, task, params={}, **options): """Removes each of the specified followers from the task if they are following. Returns the complete, updated record for the affected task. Parameters ---------- task : {Id} The task to remove followers from. [data...
0.005425
def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. Modified from 'pydrizzle.fileutil' to allow this module to be independent of PyDrizzle/MultiDrizzle. """ # Parse out any extension speci...
0.002
def decode_timeseries_row(self, tsrow, tscols=None, convert_timestamp=False): """ Decodes a TsRow into a list :param tsrow: the protobuf TsRow to decode. :type tsrow: riak.pb.riak_ts_pb2.TsRow :param tscols: the protobuf TsColumn data to help decode...
0.001398
def _build_amps_list(self, amp_value, processlist): """Return the AMPS process list according to the amp_value Search application monitored processes by a regular expression """ ret = [] try: # Search in both cmdline and name (for kernel thread, see #1261) ...
0.001921
def _compute_style_of_faulting_term(self, rup, C): """ Computes the coefficient to scale for reverse or strike-slip events Fault type (Strike-slip, Normal, Thrust/reverse) is derived from rake angle. Rakes angles within 30 of horizontal are strike-slip, angles from 30 to ...
0.002294
def initialize(self, secret_shares=5, secret_threshold=3, pgp_keys=None, root_token_pgp_key=None, stored_shares=None, recovery_shares=None, recovery_threshold=None, recovery_pgp_keys=None): """Initialize a new Vault. The Vault must not have been previously initialized. The recovery o...
0.00571
def monthdatescalendar(cls, year, month): """ Returns a list of week in a month. A week is a list of NepDate objects """ weeks = [] week = [] for day in NepCal.itermonthdates(year, month): week.append(day) if len(week) == 7: weeks.append(week) ...
0.00716
def predict(self, X): """ Predict if a particular sample is an outlier or not. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix ...
0.004624
def connectionLost(self, reason): """Called when the connection is lost to the server.""" self.factory.loader.db.session.commit() if reactor.running: reactor.stop()
0.01
def show_experiment_info(): '''show experiment information in monitor''' experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment_dict: print('There is no experiment running...') exit(1) update_experiment() experiment_id_list =...
0.005151
def _combine_sample_regions_batch(batch, items): """Combine sample regions within a group of batched samples. """ config = items[0]["config"] work_dir = utils.safe_makedir(os.path.join(items[0]["dirs"]["work"], "regions")) analysis_file = os.path.join(work_dir, "%s-analysis_blocks.bed" % batch) ...
0.005319
def print_children(data_file, group='/'): """Print all the sub-groups in `group` and leaf-nodes children of `group`. Parameters: data_file (pytables HDF5 file object): the data file to print group (string): path name of the group to be printed. Default: '/', the root node. """ ...
0.007547
def twos_comp_repr(val, bitwidth): """ Converts a value to it's two's-complement (positive) integer representation using a given bitwidth (only converts the value if it is negative). For use with Simulation.step() etc. in passing negative numbers, which it does not accept """ correctbw = abs(val...
0.005607
def textify(self, nums:Collection[int], sep=' ') -> List[str]: "Convert a list of `nums` to their tokens." return sep.join([self.itos[i] for i in nums]) if sep is not None else [self.itos[i] for i in nums]
0.0181
def db_log(self, transition, from_state, instance, *args, **kwargs): """Logs the transition into the database.""" if self.log_model: model_class = self._get_log_model_class() extras = {} for db_field, transition_arg, default in model_class.EXTRA_LOG_ATTRIBUTES: ...
0.004702
def exec(self, container: Container, command: str, context: Optional[str] = None, stdout: bool = True, stderr: bool = False, time_limit: Optional[int] = None ) -> ExecResponse: """ Executes a given command inside ...
0.005053
def smart_open(filename: str, mode: str = "rt", ftype: str = "auto", errors: str = 'replace'): """ Returns a file descriptor for filename with UTF-8 encoding. If mode is "rt", file is opened read-only. If ftype is "auto", uses gzip iff filename endswith .gz. If ftype is {"gzip","gz"}, uses gzip. ...
0.004643
def fetch_metric(self, metric, start, end, tags={}, aggregator="sum", downsample=None, ms_resolution=True): """Fetch time series data from OpenTSDB Parameters: metric: A string representing a valid OpenTSDB metric. tags: A dict mapping ta...
0.001876
def transform_courserun_schedule(self, content_metadata_item): """ Return the schedule of the courseun content item. """ start = content_metadata_item.get('start') or UNIX_MIN_DATE_STRING end = content_metadata_item.get('end') or UNIX_MAX_DATE_STRING return [{ ...
0.00396
def get_vary_headers(self, request, response): """ Hook for patching the vary header """ headers = [] accessed = False try: accessed = request.session.accessed except AttributeError: pass if accessed: headers.append("C...
0.005714
def _new_point(self, loglstar, logvol): """Propose points until a new point that satisfies the log-likelihood constraint `loglstar` is found.""" ncall, nupdate = 0, 0 while True: # Get the next point from the queue u, v, logl, nc, blob = self._get_point_value(log...
0.001366
def to_dict(self): """Convert to a ``dict`` Subclasses can override this function. Returns: Python dict with keys set from this Entity. """ entity_dict = {} for field, val in six.iteritems(self._fields): if field.multiple: if val...
0.002782
def minhash(self, v): '''Create a new weighted MinHash given a weighted Jaccard vector. Each dimension is an integer frequency of the corresponding element in the multi-set represented by the vector. Args: v (numpy.array): The Jaccard vector. ''' if...
0.003894
def searchlast(self,n=10): """Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.""" solutions = deque([], n) for solution in self: solutions.append(solution) return...
0.015152