code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def colorize(txt, fg=None, bg=None): setting = '' setting += _SET_FG.format(fg) if fg else '' setting += _SET_BG.format(bg) if bg else '' return setting + str(txt) + _STYLE_RESET
Print escape codes to set the terminal color. fg and bg are indices into the color palette for the foreground and background colors.
def detect_response_encoding(response, is_html=False, peek=131072): encoding = get_heading_encoding(response) encoding = wpull.string.detect_encoding( wpull.util.peek_file(response.body, peek), encoding=encoding, is_html=is_html ) _logger.debug(__('Got encoding: {0}', encoding)) return encod...
Return the likely encoding of the response document. Args: response (Response): An instance of :class:`.http.Response`. is_html (bool): See :func:`.util.detect_encoding`. peek (int): The maximum number of bytes of the document to be analyzed. Returns: ``str``, ``None``: The cod...
def has_unclosed_brackets(text): stack = [] text = re.sub(r, '', text) for c in reversed(text): if c in '])}': stack.append(c) elif c in '[({': if stack: if ((c == '[' and stack[-1] == ']') or (c == '{' and stack[-1] == '}') or ...
Starting at the end of the string. If we find an opening bracket for which we didn't had a closing one yet, return True.
def _processing_limit(self, spec): processing_rate = float(spec.mapper.params.get("processing_rate", 0)) slice_processing_limit = -1 if processing_rate > 0: slice_processing_limit = int(math.ceil( parameters.config._SLICE_DURATION_SEC*processing_rate/ int(spec.mapper.shard_count)))...
Get the limit on the number of map calls allowed by this slice. Args: spec: a Mapreduce spec. Returns: The limit as a positive int if specified by user. -1 otherwise.
def system_requirements(): command_exists("systemd-nspawn", ["systemd-nspawn", "--version"], "Command systemd-nspawn does not seems to be present on your system" "Do you have system with systemd") command_exists( "machinectl", ["machinectl", "-...
Check if all necessary packages are installed on system :return: None or raise exception if some tooling is missing
def build_license_file(directory, spec): name, text = '', '' try: name = spec['LICENSE'] text = spec['X_MSI_LICENSE_TEXT'] except KeyError: pass if name!='' or text!='': file = open( os.path.join(directory.get_path(), 'License.rtf'), 'w' ) file.write('{\\rtf') ...
Creates a License.rtf file with the content of "X_MSI_LICENSE_TEXT" in the given directory
def do_find(self, params): for path in self._zk.find(params.path, params.match, 0): self.show_output(path)
\x1b[1mNAME\x1b[0m find - Find znodes whose path matches a given text \x1b[1mSYNOPSIS\x1b[0m find [path] [match] \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) * match: the string to match in the paths (default: '') \x1b[1mEXAMPLES\x1b[0m > find / foo /foo2 ...
def launch_processes(tests, run_module, group=True, **config): manager = multiprocessing.Manager() test_summaries = manager.dict() process_handles = [multiprocessing.Process(target=run_module.run_suite, args=(test, config[test], test_summaries)) for test in tests] for p in process...
Helper method to launch processes and sync output
def add_text(self, value): if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value)
Adds text corresponding to `value` into `self.pieces`.
def on_finish(func, handler, args, kwargs): tracing = handler.settings.get('opentracing_tracing') tracing._finish_tracing(handler) return func(*args, **kwargs)
Wrap the handler ``on_finish`` method to finish the Span for the given request, if available.
def reseed_random(seed): r = random.Random(seed) random_internal_state = r.getstate() set_random_state(random_internal_state)
Reseed factory.fuzzy's random generator.
def topil(self, **kwargs): if self.has_preview(): return pil_io.convert_image_data_to_pil(self._record, **kwargs) return None
Get PIL Image. :return: :py:class:`PIL.Image`, or `None` if the composed image is not available.
def get_bank_ids_by_item(self, item_id): mgr = self._get_provider_manager('ASSESSMENT', local=True) lookup_session = mgr.get_item_lookup_session(proxy=self._proxy) lookup_session.use_federated_bank_view() item = lookup_session.get_item(item_id) id_list = [] for idstr in i...
Gets the list of ``Bank`` ``Ids`` mapped to an ``Item``. arg: item_id (osid.id.Id): ``Id`` of an ``Item`` return: (osid.id.IdList) - list of bank ``Ids`` raise: NotFound - ``item_id`` is not found raise: NullArgument - ``item_id`` is ``null`` raise: OperationFailed - unab...
def __dict_to_BetterDict(self, attr): if type(self[attr]) == dict: self[attr] = BetterDict(self[attr]) return self[attr]
Convert the passed attr to a BetterDict if the value is a dict Returns: The new value of the passed attribute.
def _parse_binary(v, header_d): v = nullify(v) if v is None: return None if six.PY2: try: return six.binary_type(v).strip() except UnicodeEncodeError: return six.text_type(v).strip() else: try: return six.binary_type(v, 'utf-8').strip()...
Parses binary string. Note: <str> for py2 and <binary> for py3.
def get_usb_controller_count_by_type(self, type_p): if not isinstance(type_p, USBControllerType): raise TypeError("type_p can only be an instance of type USBControllerType") controllers = self._call("getUSBControllerCountByType", in_p=[type_p]) return controllers
Returns the number of USB controllers of the given type attached to the VM. in type_p of type :class:`USBControllerType` return controllers of type int
def remove(self, dist): while dist.location in self.paths: self.paths.remove(dist.location) self.dirty = True Environment.remove(self, dist)
Remove `dist` from the distribution map
def get_indicators(self, from_time=None, to_time=None, enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None, start_page=0, page_size=None): indicators_page_generator = self._get_indicators_page_generator( from_time=from_time, to_tim...
Creates a generator from the |get_indicators_page| method that returns each successive indicator as an |Indicator| object containing values for the 'value' and 'type' attributes only; all other |Indicator| object attributes will contain Null values. :param int from_time: start of time window in...
def copy2(src, dst, metadata=None, retry_params=None): common.validate_file_path(src) common.validate_file_path(dst) if metadata is None: metadata = {} copy_meta = 'COPY' else: copy_meta = 'REPLACE' metadata.update({'x-goog-copy-source': src, 'x-goog-metadata-directive': copy_me...
Copy the file content from src to dst. Args: src: /bucket/filename dst: /bucket/filename metadata: a dict of metadata for this copy. If None, old metadata is copied. For example, {'x-goog-meta-foo': 'bar'}. retry_params: An api_utils.RetryParams for this call to GCS. If None, the default ...
def _get_config(self): filename = '{}/{}'.format(self.PLUGIN_LOGDIR, CONFIG_FILENAME) modified_time = os.path.getmtime(filename) if modified_time != self.config_last_modified_time: config = read_pickle(filename, default=self.previous_config) self.previous_config = config else: config =...
Reads the config file from disk or creates a new one.
def init_prior(self, R): centers, widths = self.init_centers_widths(R) prior = np.zeros(self.K * (self.n_dim + 1)) self.set_centers(prior, centers) self.set_widths(prior, widths) self.set_prior(prior) return self
initialize prior for the subject Returns ------- TFA Returns the instance itself.
def sg_transpose(tensor, opt): r assert opt.perm is not None, 'perm is mandatory' return tf.transpose(tensor, opt.perm, name=opt.name)
r"""Permutes the dimensions according to `opt.perm`. See `tf.transpose()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: perm: A permutation of the dimensions of `tensor`. The target shape. name: If provided, replace current tensor's name. Returns...
def download_to_file(self, file): con = ConnectionManager().get_connection(self._connection_alias) return con.download_to_file(self.file, file, append_base_url=False)
Download and store the file of the sample. :param file: A file-like object to store the file.
def array(self, dimensions=None): if dimensions is None: dims = [d for d in self.kdims + self.vdims] else: dims = [self.get_dimension(d, strict=True) for d in dimensions] columns, types = [], [] for dim in dims: column = self.dimension_values(dim) ...
Convert dimension values to columnar array. Args: dimensions: List of dimensions to return Returns: Array of columns corresponding to each dimension
def make(self, cmd_args, db_args): with NamedTemporaryFile(delete=True) as f: format_file = f.name + '.bcp-format' format_args = cmd_args + ['format', NULL_FILE, '-c', '-f', format_file, '-t,'] + db_args _run_cmd(format_args) self.load(format_file) return format_file
Runs bcp FORMAT command to create a format file that will assist in creating the bulk data file
def find_suitable_period(): highest_acceptable_factor = int(math.sqrt(SIZE)) starting_point = len(VALID_CHARS) > 14 and len(VALID_CHARS) / 2 or 13 for p in range(starting_point, 7, -1) \ + range(highest_acceptable_factor, starting_point + 1, -1) \ + [6, 5, 4, 3, 2]: if SIZE %...
Automatically find a suitable period to use. Factors are best, because they will have 1 left over when dividing SIZE+1. This only needs to be run once, on import.
def report_build_messages(self): if os.getenv('TEAMCITY_VERSION'): tc_build_message_warning = " tc_build_message_error = " stdout.write(tc_build_message_warning.format(self.total_warnings)) stdout.write(tc_build_message_error.format(self.total_errors)) ...
Checks environment variables to see whether pepper8 is run under a build agent such as TeamCity and performs the adequate actions to report statistics. Will not perform any action if HTML output is written to OUTPUT_FILE and not stdout. Currently only supports TeamCity. :return: A list...
def get_next_ip(self, tenant_id, direc): if direc == 'in': subnet_dict = self.get_in_ip_addr(tenant_id) else: subnet_dict = self.get_out_ip_addr(tenant_id) if subnet_dict: return subnet_dict if direc == 'in': ip_next = self.check_allocate_i...
Retrieve the next available subnet. Given a tenant, it returns the service subnet values assigned to it based on direction.
def OnTimerToggle(self, event): if self.grid.timer_running: self.grid.timer_running = False self.grid.timer.Stop() del self.grid.timer else: self.grid.timer_running = True self.grid.timer = wx.Timer(self.grid) self.grid.timer.Start(...
Toggles the timer for updating frozen cells
def handle_presentation(msg): if msg.child_id == SYSTEM_CHILD_ID: sensorid = msg.gateway.add_sensor(msg.node_id) if sensorid is None: return None msg.gateway.sensors[msg.node_id].type = msg.sub_type msg.gateway.sensors[msg.node_id].protocol_version = msg.payload m...
Process a presentation message.
def _combine_lines(self, lines): lines = filter(None, map(lambda x: x.strip(), lines)) return '[' + ','.join(lines) + ']'
Combines a list of JSON objects into one JSON object.
def create(self, ip_dest, next_hop, **kwargs): return self._set_route(ip_dest, next_hop, **kwargs)
Create a static route Args: ip_dest (string): The ip address of the destination in the form of A.B.C.D/E next_hop (string): The next hop interface or ip address **kwargs['next_hop_ip'] (string): The next hop address on destination interface ...
def addReward(self, r=None): r = self.getReward() if r is None else r if self.discount: self.cumulativeReward += power(self.discount, self.samples) * r else: self.cumulativeReward += r
A filtered mapping towards performAction of the underlying environment.
def phase_from_polarizations(h_plus, h_cross, remove_start_phase=True): p = numpy.unwrap(numpy.arctan2(h_cross.data, h_plus.data)).astype( real_same_precision_as(h_plus)) if remove_start_phase: p += -p[0] return TimeSeries(p, delta_t=h_plus.delta_t, epoch=h_plus.start_time, copy=Fals...
Return gravitational wave phase Return the gravitation-wave phase from the h_plus and h_cross polarizations of the waveform. The returned phase is always positive and increasing with an initial phase of 0. Parameters ---------- h_plus : TimeSeries An PyCBC TmeSeries vector that contain...
def _get_interval(variant_regions, region, out_file, items): target = shared.subset_variant_regions(variant_regions, region, out_file, items) if target: if isinstance(target, six.string_types) and os.path.isfile(target): return "--interval %s" % target else: return "--int...
Retrieve interval to run analysis in. Handles no targets, BED and regions region can be a single region or list of multiple regions for multicore calling.
def save_encoder(self, name:str): "Save the encoder to `name` inside the model directory." encoder = get_model(self.model)[0] if hasattr(encoder, 'module'): encoder = encoder.module torch.save(encoder.state_dict(), self.path/self.model_dir/f'{name}.pth')
Save the encoder to `name` inside the model directory.
def terminate(self): try: self.id2sims.terminate() except: pass import glob for fname in glob.glob(self.fname + '*'): try: os.remove(fname) logger.info("deleted %s" % fname) except Exception, e: ...
Delete all files created by this index, invalidating `self`. Use with care.
def closed(lower_value, upper_value): return Interval(Interval.CLOSED, lower_value, upper_value, Interval.CLOSED)
Helper function to construct an interval object with closed lower and upper. For example: >>> closed(100.2, 800.9) [100.2, 800.9]
def draw(self): cell_background_renderer = GridCellBackgroundCairoRenderer( self.context, self.code_array, self.key, self.rect, self.view_frozen) cell_content_renderer = GridCellContentCairoRenderer( self.context, self.c...
Draws cell to context
def _parse_info(self, info_str, num_alts): result = OrderedDict() if info_str == ".": return result for entry in info_str.split(";"): if "=" not in entry: key = entry result[key] = parse_field_value(self.header.get_info_field_info(key), Tru...
Parse INFO column from string
def currentText(self): lineEdit = self.lineEdit() if lineEdit: return lineEdit.currentText() text = nativestring(super(XComboBox, self).currentText()) if not text: return self._hint return text
Returns the current text for this combobox, including the hint option \ if no text is set.
def add_native_name(self, name): self._ensure_field('name', {}) self.obj['name'].setdefault('native_names', []).append(name)
Add native name. Args: :param name: native name for the current author. :type name: string
def _runPopUp(workbench, popUp): workbench.display(popUp) d = popUp.notifyCompleted() d.addCallback(_popUpCompleted, workbench) return d
Displays the pop-up on the workbench and gets a completion notification deferred. When that fires, undisplay the pop-up and return the result of the notification deferred verbatim.
def _name_helper(name: str): name = name.rstrip() if name.endswith(('.service', '.socket', '.target')): return name return name + '.service'
default to returning a name with `.service`
def light(obj, sun): dist = angle.distance(sun.lon, obj.lon) faster = sun if sun.lonspeed > obj.lonspeed else obj if faster == sun: return LIGHT_DIMINISHING if dist < 180 else LIGHT_AUGMENTING else: return LIGHT_AUGMENTING if dist < 180 else LIGHT_DIMINISHING
Returns if an object is augmenting or diminishing light.
def gauss_box_model_deriv(x, amplitude=1.0, mean=0.0, stddev=1.0, hpix=0.5): z = (x - mean) / stddev z2 = z + hpix / stddev z1 = z - hpix / stddev da = norm.cdf(z2) - norm.cdf(z1) fp2 = norm_pdf_t(z2) fp1 = norm_pdf_t(z1) dl = -amplitude / stddev * (fp2 - fp1) ds = -amplitude / stddev * ...
Derivative of the integral of a Gaussian profile.
def difference(self, second_iterable, selector=identity): if self.closed(): raise ValueError("Attempt to call difference() on a " "closed Queryable.") if not is_iterable(second_iterable): raise TypeError("Cannot compute difference() with second_iterab...
Returns those elements which are in the source sequence which are not in the second_iterable. This method is equivalent to the Except() LINQ operator, renamed to a valid Python identifier. Note: This method uses deferred execution, but as soon as execution commences the ent...
def create_from_remote_file(self, group, snapshot=True, **args): import requests url = "http://snapshot.geneontology.org/annotations/{}.gaf.gz".format(group) r = requests.get(url, stream=True, headers={'User-Agent': get_user_agent(modules=[requests], caller_name=__name__)}) p = GafParser...
Creates from remote GAF
def emit(events, stream=None, Dumper=Dumper, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None): getvalue = None if stream is None: from StringIO import StringIO stream = StringIO() getvalue = stream.getvalue dumper = Dumper(stream, canonica...
Emit YAML parsing events into a stream. If stream is None, return the produced string instead.
def invoice_pdf(self, invoice_id): return self._create_get_request(resource=INVOICES, billomat_id=invoice_id, command=PDF)
Opens a pdf of an invoice :param invoice_id: the invoice id :return: dict
def has_tag(self, p_key, p_value=""): tags = self.fields['tags'] return p_key in tags and (p_value == "" or p_value in tags[p_key])
Returns true when there is at least one tag with the given key. If a value is passed, it will only return true when there exists a tag with the given key-value combination.
def smooth(sig, window_size): box = np.ones(window_size)/window_size return np.convolve(sig, box, mode='same')
Apply a uniform moving average filter to a signal Parameters ---------- sig : numpy array The signal to smooth. window_size : int The width of the moving average filter.
def dump(self): dumpfile = self.args.dumpfile if not dumpfile: db, env = self.get_db_args_env() dumpfile = fileutils.timestamp_filename( 'omero-database-%s' % db['name'], 'pgdump') log.info('Dumping database to %s', dumpfile) if not self.args.dry_r...
Dump the database using the postgres custom format
def mask_xdata(self) -> DataAndMetadata.DataAndMetadata: display_data_channel = self.__display_item.display_data_channel shape = display_data_channel.display_data_shape mask = numpy.zeros(shape) for graphic in self.__display_item.graphics: if isinstance(graphic, (Graphics.Spo...
Return the mask by combining any mask graphics on this data item as extended data. .. versionadded:: 1.0 Scriptable: Yes
def write(self, string): x, y = self._normalizeCursor(*self._cursor) width, height = self.get_size() wrapper = _textwrap.TextWrapper(initial_indent=(' '*x), width=width) writeLines = [] for line in string.split('\n'): if line: writeLines += wrapper.wra...
This method mimics basic file-like behaviour. Because of this method you can replace sys.stdout or sys.stderr with a :any:`Console` or :any:`Window` instance. This is a convoluted process and behaviour seen now can be excepted to change on later versions. Args: str...
def do_callback(self, pkt): callback, parser = self.get_callback_parser(pkt) if asyncio.iscoroutinefunction(callback): self.loop.call_soon_threadsafe(self._do_async_callback, callback, parser) else: self.loop.call_soon(callback, ...
Add the callback to the event loop, we use call soon because we just want it to be called at some point, but don't care when particularly.
def _find_all_simple(path): results = ( os.path.join(base, file) for base, dirs, files in os.walk(path, followlinks=True) for file in files ) return filter(os.path.isfile, results)
Find all files under 'path'
def _generate_upload_key(self, allow_timeout=False): while not self.user.nick: with ARBITRATOR.condition: ARBITRATOR.condition.wait() while True: params = { "name": self.user.nick, "room": self.room_id, "c": self.__u...
Generates a new upload key
def get_currencies(self): try: resp = get(self.endpoint) resp.raise_for_status() except exceptions.RequestException as e: self.log(logging.ERROR, "%s: Problem whilst contacting endpoint:\n%s", self.name, e) else: with open(self._cached_currency_fil...
Downloads xml currency data or if not available tries to use cached file copy
def require_auth(function): @functools.wraps(function) def wrapper(self, *args, **kwargs): if not self.access_token(): raise MissingAccessTokenError return function(self, *args, **kwargs) return wrapper
A decorator that wraps the passed in function and raises exception if access token is missing
def _from_dict(cls, _dict): args = {} if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) ] if 'entities...
Initialize a MessageRequest object from a json dictionary.
def sinter(self, keys, *args): func = lambda left, right: left.intersection(right) return self._apply_to_sets(func, "SINTER", keys, *args)
Emulate sinter.
def optimal_mapping(self, reference, hypothesis, uem=None): if uem: reference, hypothesis = self.uemify(reference, hypothesis, uem=uem) mapping = self.mapper_(hypothesis, reference) return mapping
Optimal label mapping Parameters ---------- reference : Annotation hypothesis : Annotation Reference and hypothesis diarization uem : Timeline Evaluation map Returns ------- mapping : dict Mapping between hypothesis (k...
def _nth(arr, n): try: return arr.iloc[n] except (KeyError, IndexError): return np.nan
Return the nth value of array If it is missing return NaN
def _download_file_from_drive(filename, url): confirm_token = None confirm_token = None session = requests.Session() response = session.get(url, stream=True) for k, v in response.cookies.items(): if k.startswith("download_warning"): confirm_token = v if confirm_token: ...
Download filename from google drive unless it's already in directory. Args: filename (str): Name of the file to download to (do nothing if it already exists). url (str): URL to download from.
def create_collection(self, name="collection", position=None, **kwargs): if name in self.item_names: wt_exceptions.ObjectExistsWarning.warn(name) return self[name] collection = Collection( filepath=self.filepath, parent=self.name, name=name, edit_local=True, **kwargs ...
Create a new child colleciton. Parameters ---------- name : string Unique identifier. position : integer (optional) Location to insert. Default is None (append). kwargs Additional arguments to child collection instantiation. Returns ...
def _add_to_to_ordered_dict(self, d, dataset_index, recommended_only=False): if self.doses_dropped_sessions: for key in sorted(list(self.doses_dropped_sessions.keys())): session = self.doses_dropped_sessions[key] session._add_single_session_to_to_ordered_dict(d, datas...
Save a session to an ordered dictionary. In some cases, a single session may include a final session, as well as other BMDS executions where doses were dropped. This will include all sessions.
def bulk_launch(self, jobs=None, filter=None, all=False): json = None if jobs is not None: schema = JobSchema(exclude=('id', 'status', 'package_name', 'config_name', 'device_name', 'result_id', 'user_id', 'created', 'updated', 'automatic')) jobs_json = self.service.encode(schema,...
Bulk launch a set of jobs. :param jobs: :class:`jobs.Job <jobs.Job>` list :param filter: (optional) Filters to apply as a string list. :param all: (optional) Apply to all if bool `True`.
def get_backend(name): for backend in _BACKENDS: if backend.NAME == name: return backend raise KeyError("Backend %r not available" % name)
Returns the backend by name or raises KeyError
def DeleteGRRTempFile(path): precondition.AssertType(path, Text) if not os.path.isabs(path): raise ErrorBadPath("Path must be absolute") prefix = config.CONFIG["Client.tempfile_prefix"] directories = [ GetTempDirForRoot(root) for root in config.CONFIG["Client.tempdir_roots"] ] if not _CheckIfPathI...
Delete a GRR temp file. To limit possible damage the path must be absolute and either the file must be within any of the Client.tempdir_roots or the file name must begin with Client.tempfile_prefix. Args: path: path string to file to be deleted. Raises: OSError: Permission denied, or file not found...
def list_vlans(self, datacenter=None, vlan_number=None, name=None, **kwargs): _filter = utils.NestedDict(kwargs.get('filter') or {}) if vlan_number: _filter['networkVlans']['vlanNumber'] = ( utils.query_filter(vlan_number)) if name: _filter['networkVlans']...
Display a list of all VLANs on the account. This provides a quick overview of all VLANs including information about data center residence and the number of devices attached. :param string datacenter: If specified, the list will only contain VLANs in the spec...
def cbpdnmsk_class_label_lookup(label): clsmod = {'admm': admm_cbpdn.ConvBPDNMaskDcpl, 'fista': fista_cbpdn.ConvBPDNMask} if label in clsmod: return clsmod[label] else: raise ValueError('Unknown ConvBPDNMask solver method %s' % label)
Get a ConvBPDNMask class from a label string.
def completed_task(self): if self.remote_channel and self.remote_channel.exit_status_ready(): while self.remote_channel.recv_ready(): self.stdout += self.remote_channel.recv(1024) while self.remote_channel.recv_stderr_ready(): self.stderr += self.remote_ch...
Handle wrapping up a completed task, local or remote
def locate_bar_r(icut, epos): sm = len(icut) def swap_coor(x): return sm - 1 - x def swap_line(tab): return tab[::-1] return _locate_bar_gen(icut, epos, transform1=swap_coor, transform2=swap_line)
Fine position of the right CSU bar
def get_child_for_path(self, path): path = ensure_str(path) if not path: raise InvalidPathError("%s is not a valid path" % path) as_private = True if path.startswith("M"): as_private = False if path.endswith(".pub"): as_private = False ...
Get a child for a given path. Rather than repeated calls to get_child, children can be found by a derivation path. Paths look like: m/0/1'/10 Which is the same as self.get_child(0).get_child(-1).get_child(10) Or, in other words, the 10th publicly derived chil...
def _args_checks_gen(self, decorated_function, function_spec, arg_specs): inspected_args = function_spec.args args_check = {} for i in range(len(inspected_args)): arg_name = inspected_args[i] if arg_name in arg_specs.keys(): args_check[arg_name] = self.check(arg_specs[arg_name], arg_name, decorated_func...
Generate checks for positional argument testing :param decorated_function: function decorator :param function_spec: function inspect information :param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate`) :return: internal structure, that is used by :meth:`.Verifier._args_checks...
def _extract_ocsp_certs(self, ocsp_response): status = ocsp_response['response_status'].native if status == 'successful': response_bytes = ocsp_response['response_bytes'] if response_bytes['response_type'].native == 'basic_ocsp_response': response = response_bytes...
Extracts any certificates included with an OCSP response and adds them to the certificate registry :param ocsp_response: An asn1crypto.ocsp.OCSPResponse object to look for certs inside of
def get_required_config(self): required_config = Namespace() for k, v in iteritems_breadth_first(self.required_config): required_config[k] = v try: subparser_namespaces = ( self.configman_subparsers_option.foreign_data .argparse.subprocesso...
because of the exsistance of subparsers, the configman options that correspond with argparse arguments are not a constant. We need to produce a copy of the namespace rather than the actual embedded namespace.
def filter_significant_motifs(fname, result, bg, metrics=None): sig_motifs = [] with open(fname, "w") as f: for motif in result.motifs: stats = result.stats.get( "%s_%s" % (motif.id, motif.to_consensus()), {}).get(bg, {} ) if _is_significa...
Filter significant motifs based on several statistics. Parameters ---------- fname : str Filename of output file were significant motifs will be saved. result : PredictionResult instance Contains motifs and associated statistics. bg : str Name of background type to use. ...
def collect_tokens_until(self, token_type): self.next() if self.current_token.type == token_type: return while True: yield self.current_token self.next() if self.current_token.type == token_type: return if self.current_t...
Yield the item tokens in a comma-separated tag collection.
def source_filename(self, docname: str, srcdir: str): docpath = Path(srcdir, docname) parent = docpath.parent imgpath = parent.joinpath(self.filename) if not imgpath.exists(): msg = f'Image does not exist at "{imgpath}"' raise SphinxError(msg) return imgpa...
Get the full filename to referenced image
def tile_to_path(self, tile): return os.path.join(self.cache_path, self.service, tile.path())
return full path to a tile
def calculate_sampling_decision(trace_header, recorder, sampling_req): if trace_header.sampled is not None and trace_header.sampled != '?': return trace_header.sampled elif not recorder.sampling: return 1 else: decision = recorder.sampler.should_trace(sampling_req) return decisio...
Return 1 or the matched rule name if should sample and 0 if should not. The sampling decision coming from ``trace_header`` always has the highest precedence. If the ``trace_header`` doesn't contain sampling decision then it checks if sampling is enabled or not in the recorder. If not enbaled it returns ...
def set_all_tiers(key, value, django_cache_timeout=DEFAULT_TIMEOUT): DEFAULT_REQUEST_CACHE.set(key, value) django_cache.set(key, value, django_cache_timeout)
Caches the value for the provided key in both the request cache and the django cache. Args: key (string) value (object) django_cache_timeout (int): (Optional) Timeout used to determine if and for how long to cache in the django cache. A timeout of ...
def create_traj_ranges(start, stop, N): steps = (1.0/(N-1)) * (stop - start) if np.isscalar(steps): return steps*np.arange(N) + start else: return steps[:, None]*np.arange(N) + start[:, None]
Fills in the trajectory range. # Adapted from https://stackoverflow.com/a/40624614
def tokenize(self, string): if self.language == 'akkadian': tokens = tokenize_akkadian_words(string) elif self.language == 'arabic': tokens = tokenize_arabic_words(string) elif self.language == 'french': tokens = tokenize_french_words(string) elif self...
Tokenize incoming string.
def isAuthorized(self, pid, action, vendorSpecific=None): response = self.isAuthorizedResponse(pid, action, vendorSpecific) return self._read_boolean_401_response(response)
Return True if user is allowed to perform ``action`` on ``pid``, else False.
def is_zipfile(filename): result = False try: if hasattr(filename, "read"): result = _check_zipfile(fp=filename) else: with open(filename, "rb") as fp: result = _check_zipfile(fp) except OSError: pass return result
Quickly see if a file is a ZIP file by checking the magic number. The filename argument may be a file or file-like object too.
def complete_func(self, findstart, base): self.log.debug('complete_func: in %s %s', findstart, base) def detect_row_column_start(): row, col = self.editor.cursor() start = col line = self.editor.getline() while start > 0 and line[start - 1] not in " .,([{"...
Handle omni completion.
def orders_after_any(self, other, *, visited=None): if not other: return False if visited is None: visited = set() elif self in visited: return False visited.add(self) for item in self.PATCHED_ORDER_AFTER: if item in visited: ...
Return whether `self` orders after any of the services in the set `other`. :param other: Another service. :type other: A :class:`set` of :class:`aioxmpp.service.Service` instances .. versionadded:: 0.11
def _tuple_from_str(bbox): return tuple([float(s) for s in bbox.replace(',', ' ').split() if s])
Parses a string of numbers separated by any combination of commas and spaces :param bbox: e.g. str of the form `min_x ,min_y max_x, max_y` :return: tuple (min_x,min_y,max_x,max_y)
def get_prep_value(self, value): value = super(NullBooleanPGPPublicKeyField, self).get_prep_value(value) if value is None: return None return "%s" % bool(value)
Before encryption, need to prepare values.
def namespace(sharing=None, owner=None, app=None, **kwargs): if sharing in ["system"]: return record({'sharing': sharing, 'owner': "nobody", 'app': "system" }) if sharing in ["global", "app"]: return record({'sharing': sharing, 'owner': "nobody", 'app': app}) if sharing in ["user", None]: ...
This function constructs a Splunk namespace. Every Splunk resource belongs to a namespace. The namespace is specified by the pair of values ``owner`` and ``app`` and is governed by a ``sharing`` mode. The possible values for ``sharing`` are: "user", "app", "global" and "system", which map to the follow...
def _get_config(): cfg = os.path.expanduser('~/.dockercfg') try: fic = open(cfg) try: config = json.loads(fic.read()) finally: fic.close() except Exception: config = {'rootPath': '/dev/null'} if not 'Configs' in config: config['Configs'] = ...
Get user docker configuration Return: dict
def annualization_factor(period, annualization): if annualization is None: try: factor = ANNUALIZATION_FACTORS[period] except KeyError: raise ValueError( "Period cannot be '{}'. " "Can be '{}'.".format( period, "', '".join(A...
Return annualization factor from period entered or if a custom value is passed in. Parameters ---------- period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are:: ...
def AllBalancesZeroOrLess(self): for key, fixed8 in self.Balances.items(): if fixed8.value > 0: return False return True
Flag indicating if all balances are 0 or less. Returns: bool: True if all balances are <= 0. False, otherwise.
def gather_details(): try: data = { 'kernel': platform.uname(), 'distribution': platform.linux_distribution(), 'libc': platform.libc_ver(), 'arch': platform.machine(), 'python_version': platform.python_version(), 'os_name': platform.sys...
Get details about the host that is executing habu.
def xslt(request): foos = foobar_models.Foo.objects.all() return render_xslt_to_response('xslt/model-to-xml.xsl', foos, mimetype='text/xml')
Shows xml output transformed with standard xslt
def AddDateTimeRange( self, time_value, start_time_string=None, end_time_string=None): if not isinstance(time_value, py2to3.STRING_TYPES): raise ValueError('Filter type must be a string.') if start_time_string is None and end_time_string is None: raise ValueError( 'Filter must have e...
Adds a date time filter range. The time strings are formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and timezone offset are optional. The default timezone is UTC....
def write_data(fo, datum, schema): record_type = extract_record_type(schema) logical_type = extract_logical_type(schema) fn = WRITERS.get(record_type) if fn: if logical_type: prepare = LOGICAL_WRITERS.get(logical_type) if prepare: datum = prepare(datum, sc...
Write a datum of data to output stream. Paramaters ---------- fo: file-like Output file datum: object Data to write schema: dict Schemda to use