content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import random from typing import List def create_buckets_ordered_randomly( nparts_lhs: int, nparts_rhs: int, *, generator: random.Random, ) -> List[Bucket]: """Return all buckets, randomly permuted. Produce buckets for [0, #LHS) x [0, #RHS) and shuffle them. """ buckets = create_buck...
83fd0bacad5ad08e3a8a1928915efd7447871063
3,619,600
import os def extract_features(sourcedir): """ This function parses a directory for images, extracts their labels, applies ImageNet preprocessing and extracts CNN codes from the final average pooling layer in ResNet50. Params: sourcedir: The root directory to parse for images. Return...
f5916f28e4a488bf8e468af6800f9342bd38a5ab
3,619,601
def regression_on_terrain_ridge_lasso(filename, method, degree_arr, lambda_arr, k=5): """ Info: Perform RIDGE/LASSO regression on ".tif" terrain data for all degrees in degree_arr and all alphas in 10**lambda_arr. MSE is evaluated by using k-fold CV. Input: * filename: names of files in dat...
a57f4b1c5e4454206614c43a98fc62b9018d0ca4
3,619,602
def get_parametric_distribution_for_action_space(action_space): """Returns an action distribution parametrization based on the action space. Args: action_space: action space of the environment """ if isinstance(action_space, gym.spaces.Discrete): return CategoricalDistribution(action_space.n, ...
1c37cd9a1954f09875c96b58211d0008c56128e2
3,619,603
def find_vigenere_key(cipher, keylen): """Breaks a vigenere cipher with known keylen""" key = [] for block in utility.transpose(cipher, keylen): _, k, _ = find_single_byte_xor_key(block) key.append(k) return bytes(key)
e4da24d05a900a46df1368afeea8007b2c303687
3,619,604
def client_dual_1() -> testing.TestClient: """Create testing client""" return testing.TestClient(app_dual_1)
6e6a6ccb249a5c9bf19184fcca3390f8705e9f4c
3,619,605
def Variable_Point_to_Probability(train, forecast, alpha=0.3, beta=1): """Data driven placeholder for model error estimation. ErrorRange = beta * (En + alpha * En-1 [cum sum of En]) En = abs(0.5 - QTP) * D D = abs(Xn - ((Avg % Change of Train * Xn-1) + Xn-1)) Xn = Forecast Value QTP = Percentil...
85be0097125e95954b07b722d0229912becdf37a
3,619,606
def count_frequency(df, col): """Count the number of occurence value in a column.""" df['Freq'] = df.groupby(col)[col].transform('count') return df
28f502d79bacaba474c6df8b642f8e3f7875d1f3
3,619,607
def _get_all_objs(container, classname): """Get all `neo` objects of a given type from a container. The objects can be any list, dict, or other iterable or mapping containing neo objects of a particular class, as well as any neo object that can hold the object. Objects are searched recursively, so ...
33133c63af0fb6375ea4f6f69bb7b3798f2d0d25
3,619,608
from typing import Tuple def paired_dot_distance(par_xy: np.ndarray, dau_xy: np.ndarray ) -> Tuple[np.ndarray]: """Calculates error for normalized dot distance and error along line NOTE: - x, y are switched in this function relative to the image. T...
9bb1b37388e1e7f983f224ce8efef022fc121f0a
3,619,609
import warnings def project(B, nodes, create_using=None): """Return the graph of the the given bipartite graph projected onto a subset of nodes. The nodes retain their names and are connected in the resulting graph if have an edge to a common node in the original graph. Parameters ---------...
1ea88dfad4d7193f8843756c213a8153be0c5f55
3,619,610
def DBSCAN(M, eps=0.5, min_pts=5, d='euclidean'): """ Performs DBSCAN clustering. M: matrix to use eps: Epsilon for DBSCAN algorithm, Neighbourhood to find points in min_pts: Threshold to consider neighbourhood dense. d: Distance metric to use. """ dbscan_obj = clus...
877974edaa0ffd922ff8d14efee3108c07f492af
3,619,611
def _do_ramp(psi_0,H,basis,v,E_final,V_final): """ Auxiliary function to evolve the state and calculate the entropies after the ramp. --- arguments --- psi_0: initial state H: time-dependent Hamiltonian basis: spin_basis_1d object containing the spin basis (required for Sent) E_final, V_final: eigensystem of H(...
179916d5c4ef0e3ba4e0184d539ad62ef8b77974
3,619,612
def extract_tty_phone(service_center): """ Extract a TTY phone number if one exists from the service_center entry in the YAML. """ tty_phones = [p for p in service_center['phone'] if 'TTY' in p] if len(tty_phones) > 0: return tty_phones[0]
9c4d349e0c75b1d75f69cb7758a3aac7dca5b5a5
3,619,613
def get_nature(nature_id): """Retrieves a set of information about a nature. Keyword arguments: nature_id (int) -- the ID of the nature (0-24) """ db = get_cursor() query = 'SELECT `id`, `name`, `atk`, `def`, `spe`, `spa`, `spd` FROM `natures` WHERE `id` = ?' nature = db.execute(query, (n...
d597546829bef0e9d5045dbc82c7ff2abd328481
3,619,614
from pathlib import Path def get_data_dir() -> str: """Get a filepath to the drem data directory. Returns: str: Filepath to the drem data directory """ cwd = Path(__file__) base_dir = cwd.resolve().parents[3] data_dir = base_dir / "data" return str(data_dir)
16e1bf3d8eab4c4f58ec90f832fd15809bdbbbca
3,619,615
import select def get_sites_by_processing_status(s_status, sorting_desc=False): """ Gets sites by processing status :param s_status: str - The chosen processing status :param sorting_desc: bool - Sorting order: True (desc), False (asc - default in PONY) :return: sites_names: list of str - The ur...
2316bc9a8fbd1bff0e1af72b20a390a710e9fb2e
3,619,616
from typing import Dict import logging def _encode_json(tokenizer, sample_json: dict, max_sequence_length: int) -> Dict: """ Method enrich utterance json with encoded utterance, value and label for training later. :param tokenizer: BERT tokenizer :param sample_json: utterance JSON :param max_sequ...
161f8eac904674cefb815861d8c8aa5fe2787901
3,619,617
import os import tempfile def exportBushfire(bushfire,folder=None,merged_bushfires=None): """ export bushfire as geojson file bushfire should be a Bushfire or BushfireSnapshot object """ bushfire = get_bushfire(bushfire) if merged_bushfires: merged_bushfires = get_bushfire(merged_bushf...
b40e6d3513d35cb35d417ee3959b22832e3bae2f
3,619,618
def is_trimesh_installed(raise_exception: Boolean = False) -> Boolean: """ Returns whether *Trimesh* is installed and available. Parameters ---------- raise_exception Whether to raise an exception if *Trimesh* is unavailable. Returns ------- :class:`bool` Whether *Trime...
4596af266177d424de2549b14650a1ba487a7ab7
3,619,619
import shutil def get_unshare_path(): """Find the path to the unshare utility.""" return shutil.which('unshare')
5ca2f1a9bdd8cc107c00be137c6dc3ca0a6f0db7
3,619,620
def l3_interface_group_id(ne_id): """ L3 Interface Group Id """ return 0x50000000 + (ne_id & 0x0fffffff)
00576c8c33fc965d759abc2aa00aa8f46b930a07
3,619,621
def LogStatusFrame(*args, **kwargs): """LogStatusFrame(wxFrame pFrame, String msg)""" return _misc_.LogStatusFrame(*args, **kwargs)
e227ef646140b3cb7fb8ffaa938981a7cacb910d
3,619,622
def set_safari_cookie(request): """ Special handling for Safari's third party cookie blocking: when showing a private link, user will be forwarded to this view on WARC_HOST to have an arbitrary cookie set, so Safari will let us set an authorization cookie in the iframe. Once we set the cooki...
71aa8996e1ecbe9f391fa9f85e0886d4ce36e9ed
3,619,623
import re def eat_arguments(node, text): """ gets the (parameters) appended to the +tag """ DEL = r'(?P<argend>\))|(?P<has_value>=)' ATTR = r'\s*(?P<attribute>[\w\-:\.#]+)\s*' VAL = r'\s*"(?P<value>.*?)"\s*' tokens = re.compile('|'.join((VAL, ATTR, DEL))).finditer(text) for mo in tokens: type_ = mo.lastg...
aeb61ba1ee0636af06a53848e9dcd2f9d5ec9670
3,619,624
def checkpoint(func, inputs, params, flag, final_nograd=0): """ Evaluate a function without caching intermediate activations, allowing for reduced memory at the expense of extra compute in the backward pass. :param func: the function to evaluate. :param inputs: the argument sequence to pass to `fun...
36cc3a8d66337992e7f8969026db386e34905825
3,619,625
def get_data(name): """Utility for convenient data loading.""" images, labels = extract_images() images = np.reshape(images, list(images.shape) + [1, ]) rng = np.random.RandomState(seed=47) # inds = rng.choice(len(images), int(len(images) / 5 * 4)) # print(inds) if name == 'train' or name...
635d8c246aa39ed752da747bd253bed30ea15fa3
3,619,626
def check_unlogged(tasks, logs, user, log_date): """Given a queryset of tasks, a queryset of logs and a log date, checks for unlogged tasks and creates new logs where needed, returning True. Returns False if no new logs are created.""" unlogged = [] # Check for unlogged tasks for task in tasks:...
ac8701a343b2fbc3d473e10380bd328a78c2c293
3,619,627
from datetime import datetime def _pipeline_runtime(jobs): """Compute the runtim of the pipeline""" times = [] now = datetime.now() # collect the times for j in jobs: if j.start_date: s = j.start_date e = j.finish_date if j.finish_date else now times.app...
c6f819283bd736a3077e6bea3a372bcf87d7a38a
3,619,628
def addresses(x: bytes) -> list: """ Creating a list of IPv4 addresses from a byte string Args: x: source bytesting Returns: A list of one or multiple IPv4 addresses """ x = x[4:] addr: list = [] while len(x) > 0: single_address: bytes = x[5:9] addr.append(i...
92a4eefb537a07065f8cb6e7100030894c4a6333
3,619,629
def __max_group_mass__(groupMass, parameters): # type: (pandas.DataFrame, LFParameters) -> pandas.DataFrame """Replace the m/z value of each row by the m/z with the highest sample mean intensity. Keyword Arguments: groupMass -- mass or feature cluster parameters -- LipidFinder's PeakFi...
129f5381b18a0a89bab3758d9531175de3b61e0f
3,619,630
def color_from_string(cstr): """ Return a Geosoft color number from a color string. :param cstr: color string (see below) :returns: color Colour strings may be "R", "G", "B", "C", "M", "Y", "H", "S", "V", or "K" or a combination of these characters, each followed by up to three di...
bd4fccbf67f436c3a7a10b8ce13f542c6cbbf038
3,619,631
def corr_pred_gold(gold, pred, eval_type=EvalTypes.NODE): """Given a golden tree/sentence and a predicted tree/sentence, this counts correctly predicted nodes/tokens (true positives), all predicted nodes/tokens (true + false positives), and all golden nodes/tokens (true positives + false negatives). @p...
8e81d45af2a8ffce71962a8de9ccd3160e1a3513
3,619,632
def get_value(amount, currency): """ Returns the value of the transfer in the representation of the currency it is in, without symbols That is, 1000 cents as 10.00, 1000 yen as 1000 """ if currency in DECIMAL_CURRENCIES: return Decimal(amount)/Decimal(100) return Decimal(amount)
f5edd6cafb1ffa1e87e88b09affb2182e00586f9
3,619,633
def subaward_types_are_valid_groups(type_list): """Check to ensure the award type list is a subset of one and only one award group. Groups: are "Procurement" and "Assistance" If false, the award type codes aren't a subset of either category. """ is_procurement = set(type_list).difference(set(procur...
8ef5eea5e9480c8cc1573e41195fa9ea50ebd519
3,619,634
def parse_none(func): """Decorator for a parser which can parse None Args: callable: function to be decorated Returns: callable: func with attr indicating it can parse None """ setattr(func, _PARSE_NONE_ATTR, True) return func
4752bc774caf434b219cf8ffafa65cba067fb62b
3,619,635
def register(request): """ Register new user. Args: request (HttpRequest): Request with user `name`, `first_name` and `password` passed with the `GET` method. Returns: An `HttpResponse` with search results. """ if request.method == 'POST': user...
14d55ac2d0a185797b94d9f216476e7bd0a74969
3,619,636
def make_tag_list(tag_dict): """ make list from tag dictionary """ tag_list = tag_dict.keys() # needless because keys doesn't overlap. # tag_list = list(set(tag_list)) # but, in python3, type of tag_list is not list, it is dict_key. tag_list = list(tag_list) tag_list.sort() return tag_li...
3dc825c1ac9cf9b6a1d2df5d4b46f2755b267381
3,619,637
def temp_dynamics( models: dict, ) -> np.ndarray: """Returns the new zone temperatures based on the current state.""" zone_temp = np.zeros(Z, dtype=np.float64) for z in range(Z): y = np.array(models[z]["ss_C"]).squeeze() * models[z]["x_k"].squeeze() zone_temp[z] = y + models[z]["mean_ou...
bf4fcdfb34367663499b5dd16e4611f20cea3d0e
3,619,638
def logsig(x): """ logsig activation function """ return 1.0 / (1.0 + exp(-x))
896b8f779010b4591e3efcccca3bfb3a81cf1a01
3,619,639
def filter_cpgkeys_using_bedfile(cpgKeys, bedFileName): """ Keep only cpg keys in bed file range, return set of keys :param cpgKeys: :param bedFileName: :return: """ cpgBed = calldict2bed(cpgKeys) coordBed = get_region_bed(bedFileName) intersectBed = intersect_bed_regions(cpgBed, coo...
420f07571b0239e9df90ad25fc640baad444c253
3,619,640
def adjust_prices(utilities, caps, budgets, prices, n): """return the new prices""" cleared_bool = clearing(np.sum(allocate(utilities, caps, budgets, prices, n), axis=0), utilities, caps) # Find clearing prices while not np.all(cleared_bool): if not cleared_bool[0]: for i in range(n)...
64898029f4f5b66e8cf7b0bf2cc998efc84c8872
3,619,641
def symmetricTensor(a,b,c): """ symmetric tensor product from section 5.2 of Song et al. (2014) """ term1 = np.tensordot(np.tensordot(a,b,0),c,0) term2 = np.tensordot(np.tensordot(c,a,0),b,0) term3 = np.tensordot(np.tensordot(b,c,0),a,0) return term1+term2+term3
6f039972b9736ffd03aa2fff81d10aecf27ec532
3,619,642
def sentinel(name): """Create a unique, one-off object with a useful repr""" def __repr__(_): return f'<{name}>' return type(name, (), {'__repr__': __repr__})()
6abe44a5b72bf7d5685c3d7ca97caf0b9c2ee49b
3,619,643
def clifford_attractor(lvl, a, b, c, d): """ Inputs: lvl -- integer, number of iterations a, b, c, d -- numeric parameters Return a tuple with two 1D numpy arrays, each of size lvl + 1, with calculated xy coordinates. """ lvl += 1 # Containers to store xy components/coordinates...
c4c07666cc04a4cfa0f4f0f262af46f74610ad76
3,619,644
def diskAverage(s,r_out,bins=50,avgFlag=True): """ Computes the accretion disk mass-averaged for x via the following equation: integral of 2*pisigma*x*r*dr / integral of 2*pi*sigma*r*dr. Sigma, e,a... calculated on the fly to ensure that they are all evaluated at the same location. Paramete...
1d1c9ee81269c45580b6c5b30f779ba156309826
3,619,645
def datestr(datetime_inst): """ make iso time string from datetime instance """ return datetime_inst.isoformat("T")
027dbaa0c3223261f4afd4e2f3aab45611eab265
3,619,646
import ast def read_csv(fname, params_dict): """ Reads csv file. Paramenters ----------- fname : str Path to file name. params_dict : dict Dict with paramenters for parsing csv file. `csv_delimiter`, `proteins_column`, `proteins_delimiter` Returns ------- ...
145b0bc2beed493b788582a2240b5e0d3567e729
3,619,647
def minimal_spanning_tree(graph, mode='Prim', starting_node=None): """ Args: graph: weighted adjacency matrix as 2d np.array mode: method for calculating minimal spanning tree starting_node: node number to start construction of minimal spanning tree (Prim) Returns: minimal s...
2605761918b39efd7abc1f507b71a848f96d1047
3,619,648
def imaging_mask(maskbits, bitnamelist=get_default_maskbits(), bgsmask=False, mwsmask=False): """Apply the 'geometric' masks from the Legacy Surveys imaging. Parameters ---------- maskbits : :class:`~numpy.ndarray` or ``None`` General array of `Legacy Surveys mask`_ bits. b...
304a25224f37bbfb6c452c973205dee900c7abcb
3,619,649
def gen_bbox(lat1_deg,lon1_deg,radius=10): """ gen_bbox returns the upper left and lower right coordinates of the bounding box who's center is at the specified lat/lon Inputs: lat1_deg -- Input latitude (degrees) lon1_deg -- Input longitude (degrees) radius -- Inputs radius (meters) ...
51bbff58c400fcdfe0a7a5a108383e5ffeef819b
3,619,650
import bot_config import traceback def get_state(sleep_streak): """Returns dict with a state of the bot reported to the server with each poll. """ try: if _in_load_test_mode(): state = os_utilities.get_state() state['dimensions'] = os_utilities.get_dimensions() else: state = bot_config...
4fdbe3a2f5c99ab7be73f9a0c0475fcffeb2575d
3,619,651
def get_connection_probabilities(N,k_over_2,beta): """ Return the connection probabilities :math:`p_S` and :math:`p_L`. """ assert_parameters(N,k_over_2,beta) k = float(int(k_over_2 * 2)) pS = k / (k + beta*(N-1.0-k)) pL = k * beta / (k + beta*(N-1.0-k)) return pS, pL
4ad3f0d9214c1d920946714d28250a81f1596063
3,619,652
def GetPortagePackage(target, package): """Returns a package name for the given target.""" conf = Crossdev.GetConfig(target) # Portage category: if target == 'host' or package in Crossdev.MANUAL_PKGS: category = conf[package + '_category'] else: category = conf['category'] # Portage package: pn = ...
8acc7704a877738a8e2b1754a34ac4dd92b995f2
3,619,653
def get_new_objective(fields, objective): """Checks if the objective given by the user in the --objective flag differs from the one in the dataset. Returns the new objective or None if they are the same. """ if objective is None: return None try: objective_id = fields.fiel...
a17cd55864a3c2215a0b7570228643b1e35e9805
3,619,654
def RandomForestClassifier(): """Wrap a default Random Forest classifier with fixed parameter.""" return sklearn.ensemble.RandomForestClassifier(n_estimators=64)
d574a6dbb2825333b5c7c75c0ce8360619c74be0
3,619,655
def get_skew_symmetric(rotational_vector): """Get the skew symmetric matrix of a rotational vector. Parameters ---------- rotational_vector: numpy.ndarray the rotational vector. Returns ------- skew_symmetric: the skew symmetric matrix of the rotational vector. """ ...
6dc7e43b817d51f84487083e9836235cac3cb5b4
3,619,656
import os import pprint import io def get_image(folder, item, filename): """画像のレスポンス size で拡大縮小.""" if folder not in ['download', 'face', 'train', 'test']: abort(404) filename = os.path.join(DATA_PATH, folder, item, filename) try: image = Image.open(filename) except Exception as...
8f9c16cc9095d0eb02251b963e047d3a59e48f36
3,619,657
import math import torch def wrap_phi_to_2pi_torch(x): """Shift input angle x to the range of [-pi, pi] """ pi = math.pi x = torch.fmod(2 * pi + torch.fmod(x + pi, 2 * pi), 2 * pi) - pi return x
0905134f4cce5aae13f91e9e7900dd053a5861aa
3,619,658
import binascii import codecs def utf16decode(bytes): """ Take the UTF-16LE encoded strings as bytes from .tbl files and convert to a UTF-8 string. Jython-compatible. """ bytes = binascii.hexlify(bytes) bytes = [bytes[i:i+2] for i in range(0, len(bytes), 2)] bytes = (''.join(filter(lambda a:...
eff2ccc27e2175bfb05efa59216cfc2150387c55
3,619,659
def FixAbsolutePathInLine(line, relative_paths): """Fix absolute paths present in |line| to relative paths.""" absolute_path = line.split(':')[0] relative_path = relative_paths.get(absolute_path, absolute_path) if absolute_path == relative_path: return line return relative_path + line[len(absolute_path):]
e0db0d2f3a0973b4db5f3e551f164481861c0b56
3,619,660
def vgg13_XXS(*args, **kwargs): """VGG 16-layer model (configuration "D") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = VGG(make_layers(cfg['BXXS']), final_filter=64, **kwargs) model.name = "VGG13_XXS" return model
92996c6b4dc9f58b2833eaacbba9188203b0da09
3,619,661
def read_schema(path): """Reads a schema from the provided location. Args: path: The location of the file holding a serialized Schema proto. Returns: An instance of Schema or None if the input argument is None """ result = schema_pb2.Schema() contents = file_io.read_file_to_string(path) text_for...
49daaee4c2edd1de290258e3167e0b37efd04d68
3,619,662
import os def buildCudaCoreDockerCLI(devices): """ Creates the correct device and volume structures to be passed to docker. """ cli_devices = [] cli_volumes = {} libs = [] current_devices = ['/dev/{}'.format(i) for i in os.listdir('/dev/')] for device in devices: if ...
b751b0512e422a5966c4c70dc49b028c26492e49
3,619,663
from websauna.utils.configincluder import monkey_patch_paster_config_parser def ini_settings(request, test_config_path) -> dict: """Load INI settings for test run from py.test command line. Example: py.test yourpackage -s --ini=test.ini :return: A dictionary representing the key/value pairs i...
073e040bf5ebd915c1a00fa4f3869a8ff66f69bc
3,619,664
def is_http_url(url: str) -> bool: """判断url是否是http请求的url. Args: url (str): 待判断的url字符串 Returns: bool: 是否是url """ try: result = urlparse(url) return all([result.scheme, result.netloc]) and result.scheme in ("http", "https") except ValueError: return False
fdce9da96da12ad212acb1b1c8b4f70e4495cf28
3,619,665
import os import logging def eval_other(setup, nee, i, scoresheet, repeat, nw_outpath): """ Experiment to test other embedding methods not integrated in the library. """ print('Evaluating Embedding methods...') lp_coef = dict() if setup.methods_other is not None: # Evaluate non OpenNE...
0c9a2432c0d091db3633f814ec1bb26eb0b31dde
3,619,666
def setup_persistent_compute_target(workspace, cluster_name, vm_size, max_nodes): """ Set up a persistent compute target on AzureML. A persistent compute target runs noticeably faster than a regular compute target for subsequent runs. The benefit is that AzureML ...
68f0c963c5a9a6d50fa668170b1332cb3a091e5e
3,619,667
def flatten_tuple(item): """ """ if not is_valid_iterable(item): return ensure_tuple(item) if item and is_valid_iterable(item[0]) and len(item) == 1: item = item[0] if item and is_valid_iterable(item[0]): item = (*item[0], item[1]) return tuple(item)
11dc6e87ad349b6ff79360db47426c16713f4ed0
3,619,668
import yaml def connect_mongodb() -> MongoClient: """connect mongodb""" config = yaml.load(open(SERVER_FILE_PATH, encoding="utf-8")) config_dct = config.get("mongodb") client = MongoClient( "mongodb://{user}:{pwd}@{host}:{port}/{db}" "?readPreference=primary".format( user=c...
b50a55beadee3c2d6c0f48a9e6021f6e948a9e69
3,619,669
def f5(seq, idfun=None): """Uniqify a list (remove duplicates). This is the fast order-preserving uniqifier "f5" from http://www.peterbe.com/plog/uniqifiers-benchmark The list does not need to be sorted. The return value is the uniqified list. """ # order preserving if idfun is None: ...
a64aa35e1d4ab89213240c8ec2325bab9ee75ffe
3,619,670
def cvCrossProduct(*args): """cvCrossProduct(CvArr src1, CvArr src2, CvArr dst)""" return _cv.cvCrossProduct(*args)
14b317055dc0d47f8687a510f8cb841c6b5969a3
3,619,671
def compute_oks(points_gt, points_pr, scale=None, stddev=0.025): """Computes the object keypoints similarity between sets of points. Args: points_gt: Ground truth instances of shape (n_gt, n_nodes, n_ed), where n_nodes is the number of body parts/keypoint types, and n_ed is the ...
893a995bb9fbfe0d9acf8d99911588008fe486ab
3,619,672
async def get_member(message, command, example): """ getting the user from reply message """ try: member = message.reply_to_message.from_user logger.info(f"received the user {member}") except AttributeError: await message.answer(f"You must <b>send</b> the message " ...
e45250733c395fb3b2e3337b009a1a9d4e4119c0
3,619,673
import arcgis def define_output_datastore(datastore=None, template=None): """ Sets the `arcgis.env.output_datastore` by providing the datastore and template name to this method. If datastore is None, the `arcgis.env.output_datastore` will reset to default. ========================== ===========...
91f8030cdaf9face090b53ed9014168f3b439c7b
3,619,674
import kwplot def draw_roc(roc_info, prefix='', fnum=1, **kw): """ NOTE: There needs to be enough negative examples for using ROC to make any sense! Example: >>> # xdoctest: +REQUIRES(module:kwplot) >>> # xdoctest: +REQUIRES(module:ndsampler) >>> from netharn.metrics import De...
127237f9d327d711dd16e246cdbf1b0c6f6863fb
3,619,675
import json def verify_recognized(file_path, mkvmerge_path='mkvmerge'): """Verify a file is recognized by mkvmerge. file_path (str): Path to the file to be verified. mkvmerge_path (str): Alternate path to mkvmerge if it is not already in the $PATH variable. """ if not verify_mkvme...
594619ceb240e384e85aa61570aab47e3e5b7e42
3,619,676
def padded_gather_nd(params, indices, r, idx_rank): """Version of gather_nd that supports gradients and blank indices. Works like gather_nd, but if an index is given as -1, a 0 will be inserted in that spot in the output tensor. Args: params: tensor from which to gather (see gather_nd). indices: tenso...
909c1b8f615367887ea5abe9a7ea881650c425b0
3,619,677
def formatted_bool_eval(token_lst, op_dict): """eval a formatted (i.e. of the form 'ToFa(ToF)') string""" if not token_lst: return None if len(token_lst) == 1: return token_lst[0] has_parens, l_paren, r_paren = parens(token_lst) if not has_parens: return generic_eval(token...
e6e88099506884e197adb1d29d58665253904daf
3,619,678
def mapk(actual, predicted, k=10): """ Computes the mean average precision at k. This function computes the mean average prescision at k between two lists of lists of items. Parameters ---------- actual : list A list of lists of elements that are to be predicted (o...
5c55bc1dfa48ee42e97560f72f7f72338eb8dfe1
3,619,679
def loss(_sender_input, _message, _receiver_input, receiver_output, labels, _aux_input): """ Accuracy loss - non-differetiable hence cannot be used with GS """ acc = (labels == receiver_output).float() return -acc, {"acc": acc}
85c7d614e004c6c5349c4f42eb99155b7c7aee48
3,619,680
def lazyprop(func): """Wraps a property so it is lazily evaluated. Args: func: The property to wrap. Returns: A property that only does computation the first time it is called. """ attr_name = '_lazy_' + func.__name__ @property def _lazyprop(self): """A lazily evalu...
b14f82b196177be207923744dda695d6aa70248f
3,619,681
def text_to_hitobject(text: str) -> HitObject: """ HitObjectの文字列を各情報に変換してHitObjectクラスで出力します 引数 ---- text: str -> HitObject 戻り値 ------ HitObject -> HitObjectクラス 予想される例外 -------------- ValueError -> おそらくフォーマットが合っていないです、一旦見直しましょう """ text_split: list = text.split(',') if len(text_split) != 6: rais...
62cfc588e5b421b411cd08c1ec94653256924caf
3,619,682
def convert_DateTimeField(model, prop, kwargs): """Returns a form field for a DateTimeField.""" return f.DateTimeField(**kwargs)
e0a6cde4d5f96ba51a59868da20191ff4e4b2ca4
3,619,683
def extract_range(s): """ Extract range from string""" ranges = s.split(',') if len(ranges) > 1: return (int(ranges[0]), int(ranges[1])) else: return (int(ranges[0]), None)
2a0fea0bdbd40a9fc998fa0b1e2af97be1cbd980
3,619,684
def expand_machine_type(): """ get machine type specs from api """ machines = {} compute = googleapiclient.discovery.build('compute', 'v1', cache_discovery=False) for pid, part in cfg.instance_defs.items(): machine = {'cpus': 1, 'memory': 1} ...
645332927003ade153f3be57eb263e7483f11422
3,619,685
import os def create_output_path(filename, outdir=None): """ Given a filename for keypoints and descriptors, create an output directory with _kps.h5 appended. Parameters ---------- filename : str The filename or full path outdir : str An optional output path ...
102efd0ee8a523ac5050bcec5d6a1a41670d5203
3,619,686
def _ChooseTest(anomalies): """Chooses a test to use for a bisect job. The particular TestMetadata chosen determines the command and metric name that is chosen. The test to choose could depend on which of the anomalies has the largest regression size. Ideally, the choice of bisect bot to use should be based...
ddad6c52f2560e550bbbd4e72036669915fc4521
3,619,687
def _make_contrib(superclass, func=None): """Backport from django 1.8.""" def contribute_to_class(self, cls, name, **kwargs): if func: func(self, cls, name, **kwargs) else: super(superclass, self).contribute_to_class(cls, name, **kwargs) setattr(cls, self.name, _C...
ed92c383c2336134ac0e1598658de45ec384af52
3,619,688
import sys def _get_python_executable() -> str: """Returns Python executable. Returns: Python executable to use for setuptools packaging. Raises: EnvironmentError: If Python executable is not found. """ python_executable = sys.executable if not python_executable: rai...
90bcc7a8c4f57d092aca81720f68f005a1974f60
3,619,689
from typing import List from typing import Callable from typing import Optional def get_bundle_from_waypoints( ports1: List[Port], ports2: List[Port], waypoints: Coordinates, straight: Callable = straight, taper_factory: Callable = taper_function, bend: Callable = bend_euler, sort_ports: b...
b7c86dc5718b44c26ba26d98daca7185de0ee9e5
3,619,690
def Gaussian(values, errors, Nsamples=100, weights=None, guess=None, bias=True): """ A maximum likelihood estimator that returns the parameters for a Gaussian that best describes a given data set. Uncertainties on the best-fitting parameters are calculated using Monte Carlo sampling, but this c...
e479f20049314611d7225115f27d57bfa4d7da2d
3,619,691
def leNetModel(): """ Creates a LeNet model. """ model = createPreProcessingLayers() model.add(Convolution2D(6,5,5,activation='relu')) model.add(MaxPooling2D()) model.add(Convolution2D(6,5,5,activation='relu')) model.add(MaxPooling2D()) model.add(Flatten()) model.add(Dense(120)) ...
27fd6d4276215cf3bb1cf93d5c639ae715910750
3,619,692
def simpleCollision(spriteOne, spriteTwo): """ Simple bounding box collision detection. """ widthSpriteOne, heightSpriteOne = spriteOne.image.get_size() rectSpriteOne = spriteOne.image.get_rect().move( spriteOne.pos.x - widthSpriteOne / 2, spriteOne.pos.y - heightSpriteOne / 2) ...
b6084ad260e084effb11701a6b859e0a58c9d19b
3,619,693
def points_in_box(box: 'Box', points: np.ndarray, wlh_factor: float = 1.0): """ Checks whether points are inside the box. Picks one corner as reference (p1) and computes the vector to a target point (v). Then for each of the 3 axes, project v onto the axis and compare the length. Inspired by: https...
cd33957b0f87b71548dd20c9ca34fccb8666aa59
3,619,694
def random_flip(flip_x_chance, flip_y_chance, prng=DEFAULT_PRNG): """ Construct a transformation randomly containing X/Y flips (or not). Args flip_x_chance: The chance that the result will contain a flip along the X axis. flip_y_chance: The chance that the result will contain a flip along the Y ...
5e4b479f4c03464ad7e76788e783f59ef445adb9
3,619,695
import traceback def compare_image(name,func,options): """ Returns comparison information about the function performance on the given image. This function takes the image with the given name and filters it with the given function and options. It then compares it to the solution image. If the im...
6d24c5e850bb3f0d35dfa6a721f0e73f47cfb8ff
3,619,696
def load_yaml(filename: str): """ Load contents of a yaml file in a dictionary :param filename: path to the yaml file :return: a data object contains contents of the yaml file """ with open(filename, "r") as f: data_stream = f.read() return load(data_stream, Loader=Loader)
817d7974359840b083320928918a064ba0e3008c
3,619,697
def display_email_address(email): """Make a formatted address (eg: "User Name <username@somewhere.net>"), from a tuple (Display name, email address) or a list of tuples. If the parameter is a string, it is returned. >>> recipients = [('Joe','joe@smith.com'),'sally@smith.com'] >>> displa...
500f99d36f018f6ccf77fa941b14caca4aa02032
3,619,698
def create_dataframe(records, cache=False, require_unique=None): """Create a spark DataFrame from a list of records. Parameters ---------- records : list list of spark.sql.Row cache : bool If True, cache the DataFrame in memory. require_unique : list list of column names...
8889c9160f2fa869592b01639b057435d65de0d3
3,619,699