text
stringlengths
78
104k
score
float64
0
0.18
def _build_instance_count_and_type_args(self, master_instance_type, slave_instance_type, num_instances): """ Takes a master instance type (string), a slave instance type (string), and a number of instances. Returns a comparable dict for use in ...
0.011628
def bytes_iter(obj): """Turn a complex object into an iterator of byte strings. The resulting iterator can be used for caching. """ if obj is None: return elif isinstance(obj, six.binary_type): yield obj elif isinstance(obj, six.string_types): yield obj elif isinstanc...
0.000973
def FromStream(cls, stream): """Create a DataStreamSelector from a DataStream. Args: stream (DataStream): The data stream that we want to convert. """ if stream.system: specifier = DataStreamSelector.MatchSystemOnly else: specifier = DataStre...
0.007009
def publish_ap(self, apid, args): """绑定自定义域名 绑定用户自定义的域名,仅对公网域名模式接入点生效。 Args: - apid: 接入点ID - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"...
0.003976
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'name') and self.name is not None: _dict['name...
0.001147
def new_knitting_pattern_set_loader(specification=DefaultSpecification()): """Create a loader for a knitting pattern set. :param specification: a :class:`specification <knittingpattern.ParsingSpecification.ParsingSpecification>` for the knitting pattern set, default :class:`DefaultSpecificati...
0.002132
def coordination_geometry_symmetry_measures_standard(self, coordination_geometry, algo, points_perfect=None, ...
0.004257
def _set_fcoe_map_cee_map(self, v, load=False): """ Setter method for fcoe_map_cee_map, mapped from YANG variable /fcoe/fcoe_map/fcoe_map_cee_map (container) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe_map_cee_map is considered as a private method. Backends ...
0.005411
def require_flush(fun): """Decorator for methods that need to query security. It ensures all security related operations are flushed to DB, but avoids unneeded flushes. """ @wraps(fun) def ensure_flushed(service, *args, **kwargs): if service.app_state.needs_db_flush: sessio...
0.001377
def get_statement_queries(stmts, **params): """Get queries used to search based on a statement. In addition to the stmts, you can enter any parameters standard to the query. See https://github.com/indralab/indra_db/rest_api for a full list. Parameters ---------- stmts : list[Statement] ...
0.000678
def generate_read_batches( self, table, columns, keyset, index="", partition_size_bytes=None, max_partitions=None, ): """Start a partitioned batch read operation. Uses the ``PartitionRead`` API request to initiate the partitioned read....
0.001462
def to_json_object(self): """Returns a dict representation that can be serialized to JSON.""" obj_dict = dict(namespace_start=self.namespace_start, namespace_end=self.namespace_end) if self.app is not None: obj_dict['app'] = self.app return obj_dict
0.006873
def verbose_option(default=False): """ Attaches the option ``verbose`` with its *default* value to the keyword arguments when the option does not exist. All positional arguments and keyword arguments are forwarded unchanged. """ def decorator(method): @wraps(method) def wrapper(*arg...
0.001898
def _init_edges(self, dst_srcs_list): """Create all GO edges given a list of (dst, srcs).""" from goatools.gosubdag.go_paths import get_paths_goobjs, paths2edges edges_all = set() goid_all = set() go2obj = self.go2obj for dst, srcs in dst_srcs_list: go2obj_src...
0.004471
def set_start_timestamp(self, start_timestamp=None): """stub""" if start_timestamp is None: raise NullArgument() if self.get_start_timestamp_metadata().is_read_only(): raise NoAccess() if not self.my_osid_object_form._is_valid_integer( start_timest...
0.004073
def parse_docstring(self): """Parse a single docstring and return its value.""" self.log.debug( "parsing docstring, token is %r (%s)", self.current.kind, self.current.value ) while self.current.kind in (tk.COMMENT, tk.NEWLINE, tk.NL): self.stream.move() ...
0.004666
def _repo_packages(self, args, search=False): ''' List packages for one or more configured repos ''' packages = [] repo_metadata = self._get_repo_metadata() for repo in repo_metadata: for pkg in repo_metadata[repo]['packages']: if args[1] in pk...
0.005413
def ensure_time_avg_has_cf_metadata(ds): """Add time interval length and bounds coordinates for time avg data. If the Dataset or DataArray contains time average data, enforce that there are coordinates that track the lower and upper bounds of the time intervals, and that there is a coordinate that trac...
0.000463
def create_aql_text(*args): """ Create AQL querty from string or list or dict arguments """ aql_query_text = "" for arg in args: if isinstance(arg, dict): arg = "({})".format(json.dumps(arg)) elif isinstance(arg, list): arg ...
0.006667
def createDevice(self, deviceCfg): """ Creates a measurement deviceCfg from the input configuration. :param: deviceCfg: the deviceCfg cfg. :param: handlers: the loaded handlers. :return: the constructed deviceCfg. """ ioCfg = deviceCfg['io'] type = deviceC...
0.003465
def _check_update_fw(self, tenant_id, drvr_name): """Update the Firewall config by calling the driver. This function calls the device manager routine to update the device with modified FW cfg. """ if self.fwid_attr[tenant_id].is_fw_complete(): fw_dict = self.fwid_att...
0.004739
def TRCCp_integral(T, a0, a1, a2, a3, a4, a5, a6, a7, I=0): r'''Integrates ideal gas heat capacity using the model developed in [1]_. Best used as a delta only. The difference in enthalpy with respect to 0 K is given by: .. math:: \frac{H(T) - H^{ref}}{RT} = a_0 + a_1x(a_2)/(a_2T) + I/T + h(T)...
0.005081
def updateGroupResponse(self, group, vendorSpecific=None): """CNIdentity.addGroupMembers(session, groupName, members) → boolean https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNIdentity.addGroupMembers. Args: group: vendorSpecific: ...
0.00409
def update_beliefs(self, corpus_id): """Return updated belief scores for a given corpus. Parameters ---------- corpus_id : str The ID of the corpus for which beliefs are to be updated. Returns ------- dict A dictionary of belief scores wi...
0.002041
def _check_for_misplaced(xs, subkey, other_keys): """Ensure configuration keys are not incorrectly nested under other keys. """ problems = [] for x in xs: check_dict = x.get(subkey, {}) for to_check in other_keys: if to_check in check_dict: problems.append((x[...
0.006435
def filter(self, filter_func): """Return a new SampleCollection containing only samples meeting the filter criteria. Will pass any kwargs (e.g., field or skip_missing) used when instantiating the current class on to the new SampleCollection that is returned. Parameters --------...
0.008821
def _eval_density(means, variances,observed_values, distribution): """ Calculates gamma/lognormal/normal pdf given mean variance, x where x is the experimental species number measured at a particular timepoint. Returns ln(pdf) :param mean: mean :param var: variance :param observed_values: experi...
0.005133
def do_help(self, line): """Displays help information.""" print "" print "Perfdump CLI provides a handful of simple ways to query your" print "performance data." print "" print "The simplest queries are of the form:" print "" print "\t[slowest|fastest] [te...
0.002513
def run_lda(abstracts, n_topics=50, n_words=31, n_iters=1000, alpha=None, beta=0.001): """ Perform topic modeling using Latent Dirichlet Allocation with the Java toolbox MALLET. Args: abstracts: A pandas DataFrame with two columns ('pmid' and 'abstract') containing ...
0.000152
def get_staff_url(self): """ Return the Admin URL for the current view. By default, it uses the :func:`get_staff_object` function to base the URL on. """ object = self.get_staff_object() if object is not None: # View is likely using SingleObjectMixin ...
0.00639
def get_keybindings(self, mode): """look up keybindings from `MODE-maps` sections :param mode: mode identifier :type mode: str :returns: dictionaries of key-cmd for global and specific mode :rtype: 2-tuple of dicts """ globalmaps, modemaps = {}, {} bindin...
0.001567
def move_datetime_year(dt, direction, num_shifts): """ Move datetime 1 year in the chosen direction. unit is a no-op, to keep the API the same as the day case """ delta = relativedelta(years=+num_shifts) return _move_datetime(dt, direction, delta)
0.00369
def isJournal(self, dbname = abrevDBname, manualDB = manualDBname, returnDict ='both', checkIfExcluded = False): """Returns `True` if the `Citation`'s `journal` field is a journal abbreviation from the WOS listing found at [http://images.webofknowledge.com/WOK46/help/WOS/A_abrvjt.html](http://images.webofknowle...
0.010565
def result(self, timeout=None): """ Waits up to timeout for the result the threaded job. Returns immediately the result if the job has already been done. :param timeout: The maximum time to wait for a result (in seconds) :raise OSError: The timeout raised before the job finished...
0.003636
def _parse_environment(env_str): ''' Parsing template ''' try: env = salt.utils.yaml.safe_load(env_str) except salt.utils.yaml.YAMLError as exc: raise ValueError(six.text_type(exc)) else: if env is None: env = {} elif not isinstance(env, dict): ...
0.003425
def plugins(flags=None): """ Returns the plugins registered for the exporter. If the optional flags are set then only plugins with the inputed flags will be returned. :param flags | <XExporter.Flags> """ XExporter.init() p...
0.008621
def touch(self, filepath): """Touches the specified file so that its modified time changes.""" if self.is_ssh(filepath): self._check_ssh() remotepath = self._get_remote(filepath) stdin, stdout, stderr = self.ssh.exec_command("touch {}".format(remotepath)) ...
0.007538
def remove_tenant_from_flavor(request, flavor, tenant): """Remove a tenant from the given flavor access list.""" return _nova.novaclient(request).flavor_access.remove_tenant_access( flavor=flavor, tenant=tenant)
0.004405
def print_pretty(text, **kwargs): ''' Prints using pycolorterm formatting :param text: Text with formatting :type text: string :param kwargs: Keyword args that will be passed to the print function :type kwargs: dict Example:: print_pretty('Hello {BG_RED}WORLD{END}') ''' t...
0.004454
def contains(self, key): """Checks if the specified item exists. Args: key: the key of the item to lookup. Returns: True if the item exists; False otherwise. Raises: Exception if there was an error requesting information about the item. """ try: self._api.objects_get(sel...
0.00998
def unitary_function(mappings: Dict[str, str]) -> np.ndarray: """ Creates a unitary transformation that maps each state to the values specified in mappings. Some (but not all) of these transformations involve a scratch qubit, so room for one is always provided. That is, if given the map...
0.00404
def format_docstring(template_="{__doc__}", *args, **kwargs): r""" Parametrized decorator for adding/changing a function docstring. For changing a already available docstring in the function, the ``"{__doc__}"`` in the template is replaced by the original function docstring. Parameters ---------- temp...
0.003003
def shutdown(self): """Shuts down the scheduler and immediately end all pending callbacks. """ # Drop all pending item from the executor. Without this, the executor # will block until all pending items are complete, which is # undesirable. try: while True: ...
0.004396
def olympic_sprints(data_set='rogers_girolami_data'): """All olympics sprint winning times for multiple output prediction.""" X = np.zeros((0, 2)) Y = np.zeros((0, 1)) cats = {} for i, dataset in enumerate([olympic_100m_men, olympic_100m_women, ...
0.011429
def membership_vector(clusterer, points_to_predict): """Predict soft cluster membership. The result produces a vector for each point in ``points_to_predict`` that gives a probability that the given point is a member of a cluster for each of the selected clusters of the ``clusterer``. Parameters ...
0.000636
def to_yellow(self, on: bool=False): """ Change the LED to yellow (on or off) :param on: True or False :return: None """ self._on = on if on: self._load_new(led_yellow_on) if self._toggle_on_click: self._canvas.bind('<Butto...
0.006678
def copy(src_uri, dest_base_uri, config_path=None, progressbar=None): """Copy a dataset to another location. :param src_uri: URI of dataset to be copied :param dest_base_uri: base of URI for copy target :param config_path: path to dtool configuration file :returns: URI of new dataset """ da...
0.001603
def _annotate_with_past_uses(cls, queryset, user): ''' Annotates the queryset with a usage count for that discount claus by the given user. ''' if queryset.model == conditions.DiscountForCategory: matches = ( Q(category=F('discount__discountitem__product__category'))...
0.001923
def fetch_entries(self): """Fetch data and parse it to build a list of broadcast entries.""" current_time = '' data = [] for row in self.get_rows(): # Stop fetching data if limit has been met if exceeded_limit(self.limit, len(data)): break ...
0.001692
def superReadText(filepath, **kwargs): """ A wrapper to superReadCSV which wraps pandas.read_csv(). The benefit of using this function is that it automatically identifies the column separator. .tsv files are assumed to have a \t (tab) separation .csv files are assumed to have a comma separation....
0.001056
def fast_sync_sign_snapshot( snapshot_path, private_key, first=False ): """ Append a signature to the end of a snapshot path with the given private key. If first is True, then don't expect the signature trailer. Return True on success Return False on error """ if not os.path.exists...
0.006927
def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr]: """Search for a tag among direct children of the s-expression.""" _assert_valid_sexpr(sexpr) for child in sexpr[1:]: if _is_sexpr(child) and child[0] in tags: return child return None
0.003546
def _process_uniprot_ids(self, limit=None): """ This method processes the mappings from ZFIN gene IDs to UniProtKB IDs. Triples created: <zfin_gene_id> a class <zfin_gene_id> rdfs:label gene_symbol <uniprot_id> is an Individual <uniprot_id> has type <polypeptide...
0.002242
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a WCNF+ formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. ...
0.00247
def from_deformation(cls, deformation): """ Factory method that returns a Strain object from a deformation gradient Args: deformation (3x3 array-like): """ dfm = Deformation(deformation) return cls(0.5 * (np.dot(dfm.trans, dfm) - np.eye(3)))
0.006452
def add_highlights_docs(docs): """ "highlight": { "knowledge_graph.title.value": [ "Before 1 January 2018, will <em>South</em> <em>Korea</em> file a World Trade Organization dispute against the United States related to solar panels?" ] } """ if not...
0.004922
def json_decode(s: str) -> Any: """ Decodes an object from JSON using our custom decoder. """ try: return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s) except json.JSONDecodeError: log.warning("Failed to decode JSON (returning None): {!r}", s) return None
0.003155
def get_scheduling_block_event(): """Return the latest Scheduling Block event""" event = DB.rpoplpush('scheduling_block_events', 'scheduling_block_event_history') if event: event = json.loads(event.decode('utf-8')) return event
0.003623
def connect(self, action=None, method=None, **kwargs): """ Create a <Connect> element :param action: Action URL :param method: Action URL method :param kwargs: additional attributes :returns: <Connect> element """ return self.nest(Connect(action=action, ...
0.005797
def get_kmgraph_meta(mapper_summary): """ Extract info from mapper summary to be displayed below the graph plot """ d = mapper_summary["custom_meta"] meta = ( "<b>N_cubes:</b> " + str(d["n_cubes"]) + " <b>Perc_overlap:</b> " + str(d["perc_overlap"]) ) me...
0.001524
def neg_loglik(self, beta): """ Creates negative loglikelihood of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- - Negative loglikelihood """ Z = np....
0.012141
def make_exttrig_file(cp, ifos, sci_seg, out_dir): ''' Make an ExtTrig xml file containing information on the external trigger Parameters ---------- cp : pycbc.workflow.configuration.WorkflowConfigParser object The parsed configuration options of a pycbc.workflow.core.Workflow. ifos : str ...
0.004167
def resample(self, sampling_rate=None, variables=None, force_dense=False, in_place=False, kind='linear'): ''' Resample all dense variables (and optionally, sparse ones) to the specified sampling rate. Args: sampling_rate (int, float): Target sampling rate (in Hz). I...
0.001576
def _update_persistent_boot(self, device_type=[], persistent=False): """Changes the persistent boot device order in BIOS boot mode for host Note: It uses first boot device from the device_type and ignores rest. :param device_type: ordered list of boot devices :param persistent: Boolean...
0.000817
def _post(self, *args, **kwargs): """ Make a POST request. """ data = self._default_data() data.update(kwargs.get('data') or {}) kwargs['data'] = data return self._request(requests.post, *args, **kwargs)
0.007722
def pickByDistribution(distribution, r=None): """ Pick a value according to the provided distribution. Example: :: pickByDistribution([.2, .1]) Returns 0 two thirds of the time and 1 one third of the time. :param distribution: Probability distribution. Need not be normalized. :param r: Instance o...
0.010889
def cmd_list(self, argv, help): """Return a list of various things""" parser = argparse.ArgumentParser( prog="%s list" % self.progname, description=help, ) parser.add_argument("list", nargs=1, metavar="listname", ...
0.002642
def set_ref(self, ref_key, ref_id): """ Using a ref key and ref id set the reference to the appropriate resource type. """ if ref_key == 'NETWORK': self.network_id = ref_id elif ref_key == 'NODE': self.node_id = ref_id elif ref_key ...
0.004545
def augment(self, session, parent, addendum): ''' Augments a DATASET with some calcs NB: this is the PUBLIC method @returns error ''' parent_calc = session.query(model.Calculation).get(parent) if not parent_calc or not parent_calc.siblings_count: retur...
0.006328
def send_file_to_host(src_filename, dst_file, filesize): """Function which runs on the pyboard. Matches up with recv_file_from_remote.""" import sys import ubinascii try: with open(src_filename, 'rb') as src_file: bytes_remaining = filesize if HAS_BUFFER: ...
0.002553
def _iterate_namespace_models(self, **kwargs) -> Iterable: """Return an iterator over the models to be converted to the namespace.""" return tqdm( self._get_query(self.namespace_model), total=self._count_model(self.namespace_model), **kwargs )
0.009901
def put(self, thing_id='0', property_name=None): """ Handle a PUT request. thing_id -- ID of the thing this request is for property_name -- the name of the property from the URL path """ thing = self.get_thing(thing_id) if thing is None: self.set_stat...
0.00191
def format (self, record): """Returns the given LogRecord as formatted text.""" record.hostname = self.hostname return logging.Formatter.format(self, record)
0.016575
def cast_to_number_or_bool(inputstr): """Cast a string to int, float or bool. Return original string if it can't be converted. Scientific expression is converted into float. """ if inputstr.strip().lower() == "true": return True elif inputstr.strip().lower() == "false": return F...
0.004098
def p_save_data(p): """ statement : SAVE expr DATA | SAVE expr DATA ID | SAVE expr DATA ID LP RP """ if p[2].type_ != TYPE.string: api.errmsg.syntax_error_expected_string(p.lineno(1), p[2].type_) if len(p) != 4: entry = SYMBOL_TABLE.access_id(p[4], ...
0.001805
def convert_sub(sub): """Convert BEL1 sub() to BEL2 var()""" args = sub.args (ref_aa, pos, new_aa) = args parent_fn_name = sub.parent_function.name_short prefix_list = {"p": "p.", "r": "r.", "g": "c."} prefix = prefix_list[parent_fn_name] new_var_arg = f'"{prefix}{spec["namespaces"]["Amin...
0.003604
def collect(self): """ Collect and publish metrics """ stats = self.parse_stats_file(self.config["status_path"]) if len(stats) == 0: return {} elif "info" not in stats.keys(): return {} elif "programstatus" not in stats.keys(): ...
0.002193
def _set_compression(self, value): """ May be used to compress PDF files. Code is more readable for testing and inspection if not compressed. Requires a boolean. """ if isinstance(value, bool): self.compression = value else: raise Exception( ...
0.007752
def join(self, *colrs, **colorkwargs): """ Like str.join, except it returns a Colr. Arguments: colrs : One or more Colrs. If a list or tuple is passed as an argument it will be flattened. Keyword Arguments: fore, back, style... ...
0.002047
def validate(self, messages): """Returns True if the fields are valid according to the SPDX standard. Appends user friendly messages to the messages parameter. """ messages = self.validate_creators(messages) messages = self.validate_created(messages) return messages
0.006349
def get_lib_ffi_shared(libpath, c_hdr): ''' libpath-->str: shared library filename with optional path c_hdr-->str: C-style header definitions for functions to wrap Returns-->(ffi, lib) ''' lib = SharedLibWrapper(libpath, c_hdr) ffi = lib.ffi return (ffi, lib)
0.003436
def kpoints(self): """ k_product, default to 50, is kpoint number * length for a & b directions, also for c direction in bulk calculations Automatic mesh & Gamma is the default setting. """ # To get input sets, the input structure has to has the same number #...
0.00185
def delete(cls, cert_id, background=False): """ Delete a certificate.""" result = cls.call('cert.delete', cert_id) if background: return result cls.echo("Deleting your certificate.") cls.display_progress(result) cls.echo('Your certificate %s has been deleted...
0.005618
def resample(sig, old=1, new=1, order=3, zero=0.): """ Generic resampler based on Waring-Lagrange interpolators. Parameters ---------- sig : Input signal (any iterable). old : Time duration reference (defaults to 1, allowing percentages to the ``new`` keyword argument). This can be float number...
0.00823
def isexec(self, mode=stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH): """ isexec: @rtype: bool @return: Indicates whether the path points to a file or folder which has the executable flag set. Note that on systems which do not support executables flags the result m...
0.003922
def _dinic_step(graph, capacity, lev, flow, u, target, limit): """ tenter de pousser le plus de flot de u à target, sans dépasser limit """ if limit <= 0: return 0 if u == target: return limit val = 0 for v in graph[u]: residual = capacity[u][v] - flow[u][v] if le...
0.001513
def _incr_exceptions(self): """Increment the number of exceptions for the current connection.""" self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
0.01087
def trace(self, data, callback=None): """Queue data for tracing Args: data (bytearray, string): Unstructured data to trace to any connected client. callback (callable): An optional callback that will be called with a bool value of True when this d...
0.00274
def describe_event_source_mapping(UUID=None, EventSourceArn=None, FunctionName=None, region=None, key=None, keyid=None, profile=None): ''' Given an event source mapping ID or an event source ARN and FunctionName, obtain the current settings...
0.002342
def lz4f_decode(payload): """Decode payload using interoperable LZ4 framing. Requires Kafka >= 0.10""" # pylint: disable-msg=no-member ctx = lz4f.createDecompContext() data = lz4f.decompressFrame(payload, ctx) lz4f.freeDecompContext(ctx) # lz4f python module does not expose how much of the payl...
0.003945
def status(self, value): """ Property for getting or setting the bug status >>> bug.status = "REOPENED" """ if self._bug.get('id', None): if value in VALID_STATUS: self._bug['status'] = value else: raise BugExceptio...
0.003876
def upload_entities(namespace, workspace, entity_data): """Upload entities from tab-delimited string. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name entity_data (str): TSV string describing entites Swagger: https://api.firecloud.or...
0.003155
def get_params(self): "Parameters used to initialize the class" import inspect a = inspect.getargspec(self.__init__)[0] out = dict() for key in a[1:]: value = getattr(self, "_%s" % key, None) out[key] = value return out
0.006873
def wait_for_device_ready(self, timeout=None, wait_polling_interval=None, after_first=None): """Wait for the device to become ready for reliable interaction via adb. NOTE: if the device is *already* ready this method will timeout. :param timeout: Maximum time to wait for the device to become re...
0.004049
def get_DRAT(delta_x_prime, delta_y_prime, max_ptrm_check): """ Input: TRM length of best fit line (delta_x_prime), NRM length of best fit line, max_ptrm_check Output: DRAT (maximum difference produced by a ptrm check normed by best fit line), length best fit line """ L = num...
0.004662
def xinfo_help(self): """Retrieve help regarding the ``XINFO`` sub-commands""" fut = self.execute(b'XINFO', b'HELP') return wait_convert(fut, lambda l: b'\n'.join(l))
0.010526
def _write(self, ret): """ This function needs to correspond to this: https://github.com/saltstack/salt/blob/develop/salt/returners/redis_return.py#L88 """ self.redis.set('{0}:{1}'.format(ret['id'], ret['jid']), json.dumps(ret)) self.redis.lpush('{0}:{1}'.format(ret['id']...
0.006881
def _gaps_from(intervals): """ From a list of intervals extract a list of sorted gaps in the form of [(g,i)] where g is the size of the ith gap. """ sliding_window = zip(intervals, intervals[1:]) gaps = [b[0] - a[1] for a, b in sliding_window] return gaps
0.003484
def fetch(self, start=False, full_data=True): """ Get the current job data and possibly flag it as started. """ if self.id is None: return self if full_data is True: fields = None elif isinstance(full_data, dict): fields = full_data else: ...
0.003236
def _find_batch_containing_event(self, uuid): """Find the batch number that contains a certain event. Parameters: uuid -- the event uuid to search for. returns -- a batch number, or None if not found. """ if self.estore.key_exists(uuid): # Reusing alread...
0.002528