content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os import subprocess def scale_video(fname, x, y): """ Scales the video to x by y size """ out = fname tmp = '%s.tmp' % fname resolution = '%sx%s' % (x, y) # logger.info(".. renaming %s to %s" % (fname, tmp)) try: os.rename(fname, tmp) except OSError: logger....
7fb48bc478653f89d61ccceb22dc3789de123bc3
57,000
from typing import Union from pathlib import Path from typing import Any def load_from_cache(filepath: Union[Path, str]) -> Any: """Load a Python object pickled in a file located at `filepath`. This function will raise a `FileNotFoundError` if the cache file doesn't exist. It is the responsibility of the...
79155d66afb6915bc8bbe4aeae0529615bb961e7
57,001
from typing import Coroutine def _coro_get_awaitable_iter(o): """Interal helper function to get an awaitable iterator. Corresponding impl.: https://github.com/python/cpython/blob/3.5/Objects/genobject.c#L783-L823 """ if isinstance(o, (Coroutine, CoroWrapper)) or gen_is_iterable_coroutine(o): ...
d47e3d1df45beb6ea2622ee90bdcbcebdc17e48b
57,002
def kronecker_prod(x, y): """Returns the tensor / Kronecker product of 2 complex matrices, x and y. :param x: A complex matrix. :type x: torch.Tensor :param y: A complex matrix. :type y: torch.Tensor :raises ValueError: If x and y do not have 3 dimensions or their first ...
1b968d0eb9132419a476b0631f8be7184999b2d7
57,003
def _instance_data(data): """Returns input data with correct shape. For any one-element array, i.e. array of shape (1, ) or (1, 1) returns the single object inside it as a built-in type. Parameters ---------- data : array_like or scalar or NotImplemented Data to be converted. Could be...
2bad0dae958f69a2221e4f11b7a0a3c1f4abb114
57,004
def get_koji_build_info_url_from_flask(id_: int = None,) -> str: """ provide absolute URL to p-s koji build logs view meant to set in a commit status """ with application.app_context(): return url_for( "builds.koji_build_info", id_=id_, _external=True, # _ext...
578e07300a47d73984a6cbce95b45b2ba26bf0b6
57,005
def remove_well_known_protos(filenames): """Remove "well-known" protos for objc. On those platforms we get these for free as a part of the protobuf runtime. We only need them for nanopb. Args: filenames: A list of filenames, each naming a .proto file. Returns: The filenames with members of google/p...
9aa14b70e9251fe4d8ff42277be969d23f3ecdba
57,006
def count_cigar_ops(cigar): """ For curious people: regexes are very slow for parsing CIGAR strings. cigar: Unicode """ b = 0 num_m, num_i, num_d = 0, 0, 0 for i in range(len(cigar)): if cigar[i] <= '9': continue # Check if there are no digits before the op char....
7efacce3a9b13249718ae140e79a5800b8682ff5
57,007
def get_dwtype_floor_area(dwtype_floorarea_by, dwtype_floorarea_ey, sim_param): """Calculates the floor area per dwelling type for every year Parameters ---------- dwtype_distr_by : dict Distribution of dwelling types base year assump_dwtype_distr_ey : dict Distribution of dwelling ...
3b87386bbf5bf051aec5d43ebd47f3359885c8b4
57,008
def generate_field_shift(mask_image, vector_shift=(10, 10, 10), gaussian_smooth=5): """ Shifts (moves) a structure defined using a binary mask. Args: mask_image ([SimpleITK.Image]): The binary mask to shift. vector_shift (tuple, optional): The displacement vector applied to the entire binar...
1082bd23455d138ee69f3c2663d61cd346e1d917
57,009
def Credible_Set(position, pos_prob, threshold): """Function that finds the credible set according to a set threshold""" total = sum(pos_prob) bounds = threshold*total #make into tuples tuple_vec = [] for i in range(0, len(position)): tup = (position[i], pos_prob[i]) tuple_vec.ap...
01a587c0e7e6de995fd77c85f30011784018c383
57,010
def apply_size_filter(segmentation, input_, size_filter, exclude=None): """ Apply size filter to segmentation. Arguments: segmentation [np.ndarray] - input segmentation. input_ [np.ndarray] - input height map. size_filter [int] - minimal segment size. exclude [list] - list of se...
8a5ee3f88c609cad09a5d179c24dfb0f77f7034e
57,011
def load_Sentinel1(site, StartDate, EndDate): """ Function to retrieve and filter Sentinel-1 images args: aoi: region of interest StartDate: Starting date to filter data EndDate: End date to filter data returns: Image collection of Sentinel-1 images """ filtere...
4887a2aabdfee9c689b774fef323a783ac50cd58
57,012
import logging def recover_lost_connection(connection:obd.OBD, fast:bool, timeout:float)->obd.OBD: """ Recover lost connection and return a new working connection handle. """ logging.info("recovering lost connection") connection.close() sleep(CONNECTION_WAIT_DELAY) connection = get_obd_con...
f68968193c80be49142e05de8aae02e3fc3e144e
57,013
def get_ps_aux(connection_obj, search_string, device="dut"): """ API to get the ps aux output Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) :param conn_obj: :param search_string: :param device: :return: """ command = "sudo ps aux" if search_string: command ...
d9f359f607a3b9f83fd8300874008ce35be2d750
57,014
def estimate_power(sim, test, auto=False): """Compute the mean of the estimated power of 5 replications over sample sizes.""" if test == "MaxMargin": test = ["MaxMargin", "Dcorr"] dim_range = find_dim_range(find_dim(sim)) est_power = np.array( [ np.mean( [ ...
67550a596285cff028712f9558ba8ec6e699a892
57,015
from pathlib import Path import re def listdir_with_only(path, names=None, ext=None): """Lists items in the directory conforming name regexes or extensions.""" dir_ = Path(path) if not dir_.is_dir(): raise ValueError('path must be a directory.') names = names if names else [] ext = ext if ...
66aab005255f1a52c88577df02c53c2ab020469f
57,016
def look_and_say(n): """Returns the nth term of the "look and say" sequence, which is defined as follows: beginning with the term 1, each subsequent term visually describes the digits appearing in the previous term. The first few terms are as follows: 1 11 21 1211 111221 Ex: the fo...
5cb341d0bce8bc363b2b734e9da66a07b7da2434
57,017
def compound_alternative_forms(forms, sec_pos, forms_ind_or_con, forms_imp): """ compuond all alternative forms into a set :return: """ if not forms: if forms_imp: forms = {sec_pos: forms_ind_or_con, 'imp': forms_imp} else: forms = {sec_pos: forms_ind_or_con} ...
9b81aea6ef9edbe71560d2ca1d001a3971928c00
57,018
def hasher_unsigned(first_last_name: str, mask, init: int=HASH_INIT) -> int: """The hash function to hash the combined first + last name into a check value""" h = init for c in first_last_name: h = (h * HASH_PRIME + ord(c)) & mask return h
e0b4133762ad7fb41c3aac89bcfe3849ffcfb4f2
57,019
async def get_weakness_chart(type_name: str, generation: int = APP_DEFAULT_GEN): """This path returns the weaknesses of pokemon with type {type_name}.""" if not is_valid_type(type_name.capitalize(), generation=generation): return {"error": "%s is not a valid type for generation %s" % (type_name, generat...
2637488f22ca353427d5febbd60058041ef4132f
57,020
def difficulty_rank(sentence: Text) -> int: """Calculates 'sentence' difficulty level. Returns Integer.""" chars = len(sentence) words = len(word_tokenize(sentence)) return words + (chars//5)
2b072b1518d850c2aa88198e20d331459753e278
57,021
def read_list(filename): """ Read a list from a JSON file. :param filename: file name (string). :return: list. """ _list = [] # open output file for reading try: with open(filename, 'r') as filehandle: _list = load(filehandle) except IOError as e: logge...
f798234633e84a2082a0394e5480b2b355edc57c
57,022
def _preprocess_hash(hash_str: str) -> SanitizedObservable: """Ensure Hash has minimum entropy (rather than a string of 'x').""" str_entropy = entropy(hash_str) if str_entropy < 3.0: return SanitizedObservable(None, "String has too low an entropy to be a hash") return SanitizedObservable(hash_st...
efe932c6df9b6e2ab566ba2029bf75bc7b6c6233
57,023
def Reformer(input_vocab_size, output_vocab_size=None, d_model=512, d_ff=2048, n_encoder_layers=6, n_decoder_layers=6, n_heads=8, dropout=0.1, max_len=2048, ff_activation=tl.Relu, ff_dropout...
2ab5e2312d3034f33b666a7a891b39c71f580dc3
57,024
from typing import Union def make_wordcloud(data: Union[dict, list, object, str, tuple], opts: dict = None, round: int = None ): """Make a word cloud. Accepts data from a string, list of lists or tuples, a dict with terms as keys and counts/frequenc...
0a9b1b9dfe5311ae7a4edd0b909526cd0d4d9e13
57,025
def deleteDuplicates2(self, head: ListNode) -> ListNode: """ recursive :param self: :param head: :return: """ if not head: return head if head.next and head.val == head.next.val: while head.next and head.val == head.next.val: head = head.next return s...
185c15ebe61dba769d8ef04aa1f5a28603b807d1
57,026
import random def generate(length: int = 1) -> str: """Generates a random string of alphanumeric characters of the given length. If no length is specified, a single character is returned. On Python 3.5, this string is pseudo-randomly generated using :py:mod:`random`. With 3.6 and later, the randomnes...
b04f0e448e4308601741121dd2892f990fe6ee64
57,027
def get_balance(user): """ Get UND Balance for a user \b :param user: The EOS user account name. """ cleos = get_cleos() ret = cleos.run(['get', 'currency', 'balance', 'unif.token', user, 'UND']) stripped = ret.stdout.strip() if len(stripped) > 0: my_balance = stripped ...
8a2d2d863139ddbbe2ea61b8cc32a7f2ad282fa5
57,028
import requests import json def get_recommended_fees(): """Retrieves current recommended fastest fees from bitcoinfees API in satoshis """ uri = 'https://bitcoinfees.earn.com/api/v1/fees/recommended' response = requests.get(uri) if response.status_code == 200: fees = json.loads(response...
1311f6de617caf1755c1588378d106b252f24c4e
57,029
from typing import Tuple import numpy def clip_solution( x: ndarray, g: ndarray, H: ndarray, constraints: Tuple[ndarray, ndarray, ndarray, ndarray], delta: float, ) -> Tuple[ndarray, bool, int]: """ x: S个N-dim的列向量 先 assert 它们都是单位向量 - 根据a = argmin f(a): a * gx + a^2 * 0.5xHx获得缩放尺度 ...
6444b5d7d913796b0c7a008a23a4e93210b2c6cd
57,030
def property_node_uriref(property_name): """ Create a Survol property node. """ return rdflib.URIRef(LDT[property_name])
9994639f3883bfa8ccf97c15bfee6e2e7839f8d1
57,031
from typing import Tuple from typing import Optional from datetime import datetime def try_to_format_date(might_be_date: str, date_format: str) -> Tuple[bool, Optional[date]]: """ return a datetime object is parsed """ try: d = datetime.strptime(might_be_date, date_format) return True, d except ValueError: ...
0bfa9be5d4b3a542f80682a53b9bd63d8efbeb51
57,032
def get_text_ls(filename): """Returns text of file as a list of strings""" with open(filename, 'r') as f_in: return f_in.readlines()
5b788f38e683c82648224b7cc1b5875a0f602dce
57,033
def rebuild_command(args): """Rebuilds a unicode command string prepared to be stored in a file """ return "%s\n" % (" ".join(args)).replace("\\", "\\\\")
38643f1e2c7414683a4b2d89c517aa8c432bb9a3
57,034
import string import secrets def generate_secure_random_string(stringLength=10): """Generate a secure random string of letters, digits and special characters """ password_characters = string.ascii_letters + string.digits + string.punctuation return ''.join(secrets.choice(password_characters) for i in rang...
66a0d5863f1955b036e95479bbde40c6ee031437
57,035
def get_title(soup): """Given a soup, pick out a title""" if soup.title: return soup.title.string if soup.h1: return soup.h1.string return ''
bcec80e0c6e5163ed90a4975b81a5c5a3d418132
57,036
def locate_peaks(data,sorted=False): """<numpy array> return all (index,value) pairs of the spectral peaks in the given data, with the option of being sorted in descending order of data value""" indices = filter(lambda j: data[j]>=max([data[j-1],data[j+1]]),range(1,len(data)-1)) result = zip(in...
9f6e09e96d4490fc9e848e833f531883b844f41c
57,037
def get_quality(all_qualities, pref=0, *args): """Gets the best, middle or lowest quality from the Quality types given. Args: all_quality: iterable having all qualities from best to lowest *args: qualities to sort pref: (0,1,2) int ...
94d0aeb3d15f07e860d8779df0d181607ad2b38e
57,038
def blur(rgb: np.ndarray, sigma: float) -> np.ndarray: """ぼかし。sigmaは0~1程度がよい?""" rgb = cv2.GaussianBlur(rgb, (5, 5), sigma) if rgb.ndim == 2: rgb = np.expand_dims(rgb, axis=-1) return rgb
a836903535a47e916590ba0685eb4158301ec962
57,039
import numpy import pandas def bin_library_quantification(quantification, quantification_name, bins=None): """Bin a library quantification file default bins are [0.1, 1, 2, 5, 10, 50, 500, 5000, 1e9] """ if bins is None: bins = DEFAULT_BINS histogram = {} for col in quantification: ...
3f6923284a3e1ac771c82f35567536839548ddc2
57,040
def add_motif(genome, motif, index): """ Replace from the index to index+len(motif) in the genome with the motif selected """ try: # If this can be done is because index is an integer index = index-len(motif) return genome[:index]+motif+genome[index+len(motif):] except: ...
b4fa3f957fc440a837a0f65fd431f1fc9119f077
57,041
from datetime import datetime def get_yearly_mb_temp_prcp(gdir, time_range=None, year_range=None): """Read climate file and compute mass balance relevant climate parameters. Those are the positive melting temperature at glacier terminus elevation as energy input and the amount of solid precipitation onto ...
e4889eb7dcf629d700402135ce9c56bde60990c6
57,042
def get_nsx_resource_binding(client, name, id): """ :param client: nsx resource client :param name: name of neutron object :param id: id of neutron object :return: return the nsx resource id """ nsx_name = utils.get_name_and_uuid(name, id) nsx_resource = client.find_by_display_name(nsx_n...
34d680fb2f54352ff10acdc9a04f833ab1ec09a9
57,043
import types import sys def createModule(name, source, filename="<dynamic-module>", namespace=None): """ Utility function to create a new module with the given name (dotted notation allowed), directly from the source string. Adds it to sys.modules, and returns the new module object. If you provide a n...
08dd8a642f9baad2f2c03224b21339d44c6b09f2
57,044
def latest(name, minor_only=True, region=None, keyid=None, key=None, profile=None): """ Ensures the Elasticsearch domain specifies runs on the latest compatible version of elasticsearch, upgrading it if it is not. Note that this operation is blocking until the upgrade is complete. :param str name:...
5e7ac23220d92cf8c638bdd4ff89cca014059fec
57,045
def annotate(query_text: str): """ annotate plain text with links to wikipedia pages """ plain_text = unquote(query_text) response = model.annotate(plain_text) return { "request": query_text, "response": response }
f1862d697267075edff64dcea5cf196cc187a8c5
57,046
def collect_mysqldump_options(config, mysqldump, client): """Do intelligent collection of mysqldump options from the config and add any additional options for further validation""" options = [] if config['flush-logs']: options.append('--flush-logs') if config['flush-privileges']: if ...
c1e1b45bf62b6b7c5c8701bb78cc198cde4c2a16
57,047
from .model import Model from .detail.model_implementation import ( force_offset_model, offset_model_jac, offset_model_derivative, offset_equation, offset_equation_tex, ) def force_offset(name): """Offset on the the model output. Parameters ---------- name ...
127aa452877e12d95850d98bbcc8416c15e2df10
57,048
import logging import six import os def compare_test(test_sut, test_ref, rtol, atol): """Compare the results of a single test against a benchmark. Args: test_sut: SUT test test_ref: benchmark test tolerance: relative precision at which results considered compatible Returns: boole...
7f571aa808dd11ff54fe4a75dd9cea6c11d70031
57,049
import copy import os import logging def create_environment(preamble): """ Create a dictionary of variables obtained from the preamble of the task file and the environment the program is running on. """ environment = copy.deepcopy(os.environ) for line in preamble: logging.debug(line) ...
f47793231594370d65a804b63d4925f466eb5277
57,050
def parse_user_agents(text): """.""" user_agents = ioc_grammars.user_agent.searchString(text) return _listify(user_agents)
dede1b1b5ce99e663efc891466683e7ac13af9eb
57,051
def featurizeDoc(doc): """ get key : value of metadata """ doc_features = [] for key in doc: doc_features.append("{0}: {1}".format(key, doc[key])) return doc_features
7204fe1ded828112e69c120c944a5a16cc00f628
57,052
def get_lsr_pwaves(p_idx, lsr, post_stim=0.1, sr=1000., lat_th=0): """ Get indices of laser-triggered P-waves, spontaneous P-waves, successful laser pulses, and failed laser pulses @Params p_idx - indices of P-waves lsr - laser stimulation vector post_stim - P-waves within $post_stim s of la...
5e27bc106d649d4924e9ff5e2a6894ebb995f39d
57,053
def get_flux(shot, time, phis=[222.5*deg2rad], labels=['TS']): """ """ flux_grids = {} flux = {} for label,phi in zip(labels,phis): flux_grids[label] = get_flux_grid(shot, time, phi=phi) # Build the interpolation functions for label in labels: sample_coords = list(zi...
ef2d2d78f76ae3c0a61336b3b3ab038eb0fa204d
57,054
def log_sum_exp(Z): """ Compute log(\sum_i exp(Z_i)) for some array Z.""" return np.max(Z) + np.log(np.sum(np.exp(Z - np.max(Z))))
808329e0cfe14e124433cb0ad48eb4e4f78ebe14
57,055
def f(f_prob): """Deterministic forecast matching observation o.""" return f_prob.isel(member=0, drop=True)
4163e9a40916bd6c1dbf00e6ed635cf2b78bcfc7
57,056
def setup(the_model, rolling_length, rolling_radius, vertical_load, cycles=[1], speed=1.0, slip=0.0, rail_ext=0.0, num_cycles=1, initial_depression=0.1, inbetween_step_time=1.e-6, inbetween_max_incr=100, max_incr=1000, min_incr=100): """Setup the loading for the rollover simulation ...
b76efc23a43986fed7032ede6c707227d6de267c
57,057
def wait_for_handshake(sim, ifname, basename="s_axi_control_", dataname="DATA"): """Wait for handshake (READY and VALID high at the same time) on given interface on PyVerilator sim object. Arguments: - sim : PyVerilator sim object - ifname : name for decoupled interface to wait for handshake on ...
41f35cf15751fab44bca275cc2381e83e8908cd1
57,058
import os def get_archives(archives=None): """Get a matching between version and path from archives or `metalk8s.archives` from pillar if archives is None Arguments: archives (list): list of path to directory or iso """ if not archives: archives = __pillar__.get('metalk8s', {}).ge...
0f6235db5fda4f07cc6b280c92b81964bac2f827
57,059
def mysin(x): """ My sine. Note that this is only accurate for small x. """ return x
9589b1a3106b13ff230e614dcfc1477b422c9879
57,060
import logging def get_module_logger(module_name, level=None): """ Get a logger for a specific module. :param module_name: str Logic module name. :param level: int :param sh_level: int Stream handler log level. :param log_format: str :return: Logger Logger object. ...
0fd2c8be1463da464700964c2d5ad895a40f4a9c
57,061
from typing import Optional def get_transit_gateway_multicast_group_source(group_ip_address: Optional[str] = None, network_interface_id: Optional[str] = None, transit_gateway_multicast_domain_id: Optional[str] = None, ...
a834db7d20610870ae7c64d0bae139ed262f9341
57,062
import glob def getAllOfAFile(file_dir, ext): """ Returns a list of all the files the direcotry with the specified file extenstion :param file_dir: Directory to search :param ext: The file extension (IE: ".py") """ return glob.glob(file_dir+"/*"+ext)
876a4f4b30653bd08454db9ee425d56fe408623d
57,063
def support_jsonp(f): """Wraps JSONified output for JSONP""" @wraps(f) def decorated_function(*args, **kwargs): print('s') callback = request.args.get('callback', False) if callback: content = str(callback) + '(' + str(f().data) + ')' return current_app.respon...
0ccfed2ef7702a0d364376e84b1eb3bd1c917d68
57,064
def topk(x_in, weights, num_top_k, verbose=False): """ x_in: BNK4 weights: BNK num_top_k: int """ # rate num_kp = tf.shape(weights)[2] # num_top_divider = config.num_top_divider # num_top_k = tf.to_int32(num_kp / num_top_divider) B = tf.shape(weights)[0] num_pairs = tf.shape(...
d90bedffb6d5b406ff0406eb0d367dab1760858a
57,065
def accumulate_strings(values, name="strings"): """Accumulates strings into a vector. Args: values: A 1-d string tensor that contains values to add to the accumulator. Returns: A tuple (value_tensor, update_op). """ tf.assert_type(values, tf.string) strings = tf.Variable( name=name, in...
2b59fe76c6c74d378db2ebe3521c72c3ab3cbc2a
57,066
def interference_point(img, img_name,fileInterferencePath, x=0, y=0): """点降噪 9邻域框,以当前点为中心的田字框,黑点个数 :param x: :param y: :return: """ filename = fileInterferencePath + img_name.split('.')[0] + '_interferencePoint.jpg' # todo 判断图片的长宽度下限 cur_pixel = img[x, y] # 当前像素点的值 height, width...
ed1533c63ac497841989f25a738a7fd5ce7e80f5
57,067
from typing import List import tqdm def sliding_convert_examples_to_features( examples: List[InputExample], label_list: List[str], max_length: int, tokenizer: PreTrainedTokenizer, ) -> List[InputFeatures]: """ Loads a data file into a list of `InputFeatures` """ label_map = {label: i ...
50d2cf1f7aa94801aa91d3c39226a7b230bbdf7d
57,068
def http_date(epoch_seconds=None): """ Format the time to match the RFC1123 date format as specified by HTTP RFC7231 section 7.1.1.1. `epoch_seconds` is a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, it defaults to t...
91f6fb9cd8ca69959669661d2a4ffe2c2d1fbfa2
57,069
def rms_error(observed_values, estimated_values): """Root-mean-squared Error function.""" N_values = np.prod(observed_values.shape) sse = ss_error(observed_values, estimated_values) rmse = sse_to_rmse(sse, N_values) return rmse
7899752378a38796fcc7974c3ff5728dd3a8744d
57,070
def parse(data, raw=False, quiet=False): """ Main text parsing function Parameters: data: (string) text data to parse raw: (boolean) unprocessed output if True quiet: (boolean) suppress warning messages if True Returns: List of Dictionaries. Raw ...
cac4424857335484e9ef9258d6742e487d5d40d0
57,071
def convert_onnx_sub(operator, device=None, extra_config={}): """ Converter for `ai.onnx.Sub`. Args: operator: An operator wrapping a `ai.onnx.Sub` model device: String defining the type of device the converted operator should be run on extra_config: Extra configuration used to sele...
4cfb98714ec23e1ea3e70be1bdede0fb805afd63
57,072
def infer_tree_dp(model: PairWiseFiniteModel, subtree_mp=False) -> InferenceResult: """Inference using DP on tree. Performs dynamic programming on tree. Applicable only if the interaction graph is a tree or a forest. Otherwise throws exception. :param model: Model for which to p...
e5cd16e5229846c2e038d47885fd5b6c477f20f6
57,073
from typing import Union import platform def get_platform_ca_certs() -> Union[bool, str]: """Get correct platform value for 'verify' parameter specifying CA certificates for TLS @return: (bool or str) True for Windows, LINUX_CA_FILE for Linux""" if platform.system() == 'Windows': return True ...
396edecf3e78c9e1171e4e08fc2cb1410e562f49
57,074
import subprocess def out(*command, **keys): """Run a subprogram and return it's stdout.""" keys = dict(keys) keys["stdout"] = subprocess.PIPE return _sh(command, **keys).stdout
b79c3b603d4df2caee2432f6d3d4c87019dbab82
57,075
def set_weight_decay(model, weight_decay, skip_list={"decoder.attention.v", "rnn", "lstm", "gru", "embedding"}): """ Skip biases, BatchNorm parameters, rnns. and attention projection layer v """ decay = [] no_decay = [] for name, param in model.named_parameters(): if not param.requir...
7e2702d544497b03fffda4558f4aa5fcd2dd4f43
57,076
def extract_sample_info(sample_str): """Extract kit, sample, and technical replicate from sample_str. Inputs - sample_str - string from sample name Returns - tuple (kit, biological sample name, technical replicate) """ s = sample_str.replace('Ftube', '') # The biological sample...
f67440528391e1c463bb940cad9e59e8e61aa4c3
57,077
def OffsetPosition(in_ra,in_dec,delta_ra,delta_dec): """ Offset a position given in decimal degrees. Parameters ---------- in_ra: float Initial RA (decimal degrees). in_dec: float Initial DEC (demical degrees). delta_ra: float Offset in RA (decimal degrees). ...
7b027a2e0bf87dba9d1136e68af258b21223cedb
57,078
def input_checks(catalogue, config, completeness): """ Performs a basic set of input checks on the data """ if isinstance(completeness, np.ndarray): # completeness table is a numpy array (i.e. [year, magnitude]) if np.shape(completeness)[1] != 2: raise ValueError('Completeness T...
4fb5e2a3241a2953ae2432add64dc69c1c2af4f6
57,079
def mad_outliers(x, cutoff=2, z_score_coeff=0.6745): """ Median Absolute Deviation outliers method. It returns values as outliers if their residuals relative to the median exceeds 'n' times the ratio to the MAD. The cutoff parameter represents this 'n' times quantity. Main code: x_mad = np...
0718a71d2fcde75356f016df4c56621534b379a7
57,080
def function_executor(type=None, mode=None, config=None, backend=None, storage=None, runtime=None, runtime_memory=None, workers=None, rabbitmq_monitor=None, remote_invoker=None, log_level=None): """ Generic function executor """ return FunctionExecutor( ...
3b0fe732f0c87b13da44bae460d486608b685694
57,081
def create_mssql_adapter_with_integrated_security( server: str, db_name: str, port: int = 1433, encrypt: bool = False, trust_certificate: bool = False, ) -> Adapter: """ Creates a SQL Alchemy database engine for Microsoft SQL Server, using integrated security (aka SSPI, aka Windows domai...
74f721a2a474dcbb92b742a5919b39a8473895f0
57,082
def datetime_isoformat( tdt, format=DATE_EXT_COMPLETE + "T" + TIME_EXT_COMPLETE + TZ_EXT ): """ Format datetime strings. This method is just a wrapper around isodate.isostrf.strftime and uses Extended-Complete as default format. """ return strftime(tdt, format)
269d675600a10ca75b754e2f4c9b92cf46f94ef5
57,083
def get_prime_factors(n): """ Find all prime factors in N and return them as a list. """ i = 2 factors = set() while n > 1: if n % i == 0: factors.add(i) n = n / i else: # only increment if we did not find a factor. i = i + 1 i...
da6f13b1c910f4b90cf84bbb7cfe6ecc2b735863
57,084
import tqdm from pathlib import Path import concurrent def download_list(uids, username, password, outdir, threads=1, show_progress=True): """Downloads a list of UIDS Parameters ---------- uids: A list of UIDs username: Username password: Password outdir: O...
4a7b4f7724b41fb05580ebd2540c73b77b31d0ac
57,085
def ping(): # pragma: no cover """ ignore connection validation with task server (celery) """ """Simple task that just returns 'pong'.""" return "pong"
9967a01f8c509e272e7215a843e513ce4dc9a2be
57,086
def deep_index_items_by(items, key): """ Index a list of dicts by a given key. Returns a dict of the arrays of items based on the value of `key` in each item. """ index = {} for item in items or []: try: index_key = str((dpath.util.get(item, key) or "")).lower() excep...
1ce8788aab61401d3767c4d00e5cd1c477b1010f
57,087
from typing import Optional def from_pytest_fixture( fixture_name: str, method: Optional[Filter] = NOT_SET, endpoint: Optional[Filter] = NOT_SET ) -> LazySchema: """Needed for a consistent library API.""" return LazySchema(fixture_name, method=method, endpoint=endpoint)
7dc126978cb2e7aed9dc24e012d4d89a2fe3ea8c
57,088
def get_database_user(config, credentials): """ Returns the database user from the credentials. """ return credentials.get('user', 'unknown')
90e0a25a888e2de73ea7688a4da2e5de2ae02fbb
57,089
def extract_region_with_index(image, region_index, labeled_image): """ Helper function that masked the labeled image on the input image, and extract the region with corresponding region index in the labeled image from the input image :param image: input image shape=(row(height), col(width)) :type i...
93b861b26fad90b93bcc6a7fb79bbea7c542ed88
57,090
from typing import OrderedDict def _list_to_dict_list(list_items): """ Takes a list and creates a dict with the list values as keys. Returns a list of the created dict or an empty list """ if list_items: k = OrderedDict() for item in list_items: k["%s" % item] = "" ...
48e3448b79530e4bc7c4674a168429208b9f62b4
57,091
def dms2deg(valin): """ Converts DMS input to decimal degrees. Input can be either a string delimeted by : or spaces, or a list of [D,M,S] numbers. Parameters ---------- valin: float Input value in DMS. Can be either: \n - a string delimeted by : or spaces \n - a lis...
3efac9d11c8a7b5933766a0610f49a884e20925b
57,092
def spherical_to_cartesian(spherical): """ Convert a numpy array (Nx3) from spherical coordinates to cartesian coordinates We use the mathematical notation (radial, azimuthal, polar) :param spherical: numpy.array :return: numpy.array """ spherical = np.array(spherical).reshape(...
d5379a32c6d1eebe5fbc8b54585f3e98d678fe40
57,093
def filterAudio(audio_signal, sr, filename="jack-audio.wav", signal_length=MAX_SIGNAL_LENGTH): """ Performs Wiener Filtering on a 1D numpy audio array :param clean_signal: 1D numpy array containing the signal of a clean audio file :param sr: sample rate of audio :param filename: string of the audio ...
c03c552c193fa0ecd84aca30d6527573ecac9b6a
57,094
def maybe_split_sequence_lengths(sequence_length, num_splits, total_length): """Validates and splits `sequence_length`, if necessary. Returned value must be used in graph for all validations to be executed. Args: sequence_length: A batch of sequence lengths, either sized `[batch_size]` and equal to ei...
065291a8b46d9d8df9cf28b44ae7272b1e4917f0
57,095
def attr_is_iterable( member_validator, # type: AttrsValidator iterable_validator=None # type: Optional[AttrsValidator] ): # type: (...) -> AttrsValidator """ The equivalent of `attr.validators.deep_iterable` added in Attrs 19.1.0, but we still support older versions. """ # noinspection P...
2f0f31029fd81adcc79f7451261b589a12da492d
57,096
import socks import supybot.conf as conf import socket def getSocket(host, port=None, socks_proxy=None, vhost=None, vhostv6=None): """Returns a socket of the correct AF_INET type (v4 or v6) in order to communicate with host. """ if not socks_proxy: addrinfo = socket.getaddrinfo(host, port) ...
6bc509383f3b574c578df6bf52aafca1a1b2d6e4
57,097
def square_loss(labels, predictions): """ Square loss function Args: labels (array[float]): 1-d array of labels predictions (array[float]): 1-d array of predictions Returns: float: square loss """ loss = 0 for l, p in zip(labels, predictions): loss = loss + (l -...
dda95c44073215cec19ed4f4ff8224ad46729ceb
57,098
import fnmatch from concurrent.futures import ThreadPoolExecutor import os def run_each_async(path: str, glob: str, func, pool_size:int =max(1,os.cpu_count()-1)): """ Scan files and run in a multi-process fashion. The func must return True if make some changes The function must AVOID calling not hr...
7537756f6abe9da7bdfa0bb8c3118377cf3dae3a
57,099