content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def _transform_build_config(config, config_files, whitelabel): """Transforms Config instance into target platform JSON schema. Args: config: Config namedtuple config_files: Map to look up the generated config files. whitelabel: Whether the config is for a whitelabel design Returns: U...
d0da1f26c194a9c2371f714ea745ca124812a88c
46,700
from datetime import datetime import binascii def is_valid(token): """Checks if the token is valid. Args: token (str): Token Returns: Boolean: True or false """ if len(token) < 64: return False now = datetime.now().timestamp() time = token[22:][:20] decode_tim...
ea1b28d2a04f3d72a0388c41feeb2bd764a78239
46,701
def shared_dataset(filename): """Returns the training-, validation- and test-datasets as shared variables""" train_set, valid_set, test_set = load_dataset(filename) train_x, train_y = shared_variables(train_set, 'Training') valid_x, valid_y = shared_variables(valid_set, 'Validation') test_x, test_y...
71ff6a10845720f0eb2bb6f7f9035574cb52970d
46,702
def _stats_print(good_noise, good_gains, good_fit, test_chans): """Generate a simple set of statistics for the test and print them to screen. """ print("\nFilter statistics:") good_chans = [1] * len(test_chans) Nact = len(test_chans) # Number of active channels if good_noise is not None: ...
31044ffd6966a0e7d910bcafa92616de36ce4e81
46,703
def text(): """make text files""" return build('text', 'The text files are in {}.')
b066b813722be90c69eae68972cf33475c5f0023
46,704
import requests def upload2ipfs(file_path: str) -> str: """Upload to ipfs using local port. IPFS node must be running locally. Run: $ ipfs daemon Args: nft_path (str): path to metadata file """ with open(file_path, "rb") as f: nft_binary = f.read() ipfs_endpoint = "http://...
4fdb53d4d6d61b1784673be6d84cb7ba41fc84a5
46,705
def rotateImage(imgdata, org_corners): """ """ rotation = calculateRotation(org_corners.ul, org_corners.ur) rot_img = skimage.transform.rotate(imgdata, rotation, resize = True, preserve_range = True) return rot_img
c4649b964a99345b62b4b53184efe5757639f0e2
46,706
def mean_absolute_scaled_error(y_true: ArrayLike, y_pred: ArrayLike) -> float: """Compute the mean absolute scaled error (MASE). MASE is computed by comparing mean absolute error of the predictions to the mean absolute error obtained from a lag-1 forecast. Args: y_true: the actual values. ...
7931d81f952e692f1b14f578ee93182b3289074d
46,707
def GetCloudBasePath(): """Returns the folder within the Makani bucket where all databases live.""" return 'gs://gcp-public-data-makani-deps/deps/turbsim_databases'
40091d491fdc3960cc5aa08e0ca58ae0cf2009aa
46,708
import json def create_entity(station: WeatherStationTuple) -> dict: """ Conversion from input data to desired properties and types """ entity = Entity() entity.provider = 'bom' entity.country = 'Australia' entity.country_code = 'AU' entity.state = station.state entity.site = station.site...
2e6398490afdee43a5d8d43c58634ffdff7bc3dd
46,709
def line(char='-', length=48): """Generates a string of characters with a certain length""" return ''.join([char for _ in range(length)])
32de8abb95ab7e73912e2b37f0996361ed181c5b
46,710
import collections def dict_update(d, u): """Recursive update dictionary""" for k, v in u.items(): if isinstance(v, collections.Mapping): d[k] = dict_update(d.get(k, {}), v) else: d[k] = v return d
bf49b0e4a8f35595a2258aaadcad231d8b9325da
46,711
def _handle_tracking(request, response): """Handles the share tracking logic so that users get their number of shares increased when someone downloads Firefox mobile via their user page.""" if not _has_parent_cookie(request): parent_username = _add_share_from_cookies(request) # Set a 'par...
f491e44253face9148aaf4f4e09cb122c4b495b6
46,712
def prompt_yn(msg, default=None): """ Prompts the user for a y/n response. default param should be either 'y' or 'n' Returns True if 'Y' and False if 'N' """ if default is True: default = 'y' elif default is False: default = 'n' if default == 'y' or default is True: ...
f5df7d5bf32153dd1a0e34b26997aabd683066f8
46,713
def noise_for_example(x, extent=1000, intensity=0.1, rng=None, **kwargs): """ Add noise to x. Just for demonstration. Arguments: extent -- number of points to add noise at intensity -- scale parameter of half-normal distribution; samples from this distribution will be added at each nois...
55a76ea075f6f36d874293ee8aacbd1419fd1e32
46,714
def get_spectra(st, event, inventory, synthetic_picks, calc_displacement=False, S_win_len=.1, P_or_S='P'): """ Calculate the fft at each channel in the stream that has an arrival in event.arrivals :param st: uquake.core.stream.Stream :type st: uquake.core.stream...
2c25911efcc03657178980f643265823d7bcf25d
46,715
from typing import List import os import shutil import threading async def upload_file(request: Request, file: List[UploadFile] = File(...)): """ Uploads temporary file which is loadied in to the cdQA model as the data """ query = await request.form() user = request.headers["authorization"] #c...
357d33e2c238841935671512c0cb826e9b244f00
46,716
def datasets_loader(conf, train=True, dev=True, test=True): """ simple wrapper for unified interface of datasets loaders """ fmt = conf.pop("fmt") if fmt == "kaldi_ra": return kaldi_ra_datasets_loader(conf, train, dev, test) else: raise ValueError("dataset format %s not supported...
d82f097e00cffc31ee53ac1a57635a1fcc871990
46,717
import json def remove_existing_datasets(viable_datasets, connection): """Remove the viable datasets that are already existing datasets.""" for dataset_type in viable_datasets: for container, datasets in viable_datasets[dataset_type].items(): actually_viable_datasets = [] for ...
889a87d144c795b1bfe40aaad92ca1b36c64b3b3
46,718
import logging def group_by_size(input_tensors, bytes_per_pack): """Groups `input_tensors` into chunks of `bytes_per_pack`. The method preserves the original order of `input_tensors`. The grouping is best effort, each pack could have more or less bytes than `bytes_per_pack`. It only groups values with known ...
9ab5805898678b1541f116e5ef5ae1b9a1c42791
46,719
def np_emd_loss(y_true, y_pred, reduction_axis=None, num_bins=327, **kwargs): """Earth Mover Distance between two waveforms Parameters ---------- y_true : np.ndarray A tensorflow tensor defining the true waveform shape: [batch_size, num_bins] y_pred : np.ndarray A tensorflow...
d5c70b35d466d8c62efb31c91cef87da5eebd076
46,720
def adapters(text): """ Parse lines of text into a list of adapters (represented by their joltage), supplemented by the outlet (0) and your device (maximum + 3). """ adapters = list(sorted(map(int, text.splitlines()))) adapters = [0] + adapters + [max(adapters) + 3] return adapters
cb5aa44963506e8d0ea6aa0aeb89d094bfbb0bc8
46,721
def assign_bonds_to_groups(tors, group): """ | **Description:** Make a group for each torsion bond and keep track of how many members Finally it returns the biggest group. **Input:** - Tors: atoms with torsions - Group: Atoms grouped by proximity **Output:** - output: li...
8147c016efe435f46b587bc86e6fab713375bb70
46,722
def _build_generator_map(): """Build a map of sdtype to data generator. Output: dict: A mapping of sdtype (str) to a list of data generators (rdt.tests.datasets.BaseDatasetGenerator). """ generators = defaultdict(list) for generator in BaseDatasetGenerator.get_subcl...
4660f8b84f1a048942e519d188b17bac10903b1f
46,723
import glob import tqdm import os def read_file(path, sep): """ ファイルの読み込みを行う。一度に、複数ファイルの読み込みも可能。 相対パスと絶対パス、どちらでも可能。 Input ------ path : 読み込みたいファイルへのパス sep : 読み込みたいファイルの区切り文字の指定 Output ------ df_array : 読み込んだdfのリスト path_array : globで取得した、ファイルパスのリスト Raises -----...
0a892d55e5fdb6f99a603a6624d8d24bc7246822
46,724
import re def get_ignore_unknown_patterns(): """ Fetch the value of the setting that tells us what unknown overrides we should ignore in reports. The regular expressions from the settings file (if any) are compiled in the returned list. When the setting is a boolean, the result is either an empty...
5437159c9bddbc80585e31156d0740108df2dcca
46,725
from typing import Any import os import pickle def main(xyz_file) -> Any: """ Execute main code for function by reading an xyz file and returning persistence diagram Arg: xyz_file is the name of an xyz structure (which is stored in 'xyz_structures') Return: persistence diagram from Delaunay triangul...
41cf54df7520fc7173fbd66038cd7a3e40d3015d
46,726
def test_dal_method_middleware(): """ Verify that when calling a method on a service off the DAL, the method middlewares run, in the correct order and run before the method itself is called. We deliberately do not use the DalMethodResolverMiddleware here, because we are testing middleware call...
71f43002001b5c4bb2b43f72ac29ab4bae9e6159
46,727
def chain_functions(fun_first: tp.Callable[..., tp.Union[tp.Tuple[tp.Tuple, tp.Dict], tp.Dict, tp.Tuple]]) -> tp.Callable: """ A decorator to chain function calls. This function is expected to return: * a 2-tuple [tp.Tuple, tp.Dict] - args and k...
e78f42d30fb788751703f1b56bafd485b27c1a0e
46,728
from typing import Union import types from typing import List from typing import Tuple from typing import Set def find_variables( expr: Union[types.Constraint, List[types.Constraint], Tuple[types.Constraint]] ) -> Set[core.Symbol]: """Find variables in constraints.""" if not isinstance(expr, (list, tuple)): ...
d9b737260b1c2b5d25f6718530ed74245c76abfd
46,729
def _number_of_neighbors(i, j, height, width, state): """ Counts the number of LIVE neighbors of the cell in position (i, j). :param i: Row of the cell. :param j: Column of the cell. :param height: Height of the input state. :param width: Width of the input state. :param state: A game state...
cb88e81fb7124ef6c97de75cfecef5b11767da14
46,730
def _format_cpu_memory(container_group): """Format CPU and memory. """ containers = container_group.get('containers') if containers is not None and containers: total_cpu = 0 total_memory = 0 for container in containers: resources = container.get('resources') i...
1e1db12afd45a6d0634a6d9f701f3c3bb7bc9570
46,731
def create_category(name): """ Create a new category :param name: :return object: """ category = Category(name=name) session.add(category) session.commit() return category
512092a2b3c3c9fd4a912f99dbfe35a8645d228e
46,732
def logpost_negb(state,params): """ Compute log-posterior density values; this function assumes the likelihood is a product of negative-binomial distributions Parameters ---------- state: python list or numpy array model parameters params: dictionary detailed settings for...
0b88b2f39f70d7cd07f8cfbd9a8434f56ba306ad
46,733
import os def GetBinhostCache(options): """Get and optionally clear the binhost cache.""" cache_dir = os.path.join(path_util.FindCacheDir(), 'cros_install_debug_syms-v' + CACHE_VERSION) if options.clearcache: osutils.RmDir(cache_dir, ignore_missing=True) binhost_cache = None ...
1305cd893e3f809ee32b9e01dab3d7057e0eb0ff
46,734
import functools def matcher(callable_or_names, names=None): """ Implicitly registers it with function's __name__, "be_a_dog": @matcher def be_a_dog(x): return type(x) == dog Explicitly registers it with names "be_a_dog" and "be_canine" @matcher("be_a_dog, be_canine") def whatev...
6e79149c45ba32576d9fa7cde373d14279c401e9
46,735
def update_tree( tree: EmptyTree, oid: str, current_user: User = Depends(get_current_active_user) ): """ Update tree DB entry """ print(tree) try: selected_tree = TreeDB.objects.get(id=oid) selected_tree.species = tree.species if tree.species else selected_tree.species s...
49ac41202d2b6471574a55cacfcf746b646437b3
46,736
def get_queue_jobs(queue_name): """Get the jobs by status of a Queue. Args: queue_name (str): The RQ Queue name Returns: dict: Number of jobs by job status Raises: redis.exceptions.RedisError: On Redis connection errors """ queue = Queue(queue_name) return { ...
a5ba497545955ad5bb42406cf289d69f05b1101a
46,737
def update_lengths(lengths, eoses, idx): """Update the length of a generated tensor based on the first EOS found. This is useful for a decoding situation where tokens after an EOS can be something other than EOS. This also makes sure that a second generated EOS doesn't effect the lengths. :param l...
bad4dce46e498da09400673abacebdba8db5ddae
46,738
def delete_widget_config(id_): """Deletes a widget :param id: ID of the widget to delete :type id: str :rtype: tuple """ widget_config = WidgetConfig.query.get(id_) if not widget_config: return "Not Found", 404 else: session.delete(widget_config) session.commit(...
74e9e1568cbbcfe825dc936699682db270aa0125
46,739
def detail_view(request): """ Directs user to the detail template """ try: symbol = request.matchdict['symbol'] except KeyError: return HTTPNotFound() try: query = request.dbsession(Account) stock_detail = query.filter(Account.username == request.authenticated_us...
aa45381bce120007a6fd957b0d3c433ec0fa3303
46,740
def is_right_censored(lc, frange): """ Returns true if the light curve is cutoff on the right. """ return len(lc['t0'])-1 in frange
de2e81605db2dc2a5f073d8400e2e8ee1b46f199
46,741
def neural_net_learning_rate_input(): """ Return a Tensor for the learning rate """ return tf.placeholder(tf.float64, name="learning_rate")
3d7e21cafd617b69aafa439c238f9d16c0eb28b4
46,742
def decode_csr(b64der): """ Decode JOSE Base-64 DER-encoded CSR. :param str b64der: The encoded CSR. :rtype: `cryptography.x509.CertificateSigningRequest` :return: The decoded CSR. """ try: return x509.load_der_x509_csr( jose.decode_b64jose(b64der), default_backend()) ...
0eb7dd2acd8cd8a210969e0ea1d2e99ecca07a97
46,743
def retrieve_span(task, task_id): """Helper to retrieve an active `Span` stored in a `Task` instance """ weak_dict = getattr(task, CTX_KEY, None) if weak_dict is None: return else: return weak_dict.get(task_id)
74d003e9b2a019a8b0b1527952dabcb8a21f6e2b
46,744
def check_data(func): """Decorator function for checking possible exceptions during extraction. Args: func (obj): function used in try-except block Except: (str) : in case of exception assigns '-' for the missing data. """ def inner(line): try: return func(line)...
b9dad9ff8adbee9f8307c4c61fc2d5e1918092e2
46,745
def fscale(ns, si=1, one_sided=False): """ numpy.fft.fftfreq returns Nyquist as a negative frequency so we propose this instead :param ns: number of samples :param si: sampling interval in seconds :param one_sided: if True, returns only positive frequencies :return: fscale: numpy vector contain...
f6cf820c184651396c3fc61a366391c9d03f086b
46,746
def get_features_from_files( data_dir, features_ext='.proc.c3d-avg.npy', test_split=[], classes=None, max_elements=13320): """ Creates and executes mPyPl pipe to load feature vectors from serialized files and returns a preprocessed data stream that can be further used with respect to...
f53f0781a6108e8e31ba75613c007368b095fdfb
46,747
import json import hashlib def crypto_hash(*args): """ Return a SHA-256 hash of the given arguments """ stringified_args = sorted(map(lambda x: json.dumps(x), args)) joined_data = "".join(stringified_args) return hashlib.sha256(joined_data.encode("utf-8")).hexdigest()
3c4329a6e99826a15e52e2921040045697ce5aa0
46,748
def vectorized(csm, e, h, r0, rm, kj): """ Uses Numpys fast array operations, distributed via the mkl-package. Those oparations are already optimized and use all available physical cores. """ nFreqs = csm.shape[0] nGridPoints = r0.shape[0] beamformOutput = np.zeros((nFreqs, nGridPoints), np.comp...
15c2fb6a9f7f8551314d0a0e9c219308dc7b2741
46,749
def is_empty_line(line: str) -> bool: """Checks whether a line is empty.""" return line.strip("\n").strip("\t").strip() == ""
ad58cc78e5f25353419682343c34c21e2679304d
46,750
def to_host_list(value): """Space separated list of FQDNs.""" return value.split()
85740e6e90096d5711022a7ae18b919673899b36
46,751
import click def drop_prediction_column(data_path, group_name, column_name, yes=True): """ Deletes prediction columns in a h5py file if the columns exist. Including 'mean' and 'std' columns. """ n_del = 0 with h5py.File(data_path, "r+") as f: if group_name not in f.keys(): ...
9ac7e06ddcf71af87b383ecefe5f3aac1a0e2159
46,752
def create_indep_noise_weight_matrix(Nbm, Knoise, gamma, g, w): """create a weight matrix for Nbm * Knoise sources projecting to Nbm targets with a fixed indegree of Knoise. no shared inputs are allowed, hence each target receives uncorrelated input of the sources are uncorrelated. """ Nnoise ...
4760fcf51d9418243df7ecb9027d81b77dd85a00
46,753
import torch def tensordot(x, y, axis=2): """ Compute tensor dot product along specified axes. axes : int or (2,) array_like integer_like If an int N, sum over the last N axes of a and the first N axes of b in order. The sizes of the corresponding axes must match. (2,) array_like Or, a list of axes t...
c833140019247602643166e3527cd8c506efd794
46,754
def _is_tarfile(filename): """Returns true if 'filename' is TAR file.""" return (filename.endswith(".tar") or filename.endswith(".tar.gz") or filename.endswith(".tgz"))
761b776e0e8078ddd4bee694e0a9d853dd2e31fd
46,755
def deleteAnonMsgs(key, dbn='anon', env=None): """ Deletes messages at key uid Parameters: key is anon uid dbn is name str of named sub database, Default is 'anon' env is main LMDB database environment If env is not provided then use global gDbEnv """ global gDbE...
054645e2267f6add970b5b44ad13825e8a739f3b
46,756
import pydantic import json def configured_model(): """ Fixture for configured model - this was how aliasing was achieved for the first schema, but since nearly every object will need aliasing methods, the models now inherit from AbstractModel - this fixture is for testing that AbstractModel behaves t...
7f06c86a78c445a1f68343623a8ab7ef305ffcd6
46,757
def get_rho(w): """ :param w: 対象の値 最小位から数えて最初の1ビットの位置(1-indexed) """ return libc.ffs(w)
6b05211eb86eff1a1473e1f42681063ef8878cc0
46,758
import tqdm import torch def data_collection(env: gym.Env, num_episodes: int = 10, epsilon: float = 0.2, use_gt_states: bool = False, use_tqdm: bool = False): """ Collect demonstration dataset """ train_inputs = [] train_actio...
7d8967934526bb1ef56e4097a3da9f9c099402e7
46,759
from typing import Optional import asyncio import contextlib from typing import cast def get_running_loop() -> Optional[asyncio.AbstractEventLoop]: """Check if an event loop is already running.""" with contextlib.suppress(RuntimeError): if hasattr(asyncio, "get_running_loop"): return cast(...
48750bc03be5d8cd17da20a3ca01d02149d471f5
46,760
def distance_diff_catl(ra, dist, gap): """ Computes the necessary distance between catalogues Parameters ----------- ra: float 1st distance dist: float 2nd distance Returns ----------- dist_diff: float amount of distance necessary between mocks """ ...
2a523d1c9c132dc8fcb65bd8d633bf24fcf46f42
46,761
def calculate_degree(network): """Calculates the degree of the nodes from the from and to ids. It is not wise to call this method after removing nodes or edges without first resetting the ids Args: network (class): A network composed of nodes (points in space) and edges (lines) Returns: ...
11e1d0ad1d02f1e32c89688a368e359c278c1581
46,762
def parse_token(filehandle, token): """Iterates through filehandle until token found. If value found after token, returns it.""" for line in filehandle: line = line.strip() if line.startswith(token): if len(line) > len(token): return line.rsplit('\t', 1)[1] ...
9f65ec378b33903250173aaa3f97cd058de13d2b
46,763
import sys import random def send_transaction(orderers, tran_req, tx_context): """Send a transaction to the chain's orderer service (one or more orderer endpoints) for consensus and committing to the ledger. This call is asynchronous and the successful transaction commit is notified via a BLOCK or CH...
3a932847ec38361be94e1716f07fcf868ddfe9fb
46,764
def logsumexp(matrix, dim=None): """ Compute log(sum(exp(matrix), dim)) in a numerically stable way. :param matrix: input ndarray :type matrix: ndarray :param dim: integer indicating which dimension to sum along :type dim: int :return: numerically stable equivalent of np.log(np.sum(np.e...
2fefc6e4a88d5dfa006d8e587ee18845960689c9
46,765
import os import csv def import_book(book_path): """ Read book at (book_path) """ book = dict(name=os.path.basename(os.path.splitext(book_path)[0])) with open(book_path, 'r') as f: book['content'] = f.read() region_file = to_region_file(book_path) if os.path.exists(region_file): ...
1d1bfd5b10ab523eea4b9fe1aea4e39920973e95
46,766
def _run_adb(adbcommand): """Run the adb binary.""" cmd = [ADB] cmd.extend(adbcommand.split()) return process.check_output(cmd)
72e718f77e0d23055dcc9ba3e83ad547bfac26f2
46,767
import os def get_hooks(additional_dirs=None): """ Helper function to find and load all hooks. """ log.debug("get_hooks()") if additional_dirs is None: additional_dirs = [] hooks = annex.Annex(BaseHermesHook, [ os.path.join(BUILTIN_PLUGIN_DIR, "hooks"), "/etc/hermes/plugins/hoo...
5fee059ed4df510005c0f0df58a4e310f40964ce
46,768
def _label_constraint(key, value): """ Returns a label constraint for host limit 1 :param key: The key fo the label :param value: The value of the label """ return task_pb2.Constraint( type=1, labelConstraint=task_pb2.LabelConstraint( kind=1, condition=2, ...
6c18e9a852b0bd924cf3ac70669acb7cc8676e57
46,769
def trim(infile, outfile): """Trim video with ffmpeg. Returns tuple of filename and dict of trim times""" if not pyask.yes_no("Does the video need to be trimmed?", default="yes"): return (infile, {"start": 0, "end": None}) start, end = get_trim_times() run( [ "ffmpeg", ...
a21e8515cbf5e03b5e68493279a021bf0bd41c12
46,770
def u3u2(u3): """ feet&inch to inch """ f = u3[0] if f == '': f = 0 else: f = int(f) i = u3[1] if i == '': i = 0 else: i = round(convert_to_float(u3[1]), 2) u2 = f*12 + i return str(u2)
271bec37281a89e4add68828e437ae909d8cbbd6
46,771
import os def is_csv(path): """Is a file a CSV file extension?""" (filename, ext) = os.path.splitext(path) return ext.lower() in ['.csv', '.CSV']
d9ccb799a432f9695ac64c87b3f5eda54748f5df
46,772
from pydantic_factories import ModelFactory def create(policy_backbone: ModelFactory, value_backbone: ModelFactory): """ Vel creation function """ return DeterministicPolicyModelFactory( policy_backbone=policy_backbone, value_backbone=value_backbone )
05970ef98baec267a33629c0eb13da1dd807db12
46,773
def main(args: Namespace) -> bool: """ The Function to process the data at the given path using the given transformation rules and store them at given destination path. if any file fails at transformation level, it will be stored in error path Args: args (Namespace): Argument Namespace con...
96a3098f9df10b58fdc55b894ff3901d80ab7eeb
46,774
def rising_edge(signal): """ FUNCTION: rising_edge(a str) a: signal name Rising edge wait function. """ global sim_time_queue if (sim_time > 0): signal_cur_value = 0 signal_prev_value = 0 ...
61d3f654f908b4e50fbbb64f23629a6d08bb08b5
46,775
def alt(*args: Pat) -> Pat: """Matches one of the given choices. >>> alt() # will never match alt() >>> alt('a') 'a' >>> alt(alt('b', 'c'), 'd') alt('b', 'c', 'd') """ choices = [] for a in args: if isinstance(a, Alt): choices.extend(a.choices) else...
88f8490cb800d80315ad81aac7b9a62f6055fe56
46,776
def batch_get_value(ops): """Returns the value of more than one tensor variable. # Arguments ops: list of ops to run. # Returns A list of Numpy arrays. """ if ops: return get_session().run(ops) else: return []
ef3018db0f3640c13910cc9d1b7af848499d4e51
46,777
def calculate_interest_years(starting_amount, requested_amount, interest_rate, stipend_rate): """ If I want X in the bank, how long will it take? :param starting_amount: The amount of money the bank has to start with. :type starting_amount: double :param requested_amount: The amount requested in the...
9af2d7917d4b7184d09467a1a996bdb86adcbd21
46,778
def short_information(title, index=0): """ Takes in track information and returns everything as a short formatted String. Args: title (str): track title string index (str): optional track number string Returns: A short formatted string of all track information. """ if ...
6754af1f2327eb5d9f37f4d25aa4f808d4793553
46,779
def _reduction_a_cell_do(ip, p, filters, net_type, cell_num, total_num_cells, total_training_steps, do_p=0.3, block_id=None): """Adds a Reduction cell for NASNet-A (Fig. 4 in the paper). Args: ip: Input tensor `x` p: Input tensor `p` filters: Number of output filters block_id: S...
017d5b05951c8c60667ff9dd0a77baf29e3b9c55
46,780
from typing import List from typing import Dict from typing import Callable def post_processor(provider: str = None, parser: str = None, provider_parser_list: List[Dict] = None) -> Callable: """ Decorator that register function for post processing. You can insert provider and parser or ...
a0a4a27d405c130547c0c83908133e4a882804e6
46,781
def AddAttachedCertificatesFlagsToParser(parser): """Adds flags describing certificate update without resource args.""" is_clear_certificates = base.Argument( '--clear-certificates', help='Removes all certificates from the entry', action='store_true') group = base.ArgumentGroup( help='Arg...
5b5cbea6f5b18db1ea4b04bd45c1693e8c78d2f0
46,782
def vmaddrelu(x, y, z): """ calculate relu(x * z + y), only support float16, float32. Args: x (tvm.tensor.Tensor): input. y (tvm.tensor.Tensor): input. z (tvm.tensor.Tensor): input. Returns: tvm.tensor.Tensor, relu(X * Z + Y). """ return multiple_elewise_op(x,...
c1f10e19208ba43c60f98832a99f4aad20792202
46,783
def setup(hass, config): """Set up the keyboard_remote.""" config = config.get(DOMAIN) keyboard_remote = KeyboardRemote(hass, config) def _start_keyboard_remote(_event): keyboard_remote.run() def _stop_keyboard_remote(_event): keyboard_remote.stop() hass.bus.listen_once(EVENT...
2b519b4a7ce979e3c74e9f299f4b8d54bc6dd7d2
46,784
import six def _write_metadata(output_fp, metadata, metadata_args): """ Write the metadata to a file pointer. Parameters ---------- output_fp : file like the file pointer to write to metadata : dict the metadata to write metadata_args : MetadataArgs the metadata args ...
d42df9bad4462ad0095f1ae62e19f6a23f89c055
46,785
def _compute_taylor(data_input): """Algorithm: atanh(x) = x + x^3/3 + x^5/5 + x^7/7""" taylor_para = [0, 1.0, 0, 1/3.0, 0, 1.0/5, 0, 1.0/7] # x^2 data_mul_2 = topi.multiply(data_input, data_input) # 1/5 + x^2/7 data_mul_2_7 = topi.multiply(data_mul_2, tvm.const(taylor_para[7], "float32")) ...
a4e96d647ddc8531c8ba1a4c1d878922881a13e1
46,786
def infer_feature_types(data, feature_types=None): """Create a Woodwork structure from the given list, pandas, or numpy input, with specified types for columns. If a column's type is not specified, it will be inferred by Woodwork. Arguments: data (pd.DataFrame): Input data to convert to a Woodw...
f584d5d6d8c4034a547af0e75d46a4ed9edd377d
46,787
def apply_token_replay(log, net, initial_marking, final_marking, parameters=None): """ Calculates all metrics based on token-based replay and returns a unified dictionary Parameters ----------- log Trace log net Petri net initial_marking Initial marking final_mar...
3712011039921d88bfd0026fd824dd84148353cd
46,788
def add_css_file_extension(name): """ Appends the CSS file extension to a string. :return: name with '.css' append at the end append at the end :rType: string """ return '%s.css' % name
fbe4569e4660cc4145bac36a5ea88ae87ec4c319
46,789
import collections import numpy def get_data_hlsp_everest(obsid): """ Given a EVEREST observation ID, returns the lightcurve data. :param obsid: The EVEREST observation ID to retrieve the data from. :type obsid: str :returns: JSON -- The lightcurve data for this observation ID. Error codes...
1a3ff1f4421fc1b6ca0ccdd83aa69c6c684b83f3
46,790
def try_protection(var, target, attacker, attacker_role, reason): """Attempt to protect the player, and return a list of messages or None.""" prots = [] for protector, entries in PROTECTIONS.get(target, {}).items(): for scope, protector_role in entries: if attacker_role in scope: ...
2e226135a222a887ce39bda8a61c146fd7dfeade
46,791
def _get_position(a, n): """ returns position of substring :n: as "start", "end" or "middle" """ position = a.index(n) if position == 0: return ("start", position) elif position+len(n) == len(a): return ("end", position) else: return ("middle", position)
f7a18c540542f117df822c18396e3e554d1eba45
46,792
import six import uuid def data_factory(value, encoding='UTF-8'): """Wrap a Python type in the equivalent C AMQP type. If the Python type has already been wrapped in a ~uamqp.types.AMQPType object - then this will be used to select the appropriate C type. - bool => c_uamqp.BoolValue - int => c_uam...
47021c6afb22bee803c36ba1b4eb3ab4b8a3687c
46,793
def AllTokens(): """Retrieves all descendants of pygments.token.Token.""" def Traverse(token): for tok in token.subtypes: yield tok for sub_token in Traverse(tok): yield sub_token return sorted(Traverse(pygments.token.Token))
86686f691a3023477ce9c1892641de1d4a6e509a
46,794
def previous(values, elements, scope=None, strict=True): """Return closest previous (index, elem) of values withing scope. Assumption: values and elements are sorted """ # Init iterator on elements elem_indexes = enumerate(elements) index, elem = next(elem_indexes) try: nin...
36b83dc2665539a3a9cb8b50419cd15410a8969c
46,795
from typing import Dict from typing import Any import toml def _load_prefs() -> Dict[str, Any]: """Load user preferences from TOML and return as a dict :return: dict containing user preferences """ try: return dict(toml.load(PREFERENCES)) except (IOError, toml.TomlDecodeError): l...
369296b7292b02cec01503462ed5bf6a54c949c9
46,796
def slice(from_index, to_index, list_or_string): """Returns the elements of the given list or string (or object with a slice method) from fromIndex (inclusive) to toIndex (exclusive). Dispatches to the slice method of the third argument, if present""" return list_or_string[from_index:to_index]
130692bad6f7de87a07786afe0ea3d6d30902ba7
46,797
def make_app(): """Create page handlers and create a Tornado app.""" handlers = create_route_handlers(config.pages) settings = { "static_path": config.static_path, "template_path": config.template_path, "debug": True } return tornado.web.Application(handlers, **settings)
895697f04161c3c73e57d55cdd652a30107a8337
46,798
def accuracy(output, target): """Computes the precision@k for the specified values of k""" # batch_size = target.size(0) * target.size(1) * target.size(2) _, pred = output.max(1) pred = pred.view(1, -1) target = target.view(1, -1) correct = pred.eq(target) # correct = correct[target != 255] ...
4f6f25311f1579d8d638a684d40bd80d99387eae
46,799