content
stringlengths
22
815k
id
int64
0
4.91M
async def revocation_registries_created(request: web.BaseRequest): """ Request handler to get revocation registries that current agent created. Args: request: aiohttp request object Returns: List of identifiers of matching revocation registries. """ context = request.app["requ...
5,291,100
def vwap(bars): """ calculate vwap of entire time series (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] """ typical = ((bars['high'] + bars['low'] + bars['close']) / 3).values volume = bars['volume'].values return pd.Series(index=ba...
5,291,101
def two_column_heatmap( df: pd.DataFrame, num_num_metric: Callable[[pd.Series, pd.Series], float] = correlation.pearson, cat_num_metric: Callable[[pd.Series, pd.Series], float] = correlation.kruskal_wallis, cat_cat_metric: Callable[[pd.Series, pd.Series], float] = correlation.cramers_v, columns_x: O...
5,291,102
def get_svn_revision(path=None): """ Returns the SVN revision in the form SVN-XXXX, where XXXX is the revision number. Returns SVN-unknown if anything goes wrong, such as an unexpected format of internal SVN files. If path is provided, it should be a directory whose SVN info you want to in...
5,291,103
def test_parallel_parametrization_over_source_files(runner, tmp_path): """Test parallelization over source files. Same as in README.rst. """ os.chdir(tmp_path) source = """ import pytask @pytask.mark.r @pytask.mark.parametrize( "depends_on, produces", [("script_1.r", "1.rds")...
5,291,104
def test_list_short_min_length_3_nistxml_sv_iv_list_short_min_length_4_5(mode, save_output, output_format): """ Type list/short is restricted by facet minLength with value 8. """ assert_bindings( schema="nistData/list/short/Schema+Instance/NISTSchema-SV-IV-list-short-minLength-4.xsd", in...
5,291,105
def checkFrameRateChange_Lenient(op, graph, frm, to): """ Confirm frame rate has not changed. :param op: :param graph: :param frm: :param to: :return: """ if _checkFrameRateChange(op, graph, frm, to): return (Severity.WARNING, 'Frame Rate Changed between nodes')
5,291,106
def img2port(img_url): """ mimvp.com的端口号用图片来显示, 本函数将图片url转为端口, 目前的临时性方法并不准确 """ code = img_url.split("=")[-1] if code.find("AO0OO0O")>0: return 80 else: return None
5,291,107
def coverage(tiles): """Sum of length of all tiles. """ accu = 0 for tile in tiles: accu = accu + tile[2] return accu
5,291,108
async def stations(id: int, date_from: str = None, date_to: str = None, param: str = 'pm25'): """ Get pollution data for a specific station and a date range :return: json of format {"data": [{date, time, value}, ...] """ if not date_from or not date_to: tz = pytz.timezone("Europe/Warsaw") ...
5,291,109
def update(head: str, td: Tag) -> Attr: """ Update a developing part dictionary based on a cell from the product table :param head: The head string from the <th> :param td: The <td> from the product table :return The applicable CSS class, and the dictionary with kvs to update. """ cl...
5,291,110
def load_doc(name, doctype = None, project = None): """Load document Args: name: Name of document (file must exist in :/username/project/docs.zip: file). doctype: Type of document. 'pdf', 'docx', etc. project: reference to ArthurProject object. Returns: list: List of two ob...
5,291,111
def lognormalize_chroma(C): """Log-normalizes chroma such that each vector is between -80 to 0.""" C += np.abs(C.min()) + 0.1 C = C / C.max(axis=0) C = 80 * np.log10(C) # Normalize from -80 to 0 return C
5,291,112
def _basemove(dev_pos_list, waithook=None, poshook=None): """Core move function. Options: *waithook*: a waiting function that gets the list of started devices *poshook*: gets device and requested pos, returns modified position """ movelist = [] errors = [] for dev, pos in _devposlist(...
5,291,113
def batch_rename_files_to_index(files_dir: str, sorted_file_names: List[str] = None, zfill: int = 6): """ Renames all files from a sorted list (which must all be located in files_dir), to index.extension. e.g. a.jpg, b.jpg -> 000000.jpg, 000001.jpg """ if sorted_file_names is None: sorte...
5,291,114
def kei_zeros(nt): """Compute nt zeros of the Kelvin function kei x """ if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): raise ValueError("nt must be positive integer scalar.") return specfun.klvnzo(nt,4)
5,291,115
def _reflect_particle_diffusive(arr, **kwargs): """ Reflect particles given in a diffusive manner. Args: arr (np.ndarray): 2D-ndarray of shape *number of particles x 5*. Each particle is describes by : [x, y, vx, vy, vz] Returns: [np.ndarray]: returns the modified array by default (in most...
5,291,116
def SearchTargets(query_term, base_url=BASE_URL, fout=None): """Search names.""" n_out=0; tags=None; df=None; offset=0; while True: url_next = (base_url+'/targets/?search={}&limit={}&offset={}'.format(urllib.parse.quote(query_term), NCHUNK, offset)) rval = rest.Utils.GetURL(url_next, parse_json=True) ...
5,291,117
def get_int() -> int: """ Gets a lone integer from the console (the integer is on its own line) :return: The int value that was read in from the console """ line = input().strip() return int(line)
5,291,118
def add_package_parser(subparsers): """Creates the parser for the command package""" package_parser = subparsers.add_parser( "package", help="Create packaged model (checkpoint only containing model)", ) package_parser.add_argument("checkpoint", type=str, help="filename of a checkpoint") pack...
5,291,119
def plot_tract_profiles( X, groups, group_names, group_by=None, group_by_name=None, bins=None, quantiles=None, palette="colorblind", ci=95.0, subplot_positions=None, nrows=None, ncols=None, ): """Plot profiles for each bundle and each metric. Parameters -----...
5,291,120
def build(data, config, output_dir): """ Build the final directory, rendering all templates and copying source files """ theme_name = config.get('theme', 'simple') vars = defaults.copy() vars.update(data) vars['config'] = config vars['h'] = helpers # make helpers module accessible via '...
5,291,121
def regex_search_matches_output(get_output, search): """ Applies a regex search func to the current output """ return search(get_output())
5,291,122
def crop(img, start_y, start_x, h, w): """ Crop an image given the top left corner. :param img: The image :param start_y: The top left corner y coord :param start_x: The top left corner x coord :param h: The result height :param w: The result width :return: The cropped image. """ ...
5,291,123
def univariate (mu, alpha, omega, T, numEvents=None, seed=None): """ generates events based on univariate hawkes process with an exponential decay kernel Parameters: ----------- mu: float The base intensity. alpha: float The self-excitation. omega: float The bandwidth parameter. T: float The fi...
5,291,124
def normalize_path(path): """ Normalizes the path separator to match the Unix standard. """ if sys.platform == 'win32': return path.replace('\\', '/') return path
5,291,125
def continuous(request): """ Creates a random regression dataset fixture. """ X, y = make_regression( n_samples=500, n_features=22, n_informative=8, random_state=2019 ) # Dataset is accessible on the class so it is only generated once request.cls.continuous = Dataset(X, y)
5,291,126
def validate_existing_delivery(start, end, queryset): """Validate if exists a deliver at that time by date""" delivery_exist = False msg = "" if len(queryset): for deliver in queryset: deliver_start = format_date(deliver.start) deliver_end = format_date(deliver.end) ...
5,291,127
def separate_by_class(train): """ For each dependent variable (last column of DF) value, map to corresponding rows of the DF """ classifications = set(train[:, -1]) return {c: train[train[:, -1] == c] for c in classifications}
5,291,128
def _cue_export(ctx, merged, output): """_cue_export performs an action to export a single Cue file.""" # The Cue CLI expects inputs like # cue export <flags> <input_filename> args = ctx.actions.args() args.add(ctx.executable._cue.path) args.add(merged.path) args.add(ctx.file.src.basename)...
5,291,129
def bootstrap(app): """Will call the register method on each module to register their commands""" call_method_on_each(rfidsecuritysvc.cli, 'register', {'app': app})
5,291,130
def register_handlers(dispatcher: Dispatcher) -> None: """Register bot handlers.""" dispatcher.add_handler(CommandHandler(command="start", callback=start)) dispatcher.add_handler( MessageHandler(CryptoCurrencyFilter(), callback=crypto_exchange_rate) ) dispatcher.add_handler(MessageHandler(F...
5,291,131
def plot_profile(datasets, fields=None, times=None, timerange=None, fig=None,ax=None, fieldlimits=None, heightlimits=None, fieldlabels={}, cmap=None, stack_by_datasets...
5,291,132
def files(): """Manage files deposited with the record.""" pass
5,291,133
def abs(v): """Create abs in the sense of distance instead of just vanishing the sign. Create abs in the sense of distance instead of vanishing the sign. Used to calculate the length of coordinates, or anything that can be interpreted as coordinate. Args ---- v: iterable of float, comp...
5,291,134
def confirm_index_opts(taxonomy_name, opts): """Confirm expected keys are present in opts for indexing.""" file_key = "taxonomy-%s-file" % taxonomy_name url_key = "taxonomy-%s-url" % taxonomy_name for key in {"taxonomy-path", file_key}: if key not in opts: LOGGER.warning("Unable to i...
5,291,135
def podcast_spider(site): """ 更新源内容 """ resp = get_with_retry(site.rss) if resp is None: logger.info(f"RSS 源可能失效了`{site.rss}") return None feed_obj = feedparser.parse(BytesIO(resp.content)) for entry in feed_obj.entries: # 有些是空的 if not entry: co...
5,291,136
def getDataSetUuid(xmlfile): """ Quickly retrieve the uuid from the root element of a dataset XML file, using a streaming parser to avoid loading the entire dataset into memory. Returns None if the parsing fails. """ try: import xml.etree.cElementTree as ET for event, element in ...
5,291,137
def ClangTidyRunDiff(build_folder, diff_branch, auto_fix): """ Run clang-tidy on the diff between current and the diff_branch. """ if diff_branch is None: diff_branch = subprocess.check_output(['git', 'merge-base', 'HEAD', 'origin/master']).strip() git_ps = subp...
5,291,138
def ctl(): """ctl help""" pass
5,291,139
def train_mnist_single_machine(data_dir, num_epochs, use_fake_data=False): """Train a ConvNet on MNIST. Args: data_dir: string. Directory to read MNIST examples from. num_epochs: int. Number of passes to make over the training set. use_fake_data: bool. If True, generate a synthetic dataset. Returns:...
5,291,140
def train_all(data_source, start_date, end_date): """ Batch training for all active stations. Args: data_source: start_date: end_date: Returns: """ variable = RAIN config = training_config #{"radius": 100, "MAX_K": 5, "FRACTION_ROWS": 0.5, "MIN_STATION": 3} thre...
5,291,141
def pick_word(probabilities, int_to_vocab): """ Pick the next word with some randomness :param probabilities: Probabilites of the next word :param int_to_vocab: Dictionary of word ids as the keys and words as the values :return: String of the predicted word """ return np.random.choice(list(int_to_vocab.values())...
5,291,142
def get_max_cost_matrix(a, bottom_right=True, top_left=False): """Return matrix with maximum cost for paths from all nodes""" maxcost = 9 * a.shape[0] * a.shape[1] cost = np.zeros(a.shape, int) + maxcost if bottom_right: cost[-1, -1] = 0 if top_left: cost[0, 0] = 0 return cost
5,291,143
def get_synthetic_data(data_size: int, features_num: int) -> (Matrix, ColumnVector): """ A method which creates a random matrix of ``size data_size x features_num`` and a ``random 1 x data_size`` random vector. Args: data_size(int): The number of samples in the data - ``n``. features_nu...
5,291,144
def injection_volume(val: Union[float, str]) -> Union[int, str]: """ Handle special case for injection volume of ``-1``, which indicates "As Method". :param val: :type val: :return: :rtype: """ if val in {-1, "-1"}: return "As Method" else: return int(val)
5,291,145
def _create_dir(path): """A private function which creates a directory if it does not exists Arguments: path (str): Directory path Returns: None """ if not os.path.isdir(path): log("Creating a directory {}".format(path)) os.mkdir(path) else: log("Directo...
5,291,146
def validate_charge_efficiency(charge_efficiency: Optional[float]) -> Optional[float]: """ Validates the charge efficiency of an object. Charge efficiency is always optional. :param charge_efficiency: The charge efficiency of the object. :return: The validated charge efficiency. """ if char...
5,291,147
def get_module_info(*args): """ get_module_info(ea, modinfo) -> bool """ return _ida_dbg.get_module_info(*args)
5,291,148
def main(argv=None): """The main entrypoint to Coverage. This is installed as the script entrypoint. """ if argv is None: argv = sys.argv[1:] try: status = CoverageScript().command_line(argv) except ExceptionDuringRun: # An exception was caught while running the product...
5,291,149
def _create_plot(mod_dict: Dict[str, Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]], labels: Union[List[str], None], max_y: int): """ Create plot. :param mod_dict: The dictionary with the condition name and the count and percentage, and total count DataFrames. :param labels: The list...
5,291,150
def set_graph_attributes(species): """ For a molecular species set the π bonds and stereocentres in the molecular graph. Arguments: species (autode.species.Species): """ logger.info('Setting the π bonds in a species') def is_idx_pi_atom(idx): return is_pi_atom(atom_label=sp...
5,291,151
def fetch_model(storage, remote_model_path, model_path): """Downloads the remote model.""" storage.get_directory(remote_model_path, model_path) if not check_model_dir(model_path): raise RuntimeError('model integrity check failed: MD5 mismatch') os.environ['MODEL_DIR'] = model_path
5,291,152
def casevault_query(self, parameters): """ Execute the query and return detailed results for the case vault :param parameters: """
5,291,153
def yices_check_context_with_model(ctx, params, mdl, n, t): """Check satisfiability modulo a model. Check whether the assertions stored in ctx conjoined with a model are satisfiable. - ctx must be a context initialized with support for MCSAT (see yices_new_context, yices_new_config, yices_set_c...
5,291,154
def is_abs_blank(str): """ To check out whether str is NONE or empty or blank. """ return not is_not_abs_blank(str)
5,291,155
def main(): """Send bulk email to multiple destinations. Parse command line arguments, read configuration, parse destination file, customize message contents and send email. Sample run: ./send_email.py -c email.conf -m samples/master-admissions/message.txt -s "$(cat samples/master-admissions/sub...
5,291,156
def test_fail_on_different_recipe(tmp_path): """Test `esmvalcore._main.parse_resume`. Test that trying to resume a different recipe fails. """ prev_run = create_previous_run(tmp_path, '20210924_123553') recipe = tmp_path / 'recipe_test.yml' recipe.write_text('something else') with pytest....
5,291,157
def get_vnf_package_data(vnf_package_obj, **kwargs): """Get the vnf package data from a FakeVnfPackage dict object. :param vnf_package_obj: A FakeVnfPackage dict object :return: A list which may include the following values: [{'packageContent': {'href': 'string'}, 'self': {'href': '...
5,291,158
def get_latest_pip_command() -> lib_bash.BashCommand: """ >>> assert get_latest_pip_command() is not None >>> assert 'pip' in get_latest_pip_command().command_string """ try: pip_command = lib_bash.get_bash_command('pip3') return pip_command except ValueError: pass ...
5,291,159
def desympify_homfly(p): """Takes a sympy HOMFLY polynomial p, and returns a tuple of (coefficient, index_a, index_z) tuples. """ if p == 1: return (1, ) p = p.expand() terms = p.as_terms()[0] coeffs = n.zeros((len(terms), 3), dtype=int) for i in range(len(terms)): entry ...
5,291,160
def gen_test_comments(max_samples=999999999): """ Generates sample dataset from parsing the SQuAD dataset and combining it with the SPAADIA dataset. The data is then shuffled, and two arrays are returned. One contains comments the other categories. The indexes for classification...
5,291,161
def triples_from_centre(k): """ Gets all the triples k positions from the centre :param k: The distance from the center. :return: A set of all the triples from the centre. """ return all_triples(neighbours_from_centre(k))
5,291,162
def _minmaxhash_add_ngrams( heap: list, heapmap: dict, maxsize: int, nsize: int, subs, nsubs: int, hashbuffer, heaptop, extracthash, make_elt, update_elt, replace, anynew, minmax_op) -> int: """ Process/add elements to the sketch (See warning below). ...
5,291,163
def load_data(labels_fl, test_size=None): """ Load and split the data into training and testing sets. :param labels_fl: directory of the labels (measurement logs) CSV file :param test_size: size of the testing set :return: training and testing input and output sets if a test_size parameter is prov...
5,291,164
def stream_name_to_dict(stream_name, separator='-'): """Transform stream name string to dictionary""" catalog_name = None schema_name = None table_name = stream_name # Schema and table name can be derived from stream if it's in <schema_nama>-<table_name> format s_parts = stream_name.split(separ...
5,291,165
def run_value_search_from_example( inputs: Union[List[Any], Dict[Text, Any]], output: Any, settings: Optional[settings_module.Settings] = None, **kwargs) -> ValueSearchResults: """Performs value search for a single user-provided input-output example. Args: inputs: A list of inputs, or a dict ma...
5,291,166
def compress(filename, output_filename=None, img_width=2048, img_format='png'): """Compress images in IPython notebooks. Parameters ---------- filename : string Notebook to compress. Will take any notebook format. output_filename : string If you do not want to overwrite your existin...
5,291,167
def top_prior(name, z_shape, learn_prior="normal", temperature=1.0): """Unconditional prior distribution. Args: name: variable scope z_shape: Shape of the mean / scale of the prior distribution. learn_prior: Possible options are "normal" and "single_conv". If set to "single_conv", the g...
5,291,168
def create_label(text = ""): """ Create a Label. :param text: Label Text :return: QTWidget Label """ label = QLabel(text) return label
5,291,169
def getLatestStatus(logfile): """Read and parse MS Teams logfile to get the last presence status. Returns: (status, logTime) """ status = "" try: with open(logfile, "r") as f: for line in f: if "(current state: " not in line: ...
5,291,170
def create_short_timestamp_uuid(): """ Generate short uuid plus timestamp """ short_uuid = create_short_uuid() return "{}{}".format(short_uuid, time.time())
5,291,171
def batch_action_list_assign_election_to_rows_process_view(request): """ :param request: :return: """ # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'verified_volunteer'} if not voter_has_authority(requ...
5,291,172
def best_partition(G: Union[nx.DiGraph, nx.Graph], starting_alpha: Optional[float] = 0.1, threshold_function: Optional[ typing.Callable] = np.mean, cluster_function: Optional[typing.Callable] = None, weight: Optional[str] = "weight") -> tuple: """ Returns the best partition according to c...
5,291,173
def auth(): """ Authenticate the app. Duis lacus nibh, feugiat a nibh a, commodo dictum libero. Ut ac nulla tincidunt, bibendum nisi vitae, sodales ex. Vestibulum efficitur, lectus quis venenatis porta, dolor elit varius mauris, consequat interdum lectus est quis mi. Vestibulum imperdiet sed dol...
5,291,174
def process_nick_list(nicks, platforms=None, rutaDescarga="./", avoidProcessing=True, avoidDownload=True, nThreads=12, verbosity=1, logFolder="./logs"): """ Process a list of nicks to check whether they exist. This method receives as a parameter a series of nicks and verifies whether those nicks have a...
5,291,175
def make_hash(o): """ Makes a hash from a dictionary, list, tuple or set to any level, that contains only other hashable types (including any lists, tuples, sets, and dictionaries). https://stackoverflow.com/questions/5884066/hashing-a-dictionary """ if isinstance(o, (set, tuple, list)): ...
5,291,176
def uivec4(x, y, z, w): """returns an ivec4-compatible numpy array""" return np.array([x, y, z, w], dtype=np.uint32)
5,291,177
def cli(): """Command line interface."""
5,291,178
def compute_spectral_wcut(A, w=None, K=2, max_iter=50): """ Solves weighted ratio cut as a relaxed trace maximization problem with Yu and Shi postprocessing.""" N = A.shape[0] if w is None: w = np.ones(N) L = np.diag(np.sum(A, axis=1)) - A # Solve eigenvalue problem w_inv_sqrt = w ** (-...
5,291,179
def relpath(target, base=os.curdir): """ Return a relative path to the target from either the current dir or an optional base dir. Base can be a directory specified either as absolute or relative to current dir. """ if not os.path.exists(target): raise OSError, 'Target does not exist: '+tar...
5,291,180
def mock(connectable, replace_new_patch_aliases=None): """Creates a mock selector that can be patched. This is intended to be used as a context manager with a given SQLAlchemy connectable (e.g. an engine, session, connection, etc). For example:: with pgmock.mock(engine) as mocker: mock...
5,291,181
def evaluate_bias(ds: List[str], predicted: List[GENDER]) -> Dict: """ (language independent) Get performance metrics for gender bias. """ assert(len(ds) == len(predicted)) prof_dict = defaultdict(list) conf_dict = defaultdict(lambda: defaultdict(lambda: 0)) total = defaultdict(lambda: 0...
5,291,182
def read_img(pat_id): """ read in the raw images :param pat_id: the id if the patient to read in :return: the images and the ground truth """ assert os.path.exists('../input/PnpAda_release_data/test_ct_image_n_labels/image_ct_{}.nii.gz'.format(pat_id)), "The specified patid doesnot exists: {}".f...
5,291,183
def test_attachment_author(attachment): """ author method of Attachment object. Args: attachment (pryke.Attachment): Attachment to test. """ add_response(responses.GET, 'https://www.wrike.com/api/v3/users/KUAJ25LD') assert isinstance(attachment.author, User) assert attachment.autho...
5,291,184
def map_statements(stmts, source, outfile=None): """Tabulate valid, invalid, and mapped sites from a set of Statements.""" # Look for errors in database statements sm = SiteMapper(default_site_map) valid_stmts, mapped_stmts = sm.map_sites(stmts) # Collect stats from SiteMapper itself sites = [] ...
5,291,185
def show_dynamic_OD_matrix(estim_param, network, evaluate, estpar_ref, eval_ref): """ Method creating the OD matrix visualization. """ fig = plt.figure(1) def plot_cur_ODmap(t, flag=None): fig.clf() plt.axis('off') if t >= 0: time_span = str(estim_param.tint_ev...
5,291,186
def getCriterion(): """Criterion (Loss function) for training and validation""" def loss_func(output, target, batch_size): output_for_loss = output.view(-1, output.size(2)) # seq_len * N, ntokens target_for_loss = target.view(-1) # seq_len * N loss = F.cross_entropy(output_for_loss, targ...
5,291,187
def parse_variable_array(buf, lenbytes): """ Parse an array described using the 'Type name<x..y>' syntax from the spec Read a length at the start of buf, and returns that many bytes after, in a tuple with the TOTAL bytes consumed (including the size). This does not check that the array is the right ...
5,291,188
def encode_features(feature_points, src, patch_size=(41, 41), display_img=True, save_img=False): """ feature_points: list of keypoint/feature point around which we will take a patch of size 41x41 src: input image patch_size: a small img which will be encoded as feature vector consider only those fe...
5,291,189
def snake_split(s): """ Split a string into words list using snake_case rules. """ s = s.strip().replace(" ", "") return s.split("_")
5,291,190
def esm_analysis(): """Manipulate the cachedir of esm_analysis.""" import esm_analysis with TemporaryDirectory() as cache_dir: esm_analysis.Reader._cache_dir = Path(cache_dir) esm_analysis.cacheing._cache_dir = Path(cache_dir) yield esm_analysis
5,291,191
def main(): """ 認証を行う """ config = Config() credentials = (config.get_client_id(), config.get_client_secret()) token_backend = FileSystemTokenBackend(token_path=config.get_token_path(), token_filename=config.get_token_file()) account = A...
5,291,192
def task_estimates(iterations=None): """Discrete task iteration converted to array""" task_iteration_list = [] for _ in range(iterations): r_float = random_float() min_val, max_val, a_val, b_val = 24, 90, 2, 4 beta_value = beta_values( random_number=r_float, ...
5,291,193
def subroutine_definition(line: str) -> Tuple[bool, Optional[list]]: """ Indicates whether a line in the program is the first line of a subroutine definition and extracts subroutine name and the arguments. Args: line Returns: (True, list) if line begins a definition for subroutine; ...
5,291,194
def try_parse(text, valid_types=None): """try to parse a text string as a number. Returns (valid, value) where valid represents whether the conversion was successful, and value is the result of the conversion, or None if failed. Accepts a string, and one optional parameter "valid_types" which is a list...
5,291,195
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up YoLink siren from a config entry.""" device_coordinators = hass.data[DOMAIN][config_entry.entry_id][ATTR_COORDINATORS] siren_device_coordinators = [ ...
5,291,196
def throttle(wait): """Second order decorator for rate-limiting a function within an asyncio concurrent app - The first call will always happen *without* delay. - Subsequent calls, within wait seconds, are dropped, even if argurments differ. - The final call will always execute, sometimes with a delay....
5,291,197
def plot_tsne( arrays, legends, filename=None, use_umap=False, **kwargs ): """ Plot tSNE and return the figure. Parameters: arrays (List of ndarray): Vectors to be plotted. Each array will be colored and named differently. legends (List of str): Name for each...
5,291,198
def _compute_sequence_bias_grad_sample( layer: SequenceBias, A: torch.Tensor, B: torch.Tensor, batch_dim: int = 0 ) -> None: """ Computes per sample gradients for ``SequenceBias`` layer Parameters ---------- layer : opacus.layers.dp_multihead_attention.SequenceBias Layer A : torch.T...
5,291,199