content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def run_garage(env, seed, log_dir): """ Create garage model and training. Replace the ppo with the algorithm you want to run. :param env: Environment of the task. :param seed: Random seed for the trail. :param log_dir: Log dir path. :return: """ ext.set_seed(seed) with tf.Grap...
a1a1f2adadab26460b0035c02d663af031db62cc
62,835
def modified_helmholtz_adjoint_double_layer_singular( test_points, trial_points, test_normal, trial_normal, kernel_parameters ): """Modified Helmholtz adjoint double layer for singular kernels.""" npoints = trial_points.shape[1] dtype = trial_points.dtype diff = _np.zeros((3, npoints), dtype=dtype) ...
afe0c8c8e9f2a6096fb4928000ae46dcc2c326cd
62,836
import time import shutil def curate_dataset(sourcedataset, destinationdataset, pathdataset, newdatasetname,\ manifeststatus, jsonpath, jsondescription): """ Associated with 'Generate' button in the 'Generate dataset' section of SODA interface Checks validity of files / paths / folders and then ge...
e4427d48d3bdb81d384d3d2673f1a88f817b377c
62,837
def adp_to_cartesian(alpha, delta, parallax): """ Convert coordinates from (alpha, delta, parallax) format into the (x, y, z) format. :param azimuth: [rad] :param altitude: [rad] :param parallax: [mas] :return: [parsec](x, y, z) array in parsecs. """ parallax = parallax / const.rad...
bc3dac955d57458fbcb3f737617850730e6862c7
62,838
def render_hunspell_word_error( data, fields=["filename", "word", "line_number", "word_line_index"], sep=":", ): """Renders a mispelled word data dictionary. This function allows a convenient way to render each mispelled word data dictionary as a string, that could be useful to print in the con...
9bbefd0b998abe25d0a977adfe69ef51185cde37
62,839
def atan2(y, x): """ My implementation of atan2 in tensorflow. Returns in -pi .. pi.""" tan = tf.atan(y / (x + 1e-8)) # this returns in -pi/2 .. pi/2 one_map = tf.ones_like(tan) # correct quadrant error correction = tf.where(tf.less(x + 1e-8, 0.0), 3.141592653589793*one_map, 0.0*one_map) tan...
6874de9fa697102d7af47af241e73ee322ce54c7
62,840
def ElasticConstants(atoms, symmetry, minimize=False, **kwargs): """Calculate the anisotropic elastic constants of a system. The atoms must be a periodic system with an orthorhombic cell, and the lattice constant(s) should be the equilibrium value(s). If not, the function will crash, unless calle...
ba0b70e21209c9eb1691ec8b2af247a86d755759
62,841
from typing import List import torch def sample_subgraph(graph_data: List[GraphInput], n_nodes=None, max_graph_size=None, do_sample=True, permuted_nodes=None): """ @param do_sample: if False, return original graph. @param graph_data: a list of N graphs, [anchor, ...], which share the ...
dca3d0af8b3f6256e7bfcf5581f9d51011731784
62,842
import re def tokenize(document): """ A tokenizer for the Python Textmining Package that works for unicode strings and doesn't replace non-ASCII characters (such as 'åäö') with spaces. """ document = document.lower() document = re.sub(u'[^\w]|[0-9]', u' ', document, flags=re.UNICODE) retur...
1d4a1e8ed05796df3ac797a0a08b82dba5f640e6
62,843
def update_context_path_comp_service_objective_function_name_name_by_id(uuid, value_name, name): # noqa: E501 """Update name by ID Update operation of resource: name # noqa: E501 :param uuid: ID of uuid :type uuid: str :param value_name: ID of value_name :type value_name: str :param name:...
921bc1f4859de1ec74b4ee84f51974c2a790639d
62,844
def ldns_resolver_print(*args): """LDNS buffer.""" return _ldns.ldns_resolver_print(*args)
bd4aa9bceaf5d20c5a3d8da980641b952a3f2332
62,845
import logging def show_metadata_probe(pad, info, user_data): """Buffer probe to show metadata in a buffer""" gst_buffer = info.get_buffer() if gst_buffer: logging.info("show_metadata_probe: %20s:%-8s: pts=%23s, dts=%23s, duration=%23s, size=%8d" % ( pad.get_parent_element().name, ...
f10c06f2dc61e545bd408dc48d18bf43b2459ccd
62,846
def _get_dataset_iterator(snli_data, batch_size): """Get a data iterator for a split of SNLI data. Args: snli_data: A `data.SnliData` object. batch_size: The desired batch size. Returns: A dataset iterator. """ with tf.device("/device:CPU:0"): # Some tf.data ops, such as ShuffleDataset, are ...
5574e3d9eecbfbe4e3db6390b0ca9bb10e5ac813
62,847
import signal def coherence(original_values, frames=[0]): """Calculate coherence and an idea ribo-seq signal Parameters ---------- values : array like List of values Returns ------- periodicity : float Periodicity score calculated as coher...
0656b7c5a43feb9c6264a24177754afb9e56de0a
62,848
def distance_matrix(coords: list) -> np.ndarray: """Return distance matrix from coords""" return np.triu(spt.distance.cdist(coords, coords, "euclidean"))
050061e9624148a83e056511535094a5345f57e6
62,849
def get_domain_alerts_command(client: MsClient, args: dict): """Retrieves a collection of Alerts related to a given domain address. Returns: (str, dict, dict). Human readable, context, raw response """ headers = ['ID', 'Title', 'Description', 'IncidentID', 'Severity', 'Status', 'Classification'...
4d6a8fbaf929e3c55849d67e08abf5b88dd91a5c
62,850
import torch def load_model(config, from_checkpoint=False): """ Wrapper around initialize_model. Loads model with parameters in config and loads weights if from_checkpoint is set to True. Args: config (coconet.core.Configuration object) from_checkpoint (bool): whether to load a pre-tr...
3bfae38e940f8158eddae0a0922a45054cb2b901
62,851
from create_gitrepo import create_gitrepo import random import tqdm from pathlib import Path import re import json from datetime import datetime def make_gt_line_pairs(ctx, fpaths, outputfolder, psm, lang, ext, autocontrast, level, padval, padprc, regex, min_len, max_len,...
86082484b630a3e3e52bb4f657bb354612054a91
62,852
def postprocess_metainfo( opts, doxyindex, result ): """finalizes a metainfo by adding some generic fields""" result['base_name'] = result['base'].decl_string.lstrip( '::' ) assert result['base'] and result['type'] and result['category'] result['gcc'] = create_decl( result['base'], doxyindex, opts ) ...
8382e41a6cda86904364b9010e94f3ed9fd2837a
62,854
def int2lehex(value, width): """ Convert an unsigned integer to a little endian ASCII hex string. Args: value (int): value width (int): byte width Returns: string: ASCII hex string """ return value.to_bytes(width, byteorder='little').hex()
1ce9bb9447236c36bb906560c65ffd8e058c5aa4
62,855
def get_df_from_list(audio_files): """ Will return a data frame filled with the features from audio files from the list """ frames = [get_features_from_file(f) for f in audio_files] return pd.concat(frames, ignore_index=True)
e68f80d7f556a746f4232c031d6d917fb30f95bb
62,856
def simple_env(): """Start up a super simple OneVsOne config.""" env = envs.v0.Pomme game_type = constants.GameType.OneVsOne env_entry_point = 'pommerman.envs.v0:Pomme' env_id = 'Simple-v0' env_kwargs = { 'game_type': game_type, 'board_size': constants.BOARD_SIZE_SIMPLE, ...
ddfd7b03a95abb85ca23ddc332dc62aa7968a89f
62,858
def batchnorm_forward(x, gamma, beta, bn_param): """ 使用使用类似动量衰减的运行时平均,计算总体均值与方差 例如: running_mean = momentum * running_mean + (1 - momentum) * sample_mean running_var = momentum * running_var + (1 - momentum) * sample_var Input: - x: 数据(N, D) - gamma: 缩放参数 (D,) - beta: 平移参数 (D,) ...
32d662f5a40f35c8d97d3823d25ca13fc6f5916f
62,859
def nearest_cluster_center(point, cluster_centers): """Distance and index of the closest cluster center""" min_index = point.group min_dist = FLOAT_MAX for i, cc in enumerate(cluster_centers): d = sqr_distance_2D(cc, point) if min_dist > d: min_dist = d min_inde...
ccbebac91402e1bb0d3e5f4a8dd42028f858201b
62,860
from typing import Callable from typing import Tuple import time import warnings def lanczos_algorithm(mvp_fn: Callable[[tf.Tensor], tf.Tensor], dim: int, order: int, random_seed: int = 0, only_gpu: bool = True) -> Tuple[tf.Tensor...
859c395531ff3edf3f2a8495a52eb03c288379b3
62,861
def calculate_active_senders(api, all_messages, top_n=20, template=None): """ Return a top_n long df group of number of messages and average length. """ groupbys = {group: am.groupby("usender") for group, am in all_messages.items()} active_senders = {group: pd.DataFrame(groupby.count()['body'].sort_...
64de84679c26b1b396a8335db65b9d50374ef98c
62,862
def detect() -> tp.List[Device]: """ Calls all detectors and returns a list of available devices. """ devices = [] SmlReader.detect(devices) PlainReader.detect(devices) Bme280Reader.detect(devices) return devices
696813b833c9a28f4a1862de27327f7d6ac66cdc
62,863
from datetime import datetime from typing import Optional def update_datetime( dt: datetime.datetime, date: Optional[datetime.date] = None, time: Optional[datetime.time] = None, date_delta: Optional[datetime.timedelta] = None, time_delta: Optional[datetime.timedelta] = None, ) -> datetime.datetime...
f78e61232e6a886f669c210da0a8e051594acd87
62,864
def load_lr_data(data_path, sep='\t'): """ load data with features :param data_path: :return: """ data_x = [] data_y = [] with open(data_path, encoding='utf-8') as f: for line in f: parts = line.strip().split(sep) if len(parts) < 2: ...
ec10ec910d250b6de17b45a4d3f38b485eca61ad
62,865
def patient_eval_before_2015(patient_eval_date, patient_phen): """Gets an updated dictionary of patient phenotype, with patients before 2015 with no negative \ values (cf paper for explanation of possible bias) Parameters: patient_eval_date (dict): dict with patient as key, evaluation date as value ...
e9f3c9456dac3b178f3746eb7a923148a1b81763
62,867
from typing import List def describeMSCollectionTime(trap_metrics: mzqc.QualityMetric, ms_level: int) -> List[mzqc.QualityMetric]: """ describeMSCollectionTime calculates the descriptive statistics metrics for ion collection times of spectra from a given level. From the proto-metrics on ion collection for ...
08904a388ae7b9f3521dc1ab6bdc1766f9241b3f
62,868
def parse_file(infile, LOGFC_threshold=1.6, FDR_threshold=0.05): """to do""" count = 0 gene_to_logFC = defaultdict(str) f_in = open(infile, "r") for line in f_in: if test_line(line): data = line.split() gene = data[0].strip() logfc = data[3].strip() ...
01f9abe719da8c0db0170bfa949543085a4e35ef
62,869
def post_message_log(body: hug.types.json, response: 'hug.Response') -> hug.types.json: """Creates a new message log from the given data.""" try: log = create_message_log(body, db) except ValidationError: response.status = HTTP_422 else: return {'log_id': log.id}
857f4b4917ee101eae0a333d0754f93d46849f58
62,870
def skewness(data_list): """ Skewness of the data Inputs: data_list - a list of floats Outputs: val - The skewness of the data """ sigma = std(data_list) mu = mean(data_list) n = count(data_list) if n == 0 or sigma == 0: return 'NaN' skew = sum...
c187828fcdf54406dcb8b0117bdeecbbf30e3b5f
62,871
import platform def getAllContexts(): """Returns all available contexts. >>> allContext = getAllContexts() """ contexts = [] for contextType in contextTypes: contexts.append(getPlatformContext(contextType=contextType)) if platform == 'darwin': for contextType in contextTypesO...
d93d5173d9f00628092c38ddda59e8a342084ab6
62,872
def muted_help(ctx): """ Returns help for muted players embed """ embed = Embed(colour=Color.blurple()) embed.add_field(name='You are currently muted!', value='`=escape` See how long you are muted for, give back permissions if no longer muted', inline=False) r...
84fe8f5855f2de9afe3d2140d590865fe8435095
62,873
import socket import struct def ip4_from_int(ip): """Convert :py:class:`int` to IPv4 string :param ip: int representing an IPv4 :type ip: int :return: IP in dot-decimal notation :rtype: str """ return socket.inet_ntoa(struct.pack(">L", ip))
94091bd650cf15bb216e82072478e73180c0027c
62,874
def keras_prepare_labels(model, labels): """ Preformat labels to be processed by the Keras model - mainly handle the case of categorical_crossentropy """ loss = None if hasattr(model, 'loss_functions') and model.loss_functions is not None and len(model.loss_functions) > 0: # As in test mod...
22e6afe1370848c1db9be2f8b803da2b1fee281c
62,875
def nameToClass(name): """Converts a class name to a class. Returns None if not an ee class. Args: name: The class name. Returns: The named class. """ return _registered_classes.get(name)
00688c60ba236e39d9d4d538e154b01cc4c59ca2
62,876
import torch def simulator(param, n=100): """ Simulate a given parameter combination. Parameters ---------- param : vector or 1D array Parameters to simulate (\theta). n : integer Time series length """ m = len(param) g = np.random.normal(0, 1, n) gy = np.rando...
18c330b0890541dca27fdd1f81fd1e9f7b35c14b
62,877
def overlap(start_1, end_1, start_2, end_2): """Return the `range` covered by two sets of coordinates. The coordinates should be supplied inclusive, that is, the end coordinates are included in the region. The `range` returned will be exclusive, in keeping with the correct usage of that type. Para...
0bf76a98feaf94fffa2a13eb74f2a16e4fafe350
62,878
def fill_card(template: Template, row: Row, card_index: int, card_copy_index: int, definitions: dict) -> (str, TemplateRenderData): """ Return the contents of a card using the specified template. """ # attempt to fill all fields discovered in the template...
e8cf14fd24e3f6c4c5909e7c2879df97146b7a65
62,879
import inspect def _get_all_prior_frames(): """ Gets the calling stack formatted as a string seperated by periods, e.g.: __main__.bar.baz """ frame = inspect.currentframe() out = [] #container for output while True: frame = frame.f_back name = _filter_frame(frame) i...
84473e7ab6b26fa5a848936d3aae4eebef7a3191
62,880
import asyncio from typing import Optional def _begin_validation( session: UpdateSession, config: config.Config, loop: asyncio.AbstractEventLoop, downloaded_update_path: str, actions: update_actions.UpdateActionsInterface, ) -> "asyncio.futures.Future[Optional[str]]": """Start the validation p...
0aaca2bd393dd795a19befa608f8214bccd0709f
62,881
def csc_zero_cols(csc, cols_to_zero): """Set rows given by cols_to_zero in a sparse csc matrix to zero. NOTE: Inplace operation! Does not return a copy of sparse matrix.""" rows, cols = csc.shape mask = np.ones((cols,), dtype=np.bool) mask[cols_to_zero] = False nnz_per_row = np.diff(csc.indptr) ...
ff3b9868d26c7b773d7073afa723f29aca00033f
62,882
def tracer_injection(logger, log_method, event_dict): """Inject tracer information into custom structlog log""" correlation_log_context = tracer.get_log_correlation_context() # add ids and configs to structlog event dictionary event_dict["dd"] = correlation_log_context return event_dict
b0f29e1db7c9f8422b9a82f2635f146413079ad9
62,885
def view_public_cluster(name): """ - List Clusters Registered on SLATE """ if request.method == 'GET': # Check if cluster exists if cluster_exists(name): print("Found cluster: {}".format(name)) # cluster_info = get_cluster_info(name) # print("Response ...
8e952c19acf3e897253a01351765e61aade7c724
62,886
def get_best_beam(beam_model, sess, inp, target, batch_size, beam_size, bucket, history, p, test_mode=False): """Run beam_model, score beams, and return the best as target and in input.""" _, output_logits, _, _ = beam_model.step( sess, inp, target, None, beam_size=FLAGS.beam_size) new_tar...
09ffe12279ec06333725832a77a8331c5d7e60d1
62,887
def total_anchors(object_boxes, object_class_name=None, class_name_set=None): """ 对所有待检测目标进行聚类,求出聚类中心,并绘制散点图 :param object_boxes: 所有物体的boxes :param object_class_name: 对应的boxes的物体类别的名称 :param class_name_set: 物体类别名称的集合 :return 聚类中心 """ # 开始聚类 cluster_machine = KMeans(object_boxes, k=5,...
0c1d0e33e7f4bbecd1c196f199e26c10b97ea8a9
62,888
def async_run_job(jsondata, program, env): """ Run job asynchronously. :param jsondata: a dictionary that will be sent as request body. :param program: a dictionary that defined request meta and parameter. :param env: a dictionary that contained environments. :return: AsyncResult, a celery task. ...
346f059deb367070aaed106b72b5acb01070c178
62,890
import torch def count_examples(loader: data.DataLoader): """Count the number of examples in a dataloader.""" count = 0 for batch in loader: unpacked = batch while not torch.is_tensor(unpacked): unpacked = unpacked[0] count += unpacked.size(0) return count
93e8d9e7e3e74e94a5fdc81fbe5666f583802882
62,891
def issubset(a, b): """Determines if a exists in b Args: a: sequence a b: sequence b Returns: bool: True or False """ return set(a).issubset(set(b))
39e3c974cb2f3bc3ecfe17589292646f7a1a3383
62,892
def compare_pdf_file(path1, path2): """ Compare content of 2 pdf files by converting pages to png image files :param path1: path of the pdf file to compare :param path2: path of the pdf file to compare :return: difference of image files """ img1 = Image.open(path1) img2 = Image.open(pat...
b89cedf19d805d4ce1113e3d4543a38239cbd444
62,893
def bot() -> Bot: """ Creates a valid bot instance, with a token from 'TOKEN' environment variable if exists, or the default one from PUBLIC_TEST_BOT_PARAMETERS otherwise. :return: a bot instance """ return Bot(_get_bot_parameter('token'))
a17f5daeeadda5f78107d9dcfa5f6fcaac7d47e9
62,895
def checkins_to_string(count: int, checkins: list): """Takes a list of checkins and returns a string""" # checkin_text = ("**checkin** - **beerID** - **beer (caps)**\n\t**brewery** - **badges** - **when**\n") checkin_text = "" for num, checkin in zip(range(count), checkins): checkin_text += ("{!...
4bde62bd6a6c0b194e306080413ff686d29bd8c5
62,896
def check_from_dict(method): """A wrapper that wrap a parameter checker to the original function.""" @wraps(method) def new_method(self, *args, **kwargs): word_dict, = (list(args) + [None])[:1] if "word_dict" in kwargs: word_dict = kwargs.get("word_dict") if not isinstan...
79158edde23d2e2b8b812d6dd117ab91351b44fd
62,897
from src.bot.common import bot def safe(msg=None): """Call the decorated function and log any exception thrown but do not interrupt the program. """ def deco_safe(f): @wraps(f) def f_safe(*args, **kwargs): try: return f(*args, **kwargs) except Except...
20864f671617ba32677be884f13fb202c1b1fef5
62,898
def _get_eigen_vector(dot_matrix, variance_thresh): """ Get eigen values and eigen vector from matrix which explain % variance_thresh of total variance :param dot_matrix: (np.array): matrix for which eigen values/vectors should be computed :param variance_thresh: (float): % of overall variance whic...
1e98aa9e6c1c1a5716d4c6b3f85a399de73a19f4
62,899
def cache_except_staff(decorator): """ Returns decorated view if user is not staff. Un-decorated otherwise """ def _decorator(view): decorated_view = decorator(view) def _view(request, *args, **kwargs): if request.user.is_staff: # view without @cache ...
83bf8f76e4b09cb651fd3fda9745a94fd65d80d8
62,900
def moments(data): """Returns (height, x, y, width_x, width_y) the gaussian parameters of a 2D distribution by calculating its moments """ total = data.sum() X, Y = np.indices(data.shape) x = (X*data).sum()/total y = (Y*data).sum()/total col = data[:, int(y)] width_x = np.sqrt(np.abs...
3bcce628e8d5548327a787540b9839d2a6ba31a8
62,901
import math def Conv2D(x, filters, kernel_size=(3, 3), strides=(1, 1), padding='same', dilations=(1, 1), use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), trainable=True, name='Conv2D'): """Convolution 2D layer.""" if kernel_initializer is None: kernel_initial...
676a337ad27cf319441bcbd361e5207730a88018
62,903
from datetime import datetime import pytz import json import requests import traceback def rule_pseudo_request(request, rule_type_id): """ [メソッド概要] テストリクエスト実行時のリクエストを処理する """ logger.logic_log('LOSI00001', 'None', request=request) err_flg = 1 msg = '' now = datetime.datetime.now(pytz...
d955e4df3be7344d93f3ccec9c1cb13f462cb6c1
62,904
def sigmoid(z): """ Sigmoid function :param z: input of the sigmoid function :return: sigmoid calculation """ return 1 / (1 + np.exp(-z))
835a2682f80cccefec884730b02adb9989ad4699
62,905
import random def random_noisy_bipartite_graph(n, p, seed): """Generates a base bipartite graph with evently split nodes. Adds a bipatite edge with probability p. Add every edge with probability 1/10. Parameters ---------- n : int Number of nodes p : double Probability of ...
e724a8e6af04a422dea77c9bc80113a00a63d0a6
62,906
def random_explorer_player(bot, state): """ Least visited random player. Will prefer moving to a position it’s never seen before. """ if not bot.turn in state: # initialize bot state[bot.turn] = { 'visited': [] } if bot.position in state[bot.turn]['visited']: state[bot.turn]['visit...
95b05d749b9fa7994ddb0b1e6adae5ef5c3b25ea
62,907
def get_latest(): """Get 3 latest transactions.""" return render_template( 'input.html.j2', today=date.today().strftime('%Y-%m-%d'), suppliers=get_suppliers(), categories=get_categories(), transactions=get_transactions(3, True) )
5801d2d5e9d9a38937a38b66b8ef2153e7cb7a8c
62,908
import json def is_master(): """ Returns true if executed on the AWS EMR master node :return: """ with open('/mnt/var/lib/info/instance.json', 'r') as f: data = f.read() return json.loads(data)['isMaster']
e18cba58143cb3bd0a990324ae6bd6013cf47739
62,909
def f(x,y): """dy/dx = f(x,y) = 3x^2y""" Y = 3.*x**2. * y return Y
4e18d6411be1c1445ea1aa4d9836b8bf5e26e3d6
62,910
import warnings def encoder(encoder_type='Default', input_tensor=None, encoder_weights=None, encoder_freeze=False, num_blocks=5, encoder_filters=[32, 64, 128, 256, 512]): """ Instantiates the encoder architecture for the DoubleU-Net segmentation mode...
855fdf6edfb4b779cdb8b66d4e091519580752e2
62,911
def products_delete(id): """Exclui item selecionado""" #Valida acesso if int(session.get('user_role')) == 2: flash("Acesso não permitido") return redirect(url_for("index")) message = "Cadastro excluído com successo." if Activity.query.filter_by(id_product=id).count() > 0: ...
aedc4616acb3808469b3c5390cc4c48962419321
62,912
def central_moment(dist, n): """ Computes the `n`th central moment of a distribution. Parameters ---------- dist : Distribution The distribution to take the moment of. n : int Which moment to take. Returns ------- moments : ndarray The `n`th central moment o...
85cae07cd61662f33b4f85babad4ecc7eb666e19
62,914
def get_face_points(gray_frame, face): """ """ land_mark = predictor(gray_frame, face) face_points = [] for n in range(68): x, y = land_mark.part(n).x, land_mark.part(n).y face_points.append([x,y]) return face_points
3bc2d47ea9c89362decfd1855b4db95afbc35c8e
62,915
def anim_classic_walk(transition, projection, start_pd, n_steps=10, show_equil=False, frame_option='pairsmean'): """ calculate the evolution of random walk and prepare dataframe df of the evolutionvof probability distribution the probability distribution at start is given as input start_pd. i in ea...
17358b078e04e324db59b1f144efc811a1f2e704
62,916
import logging import base64 import hashlib def check_password(ssha_ldap_salted_password, password) -> bool: """Check the OpenLDAP tagged digest against the given password.""" # See https://www.openldap.org/doc/admin24/security.html#SSHA%20password%20storage%20scheme # We should (also) support SHA512 as S...
003972ff32df6a6b55ada07b512154ee7b99d957
62,918
def input_fn(request_body, request_content_type): """ The SageMaker XGBoost model server receives the request data body and the content type, and invokes the `input_fn`. Return a DMatrix (an object that can be passed to predict_fn). """ if request_content_type == "text/libsvm": return xg...
b408fc27ba3291da236848f6d81514863bb4e8d7
62,919
import re def generate_c_header_finders(): """ Generate the header finders for c style files. """ def find_header_start(line): match = re.search("/\*\*", line) if match: return True else: return False def find_header_end(line): match = re.search...
fa094e7be0e3b9b89b8fdc3f32d729f024f62c7e
62,920
import copy def pred_twostage(ReasonerObj, args): """Based on gt labels in original implementation by Zeng et al.: https://github.com/andyzeng/arc-robot-vision/image-matching/evaluateTwoStage.m" but here no novel vs known prediction are made, simply both K-net and N-net preds are returned """ ...
e3bae64db3e100d8e85de166c047ca7c41461cef
62,922
def hxlm_factum_to_object(factum) -> dict: """Factum to an object""" # return dict(factum) # this does not transpile well... return factum
54cba326d6874768f2893f97277a691e7e77a2d7
62,923
def parse_example(example_proto): """Parse a serialized SequenceExample read from a TFRecord. Args: example_proto: str, a single binary serialized SequenceExample proto. Returns: length: 1-D Tensor of length 1 label: 1-D Tensor of length 1 words: 1-D Tensor of variable length...
55b6af7f58fd3151faff79e7833decaddc6de96e
62,924
from typing import Tuple def _compute_chroma(rgb: np.ndarray, axis: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Compute the chroma for an RGB triple""" big_m = np.max(rgb, axis=axis, keepdims=True) little_m = np.min(rgb, axis=axis, keepdims=True) chroma = big_m - little_m...
0b8d185c8bf969dfdf489e2c56e1fd5c0f2bb2fa
62,925
def pareto(costs: np.ndarray): """ Find the pareto-optimal points :param costs: (n_points, m_cost_values) array :return: (n_points, 1) indicator if point is on pareto front or not. """ assert type(costs) == np.ndarray assert costs.ndim == 2 # first assume all points are pareto optimal ...
9062696d4ce69115aa745a7affae24a578d05f74
62,926
def pop(obj, key=0, *args, **kwargs): """Pop an element from a mutable collection. Parameters ---------- obj : dict or list Collection key : str or int Key or index default : optional Default value. Raise error if not provided. Returns ------- elem P...
71222b35f52a1ee118a352596caefebe9b7070fa
62,928
def _ValidateAgentVersion(agent_type, version): """Validates agent version format. This validation happens after the arg parsing stage. At this point, we can assume that the field is a valid string. Args: agent_type: str. The type of agent to be installed. Allowed values: * "logging" * "metric...
d8cf8f8584d2d8b8c4e3ce8aa07ba9c0ae4a75fd
62,929
def calculate_bridge_score(bid : Bid, tricks : int, vul : bool,joueur : str) -> FinalContract : """Knowing the contract and the number or tricks, return the bridge score (absolute negative = EW scores)""" PRIME_PARTIELLE = 50 PRIME_MANCHE = 300 PRIME_PETIT_CHELEM = 500 PRIME_GRAND_CHELEM = 1000 ...
dd231dfd749fefaa29ffdda8e1c31b9f1d739f5b
62,931
def validate_notebook_defaults(value): """Returns the parameter, if it's a dict, otherwise raises an exception. :param value: Object to validate. :raises TypeError: On wrong type. """ if isinstance(value, dict): return value raise TypeError(validation_error_message( ...
bcef39d7e7c7986d3baa6e85e55c2d18ce36c4e7
62,932
from typing import List def classify_from_patchlist(patchlist: List, pyparams: dict, modeldef_path: str, modelweighs_path: str, scorelayer: str = 'score', startlayer: str = 'conv...
180386632f9972db2ec920d3a1dd76f5c1345631
62,934
def route_index(): """Display an overview of the exporters capabilities.""" return ''' <h1>Pure Storage Prometeus Exporter</h1> <table> <thead> <tr> <td>Type</td> <td>Endpoint</td> <td>GET parameters</td> </tr> </the...
a0d0d505a73f2239f1b0fe30358d52d0dd5be5fe
62,935
def create_model(params, training, custom_pos_enc=False, attn_weights=False): """ Args: params: dict, hyperparameter dictionary training: bool, whether model is called in training mode or not custom_pos_enc, bool, whether a custom positional encoding is provided as additional input ...
8d58c4e24f1fe38af09c408a847121f7a04d52a6
62,936
import itertools def calc_feature_values(db_file, identifiers, feature, window=0): """ Calculate the given feature for a list of identifiers. Args: db_file: The sqlite3 DB file. identifiers: List of identifiers. feature: Feature as class instance. window: Window size. ...
af96f1ebcb71d5cefd25ace7c8251ad1c0f6d944
62,937
def new_ipc_message(draft=None): """Basic ipc message we can send to the bots Parameters ---------- draft: Optional[int] 0, or 1, 0 to disable ML drafting and fallback to hardcoded hero selection. """ base = { 'uid': 0, TEAM_RADIANT: { 0: dict(), ...
b0ff0dfdd9d4c45d618a0f5748538b8b5bb340f5
62,938
def parse_rp_inventory_defaults(inventory_defaults): """Parse and validate config option: parse_rp_inventory_defaults. Cast the dict values to the proper numerical types. Input in the config: resource_provider_inventory_defaults = allocation_ratio:1.0,min_unit:1 Input here: { ...
e09dc1aa8f02de3046a4348cda25b3b8cdcfd8de
62,939
def get_compiler(compiler, **compiler_attrs): """get and customize a compiler""" if compiler is None or isinstance(compiler, str): cc = ccompiler.new_compiler(compiler=compiler) # customize_compiler(cc) if cc.compiler_type == 'mingw32': customize_mingw(cc) else: c...
61815a3bccb9b8d98e3b748c59a3249629d3974a
62,940
def read_ascii(file): """ Function to read in photometric data from original '_phot.dat' style sedbys file. - file is a pathlib.Path object """ wvlen, band, mag, emag, fmag, unit, beam, odate, ref = [],[],[],[],[],[],[],[],[] with open(file, 'r') as f_in: for line in f_in: ...
1baee61f90321a6006bcd58e5e5de4ff08e96b26
62,941
import sqlite3 def get_test_database() -> sqlite3.Connection: """get_test_database for unit testing the model classes""" db_conn = sqlite3.connect( ":memory:", detect_types=sqlite3.PARSE_DECLTYPES ) with open("ticket/schema.sql") as schema_file: db_conn.executescript(s...
aeff27686a7fc4efd66597a5e2264056de9cee8a
62,942
import re def normalize_text(text): """ Strips formating spaces/tabs, carriage returns and trailing whitespace. """ text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\r", "", text) # Remove whitespace in the middle of text. text = re.sub(r"[ \t]+\n", "\n", text) # Remove whitespace ...
aec04cc84aa91e16ca0f8ac18530813a6de3c187
62,943
def convert_tractor_e1e2(e1, e2): """Convert Tractor epsilon1, epsilon2 values to ellipticity and position angle. Taken from tractor.ellipses.EllipseE """ e = np.hypot(e1, e2) ba = (1 - e) / (1 + e) #e = (ba + 1) / (ba - 1) phi = -np.rad2deg(np.arctan2(e2, e1) / 2) #angle = np.deg2rad...
56cd5c4e6705165f263fbed385c03694b41c1c99
62,944
def app_plan(service, custom_app_plan, request): """ Creates an app plan with a limit on hits """ metric = service.metrics.list()[0] plan = custom_app_plan( rawobj.ApplicationPlan(blame(request, "app")), service) plan.limits(metric).create({ "metric_id": metric["id"], "period": ...
bc8cad2f682bb0ec47ba65cf2cfb4f3e279cb7c2
62,945
from typing import Sequence from typing import Callable from typing import Union def predmix_upper_cs( x: Sequence[float], v: Sequence[float], lambdas_fn: Callable[[Sequence[float]], Sequence[float]], psi_fn: Callable[[Sequence[float]], Sequence[float]], alpha: float = 0.05, running_intersecti...
1a3559ef109640fcf4bf9a2b5de9afb6e8e0fd41
62,946
def image_to_rgb(img): """ Convert *img* (an :class:`~PIL.Image.Image`) to an :class:`~numpy.ndarray` in RGB format (structured floating-point type with 3 values each between 0 and 1). """ return rgb888_to_rgb(image_to_rgb888(img))
d8c87a3733145e061b18c3333e9ca64767174d19
62,947
import copy import numpy def sbs_with_forward_steps( training_table, validation_table, testing_table, feature_names, target_name, estimator_object, cost_function=_cross_entropy_function, num_forward_steps=DEFAULT_NUM_FORWARD_STEPS_FOR_SBS, num_backward_steps=DEFAULT_NUM_BACKWARD_STEPS_...
dbee37b87c61bf078217e64e73755a3057af3cbd
62,948