Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
17,500
def _lt(field, value, document): try: return document.get(field, None) < value except TypeError: return False
Returns True if the value of a document field is less than a given value
17,501
def data_lookup_method(fields_list, mongo_db_obj, hist, record, lookup_type): if hist is None: hist = {} for field in record: if record[field] != and record[field] is not None: if field in fields_list: ...
Method to lookup the replacement value given a single input value from the same field. :param dict fields_list: Fields configurations :param MongoClient mongo_db_obj: MongoDB collection object :param dict hist: existing input of history values object :param dict record: values t...
17,502
def get_settings(self, section=None, defaults=None): section = self._maybe_get_default_name(section) if self.filepath is None: return {} parser = self._get_parser(defaults) defaults = parser.defaults() try: raw_items = ...
Gets a named section from the configuration source. :param section: a :class:`str` representing the section you want to retrieve from the configuration source. If ``None`` this will fallback to the :attr:`plaster.PlasterURL.fragment`. :param defaults: a :class:`dict` that will g...
17,503
def nt_commonpath(paths): from ntpath import splitdrive if not paths: raise ValueError() check_arg_types(, *paths) if isinstance(paths[0], bytes): sep = b altsep = b curdir = b else: sep = altsep = curdir = drivesplits = [spl...
Given a sequence of NT path names, return the longest common sub-path.
17,504
def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng): membs = np.empty(shape=X.shape[0], dtype=int) centers = kmeans._kmeans_init(X, n_clusters, method=, rng=rng) sse_last = 9999.9 n_iter = 0 for it in range(1,max_iter): membs = kmeans._assign_clusters(X, centers) cen...
Run a single trial of k-medoids clustering on dataset X, and given number of clusters
17,505
def seqids(args): p = OptionParser(seqids.__doc__) p.add_option("--maxn", default=100, type="int", help="Maximum number of seqids") p.add_option("--prefix", help="Seqids must start with") p.add_option("--exclude", default="random", help="Seqids should not contain") opts, args =...
%prog seqids bedfile Print out all seqids on one line. Useful for graphics.karyotype.
17,506
def references(self, criteria, publications=, column_name=, fetch=False): data_tables = dict() if isinstance(criteria, type(1)) and column_name == : t = self.query("SELECT * FROM {} WHERE id={}".format(publications, criteria), fmt=) if len(t) > 0: ...
Do a reverse lookup on the **publications** table. Will return every entry that matches that reference. Parameters ---------- criteria: int or str The id from the PUBLICATIONS table whose data across all tables is to be printed. publications: str Name of the publ...
17,507
def _session(): profile_name = _cfg() if profile_name: log.info(, profile_name) else: log.info() try: return boto3.Session(profile_name=profile_name) except botocore.exceptions.ProfileNotFound as orig_exc: err_msg = .format( profile_name or ) ...
Return the boto3 session to use for the KMS client. If aws_kms:profile_name is set in the salt configuration, use that profile. Otherwise, fall back on the default aws profile. We use the boto3 profile system to avoid having to duplicate individual boto3 configuration settings in salt configuration.
17,508
def framesToFrameRanges(frames, zfill=0): _build = FrameSet._build_frange_part curr_start = None curr_stride = None curr_frame = None last_frame = None curr_count = 0 for curr_frame in frames: if curr_start is None: curr_start ...
Converts a sequence of frames to a series of padded frame range strings. Args: frames (collections.Iterable): sequence of frames to process zfill (int): width for zero padding Yields: str:
17,509
def remove_comments_and_docstrings(source): io_obj = io.StringIO(source) out = "" prev_toktype = tokenize.INDENT last_lineno = -1 last_col = 0 for tok in tokenize.generate_tokens(io_obj.readline): token_type = tok[0] token_string = tok[1] start_line, start_col = tok[...
Returns *source* minus comments and docstrings. .. note:: Uses Python's built-in tokenize module to great effect. Example:: def noop(): # This is a comment ''' Does nothing. ''' pass # Don't do anything Will become:: def noop(): ...
17,510
def priority_run_or_raise(self, hosts, function, attempts=1): return self._run(hosts, function, self.workqueue.priority_enqueue_or_raise, False, attempts)
Like priority_run(), but if a host is already in the queue, the existing host is moved to the top of the queue instead of enqueuing the new one. :type hosts: string|list(string)|Host|list(Host) :param hosts: A hostname or Host object, or a list of them. :type function: functio...
17,511
def pil_image(self): if not self._pil_image: if self._format == "SVG": raise VectorImageError("can't rasterise vector images") self._pil_image = PIL.Image.open(StringIO(self.contents)) return self._pil_image
A :class:`PIL.Image.Image` instance containing the image data.
17,512
def unique_list_dicts(dlist, key): return list(dict((val[key], val) for val in dlist).values())
Return a list of dictionaries which are sorted for only unique entries. :param dlist: :param key: :return list:
17,513
def _put_or_post_multipart(self, method, url, data): fields = [] files = [] for key, value in data.items(): if type(value) == file: files.append((key, value.name, value.read())) else: fields.append((key, value)) content_typ...
encodes the data as a multipart form and PUTs or POSTs to the url the response is parsed as JSON and the returns the resulting data structure
17,514
def get_planes(im, squeeze=True): r x, y, z = (sp.array(im.shape) / 2).astype(int) planes = [im[x, :, :], im[:, y, :], im[:, :, z]] if not squeeze: imx = planes[0] planes[0] = sp.reshape(imx, [1, imx.shape[0], imx.shape[1]]) imy = planes[1] planes[1] = sp.reshape(imy, [im...
r""" Extracts three planar images from the volumetric image, one for each principle axis. The planes are taken from the middle of the domain. Parameters ---------- im : ND-array The volumetric image from which the 3 planar images are to be obtained squeeze : boolean, optional ...
17,515
def pathparse(value, sep=os.pathsep, os_sep=os.sep): PATH escapes = [] normpath = ntpath.normpath if os_sep == else posixpath.normpath if not in (os_sep, sep): escapes.extend(( (, , ), (, , ), (<ESCAPE-SQUOTE>\), ( % sep, , sep), )) ...
Get enviroment PATH directories as list. This function cares about spliting, escapes and normalization of paths across OSes. :param value: path string, as given by os.environ['PATH'] :type value: str :param sep: PATH separator, defaults to os.pathsep :type sep: str :param os_sep: OS filesy...
17,516
def Matches(self, file_entry): if not self._date_time_ranges: return None for date_time_range in self._date_time_ranges: time_attribute = self._TIME_VALUE_MAPPINGS.get( date_time_range.time_value, None) if not time_attribute: continue timestamp = getattr(file_ent...
Compares the file entry against the filter. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches the filter, False if not or None if the filter does not apply.
17,517
def get_device_model(self) -> str: output, _ = self._execute( , self.device_sn, , , ) return output.strip()
Show device model.
17,518
def from_element(cls, element): def _int_helper(name): result = element.get(name) if result is not None: try: return int(result) except ValueError: raise DIDLMetadataError( ...
Set the resource properties from a ``<res>`` element. Args: element (~xml.etree.ElementTree.Element): The ``<res>`` element
17,519
def find_files(root, pattern): results = [] for base, dirs, files in os.walk(root): matched = fnmatch.filter(files, pattern) results.extend(os.path.join(base, f) for f in matched) return results
Find all files matching the glob pattern recursively :param root: string :param pattern: string :return: list of file paths relative to root
17,520
def GetAvailableClaimTotal(self): coinrefs = [coin.Reference for coin in self.GetUnclaimedCoins()] bonus = Blockchain.CalculateBonusIgnoreClaimed(coinrefs, True) return bonus
Gets the total amount of Gas that this wallet is able to claim at a given moment. Returns: Fixed8: the amount of Gas available to claim as a Fixed8 number.
17,521
def update(self, campaign_id, budget, nick=None): request = TOPRequest() request[] = campaign_id request[] = budget if nick!=None: request[] = nick self.create(self.execute(request), fields=[,,,,], models={:CampaignBudget}) return self.result
xxxxx.xxxxx.campaign.budget.update =================================== 更新一个推广计划的日限额
17,522
def convert_date_to_iso(value): date_formats = ["%d %b %Y", "%Y/%m/%d"] for dformat in date_formats: try: date = datetime.strptime(value, dformat) return date.strftime("%Y-%m-%d") except ValueError: pass return value
Convert a date-value to the ISO date standard.
17,523
def rotate(self, angle, axis, point=None, radians=False): q = Quaternion.angle_and_axis(angle=angle, axis=axis, radians=radians) self._vector = q.rotate_vector(v=self._vector, point=point) return
Rotates `Atom` by `angle`. Parameters ---------- angle : float Angle that `Atom` will be rotated. axis : 3D Vector (tuple, list, numpy.array) Axis about which the `Atom` will be rotated. point : 3D Vector (tuple, list, numpy.array), optional P...
17,524
def threshold_monitor_hidden_threshold_monitor_security_pause(self, **kwargs): config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor") threshold_monitor = ET.SubElement(threshold_m...
Auto Generated Code
17,525
def create_instance(self, port): instance_type = self.get_instance_type(port) if not instance_type: return i_res = MechResource(port[], instance_type, a_const.CREATE) self.provision_queue.put(i_res)
Enqueue instance create
17,526
def _flatten_list(self, data): if data is None: return if isinstance(data, types.StringTypes): return data elif isinstance(data, (list, tuple)): return .join(self._flatten_list(x) for x in data)
Flattens nested lists into strings.
17,527
def get_geophysical_variables(ds): parameters = [] for variable in ds.variables: if is_geophysical(ds, variable): parameters.append(variable) return parameters
Returns a list of variable names for the variables detected as geophysical variables. :param netCDF4.Dataset nc: An open netCDF dataset
17,528
def find_sparse_mode(self, core, additional, scaling, weights={}): if len(core) == 0: return self.lp7(core) k = set() for reaction_id in core: flux = self.get_flux(reaction_id) if self.is_flipped(reaction_id): flux *= -1 ...
Find a sparse mode containing reactions of the core subset. Return an iterator of the support of a sparse mode that contains as many reactions from core as possible, and as few reactions from additional as possible (approximately). A dictionary of weights can be supplied which gives fur...
17,529
def build_task(self, name): try: self._gettask(name).value = ( self._gettask(name).task.resolve_and_build()) except TaskExecutionException as e: perror(e.header, indent="+0") perror(e.message, indent="+4") self._gettask(name).valu...
Builds a task by name, resolving any dependencies on the way
17,530
def on_backward_begin(self, last_loss:Rank0Tensor, **kwargs:Any) -> Rank0Tensor: "Scale gradients up by `self.loss_scale` to prevent underflow." ret_loss = last_loss * self.loss_scale return {: ret_loss}
Scale gradients up by `self.loss_scale` to prevent underflow.
17,531
def CreateFromDocument(xml_text, default_namespace=None, location_base=None): if pyxb.XMLStyle_saxer != pyxb._XMLStyle: dom = pyxb.utils.domutils.StringToDOM(xml_text) return CreateFromDOM(dom.documentElement, default_namespace=default_namespace) if default_namespace is None: defau...
Parse the given XML and use the document element to create a Python instance. @param xml_text An XML document. This should be data (Python 2 str or Python 3 bytes), or a text (Python 2 unicode or Python 3 str) in the L{pyxb._InputEncoding} encoding. @keyword default_namespace The L{pyxb.Namespace} in...
17,532
def within(self, x, ctrs, kdtree=None): if kdtree is None: idxs = np.where(lalg.norm(ctrs - x, axis=1) <= self.radius)[0] else: idxs = kdtree.query_ball_point(x, self.radius, p=2.0, eps=0) return idxs
Check which balls `x` falls within. Uses a K-D Tree to perform the search if provided.
17,533
def minute_frame_to_session_frame(minute_frame, calendar): how = OrderedDict((c, _MINUTE_TO_SESSION_OHCLV_HOW[c]) for c in minute_frame.columns) labels = calendar.minute_index_to_session_labels(minute_frame.index) return minute_frame.groupby(labels).agg(how)
Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `dt` (minute dts) calendar : trading_calendars.trading_calendar.Tradin...
17,534
def get_all_snapshots(self): data = self.get_data("snapshots/") return [ Snapshot(token=self.token, **snapshot) for snapshot in data[] ]
This method returns a list of all Snapshots.
17,535
def actions_for_project(self, project): project.cflags = ["-O3", "-fno-omit-frame-pointer"] project.runtime_extension = time.RunWithTime( run.RuntimeExtension(project, self)) return self.default_runtime_actions(project)
Compile & Run the experiment with -O3 enabled.
17,536
def update(self, *args, **kwargs): self._call_helper("Updating", self.real.update, *args, **kwargs)
This funcion updates a checkout of source code.
17,537
def makeEndOfPrdvFunc(self,EndOfPrdvP): vLvlNext = self.vFuncNext(self.mLvlNext,self.pLvlNext) EndOfPrdv = self.DiscFacEff*np.sum(vLvlNext*self.ShkPrbs_temp,axis=0) EndOfPrdvNvrs = self.uinv(EndOfPrdv) EndOfPrdvNvrsP = EndOfPrdvP*self.uinvP(End...
Construct the end-of-period value function for this period, storing it as an attribute of self for use by other methods. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal value of assets corresponding to the asset values in self.aLvlNow ...
17,538
def _plot_posterior_op( values, var_name, selection, ax, bw, linewidth, bins, kind, point_estimate, round_to, credible_interval, ref_val, rope, ax_labelsize, xt_labelsize, **kwargs ): def format_as_percent(x, round_to=0): return "{0:.{1...
Artist to draw posterior.
17,539
def memoize(func=None, maxlen=None): if func is not None: cache = BoundedOrderedDict(maxlen=maxlen) @functools.wraps(func) def memo_target(candidates, args): fitness = [] for candidate in candidates: lookup_value = pickle.dumps(candidate, 1) ...
Cache a function's return value each time it is called. This function serves as a function decorator to provide a caching of evaluated fitness values. If called later with the same arguments, the cached value is returned instead of being re-evaluated. This decorator assumes that candidates ar...
17,540
def _mpv_coax_proptype(value, proptype=str): if type(value) is bytes: return value; elif type(value) is bool: return b if value else b elif proptype in (str, int, float): return str(proptype(value)).encode() else: raise TypeError(.format(type(value), proptype))
Intelligently coax the given python value into something that can be understood as a proptype property.
17,541
def _parse_team_data(self, team_data): for field in self.__dict__: if field == or \ field == : continue value = utils._parse_field(PARSING_SCHEME, team_data, ...
Parses a value for every attribute. This function looks through every attribute and retrieves the value according to the parsing scheme and index of the attribute from the passed HTML data. Once the value is retrieved, the attribute's value is updated with the returned result. ...
17,542
def CreateLink(target_path, link_path, override=True): _AssertIsLocal(target_path) _AssertIsLocal(link_path) if override and IsLink(link_path): DeleteLink(link_path) dirname = os.path.dirname(link_path) if dirname: CreateDirectory(dirname) if sys.platform != : ...
Create a symbolic link at `link_path` pointing to `target_path`. :param unicode target_path: Link target :param unicode link_path: Fullpath to link name :param bool override: If True and `link_path` already exists as a link, that link is overridden.
17,543
def fftp(wave, npoints=None, indep_min=None, indep_max=None, unwrap=True, rad=True): r return phase(fft(wave, npoints, indep_min, indep_max), unwrap=unwrap, rad=rad)
r""" Return the phase of the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector ...
17,544
def count(expr): if isinstance(expr, SequenceExpr): unique_input = _extract_unique_input(expr) if unique_input: return nunique(unique_input).rename() else: return Count(_value_type=types.int64, _input=expr) elif isinstance(expr, SequenceGroupBy): ret...
Value counts :param expr: :return:
17,545
def return_abs_path(directory, path): if directory is None or path is None: return directory = os.path.expanduser(directory) return os.path.abspath(os.path.join(directory, path))
Unfortunately, Python is not smart enough to return an absolute path with tilde expansion, so I writing functionality to do this :param directory: :param path: :return:
17,546
def main(): plugins = DefaultPluginManager() plugins.load_plugins() parser, _ = create_argparser() for kls in updater_classes(): kls.register_arguments(parser) for kls in detector_classes(): kls.register_arguments(parser) from os import environ plugins.optio...
Run the main CLI program. Initializes the stack, parses command line arguments, and fires requested logic.
17,547
def parametrize_grid(self, debug=False): self._station.set_operation_voltage_level() self.default_branch_type,\ self.default_branch_type_aggregated,\ self.default_branch_type_settle = self.set_default_branch_type(debug) self.default...
Performs Parametrization of grid equipment: i) Sets voltage level of MV grid, ii) Operation voltage level and transformer of HV/MV station, iii) Default branch types (normal, aggregated, settlement) Args ---- debug: bool, defaults to False ...
17,548
def _correct_qualimap_genome_results(samples): for s in samples: if verify_file(s.qualimap_genome_results_fpath): correction_is_needed = False with open(s.qualimap_genome_results_fpath, ) as f: content = f.readlines() metrics_started = False ...
fixing java.lang.Double.parseDouble error on entries like "6,082.49"
17,549
def com_google_fonts_check_italic_angle(ttFont, style): failed = False value = ttFont["post"].italicAngle if value > 0: failed = True yield FAIL, Message("positive", ("The value of post.italicAngle is positive, which" " is likely a mistake and should...
Checking post.italicAngle value.
17,550
def get(self, name: str) -> Union[None, str, List[str]]: if name in self._headers: return self._headers[name] return None
获取 header
17,551
def produce_context(namespace, context_id, max_delay=None): try: context_obj = get_context(namespace, context_id) logger.info("Found context ", namespace, context_id) except ContextError: logger.info("Context not found", namespace, context_id) if max_delay is not None: ...
Produce event context.
17,552
def numberOfConnectedProximalSynapses(self, cells=None): if cells is None: cells = xrange(self.numberOfCells()) return _countWhereGreaterEqualInRows(self.proximalPermanences, cells, self.connectedPermanenceProximal)
Returns the number of proximal connected synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells.
17,553
def _ShouldPrintError(category, confidence, linenum): if category.startswith(one_filter[1:]): is_filtered = False else: assert False if is_filtered: return False return True
If confidence >= verbose, category passes filter and is not suppressed.
17,554
def on_service_departure(self, svc_ref): with self._lock: if svc_ref is self.reference: service = self._value self._current_ranking = None self._value = None self.reference = None ...
Called when a service has been unregistered from the framework :param svc_ref: A service reference
17,555
def _(pymux, variables): " Go to previous active window. " w = pymux.arrangement.get_previous_active_window() if w: pymux.arrangement.set_active_window(w)
Go to previous active window.
17,556
def CRPS(label, pred): for i in range(pred.shape[0]): for j in range(pred.shape[1] - 1): if pred[i, j] > pred[i, j + 1]: pred[i, j + 1] = pred[i, j] return np.sum(np.square(label - pred)) / label.size
Custom evaluation metric on CRPS.
17,557
def update(self,*flags): super(Flags,self).update([(flag.name,flag) for flag in flags])
Update Flags registry with a list of :class:`Flag` instances.
17,558
def get_configuration(self): mapping = {} settings = self.get_settings() for record in self.context.getAnalyses(): uid = record.get("service_uid") setting = settings.get(uid, {}) config = { "partition": record.get("partition"), ...
Returns a mapping of UID -> configuration
17,559
def decorator(wrapped_decorator): def helper(_func=None, **options): def outer_wrapper(func): @wrapping(func) def inner_wrapper(*args, **kwds): return wrapped_decorator(func, args, kwds, **options) return inner_wrapper if _func is None: return outer_wrapper ...
Converts a function into a decorator that optionally accepts keyword arguments in its declaration. Example usage: @utils.decorator def decorator(func, args, kwds, op1=None): ... apply op1 ... return func(*args, **kwds) # Form (1), vanilla @decorator foo(...) ... # Form (...
17,560
def parse_variable_definition(lexer: Lexer) -> VariableDefinitionNode: start = lexer.token return VariableDefinitionNode( variable=parse_variable(lexer), type=expect_token(lexer, TokenKind.COLON) and parse_type_reference(lexer), default_value=parse_value_literal(lexer, True) ...
VariableDefinition: Variable: Type DefaultValue? Directives[Const]?
17,561
def distroinfo(cargs, version=__version__): code = 1 args = docopt(__doc__, argv=cargs) try: if args[]: if not version: version = print(version) code = 0 elif args[]: code = fetch( info_url=args[], ...
distroinfo Command-Line Interface
17,562
def _normalize_server_settings(**settings): ret = dict() settings = salt.utils.args.clean_kwargs(**settings) for setting in settings: if isinstance(settings[setting], dict): value_from_key = next(six.iterkeys(settings[setting])) ret[setting] = "{{{0}}}".format(value_fr...
Convert setting values that has been improperly converted to a dict back to a string.
17,563
def returnOrderBook(self, currencyPair=, depth=): return self._public(, currencyPair=currencyPair, depth=depth)
Returns the order book for a given market, as well as a sequence number for use with the Push API and an indicator specifying whether the market is frozen. You may set currencyPair to "all" to get the order books of all markets.
17,564
def input_dim(self): n_cont = len(self.get_continuous_dims()) n_disc = len(self.get_discrete_dims()) return n_cont + n_disc
Extracts the input dimension of the domain.
17,565
def AddEventAttribute(self, attribute_name, attribute_value): if attribute_name in self._extra_event_attributes: raise KeyError(.format( attribute_name)) self._extra_event_attributes[attribute_name] = attribute_value
Adds an attribute that will be set on all events produced. Setting attributes using this method will cause events produced via this mediator to have an attribute with the provided name set with the provided value. Args: attribute_name (str): name of the attribute to add. attribute_value (s...
17,566
def compute_json(self, build_context): props = {} test_props = {} for prop in self.props: if prop in self._prop_json_blacklist: continue sig_spec = Plugin.builders[self.builder_name].sig.get(prop) if sig_spec is None: c...
Compute and store a JSON serialization of this target for caching purposes. The serialization includes: - The build flavor - The builder name - Target tags - Hashes of target dependencies & buildenv - Processed props (where target props are replaced with their...
17,567
def get_bandstructure(self): return LobsterBandStructureSymmLine(kpoints=self.kpoints_array, eigenvals=self.eigenvals, lattice=self.lattice, efermi=self.efermi, labels_dict=self.label_dict, structure=self.structure...
returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter
17,568
def pauli_expansion( val: Any, *, default: Union[value.LinearDict[str], TDefault] = RaiseTypeErrorIfNotProvided, atol: float = 1e-9 ) -> Union[value.LinearDict[str], TDefault]: method = getattr(val, , None) expansion = NotImplemented if method is None else method() if expansion...
Returns coefficients of the expansion of val in the Pauli basis. Args: val: The value whose Pauli expansion is to returned. default: Determines what happens when `val` does not have methods that allow Pauli expansion to be obtained (see below). If set, the value is returned ...
17,569
def get_value(self): def get_element_value(): if self.tag_name() == : return self.get_attribute() elif self.tag_name() == : selected_options = self.element.all_selected_options if len(selected_options) > 1: rais...
Gets the value of a select or input element @rtype: str @return: The value of the element @raise: ValueError if element is not of type input or select, or has multiple selected options
17,570
def to_header(self): d = dict(self) auth_type = d.pop("__auth_type__", None) or "basic" return "%s %s" % ( auth_type.title(), ", ".join( [ "%s=%s" % ( key, quo...
Convert the stored values into a WWW-Authenticate header.
17,571
def _analyze_single(self, reference, result): reference_str = str(reference) result_str = str(result) report = {: [], : [], : []} for i, (ref, res) in enumerate(zip(reference_str, result_str)): if ref != res: return report
Report mistmatches and indels for a single (aligned) reference and result.
17,572
def _fill_from_config(self, config): for k,v in config.items(): if k in H2OConnectionConf.allowed_properties: setattr(self, k, v) else: raise H2OValueError(message="Unsupported name of property: %s!" % k, var_name="config")
Fill this instance from given dictionary. The method only uses keys which corresponds to properties this class, throws exception on unknown property name. :param conf: dictionary of parameters :return: a new instance of this class filled with values from given dictionary :raise...
17,573
def sources(self): data = clips.data.DataObject(self._env) lib.EnvSlotSources(self._env, self._cls, self._name, data.byref) return tuple(data.value) if isinstance(data.value, list) else ()
A tuple containing the names of the Class sources for this Slot. The Python equivalent of the CLIPS slot-sources function.
17,574
def s(self, *args, **kwargs) -> Partial[Stepwise]: return Partial(Stepwise, self.base, *self.rules, *args, **kwargs)
Create an unbound prototype of this class, partially applying arguments .. code:: python @stepwise def control(pool: Pool, interval): return 10 pipeline = control.s(interval=20) >> pool :note: The partial rules are sealed, and :py:meth:`~.UnboundSt...
17,575
def getdateByTimezone(cDateUTC, timezone=None): dt = cDateUTC[0:19] if timezone and len(cDateUTC) == 25: tz = cDateUTC[19:25] tz = int(tz.split()[0]) dt = datetime.strptime(dt, ) dt = dt - timedelta(hours=tz) d...
Esse método trata a data recebida de acordo com o timezone do usuário. O seu retorno é dividido em duas partes: 1) A data em si; 2) As horas; :param cDateUTC: string contendo as informações da data :param timezone: timezone do usuário do sistema :return: data e hora convertidos para a time...
17,576
def change_dir(): try: d = os.environ[] sys.stderr.write( % d) except KeyError: pass else: try: os.chdir(d) except OSError: sys.stderr.write( % d)
Change the local directory if the HADOOPY_CHDIR environmental variable is provided
17,577
def plot_energy(time, H, T, U): T0 = T[0] H = H / T0 T = T / T0 U = U / T0 fig, ax = plt.subplots(figsize=[16,8]) ax.set_title() ax.set_xlabel() ax.set_ylabel() ax.plot(time, T, label=, color=) ax.plot(time, U, label=, color=) ax.plot(time, H, label=, colo...
Plot kinetic and potential energy of system over time
17,578
def to_json(self): cursor = self._get_cursor() cursor_object = False if cursor and isinstance(cursor, datastore_query.Cursor): cursor = cursor.to_websafe_string() cursor_object = True return {"key_range": self._key_range.to_json(), "query_spec": self._query_spec.to_json(), ...
Serializes all states into json form. Returns: all states in json-compatible map.
17,579
def get_kabsch_rotation(Q, P): A = np.dot(np.transpose(P), Q) V, S, W = np.linalg.svd(A) W = W.T d = np.linalg.det(np.dot(W, V.T)) return np.linalg.multi_dot((W, np.diag([1., 1., d]), V.T))
Calculate the optimal rotation from ``P`` unto ``Q``. Using the Kabsch algorithm the optimal rotation matrix for the rotation of ``other`` unto ``self`` is calculated. The algorithm is described very well in `wikipedia <http://en.wikipedia.org/wiki/Kabsch_algorithm>`_. Args: other (Cartesi...
17,580
def get_params(self, param=""): fullcurdir = os.path.realpath(os.path.curdir) if not param: for index, (key, value) in enumerate(self.paramsdict.items()): if isinstance(value, str): value = value.replace(fullcurdir+"/", "./") sys.s...
pretty prints params if called as a function
17,581
def remember_encrypted_identity(self, subject, encrypted): try: encoded = base64.b64encode(encrypted).decode() subject.web_registry.remember_me = encoded except AttributeError: msg = ("Subject argument is not an HTTP-aware instance. This " ...
Base64-encodes the specified serialized byte array and sets that base64-encoded String as the cookie value. The ``subject`` instance is expected to be a ``WebSubject`` instance with a web_registry handle so that an HTTP cookie may be set on an outgoing response. If it is not a ``WebSub...
17,582
def from_string(bnf: str, entry=None, *optional_inherit) -> Grammar: inherit = [Grammar] + list(optional_inherit) scope = {: bnf, : entry} return build_grammar(tuple(inherit), scope)
Create a Grammar from a string
17,583
def users_update(self, user_id, **kwargs): return self.__call_api_post(, userId=user_id, data=kwargs)
Update an existing user.
17,584
def as_yml(self): return YmlFileEvent(name=str(self.name), subfolder=str(self.subfolder))
Return yml compatible version of self
17,585
def build_permission_name(model_class, prefix): model_name = model_class._meta.object_name.lower() app_label = model_class._meta.app_label action_name = prefix perm = % (app_label, action_name, model_name) return perm
Build permission name for model_class (like 'app.add_model').
17,586
def create_attach_volumes(name, kwargs, call=None): volumesnodenodevolumes if call != : raise SaltCloudSystemExit( ) volumes = literal_eval(kwargs[]) node = kwargs[] conn = get_conn() node_data = _expand_node(conn.ex_get_node(node)) letter = ord() -...
.. versionadded:: 2017.7.0 Create and attach multiple volumes to a node. The 'volumes' and 'node' arguments are required, where 'node' is a libcloud node, and 'volumes' is a list of maps, where each map contains: size The size of the new disk in GB. Required. type The disk type, e...
17,587
def axes(self): return tuple(i for i in range(self.domain.ndim) if self.domain.shape[i] != self.range.shape[i])
Dimensions in which an actual resizing is performed.
17,588
def get_point(theta_ik, theta_jk, Pi, Pj): A = np.array([[sin(theta_ik), -cos(theta_ik)], [sin(theta_jk), -cos(theta_jk)]]) B = np.array([[sin(theta_ik), -cos(theta_ik), 0, 0], [0, 0, sin(theta_jk), -cos(theta_jk)]]) p = np.r_[Pi, Pj] Pk = np.linalg.solve(A, np.d...
Calculate coordinates of point Pk given two points Pi, Pj and inner angles. :param theta_ik: Inner angle at Pi to Pk. :param theta_jk: Inner angle at Pj to Pk. :param Pi: Coordinates of point Pi. :param Pj: Coordinates of point Pj. :return: Coordinate of point Pk.
17,589
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable=): bufsize = 4096 try: chan = self.ssh.get_transport().open_session() except Exception, e: msg = "Failed to open session" if len(str(e)) > 0: msg += ": %s" % ...
run a command on the remote host
17,590
def run_evaluation(self, stream_name: str) -> None: def prediction(): logging.info() self._run_zeroth_epoch([stream_name]) logging.info() self._try_run(prediction)
Run the main loop with the given stream in the prediction mode. :param stream_name: name of the stream to be evaluated
17,591
def joliet_vd_factory(joliet, sys_ident, vol_ident, set_size, seqnum, log_block_size, vol_set_ident, pub_ident_str, preparer_ident_str, app_ident_str, copyright_file, abstract_file, bibli_file, vol_expire_date, app_use, xa): t work. vol_set...
An internal function to create an Joliet Volume Descriptor. Parameters: joliet - The joliet version to use, one of 1, 2, or 3. sys_ident - The system identification string to use on the new ISO. vol_ident - The volume identification string to use on the new ISO. set_size - The size of the set o...
17,592
def generate(cls, size, string, filetype="JPEG"): render_size = max(size, GenAvatar.MAX_RENDER_SIZE) image = Image.new(, (render_size, render_size), cls._background_color(string)) draw = ImageDraw.Draw(image) font = cls._font(render_size) text =...
Generates a squared avatar with random background color. :param size: size of the avatar, in pixels :param string: string to be used to print text and seed the random :param filetype: the file format of the image (i.e. JPEG, PNG)
17,593
def partition_version_classifiers( classifiers: t.Sequence[str], version_prefix: str = , only_suffix: str = ) -> t.Tuple[t.List[str], t.List[str]]: versions_min, versions_only = [], [] for classifier in classifiers: version = classifier.replace(version_prefix, ) versions = v...
Find version number classifiers in given list and partition them into 2 groups.
17,594
def _create_source(self, src): if src[] == : pylike_src = pyLike.PointSource(self.like.logLike.observation()) pylike_src.setDir(src.skydir.ra.deg, src.skydir.dec.deg, False, False) elif src[] == : filepath = str(utils.path_to_xm...
Create a pyLikelihood Source object from a `~fermipy.roi_model.Model` object.
17,595
def register_job(self, job_details): try: job_details_old = self.get_details(job_details.jobname, job_details.jobkey) if job_details_old.status <= JobStatus.running: job_details_old.status = job_details.stat...
Register a job in this `JobArchive`
17,596
def update_vpnservice(self, vpnservice, body=None): return self.put(self.vpnservice_path % (vpnservice), body=body)
Updates a VPN service.
17,597
def nat_gateways(self): api_version = self._get_api_version() if api_version == : from .v2019_02_01.operations import NatGatewaysOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return Oper...
Instance depends on the API version: * 2019-02-01: :class:`NatGatewaysOperations<azure.mgmt.network.v2019_02_01.operations.NatGatewaysOperations>`
17,598
def conflicts_with(self, other): if isinstance(other, Requirement): if (self.name_ != other.name_) or (self.range is None) \ or (other.range is None): return False elif self.conflict: return False if other.conflict \ ...
Returns True if this requirement conflicts with another `Requirement` or `VersionedObject`.
17,599
def make_regular_points_with_no_res(bounds, nb_points=10000): minlon, minlat, maxlon, maxlat = bounds minlon, minlat, maxlon, maxlat = bounds offset_lon = (maxlon - minlon) / 8 offset_lat = (maxlat - minlat) / 8 minlon -= offset_lon maxlon += offset_lon minlat -= offset_lat maxlat +...
Return a regular grid of points within `bounds` with the specified number of points (or a close approximate value). Parameters ---------- bounds : 4-floats tuple The bbox of the grid, as xmin, ymin, xmax, ymax. nb_points : int, optionnal The desired number of points (default: 10000)...