Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
367,100
def update(self, data): updated = self.set_property(, data[]) updated |= self.set_property(, data[]) if not in data: data[] = None updated |= self.set_property( , data[] ) return updated
Updates object information with live data (if live data has different values to stored object information). Changes will be automatically applied, but not persisted in the database. Call `db.session.add(elb)` manually to commit the changes to the DB. Args: # data (:obj:) AWS...
367,101
def remove(self, env_path): with filelock(self.lockpath): cache = self._read_cache() logger.debug("Removing virtualenv from cache: %s" % env_path) lines = [ line for line in cache if json.loads(line).get(, {}).get() != env_path ...
Remove metadata for a given virtualenv from cache.
367,102
def has_valid_soma(data_wrapper): try: make_soma(data_wrapper.soma_points()) return CheckResult(True) except SomaError: return CheckResult(False)
Check if a data block has a valid soma Returns: CheckResult with result
367,103
def nodes(self) -> List[str]: if self._scenario_version == 1 and in self._config: range_config = self._config[] try: start, stop = range_config[], range_config[] + 1 except KeyError: raise MissingNodesConfiguration( ...
Return the list of nodes configured in the scenario's yaml. Should the scenario use version 1, we check if there is a 'setting'. If so, we derive the list of nodes from this dictionary, using its 'first', 'last' and 'template' keys. Should any of these keys be missing, we throw an appro...
367,104
def jsonld(client, datasets): from renku.models._json import dumps from renku.models._jsonld import asjsonld data = [ asjsonld( dataset, basedir=os.path.relpath( , start=str(dataset.__reference__.parent) ) ) for dataset in datasets ...
Format datasets as JSON-LD.
367,105
def get_buffer(self): if self.doc_to_update: self.update_sources() ES_buffer = self.action_buffer self.clean_up() return ES_buffer
Get buffer which needs to be bulked to elasticsearch
367,106
def join(self): with self._parent._all_tasks_done: while self._parent._unfinished_tasks: self._parent._all_tasks_done.wait()
Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the...
367,107
def query(number, domains, resolver=None): if resolver is None: resolver = dns.resolver.get_default_resolver() for domain in domains: if isinstance(domain, (str, unicode)): domain = dns.name.from_text(domain) qname = dns.e164.from_e164(number, domain) try: ...
Look for NAPTR RRs for the specified number in the specified domains. e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.'])
367,108
def _sort_r(sorted, processed, key, deps, dependency_tree): if key in processed: return processed.add(key) for dep_key in deps: dep_deps = dependency_tree.get(dep_key) if dep_deps is None: log.debug(, Repr(dep_key)) continue _sort_r(sorted, proces...
Recursive topological sort implementation.
367,109
def from_shorthand(shorthand_string, slash=None): if type(shorthand_string) == list: res = [] for x in shorthand_string: res.append(from_shorthand(x)) return res if shorthand_string in [, ]: return [] shorthand_string = shorthand_string.replace(, )...
Take a chord written in shorthand and return the notes in the chord. The function can recognize triads, sevenths, sixths, ninths, elevenths, thirteenths, slashed chords and a number of altered chords. The second argument should not be given and is only used for a recursive call when a slashed chord or...
367,110
def _calculate_period(self, vals): if len(vals) < 4: return None if self.firmware[] < 16: return ((vals[3] << 24) | (vals[2] << 16) | (vals[1] << 8) | vals[0]) / 12e6 else: return self._calculate_float(vals)
calculate the sampling period in seconds
367,111
def set_label_elements(self, wanted_label_elements): if isinstance(wanted_label_elements, str): wanted_label_elements = [wanted_label_elements] missing_elements = [e for e in wanted_label_elements if getattr(self, e) is None] contained_elements = [e for e in ann_l...
Set one or more label elements based on at least one of the others
367,112
def keyPressEvent(self, event): if event.key() == Qt.Key_Alt: self._alt_key_is_down = True self.update()
Override Qt method
367,113
def from_curvilinear(cls, x, y, z, formatter=numpy_formatter): return cls(x, y, z, formatter)
Construct a contour generator from a curvilinear grid. Note ---- This is an alias for the default constructor. Parameters ---------- x : array_like x coordinates of each point in `z`. Must be the same size as `z`. y : array_like y coordi...
367,114
def token(self): header = self.default_headers.get(, ) prefex = if header.startswith(prefex): token = header[len(prefex):] else: token = header return token
get the token
367,115
def monitorSearchJob(self): assert self.__searchJob is not None jobID = self.__searchJob.getJobID() startTime = time.time() lastUpdateTime = datetime.now() expectedNumModels = self.__searchJob.getExpectedNumModels( searchMethod = self._options["sear...
Parameters: ---------------------------------------------------------------------- retval: nothing
367,116
def series_with_permutation(self, other): combined_permutation = tuple([self.permutation[p] for p in other.permutation]) return CPermutation.create(combined_permutation)
Compute the series product with another channel permutation circuit Args: other (CPermutation): Returns: Circuit: The composite permutation circuit (could also be the identity circuit for n channels)
367,117
def _calcDistance(self, inputPattern, distanceNorm=None): if distanceNorm is None: distanceNorm = self.distanceNorm if self.useSparseMemory: if self._protoSizes is None: self._protoSizes = self._Memory.rowSums() overlapsWithProtos = self._Memory.rightVecSumAtNZ(inputPattern)...
Calculate the distances from inputPattern to all stored patterns. All distances are between 0.0 and 1.0 :param inputPattern The pattern from which distances to all other patterns are calculated :param distanceNorm Degree of the distance norm
367,118
def build_data_set(self): "Construct a sequence of name/value pairs from controls" data = {} for field in self.fields: if field.name: val = field.get_value() if val is None: continue elif isinstance(val, unicode): ...
Construct a sequence of name/value pairs from controls
367,119
def parse_if_range_header(value): if not value: return IfRange() date = parse_date(value) if date is not None: return IfRange(date=date) return IfRange(unquote_etag(value)[0])
Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionadded:: 0.7
367,120
def cast_scalar_to_array(shape, value, dtype=None): if dtype is None: dtype, fill_value = infer_dtype_from_scalar(value) else: fill_value = value values = np.empty(shape, dtype=dtype) values.fill(fill_value) return values
create np.ndarray of specified shape and dtype, filled with values Parameters ---------- shape : tuple value : scalar value dtype : np.dtype, optional dtype to coerce Returns ------- ndarray of shape, filled with value, of specified / inferred dtype
367,121
def run_tasks(header, tasks): tasks = list(tasks) with timed_display(header) as print_message: with tqdm(tasks, position=1, desc=, disable=None, bar_format=, total=sum(t[2] if len(t) > 2 else 1 for t in tasks), dynamic_ncols=True) as pbar: ...
Run a group of tasks with a header, footer and success/failure messages. Args: header: A message to print in the header bar before the tasks are run. tasks: A list of tuples containing a task title, a task, and a weight. If the tuple only contains two values, the weight is assumed to be...
367,122
def mouse_move(self, event): if (self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE): self.posX = event.xdata self.posY = event.ydata self.graphic_target(self.posX, self.posY)
The following gets back coordinates of the mouse on the canvas.
367,123
def openstack_upgrade_available(package): import apt_pkg as apt src = config() cur_vers = get_os_version_package(package) if not cur_vers: return False if "swift" in package: codename = get_os_codename_install_source(src) avail_vers = get_os_version_codename_sw...
Determines if an OpenStack upgrade is available from installation source, based on version of installed package. :param package: str: Name of installed package. :returns: bool: : Returns True if configured installation source offers a newer version of package.
367,124
def sli_run(parameters=object(), fname=, verbosity=): str send_nest_params_to_sli(vars(parameters)) nest.sli_run("%s setverbosity" % verbosity) nest.sli_run( % fname)
Takes parameter-class and name of main sli-script as input, initiating the simulation. kwargs: :: parameters : object, parameter class instance fname : str, path to sli codes to be executed verbosity : 'str', nest verbosity flag
367,125
def decode_cf_datetime(num_dates, units, calendar=None, use_cftime=None): num_dates = np.asarray(num_dates) flat_num_dates = num_dates.ravel() if calendar is None: calendar = if use_cftime is None: try: dates = _decode_datetime_with_pandas(flat_num_dates, units, ...
Given an array of numeric dates in netCDF format, convert it into a numpy array of date time objects. For standard (Gregorian) calendars, this function uses vectorized operations, which makes it much faster than cftime.num2date. In such a case, the returned array will be of type np.datetime64. Not...
367,126
def remove_site(name): ret = {: name, : {}, : None, : } current_sites = __salt__[]() if name not in current_sites: ret[] = .format(name) ret[] = True elif __opts__[]: ret[] = .format(name) ret[] = {: name, ...
Delete a website from IIS. :param str name: The IIS site name. Usage: .. code-block:: yaml defaultwebsite-remove: win_iis.remove_site: - name: Default Web Site
367,127
def get_acquaintance_size(obj: Union[circuits.Circuit, ops.Operation]) -> int: if isinstance(obj, circuits.Circuit): if not is_acquaintance_strategy(obj): raise TypeError() return max(tuple(get_acquaintance_size(op) for op in obj.all_operations()) or (0,)) ...
The maximum number of qubits to be acquainted with each other.
367,128
def _split_keys_v1(joined): left, _, right = joined.partition() return _decode_v1(left), _decode_v1(right)
Split two keys out a string created by _join_keys_v1.
367,129
def __construct_lda_model(self): repos_of_interest = self.__get_interests() cleaned_tokens = self.__clean_and_tokenize(repos_of_interest) if not cleaned_tokens: cleaned_tokens = [["zkfgzkfgzkfgzkfgzkfgzkfg"]] d...
Method to create LDA model to procure list of topics from. We do that by first fetching the descriptions of repositories user has shown interest in. We tokenize the hence fetched descriptions to procure list of cleaned tokens by dropping all the stop words and language names from it. ...
367,130
def _read_mode_sec(self, size, kind): if size < 3: raise ProtocolError(f) _clvl = self._read_unpack(1) data = dict( kind=kind, type=self._read_opt_type(kind), length=size, level=_CLASSIFICATION_LEVEL.get(_clvl, _clvl), ...
Read options with security info. Positional arguments: size - int, length of option kind - int, 130 (SEC )/ 133 (ESEC) Returns: * dict -- extracted option with security info (E/SEC) Structure of these options: * [RFC 1108] Security (SEC) ...
367,131
def update(self, ip_address=values.unset, friendly_name=values.unset, cidr_prefix_length=values.unset): data = values.of({ : ip_address, : friendly_name, : cidr_prefix_length, }) payload = self._version.update( , ...
Update the IpAddressInstance :param unicode ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. :param unicode friendly_name: A human readable descriptive text for this re...
367,132
def query_array(ncfile, name) -> numpy.ndarray: variable = query_variable(ncfile, name) maskedarray = variable[:] fillvalue_ = getattr(variable, , numpy.nan) if not numpy.isnan(fillvalue_): maskedarray[maskedarray.mask] = numpy.nan return maskedarray.data
Return the data of the variable with the given name from the given NetCDF file. The following example shows that |query_array| returns |nan| entries to represent missing values even when the respective NetCDF variable defines a different fill value: >>> from hydpy import TestIO >>> from hydpy....
367,133
def __generate_key(self, config): cwd = config.get(, self._install_directory()) if config.is_affirmative(, default="yes"): if not os.path.exists(cwd): os.makedirs(cwd) if not os.path.exists(os.path.join(cwd, config.get())): command = "ssh-...
Generate the ssh key, and return the ssh config location
367,134
def _remote_chmod(self, paths, mode, sudoable=False): LOG.debug(, paths, mode, sudoable) return self.fake_shell(lambda: mitogen.select.Select.all( self._connection.get_chain().call_async( ansible_mitogen.target.set_file_mode, path, mode ...
Issue an asynchronous set_file_mode() call for every path in `paths`, then format the resulting return value list with fake_shell().
367,135
def html(text, lazy_images=False): extensions = [ , , , , OEmbedExtension() ] if lazy_images: extensions.append(LazyImageExtension()) return markdown.markdown(text, extensions=extensions)
To render a markdown format text into HTML. - If you want to also build a Table of Content inside of the markdow, add the tags: [TOC] It will include a <ul><li>...</ul> of all <h*> :param text: :param lazy_images: bool - If true, it will activate the LazyImageExtension :return:
367,136
def t_whitespace_or_comment(self, s): r if in s: matches = re.match(, s) if matches and self.is_newline: self.handle_indent_dedent(matches.group(1)) s = matches.group(2) if s.endswith("\n"): self.add_token(...
r'([ \t]*[#].*[^\x04][\n]?)|([ \t]+)
367,137
def _prepare_b_jkl_mn(readout_povm, pauli_basis, pre_channel_ops, post_channel_ops, rho0): c_jk_m = state_tomography._prepare_c_jk_m(readout_povm, pauli_basis, post_channel_ops) pre_channel_transfer_matrices = [pauli_basis.transfer_matrix(qt.to_super(ek)) for ek in pre_...
Prepare the coefficient matrix for process tomography. This function uses sparse matrices for much greater efficiency. The coefficient matrix is defined as: .. math:: B_{(jkl)(mn)}=\sum_{r,q}\pi_{jr}(\mathcal{R}_{k})_{rm} (\mathcal{R}_{l})_{nq} (\rho_0)_q where :math:`\mathcal{R}_{k}` is the ...
367,138
def logn_correlated_rate(parent_rate, branch_length, autocorrel_param, size=1): if autocorrel_param <= 0: raise Exception() variance = branch_length * autocorrel_param stdev = np.sqrt(variance) ln_descendant_rate = np.random.normal(np.log(parent_rate) - 0.5 * variance, ...
The log of the descendent rate, ln(Rd), is ~ N(mu, bl*ac), where the variance = bl*ac = branch_length * autocorrel_param, and mu is set so that E[Rd] = Rp: E[X] where ln(X) ~ N(mu, sigma^2) = exp(mu+(1/2)*sigma_sq) so Rp = exp(mu+(1/2)*bl*ac), ln(Rp) = mu + (1/2)*bl*ac, ln(Rp) - (1/2)*bl*ac = mu...
367,139
def QA_fetch_lhb(date, db=DATABASE): try: collections = db.lhb return pd.DataFrame([item for item in collections.find( {: date}, {"_id": 0})]).set_index(, drop=False).sort_index() except Exception as e: raise e
获取某一天龙虎榜数据
367,140
def remove_bucket_list_item(self, id, collection, item): if type(id) is not ObjectId: id = ObjectId(id) obj = getattr(self.db, collection) result = obj.update( {: id}, {: {: item}} ) return result
Removes an item from the bucket list Args: id: the CRITs object id of the TLO collection: The db collection. See main class documentation. item: the bucket list item to remove Returns: The mongodb result
367,141
def move_item_into_viewport(self, item): if not item: return HORIZONTAL = 0 VERTICAL = 1 if not isinstance(item, Item): state_v = item.parent elif not isinstance(item, StateView): state_v = self.canvas.get_parent(item) else: ...
Causes the `item` to be moved into the viewport The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item` is not a `StateView`, the parental `StateView` is moved into the viewport. :param StateView | ConnectionView | PortView item: The item to...
367,142
def evaluate_postfix(tokens): stack = [] for token in tokens: total = None if is_int(token) or is_float(token) or is_constant(token): stack.append(token) elif is_unary(token): a = stack.pop() total = mathwords.UNARY_FUNCTIONS[token](a) e...
Given a list of evaluatable tokens in postfix format, calculate a solution.
367,143
def insert_device_filter(self, position, filter_p): if not isinstance(position, baseinteger): raise TypeError("position can only be an instance of type baseinteger") if not isinstance(filter_p, IUSBDeviceFilter): raise TypeError("filter_p can only be an instance of type ...
Inserts the given USB device to the specified position in the list of filters. Positions are numbered starting from 0. If the specified position is equal to or greater than the number of elements in the list, the filter is added to the end of the collection. ...
367,144
def align(args): from jcvi.formats.fastq import guessoffset p = OptionParser(align.__doc__) p.add_option("--rnaseq", default=False, action="store_true", help="Input is RNA-seq reads, turn splicing on") p.add_option("--native", default=False, action="store_true", h...
%prog align database.fasta read1.fq read2.fq Wrapper for `gsnap` single-end or paired-end, depending on the number of args.
367,145
def is_url(): regex = re.compile( r r r r r r, re.IGNORECASE) def validate(value): if not regex.match(value): return e("{} is not a valid URL", value) return validate
Validates that a fields value is a valid URL.
367,146
def omim(context, api_key, institute): LOG.info("Running scout update omim") adapter = context.obj[] api_key = api_key or context.obj.get() if not api_key: LOG.warning("Please provide a omim api key to load the omim gene panel") context.abort() institute_obj = adapter....
Update the automate generated omim gene panel in the database.
367,147
def email(self, comment, content_object, request): if not self.email_notification: return send_comment_posted(comment, request)
Overwritten for a better email notification.
367,148
def non_decreasing(values): return all(x <= y for x, y in zip(values, values[1:]))
True if values are not decreasing.
367,149
def _convert_to_hashable(data, types=True): r if data is None: hashable = b prefix = b elif isinstance(data, six.binary_type): hashable = data prefix = b elif isinstance(data, six.text_type): hashable = data.encode() prefix = b elif isins...
r""" Converts `data` into a hashable byte representation if an appropriate hashing function is known. Args: data (object): ordered data with structure types (bool): include type prefixes in the hash Returns: tuple(bytes, bytes): prefix, hashable: a prefix hinting th...
367,150
def match(self, context, line): return line.kind == and line.partitioned[0] in self._both
Match code lines prefixed with a variety of keywords.
367,151
def flush(self, meta=None): pattern = self.basekey(meta) if meta else self.namespace return self.client.delpattern( % pattern)
Flush all model keys from the database
367,152
def join(self): self.closed = True while self.expect > 0: val = self.wait_change.get() self.expect -= 1 if val is not None: gevent.joinall(list(self.greenlets), timeout=30) g...
Wait for transfer to exit, raising errors as necessary.
367,153
def r_passage(self, objectId, subreference, lang=None): collection = self.get_collection(objectId) if isinstance(collection, CtsWorkMetadata): editions = [t for t in collection.children.values() if isinstance(t, CtsEditionMetadata)] if len(editions) == 0: ...
Retrieve the text of the passage :param objectId: Collection identifier :type objectId: str :param lang: Lang in which to express main data :type lang: str :param subreference: Reference identifier :type subreference: str :return: Template, collections metadata a...
367,154
def register_annotype_converter(cls, types, is_array=False, is_mapping=False): if not isinstance(types, Sequence): types = [types] def decorator(subclass): for typ in types: cls._annotype_lookup[(typ, is_array...
Register this class as a converter for Anno instances
367,155
def norm(self): tmp = self.w**2 + self.x**2 + self.y**2 + self.z**2 return tmp**0.5
Returns the norm of the quaternion norm = w**2 + x**2 + y**2 + z**2
367,156
def get_redirect_url(self, url, encrypt_code, card_id): from wechatpy.utils import WeChatSigner code = self.decrypt_code(encrypt_code) signer = WeChatSigner() signer.add_data(self.secret) signer.add_data(code) signer.add_data(card_id) signature = signer...
获取卡券跳转外链
367,157
def write_back_register(self, reg, val): if self.write_backs_disabled: return if issymbolic(val): logger.warning("Skipping Symbolic write-back") return if reg in self.flag_registers: self._emu.reg_write(self._to_unicorn_id(), self._cpu.rea...
Sync register state from Manticore -> Unicorn
367,158
def filter(args): p = OptionParser(filter.__doc__) p.add_option("--type", default="mRNA", help="The feature to scan for the attributes [default: %default]") g1 = OptionGroup(p, "Filter by identity/coverage attribute values") g1.add_option("--id", default=95, type="float", ...
%prog filter gffile > filtered.gff Filter the gff file based on criteria below: (1) feature attribute values: [Identity, Coverage]. You can get this type of gff by using gmap $ gmap -f 2 .... (2) Total bp length of child features
367,159
def apply_injectables(self, targets): target_types = {type(t) for t in targets} target_subsystem_deps = {s for s in itertools.chain(*(t.subsystems() for t in target_types))} for subsystem in target_subsystem_deps: if issubclass(subsystem, InjectablesMixin) and subsystem.is_initialized(): ...
Given an iterable of `Target` instances, apply their transitive injectables.
367,160
def apply_clicked(self, button): if isinstance(self.model.state, LibraryState): logger.warning("It is not allowed to modify libraries.") self.view.set_text("") return while Gtk.events_pending(): Gtk.main_iterat...
Triggered when the Apply button in the source editor is clicked.
367,161
def storage_expansion(network, basemap=True, scaling=1, filename=None): stores = network.storage_units[network.storage_units.carrier == ] batteries = stores[stores.max_hours == 6] hydrogen = stores[stores.max_hours == 168] storage_distribution =\ network...
Plot storage distribution as circles on grid nodes Displays storage size and distribution in network. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis filename : str Specify filename If not given, fi...
367,162
def getGerritChanges(props): if in props: return props.getProperty() if in props: return [{ : props.getProperty(), : props.getProperty() }] return []
Get the gerrit changes This method could be overridden if really needed to accommodate for other custom steps method for fetching gerrit changes. :param props: an IProperty :return: (optionally via deferred) a list of dictionary with at list change_id, ...
367,163
def find_by_id(self, repoid): for row in self.jsondata: if repoid == row["repoid"]: return self._infofromdict(row)
Returns the repo with the specified <repoid>
367,164
def emd2(a, b, M, processes=multiprocessing.cpu_count(), numItermax=100000, log=False, return_matrix=False): a = np.asarray(a, dtype=np.float64) b = np.asarray(b, dtype=np.float64) M = np.asarray(M, dtype=np.float64) if len(a) == 0: a = np.ones((M.shape[0],), dtype=np.float6...
Solves the Earth Movers distance problem and returns the loss .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed i...
367,165
def get_template(self, template_name): try: return self.loader.load(template_name, encoding=self.encoding) except self.not_found_exception, e: raise TemplateNotFound(template_name)
Get the template which is at the given name
367,166
def spi_ss_polarity(self, polarity): ret = api.py_aa_spi_master_ss_polarity(self.handle, polarity) _raise_error_if_negative(ret)
Change the ouput polarity on the SS line. Please note, that this only affects the master functions.
367,167
def validate_email(self, email): try: self.user = User.objects.get_by_natural_key(email) except User.DoesNotExist: msg = _() raise serializers.ValidationError(msg) if self.user.email_verified: msg = _() raise serializers.Valid...
Validate if email exists and requires a verification. `validate_email` will set a `user` attribute on the instance allowing the view to send an email confirmation.
367,168
def get_capability_report(self, raw=True, cb=None): task = asyncio.ensure_future(self.core.get_capability_report()) report = self.loop.run_until_complete(task) if raw: if cb: cb(report) else: return report else: ...
This method retrieves the Firmata capability report :param raw: If True, it either stores or provides the callback with a report as list. If False, prints a formatted report to the console :param cb: Optional callback reference to receive a raw report :...
367,169
def parse_requestline(s): methods = .join(HttpBaseClass.METHODS) m = re.match(r + methods + , s, re.I) if m: return m.group(1).upper(), m.group(2), m.group(3) else: raise ValueError()
http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5 >>> parse_requestline('GET / HTTP/1.0') ('GET', '/', '1.0') >>> parse_requestline('post /testurl htTP/1.1') ('POST', '/testurl', '1.1') >>> parse_requestline('Im not a RequestLine') Traceback (most recent call last): ... Val...
367,170
def hash(self): if not in self._p4dict: self._p4dict = self._connection.run([, , , , self.depotFile])[0] return self._p4dict[]
The hash value of the current revision
367,171
def styleInheritedFromParent(node, style): parentNode = node.parentNode if parentNode.nodeType == Node.DOCUMENT_NODE: return None styles = _getStyle(parentNode) if style in styles: value = styles[style] if not value == : return value value =...
Returns the value of 'style' that is inherited from the parents of the passed-in node Warning: This method only considers presentation attributes and inline styles, any style sheets are ignored!
367,172
def send_scheduled_messages(priority=None, ignore_unknown_messengers=False, ignore_unknown_message_types=False): dispatches_by_messengers = Dispatch.group_by_messengers(Dispatch.get_unsent(priority=priority)) for messenger_id, messages in dispatches_by_messengers.items(): try: messenge...
Sends scheduled messages. :param int, None priority: number to limit sending message by this priority. :param bool ignore_unknown_messengers: to silence UnknownMessengerError :param bool ignore_unknown_message_types: to silence UnknownMessageTypeError :raises UnknownMessengerError: :raises UnknownM...
367,173
def _update_dPrxy(self): super(ExpCM_fitprefs, self)._update_dPrxy() if in self.freeparams: tildeFrxyQxy = self.tildeFrxy * self.Qxy j = 0 zetaxterm = scipy.ndarray((self.nsites, N_CODON, N_CODON), dtype=) zetayterm = scipy.ndarray((self.nsites,...
Update `dPrxy`.
367,174
def load_config(self, config): if config is not None and config.has_section(): logger.debug() n = config.get_value(, , default=None) logger.debug(.format(n))
Load the outputs section of the configuration file.
367,175
def depends_on(self, *keys): def decorator(wrapped): if keys: if wrapped not in self._dependencies: self._dependencies[wrapped] = set() self._dependencies[wrapped].update(keys) return wrapped return decorator
Decorator that marks the wrapped as depending on specified provider keys. :param keys: Provider keys to mark as dependencies for wrapped :type keys: tuple :return: decorator :rtype: decorator
367,176
def swpool(agent, nnames, lenvals, names): agent = stypes.stringToCharP(agent) nnames = ctypes.c_int(nnames) lenvals = ctypes.c_int(lenvals) names = stypes.listToCharArray(names) libspice.swpool_c(agent, nnames, lenvals, names)
Add a name to the list of agents to notify whenever a member of a list of kernel variables is updated. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/swpool_c.html :param agent: The name of an agent to be notified after updates. :type agent: str :param nnames: The number of variables to a...
367,177
def get_number_of_app_ports(app): mode = _get_networking_mode(app) ports_list = None if mode == : ports_list = _get_port_definitions(app) elif mode == : ports_list = _get_port_definitions(app) if ports_list is None: ports_list = _get_container_port_mappings(app) ...
Get the number of ports for the given app JSON. This roughly follows the logic in marathon-lb for finding app IPs/ports, although we are only interested in the quantity of ports an app should have and don't consider the specific IPs/ports of individual tasks: https://github.com/mesosphere/marathon-lb/bl...
367,178
def get_port_mappings(self, port=None): port_mappings = self.inspect(refresh=True)["NetworkSettings"]["Ports"] if not port: return port_mappings if str(port) not in self.get_ports(): return [] for p in port_mappings: if p.split("/")[0] == s...
Get list of port mappings between container and host. The format of dicts is: {"HostIp": XX, "HostPort": YY}; When port is None - return all port mappings. The container needs to be running, otherwise this returns an empty list. :param port: int or None, container port :re...
367,179
def main(): logging.basicConfig(format=) try: cli() return 0 except LocationsError as error: print(error) return 2 except RuntimeError as error: print(error) return 255 except OSError as error: return error.errno
Main script handler. Returns: int: 0 for success, >1 error code
367,180
def drop(self, relation): dropped = _make_key(relation) logger.debug(.format(dropped)) with self.lock: self._drop_cascade_relation(dropped)
Drop the named relation and cascade it appropriately to all dependent relations. Because dbt proactively does many `drop relation if exist ... cascade` that are noops, nonexistent relation drops cause a debug log and no other actions. :param str schema: The schema of the relati...
367,181
def from_outcars(cls, outcars, structures, **kwargs): if len(outcars) != len(structures): raise ValueError(" r = [0] prev = structures[0] for st in structures[1:]: dists = np.array([s2.distance(s1) for s1, s2 in zip(pr...
Initializes an NEBAnalysis from Outcar and Structure objects. Use the static constructors, e.g., :class:`from_dir` instead if you prefer to have these automatically generated from a directory of NEB calculations. Args: outcars ([Outcar]): List of Outcar objects. Note that th...
367,182
def getItemWidth(self) -> int: if not isinstance(self.dtype, HArray): raise TypeError() return (self.bitAddrEnd - self.bitAddr) // self.itemCnt
Only for transactions derived from HArray :return: width of item in original array
367,183
def get_settings(self): settings = self.context.getAnalysisServicesSettings() mapping = dict(map(lambda s: (s.get("uid"), s), settings)) return mapping
Returns a mapping of UID -> setting
367,184
def console_load_asc(con: tcod.console.Console, filename: str) -> bool: return bool( lib.TCOD_console_load_asc(_console(con), filename.encode("utf-8")) )
Update a console from a non-delimited ASCII `.asc` file.
367,185
def instance_config_path(cls, project, instance_config): return google.api_core.path_template.expand( "projects/{project}/instanceConfigs/{instance_config}", project=project, instance_config=instance_config, )
Return a fully-qualified instance_config string.
367,186
def find(cls, *args, **kwargs): return list(cls.collection.find(*args, **kwargs))
Returns all document dicts that pass the filter
367,187
def stop_all(self, run_order=-1): shutit_global.shutit_global_object.yield_to_draw()
Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc.
367,188
def delete(self, tag, ref): _checkErr(, _C.Vdeletetagref(self._id, tag, ref), "error deleting member")
Delete from the vgroup the member identified by its tag and reference number. Args:: tag tag of the member to delete ref reference number of the member to delete Returns:: None Only the link of the member with the vgroup is deleted. The me...
367,189
def _leaf_list_stmt(self, stmt: Statement, sctx: SchemaContext) -> None: node = LeafListNode() node.type = DataType._resolve_type( stmt.find1("type", required=True), sctx) self._handle_child(node, stmt, sctx)
Handle leaf-list statement.
367,190
def _get_opt(config, key, option, opt_type): for opt_key in [option, option.replace(, )]: if not config.has_option(key, opt_key): continue if opt_type == bool: return config.getbool(key, opt_key) if opt_type == int: return config.getint(key, opt_key...
Get an option from a configparser with the given type.
367,191
def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None: for d in dict_list: d[key] = str(d[key]) if d[key] == "": d[key] = None
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``.
367,192
def add_raw(self, raw): if type(raw) == list: self._q += raw if type(raw) == dict: self._q.append(raw) return self
Adds row aggregation state at the query :param raw: list of raw stages or a dict of raw stage :return: The current object
367,193
def load_jws_from_request(req): current_app.logger.info("loading request with headers: %s" % req.headers) if (("content-type" in req.headers and "application/jose" in req.headers[]) or ("Content-Type" in req.headers and "application/jose" in req.headers[])): path = urlpars...
This function performs almost entirely bitjws authentication tasks. If valid bitjws message and signature headers are found, then the request will be assigned 'jws_header' and 'jws_payload' attributes. :param req: The flask request to load the jwt claim set from.
367,194
def add(self, docs, boost=None, fieldUpdates=None, commit=None, softCommit=False, commitWithin=None, waitFlush=None, waitSearcher=None, overwrite=None, handler=): start_time = time.time() self.log.debug("Starting to build add request...") message = ElementTree.Element() ...
Adds or updates documents. Requires ``docs``, which is a list of dictionaries. Each key is the field name and each value is the value to index. Optionally accepts ``commit``. Default is ``None``. None signals to use default Optionally accepts ``softCommit``. Default is ``False``. ...
367,195
def get_reservations(self, sessionid, timeout=None): url = "{}{}".format(BASE_URL, "/reservations/") cookies = dict(sessionid=sessionid) try: resp = requests.get(url, timeout=timeout, cookies=cookies) except resp.exceptions.HTTPError as error: raise APIE...
Returns a list of location IDs and names.
367,196
def between(self, other_user_id): params = {: self.user_id, : other_user_id} response = self.session.get(self.url, params=params) return response.data[]
Check if there is a block between you and the given user. :return: ``True`` if the given user has been blocked :rtype: bool
367,197
def _EnvOpen(var, mode): value = os.getenv(var) if value is None: raise ValueError("%s is not set" % var) fd = int(value) if _WINDOWS: fd = msvcrt.open_osfhandle(fd, 0) return os.fdopen(fd, mode)
Open a file descriptor identified by an environment variable.
367,198
def get_account_policy(region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy ...
Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy
367,199
def _send_broker_aware_request(self, payloads, encoder_fn, decoder_fn): original_ordering = [(p.topic, p.partition) for p in payloads] brokers_for_payloads = [] payloads_by_broker = collections.defaultdict(list) responses = {} for payload in ...
Group a list of request payloads by topic+partition and send them to the leader broker for that partition using the supplied encode/decode functions Arguments: payloads: list of object-like entities with a topic (str) and partition (int) attribute; payloads with duplicate t...