Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
339,300
def _get_fit_params(self, x, fit_key): q, chiAz, chiBz = x[0], x[3], x[6] eta = q/(1.+q)**2 chi_wtAvg = (q*chiAz+chiBz)/(1.+q) chiHat = (chi_wtAvg - 38.*eta/113.*(chiAz + chiBz))/(1. - 76.*eta/113.) chi_a = (chiAz - chiBz)/2. fit_params = x fit_params[0]...
Transforms the input parameter to fit parameters for the 7dq2 model. That is, maps from x = [q, chiAx, chiAy, chiAz, chiBx, chiBy, chiBz] fit_params = [np.log(q), chiAx, chiAy, chiHat, chiBx, chiBy, chi_a] chiHat is defined in Eq.(3) of 1508.07253, but with chiAz and chiBz instead of chiA and chiB....
339,301
def _get_attention(inp_text, out_text, enc_atts, dec_atts, encdec_atts): def get_full_attention(layer): enc_att = enc_atts[layer][0] dec_att = dec_atts[layer][0] encdec_att = encdec_atts[layer][0] enc_att = np.transpose(enc_att, [0, 2, 1]) dec_att = np.transpose(dec_att, [0, 2, 1]) enc...
Compute representation of the attention ready for the d3 visualization. Args: inp_text: list of strings, words to be displayed on the left of the vis out_text: list of strings, words to be displayed on the right of the vis enc_atts: numpy array, encoder self-attentions [num_layers, batch_size, nu...
339,302
def Tethering_unbind(self, port): assert isinstance(port, (int,) ), "Argument must be of type int. Received type: " % type( port) subdom_funcs = self.synchronous_command(, port=port) return subdom_funcs
Function path: Tethering.unbind Domain: Tethering Method name: unbind Parameters: Required arguments: 'port' (type: integer) -> Port number to unbind. No return value. Description: Request browser port unbinding.
339,303
def simplify_path(path: str, path_prefixes: list = None) -> str: test_path = .format(path if path else ) replacements = (path_prefixes if path_prefixes else []).copy() replacements.append((, os.path.expanduser())) for key, value in replacements: if test_path.startswith(value): ...
Simplifies package paths by replacing path prefixes with values specified in the replacements list :param path: :param path_prefixes: :return:
339,304
def from_timeseries(ts1, ts2, stride, fftlength=None, overlap=None, window=None, nproc=1, **kwargs): if fftlength is None: fftlength = stride / 2. nsteps = int(ts1.size // (stride * ts1.sample_rate.value)) nproc = min(nsteps, nproc) if nsteps == 0 or npr...
Calculate the coherence `Spectrogram` between two `TimeSeries`. Parameters ---------- timeseries : :class:`~gwpy.timeseries.TimeSeries` input time-series to process. stride : `float` number of seconds in single PSD (column of spectrogram). fftlength : `float` number of secon...
339,305
def _get_endpoint(self): return SSHCommandClientEndpoint.newConnection( reactor, b, self.username, self.hostname, port=self.port, keys=self.keys, password=self.password, knownHosts = self.knownHosts)
Creates a generic endpoint connection that doesn't finish
339,306
def to_ascii_hex(value: int, digits: int) -> str: if digits < 1: return text = for _ in range(0, digits): text = chr(ord() + (value % 0x10)) + text value //= 0x10 return text
Converts an int value to ASCII hex, as used by LifeSOS. Unlike regular hex, it uses the first 6 characters that follow numerics on the ASCII table instead of A - F.
339,307
def dbscan(self, eps=0.75, min_samples=3): est = DBSCAN(metric=, eps=eps, min_samples=min_samples) est.fit(self.get_dm(False)) return Partition(est.labels_)
:param kwargs: key-value arguments to pass to DBSCAN (eps: max dist between points in same neighbourhood, min_samples: number of points in a neighbourhood) :return:
339,308
def extract(fileobj, keywords, comment_tags, options): extractor = BabelMakoExtractor(keywords, comment_tags, options) for message in extractor(fileobj): yield message
Extract messages from Mako templates. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and...
339,309
def _kbos_from_survey_sym_model_input_file(model_file): lines = storage.open_vos_or_local(model_file).read().split() kbos = [] for line in lines: if len(line) == 0 or line[0] == : continue kbo = ephem.EllipticalBody() values = line.split() kbo.name = values...
Load a Survey Simulator model file as an array of ephem EllipticalBody objects. @param model_file: @return:
339,310
def validate(): with current_app.test_request_context(): schema = json.loads(json.dumps(api.__schema__)) try: schemas.validate(schema) success() except schemas.SchemaValidationError as e: exit_with_error(, e)
Validate the Swagger/OpenAPI specification with your config
339,311
def main(argv=None): cmd_opts = parse_cmdline(argv)[0] if cmd_opts.confpath is not None: if os.path.exists(cmd_opts.confpath): conf_paths = [cmd_opts.confpath,] else: return "Configuration file not found: %s" % cmd_opts.confpath else: conf_paths = [os.pat...
Main Block - Configure and run the Bottle Web Server.
339,312
def _generate_data_key(self, algorithm, encryption_context): plaintext_data_key = os.urandom(algorithm.kdf_input_len) encrypted_data_key = self._encrypt_data_key( data_key=RawDataKey(key_provider=self.key_provider, data_key=plaintext_data_key), algorithm=algorithm, ...
Generates data key and returns :class:`aws_encryption_sdk.structures.DataKey`. :param algorithm: Algorithm on which to base data key :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param dict encryption_context: Encryption context to use in encryption :returns: Generated data...
339,313
def _get_stddevs(self, C, stddev_types, nsites): stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(C[] + np.zeros(nsites, dtype=float)) ...
Compute total standard deviation, see table 4.2, page 50.
339,314
def checkout(self, revision=None, clean=False): self.create() self.ensure_working_tree() revision = revision or self.default_revision logger.info("Checking out revision in %s ..", revision, format_path(self.local)) self.context.execute(*self.get_checko...
Update the working tree of the local repository to the specified revision. :param revision: The revision to check out (a string, defaults to :attr:`default_revision`). :param clean: :data:`True` to discard changes in the working tree, :data:`False` otherwi...
339,315
def fetch_post_data(self): post_data = {} ext_dic = {} for key in self.request.arguments: if key.startswith() or key.startswith(): ext_dic[key] = self.get_argument(key) else: post_data[key] = self.get_arguments(key)[0] pos...
fetch post accessed data. post_data, and ext_dic.
339,316
def on_message(self, ws, message): try: data = json.loads(message) except Exception: self._set_error(message, "decode message failed") else: self._inbox.put(RTMMessage(data))
Websocket on_message event handler Saves message as RTMMessage in self._inbox
339,317
def init_backend(limit=None): backend._limit = limit keyrings = filter(limit, backend.get_all_keyring()) set_keyring( load_env() or load_config() or max(keyrings, default=fail.Keyring(), key=backend.by_priority) )
Load a keyring specified in the config file or infer the best available. Limit, if supplied, should be a callable taking a backend and returning True if that backend should be included for consideration.
339,318
def get_data_multiplication_queue(model_description_multiply): return utils.get_objectlist(model_description_multiply, config_key=, module=sys.modules[__name__])
Get features from a list of dictionaries >>> l = [{'Multiply': [{'nr': 1}]}, \ {'Rotate': [{'minimum':-30}, {'maximum': 30}, {'step': 5}]}] >>> get_data_multiplication_queue(l) [Multiply (1 times), Rotate (-30.00, 30.00, 5.00)]
339,319
def set(self, value): if isinstance(value, set): if self._map is None: raise ValueError(unwrap( , type_name(self) )) bits = [0] * self._size self._native = value for index in range(...
Sets the value of the object :param value: An integer or a tuple of integers 0 and 1 :raises: ValueError - when an invalid value is passed
339,320
def set_cluster_info(self, aws_access_key_id=None, aws_secret_access_key=None, aws_region=None, aws_availability_zone=None, vpc_id=None, subnet_id=None, master_elastic_ip...
Kwargs: `aws_access_key_id`: The access key id for customer's aws account. This is required for creating the cluster. `aws_secret_access_key`: The secret access key for customer's aws account. This is required for creating the cluster. `aws_region`: AWS region to creat...
339,321
def insert_line_below(self, copy_margin=True): if copy_margin: insert = + self.document.leading_whitespace_in_current_line else: insert = self.cursor_position += self.document.get_end_of_line_position() self.insert_text(insert)
Insert a new line below the current one.
339,322
def _create_projects_file(project_name, data_source, items): repositories = [] for item in items: if item[] not in repositories: repositories.append(item[]) projects = { project_name: { data_source: repositories } } projects_file, projects_file_...
Create a projects file from the items origin data
339,323
def get_api_keys(request): with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute() api_keys = [x[0] for x in cursor.fetchall()] return api_keys
Return the list of API keys.
339,324
def __input_thread(self): "Input thread" last_input = time.time() while self.alive: x = input(config.prompt) self.issue_alert = (time.time() - last_input) > 10 last_input = time.time() msg = self.name + + x if self.mode == : ...
Input thread
339,325
def BGPNeighborPrefixExceeded_originator_switch_info_switchIpV6Address(self, **kwargs): config = ET.Element("config") BGPNeighborPrefixExceeded = ET.SubElement(config, "BGPNeighborPrefixExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ET.Sub...
Auto Generated Code
339,326
def get_status(self): try: api_response = self.api.read_namespaced_service_status(self.name, self.namespace) except ApiException as e: raise ConuException( "Exception when calling Kubernetes API - read_namespaced_service_status: %s\n" % e) retur...
get status of service :return: V1ServiceStatus, https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1ServiceStatus.md
339,327
def flush(self): if not self.items: return retry = 0 options = {"deadline": DATASTORE_DEADLINE} while retry <= self.__timeout_retries: try: self.__flush_function(self.items, options) self.clear() break except db.Timeout, e: logging.warning(e) ...
Force a flush.
339,328
def any2sha1(text): if type(text) in [dict, list]: text = json.dumps(text, sort_keys=True) if isinstance(text, unicode): text = text.encode() return hashlib.sha1(text).hexdigest()
convert a string into sha1hash. For json object/array, first convert it into canonical json string.
339,329
def get_merge_bases(self, repository_name_or_id, commit_id, other_commit_id, project=None, other_collection_id=None, other_repository_id=None): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) if repository_name_or_id is not None: ...
GetMergeBases. [Preview API] Find the merge bases of two commits, optionally across forks. If otherRepositoryId is not specified, the merge bases will only be calculated within the context of the local repositoryNameOrId. :param str repository_name_or_id: ID or name of the local repository. :par...
339,330
def date_field_data(field, **kwargs): from_date = kwargs.get(, date(1990, 1, 1)) to_date = kwargs.get(, date.today()) date_format = random.choice(field.input_formats or formats.get_format()) return xunit.any_date(from_date=from_date, to_date=to_date).strftime(d...
Return random value for DateField >>> result = any_form_field(forms.DateField()) >>> type(result) <type 'str'>
339,331
def check_permission(cls, role, permission): result = permission in settings.ARCTIC_ROLES[role] if result: try: return getattr(cls, permission)(role) except AttributeError: pass return result
Check if role contains permission
339,332
def sync_state(self): self.sync_ik_robot(self.robot_jpos_getter()) pos_r, orn_r, pos_l, orn_l = self.ik_robot_eef_joint_cartesian_pose() self.ik_robot_target_pos_right = pos_r self.ik_robot_target_orn_right = orn_r self.ik_robot_target_pos_left = pos...
Syncs the internal Pybullet robot state to the joint positions of the robot being controlled.
339,333
def _linkcode_resolve(domain, info, package, url_fmt, revision): if revision is None: return if domain not in (, ): return if not info.get() or not info.get(): return class_name = info[].split()[0] if type(class_name) != str: class_name = class_name.en...
Determine a link to online source for a class/method/function This is called by sphinx.ext.linkcode An example with a long-untouched module that everyone has >>> _linkcode_resolve('py', {'module': 'tty', ... 'fullname': 'setraw'}, ... package='tty', ....
339,334
def predict(self, u=0): A = dot(self._F_inv.T, self.P_inv).dot(self._F_inv) try: AI = self.inv(A) invertable = True if self._no_information: try: self.x = dot(self.inv(self.P_inv), self.x) ...
Predict next position. Parameters ---------- u : ndarray Optional control vector. If non-zero, it is multiplied by B to create the control input into the system.
339,335
def set_volume(self, percent, update_group=True): if percent not in range(0, 101): raise ValueError() new_volume = self._client[][] new_volume[] = percent self._client[][][] = percent yield from self._server.client_volume(self.identifier, new_volume) ...
Set client volume percent.
339,336
def com_google_fonts_check_glyf_unused_data(ttFont): try: expected_glyphs = len(ttFont.getGlyphOrder()) actual_glyphs = len(ttFont[].glyphs) diff = actual_glyphs - expected_glyphs if diff < 0: yield FAIL, Message("unreachable-data", ("Glyf table has unreachable data...
Is there any unused data at the end of the glyf table?
339,337
def children(self, alias, bank_id): return self._root + self._safe_alias(alias) + + str(bank_id)
URL for getting or setting child relationships for the specified bank :param alias: :param bank_id: :return:
339,338
def formatTimeFromNow(secs=0): return datetime.utcfromtimestamp(time.time() + int(secs)).strftime(timeformat)
Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str
339,339
def _update_lhs(lhs, xCore, zCore, new_lhs): r_old_x, n, r_x = xCore.shape num_obj, r_old_z, n, r_z = zCore.shape for idx in range(num_obj): for val in range(n): for alpha_old_z in range(r_old_z): for alpha_z in range(r_z): for alpha_old_x in...
Function to be called from the project()
339,340
def add_mvn(self, name, input_name, output_name, across_channels = True, normalize_variance = True, epsilon = 1e-5): spec = self.spec nn_spec = self.nn_spec spec_layer = nn_spec.layers.add() spec_layer.name = name spec_layer.input.append(input_name) sp...
Add an MVN (mean variance normalization) layer. Computes mean, variance and normalizes the input. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str The output blob name...
339,341
def _obtain_token(self): if self.expiration and self.expiration > datetime.datetime.now(): return resp = requests.post("{}/1.1/oauth/token".format(API_URL), data={ "client_id": self.client_id, "client_secret": self.client_secret, "grant...
Obtain an auth token from client id and client secret.
339,342
def send_signature_request(self, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, metadata=None, ux_version=None, allow_decline=False): ...
Creates and sends a new SignatureRequest with the submitted documents Creates and sends a new SignatureRequest with the submitted documents. If form_fields_per_document is not specified, a signature page will be affixed where all signers will be required to add their signature, signifyi...
339,343
async def sinter(self, keys, *args): k = list_or_args(keys, args) res = await self.smembers(k[0]) for arg in k[1:]: res &= await self.smembers(arg) return res
Return the intersection of sets specified by ``keys`` Cluster impl: Querry all keys, intersection and return result
339,344
def optimize(self, duplicate_manager=None): if not self.analytical_gradient_acq: out = self.optimizer.optimize(f=self.acquisition_function, duplicate_manager=duplicate_manager) else: out = self.optimizer.optimize(f=self.acquisition_function, f_df=self.acquisition_functio...
Optimizes the acquisition function (uses a flag from the model to use gradients or not).
339,345
def get_cache(subfolder=None, quiet=False): s cache for singularity. :param subfolder: a subfolder in the cache base to retrieve, specifically t exist mkdir_p(cache_base) if not quiet: bot.debug("Cache folder set to %s" % cache_base) return cache_base
get_cache will return the user's cache for singularity. :param subfolder: a subfolder in the cache base to retrieve, specifically
339,346
def get_json(self): if self.dhcp_usage: return {: self.dhcp_usage, : self.iqn} else: return self.get_basic_json()
Create JSON data for iSCSI initiator. :returns: JSON data for iSCSI initiator as follows: { "DHCPUsage":{ }, "Name":{ }, "IPv4Address":{ }, "SubnetMask":{ }, ...
339,347
def conditions(self, start, last_attempt): if time.time() - start > self.timeout: yield WaitCondition.Timedout return if last_attempt is not None and time.time() - last_attempt < self.wait_between_attempts: yield WaitCondition.KeepWaiting return ...
Yield lines to execute in a docker context All conditions must evaluate for the container to be considered ready
339,348
def build_alias_map(regex_map, tag_vocab): import utool as ut import re alias_map = ut.odict([]) for pats, new_tag in reversed(regex_map): pats = ut.ensure_iterable(pats) for pat in pats: flags = [re.match(pat, t) for t in tag_vocab] for old_tag in ut.compres...
Constructs explicit mapping. Order of items in regex map matters. Items at top are given preference. Example: >>> # DISABLE_DOCTEST >>> tags_list = [['t1', 't2'], [], ['t3'], ['t4', 't5']] >>> tag_vocab = ut.flat_unique(*tags_list) >>> regex_map = [('t[3-4]', 'A9'), ('t0', 'a0')...
339,349
def apply_and_save(self): patches = self.patches content = None with open(self.IN_PATH) as f_in: f_out.write(content) self.pathces = out_patches content = None
Apply replaced words and patches, and save setup.py file.
339,350
def get_team_id(team_name): df = get_all_team_ids() df = df[df.TEAM_NAME == team_name] if len(df) == 0: er = "Invalid team name or there is no team with that name." raise ValueError(er) team_id = df.TEAM_ID.iloc[0] return team_id
Returns the team ID associated with the team name that is passed in. Parameters ---------- team_name : str The team name whose ID we want. NOTE: Only pass in the team name (e.g. "Lakers"), not the city, or city and team name, or the team abbreviation. Returns ------- t...
339,351
def run_tpm(tpm, time_scale): sbs_tpm = convert.state_by_node2state_by_state(tpm) if sparse(tpm): tpm = sparse_time(sbs_tpm, time_scale) else: tpm = dense_time(sbs_tpm, time_scale) return convert.state_by_state2state_by_node(tpm)
Iterate a TPM by the specified number of time steps. Args: tpm (np.ndarray): A state-by-node tpm. time_scale (int): The number of steps to run the tpm. Returns: np.ndarray
339,352
def phase_histogram(dts, times=None, nbins=30, colormap=mpl.cm.Blues): if times is None: times = np.linspace(dts.tspan[0], dts.tspan[-1], num=4) elif isinstance(times, numbers.Number): times = np.array([times], dtype=np.float64) indices = distob.gather(dts.tspan.searchsorted(times)) ...
Plot a polar histogram of a phase variable's probability distribution Args: dts: DistTimeseries with axis 2 ranging over separate instances of an oscillator (time series values are assumed to represent an angle) times (float or sequence of floats): The target times at which to plot the ...
339,353
def _clean_body_df(self, df): if self.suffix == : df = df.dropna(subset=(, , , ), how=).reset_index(drop=True) df.units = {: , : , : , : , : , ...
Format the dataframe, remove empty rows, and add units attribute.
339,354
def generate_account_shared_access_signature(self, resource_types, permission, expiry, start=None, ip=None, protocol=None): _validate_not_none(, self.account_name) _validate_not_none(, self.account_key) sas = SharedAccessSignature(self.account_n...
Generates a shared access signature for the table service. Use the returned signature with the sas_token parameter of TableService. :param ResourceTypes resource_types: Specifies the resource types that are accessible with the account SAS. :param AccountPermissions permission: ...
339,355
def setup(pin, mode, pullup=None, initial=False): if pullup is not None: raise ValueError("sysfs does not support pullups") if mode not in (IN, OUT, LOW, HIGH): raise ValueError(mode) log.debug("Setup {0}: {1}".format(pin, mode)) f = _open[pin].direction _write(f, mo...
Setup pin with mode IN or OUT. Args: pin (int): mode (str): use either gpio.OUT or gpio.IN pullup (None): rpio compatibility. If anything but None, raises value Error pullup (bool, optional): Initial pin value. Default is False
339,356
def delete_clinvar_object(self, object_id, object_type, submission_id): LOG.info("Deleting clinvar object %s (%s)", object_id, object_type) result = if object_type == : self.clinvar_submission_collection.find_one_and_update( {: Ob...
Remove a variant object from clinvar database and update the relative submission object Args: object_id(str) : the id of an object to remove from clinvar_collection database collection (a variant of a case) object_type(str) : either 'variant_data' or 'case_data'. It's a key ...
339,357
def modelnumericfunctions(self): lines = Lines() lines.extend(self.solve) lines.extend(self.calculate_single_terms) lines.extend(self.calculate_full_terms) lines.extend(self.get_point_states) lines.extend(self.set_point_states) lines.extend(self.set_resul...
Numerical functions of the model class.
339,358
def is_output_supports_color(): plat = sys.platform supported_platform = plat != and (plat != or in os.environ) is_a_tty = hasattr(sys.stdout, ) and sys.stdout.isatty() if not supported_platform or not is_a_tty: return False return True
Returns True if the running system's terminal supports color, and False otherwise.
339,359
def _connect(self, server, port, tls=True, tls_verify=True, proxy=False, proxy_type=, proxy_server=None, proxy_port=None, proxy_username=None, proxy_password=None): with self.lock: if proxy: if proxy_type == : proxy_type ...
Connects the socket to an IRC server. Required arguments: * server - Server to connect to. * port - Port to use. Optional arguments: * tls=True - Should we use TLS/SSL? * tls_verify=True - Verify the TLS certificate? Only works with Python 3. * pro...
339,360
def _filter_update_security_group_rule(rule): allowed = [, ] filtered = {} for k, val in rule.iteritems(): if k in allowed: if isinstance(val, basestring) and \ len(val) <= GROUP_NAME_MAX_LENGTH: filtered[k] = val return filtered
Only two fields are allowed for modification: external_service and external_service_id
339,361
def power_chisq_bins_from_sigmasq_series(sigmasq_series, num_bins, kmin, kmax): sigmasq = sigmasq_series[kmax - 1] edge_vec = numpy.arange(0, num_bins) * sigmasq / num_bins bins = numpy.searchsorted(sigmasq_series[kmin:kmax], edge_vec, side=) bins += kmin return numpy.append(bins, kmax)
Returns bins of equal power for use with the chisq functions Parameters ---------- sigmasq_series: FrequencySeries A frequency series containing the cumulative power of a filter template preweighted by a psd. num_bins: int The number of chisq bins to calculate. kmin: int ...
339,362
def page_list( request, template_name=, extra_context=None ): page_list = WikiPage.objects.all() page_list = page_list.order_by() template_context = { : page_list, : getattr(settings, , ), } template_context.update(extra_context or {}) return render(request, template_na...
Displays all Pages
339,363
def add_inputs(self, xs): states = [] cur = self for x in xs: cur = cur.add_input(x) states.append(cur) return states
returns the list of states obtained by adding the given inputs to the current state, one by one.
339,364
def get_height(self, points, edge=True): for poly in self: points = poly.get_height(points, edge=edge, full=True) for hole in self.holes: pip = hole.contains(points, edge=True) points[pip, 2] = np.nan return points
Given a set of points, computes the z value for the parametric equation of the Polygons in the Surface. This method computes recursively the ``Polygon.get_height()`` method for all the Polygons in the Surface, obtaining the z value for the points according to the local Pol...
339,365
def build(cls: Type[T], data: Generic) -> T: fields = fields_dict(cls) kwargs: Dict[str, Any] = {} for key, value in data.items(): if key in fields: if isinstance(value, Mapping): t = fields[key].type if issubclass(t, A...
Build objects from dictionaries, recursively.
339,366
def _strip_cache_events(data, opts): event_data = copy.deepcopy(data) strip_fields = opts.get(, []) for field in strip_fields: if field in event_data: del event_data[field] return event_data
Strip out user-configured sensitive event data. The fields to be stripped are configured in the main Salt Cloud configuration file, usually ``/etc/salt/cloud``. .. code-block: yaml cache_event_strip_fields: - password - priv_key .. versionadded:: 2014.7.0
339,367
def from_array(array): if array is None or not array: return None assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.reply_markup import InlineKeyboardButton data = {} data[] = InlineKeyboardButton.fro...
Deserialize a new InlineKeyboardMarkup from a given dictionary. :return: new InlineKeyboardMarkup instance. :rtype: InlineKeyboardMarkup
339,368
def get_year_description(self): def format_year(s): regex = re.compile(r"^\d+$") if regex.match(s): year_int = int(s) if year_int < 1900: return year_int return datetime.date(year_int, 1, 1).strftime("%Y") ...
Generates a description for only the YEAR portion of the expression Returns: The YEAR description
339,369
def send_email(self, to): body = self.body() subject = self.subject() import letter class Message(letter.Letter): Postie = letter.DjangoPostman() From = getattr(settings, , ) To = to Subject = subject Body ...
Do work.
339,370
def get_secret(secret_name, default=None): secrets_dir = get_secrets_dir() secret_path = os.path.join(secrets_dir, secret_name) try: with open(secret_path, "r") as secret_file: return secret_file.read() except OSError: return default
Gets contents of secret file :param secret_name: The name of the secret present in BANANAS_SECRETS_DIR :param default: Default value to return if no secret was found :return: The secret or default if not found
339,371
def clear(self): self.__modified_data__ = {} self.__deleted_fields__ = [field for field in self.__original_data__.keys()]
Clears all the data in the object, keeping original data
339,372
def full_research_organism(soup): "research-organism list including inline tags, such as italic" if not raw_parser.research_organism_keywords(soup): return [] return list(map(node_contents_str, raw_parser.research_organism_keywords(soup)))
research-organism list including inline tags, such as italic
339,373
def parse_xml_node(self, node): self.connector_id = node.getAttributeNS(RTS_NS, ) self.name = node.getAttributeNS(RTS_NS, ) self.data_type = node.getAttributeNS(RTS_NS, ) self.interface_type = node.getAttributeNS(RTS_NS, ) self.data_flow_type = node.getAttributeNS(RTS_NS...
Parse an xml.dom Node object representing a data connector into this object.
339,374
def fcsp_sa_fcsp_auth_policy_switch(self, **kwargs): config = ET.Element("config") fcsp_sa = ET.SubElement(config, "fcsp-sa", xmlns="urn:brocade.com:mgmt:brocade-fc-auth") fcsp = ET.SubElement(fcsp_sa, "fcsp") auth = ET.SubElement(fcsp, "auth") policy = ET.SubElement(aut...
Auto Generated Code
339,375
def change_prior(self,**kwargs): for kw,val in kwargs.items(): if kw==: logging.warning() continue for pop in self.poplist: k = {kw:val} pop.change_prior(**k)
Changes prior factor(s) in all populations
339,376
def _find_usage_parameter_groups(self): num_groups = 0 paginator = self.conn.get_paginator() for page in paginator.paginate(): for group in page[]: num_groups += 1 self.limits[]._add_current_usage( num_groups, aws_type= ...
find usage for elasticache parameter groups
339,377
def has_permission(self, permission): f = self.create_future() if self.api_level < 23: f.set_result(True) return f def on_result(allowed): result = allowed == Activity.PERMISSION_GRANTED self.set_future_result(f, result) ...
Return a future that resolves with the result of the permission
339,378
def add_column(self, name, data): super(DataFrameArrays, self).add_column(name, data) self._length_unfiltered = int(round(self._length_original * self._active_fraction))
Add a column to the DataFrame :param str name: name of column :param data: numpy array with the data
339,379
def set_acl(self, acl_or_str, key_name=, validate=True, headers=None, version_id=None): if not self.bucket_name: raise InvalidUriError( % self.uri) self.get_bucket(validate, headers).set_acl(acl_or_str, key_name, ...
sets or updates a bucket's acl
339,380
def lsm_data_to_arc_ascii(self, data_var_map_array, main_output_folder=""): self._check_lsm_input(data_var_map_array) if not main_output_folder: main_output_folder = path.join(self.gssha_project_folder, "hmet_ascii_data") try: ...
Writes extracted data to Arc ASCII file format into folder to be read in by GSSHA. Also generates the HMET_ASCII card file for GSSHA in the folder named 'hmet_file_list.txt'. .. warning:: For GSSHA 6 Versions, for GSSHA 7 or greater, use lsm_data_to_subset_netcdf. .. note:: ...
339,381
def add_device(self, params): return DistributionDevice.create(self.api, distribution_id=self.id, **params)
Method for `Add Device to an Existing Distribution <https://m2x.att.com/developer/documentation/v2/distribution#Add-Device-to-an-existing-Distribution>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. :return: The newly cre...
339,382
def autodiscover(self, module_name=None, verbose=False): module_name = module_name or "notifications" verbose = True if verbose is None else verbose sys.stdout.write(f" * checking for {module_name} ...\n") for app in django_apps.app_configs: try: mod ...
Autodiscovers classes in the notifications.py file of any INSTALLED_APP.
339,383
def dot_product_self_attention_relative_v2(q, k, v, bias, max_relative_position=None, dropout_rate=0.0, ...
Calculate relative position-aware dot-product self-attention. Only works for masked self-attention (no looking forward). The attention calculation is augmented with learned representations for the relative position between each element in q and each element in k and v. Args: q: a Tensor with shape [batch...
339,384
def tocvx(B): Bcoo = B.tocoo() return spmatrix(Bcoo.data, Bcoo.row.tolist(), Bcoo.col.tolist())
Converts a sparse SciPy matrix into a sparse CVXOPT matrix.
339,385
def get_build_flavor(settings_module, args): known_flavors = listify(call_user_func(settings_module, )) if args.flavor: if args.flavor not in known_flavors: raise ValueError(.format(args.flavor)) else: args.flavor = call_user_func(settings_module, ) if args.flavor an...
Update the flavor arg based on the settings API
339,386
def _convert_to_wakat_format(seeder_struct): def pick_active(seeder_struct, what): items = seeder_struct.get(what) if not items: return None if not (isinstance(items, list) or isinstance(items, tuple)): items = [items] active_items = [item for...
Convert Seeder's structure to the internal structure used at frontend. Args:, seeder_struct (dict): Dictionary with Seeder data. Returns: obj: :class:`Model`.
339,387
def sorted_dict_repr(d): keys = list(d.keys()) keys.sort() return "{" + ", ".join(["%r: %r" % (k, d[k]) for k in keys]) + "}"
repr() a dictionary with the keys in order. Used by the lexer unit test to compare parse trees based on strings.
339,388
def _generate_client_h(self, api): self.emit_raw(stone_warning) self.emit() import_classes = [ fmt_routes_class(ns.name, self.args.auth_type) for ns in api.namespaces.values() if ns.routes and self.namespace_to_has_routes[ns] ] impor...
Generates client base header file. For each namespace, the client will have an object field that encapsulates each route in the particular namespace.
339,389
def learn(self, matches, recall): compound_length = 2 dupe_cover = Cover(self.blocker.predicates, matches) dupe_cover.dominators(cost=self.total_cover) dupe_cover.compound(compound_length) comparison_count = self.comparisons(dupe_cover, compound_length) dupe_c...
Takes in a set of training pairs and predicates and tries to find a good set of blocking rules.
339,390
async def click(self, i=None, j=None, *, text=None, filter=None, data=None): if data: if not await self.get_input_chat(): return None try: return await self._client( functions.messages.GetBotCallbackAnswerR...
Calls `telethon.tl.custom.messagebutton.MessageButton.click` for the specified button. Does nothing if the message has no buttons. Args: i (`int`): Clicks the i'th button (starting from the index 0). Will ``raise IndexError`` if out of bounds. Exampl...
339,391
def convert_transpose(net, node, module, builder): input_name, output_name = _get_input_output_name(net, node) name = node[] param = _get_attrs(node) axes = literal_eval(param[]) builder.add_permute(name, axes, input_name, output_name)
Convert a transpose layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
339,392
def set_flushing_policy(flushing_policy): if "RAY_USE_NEW_GCS" not in os.environ: raise Exception( "set_flushing_policy() is only available when environment " "variable RAY_USE_NEW_GCS is present at both compile and run time." ) ray.worker.global_worker.check_connect...
Serialize this policy for Monitor to pick up.
339,393
def do_time(self, params): start = time.time() for cmd in params.cmds: try: self.onecmd(cmd) except Exception as ex: self.show_output("Command failed: %s.", ex) elapsed = "{0:.5f}".format(time.time() - start) self.show_out...
\x1b[1mNAME\x1b[0m time - Measures elapsed seconds after running commands \x1b[1mSYNOPSIS\x1b[0m time <cmd1> <cmd2> ... <cmdN> \x1b[1mEXAMPLES\x1b[0m > time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"' Took 0.05585 seconds
339,394
def getall(self, key): if key in self: return [self[key]] else: key = key + return [v for s, v in self.items() if s.startswith(key)]
Return all frames with a given name (the list may be empty). This is best explained by examples:: id3.getall('TIT2') == [id3['TIT2']] id3.getall('TTTT') == [] id3.getall('TXXX') == [TXXX(desc='woo', text='bar'), TXXX(desc='baz', text='quuu...
339,395
def pipe_handle(loc, tokens, **kwargs): internal_assert(set(kwargs) <= set(("top",)), "unknown pipe_handle keyword arguments", kwargs) top = kwargs.get("top", True) if len(tokens) == 1: item = tokens.pop() if not top: return item name, split_item = pipe_i...
Process pipe calls.
339,396
def remove_component(self, entity: int, component_type: Any) -> int: self._components[component_type].discard(entity) if not self._components[component_type]: del self._components[component_type] del self._entities[entity][component_type] if not self._entities[ent...
Remove a Component instance from an Entity, by type. A Component instance can be removed by providing it's type. For example: world.delete_component(enemy_a, Velocity) will remove the Velocity instance from the Entity enemy_a. Raises a KeyError if either the given entity or Component t...
339,397
def previous_close(self, dt): idx = previous_divider_idx(self.market_closes_nanos, dt.value) return pd.Timestamp(self.market_closes_nanos[idx], tz=UTC)
Given a dt, returns the previous close. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous close. Returns ------- pd.Timestamp The UTC timestamp of the previous close.
339,398
def get_type(self): if self == silhouette_ksearch_type.KMEANS: return kmeans elif self == silhouette_ksearch_type.KMEDIANS: return kmedians elif self == silhouette_ksearch_type.KMEDOIDS: return kmedoids else: return None
! @brief Returns algorithm type that corresponds to specified enumeration value. @return (type) Algorithm type for cluster analysis.
339,399
def to_dict(x, depth, exclude_keys=set(), depth_threshold=8): if x is None or isinstance(x, (str, int, float, bool)): return x if isinstance(x, np.int_): return int(x) if isinstance(x, np.int64): return int(x) if isinstance(x, np.float_): return float(x) if isins...
Transform a nested object/dict/list into a regular dict json.dump(s) and pickle don't like to un/serialize regular Python objects so this function should handle arbitrarily nested objects to be serialized to regular string, float, int, bool, None values. This is a recursive function so by defa...