content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def log5(mean, *args): """Calculate expected value given mean and samples from the population""" odds0 = mean / (1 - mean) odds = args[0] / (1 - args[0]) / odds0 ** (len(args) - 1) for arg in args[1:]: odds *= arg / (1 - arg) return odds / (odds + 1)
64d129c4d1da18492cc9a66aa40a4499479f8c12
686,539
from typing import Optional from typing import Tuple import cgi def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]: """Tease out the content-type and character encoding. A default character encoding of UTF-8 is used, so the content-type must be used to determine if any deco...
e6ae570ff6bf65fce4000d8d5216f8977f6a19a0
686,541
def extract_source(file_name): """ Allows to detect the source contained in the file name of a document. """ splited = file_name.split("/") return splited[len(splited) - 1].split("_")[1]
912a1f323917a3cc2ad8920f4a56938590c1c336
686,542
def cisfun(text): """ Receive string and print it""" text = text.replace('_', ' ') return 'C %s' % text
e5d4b75e5ef92635e271a0aac95106d81fca56c6
686,543
def ranked_vaccine_peptides(variant_to_vaccine_peptides_dict): """ This function returns a sorted list whose first element is a Variant and whose second element is a list of VaccinePeptide objects. Parameters ---------- variant_to_vaccine_peptides_dict : dict Dictionary from varcode.Var...
e775eff9c84a0404dfd5165b3116c5a661c475e3
686,544
import os def init(dataset_id, api_key, download_dir_path): """ Initiates a dictionary with keys needed to use the HDA API. Parameters: dataset_id: String representing the WEkEO collection id api_key: Base64-encoded string download_dir_path: directory path where data shall be...
cfcdc4799b15b4a097ae4bcd942f4a0c0b90391d
686,545
def get_coord_by_index(da, indx): """ Take an Xarray DataArray, return a coordinate by its index in the order of the data structure. E.g. if var is defined on: ('time', 'lat'), indx=0 will return the coordinate labelled as 'time'. """ coord_name = da.dims[indx] return da.coords[coord_name]
c6b2710351e71f6d17f5b50a8759a30811e4a41c
686,546
from typing import Tuple from typing import Iterable def encode(data: bytes) -> Tuple[bytes, Iterable[int]]: """Encode the given data to be valid ASCII. As we recommended in the exercise, the easiest way would be to XOR non-ASCII bytes with 0xff, and have this function return the encoded data and the...
1053211abab4f93f65e11dbb1307fc674ed30742
686,547
def variance(hist:dict): """Compute the variance of an histogram. :param hist: the histogram :type hist: dict :return: the variance of the histogram :rtype: float """ vl = list(hist.values()) m = sum(vl) / float(len(vl)) return sum([(m - v)**2 for v in vl]) / float(len(vl))
87124db6bc41757fd899177fb935c0023d007140
686,548
def to_dict(**kwargs): """Create a dictionary from keyword arguments""" dict = locals() return dict['kwargs']
e75c3db742398b79b0d4420b199f23a6bedfe0f8
686,549
def cat_to_num(cleaned): """ Function to convert categorical values into numerical values to use for classifiers """ cleaned.loc[(cleaned.H1B_DEPENDENT=="Y"),"H1B_DEPENDENT"] = 1 cleaned.loc[(cleaned.H1B_DEPENDENT=="N"),"H1B_DEPENDENT"] = 0 cleaned.loc[(cleaned.CASE_STATUS == "CERTIFIED"),"CASE_...
c1c7a75f61908176d1a0d3ce6a954d913b32da92
686,550
def calculate_safety(vuls): """ 通过漏洞等级返回对应正式名称 :param vuls: :return: """ for vul in vuls: if vul['level'][0] == '高': return '高危' elif vul['level'][0] == '中': return '中危' elif vul['level'][0] == '低': return '低危' return '健康'
592e955aa230b8abb76942a8f9ce02f6f55b2f05
686,551
def read_from_txt(txt_file: str = "ww2_words.txt") -> list: """Opens a text file to get all words""" with open(txt_file, "r") as words: lines = words.readlines() return [line.split(".")[1].lower().replace(" ", "").strip() for line in lines]
956054804c0e9f0e3557faca9165a418a877ee45
686,552
import base64 import io def mpl_png(fig) -> str: """Return the base64 encoded png string of a matplotlib figure. Parameters ---------- fig : Figure Matplotlib figure Returns ------- str Figure base64 encoding """ f = io.BytesIO() fig.savefig(f, format="png", ...
7e11fdeeceef128141ff63cfd4cbbacfa40cca8f
686,553
import subprocess import sys def get_abspath(exec_name): """ Get absolute path for exec file, return none if not found """ proc = subprocess.Popen(['which', exec_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) outs, errs = proc.communicate() bin_path = outs.decode(sys.stdout.encoding).rstrip('\...
500fbffa2dc70a5509bc2ff5f9a00c8a881b8ba1
686,554
def conway_cross_product_doubled_power(self, p): """ Computes twice the power of p which evaluates the 'cross product' term in Conway's mass formula. INPUT: `p` -- a prime number > 0 OUTPUT: a rational number EXAMPLES:: sage: Q = DiagonalQuadraticForm(ZZ, range(1,8)...
df3d0a12562e3880af9542d2c0f5ac7566d3f1d9
686,555
import collections def compute_f1(hypothesis_list, reference_list, eps=1e-8): """ Computes token F1 given a hypothesis and reference. This is defined as F1 = 2 * ((P * R) / (P + R + eps)) where P = precision, R = recall, and eps = epsilon for smoothing zero denominators. By default, eps = 1e-8. ""...
0d4c4cec2dcd91791b2e00c8792ed2ea5d9e814b
686,556
def new_workbook_text(db): """ Returns xl/workbook.xml text :param pylightxl.Database db: database contains sheetnames, and their data :return str: xl/workbook.xml text """ # location: xl/workbook.xml # inserts: many_tag_sheets xml_base = '<?xml version="1.0" encoding="UTF-8" standalo...
b829d4f449570b58ee3008d0eb740afcb081ab0e
686,557
def badAddEm(somelist): """ try to return sum of numbers in somelist but something goes wrong... """ total = 0 for num in somelist: total = total + num return total
2fdf30a4ab45a4391e558e50ab146aaeb99c6ab0
686,558
def df_to_frame(self): """ """ return self
3fab5a488f11009911c05d609173ca66c98e4b9c
686,559
def get_p_key(episode_info): """ create the primary key field by concatenating episode information :param episode_info: Dictionary of a single episode """ return f'{episode_info["show_stub"]}S{episode_info["season"]}E{episode_info["episode"]}'
f1f7b497aae69a715c312c2de4384f53ee1755d8
686,560
import logging import smtplib def get_gmail_client(gmail_username, gmail_password): """Attempts to get a gmail smtp client""" logging.info("Connecting to smtplib server") email_client = None try: email_client = smtplib.SMTP("smtp.gmail.com", 587) email_client.ehlo() email_clien...
7cb5c338cd5ca3cb67b45770c090c86bd6a6a6dd
686,561
def wikipedia_link(pred_lab): """ Return link to wikipedia webpage """ base_url = 'https://en.wikipedia.org/wiki/' link = base_url + pred_lab.replace(' ', '_') return link
44f4ff1702c57ff8cc73eafd02370b8dfe280c7a
686,563
def getRenderProgress(): """ getRenderProgress() -> Returns the progress of the render of a frame from 0 - 100 % complete. @return: The progress of the render. Can be 0 if there is no progress to report. """ return int()
dfef48d2c69040dd7cb5361e25585a029bca3ec4
686,564
def check_on_not_eq_vals(val1, val2): """ Func which check values on non equivalent and return tuple of vals. :param val1: :param val2: :return: """ return (val1, val2) if val1 != val2 else (val1,)
84888e02856c897263b4a7aa8080968333f4e619
686,565
def query_db(sqldb, query, args=(), one=False): """Queries the database and returns a list of dictionaries.""" cur = sqldb.execute(query, args) rv = cur.fetchall() return (rv[0] if rv else None) if one else rv
6bafca17825637d4e4b8d6b6c6e5c3c8a65d8258
686,566
from typing import List def maxCrossingSum(arr: List[int], start: int, mid: int, stop: int): """Helper Function - Find the max crossing sum w.r.t. middle index""" leftSum = arr[mid] # start point leftMaxSum = arr[mid] # Keep track of maximum sum # Traverse in reverse direction from (mid-1) to start ...
61c334b5a9d1857fb54a0518a992ef9c756f57a2
686,567
from datetime import datetime def parse_date(date_str, format='%Y%m%d', to_format=None): """ :param date_str: :param format: :return: """ if to_format is not None: return datetime.strptime(date_str, format).strftime(to_format) else: return datetime.strptime(date_str, forma...
27159509203c39a236d4e1c7ed1ec724f16cd09b
686,568
def filter_by_interface(objects, interface_name): """ filters the objects based on their support for the specified interface """ result = [] for path in objects.keys(): interfaces = objects[path] for interface in interfaces.keys(): if interface == interface_name: ...
9c0d9c64fab46aedfd2c9b4ca0ae9f8beafc6891
686,569
import codecs def determine_encoding(file_header): """Check file header if it contains byte order mark (BOM) Args: file_header: Returns: """ bom_info = ( (b'\xc4\x8f\xc2\xbb\xc5\xbc', 6, 'cp1250'), (b'\xd0\xbf\xc2\xbb\xd1\x97', 6, 'cp1251'), (b'\xc3\xaf\xc2\xbb\x...
712fa5729c6851fc18581cf830182ef23a5a17c3
686,571
def get_attack_name(node): """Returns the first of the three '|'-delimited fields in the 'text' field of the child 'attack' node.""" for child in node.iterchildren(): if child.tag == 'attack': return child.text.split('|')[0]
5ecdb060814fd94ff749718d50d9b8601351e5b4
686,572
def clean_html(html_text): """ Converts <1 to 1 in html text""" return html_text.replace("><1<", ">less than 1<")
d07db5cf23445aa9a6e6782a8de089299ec30dc4
686,573
def occupancy_accuracy(gt, pred): """Compute occupancy accuracy of numpy tensors.""" return (gt == pred).sum() / float(gt.size)
e3eb56650978d33f1e1c61d0128695ec2fc399d8
686,574
def get_emojis_in_tweet(tweet, emojis_ours, emojis_theirs, emojis_popular, tokenizer): """Get a list of all the emojis in a tweet based on the sets provided Args: tweet: Tweet emojis_ours: Emoji vectors trained on our model emojis_theirs: Emoji vectors trained on an external model ...
350d858131adca90484c564c1c51eadad8a34dba
686,575
import select import sys def read_input_from_pipe(): """ Read stdin input if there is "echo 'str1 str2' | python xx.py", return the input string """ input_str = "" r_handle, _, _ = select.select([sys.stdin], [], [], 0) if not r_handle: return "" for item in r_handle: ...
c09736c53d2912a0a7a45034ef712f42db8da898
686,578
def _get_winsdk_full_version(repository_ctx): """Return the value of BAZEL_WINSDK_FULL_VERSION if defined, otherwise an empty string.""" return repository_ctx.os.environ.get("BAZEL_WINSDK_FULL_VERSION", default = "")
bc14431495312ee910bb9e9e69eb05b571f63deb
686,579
def function(model, x0): """ datas to be tested (from the model) """ model.set_initial_state(x0) _,X = model.meanFieldExpansionTransient(order=0, time=3) _,X1,V1,_ = model.meanFieldExpansionTransient(order=1, time=3) _,X2,V2,A2,_ = model.meanFieldExpansionTransient(order=2, time=3) value...
686314c7a74bab71bb8c02bc877733c6a1386434
686,580
def asses_quality(spec, negative_threshold_percent=20): """ // default - 0 = default // good - 1: to be defined - 2: to be defined // bad - 3: Pointing Problem - 4: more than `negative_threshold_percent` of the flux is negative - 5: A science target with no WCS """ if "...
752c97be8f0752ae7aad02b93afde77f8a36fd39
686,582
import os def get_model_names(filenames): """ Takes a list of files and removes the drive and path, only returning a list of strings with that reference stored models. Args: filenames (list): List of absolute paths. """ result = [] for _f in filenames: _drive, path = os.pat...
d4c773d4dc1487d60e56c24c266b08a9146ef881
686,583
def _soversion(target, source, env, for_signature): """Function to determine what to use for SOVERSION""" if 'SOVERSION' in env: return '.$SOVERSION' elif 'SHLIBVERSION' in env: shlibversion = env.subst('$SHLIBVERSION') # We use only the most significant digit of SHLIBVERSION ...
e1090f21e6afc9d6b266b4d1680377ec8d1a7e53
686,584
import os def construct_dividing_line(title='', padding='-'): """ Return a dividing line. """ try: term_width = os.get_terminal_size().columns except OSError: term_width = 120 side_width = max(0, (term_width - len(title)) // 2 - 1) if title == '': return padding *...
610f04e0a2908a51780396f8058cb52d6416e004
686,585
def mask_offset(y_true, y_pred): """Pre-process ground truth and prediction data""" offset = y_true[..., 0:4] mask = y_true[..., 4:8] pred = y_pred[..., 0:4] offset *= mask pred *= mask return offset, pred
6d7642718d989127f47e7575884a791da56e7c40
686,587
def timeline_postprocessing(timeline): """ Eliminates Nones in timeline so other software don't error. Extra lists are built for the vars with nones, each list with one point for each None in the form (wall_time, prev_value). """ current_time_nones = [] audio_time_nones = [] old_curr...
51ebfed147a5b4054ca03ab5b9b7108c395ea61d
686,588
import argparse def get_parser(): """ Create a parser and add arguments """ parser = argparse.ArgumentParser() parser.add_argument('-d', '--depth', type=int, default=4, help='minimum read depth') parser.add_argument('-p', '--pmtsize', type=int, default=1000, help='promoter size') parser.ad...
190bd818066f9b04ca8c05051ed597b1b89f4c2c
686,589
def extendImages(center, left, right, steering, correction): """ Extend the image paths from `center`, `left` and `right` using the correction factor `correction` Returns ([imagePaths], [steerings]) """ imagePaths = [] imagePaths.extend(center) imagePaths.extend(left) imagePaths.extend(r...
235883b4b04ed33cf36e8c0fbdb6f47c4645d95a
686,590
from typing import Callable def linear_schedule( initial_value: float, final_value: float, end: float = 0 ) -> Callable[[float], float]: """ Linear learning rate schedule. :param initial_value: Initial learning rate. :param final_value: Final learning rate :param end: Progress remaining where...
0363718b080ee9c111e25e1d32b96245d18ec0fc
686,591
def input_name(name): """specifies the name of the input the web service expects to receive. Defaults to 'input1'""" def l(func): func.__input_name__ = name return func return l
39c74818545bf0e28a3f008708661a81a0c0f1d5
686,592
import torch def get_activations(model, results): """After running evalu, pass the model and results to collect the layer activations at each timestep during experimentation Assuming the model is a FlexBase network Args: model (FlexBaseNN): loaded policy and model results (dict): dict...
8b3e58e7e13ecf789533f1a826ad3c26fd0b5689
686,593
import os def read_list(list_path): """Read list.""" if list_path is None or not os.path.exists(list_path): print('Not exist', list_path) exit(-1) content= open(list_path).read().splitlines() return content
4843602b10ad2549a36919b3f256c1564793ebd6
686,594
def is_target_platform(ctx, platform): """ Determine if the platform is a target platform or a configure/platform generator platform :param ctx: Context :param platform: Platform to check :return: True if it is a target platform, False if not """ return platform and pla...
7c48e886f15beba0f2350aee4a6b1a8aef408537
686,595
def convert_station_group_to_dictionary(group): """ Takes station group in format: [[station, component, network, location, start, end], [..], ...] and returns its dictionary representation: { station: <station>, components: [component1, .., componentN], network: <network>, location:...
f06e83188fe81f59fe6a18dc02704b47f17fbe6d
686,596
def ROI_df_subset(vcf, chrom, start, end): """ subset a single vcf based on genomic coords""" chrStr = 'chr' + str(chrom) keep0 = vcf['CHROM'] == chrStr vcf_sub0 = vcf[keep0] keep1 = vcf_sub0['POS'] >= start vcf_sub1 = vcf_sub0[keep1] keep2 = vcf_sub1['POS'] <= end vcf_sub2 = vcf_sub1[keep2] return...
699f90098bd800f11d980fea5b75bae270eb00e0
686,597
def get_max_lat(shape): """ It returns the maximum latitude given a shape :param shape: country shape :return: the max latitude """ return shape.bounds[3]
f165ac6158a874afb454bdca5fc2be59b64730d1
686,599
def get_card_group(card, idolized): """ Returns an identifier for a card's group, to help separate them by rarities :param card: card data from schoolido.lu api :param idolized: True if idolized version :return: card group name """ return "%s-%s%d" % (card['rarity'], card['attribute'], 1 if ...
d675a1c575b5e212172116eb23d97fab95ab9d32
686,600
def parse(address): """Parses the given MAC address and transforms it into "xx:xx:xx:xx:xx:xx" form. This form of expressing MAC addresses is the most standard one. In general, the "address" parameter accepts three forms of MAC address i input: - '1234567890af', - '12-34-56-78-90-af' (wi...
5bf3e63e35872b01c01f3462354bb33f27c8f7b9
686,601
def desempata_tamanho(indexes_max, dist_obj): """ Escolhe a regra com maior tamanho. :param indexes_max: Lista com os indices das regras com maior frequência no corpus. :param dist_obj: Lista com objetos do tipo Edit_distance que guardam as informações da distância do elemento frásico a cada regra. :return: Lista...
322167e2a144c61722948278adb90e7aa94b91c8
686,602
def transform_verbal_answer(response_to_be_transformed): """ Checks Parameters ---------- response_to_be_transformed : TYPE DESCRIPTION. Returns ------- num_answer : TYPE Transforms verbal answers to numerical form. 1=strongly disagree, 2=disagree, 3 = neither a...
fd4e3cfd3fa841ca322994dff2a7c149df799ef3
686,603
import numpy def ks_statistic(data1, data2): """Calculate the Kolmogorov-Smirnov statistic to compare two sets of data. The empirical cumulative distribution function for each set of set of 1-dimensional data points is calculated. The K-S statistic the maximum absolute distance between the two cumula...
21286861e65d373ebe4645f8ae8f363e7b5b2d85
686,604
def add_mask(sentence, mask_token, depth=1, ending="."): """ Helper function to add masks to the end of a sentence. By default and in the paper, we only adding one mas to the end of the descriptor sentence. """ begin = sentence.strip() for i in range(depth): begin += " [MASK]" begin ...
213de8534a096432aece54788f463e2528bdad3d
686,605
def parse_mode(cipher_nme): """ Parse the cipher mode from cipher name e.g. aes-128-gcm, the mode is gcm :param cipher_nme: str cipher name, aes-128-cfb, aes-128-gcm ... :return: str/None The mode, cfb, gcm ... """ hyphen = cipher_nme.rfind('-') if hyphen > 0: return cipher_nme[h...
0c5f82465f3ab3ec4e4735ef86c825880c1db203
686,606
def get_coordinates(read): """ return external coordinates of aligned read bases """ fivep = read.aend if read.is_reverse else read.pos threep = read.pos if read.is_reverse else read.aend return fivep, threep
fa77cc9498598ab9e64c9f008a671e56636a932a
686,607
def add_drip_columns(cave_results_df): """ Calculates Drips per min Calculates Drip Rate Error Adds all as columns ad returns input df. Parameters ---------- cave_results_df : pandas dataframe Returns ------- cave_results_df : pandas dataframe """ # Data Conversions ...
c418af1c806eee9fd09a28ffb2e6cf92bc139f0b
686,608
import calendar def datetime_to_ms(dt): """ Converts a datetime to a millisecond accuracy timestamp """ seconds = calendar.timegm(dt.utctimetuple()) return seconds * 1000 + dt.microsecond / 1000
cd2ad394c478905988b145c5b8a2c242f7165674
686,609
def temp_gradient(x, y): """Calculate the temperature gradient for a point defined by its cartesian coordinates: x, y. """ # Could also use SymPy to calculate derivative tbh fx = -x / (x**2 + y**2) fy = -y / (x**2 + y**2) return fx, fy
e21e95133cfd803bb63b14aabe6cd27ab0a08d87
686,610
def create_links(pathway_name, db): """Create html links to pathway websites. """ pathway_name = pathway_name.replace('_', ' ') encodedPathway = pathway_name.replace(' ', '+') if db == 'Reactome': linked_name = '<a href=\"http://www.reactome.org/cgi-bin/search2?DB=gk...
d5b043e09af4bd48284f0702c17e48386e9e2518
686,611
def formula_to_flatzinc_float(formula): """Converts a formula to a MiniZinc model using floats.""" # print (formula) vardefs = [] constraints = [] boolvars = [] for i, n, t in formula: if t == "atom": if str(n.probability) == "?": vardefs.append("var bool: B%...
63e98968e0eef779dcd1fe15eb73eb4525fc620d
686,612
import math def get_tile_size(num_pixels, tile_size=400): """ num_pixels is the number of pixels in a dimension of the image. tile_size is the desired tile-size. """ # How many times can we repeat a tile of the desired size. num_tiles = int(round(num_pixels / tile_size)) # Ensure tha...
a139fdb8f4548dd2f8576f116943473475294bae
686,613
def b(b1, b2): """ Return the difference between b1 and b2. """ return b1 - b2
7073bd8bceea55e130709db6f8f5ec722d3670c6
686,614
import csv def load_examples(input_file): """Load data that we'll learn from""" with open(input_file) as f: reader = csv.reader(f) header = next(reader) assert header == ["From", "To"] examples_to_learn_from = [l for l in reader] return examples_to_learn_from
e49f9f81f6993aa100378a0777166ef2efbcecdc
686,615
def jaeger_service_name(staging_gateway, jaeger): """ Deploys template apicast gateway configured with jaeger. """ return staging_gateway.connect_jaeger(jaeger)
d21aa71fa4bd720ab8cbcebffb4b6f002a1ae92e
686,616
def sublist(full_list, index): """ returns a sub-list of contiguous non-emtpy lines starting at index """ sub_list = [] while index < len(full_list): line = full_list[index].strip() if line != "": sub_list.append(line) index += 1 else: break return sub_lis...
ee4ed5e730829a22cb825e39aa95b19e037dda00
686,617
def throttle_function(func, every_n=1000): """Return a copy of function that only runs every n calls. This is useful when attaching a slow callback to a frequent event. Parameters ---------- func : callable The input function. every_n : int Number of ignored calls before lettin...
09d3ae9b0bb635c60a856e8f8ab5e41d7160336e
686,618
def log_terminal(gv): """Custom logging on the terminal.""" # Install wrappers around the train and test wrap_inherits @gv.kwrap("train") @gv.kwrap("test") def _(mode): # Printed before we enter the block print(f"Start {mode}") yield # Printed after we exit the block...
3679324d5c93c8196a921a6d2a6a32cfd67801d8
686,620
import imp def load_model(model_name, X_train, y_train, optimization_parameters, sklearn_model=None): """ Loads the base model model with the specific parameters :param model_name: the name of the model :param X_train: training data (# of samples x # of features) :param y_train: labels for the tr...
201c0b66e5cce4236f9757e781e7a9428c53840e
686,621
def is_int(n): """Determines if a value is a valid integer""" try: int(n) return True except ValueError: return False
1e99dcc056971e030853fef23b10340b2d4bf3fb
686,622
def _bind_io(function): """ Lifts ``IO`` function to be wrapped in other container. In other words, it modifies the function's signature from: ``a -> IO[b]`` to: ``Container[a] -> Container[b]`` This is how it should be used: .. code:: python >>> import anyio >>> from returns...
e5a975650b7a8ce271137d0176761195619c9378
686,623
def _token_to_dict(name, prefix=None): """ Generates function that converts a token to a dict containing the token name as key. The length of prefix is stripped from the key. """ if prefix is not None: return lambda x: {name[len(prefix) :]: x[0]} return lambda x: {name: x[0]}
2c141bb780c45c3d1bd387ed1423f900cc8a3bdb
686,625
def keypoint_outside_bbox(kp, bb): """ Check if keypoint is outside box :param kp: co ordinates of keypoint(x, y) :param bb: bounding box details (x_top_left, y_top_left, x_bottom_right, y_bottom_right) :return: True if keypoint is outside of bounding box, else False """ x = kp.pt[0] y ...
a95c02dae09468bfadd5d88f16fdf40848ef343e
686,626
def write_stress_type(key, options, value, spaces=''): """ writes: - STRESS(SORT1) = ALL - GROUNDCHECK(PRINT,SET=(G,N,N+AUTOSPC,F,A),THRESH=1e-2,DATAREC=NO) = YES """ msg = '' str_options = ','.join(options) #print("str_options = %r" % (str_options)) #print("STRESS-type key=%s valu...
1f17c607f3d2a997b975877d3eb3bc07fdd82e3f
686,627
def isInt(string): """ Determine whether a string is an int @param string: the string to check @return True if the string is an int, False otherwise """ try: int(string) except: return False return True
400eebfd4c0eeac78e56fe026e5e7b5846f9df31
686,628
import random def splitlist(basiclist, numberoflists=2): """ splits a list in numberoflists lists and returns a list of lists. Each element in the mother list has the same probability to fall in every daughter list """ newlist=[(t,random.randint(0,numberoflists-1)) for t in basiclist] metalist=[[] for t in rang...
04a061e8c35d1f588b6104eae643199ee26fee2b
686,629
def root(): """ Root view returns the system status """ return {"status": "online"}
395f1b05fa2d80d8ced56a4a033a95b5bd8c33ab
686,630
def is_unlinked_account(user): """ Returns whether the provided user has authenticated via an InstitutionAccount not yet linked to a Uniauth profile. """ return user.username and user.username.startswith('cas-')
6090c8fc6e1eacb3063bc39178f3f8dc4757274c
686,631
def add_prefix_safely(token, prefix): """Attaches the passed in prefix argument to the front of the token, unless the token is an empty string in which case nothing happens and the token is returned unchaged. This can be important for avoiding accidentally making a meaningless token meaningful by modifying it with...
bccf22b4ecbac2de40796e0b46c2707142ab3a70
686,632
import argparse def parse_args(): """Parse command line arguments.""" p = argparse.ArgumentParser() p.add_argument('--input', type=str, help='path to the directory holding the images') p.add_argument('--output', type=str, help='path to write the CloudVolume') ...
403d011237ec8178a14d550c807ef37cdfdcd8f8
686,633
def in_bounds(lat, lon, corners): """ Return true if the lat lon is within the corners. """ return \ lat >= corners[0] and lat <= corners[2] and \ lon >= corners[1] and lon <= corners[3]
680512f122f7110ff20fdf85891d0f0b87df1b29
686,634
def hours2days(input_hours): """ Receive the hours and will return ow many days and hours there is in the input """ # Floor division to get the days but not the extra hours days = input_hours // 24 # Modulus to get the left hours after calculating the days hours = input_hours % 24 # Returns tupl...
fcd04352aa990154d55bd8c3352c717d06ad50f0
686,636
from typing import Any from typing import Callable def cache_control(**kwargs: Any) -> Callable[..., Any]: """ A decorator used to add cache control headers to a route's response. """ def decorator(obj: Any) -> Any: obj.__cache_control__ = kwargs return obj return decorator
995212cbe7ed7474ba56d8f0d186004492a1b316
686,637
import os def exist(filename): """does the file exist?""" return os.path.exists(filename)
5b3541b612416cf9be987e494dd9c6efda2bdb10
686,639
def class_name(obj): """Fetch the class name of an object (class or instance). Another cosmetic shortcut. The builtin way of getting an instance's class name is pretty disgusting (and long), accessing two hidden attributes in a row just feels wrong. :param any obj: The object you want the class n...
6e6e41df7d8eb4fe83f4bea7e763446805a55477
686,640
import typing import re def extract_ints(raw: str) -> typing.List[int]: """Utility function to extract all integers from some string. Many inputs can be directly parsed with this function. """ return list(map(int, re.findall(r"((?:-|\+)?\d+)", raw)))
6385360142bfa9ba39467a2f534404e48b48c528
686,641
def tokenize_description(description, has_name): """ Splits comma-separated resource descriptions into tokens. :param description: String describing a resource, as described in the ion-hash-test-driver CLI help. :param has_name: If True, there may be three tokens, the first of which must be the resource...
34c27f892a1c3e08782c33a28f0ce76a13934044
686,642
def group(group_name): """Marks this field as belonging to a group""" tag = "group:%s" % group_name return tag
0e602afc3721b88e3b6923264848da2100086f73
686,643
def get_sample_area_quantile(data, quantile, baseline_fpart): """ returns first sample index in hit where integrated area of hit is above total area """ area = 0 area_tot = data.sum() + len(data) * baseline_fpart for d_i, d in enumerate(data): area += d + baseline_fpart if area...
87367cbda41e317f1c56efdb8ff5c0750932e65f
686,644
from typing import Counter def _get_object_count_by_type(objects): """Counts Python objects by type.""" return Counter(map(type, objects))
49b29527e08b404dd5a56090c70c82d84768ad6a
686,645
def Sqr_Chord_Len_C3V(vec1, vec2): """Computes the square length of the difference between the two arguments. The arguments are assumed to be 3d vectors (indexable items of length 3).""" diff0 = vec1[0] - vec2[0]; diff1 = vec1[1] - vec2[1]; diff2 = vec1[2] - vec2[2]; result = diff0 * diff0 + di...
2d89ddaa35aba5cc7ee9d30d07086288c3b6194f
686,646
def set_binary_labels(input_examples, positive_label): """ Replaces the class labels with 1.0 or -1.0, depending on whether the class label matches 'positive_label'. Returns an array of tuples, where the first element is the label number and the second is a path to the image file. """ exam...
e610ffb8abf6ec5e672b0a5615e219e1489ff59a
686,647
def parse_d2s2c3_name(string): """ An S2Xxxx or a C3Xxxx or None. """ # Ex. S2RTbas result = None prefix = None if string.test_and_consume("D2"): prefix = "D2" elif string.test_and_consume("S2"): prefix = "S2" elif string.test_and_consume("C3"): prefix = "C3" if p...
1b5dd7ed409dae9dc9724e2af519d686dd40dc55
686,648
def _ExtractCommentText(comment, users_by_id): """Return a string with all the searchable text of the given Comment PB.""" commenter_email = users_by_id[comment.user_id].email return '%s %s %s' % ( commenter_email, comment.content, ' '.join(attach.filename for attach in comment.at...
7c372eb15805ca3f47b54c32ba9afb64208815dc
686,649
import io def collect_until_whitespace(file_desc: io.BufferedReader): """ Read from file until whitespace :param file_desc: file descriptor :return: """ res = b'' while True: new_sym = file_desc.read(1) if new_sym == b' ' or new_sym == b'': break res += ...
3f378ae888cf6606804a9271de4bbe6e386a122d
686,650