content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import random import string def rand_string(numOfChars): """ Generates a string of lowercase letters and numbers. That makes 36^10 = 3 x 10^15 possibilities. If we generate filenames randomly, it's harder for people to guess filenames and type in their URLs directly to bypass permissions. """...
5b8bcd85b516e54686c479fe46236853c6bd2aa5
627,733
def always_str_list(list_or_str): """Makes sure list_or_str is always a tuple or list Parameters ---------- list_or_str: str or str iterable (tuple, list, ...) Parameter to set as iterable if single str. Returns ------- Iterable Iterable equivalent to list_or_str.""" if...
5c3d6c6a0ca1667d92722740941bf17366175d06
627,734
def run_services(): """Run services for tests.""" return True
79c41f79e9df341e16efc5f798fa823ee81f93ac
627,735
def find_faces_at_edges(faces): """ For each edge on the mesh, find the two faces that share the edge. Parameters ---------- faces : list of lists of three integers the integers for each face are indices to vertices, starting from zero Returns ------- faces_at_edges : dictionar...
d8e05105a85e6c724e258ebbe949029047bd1a3f
627,736
def calc_iou(pred, label, threshold=0.5, ignore_index=255, merge=False): """ calc the intersection over union :param pred: N1HW or NHW, Tensor :param label: NHW or N1HW, Tensor :return: intsec & union sum """ pred = pred.view(pred.shape[0], -1) label = label.view(label.shape[0], -1) pred = (pred > thr...
9af054c3fcee88fd854ab0ac4f572f19ecb8aa76
627,737
def get_id_from_urn(urn): """ Return the ID of a given Linkedin URN. Example: urn:li:fs_miniProfile:<id> """ return urn.split(":")[3]
8fecec105617364cf3ed9e61764041d8960060f2
627,738
def comp_radius(self): """Compute the Radius of the Arc1 (for unification with other arc objects) Parameters ---------- self : Arc1 An Arc1 object Returns ------- radius: float radius of the arc """ self.check() return abs(self.radius)
3810bfbcb852ef94e1c60260b02ef0e0403a1799
627,740
def datetime_encode(obj): """Encode a datetime.""" return obj.isoformat()
53385cb9b50db652f71953a13856f83951f36826
627,741
def plot_scatter(data, fig, axis, config_dic): """ """ if type(data) is list: x = data[0] y = data[1] # size s = data[2] if len(data) > 2 else None # color c = data[3] if len(data) > 3 else None else: x = data[:, 0] y = data[:, 1] s...
ec092c3829e5ced93d0d3811346a417b84043d14
627,743
def derivative_sigmoid(y: int) -> float: """Calculate the derivative of the sigmoid function Args: y (int): the output of the sigmoid function of x Returns: float: the output of the derivative sigmoid function """ return y * (1 - y)
067bbce65924eee234a9e3635a649af6f39bb922
627,744
def ndistance(p1, p2): """ Calculate eucleidian distance between two points in N-dimensional space NOTE: The two points must have the same number of dimensions, thus having the same shape. Points' dimension is the same as their index...
1ea394b5491aff6fa872738e74caabc63c6ee13b
627,745
def gagne_couleur(carte1, carte2, carte3, carte4): """Affiche la carte qui remporte le pli en faisant attention aux couleurs : - la carte du premier joueur `carte1` donne la couleur attendue. - une carte qui n'est pas à la bonne couleur perd automatiquement. On ne gèrera pas certains cas incohé...
8f9cb19526d6cadaf84ad49f0d5f006eb271fe3d
627,746
def combine_results(first, second): """Sum objects in given tuples using the __add__ method of each object. e.g. foo[0] = foo[0] + bar[0] foo[1] = foo[1] + bar[1] return foo Used here to sum Method and Analyze objects together for trajectories read in chunks. ...
127c339715a397636ff0a954942163d2f5dfd541
627,747
def get_header(context, header_name): """Return all response header values that've been set for header_name.""" return [header[1] for header in context.headers if header[0] == header_name]
cc2fba51f028aa76b8864376d8010099de56cc50
627,748
import re def Escape(name): """Escapes characters that could interfere with the file system or try job parsing. """ return re.sub(r'[^\w#-]', '_', name)
583281573b28fde6c5ec01fdb2e7ca2a9d3645a1
627,749
def calculate_ngram_freqs_solution(ngrams): """Calculate the frequency of a subsequent word given a sequence of ngrams :param ngrams: [['i', 'will', 'be'], ['will', 'be', 'leaving'], ['be', 'leaving', 'florida']] """ freqs = {} for ngram in ngrams: # Differentiate successor (= lastWord) ...
66867cd4e269d23e1dc22803cde2baf2b5d9f6a4
627,750
import json def return_json_file(raw_json, file_name): """function that takes in the raw_json and makes it into a nicely formatted json file Args: raw_json(json object): Takes in a json object. file_name(string): file_name is the name of the file name you want to ...
4a08e284ace533c9ee6b3dacd33b53ed59f24b12
627,752
import math import torch def simpleLambda(x, scale, sigma=1.0): """ De-noising by Soft-thresholding. Author: David L. Donoho :param x: one block of wavelet coefficients, shape [num_nodes, num_hid_features] torch dense tensor :param scale: the scale of the specific input block of wavelet coefficients,...
1d03884b4b0067cd401145047d5269fe78e33dcb
627,753
def sort(data): """ Sort list of reminders by time (oldest first). """ return sorted(data, key=lambda k: (k['time']))
2c9ec32f6e5c3435596a34cc3f98ce1ad1d12ccc
627,754
def find_gvfs(lineages, gvf_list): """This function searches for gvf files in a directory which have filenames that contain specified lineage names. :param lineages: Pangolin lineages to include in the report :type lineages: list of strings :param gvf_list: directory to search for gvf files :typ...
f2779d57a30600a48862beb30550d84cb6491495
627,755
def __int_to_bool(records: dict) -> dict: """Convert integer values to Boolean values.""" for k, v in records.items(): if isinstance(v, int): records[k] = bool(v) return records
9637290b2ff1ce6cc25a02919807861a6bf63128
627,756
import uuid def generate_request_id(): """Generate a unique request id.""" return 'req-%s' % uuid.uuid4()
642c0da0ff69e0c0c0da0d53994923e5796f887c
627,758
def create_user(name, **optional_kwargs): """ Create user """ email = optional_kwargs['email'] if 'email' in optional_kwargs else None return {'id':'124', 'name':name, 'email':email}
568f118bc4cd5b35790b0a9c9719f8ec7525384f
627,759
def CalculateForecastStats(matched, available, possible=None): """Calculate forecast percentage stats. Args: matched: The number of matched impressions. available: The number of available impressions. possible: The optional number of possible impressions. Returns: The percentage of impressions t...
cc942e16a104b1b04ccf8964f5c9a1502b121d8e
627,761
def getBasicTypesToStore(): """ Returns all basic types which will be serialized """ return ("real", "float", "int")
a4c9978a82bdf7c5c4df1dcf9032ac25ab6ca393
627,762
def get_comstr(env, action, targets, sources): """Get the un-substituted string for action.""" # Despite being having "list" in it's name this member is not # actually a list. It's the pre-subst'd string of the command. We # use it to determine if the command we're about to generate needs # to use a...
a1e69110daa8654b715bc2a14247c5d88066564b
627,763
def worldToImgPixelCoords(world_x, world_y, img_x, img_y, img_w, img_h, img_pixels_w, img_pixels_h, trun...
fddee3d0809d9667c8d0bd042128e4bdb7519435
627,764
from pathlib import Path def is_existent_file(potential_file: Path) -> bool: """Assess if a Path points to a file that exists.""" return potential_file.exists() and potential_file.is_file()
ef7fedf193a6d147b5e86f11d2f9064203f4a701
627,765
def get_Theta_set_C(): """ """ return 27.0
273135f82babd1aeb1ff5c8d8e66b91070445bf0
627,767
def choose_froyo(): """Shows a form to collect the user's Fro-Yo order.""" return """ <form action="/froyo_results" method="GET"> What is your favorite Fro-Yo flavor? <br/> <input type="text" name="flavor"><br/><br/> What toppings do you want? <input type="text" name="topping...
d0cece19c2d8e2b6455c2324d54acd56c08b39fe
627,768
def int_to_str_add_zeros(number): """ Turn an int to a sting and make sure it has 6 digit (add zeros before if needed) """ if type(number) != int: print("File number should be an integer.\n") if number < 0: print("File number can't be negative.\n") elif number > 999999: ...
120c0cab693c12613f5381bbf25bdec8a442b59a
627,769
def get_chem_formula(material_base): """creates string representation from a chemical formula inside a Material class instance.""" string_rep = '' for atom,amount in material_base: string_rep += atom.basename + str(amount) return string_rep
8a2fdb381176c487d5b2cc4f1bf47e04a91cabc0
627,770
import random def generate_code(_=None): """Simulate the way oauthlib generates authz codes.""" chars = ('abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '012a456789') rand = random.SystemRandom() return ''.join(rand.choice(chars) for x in range(30))
72a9c9a5cc3edf3cfd30ec05e1f6dd2e0d04aab1
627,771
def extra_tests(): """ Declare some custom tests Returns: dict(name = function) """ return dict( # Example: {% if a|int is custom_odd %}odd{% endif %} custom_odd=lambda n: True if (n % 2) else False )
00ffaa84063305d4974509c855babddb0474076a
627,772
def read_data(name): """ Reading data Parameters ---------- name : file name """ f = open(name, "r") lines = f.readlines() data = [] for line in lines: data.append(line.strip('\n').split('\t')) # close the file f.close() return data
8e2273852ff2801611a5088d3e96fc09ee5d82c6
627,773
def mirror_letter(letter): """ Returns the letter in the same position on the other side of the alphabet. >>> mirror_letter('a') 'z' >>> mirror_letter('z') 'a' >>> mirror_letter('B') 'Y' >>> mirror_letter('C') 'X' """ if letter.isupper(): return chr(155 - ord(l...
6d6a8dc7a55b51141e20fdc3b3e074375ef5152f
627,774
def _new_path_location_from_configuration_data(cls, configuration, configuration_data): """Parse configuration from raw, built-in types such as dictionaries, lists, and scalars. :param configuration: Configuration :param configuration_data: dict :return: cls :raise: ValueError """ if 'path'...
a4b5c57a3d836529aedb7a23c474f7ae35ced7aa
627,775
import torch def get_norm(torch_tensor, dim=0, order=2): """Get the norm of a 2D tensor of the specified dim Parameters ---------- torch_tensor : torch.tensor 2-dimensional torch tensor dim : int, optional order : float, optional Returns ------- torch_tensor : a 1-dimensi...
dc27780cf8b5a5a7a6c612be0891b36b9b3a2690
627,776
import re def parsenum( NumberPattern, strings, CollectorList, linenumber, offset=0, Range='all'): """ Number parser for reading calibration file """ # Specify Range as 'all' to take all numbers, specify number limits to # pick certain number nu...
4d97de26b3dbe9af7a3a746e40527b938edfb792
627,778
def formatAPI(io): """Structure API information. Args: io (array): a NumPy array structure containing descriptions, parameter names&descriptions, response descriptions, example input calls, example outputs. Returns: string: a formatted Markdown output """ # io = np.zeros(shape=(len(paths),6),dtype=ob...
5bc62fc4c64716bd723a5d773b1bcca071678cd6
627,779
def potencia(base, exponente): """ (num, num) -> num Calclula la potencia dada una base y un exponente >>> potencia(2,3) 8 >>> potencia(2,8) 256 >>> potencia(5,3) 125 :param base: la base de la operacion :param exponente: la cantidad de veces que se debe multiplicar por si...
b270ce885c1b37eef1fa994793ae35e840e61380
627,780
import json from datetime import datetime def build_connect_status_payload(_request): """ Build the connect status payload. It seems as though this is optional however the following keys are listed in the IBM documentation { 'ClientAddr': '195.212.29.68', 'Protocol': 'mqtt...
037cefaba7e39f447e13e0273af4038f23ca5662
627,781
def get_variables(models): """get variables of all models Args: models: dict containing all the models available Returns: variables: variables of all models """ variables = [] for model in models.keys(): variables += models[model].variables return variables
b2671c4bd2877be8fa4d241fa87dd789ceda8b7e
627,782
def params_to_lists(params): """Dictionaries are more convenient for storing and working with the parameters of the gaussians and lorentzians, but leastsq wants the initial parameters as a list (as far as I can tell...). This will take a list of dictionaries and convert it to a single list according to the ...
602ec229fa7159665179ca85a1b286e869366ac0
627,783
import sqlite3 def get_track_stats(db_file_name, Table): """Calculate track 1 or 2 or both stats of collection""" conn = sqlite3.connect(db_file_name) c = conn.cursor() c.execute('''SELECT track, count(track) FROM {} GROUP BY track'''.format(Table)) track_dict = {} results = c.fetchall() ...
54590e87141685ee73752d82763126e1ccf4c16f
627,784
import os def get_file_locations(): """ Gets the absolute paths of each data file to graph. Parameters: None Return: paths - a dict with the following structure: { env: { seeds: absolute_seeds_file_path s...
e196f0a3218f6d317dc37031f51d201db8a24a9b
627,785
import logging import traceback import time def retry(tries, delay=1, backoff=2): """A retry decorator with exponential backoff. Functions are retried when Exceptions occur. Args: tries: int Number of times to retry, set to 0 to disable retry. delay: float Initial sleep time in seconds. backoff: f...
716f687ec8716dd94feb3a6dc849838397e79525
627,787
def getConvArea(input_array, i, j, filter_width, filter_height, stride): """ 获取卷积区域 """ start_i = i * stride start_j = j * stride if input_array.ndim == 2: return input_array[start_i : start_i + filter_height, start_j : start_j + filter_width] elif input_array.ndim == 3: retu...
cf85548a0dd93d703f446a06492039131216e562
627,788
import torch def gather_word_outputs(outputs): """ 'outputs' is a list of 'output' of each GPU. As a reminder, each 'output' is a 3-tuple where: - output[0] is the last_hidden_state, i.e a tensor of shape (batch_size, sequence_length, hidden_size). - output[1] is the pooler_output, i.e. a tens...
1ce90c3ccaef5024daa4f77e2f76b2bfe76cce78
627,789
def deleteSpaces(s): """ @param s: String where we want to delete tabs ("\t"), enters ("\r") and spaces (" ") @return: The same string "s" without those special characters """ s = s.replace(" ","") s = s.replace("\n","") s = s.replace("\t","") return s
2e575ba95ee5d0bd2ce0fad0753550b4fe273068
627,790
def to_rgba(x): """ Transforms the state representation of the cellular automata into RGBA format. Primarily used in performing loss calculations with target image (which is in RGBA format). Parameters ---------- x: tensor, (batch, channel_n, h, w) State representation tensor. Retu...
9100846f5fd87a3e467b4d2bb97c6bfe098533ff
627,791
import csv def charger_fichier_entete( nom_fic ): """ Permet de lire un fichier CSV en utilisant la ligne d'entêtes Retourne une liste de dictionnaires. """ lignes = [] with open( nom_fic , "r", newline ="", encoding ="utf -8" ) as csvfile : lecteur = csv.DictReader( csvfile , delimite...
ed4e0f462a8ccce866ecd2618f1bbe2a9c1bbd17
627,793
def get_winner_name(in_group): """helper function""" try: wname = in_group[(in_group['round'] == 'F')].iloc[[0]]['winner_name'].values[0] in_group['twname'] = wname except IndexError: in_group['twname'] = 'none' return in_group
80faa37744a935ee503ad89d49be54566b556855
627,794
from datetime import datetime def decypher_date(datestr): """ Turn 12/17/2016 style dates that Goodgle sheets gives us and convert into a datetime object """ split = datestr.split('/') return datetime(int(split[2]), int(split[0]), int(split[1]))
3d44ae9fee955ba8064cdda5b1ab4839622f1ec1
627,795
def merge(a: list, b: list) -> list: """Merges two sorted lists into one sorted list""" i = 0 j = 0 result = [] while i < len(a) and j < len(b): if a[i] < b[j]: result.append(a[i]) i += 1 else: result.append(b[j]) j += 1 while i < ...
2309e21de2a73e1c9201ea7b5dcb168510841337
627,796
def find_closest_index(L,t): """ Find the index of the closest value in a list. Input: L -- the list t -- value to be found Output: index of the closest element """ beginning = 0 difference = abs(L[0] - t) best = 0 end = len(L) while beginning < end: ...
97e3177aaefaa5ffaf7da588ee780b7373f1bf27
627,797
def get_attrib(xml_obj, attrib): """Get an arbitrary XML attribute""" return xml_obj.attrib[attrib]
0c90595dfc6731f7fe2f14141d6ae003cab71905
627,799
import ast def make_arg(key, annotation=None): """Make an ast function argument.""" arg = ast.arg(key, annotation) arg.lineno, arg.col_offset = 0, 0 return arg
4a41c8335326f336a338c0c036cadca555cb7124
627,800
import os def get_event_storm_list(data_path): """Small function to create a list of with path strings to all storms in the event set. Arguments: *data_path* (string) -- string of data path where all data is located. Returns: *list* -- list with the path strings of all storms ...
5c745a9214f75f25d8ae5345b9ab5781dba9e219
627,801
def get_max_len(files_list): """Get the length of the file with the longest filename""" ret = 0 if len(files_list) > 0: filename_lengths = [len(x) for x in files_list] max_len = max(filename_lengths) ret = max_len return ret
b74d5b5685b0e6abe8bf1093911f3a9723806f69
627,802
def _set2string(items): """集合转字符串,带了花括号,元素排序 Args: items (set)): 集合,代表了函数依赖集 Returns: string: set 可视化 """ return "{{{}}}".format(", ".join(sorted([str(item) for item in items])))
db8df5c029047acd472c9ff43d2292ba6b9b6f4d
627,803
def _artifact_display_versions(versions): """Return a list of artifact versions for display purposes. This is slightly different than the 'versions' property of the artifact, as it is reverse-sorted (newest at the top) and also enumerated so that while it's reversed, the numbers still indicate chronolo...
a012fe700c987104175fea4b59bc178cf15f81d9
627,804
import logging import sys def init_logger(name, level): """ Make sure the logger flushes. """ logger = logging.getLogger(name) logger.setLevel(level) h = logging.StreamHandler(sys.stdout) h.flush = sys.stdout.flush logger.addHandler(h) return logger
0c2f1c6b47704ba5a8b2d443a20ea4d815fbf551
627,805
def replace_with_median(col, value_to_replace): """Replaces a dummy number with the median of the other numbers in the column. Parameters ---------- col : Pandas DataFrame column with numeric values value_to_replace : Dummy value that needs to be replaced Returns ---...
7962351333782164f0be023e5e6d242bda43e3e9
627,806
def get_attributes_in_sentence_list(line, attributes_dict): """ Parameters ---------- line: str, Separate info line for the attribute habitat or season. attributes_dict: dict of {str: str}, dataset_categories.habitat_key_words_dict or dataset_categories.season_categories_dict Return ...
0bf099dcff58790be6589839052f6117a834906b
627,807
from datetime import datetime def to_datetime(dict_date): """ Convert json date entry to datetime. :param dict_date: Date as retrieved from kanka in the format "YYYY-mm-dd HH:MM:SS.000000" :type dict_date: string :return: Date converted to python datetime object :rtype: datetime.datetime """ ...
7275562a5ec7657853b5d664e858c88de71014d5
627,808
import re def clear_path_string(s): """ Simple function that removes chars that are not allowed in file names :param s: path_string :return: cleaned_path_string """ return (re.sub('[^a-zA-Z]+', '#', s)).lower()
2722af065988f02cba40a4899abd92f7c9a51063
627,809
from typing import Match from typing import Mapping def _line_to_cell(match: Match[str], cell_mapping: Mapping[int, str]) -> str: """Replace Python line with corresponding Jupyter notebook cell.""" return str(cell_mapping[int(match.group())])
794b1df7f353b8d333f88fa78ef1f1db5ca6c452
627,810
from typing import Dict from typing import List def format_validation_errors(validation_errors: Dict[str, List[str]]) -> str: """Return marshmallow validation errors formatted as a single string.""" return ', '.join( '{}: {}'.format(key, value[0]) for key, value in validation_errors.items() ...
e43ab4c1d2886062a40db4c36b03783bb171c0ca
627,811
import math def test_dihedrals(pose): """ Simple Test for Dihedral output THIS NO LONGER WORKS (JAB) :param pose: BioPose :rtype: bool """ for i in range(1, pose.total_residue()+1): print("\n"+str(pose.pdb_info.pose2pdb(i))) try: print("Phi: "+repr(math.degrees...
f7772fb6d8b8d925045f38351bdf4f919da5a4b0
627,812
def moeda(p=0, moeda='R$'): """ -> Devolve uma string formatada :param p: valor inserido pelo usuário :param moeda: tipo de moeda :return: valor formatado """ float(p) return f'{moeda}{p:<4.2f}'.replace('.', ',')
d6ce00819aac8c699c2011ecf0222788db9c3526
627,814
import csv def load_data(path_to_csv, num_samples=None): """ Read the csv file given and return the path to images and steering angles """ image_path = [] steering_angle = [] with open(path_to_csv, "r", newline='') as f: recorded_data = csv.reader(f, delimiter=',', quotechar='|') ...
be02b6f02a01293b59de8a8acf63f676a64ac558
627,815
def f1_score_prob(precision, recall): """ this function use to caculate f1 score :param precision: :param recall: :return: """ f1_scores = [] for x, y in zip(precision,recall): f1 = 2.0 * (x * y) / (x + y) f1_scores.append(f1) return f1_scores
84b483bad1c04a68d79618b5f301bb3118333638
627,816
def get_c(layer_configs): """Find input channels of the yolo model from layer configs.""" net_config = layer_configs['000_net'] return net_config.get('channels', 3)
3846c4f961f3a887073b9da25c7333a65a2547be
627,817
def calculate_frame_ier(y_human, y_lena, speech_tiers, skip_overlap=True): """ Given frame-level annotations, calculates the components of the identification error rate. """ false_alarms = 0 misses = 0 confusions = 0 total = 0 # total frames of speech in ground truth correct = 0 ...
647e86a9231675f7c63c5805f03c3762fb76c1d0
627,818
def create_train_validate_sets(batches, split_ratio): """this function splits the samples in the batches into two sets, one for training, and another for validation""" training_set_end_idx = int(len(batches) * split_ratio) training_batches = batches[: training_set_end_idx] validation_batches = batches[...
09f335e8c92f38f4d5f98dfcfeaea334612e9efa
627,819
def get_format(s): """ Returns the Open Babel format of the given string. Note: It is primitive, distinguishes only xyz, smiles, inchi formats. >>> print(get_format('C')) smi >>> print(get_format('InChI=1S/H2O/h1H2')) inchi >>> print(get_format(get_xyz('C'))) xyz """ frm = 'u...
e3ec8c253b4cf14dd2401d4be710a6a596f6116b
627,820
def get_first_word(tabbed_info): """ Get the first word in a sentence, this is useful when we want to get file type, for instance, >> get_first_word('bigBed 6 +') will return 'bigBed' :param tabbed_info: the string (e.g. 'bigBed 6 +') :returns: the first word in the string """ return tab...
b3447800fbc9aea2bd685359cff30600c6f59dd5
627,821
def handle_mosaics(mosaics): """Fill gaps in mosaics If a quadkey is missing in one mosaic but exists in others, fill it in. Args: - mosaics: should be ordered from newest to oldest, so that the newest imagery is filled in. """ # Find all quadkeys quadkeys = set() for mo...
c8127d5b92eb2443302bc6b547f4b06f0e566bc1
627,823
def edge_styles(g): """ Returns the list of all possible edge styles """ styles = set() for e in g.edges(data="style"): style = "-" if e[2] is not None: style = e[2] styles.add(style) return sorted(list(styles))
cfe76dc31da95a72714b0d79a508c3c6aca95378
627,825
def transformPsychoJsCode(psychoJsCode, addons): """Transform the input PsychoJS code. Args: psychoJsCode (str): the input PsychoJS JavaScript code Returns: (str) the transformed code """ transformedPsychoJSCode = '' # add addons on a need-for basis: if 'list' in addons: ...
cdf379190960ec03db409d94e8018b6c45b97f34
627,826
import os import sys def _file(depth=0): """ get current call function name :param depth: the depth of the frame at the top of the call stack. :return: call function name """ return os.path.basename(sys._getframe(depth + 1).f_code.co_filename)
c062c4c21de81a992ad2fbe754080b46fed2cd17
627,827
def iscircular(linked_list): """ Determine whether the Linked List is circular or not Args: linked_list(obj): Linked List to be checked Returns: bool: Return True if the linked list is circular, return False otherwise """ if linked_list.head == None: return False ...
40a0ca17bc4534cfd68a46706a3445313b4ab09e
627,828
def updating_antigens(B_cells, cycleAntigens): """ The antigens for all B cells are updated with the beginning of a new cycle. """ for b in B_cells: b.update_antigens(cycleAntigens) return B_cells
9fc8f22f4c7c84bfcb8d9d1df9f5188dba2a2ada
627,829
from typing import List def get_network_mask(raw_address) -> List[int]: """ Return a network mask from the given raw address. >>> get_network_mask('0.0.0.0/8') [255, 0, 0, 0] >>> get_network_mask('0.0.0.0/9') [255, 128, 0, 0] >>> get_network_mask('0.0.0.0/32') [255, 255, 255, 255] ...
9c0a5090b9407ee7d69985455f648ea4328ec783
627,830
def find_subscript_name(subscript_dict, element): """ Given a subscript dictionary, and a member of a subscript family, return the first key of which the member is within the value list. If element is already a subscript name, return that Parameters ---------- subscript_dict: dictionary ...
6d6b088e079cd05c9ccd2637d946e921306e7b5b
627,831
import csv def csv_dict_reader(file_obj): """ Read a CSV file using csv.DictReader """ return csv.DictReader(file_obj, delimiter=',')
587e9cd8ccedfa2b80f0cd48a6b01360f5fc3b8a
627,832
def calcF1(acc, cnt, tot, beta=1.0): """ Get F1 score. """ if cnt == 0 or tot == 0: return 0 precision = float(acc) / float(cnt) recall = float(acc) / float(tot) if precision + recall < 1e-5: return 0 return (1+beta*beta) * precision * recall / (beta*beta*precision + reca...
5400c2f3de3d3b04700a88469829cde472a87ef8
627,833
import torch def pdist(vectors): """ vectors shape: (batch_size, k-dimensions) compute the Euclidean distance between any two pairs. using formula distance = ||A - B||^2 = A'A + B'B - 2A'B note: A, B represent vector, respectively. A' denotes transpose of A :param vectors: embeddings of batch_...
cad8e6f4dac8a0c3ab4333d7a9b7c064ec029ac9
627,834
def squareCoords(): """Returns a unit square camera with LL corner at the origin.""" return [[(-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)]]
7e2a4d8b3b804794822bbd96eb1a371bedad2670
627,835
from typing import Iterable from typing import Iterator def function(x: Iterable[str]) -> Iterator[str]: """Function that returns an iterator. Args: x: Iterable of string """ return iter(x)
6f21d28aab3dbd7a5dc88560b66b9761f7aec2ad
627,837
from datetime import datetime from typing import Callable def is_before(time: datetime, now: Callable[[], datetime]=datetime.now) -> Callable[[], bool]: """ :param time: A time :param now: A function to use to get the current time (defaults to datetime.now) :return: A predicate that checks if the curr...
0da53787e9cdb4246172ab86354fb09a61b1c82b
627,838
from datetime import datetime def get_index_time(index_timestamp, separator='.'): """ Gets the time of the index. :param index_timestamp: A string on the format YYYY.MM.DD[.HH] :return The creation time (datetime) of the index. """ try: return datetime.strptime(index_timestamp, separator....
3c89fdd1e816bcfeb58f8792bd14c56974ef579f
627,839
def _ReceiveBytes(conn, length): """ Receive length bytes from conn. @type conn: socket @param conn: Socket from which to receive data. @type length: int @param length: How many bytes to receive. @rtype: str @return: Buffer with received data. """ buf = [] while leng...
01d4d7cef60c96f33b274990dbe8caae83c1ba17
627,840
def sshBusy(cmd): """ This function will check the results of a Command to see if ssh was too busy. It will return False if the command completed, successfully or not, and a retry is not possible or necessary. """ retValue = False results = cmd.get_results() resultStr = results....
8b5a561d762154e11a0de9278014600bc98ca269
627,841
def solution(array): """ Computes number of distinct values in an array. """ # Sets only have distinct values # and creating a set from a list has a good time complexity, as it uses hash tables return len(set(array))
aa4d9b8bb9daa7f3935d2301c330077cd79d9988
627,842
def tokenize(s, keep_punctuation=(), drop_punctuation=(), delimiter=' ', add_start=True, add_end=True): """Tokenizes a sentence Args: s (str): the sentence keep_punctuation (tuple): contains the punctuation to keep drop_punctuation (tuple): contains the punctuation to drop ...
839404d08e2aa8fe7ee4a25a7ab474295e6834b2
627,843
import copy def _visit_bounds(visitor, bounds, *arg, **kw): """Call the `visit` method of each bound.""" bounds_ = list() for name, kind, dom in bounds: name_ = copy.copy(name) kind_ = visitor.visit(kind, *arg, **kw) dom_ = visitor.visit(dom, *arg, **kw) bound = (name_, kin...
c8a37dc3dbcd2d9a6c98390c25a9537eb4ad38df
627,844
def is_overridden(obj): """Check whether a function has been overridden. Note, this only works for API calls decorated with OverrideToImplementCustomLogic or OverrideToImplementCustomLogic_CallToSuperRecommended. """ return getattr(obj, "__is_overriden__", True)
966ba90c47d343ba1a03642f4b1b0b6a64761e6e
627,845
import argparse def parse_args(): """ Parse input arguments. """ parser = argparse.ArgumentParser(description='verfication tool') parser.add_argument('--ckpt_path', default=None, required=True, help='model_path') parser.add_argument('--backbone', default='MobileFaceNet', help='backbone type') ...
b824eca8f7e2d77766af1a3b4076761b4c1187b4
627,846