content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def render_color_palette(color: tuple) -> Image.Image: """ Assembles the entire color palette preview from all the render pieces. :param color: the color to lookup :return: the preview image """ pixel, ratio = get_cast_color_info(color) reticle_preview = render_reticle(CAST_COLOR_IMAGE, pix...
c4eb383262f66650f5240b4a52fd92fbb8527acb
35,200
def heightmap_get_interpolated_value(hm: np.ndarray, x: float, y: float) -> float: """Return the interpolated height at non integer coordinates. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. x (float): A floating point x coordi...
7319edf4f3adb08bd6e382612c917f579e7ff0b5
35,201
def construct_policy( bucket_name: str, home_directory: str, ): """ Create the user-specific IAM policy. Docs: https://docs.aws.amazon.com/transfer/latest/userguide/ custom-identity-provider-users.html#authentication-api-method """ return { 'Version': '2012-10-17', 'Stat...
650459810d01b28cc82d320a3b42592d3bb51170
35,202
def read_b2fgmtry(fileloc): """ Modified from omfit_solps.py """ with open(fileloc, 'r') as f: tmp = f.read() tmp = tmp.replace('\n', ' ') tmp = tmp.split("*c") tmp = [[f for f in x.split(' ') if f] for x in tmp] m = {'int': int, 'real': float, 'char': str} b2fgmtry = {} ...
5a198ed94442f40af7a0f823ac5a4b1ac43488a1
35,203
def random_rotation_matrix(rand=None, key=None): """Return uniform random rotation matrix. rand: array like Three independent random variables that are uniformly distributed between 0 and 1 for each returned quaternion. """ return quaternion_matrix(random_quaternion(rand, key))
7e25403afbe758029fa9773cf8bdbeecb54c076f
35,204
def vea_create(context, values, session=None): """Creates a new VEA instance in the Database""" # If we weren't given a session, then we need to create a new one if not session: session = nova_db_sa_api.get_session() # Create a Transaction around the insert in the Database with session.begin...
d3d6ea7a6a26df8f0de5d630cadf33e668523ca2
35,205
from orphics import stats def binned_power(imap,bin_edges=None,binner=None,fc=None,modlmap=None,imap2=None,mask=1): """Get the binned power spectrum of a map in one line of code. (At the cost of flexibility and reusability of expensive parts)""" shape,wcs = imap.shape,imap.wcs modlmap = enmap.mod...
2731935a1acbacea0f5a776ae72ef56f631df043
35,206
import logging def batch_to_dict(batch): """ Batch file contains two columns: FULL/PATH/TO/SAMPLE_bin.13.fa SAMPLE_bin.13 Create a dict with [sample_bin_name] = ["Tigname1", "Tigname2"] :param batch: full path to batch file :return batch_dict: dict described above :return bin_list: list o...
eabfff643ceb0afeee8825863a52d9d740fd97af
35,207
def md_link(name: str, url: str) -> str: """Makes strings easier to read when defining markdown links.""" return f"[{name}]({url})"
7fcef4e75e8fd77f81ddca23957fe326db869a01
35,208
def extract_uhs(dstore, what): """ Extracts uniform hazard spectra. Use it as /extract/uhs/mean or /extract/uhs/rlz-0, etc """ oq = dstore['oqparam'] mesh = get_mesh(dstore['sitecol']) rlzs_assoc = dstore['csm_info'].get_rlzs_assoc() dic = {} for kind, hcurves in getters.PmapGetter(d...
97209cbe923e1e237bfcacabcb9f5611866cb82c
35,209
def geocode_presidents(town): """ Returns a list of all intersections where a numbered street crosses a street named after the corresponding president ("1st and Washington", etc.) Each item in the resulting list is a tuple, with item[0] holding the name of the intersection ("1st and Washington"...
b1b257f02b1f78b1af509d30e78a003bb0d71e6a
35,210
import argparse import os def args(): """ 命令行参数以及说明 """ parser = argparse.ArgumentParser() parser.add_argument('-r', '--read', dest='read', help='input conpany file path') parse_args = parser.parse_args() # 参数为空 输出--help命令 if parse_args.read is None: parser.print_help() ...
09f14eacf3547c97bb501ac87063d5012a13b452
35,211
def _check_numeric(*, check_func, obj, name, base, func, positive, minimum, maximum, allow_none, default): """Helper function for check_float and check_int.""" obj = check_type(obj, name=name, base=base, func=func, allow_none=allow_none, default=default) if obj is No...
c3a62c5c95efe44dfb5a7dcd2f36a875f3dcdda1
35,212
import sh def cli(args, cook_url=None, flags=None, stdin=None, env=None, wait_for_exit=True): """Runs a CLI command with the given URL, flags, and stdin""" url_flag = f'--url {cook_url} ' if cook_url else '' other_flags = f'{flags} ' if flags else '' cp = sh(f'{command()} {url_flag}{other_flags}{args}...
0159cc37314c3804dd616e6a8e3068a1bcc90520
35,213
def cleanup(sender=None, dictionary=None): """Perform a platform-specific cleanup after the test.""" return True
655a4f7192d36aa9b73eca40e587eefd3e37f65d
35,214
def dB2(N,s,ρ=0.5,seed=0): """ Get random numbers for two correlated rBergomi processes, each having N paths and s steps. """ np.random.seed(0) # Following assumes orthogonal variance components equivalent rn = np.random.normal(size=(N,6*s)) # In what follows the 3 indices correspond to ...
2dfe2172bb50fd9b566860f263778f237affcfe9
35,215
def karaoke_perceptual_metric(reference_timestamps, estimated_timestamps): """Metric based on human synchronicity perception as measured in the paper "User-centered evaluation of lyrics to audio alignment" [#lizemasclef2021] The parameters of this function were tuned on data collected through a user Karaok...
830e6ae8cde5dd96aa53beabe0ffabca1e2bfa15
35,216
def buildTraceback(frames, modules): """ Build a chain of mock traceback objects from a serialized Error (or other exception) object, and return the head of the chain. """ last = None first = None for func, fname, ln in frames: fname = modules.get(fname.split('/')[-1], fname) ...
e6fa610265af765f23588cbb1cae66830007d4a5
35,217
def deployment_update(uuid, values): """Update a deployment by values. :param uuid: UUID of the deployment. :param values: dict with items to update. :raises DeploymentNotFound: if the deployment does not exist. :returns: a dict with data on the deployment. """ return get_impl().deployment_...
0589a453cdd6d6503b973a0571c58ec8fd476dad
35,218
from typing import List from typing import Tuple def navigate_part_two(commands: List[Tuple[str, int]]) -> Tuple[int, int]: """Navigate and return the horizontal position and depth.""" horizontal: int = 0 depth: int = 0 aim: int = 0 for command, units in commands: if command == 'forward':...
379c31e668ba63fb8bc3b98c28c2cd3087f66c51
35,219
import time from faker import Faker import random def _generate_events_for_day(date): """Generates events for a given day.""" # Use date as seed. seed = int(time.mktime(date.timetuple())) Faker.seed(seed) random_state = random.RandomState(seed) # Determine how many users and how many events...
0ebf0d524460d010fbbf29957276fbf81729cc6e
35,220
def _hessian_vector_product(fun, argnum=0): """Builds a function that returns the exact Hessian-vector product. The returned function has arguments (*args, vector, **kwargs). Note, this function will be incorporated into autograd, with name hessian_vector_product. Once it has been this function can be ...
0b4506645b8b5ae1572006f6b64873bf8fa129b2
35,221
def check_for_tags(*tag_args, msg="Inkluderar inte någon av de givna taggarna"): """ Compares the user tags and the test_case tags to see which tests should be be ran. """ def skip_function(): """ replaces test_cases so they are skipped """ raise SkipTest(msg) de...
5ddf41d0eb1ce3f8ee5b9c08db027af8e896fce6
35,222
def find_n_max_vals(list_, num): """Function searches the num-biggest values of a given list of numbers. Returns the num maximas list and the index list wrapped up in a list. """ li_ = list_.copy() max_vals = [] #the values max_ind = []# the index of the value, can be used to get the param w...
48e274a2e2feac04b285b883ce5948c8f39caff3
35,223
def color_burn(im1, im2): """Darkens the backdrop color to reflect the source color. The color burn formula is defined as: if(Cb == 1) B(Cb, Cs) = 1 else if(Cs == 0) B(Cb, Cs) = 0 else B(Cb, Cs) = 1 - min(1, (1 - Cb) / Cs) See the W3C document: ...
04dd7510d14fb88643fd512fc5020924c5163387
35,224
import subprocess def runGodot(command_args): """Runs godot with the command args given (a list) Returns a string of the output or None""" try: byte_string = subprocess.check_output(command_args, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: return # convert to a string and return retu...
1056bb8a9c898cad269318e68ca2b0d948901fd7
35,225
def G_2_by_2(a, b, c, d, williams=1, directional=1): """G test for independence in a 2 x 2 table. Usage: G, prob = G_2_by_2(a, b, c, d, willliams, directional) Cells are in the order: a b c d a, b, c, and d can be int, float, or long. williams is a boolean stating whether to do t...
57150b32a0c5b6416dc3c0a1ef8ee0dc7b357b14
35,226
def test_elapsed_duration(monkeypatch): """ . """ @counter_wrapper def duration(interval: float): """ . """ return interval monkeypatch.setattr(print_utils, "current_unix_timestamp", lambda: 123) monkeypatch.setattr(print_utils, "readable_duration", duration...
0ac8491ff88e09a09b952273413c51855621e3f8
35,227
def solve(y1,y2) : """ solve SIS lens equation with y1,y2 : relative source position with respect to the lens return : phi,x image position in polar coordinate as arrays of length 2 or 4 """ eq = lambda phi : eq2(phi,y1,y2) step = 0.1 phiTest = np.arange(0,2*np.pi+step,step) test = eq...
e24bd5935f5c8be3700f00cd4a51d122a0b43215
35,228
def makeNme(segID: int, N, CA, C, O, geo: NmeGeo) -> Residue: """Creates a NME capping residue""" res = makeGly(segID, N, CA, C, O, geo) res.resname = "NME" return res
9335b22a7c578a7eb026d04ba0980d239995ffb7
35,229
def compose_image_meta(image_id, image_shape, window, active_class_ids): """Takes attributes of an image and puts them in one 1D array. image_id: An int ID of the image. Useful for debugging. image_shape: [height, width, channels] window: (y1, x1, y2, x2) in pixels. The area of the image where the real...
e2b9a362f304ed194516706f30d5051a0cfb38dd
35,230
from typing import Callable from typing import Any from typing import Tuple from typing import List from typing import Union import numpy def run_episode_generic(env: Env, action_value_generator: Callable[[Any, int], Tuple[List[float], float]], max_length: int, max_len_...
3531102b0bf546b7ccf92fcbb79d9b23fcdc67ec
35,231
import resource def sobjects_metadata_resource(client: Client): """Return resource representing SObject metadata.""" path = f"{client.resources['sobjects']}" @resource class SObjectMetadataResource: """...""" def __init__(self, name): self.name = name @query ...
3c7cd711e0fb01692d43c3b726a8d9e01357b680
35,232
def makeDrinkInfo(rec_id): """ Permet de dresser les infos de la boissons passees en argument :param arg1: id de la boissons (recette) :type arg1: int :return: le nom, prix et les informations utiles (alcool, chaud ou froid) de la boissons :rtype: Json """ price = calculePriceRec(rec_id) nom = recupNameRec...
b428c55b71ab2045b8d660f6cb1e587da4723b13
35,233
def get_vars(host): """ parse ansible variables - defaults/main.yml - vars/main.yml - molecule/${MOLECULE_SCENARIO_NAME}/group_vars/all/vars.yml """ base_dir, molecule_dir = base_directory() file_defaults = "file={}/defaults/main.yml name=role_defaults".format(base_dir) file...
e2498edda87bc879b7fe571a6c21674ebf3a9164
35,234
def get_smem_args(smem_args, params): """ return a dict with kernel instance specific size """ result = smem_args.copy() if 'size' in result: size = result['size'] if callable(size): size = size(params) elif isinstance(size, str): size = replace_param_occurren...
52a77346798a7bd8cf417eb729a2a1a2d5b1059e
35,235
from math import isnan from Europe_utils import country_names def check_actual_routes(): """"Compares the number of routes in the results excel and the actual routes evt filteren op countries """ #Load the analysis file analysis_file = config['paths']['data'] / 'Overview_analysis_2021_5_5.xls' ...
d6cbf304656bc14f6b5c3ac37b80991ea6b5c251
35,236
from typing import Optional from typing import Iterable from re import T from typing import Sequence from typing import Callable def fork_procs(variant_arg: Optional[Iterable[T]] = None, variant_args: Optional[Iterable[Sequence]] = None) \ -> Callable[[Callable], process.Handle]: """ A decorate ...
149055123de138388b62e52244e9bbab9f13ebe3
35,237
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3): """ Compute c_v coherence for various number of topics Parameters: ---------- dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Returns:ocs ...
3b2391aecc67353f6d60bb68f027713ad7e4ea52
35,238
def set_mosflm_beam_centre(detector, beam, mosflm_beam_centre): """detector and beam are dxtbx objects, mosflm_beam_centre is a tuple of mm coordinates. supports 2-theta offset detectors, assumes correct centre provided for 2-theta=0 """ return set_slow_fast_beam_centre_mm(detector, beam, mosflm...
a7b0ed140a4beb05766734fe838351f5cfa0c255
35,239
import os async def connect(): """Ouvre la connexion au serveur PC Minecraft. Returns: ``True`` (la connexion a réussi) ou ``False`` (la connexion a échoué) Le *screen* Unix sur lequel tourne le serveur et le chemin d'accès (relatif ou abolu) aux logs actuels générés par le serveur sont lus ...
f566d54633cdc6b052ae3ef1cb42f0e7dfb18014
35,240
def getNumColors(path): """ Detect the number of colors in the supplied image (Only up to 8 colors not including the background) NOTE: This feature is experimental and may not work well for ALL images """ im = Image.open(path) # Resize to reduce processing time w, h = im.size wS...
7b49dbb48c25910220bcf8ec7b9c267c9d0934b0
35,241
def reduce_precision_np(x, npp): """ Reduce the precision of image, the numpy version. :param x: a float tensor, which has been scaled to [0, 1]. :param npp: number of possible values per pixel. E.g. it's 256 for 8-bit gray-scale image, and 2 for binarized image. :return: a tensor representing image...
eb322b81976ea3a2b56c408ce0b9f5eb11580f04
35,242
from typing import Callable from typing import Union from typing import Optional from typing import Tuple import functools def multi_dut_argument(func) -> Callable[..., Union[Optional[str], Tuple[Optional[str]]]]: """ Used for parse the multi-dut argument according to the `count` amount. """ @functoo...
ce7523c9e63cdc076dc4ec326ce3bc4572042a54
35,243
def ts2wws(C): """ Convert a stiffness tensor into a skew notation stiffness matrix """ Cv = zeros(3,6) for i in range(3): for j in range(6): ma = skew_mults[i] mb = mandel_mults[j] Cv[i,j] = C[skew_inds[i] + mandel[j]] * ma * mb return Cv
55fb55d32af033c6eeb082ffd2740c40376de1ee
35,244
import os def testdata(): """ Simple fixture to return reference data :return: """ class TestData(): def __init__(self): self.datadir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') def fn(self, fn): return os.path.join(self.datadir, fn...
e4bd8b1177646d85c7b2e9e7998d4cde224ca0ce
35,245
def _get_oauth2_client_id_and_secret(settings_instance): """Initializes client id and client secret based on the settings""" secret_json = getattr(django.conf.settings, 'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None) if secret_json is not None: return _load_client_secrets(secret...
1cdb02999af3ab289f262de316bc4afc17add8ac
35,246
import os import re def buildTranslation(lang): """Finds the file corresponding to 'lang' builds up string_cache. If the file is not valid, does nothing. Errors encountered during the process are silently ignored. Returns string_cache.""" global string_cache fName = os.path.join(langPath, lang...
e078bb82a574868dc5d922c7881966034f8ec5cb
35,247
def lpp_transform(X, V, ncomp=2): """ Args: -------------- X: n x d. Data matrix V: d x m. Each column of V is a LPP direction. ncomp (<= m <= d): The dimension of transformed data Returns: -------------- tr_X: n x ncomp """ _, m...
44b362932e420252689fb87e845665a3bdfe332e
35,248
def U_net(optimizer, activation, metrics): """ Parameters: - optimizer (String): Keras optimizer to use - activation (String): Keras layer activation function to use in hidden layers - metrics to use for model evaluation Returns: (Model) a compiled U-net designed for binary segmentatio...
009eea82f105d6b5975a83739f52e43855274481
35,249
def create_environment(env_name='', stacked=False, representation='extracted', rewards='scoring', enable_goal_videos=False, enable_full_episode_videos=False, render=False, ...
548449ddcb9dd35161ebb7ab65f564b9644fa438
35,250
def self_biosample_id(): """本人的样品编号""" return SELF_BIOSAMPLE_ID
d2fdf081de5248284b0317051d9d2dcc63e4913b
35,251
def exp_process_image_20(img): """Get multiprocess experiment.""" return process_image( img, imgclf.ImageClassifier(), segments_no=20, sample_size=100, random_seed=42)
4cd686fee485106a6004abb4f04fddda7aa722f4
35,252
import json import requests def get_lol_version(): """ Get current League of Legends version """ versions = json.loads(requests.get( "https://ddragon.leagueoflegends.com/api/versions.json").text) # reformats from 10.14.5 to 10.14 latest = ".".join(versions[0].split(".")[:2]) return latest
2702b3375cee503cea561f2965bbafdb17a3f232
35,253
def retrieve_domain_name(module, client, name): """ Retrieve domain name by provided name :return: Result matching the provided domain name or an empty hash """ resp = None try: resp = backoff_get_domain_name(client, name) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'...
e88959843c9973c9ac8071316cef9dcaec8ccf91
35,254
def create_BIP122_uri(chain_id, resource_type, resource_identifier): """ See: https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki """ if resource_type not in {BLOCK, TRANSACTION}: raise ValueError("Invalid resource_type. Must be one of 'block' or 'transaction'") elif not is_block...
fc6ca06c094082f748c14250cf67da416aaf5fb9
35,255
import time def draw_down(x, y, threshold, timeout): """ Draws the line down. :param x: X coordinate of click :param y: Y coordinate of click :param threshold: pixel gradient threshold :param timeout: timeout (sec) :return: Y coordinate where pixel gradient is hit """ y_position = ...
2bfa7a7fbdeea2c5e4b974cf69b473c44273ab61
35,256
def read_read_basis(input_string): """ """ pattern = ('ReadBasis' + one_or_more(SPACE) + capturing(LOGICAL)) block = _get_functional_form_section(input_string) keyword = first_capture(pattern, block) assert keyword is not None return keyword
6e2f0a59bdddb2ac34ec8cf730f9a778a67e8d59
35,257
def _Ipr7ConfigRead(config): """Extracts DPA and grants from IPR7 config JSON. Args: config: A JSON dictionary. Returns: A tuple (dpas, grants) where: dpas: a list of objects of type |dpa_mgr.Dpa|. grants: a list of |data.CbsdGrantInfo|. """ if 'portalDpa' in config: dpa_tag = 'port...
78f9288be544c6a66845eadb42bef30fcf84632c
35,258
def pack(a: ArrayLike, ox: int, oy: int, wx: int, wy: int, sx: int, sy: int, px: int = 0, py: int = 0, is_column: bool = True) -> ShapeletsArray: """ Reverses the :obj:`~shapelets.compute.unpack` operation For a thorough explanation of this method, consult the `ArrayFire documentation <https://arr...
ac1af1eeb76fed5ecf4a1d68f17a6683415a2f6d
35,259
def maybe_create_token_network( token_network_proxy: TokenNetworkRegistry, token_proxy: CustomToken ) -> TokenNetworkAddress: """ Make sure the token is registered with the node's network registry. """ block_identifier = token_network_proxy.rpc_client.get_confirmed_blockhash() token_address = token_prox...
1c477f8ad02ac99c2039d59dc04eef5f6ea6b1ed
35,260
def rmsprop(grad, init_params, callback=None, num_iters=100, step_size=0.1, gamma=0.9, eps=10**-8): """Root mean squared prop: See Adagrad paper for details.""" flattened_grad, unflatten, x = flatten_func(grad, init_params) avg_sq_grad = np.ones(len(x)) for i in range(num_iters): g ...
6c794d5a16dc7b46c055edfb714995f00450eb92
35,261
import re def parse_transceiver_dom_sensor(output_lines): """ @summary: Parse the list of transceiver from DB table TRANSCEIVER_DOM_SENSOR content @param output_lines: DB table TRANSCEIVER_DOM_SENSOR content output by 'redis' command @return: Return parsed transceivers in a list """ res = [] ...
9a9e069543a8a80b9e741452c37ed1c665b56398
35,262
def get_excerpt(post): """Returns an excerpt between ["] and [/"] post -- BBCode string""" match = _re_excerpt.search(post) if match is None: return "" excerpt = match.group(0) excerpt = excerpt.replace(u'\n', u"<br/>") return _re_remove_markup.sub("", excerpt)
b417fc18604020e91a9b5b4f4b154fba7fcbcdc1
35,263
def dropblock(net, is_training, keep_prob, dropblock_size, data_format='channels_first'): """DropBlock: a regularization method for convolutional neural networks. DropBlock is a form of structured dropout, where units in a contiguous region of a feature map are dropped together. DropBlock works bet...
de401f315590505e5db9b58c78a13fdaa3b7f1bb
35,264
from typing import get_args import string import random import sys def main(): """ Main Program """ args = get_args() random_str = ( "".join(sorted(string.ascii_letters + string.punctuation)) if not args.alphanumeric else "".join(sorted(string.ascii_letters)) ) random.see...
ecf81562987f15480ad556058d22026a0bb23d95
35,265
def certify(String, cert, password): """check a certificate for a string""" return certificate(String, password) == cert
05ecd81e4738c4304e7d37c6c530035375ded09b
35,266
def is_same_float(a, b, tolerance=1e-09): """Return true if the two floats numbers (a,b) are almost equal.""" abs_diff = abs(a - b) return abs_diff < tolerance
a8c10ae330db1c091253bba162f124b10789ba13
35,267
def generate_grid_speed(method, shape, speed_range): """Generate a speed distribution according to sampling method. Parameters ---------- method : str Method for generating the speed distribution. shape : tuple Shape of grid that the speed distribution should be defined on. spee...
700b1a6341bc1f218be04ff957ee3d02f9520adf
35,268
def common_atoms(cycle1, cycle2): """ INPUT: two cycles with type: list of atoms OUTPUT: a set of common atoms """ set1 = set(cycle1) set2 = set(cycle2) return set1.intersection(set2)
1e85887a6199bf88a71709057c79025c0937a420
35,269
import subprocess import shlex import json def ffprobe_json(media_file): """Uses ffprobe to extract media information returning json format. Arguments: media_file: media file to be probed. Returns: json output of media information. return code indicating process result. """ ...
7c13366b31de40aacae561442030d5eb0687246e
35,270
def get_two_body_decay_scaled_for_chargeless_molecules( ion_pos: Array, ion_charges: Array, init_ee_strength: float = 1.0, register_kfac: bool = True, logabs: bool = True, trainable: bool = True, ) -> Jastrow: """Make molecular decay jastrow, scaled for chargeless molecules. The scale f...
97ded768c3c0f9b61d3f5fc0e313b072b7ba241f
35,271
def compute_huffman_code(message_probs): """ The input is a dictionary of messages, and their relative probabilities (which must add to 1). The output is a dictionary of each message and it's new codeword (a bytestring) in the Huffman encoding. """ return tree_to_encoding(message_tree(message...
fa760829736810ec908ea2ed9103937477971a2d
35,272
from typing import Optional from typing import Dict from typing import Any def genomics_cnn(batch_size: int, len_seqs: int, num_motifs: int, len_motifs: int, num_denses: int, num_classes: int = 10, embed_size: int = ...
5553dfda33e2596ba3372d9b7158f9964bfd6cfd
35,273
from typing import Dict from typing import List from typing import Union from typing import Tuple from typing import Any import logging def plot_stats_for_all_selectors(stats: Dict[str, SimulationStatsDistribution], y_attr_names: List[str], y_attr_labe...
5540680cb6710bda8f708613a8fc6b47a6baf4d5
35,274
import os def repository_path(repo, rev="HEAD", in_repo_path=""): """ Build a path (for further use in sys.path) from a repository reference :param repo: a pygit2 repository object or a path to a git repository :param rev: the revision which should be used. Acceptable values are all valid git revisio...
33a5bea3cad8109314a00cd9f7059d1c0c8681e0
35,275
import os from bs4 import BeautifulSoup def process_repo(repo_dir): """parse markdown code snippets. Args: repo_dir (str): directory name. Returns: List<Dict> """ snippets = [] snippets_dir = os.path.join(repo_dir, "snippets") for idx, file in enumerate(os.listdir(snippet...
7cb6b3fb83ad2b362b0279744d68d4644cd2936d
35,276
def setDuration(*args): """setDuration(ALInterpolationBangBangAcceleration pObject, float pDuration)""" return _almathinternal.setDuration(*args)
74f8bf125266a0174aa39f6e7284854bf066a32f
35,277
def regex(pattern): """ Does a pattern search using the system's `find` utility :param pattern: a pattern you intend to search for :return: String """ cmd = "find " + MIGRATION_FOLDER + " -type f -exec grep -il " + pattern + " {} +" out = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stder...
5b5df47dc85239db2294fa36411d259617756186
35,278
def _mp_fabber_options(wsp): """ :return: General Fabber options for multiphase decoding """ # General options. note that the phase is always PSP number 1 options = { "method" : "vb", "noise" : "white", "model" : "asl_multiphase", "data" : wsp.asldata, "mask" ...
af1c724bd9b88a0d76e7c7d18a3fa2b19591984e
35,279
def get_player_objects_from_challenge_info(player, should_be_completed=False, search_by_discord_name=True): """ Search for a challenge in the DB corresponding to the player param str/int player: The gamertag or id of the player to search for param bool should_be_completed: If the challenge should alrea...
e4a39d3a72063b41d5b9b92f0b1535ba164beeb1
35,280
import subprocess import re def get_python_version(python_bin): """Returns the version of a python binary as a tuple of integers. Args: python_bin (str): Python binary. Returns: Integer tuple containing the major, minor, and micro of the version. None if version checking fails. ...
4656f8e1e21e29151ba3c614ccf1587bd0cdcc61
35,281
def get_output(interpreter, score_threshold, labels): """Returns list of detected objects.""" boxes = output_tensor(interpreter, 0) class_ids = output_tensor(interpreter, 1) scores = output_tensor(interpreter, 2) count = int(output_tensor(interpreter, 3)) def get_label(i): id = int(clas...
83518a28025d7d39bf475cd0f6aa222ad7197659
35,282
def provide_session(func): """ Function decorator that provides a session if it isn't provided. If you want to reuse a session or run the function as part of a database transaction, you pass it to the function, if not this wrapper will create one and close it for you. """ @wraps(func) de...
d11233a852a8c2f4ac7a95179b588e7b497bbf3a
35,283
def encode_urlencoded_form(fields): """ Encode dict of fields as application/x-www-form-urlencoded. """ body = urlencode(fields, doseq=1) headers = {'Content-Type': 'application/x-www-form-urlencoded'} return body, headers
26d4b99070e8d354775f7f2b6e97673dedd582f0
35,284
def process_wrapper(row, seq, cds_seq, seq_lookup, tile_begins, tile_ends, qual, locate_log, mutrate, base, posteriorQC, adjusted_er): """ Wrapper function to process each line (pair of reads) """ mut_parser = locate_mut.MutParser(row, seq, cds_seq, seq_lookup, tile_begins, tile_ends...
19547caddd84c1eb54b32525babf4d8b624aea70
35,285
def default_cfg(): """ Set parameter defaults. """ # Simulation specification cfg_spec = dict( nfreq=20, start_freq=1.e8, bandwidth=0.2e8, start_time=2458902.33333, integration_time=40., ntimes=4...
0b76e2166ce17d6ab42e4f72d7003ba6c03b11f6
35,286
def merge_outputs(*streams: Stream) -> OutputStream: """Include all given outputs in one ffmpeg command line.""" return MergeOutputsNode(streams).stream()
bd6dee8b54843556426a01f691f87f28a62c1a99
35,287
def softmax(vector, theta=1.0): """Takes an vector w of S N-element and returns a vectors where each column of the vector sums to 1, with elements exponentially proportional to the respective elements in N. Parameters ---------- vector : array of shape = [N, M] theta : float (defa...
06b4df32e5a04b49e3eaa1626638dad845c4b4a0
35,288
def scaled_elementary_effect_i( model, i_python, init_input_pars, stepsize, sd_i, sd_model ): """Scales EE by (SD_i / SD_M)""" ee_i = elementary_effect_i(model, i_python, init_input_pars, stepsize) return ee_i * (sd_i / sd_model)
c345c4e40a58b0ac9228edb0cd9e96a05d28e1db
35,289
def arch_mnasnet_b1(variant, feat_multiplier=1.0, **kwargs): """Creates a mnasnet-b1 model. Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet Paper: https://arxiv.org/pdf/1807.11626.pdf. Args: feat_multiplier: multiplier to number of channels per layer. """ ...
25a9a0c0f4a026f122c73139cb8464c47fae299a
35,290
def accession(data, location): """ Generate an accession for the given location in data. """ return "{ac}:{gene}".format( ac=parent_accession(location), gene=data["gene"], )
a8023857b812b510990c6161194b8f85832df14a
35,291
def poly_oval(x0,y0, x1,y1, steps=20, rotation=0): """return an oval as coordinates suitable for create_polygon""" # x0,y0,x1,y1 are as create_oval # rotation is in degrees anti-clockwise, convert to radians rotation = rotation * pi / 180.0 # major and minor axes a = (x1 - x0) / 2.0 b = (...
7a188676654ca47a53da33df40ac16387ecaa490
35,292
def not_found(request): """Error page for 404.""" response = render(request, "projectile/404.html") response.status_code = 404 return response
fb17b8f1cdcdfa530adb569abc9b006ed2868492
35,293
import sympy def _sympy_to_z3_rec(variable_map, expr): """Recursively convert sympy expression to z3 expressions.""" # Adapted from # https://stackoverflow.com/questions/22488553/how-to-use-z3py-and-sympy-together rv = None # TODO(yl): For some reason, # GreaterThan and LessThan are not subclasses of Ex...
9b1b6775eb5a5518201192d8066131107e76a3d2
35,294
def reset_universe_id(): """ reset_universe_id() Resets the auto-generated unique Universe ID counter to 10000. """ return _openmoc.reset_universe_id()
bd7815a749e4d89c8d3a78aea1b24046db9c78bf
35,295
from typing import Union def native_mean(data: Union[list, np.ndarray, pd.Series]) -> float: """ Calculate Mean of a list. :param data: Input data. :type data: list, np.ndarray, or pd.Series :return: Returns the mean. :rtype: float :example: *None* :note: *None* """ data = _...
3d62a3fdbb77ae0dbc8b19eaefee40abe96d3888
35,296
import json def dataset_info_4_biogps(request, ds_id): """ get information about a dataset """ ds = adopt_dataset(ds_id) if ds is None: return general_json_response(GENERAL_ERRORS.ERROR_NOT_FOUND, "dataset with this id not found") s = json.dump...
d38f3bde125cb20a48a2842bdc8021f3eb032c8c
35,297
def _set_reducemax_attrs(desc_d, attrs): """Add addition attributes for ReduceMax.""" backend = desc_d['process'] if backend == 'cuda' and _reducemax_pattern(desc_d)[0]: attrs['enable_tile_c0'] = True elem_per_thread = 4 blockdim_x = 64 blockdim_y = 16 griddim_x = 1 ...
d5b50da5b3097690a0cc2ab27bbac47448f35bb7
35,298
def getTail(compiler,version): """ Function which generates the Tail of a Compiler module file. @input compiler :: compiler name ('intel','pgi',..) @input version :: version of the compiler @return :: list of Lua lines """ strA = 'local version = "{0}"'.format(version) ...
46df63461d05b26fbc5e5a45e6162a2794f92ed1
35,299