content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Optional def does_table_exist(database: str, table: str, boto3_session: Optional[boto3.Session] = None): """Check if the table exists. Parameters ---------- database : str Database name. table : str Table name. boto3_session : boto3.Session(), optional ...
efa45b5d7ffbf6281046deb6f838e2188a06a194
62,600
import math def cluster_assortativity( sparkdf, src="src", dst="dst", cluster_id_colname="cluster_id" ): """calculate assortativity of a cluster Args: sparkdf: imput edgelist Spark DataFrame src: src column name dst: dst column name cluster_id_colname: ...
edfc9944c800547d340893b6f1aad5ea5710f816
62,601
def repository_branch_url(namespace, repository, branch_name): """ URL for retrieiving a specific branch under a repository. """ return _BASE_URL_V2 % ('repositories/%s/%s/refs/branches/%s' % (namespace, repository, branch_name))
d6b0259e94664f27ff7457fdae8a7249c082ee03
62,602
from inspect import currentframe, getframeinfo def embed_kw(verbosity=2, **kwargs): """ Prepares header for IPython prompt showing current location in code Use ``IPython.embed(**embed_kw())``. Args: verbosity (int): Level of verbose output **kwargs: Additional keyword arguments ...
acff081bc5bd3705e66d3b6754566691c75a91e2
62,603
def add_2_numbers(a, b): """ Assume your function returns the addition of 2 numbers """ return a + b
fbc3a89fb16334594914ce9cdd388d240effc7ea
62,604
import collections def defer(func, *args, **kwargs): """Invoke the given function that may or not may be a Deferred. If the return object of the function call is a Deferred return, it. Otherwise wrap it into a Deferred. >>> defer(lambda x: x, 10) #doctest: +ELLIPSIS <defer.Deferr...
4c310bc915976991834dec240459df05f338f090
62,605
from typing import List from pathlib import Path def filter_paths_to_existing(*iterables: str) -> List[str]: """ Filter paths to only existing. """ return [path for path in iterables if Path(path).exists()]
32326b3578b754c361d11c24690709dd5d114e46
62,606
import warnings def anomaly_tuning(X, base_estimator=AverageKLPE, parameters={'k': np.array([10])}, cv=None, n_sim=10000, alphas=np.arange(0.05, 1., 0.05), random_state=42, n_jobs=1, ...
a68557fe739cd06d4e0beedf73a2dfb8e34d1644
62,607
def map_pyon_exceptions(f): """Decorator that maps some Pyon exceptions to dashi """ def wrapped(*args, **kwargs): try: return f(*args, **kwargs) except IonException, e: dashi_exc = _PYON_DASHI_EXC_MAP.get(type(e)) if dashi_exc is not None: ...
9ff32cd5963a30a4605dfced252bdc313428eec3
62,608
import time import random def _generate_secret(): """ create a pseudo-random secret This is used for message authentication. """ digest = sha(str(time())) digest.update(str(random())) digest.update('lorem foo ipsum') return digest.hexdigest()
8cadb73a2f8529aa9a68341e24fa77c5d4bd9195
62,609
def show_lat_lon_gps( move_data, kind="scatter", figsize=(21, 9), plot_start_and_end=True, return_fig=True, save_fig=False, name="show_gps_points.png", ): """ Generate a visualization with points [lat, lon] of dataset. Parameters ---------- move_data : pymove.core.MoveDa...
ebd8795168a4d22bd7482973fab5229691e9144b
62,610
def dda_extended(hands, n_players: int, hand_owner=-1, times=1): """ Run alpha-beta search algorithm on multiple games. All games are analysed using the same hands, while each game has a different declarer-trump combination. :param hands: :param n_players: number of players. :param hand_owner: i...
f483c643a19e82ed9a2e36f864d8a943103ea189
62,611
def check_board(user_piece, board_state): """Check if the game is over and return the result if so""" # List containing all possible winning combinations possible_wins = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]] # Iterate through ...
e5bc6543598b8076ce3cb67b5c1ff4929d0a24d0
62,612
async def add_jira_action( request_data: JiraActionRequest, current_user: User = Security(Authentication.get_current_user_and_bot, scopes=DESIGNER_ACCESS) ): """ Stores Jira action config. """ mongo_processor.add_jira_action(request_data.dict(), current_user.get_bot(), current_user.get_u...
a841d436d72e12f1cecd68ec2dd83737a3124a60
62,613
def on_right(p1, p2, p3): """ Returns ------- out : Bool Return true if the point p3 is on the right of the line defined by the points p1 and p3. """ return ccw_angle(p1, p2, p3) > 0
135e08def2073ec8792517e2667a15e7282a7bc1
62,614
from . import persist import os import subprocess def popen(cmd, stdout=None, stderr=None, output_stream=STREAM_BOTH, env=None, extra_env=None): """Open a pipe to an external process and return a Popen object.""" info = None if os.name == 'nt': info = subprocess.STARTUPINFO() info.dwFlag...
66eb50e41433a23767afc91e79ec7f4572cead24
62,615
from typing import Union from typing import Sequence def compute_invoke_hash( contract_address: int, entry_point_selector: Union[int, str], calldata: Sequence[int], chain_id: StarknetChainId, ) -> int: """ Computes invocation hash. :param contract_address: int :param entry_point_selec...
de56d6b08a78d9cafa6ee66a41d3c076f6fb6a65
62,616
def determine_img_center(img, center_left=True, center_up=True, center=100): """ Determines the center of an image. Args: img: An opencv instance of an image. center_left: A boolean to determine whether the you should push the center width to the left or push it to the right. I...
9c567a0b398d106089858553b502477b3195d7e4
62,617
def numba_update_requestable(requestable, r_ct, c_ct, c_f, c_cf, c_dt): """ calculates: requestable *= (1 - request) """ for a, b, c, d, e in zip(r_ct, c_ct, c_f, c_cf, c_dt): requestable[a, b, c, d, e] = 0 return requestable
d1cf9c3a8c07fdfb4cab4d12733d1900e31ffd6a
62,618
def port_bind(endpoint_id, port, subnets, network=None, vm_port=None, segmentation_id=None, driver=None, **kwargs): """Binds the Neutron port to the network interface on the host. :param endpoint_id: the ID of the endpoint as string :param port: the container Neutron port dictionary...
084577ebae258414f91b0666c39aa6305a1cc8d3
62,619
def linearize_spectra(spectra: np.ndarray, x_klinear): """ This method interpolate the input spectra with the input list. Args: :param spectra: OCT spectra of mirror. :type spectra1: list :name x_klinear: The fractional indexes. :type x_klinear: list Return: :rname...
4976a4fbb0bfa011d821c75b1b77b6435201bb82
62,620
def apply_gradient_descent_run(shape, dtype, attrs=None): """run function for dsl function apply_gradient_descent.""" shapes = [shape, (1,), shape] dtypes = [dtype] * len(shapes) mod = utils.op_build_test(apply_gradient_descent, shapes, dtypes, kernel_name='apply_gradient_...
80e09fbe5b80e72b017ef130f249da44e56f3741
62,621
def compute_bid(task, fog_node, phi_CPU=1.0, phi_RAM=1.0, phi_DISK=1.0): """Calculate the bid for the current node for the current task. Args: :param task (dataframe): A dataframe containing information about the current task. :param fog_node (series): A series containing information about the ...
5e4560454fd709d3e63a3c165da84ee71dd13a49
62,622
def customer_group(request): """团队客户,可筛选""" up_name = request.session.get('user_id') users = User.objects.filter(up_name=up_name) if 'name' in request.GET and request.GET['name']: name = request.GET['name'] customers = Customer.objects.filter(name__icontains=name, user__up_name=up_name)....
aa100bc2121906bed09ebd72fc2c1730f97b7ebf
62,623
from typing import Dict from typing import Any from pathlib import Path import json def create_model_folder(model_config: Dict[str, Any]) -> None: """Create model asset folder and write config if it doesn't exist.""" model_path = get_model_path(model_config) if model_path.exists(): return None ...
87c9f91328788a87e5d0b5e17304040aaef4645c
62,624
from typing import Union from typing import List import torch def separate_parameters(module: Union[Parameter, nn.Module, List[nn.Module]]): """Separate BatchNorm2d, GroupNorm, and LayerNorm paremeters from others Args: module (Union[Parameter, nn.Module, List[nn.Module]]): to be separated. Retu...
7428dbc0e05fee868ae15ec84d13352e18c3d96f
62,625
import random def getCategories(l0keyP="", testTypeP=0): """ Depending on the provided testType, this function finds random child keys, which we use to generate Twitter hashtags. For our evaluation we mainly used testType 2 or 3. Returns: List -- List of two lists. First, the provided or random l...
d41ebf94d5a87980e2a50dc5db39033f6aa3b7ec
62,626
from typing import Optional def frame( *, scene_name: Optional[str] = None, frame_name: str, # pylint: disable=redefined-outer-name frame_data: Json, intrinsics: sunds.specs_utils.CameraIntrinsics, color_image: Optional[np.ndarray] = None, ) -> sunds.specs_utils.Frame: """Extract the frame ...
b3739fc68c46a9b587545f5a594556b3a9bc19fb
62,627
def add_grad(orig, grad): """Returns [grad, grad]""" return [collapse_sum_like(grad, orig.args[0]), collapse_sum_like(grad, orig.args[1])]
9cc1450c6867735e5833b251b0c93396a5bb098a
62,628
def CustomFancyAnalyzer(expression=r"\s+", stoplist=STOP_WORDS, minsize=2, maxsize=None, gaps=True, splitwords=False, splitnums=False, mergewords=False, mergenums=False): """Composes a RegexTokenizer with an IntraWordFilter, LowercaseFilter, and StopFilter. >>> ana = Fan...
b02e61a53670e3e3dfb30d8209a1a637327bf950
62,629
from typing import Callable def get_piecewise_rollout(start_time: float, end_times: list, vaccination_rates: list) -> Callable: """ Turn the vaccination rates and end times into a piecewise roll-out function. """ def get_vaccination_rate(time, computed_values): if time > start_time: ...
fcea805aa563efe7cd6b2dd5b38b30d039cd7027
62,630
def generate_ballot_style_contests(manifest: Manifest, ballot_style_id: str) -> dict: """ Generate the dict structure for the relevant contests for a given ballot style. Args: manifest: election manifest ballot_style_id: ballot style to reference from the manifest Returns: Dict ...
e523fd8b5fc463ef10647399eef4ae335e4ea3e2
62,631
def analysis_kindex(analysis): """ Returns a dictionary of keywords by (namespace, name). 'kindex' stands for 'keyword index'. """ return analysis.get("kindex", {})
7f8c48cf0b2acdd28466827cea9ca512e30479d8
62,632
def format_percent( number, format=None, locale=LC_NUMERIC, decimal_quantization=True): """Return formatted percent value for a specific locale. >>> format_percent(0.34, locale='en_US') u'34%' >>> format_percent(25.1234, locale='en_US') u'2,512%' >>> format_percent(25.1234, locale='sv_S...
05ff3e9bcb1b3babe53cc061a767841e432e0348
62,633
import threading def _start_kill_thread(process: WrappedPopen, kill_children: bool, timeout: int) -> threading.Timer: """Starts a thread to start killing |process| if it doesn't die before |timeout| seconds have elapsed.""" # TODO(metzman): Figure out if we should kill descendant pr...
4af7936d7fbaa24b7fd9b459d4d1a31a21063eb0
62,634
def inputs(dataset, is_training=False, num_epochs=None): """Reads input data num_epochs times. Args: dataset: num_epochs: Number of times to read the input data, or 0/None to train forever. Returns: A tuple (images, labels), where: * images is a float tensor with shape [batch_size, mnist.IMAGE_PI...
d126b6db2dcb03574764893bda4a4bb5df2736ea
62,635
import pathlib import os import re def get_long_description() -> str: """Converts relative repository links to absolute URLs if GITHUB_REPOSITORY and GITHUB_SHA environment variables exist. If not, it returns the raw content in README.md. """ raw_readme = pathlib.Path("README.md").read_text() ...
261b653af247ee9ca5f44c4c2e76ca5efb4b11bd
62,636
from typing import Tuple import argparse import json def get_args() -> Tuple[dict, str]: """ get_args. Return: Tuple[dict,str]: Args and name of file used """ parser = argparse.ArgumentParser() parser.add_argument("config_file", help="Name of configuration file") args = parser.pars...
212ff3016a35e91c5ed4571090322b7b3606f880
62,637
import numpy as np def aspect_sentiment_accuracy(true_aspects,aspect_preds,true_sentiment,sentiment_preds): """ Compute the micro and macro accuracy for the aspect sentiment predictions """ #Ensure all the inputted values contain lists and not strings true_aspects = true_aspects.app...
c7bda4660befa0b6d9d0b741a84f520cf278d66a
62,638
def table_exists(): """ Helper: Checks for table. """ print("Checking for table 'journalEntries' in database...") if engine.dialect.has_table(engine, "journal"): return True else: return False
0cba98cadf192787a91b0eee37fe40a506b6349e
62,639
import string import random import time def get_random_string(length: int = 30, allowed_chars: str = string.ascii_letters + string.digits) -> str: """ Heavily inspired by Plone/Django Returns a securely generated random string. >>> get_random_string(length=10) :param length: :param allowed_c...
cd7ef6fa8073b1df7a3c0235597d5c89f4192446
62,640
def unwrapped_data_ids_list(args): """ Transform all found data ID objects to their underlying value in an iterable object. Parameters ---------- args : iterable Sequence of data. Returns ------- list Transformed list with underlying ``DataID`` values. """ if ar...
dbf0dfa2bb1f068b150bb0ac4739242fee6618e5
62,641
import time import subprocess import sys def runlouvain(filename, level_to_return=-1, tol=1e-3, max_clusters=-1, contin_runs=50, max_runs=500, time_limit=2000, seed=1234): """ From binary graph file filename.bin, optimize modularity by running multiple random ...
9d57cc7976092530a949b11fcf1d126390a22d68
62,642
def mean_change(x): """ Returns the mean over the absolute differences between subsequent time series values which is .. math:: \\frac{1}{n} \\sum_{i=1,\ldots, n-1} x_{i+1} - x_{i} :param x: the time series to calculate the feature of :type x: pandas.Series :return: the value of this...
dffc27bec10b551e7a2f05926d0f8f2fd7399afe
62,643
from pymemcache.client.base import Client as pymemcache_Client from ast import literal_eval from sys import version_info import codecs def get_memcache_metric_object(current_skyline_app, base_name): """ Return the metrics_db_object from memcache if it exists. """ try: pymemcache_Client ex...
818d66ad731d305c69c0b5b15613795d27d0ae38
62,644
def spectral_whitening(tr, smooth=None, filter=None, waterlevel=1e-8, corners=2, zerophase=True): """ Apply spectral whitening to data Data is divided by its smoothed (Default: None) amplitude spectrum. :param tr: trace to manipulate :param smooth: length of smoothing window...
9fcdc74e3ac4e82f2764489084caa7f4f4432960
62,645
from pathlib import Path def good_maps(ref_map): """Creates a ref map with only good satellites""" pointings = ["0", "2", "4"] # load data from map .npz file f = Path(f"{map_dir}/{ref_map}") tile_data = np.load(f, allow_pickle=True) tile_data = {key: tile_data[key].item() for key in tile_dat...
2050a0aadea6cb83036e0c8d7314083882451e36
62,646
def _load_variable(metadata, var_name): """ Load data for the variable listed in metadata of the diagnostic variable. Argument: -------- metadata - nested dictionary of metadata Return: ------ iris cube of the data """ candidates = select_metadata(metadata, short_name=v...
107d160bc3a9571f0f446a5506eb644ec990277d
62,647
import logging def remap_root_mounts(root): """Read /proc/mounts and remap path to server path. Eg. /nfs/dataden/export --> /gpfs/locker0/ces/g/dataden/export """ with open("/proc/mounts", "r") as mounts: split_mounts = [s.split() for s in mounts.read().splitlines()] # compare root to mo...
84fdba44fd7a8b2ae0afe0a2fdd4973140546b58
62,648
def use_case_3(): """Processes results from the <Gather> prompt in /voice""" global n global data global bot_resp global q_repeat global conv_6_1 global conv_6_2 global texts global recheck_repeat global payable # To check whether 'no' is replied twice global repeat ...
719a099e85f71d5808ab402f45621c81eafc880a
62,649
import os def dfu(test_dir, get_fn_log_uWSGI_requests): """ get_dfu_DataFrame_uWSGI_requests_log """ log_uwsgi_requests = os.path.join(test_dir, get_fn_log_uWSGI_requests) with open(log_uwsgi_requests) as fh: pid_l, request_per_pid_l, request_total_l, response_time_l, html_response_code_l,...
2f51ee294b8cfc19389fe882d60cde900ae5f29d
62,650
def analysemathmsg(msg):# """this function analyses the message sennd by the user and calls the function that extracts the actual values of the message""" if msg[0] == "help" or msg[0] == "info": return MATHBOTINFOEMBED classes = [] for index, m in enumerate(msg): if index % 2 == ...
f9afb7f44cf82a42f1bad97b3043976185aa5cd3
62,651
from typing import Union from datetime import datetime import time def is_aware(value: Union[datetime, time]) -> bool: """ Determine if a given datetime.datetime is aware. The concept is defined in Python's docs: https://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo...
e808139c1c21f4b422022639e3a78f259e27e042
62,652
def local_client(start_connected=True): """Create a mqtt client connected to the local broker This method is a *coroutine* """ return LocalClient(start_connected)
f97b82e1139087cb4bdfcc35c1a9dbf52bc6489c
62,653
import copy def calculate_sectional_lewis(B_s:np.ndarray, T_s:np.ndarray, S_s:np.ndarray): """ Lewis form approximation' is obtained. Given the section's area, S_s, b B and draught T, the constants a, a a_3 are uniquely defined by von Kerczek and Tuck18 as: Parameters ---------- B_s : arr...
a784b31339c500b447b065ea61bca80d9c4090f6
62,654
def win32com_is_installed(): """returns True if win32com is installed""" try: return True except ImportError: return False
9b29a8f97a560d48d7a7e24f8f86770ded3c7792
62,655
import struct def is_float_broken(): """ Older versions of Python (<=2.5) and the Windows platform are renowned for mixing up 'special' floats. This function determines whether this is the case. @since: 0.4 @rtype: C{bool} @return: Boolean indicating whether floats are broken on this plat...
d29f5b1d1467c17b33f7074a6e10cef8708b8d9c
62,656
def _proxg_SNN(X, Mu): """ """ # SVD decomposition m, n, B = X.shape U, s, Vh = np.linalg.svd(X.reshape(m*n, B).T, full_matrices=False) # Soft-thresholding the singular values. s_bar = _soft_thresholding(s, Mu) # Prox output prox = U @ np.diag(s_bar) @ Vh return prox.T.reshap...
5b59166b988fd7b56f621d97ad52a96cf93d2699
62,657
def equilibrate_temperature_mpi(sim_dir, pos, cell_dim, param, comm, size=1, rank=0, inc=0.1, thresh=5E-2): """ equilibrate_temperature(pos, vel, cell_dim, bond_matrix, vdw_matrix, param, thresh=2E-2) Equilibrate temperature of system Parameters ---------- pos: array_like (float); shape=(n_bead, n_dim) Upd...
3ce8a1044b6a356be0a607c5e5e5fdadc1d4f847
62,658
def get_distance(point1, point2, metric="euclidean", testing=None): """ Returns ditance between point1 and point2 based on dist type that is passed from the dist parameter Parameters ---------- point1 : list Values defining a single observation to compute distances for. poi...
bc663757c3d3077e61ff4651b72da9d6bd699b6d
62,659
def import_nd(path): """ Import Kea 1d, 2d, 3d, 4d files Args: path (str): Path to file Returns: tuple: x (None, numpy.array): Axes if included in binary file, None otherwise data (numpy.array): Numpy array of data """ ascii_header_size = 12 ascii_h...
02f79d057eb94d905d188c73c3bbadb406af8d8d
62,660
import yaml def create_cli_parser( file: PathLike, frontend: Frontend = Frontend.ARGPARSE, **kwargs ) -> clis.AbstractCLIParser: """ Create and return a CLI parser. :param file: The file declaring the CLI. :param frontend: The frontend to use for parsing the CLI args. :param k...
423967cac621b9504e3424eefd5d0d5d2778f0b4
62,661
def _get_entity_name(entity_dictionary): """ Extract the entity name from the specified entity dictionary if it can be found. The entity dictionary must contain at least 'type' :param entity_dictionary: An entity dictionary to extract the name from :returns: The name of the ent...
d6a926400c80a3517309f26a5d0e1c903a5f8110
62,662
def shift_f(f, tau): """ shifts a curve f by tau :param f: numpy ndarray of shape (2,M) of M samples :param tau: scalar :rtype: numpy ndarray :return fn: shifted curve """ n, T = f.shape fn = zeros((n, T)) fn[:, 0:(T - 1)] = roll(f[:, 0:(T - 1)], tau, axis=1) fn[:, T - 1] ...
63dc7aed0c2f782dcbafa509d95635826b944fe6
62,663
def dst_main_directory(library: str) -> str: """ Main directory for report files resulting from the reconciliation process. """ return f"./files/{library}"
cea4ea7bcd2c37fd97302cb02185ac2090413a4d
62,664
def wing_weight_gradient(samples): """ Gradient of weight of a light aircraft wing Parameters ---------- samples : np.ndarray (nsamples, nvars) The samples at which the gradient is requested Returns ------- grads : np.ndarray (nsamples, nvars) """ S_w, W_fw, A, Lamda, q...
66a61630fd658d396c2c1e8f4bdffdc653fe277f
62,665
def amsoftmax_angular_triplet_loss(features, labels, margin, triplet_type): """Compute the triplet loss (using amsoftmax loss). Args: features: The input embeddings. labels: The input labels. margin: The margin. triplet_type: all or hard :return: The triplet loss """ ...
bb065576a33f736d5e7cf78ab73f39dd67157ecd
62,666
def aggregate_to_dataset(fields, grid_params, cf_attrs, analysis_time, *subgrid_data_and_weights): """Aggregate results from individual radar subgrids onto main grid.""" grid_shape = (grid_params['nz'], grid_params['ny'], grid_params['nx'], len(fields)) grid_sum = np.zeros(grid_shape, dtype='float32') g...
c62b5b403e815e51b6bfdb5a0deb5486856781c6
62,667
from typing import Tuple def get_dataframes(fname: str) -> Tuple[pd.DataFrame, pd.DataFrame]: """Takes the path to a FIT file (as a string) and returns two Pandas DataFrames: one containing data about the laps, and one containing data about the individual points. """ record_data = [] lap_data...
14cf1f66c867c36252832c2071a1718297c1a1e4
62,668
def normalize(*args): """" takes 1 or multiple lists of n coordinates and returns it normalized (getting rid of negatives) """ dtype = type(args[0][0]) # support list(s) of lists and list(s) of tuples if len(args)==1: # only 1 argument passed dim = dimensions(args[0]) obj = args[0] ...
e5430e6ffcbeb9ee9dc7f737516b2301d9fe5ca5
62,669
def swap_values(d: Map[K, V], key1: K, key2: K) -> Map[K, V]: """ Swap values for given keys creating new mapping. >>> swap_values({'k1': 1, 'k2': 2}, 'k1', 'k2') {'k1': 2, 'k2': 1} Original mapping is returned if at least one key does not exist in `d`. >>> swap_values({'k1': 1}, 'k1', 'k2') ...
a3237b298da9aa4f9b5203c15dc3bf51752f3548
62,670
def event(timing=True): """ Create a CUDA event. Timing data is only recorded by the event if it is created with ``timing=True``. """ evt = current_context().create_event(timing=timing) return evt
064af6c9e2968098c7031375250b852bef50f2c2
62,671
from coverage import coverage from coverage.html import HtmlReporter import time import sys import signal import multiprocessing import shutil import os def run_iptestall(options): """Run the entire IPython test suite by calling nose and trial. This function constructs :class:`IPTester` instances for all IPy...
8fb1805428474433bf837e5120a229ad8ff99fc4
62,672
from .dataset import SingleSentenceDataset from .dataset import PairedSentenceDataset from .dataset import Dataset def create_dataset(config): """Create dataset according to :attr:`config['model']` and :attr:`config['MODEL_TYPE']`. Args: config (Config): An instance object of Config, used to record p...
71107bba50c47a9c0520f1865d1a9d2180f5e375
62,673
import array def gridFromList(lists: list): """ gridFromList coputes a grid of all combinations of values provided in lists. Parameters ---------- lists : list of lists, each containing elements per dimension Returns ------- grid : list o...
5e711ffe29535cad28445e5e9e1c126d37cde1e8
62,674
def preference_GP_gradient(f, data, labels, GP_prior_cov_inv, preference_noise): """ Evaluate the gradient of the optimization objective function for finding the posterior mean of the GP preference model (at a given point). Inputs: 1) f: the "point" at which to evaluate the gradient. This ...
c9205a6982cb42d49f3595e0f36e014d2b61e474
62,675
import csv def read_csv_as_nested_dict(filename, keyfield, separator, quote): """ Inputs: filename - Name of CSV file keyfield - Field to use as key for rows separator - Character that separates fields quote - Character used to optionally quote fields Output: Returns a...
b3a16bf52c783b5b40cab35242fde41be16c6e40
62,676
def object_id_parser(*args, **kwargs): """Object (resource in storage) ID parser """ return resource_authz.resource_id_parser(*args, **kwargs)
aee215cd31f1119192f68b157ec781f6f9cb4f81
62,677
def is_urls_module_valid_constant(node): """Suppress warnings for valid constants in urls module.""" if node.name not in ('urlpatterns', 'app_name'): return False parent = node.parent while not isinstance(parent, Module): parent = parent.parent if not parent.name.endswith('urls'): ...
866410bbce40298457a4c702b560f8f20dff47f9
62,678
def make_cluster(mcluster, massfunc='kroupa', verbose=False, silent=False, tolerance=0.0, stop_criterion='nearest', mmax=120, mmin=None): """ Sample from an IMF to make a cluster. Returns the masses of all stars in the cluster massfunc must be a string tolerance is how close the clust...
4432dfb01eb8795622648c63ee8a6622ff33326f
62,679
from typing import Dict def request_schema(endpoint: str, session: Session) -> Dict: """ Makes a schema introspection and returns the resulting schema. The current query looks as following: query IntrospectionQuery { __schema { queryType { name } mutationType { name } su...
505a3f4deffb0cb9f8204ce642d286ab7f6b23da
62,680
def GetRangeMOverNSegmentedData(DataDirectory,fname_prefix,basin_list=[]): """ This function performs a linear regression on each segment of the segmented SA data and finds the median and interquartile range from the segments for each basin. The number of removed segments is also reported (segments are ...
ca08d0e578f09c9a23b413cf917fa76794f227af
62,681
def loadMR(mr): """ Load meaning representation using Dag class. Store only the set of triples, which will be required throughout """ dag = Dag.from_string(mr) #.stringify() triples = [] for triple in dag.triples(instances=False): triples.append((triple[0],Edge(triple[1],1,1),triple...
c0bec6cb35176769117edde10705c4fa6f9789e3
62,682
from ..data.information.html import HTML from ..data.information.text import Text from ..data.information.image import Image from ..data.information.binary import Binary def data_from_http_response(response): """ Extracts data from an HTTP response. :param response: HTTP response. :type response: HTT...
f2bf467d94f10daf2fc164748c80d53a3a8ffb8a
62,683
from pydantic import BaseModel # noqa: E0611 def apply(blueprint, args, args_suffix=[]): """Adjusts Rendering arguments. :param blueprint: field/model/container/function :param args: render arguments :param args_prefix: args_prefix :return: rendered record """ # num arguments adjustment ...
3384946eb32c797f2956cb79e92bf2cbbf1cfe5f
62,684
from typing import Optional from typing import Dict from typing import Any def create_session_factory(uri: str, base: Optional[DeclarativeMeta] = None, **engine_kwargs: Dict[Any, Any]) -> SessionFactoryType: """ Create an SQLAlchemy session factory. :param uri: The URI to the database to use :par...
53cce4c55a17515ce7cf1269b91c414dc74966f9
62,685
def get_duration(wav, sr): """ Compute the duration (in seconds) of an audio time series. Arguments: wav (np.ndarray): Audio time series to get the duration of. sampling_rate (int): Sampling rate of `wav`. Returns: float: Duration in seconds. """ ...
44d3b712dbfeff628efac36a1dde4f6bdad1d0e0
62,686
def g_nu_fig(): """ plot g(nu) """ N = 100 nu = np.linspace(.00001,1,N) s = np.linspace(0,10.,100) ds = (s[-1]-s[0])/len(s) g1 = np.zeros(N) g2 = np.zeros(N) for i in range(N): tot = 0 tot2 = 0 # find integral of exp(-s)*H(nu s) for j in rang...
16755668d981b7c95424adf4022da30643ff970a
62,687
import uuid from datetime import datetime import ast def create_app(data): """Create app appPostSerializer """ if not data.get('name'): return (False, 'App name should be specified.') t_ret = (False, '') s_uuid = str(uuid.uuid4()) s_created = datetime.utcnow().isoformat() + 'Z' ...
6696a9386bae5098adc78a198916835b71c5ff23
62,688
import time from datetime import datetime def parse_date(s): """parse string mode date date format must be `YYYY-mm-dd`, return the start seconds of day """ if '-' in s: sd = s.split('-') else: raise ValueError('invalid date: %s' % s) if len(sd) != 3: raise ValueError...
30a82084b347b063b5dea3ff1b13d61f244a73f7
62,689
def contrast_and_reshape(mouse, size=128): """ Enhance image contrast. :param mouse: Slices of the mouse we want to segment :type mouse: np.array :param size: Size of the images (we assume images are squares) :type size: int :return: Images list with readjusted contrast :rtype: np.array...
775157ed9fb5301e574887aec30b0074593e241b
62,690
import json def json_options_to_metadata(options, add_brackets=True): """Read metadata from its json representation""" try: options = json.loads('{' + options + '}' if add_brackets else options) return options except ValueError: return {}
60b796f804334ab095f103a56997b35a6a71271f
62,691
import os import logging def make_config(parser): """Parse config files into a single dictionary exposed to the user.""" # By default, use the CLI section of the digested .cfg files default = parser["CLI"] # Loop over [low_quality] for the keys, but get the values from [CLI] config = {opt: defaul...
7ab214ea8f4a32c794679879b9af932dc07072c7
62,692
def resize(transit, size=256): """ Resizes a 1D-array with linear interpolation :param transit: (1-D np.array) input data :param size: (int) target size :return: (1-D np.array) resized input """ x_original = np.linspace(0, 100, len(transit), endpoint=True) x_target = np.linspace(0, 100, siz...
67cf12a723f21dace8aa89ec9997ad3f4b74188c
62,693
from dcspy.aircrafts import Aircraft def aircraft(lcd_mono: LcdInfo): """ Return instance of Aircraft base class for Logitech mono LCD. :param lcd_mono: :return: Aircraft instance """ return Aircraft(lcd_mono)
00ecf81b0f42108b94ac7eef2ef451bfc5d815b1
62,694
def calc_duty_cycle(reg_dict): """ Calculate the duty cycle of the illumination. The duty cycle might want to be varied because of the rise time of the VCSEL or laser. Changing the duty cycle also changes the harmonic content of the illumination waveform which will change the wiggle/circular erro...
0c9a772b58d0d0aa684d2e5ba872796d11749760
62,695
from typing import Tuple import re def parse_cmd(cmd_str: str) -> Tuple[str, ...]: """ Parse command from text """ if not is_valid_cmd(cmd_str): return None if re.match(CMD_RE_LIST[0], cmd_str) is not None: action, loc_x, loc_y, direction = re.match(CMD_RE_LIST[0], cmd_str).groups...
38ad630fc83da9ad0d45893a8afdea95c7e2d0ab
62,696
import tempfile from pathlib import Path import json def _copy_hyperparameters(container: _LocalJobContainer, **creation_kwargs) -> bool: """If hyperpameters are present, this function will store them as a JSON object in the container in the appropriate location on disk. Args: container(_LocalJo...
57fc06d75b4ac5722cceec3b761488546769009f
62,697
import json def englishToFrench(englishText): """Translates English to French""" if englishText == '': return json.dumps(dict(message='Input cannot be null.')) translation = language_translator.translate( text=englishText, model_id='en-fr' ).get_result() # return print(json...
25aa18dbc87559d423032edab88faa3a23c24b7a
62,698
def start(game, game_state): """ Response: - taunt """ payload = serialize_game(game, game_state) return __call_snakes(game_state.snakes, 'POST', 'start', payload, game.turn_time)
5705f44ae3adbc0102c3bf2c5f8b0c14f14fbc0e
62,699