code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def datapath(self): path = self._fields['path'] if not path: path = self.fetch('directory') if path and not self._fields['is_multi_file']: path = os.path.join(path, self._fields['name']) return os.path.expanduser(fmt.to_unicode(path))
Get an item's data path.
def as_odict(self): if hasattr(self, 'cust_odict'): return self.cust_odict if hasattr(self, 'attr_check'): self.attr_check() odc = odict() for attr in self.attrorder: odc[attr] = getattr(self, attr) return odc
returns an odict version of the object, based on it's attributes
def create_backend(self, service_id, version_number, name, address, use_ssl=False, port=80, connect_timeout=1000, first_byte_timeout=15000, between_bytes_timeout=10000, error_threshold=0, max_conn=20, weight=100, auto_loadbalance=False, shield=None, request_condition=None, healthcheck...
Create a backend for a particular service and version.
def copy(self, src_fs, src_path, dst_fs, dst_path): if self.queue is None: copy_file_internal(src_fs, src_path, dst_fs, dst_path) else: src_file = src_fs.openbin(src_path, "r") try: dst_file = dst_fs.openbin(dst_path, "w") except Exception:...
Copy a file from one fs to another.
def runlist_view(name, **kwargs): ctx = Context(**kwargs) ctx.execute_action('runlist:view', **{ 'storage': ctx.repo.create_secure_service('storage'), 'name': name })
Show configuration content for a specified runlist.
def decode_token(self, token): key = current_app.secret_key if key is None: if current_app.debug: current_app.logger.debug("app.secret_key not set") return None try: return jwt.decode( token, key, algorithms=[sel...
Decode Authorization token, return None if token invalid
def deserialize_number(s, fmt=SER_BINARY): ret = gmpy.mpz(0) if fmt == SER_BINARY: if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") for c in s: ...
Deserializes a number from a string `s' in format `fmt'
def setup_observations(self): obs_methods = [self.setup_water_budget_obs,self.setup_hyd, self.setup_smp,self.setup_hob,self.setup_hds, self.setup_sfr_obs] obs_types = ["mflist water budget obs","hyd file", "external obs-sim smp files","h...
main entry point for setting up observations
def disk2ram(self): values = self.series self.deactivate_disk() self.ramflag = True self.__set_array(values) self.update_fastaccess()
Move internal data from disk to RAM.
def rpc_get_docstring(self, filename, source, offset): return self._call_backend("rpc_get_docstring", None, filename, get_source(source), offset)
Get the docstring for the symbol at the offset.
def run(self): install.run(self) spath = os.path.join(self.install_scripts, 'pygubu') for ext in ('.py', '.pyw'): filename = spath + ext if os.path.exists(filename): os.remove(filename) if platform.system() == 'Windows': spath = os.path...
Run parent install, and then save the install dir in the script.
def _serialize_object(self, response_data, request): if self._is_doc_request(request): return response_data else: return super(DocumentedResource, self)._serialize_object( response_data, request)
Override to not serialize doc responses.
def evaluate(molecules, ensemble_chunk, sort_order, options, output_queue=None): results = {} for ensemble in ensemble_chunk: results[ensemble] = calculate_performance(molecules, ensemble, sort_order, options) if output_queue is not None: output_queue.put(results) else: return re...
Evaluate VS performance of each ensemble in ensemble_chunk
def flat_data(self): def flat_field(value): try: value.flat_data() return value except AttributeError: return value modified_dict = self.__original_data__ modified_dict.update(self.__modified_data__) self.__original_...
Pass all the data from modified_data to original_data
def cost_min2(self, alpha): n = self.V.dim() ax = alpha[:n] ay = alpha[n:] q2, r2 = self.get_q2_r2(ax, ay) Lax = self.L * ax Lay = self.L * ay out = [ 0.5 * numpy.dot(Lax, Lax), 0.5 * numpy.dot(Lay, Lay), 0.5 * numpy.dot(q2 - 1,...
Residual formulation, Hessian is a low-rank update of the identity.
def run(self): while not self.wait(self.delay()): try: logger.info('Invoking callback %s', self.callback) self.callback() except StandardError: logger.exception('Callback failed')
Run the callback periodically
def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True): if root is None: root = {} tcoords = dataset.GetPointData().GetTCoords() if tcoords: dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress) root['pointData']['activeTCoords'] = len(root...
dump vtkjs texture coordinates
def _check_voSet(orb,kwargs,funcName): if not orb._voSet and kwargs.get('vo',None) is None: warnings.warn("Method %s(.) requires vo to be given at Orbit initialization or at method evaluation; using default vo which is %f km/s" % (funcName,orb._vo), galpyWarning)
Function to check whether vo is set, because it's required for funcName
def SetCoreGRRKnowledgeBaseValues(kb, client_obj): client_schema = client_obj.Schema kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.FQDN, "")) if not kb.fqdn: kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.HOSTNAME, "")) versions = client_obj.Get(client_schema.OS_VERSION) if versions...
Set core values from GRR into the knowledgebase.
def execute(self): self.prepare_models() self.prepare_worker() if self.options.print_options: self.print_options() self.run()
Main method to call to run the worker
def as_set(self, decode=False): items = self.database.smembers(self.key) return set(_decode(item) for item in items) if decode else items
Return a Python set containing all the items in the collection.
def _panel_domains(self,n=2,min_panel_size=.15,spacing=0.08,top_margin=1,bottom_margin=0): d={} for _ in range(n+1,1,-1): lower=round(bottom_margin+(min_panel_size+spacing)*(n+1-_),2) d['yaxis{0}'.format(_)]=dict(domain=(lower,lower+min_panel_size)) top=d['yaxis2']['domain'] d['yaxis2']['domain']=(top[0],...
Returns the panel domains for each axis
def _update_keymap(self, first_keycode, count): lastcode = first_keycode + count for keysym, codes in self._keymap_syms.items(): i = 0 while i < len(codes): code = codes[i][1] if code >= first_keycode and code < lastcode: del co...
Internal function, called to refresh the keymap cache.
def fetcher_factory(conf): global PROMOTERS applicable = [] if not PROMOTERS: PROMOTERS = load_promoters() for promoter in PROMOTERS: if promoter.is_applicable(conf): applicable.append((promoter.PRIORITY, promoter)) if applicable: best_match = sorted(applicable, r...
Return initialized fetcher capable of processing given conf.
def memory_error(): warning_heading = m.Heading( tr('Memory issue'), **WARNING_STYLE) warning_message = tr( 'There is not enough free memory to run this analysis.') suggestion_heading = m.Heading( tr('Suggestion'), **SUGGESTION_STYLE) suggestion = tr( 'Try zooming in to a...
Display an error when there is not enough memory.
def _empty_queue(self): while True: try: self.queue.pop() self.unused += 1 self.nqueue -= 1 except: self.nqueue = 0 break
Dump all live point proposals currently on the queue.
def to_json(self, value): if not self.is_valid(value): raise ex.SerializeException('Invalid value: {}'.format(value)) return value
Subclasses should override this method for JSON encoding.
def update(self): self.filename = self.parent.info.dataset.filename self.chan = self.parent.info.dataset.header['chan_name'] for chan in self.chan: self.idx_chan.addItem(chan)
Get info from dataset before opening dialog.
def AuthorizeUser(self, user, subject): user_set = self.authorized_users.setdefault(subject, set()) user_set.add(user)
Allow given user access to a given subject.
def settings(request): from waliki.settings import WALIKI_USE_MATHJAX return {k: v for (k, v) in locals().items() if k.startswith('WALIKI')}
inject few waliki's settings to the context to be used in templates
def do_add_item(self, args): if args.food: add_item = args.food elif args.sport: add_item = args.sport elif args.other: add_item = args.other else: add_item = 'no items' self.poutput("You added {}".format(add_item))
Add item command help
def coerce(self, value, includes=None, errors=None, resources=None, default_locale='en-US', locale=None): if includes is None: includes = [] if errors is None: errors = [] return self._coerce_block( value, includes=includes, errors=erro...
Coerces Rich Text properly.
def to_jd(year, month, day): gyear = year + 78 leap = isleap(gyear) start = gregorian.to_jd(gyear, 3, 22 - leap) if leap: Caitra = 31 else: Caitra = 30 if month == 1: jd = start + (day - 1) else: jd = start + Caitra m = month - 2 m = min(m, 5) ...
Obtain Julian day for Indian Civil date
def signup_time_future(self): now = datetime.datetime.now() return (now.date() < self.date or (self.date == now.date() and self.signup_time > now.time()))
Is the signup time in the future?
def spatialDomainNoGrid(self): self.w = np.zeros(self.xw.shape) if self.Debug: print("w = ") print(self.w.shape) for i in range(len(self.q)): if self.q[i] != 0: dist = np.abs(self.xw - self.x[i]) self.w -= self.q[i] * self.coeff * np.exp(-dist/self.alpha) * \ ...
Superposition of analytical solutions without a gridded domain
def _sync_filters(self, filters_json): for filter_json in filters_json: filter_id = filter_json['id'] self.filters[filter_id] = Filter(filter_json, self)
Populate the user's filters from a JSON encoded list.
def cancel(self, *args, **kwargs): super().cancel() for future in self.traverse(): if not future.cancelled(): future.cancel()
Manually cancel all tasks assigned to this event loop.
def as_point(row): return Point(row[COLS.X], row[COLS.Y], row[COLS.Z], row[COLS.R], int(row[COLS.TYPE]))
Create a Point from a data block row
def cleanup_event_loop(self): for task in asyncio.Task.all_tasks(loop=self.loop): if self.debug: warnings.warn('Cancelling task: %s' % task) task._log_destroy_pending = False task.cancel() self.loop.close() self.loop.set_exception_handler(self....
Cleanup an event loop and close it down forever.
def merge_dicts(*dicts, **kwargs): result = {} for d in dicts: result.update(d) result.update(kwargs) return result
Merges dicts and kwargs into one dict
def _request_eip(interface, vm_): params = {'Action': 'AllocateAddress'} params['Domain'] = interface.setdefault('domain', 'vpc') eips = aws.query(params, return_root=True, location=get_location(vm_), provider=get_provider(), ...
Request and return Elastic IP
def delete_nve_member(self, nexus_host, nve_int_num, vni): starttime = time.time() path_snip = snipp.PATH_VNI_UPDATE % (nve_int_num, vni) self.client.rest_delete(path_snip, nexus_host) self.capture_and_print_timeshot( starttime, "delete_nve", switch=nexus_host)
Delete a member configuration on the NVE interface.
def slides(self): sldIdLst = self._element.get_or_add_sldIdLst() self.part.rename_slide_parts([sldId.rId for sldId in sldIdLst]) return Slides(sldIdLst, self)
|Slides| object containing the slides in this presentation.
def _createbound(obj): try: kls = obj._unboundreference_() except AttributeError: kls = type(obj) unbound = _createunbound(kls) def valueget(): return obj for t in (BoundBitfieldNode, BoundStructureNode, BoundArrayNode): if isinstance(unbound, t._unboundtype): ...
Create a new BoundNode representing a given object.
def list_domains_by_service(self, service_id): content = self._fetch("/service/%s/domain" % service_id, method="GET") return map(lambda x: FastlyDomain(self, x), content)
List the domains within a service.
def _fix_valid_indices(cls, valid_indices, insertion_index, dim): indices = np.array(sorted(valid_indices[dim])) slice_index = np.sum(indices <= insertion_index) indices[slice_index:] += 1 indices = np.insert(indices, slice_index, insertion_index + 1) valid_indices[dim] = indices...
Add indices for H&S inserted elements.
def _read_object(self, path): if not os.path.exists(path): return None if os.path.isdir(path): raise RuntimeError('%s is a directory, not a file.' % path) with open(path) as f: file_contents = f.read() return file_contents
read in object from file at `path`
def _replace_lines(fn, startswith, new_line): new_lines = [] for line in open(fn): if line.startswith(startswith): new_lines.append(new_line) else: new_lines.append(line) with open(fn, 'w') as f: f.write('\n'.join(new_lines))
Replace lines starting with starts_with in fn with new_line.
def decls(self) -> List[z3.ExprRef]: result = [] for internal_model in self.raw: result.extend(internal_model.decls()) return result
Get the declarations for this model
def search(self, searchTerm): if type(searchTerm)==type(''): searchTerm=SearchTerm(searchTerm) if searchTerm not in self.featpaths: matches = None if searchTerm.type != None and searchTerm.type != self.classname(): matches = self._searchInChildren(searchTerm) elif searchTerm.isAtomic(): matches ...
Returns objects matching the query.
def handle_response(self, content, target=None, single_result=True, raw=False): response = content['response'] self.check_errors(response) data = response.get('data') if is_empty(data): return data elif is_paginated(data): if 'count' in data and not data['...
Parses response, checks it.
def build_dir_tree(self, files): def helper(split_files): this_dir = {'files' : {}, 'dirs' : {}} dirs = defaultdict(list) for fle in split_files: index = fle[0]; fileinfo = fle[1] if len(index) == 1: fileinfo['path'] = inde...
Convert a flat file dict into the tree format used for storage
def parse(s): stopwatch = StopWatch() for line in s.splitlines(): if line.strip(): parts = line.split(None) name = parts[0] if name != "%": rest = (float(v) for v in parts[2:]) stopwatch.times[parts[0]].merge(Stat.build(*rest)) return stopwatch
Parse the output below to create a new StopWatch.
def walk(node, walker): method_name = '_' + node.__class__.__name__ method = getattr(walker, method_name, None) if method is not None: if isinstance(node, _ast.ImportFrom) and node.module is None: node.module = '' return method(node) for child in get_child_nodes(node): ...
Walk the syntax tree
def _find_glob_matches(in_files, metadata): reg_files = copy.deepcopy(in_files) glob_files = [] for glob_search in [x for x in metadata.keys() if "*" in x]: cur = [] for fname in in_files: if fnmatch.fnmatch(fname, "*/%s" % glob_search): cur.append(fname) ...
Group files that match by globs for merging, rather than by explicit pairs.
def split(attrs, inputs, proto_obj): split_list = attrs.get('split') if 'split' in attrs else [] new_attrs = translation_utils._fix_attribute_names(attrs, {'split' : 'num_outputs'}) if 'axis' not in attrs: new_attrs = translation_utils._add_extr...
Splits an array along a particular axis into multiple sub-arrays.
def jenkins(self): job_name = self.format['jenkins_job_name'].format(**self.data) job = {'name': job_name} return job
Generate jenkins job details.
def connected(self, client): self.clients.add(client) self._log_connected(client) self._start_watching(client) self.send_msg(client, WELCOME, (self.pickle_protocol, __version__), pickle_protocol=0) profiler = self.profiler while True: try...
Call this method when a client connected.
def _bend_cos_low(a, b, deriv): a = Vector3(6, deriv, a, (0, 1, 2)) b = Vector3(6, deriv, b, (3, 4, 5)) a /= a.norm() b /= b.norm() return dot(a, b).results()
Similar to bend_cos, but with relative vectors
def invenio_query_factory(parser=None, walkers=None): parser = parser or Main walkers = walkers or [PypegConverter()] walkers.append(ElasticSearchDSL()) def invenio_query(pattern): query = pypeg2.parse(pattern, parser, whitespace="") for walker in walkers: query = query.accep...
Create a parser returning Elastic Search DSL query instance.
def json(func): "Decorator to make JSON views simpler" def wrapper(self, request, *args, **kwargs): try: response = { "success": True, "data": func(self, request, *args, **kwargs) } except GargoyleException, exc: response = { ...
Decorator to make JSON views simpler
def reset_scan_stats(self): self._scan_event_count = 0 self._v1_scan_count = 0 self._v1_scan_response_count = 0 self._v2_scan_count = 0 self._device_scan_counts = {} self._last_reset_time = time.time()
Clears the scan event statistics and updates the last reset time
def marker_index_document_id(self): params = '%s:%s:%s' % (self.index, self.doc_type, self.update_id) return hashlib.sha1(params.encode('utf-8')).hexdigest()
Generate an id for the indicator document.
def accuracy_thresh_expand(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor: "Compute accuracy after expanding `y_true` to the size of `y_pred`." if sigmoid: y_pred = y_pred.sigmoid() return ((y_pred>thresh)==y_true[:,None].expand_as(y_pred).byte()).float().mean()
Compute accuracy after expanding `y_true` to the size of `y_pred`.
def check_config(config): "basic checks that the configuration file is valid" shortnames = [count['shortname'] for count in config['count']] if len(shortnames) != len(set(shortnames)): logger.error("error: duplicate `shortname' in count configuration.") return False return True
basic checks that the configuration file is valid
def __safe_name(self, method_name): safe_name = re.sub(r'[^\.a-zA-Z0-9_]', '', method_name) safe_name = safe_name.lstrip('_') return safe_name[0:1].lower() + safe_name[1:]
Restrict method name to a-zA-Z0-9_, first char lowercase.
def add_task_to_job(self, job_or_job_name, task_command, task_name=None, **kwargs): if isinstance(job_or_job_name, Job): job = job_or_job_name else: job = self.get_job(job_or_job_name) if not job: raise DagobahError('job %s does not exi...
Add a task to a job owned by the Dagobah instance.
def getL2Representations(self): return [set(L2.getSelf()._pooler.getActiveCells()) for L2 in self.L2Regions]
Returns the active representation in L2.
def run_file(self, path, all_errors_exit=True): path = fixpath(path) with self.handling_errors(all_errors_exit): module_vars = run_file(path) self.vars.update(module_vars) self.store("from " + splitname(path)[1] + " import *")
Execute a Python file.
def image_box(center, shape, box): return tuple(slice_create(c, b, stop=s) for c, s, b in zip(center, shape, box))
Create a region of size box, around a center in a image of shape.
def write_file(data, outfilename): if not data: return False try: with open(outfilename, 'w') as outfile: for line in data: if line: outfile.write(line) return True except (OSError, IOError) as err: sys.stderr.write('An error oc...
Write a single file to disk.
def find_name(): name_file = read_file('__init__.py') name_match = re.search(r'^__package_name__ = ["\']([^"\']*)["\']', name_file, re.M) if name_match: return name_match.group(1) raise RuntimeError('Unable to find name string.')
Only define name in one place
def _merge_inplace(self, other): if other is None: yield else: priority_vars = OrderedDict( kv for kv in self.variables.items() if kv[0] not in self.dims) variables = merge_coords_for_inplace_math( [self.variables, other.variables], pri...
For use with in-place binary arithmetic.
def auto_complete(self, term, state=None, postcode=None, max_results=None): self._validate_state(state) params = {"term": term, "state": state, "postcode": postcode, "max_results": max_results or self.max_results} return self._make_request('/address/autoComplete', params)
Gets a list of addresses that begin with the given term.
def insert_child(self, child_pid): self._check_child_limits(child_pid) try: with db.session.begin_nested(): if not isinstance(child_pid, PersistentIdentifier): child_pid = resolve_pid(child_pid) return PIDRelation.create( ...
Add the given PID to the list of children PIDs.
def _tool_classpath(self, tool, products, scheduler): classpath = self.tool_classpath_from_products(products, self.versioned_tool_name(tool, self.version), scope=self.options_scope) classpath = tuple(fast_relpath...
Return the proper classpath based on products and scala version.
def could_be(self, other): if type(other) is not type(self): return NotImplemented if self == other: return True for attr in ['title', 'firstname', 'middlename', 'nickname', 'prefix', 'lastname', 'suffix']: if attr not in self or attr not in other: ...
Return True if the other PersonName is not explicitly inconsistent.
def _all_keys(self): file_keys = [self._filename_to_key(fn) for fn in self._all_filenames()] if self._sync: return set(file_keys) else: return set(file_keys + list(self._buffer))
Return a list of all encoded key names.
def overlap_summary(self): olaps = self.compute_overlaps() table = [["5%: ",np.percentile(olaps,5)], ["25%: ",np.percentile(olaps,25)], ["50%: ",np.percentile(olaps,50)], ["75%: ",np.percentile(olaps,75)], ["95%: ",np.percentile(olaps,...
print summary of reconstruction overlaps
def remove_node(self, node): if _debug: Network._debug("remove_node %r", node) self.nodes.remove(node) node.lan = None
Remove a node from this network.
def getEvent(self, dev_id, starttime, endtime): path = 'device/%s/event?startTime=%s&endTime=%s' % \ (dev_id, starttime, endtime) return self.rachio.get(path)
Retrieve events for a device entity.
def filter_dup(lst, lists): max_rank = len(lst) + 1 dct = to_ranked_dict(lst) dicts = [to_ranked_dict(l) for l in lists] return [word for word in lst if all(dct[word] < dct2.get(word, max_rank) for dct2 in dicts)]
filters lst to only include terms that don't have lower rank in another list
def set(self, val): msg = ExtendedSend( address=self._address, commandtuple=COMMAND_THERMOSTAT_SET_COOL_SETPOINT_0X6C_NONE, cmd2=int(val * 2), userdata=Userdata()) msg.set_checksum() self._send_method(msg, self._set_cool_point_ack)
Set the cool set point.
def _send_event(self, title, text, tags, event_type, aggregation_key, severity='info'): event_dict = { 'timestamp': int(time()), 'source_type_name': self.SOURCE_TYPE_NAME, 'msg_title': title, 'event_type': event_type, 'alert_type': severity, ...
Emit an event to the Datadog Event Stream.
def _convert_agent_types(ind, to_string=False, **kwargs): if to_string: return serialize_distribution(ind, **kwargs) return deserialize_distribution(ind, **kwargs)
Convenience method to allow specifying agents by class or class name.
def _parse_result(self, ok, match, fh=None): peek_match = None try: if fh is not None and self._try_peeking: peek_match = self.yaml_block_start.match(fh.peek()) except StopIteration: pass if peek_match is None: return Result( ...
Parse a matching result line into a result instance.
def threeprime_plot(self): data = dict() dict_to_add = dict() for key in self.threepGtoAfreq_data: pos = list(range(1,len(self.threepGtoAfreq_data.get(key)))) tmp = [i * 100.0 for i in self.threepGtoAfreq_data.get(key)] tuples = list(zip(pos,tmp)) ...
Generate a 3' G>A linegraph plot
def placeFiles(ftp, path): for name in os.listdir(path): if name != "config.py" and name != "config.pyc" and name != "templates" and name != "content": localpath = os.path.join(path, name) if os.path.isfile(localpath): print("STOR", name, localpath) ft...
Upload the built files to FTP
def put_field(self, field): fpath = self.fields_json_path(field) with InterProcessLock(fpath + self.LOCK_SUFFIX, logger=logger): try: with open(fpath, 'r') as f: dct = json.load(f) except IOError as e: if e.errno == errno.ENOENT...
Inserts or updates a field in the repository
def ctrl_int_cmd(self, cmd): cmd_url = 'ctrl-int/1/{}?[AUTH]&prompt-id=0'.format(cmd) return self.daap.post(cmd_url)
Perform a "ctrl-int" command.
def _check_all_metadata_found(metadata, items): for name in metadata: seen = False for sample in items: check_file = sample["files"][0] if sample.get("files") else sample["vrn_file"] if isinstance(name, (tuple, list)): if check_file.find(name[0]) > -1: ...
Print warning if samples in CSV file are missing in folder
def reset(self): self.context = pyblish.api.Context() self.plugins = pyblish.api.discover() self.was_discovered.emit() self.pair_generator = None self.current_pair = (None, None) self.current_error = None self.processing = { "nextOrder": None, ...
Discover plug-ins and run collection
def make_module_to_builder_dict(datasets=None): module_to_builder = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list))) if datasets: builders = [tfds.builder(name) for name in datasets] else: builders = [ tfds.builder(name) for ...
Get all builders organized by module in nested dicts.
def increment(self, gold_set, test_set): "Add examples from sets." self.gold += len(gold_set) self.test += len(test_set) self.correct += len(gold_set & test_set)
Add examples from sets.
def engineering(value, precision=3, prefix=False, prefixes=SI): display = decimal.Context(prec=precision) value = decimal.Decimal(value).normalize(context=display) string = value.to_eng_string() if prefix: prefixes = {e(exponent): prefix for exponent, prefix in prefixes.items()} return r...
Convert a number to engineering notation.
def negate_gate(wordlen, input='x', output='~x'): neg = bitwise_negate(wordlen, input, "tmp") inc = inc_gate(wordlen, "tmp", output) return neg >> inc
Implements two's complement negation.
def cause_repertoire(self, mechanism, purview): return self.repertoire(Direction.CAUSE, mechanism, purview)
Return the cause repertoire.
def _put_many(self, items): for item in items: if not isinstance(item, self._item_class): raise RuntimeError('Items mismatch for %s and %s' % (self._item_class, type(item))) self._put_one(item)
store items in sqlite database
def check_drives(drivename, drivestatus): return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format( drivename, DISK_STATES[int(drivestatus)]["result"])
check the drive status
def list_from_metadata(cls, url, metadata): key = cls._get_key(url) metadata = Metadata(**metadata) ct = cls._get_create_time(key) time_buckets = cls.get_time_buckets_from_metadata(metadata) return [cls(url, metadata, t, ct, key.size) for t in time_buckets]
return a list of DatalakeRecords for the url and metadata