content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def check_url_note(url, metadata): """ Checks the url note for urls that can be processed for additional files Initially this is just newspaper.com clippings. Returns True if the url needs to be processed, false if it doesn't """ # The check value and the toml value check_dict =...
a1542303644b2575af2b478773f2f557b597b6e9
41,104
def getSets(variable): """Get all sets of adjectives in this variable.""" sets = {} for a_name,adj in variable.adjectives.items(): sets[a_name] = adj.set return sets
f292548c5a1260a6ca976619d248118b74fb4af8
41,106
import random def roll_unweighted_die(weights=None): """Returns the result of an unweighted die. This uses a fair Args: weights: (integer array) a collection of the percentage chances each result of the die has. The number of sides is determined by the number of...
34a8502677b21b59c380bf7fa62eab8aac67959a
41,108
import hashlib def md5checksum(afilepath): """ md5checksum Calculates the MD5 checksum for afilepath """ with open(afilepath, 'rb') as filehandler: calc_md5 = hashlib.md5() while True: data = filehandler.read(8192) if not data: break ...
d8d4711e4657514672e455a3374e3ec400636259
41,109
def build_logfile_path(logname, logType, threadId, log_num=1): """ Helper to create a logfile path incorporating the thread ID in the filename before the file type suffix. @param logname: The valid base path without the thread Id. @type logname: Str @param logType: The type of log (e.g. fuzzing) @...
d0c8e7d27e8d7b8ca978bd4b569ec74848f76580
41,111
def move_to_end(x, dim): """ Moves a specified dimension to the end. """ N = len(x.shape) if dim < 0: dim = N + dim permute_indices = list(range(N)) permute_indices.remove(dim) permute_indices.append(dim) return x.permute(permute_indices)
dad4bbceb2c6e5519afee2a3d94e5b06cec222bb
41,112
def wrap_string(s, startstring= "(u'", endstring = "')", wrap=67): """Line-wrap a unicode string literal definition.""" c = len(startstring) contstring = "'\n" + ' ' * (len(startstring)-2) + "u'" l = [startstring] for ch in s.replace("'", r"\'"): c += 1 if ch == '...
a1a266825355f2f54dde61fec2a13a97544a28c2
41,113
import re def count_match(file, pattern="$.*^"): """Counts the number of lines matching the passed regular expression""" # print([*re.finditer(re.compile(pattern, re.M), file.read())]) return len([*re.finditer(re.compile(pattern, re.M), file.read())]) # count = 0 # for line in file.readlines(): ...
ab0aba02a43269b4d34579c04461131430a968bb
41,114
def _find_t(e, annotations): """ Given an "E" annotation from an .ann file, find the "T" annotation. Because "E" annotations can be nested, the search should be done on deeper levels. :param e: (string) the "E" annotation we want to find the target of. :param annotations: (dict) the dict of an...
b10c097ed98548d6a51447e3dd23140deef44818
41,117
def screenRegion(gfx, region=(0.0, 0.0, 1.0, 1.0)): """(gfx, 4-tuple of floats) -> (4-tuple of ints) Determine the absolute coordinates of a screen region from its relative coordinates (coordinates from 0.0 to 1.0) """ w, h = gfx.getSize() x1 = (w - 1) * region[0] y1 = (h - 1) * region[1] ...
35ef5e208bc1cd6279adaf2fef6b7dfc74830dfe
41,119
def one_vs_all_func(classes, table, TP, TN, FP, FN, class_name): """ One-vs-all mode handler. :param classes: confusion matrix classes :type classes: list :param table: input confusion matrix :type table: dict :param TP: true positive :type TP: dict :param TN: true negative :typ...
2b94aa55f4eca068ef32b65ed0b58095e96c3682
41,120
def split(iterable, function): """ Split an iterable into two lists according to test function :param iterable iterable: iterable of values to be split :param function function: decision function ``value => bool`` :returns: tuple( list with values for which function is `True`, list ...
ede20fcc80bd126410a8417d1e91dee2e530c9af
41,121
def total_coeffs_up_to(L): """The total number of coefficients to a maximum degree, L L*(L + 2) (L + 1)**2 - 1 lambda L: sum([num_coeffs(l) for l in range(1, L+1)]) """ return L*(L + 2)
e711dddc992ba3e9f6ef7bc1b6966bde4108eb93
41,122
def split_dictionary(output_dict): """Splits a dictionary into two lists for IDs and its full file paths Parameters ---------- output_dict : dictionary A dictionary with keys: 'id_llamado' and 'fullpath' Returns ------- Two lists Two lists of 'id_llamado' and 'fullp...
33958b60a0e7ca02595c688b1cf7642b6d8a56cb
41,125
def get_state(pins): """Get state from pins""" return pins
9d38848e389398ab394cab6b1ee8bb350d7f2b23
41,126
from pathlib import Path import re import click def ensure_valid_name(node_dir: Path, node_type: str, node_name: str) -> str: """Checks the validity of the specified node_name. Also checks if it already exists. """ if re.match(r"^[a-zA-Z][\w\-]*[^\W_]$", node_name) is None: raise click.excepti...
aa4b7e41aed747439ddfd87c6500f99acd9dcd21
41,128
def get_content(html_code): """ Separates the message section from the content section and returns the for further process :parameters html_code (str) html code of the downloaded :returns tuple (lists) the tuple returned contains two lists of strings. Each list ite...
debaab77f55d9328cd037d6fffc51c8a7f67758a
41,130
import copy def division_algorithm(first_polynomial, second_polynomial): """ Returns the quotient and reminder of the division between first and second polynomials. :param first_polynomial: a polynomial function with the degree greater or equal to the second polynomial function, represented as a vecto...
f21db3777f1f4df2f22f6bcdd802956bf7f88219
41,131
def read_words_from_file(path): """ Reads the content of a file and returns the content, split by space-character. :param path: The path of the file. :return: A list of words in this file. """ file_obj = open(path, "r") content = file_obj.read() return content.split(" ")
960ff1d54b0c37211fc06879a74124ff2e60872a
41,132
import os def find_images(filenames: list, folder: str, formats: list): """Returns list of image abspaths for a folder if format in 'formats'""" all_photos = [os.path.join(folder, file) for file in filenames if file.lower().endswith(tuple(formats))] return all_photos
bfe87901a6e1fa14c8cc5cfd5b85206f85c73175
41,133
def generate_query_id(query_client, branch): """ Build the body of the query and return its ID """ model_name, explore_name, fields, starting_field_count = branch query_body = {'limit': '1'} # Limit the number of rows in the query query_body['model'] = model_name query_body['view'] = explo...
3793db433922d5c029660b217be63dff20b39ae1
41,134
import sys def check_packed_shards_logical(fs_format, min_unpacked_rev): """Check if repository with logical addressing has packed shards.""" if fs_format[2] == "logical" and min_unpacked_rev > 0: sys.stdout.write("\n") sys.stdout.flush() sys.stderr.write("Packed shards with logical addressing cannot ...
3c456aeb0a20a7109d64f9acb5436c2050a6849f
41,135
import torch def beams(ctc_probs, beam_size: int, alphabet: str, blank_index: int): """ Return top-beam_size beams using CTC prefix beam search, adapted from https://github.com/wenet-e2e/wenet/blob/829d2c85e0495094636c2e7ab7a24c29818e1eff/wenet/transformer/asr_model.py#L329 """ # cur_hyps: (prefi...
8dd9813bfa480ede4f4a0b69a3b33c70bcb728a0
41,137
def asset_icon_name(asset_type_name: str) -> str: """Icon name for this asset type. This can be used for UI html templates made with Jinja. ui.__init__ makes this function available as the filter "asset_icon". For example: <i class={{ asset_type.name | asset_icon }}></i> becomes (for a bat...
43b044ce6718cca173e205a615b9ec2cfd361db9
41,139
def should_trade(strategy, date, previous_trade_date): """Determines whether a trade is happening for the strategy.""" # We invest the whole value, so we can only trade once a day. if (previous_trade_date and previous_trade_date.replace(hour=0, minute=0, second=0) == date.replace(hour=0...
8c52eb554673bb0badff4a55c8e3a11cf9392a47
41,140
import re def parser(filename): """ Parses a textfile in search of battery current information :param filename: File to be parsed :return: """ maximum = 0 log_data = open(filename, 'r') for line in log_data: m = re.search('current: (\d+\.\d*)', line) if m is None: ...
def3367b0341b5f967afb60886fb581a2d6f65e9
41,142
from functools import reduce import operator def prod(a, start=1): """Return product of elements of a. Start with int 1 so if only ints are included then an int result is returned. Examples ======== >>> from sympy import prod, S >>> prod(range(3)) 0 >>> type(_) is int True ...
844347483f2c03c0ce7121180f9ae23855846fd3
41,143
import argparse def parseCommandLineArguments(): """ Parses the arguments provided through command line. Launch python find_y2h_seq_candidates.py --help for more details """ parser = argparse.ArgumentParser(prog="NGPINT.py",description="This pipeline can be used to find potential interactors of th...
40694793169b4020f77b5c7337db3c2d94f93553
41,144
import random def form_batches(batch_size, idx): """Shuffles idx list into minibatches each of size batch_size""" idxs = [i for i in idx] random.shuffle(idxs) return [idxs[i:(i+batch_size)] for i in range(0,len(idxs),batch_size)]
2afdc93202f553b29a8f4c68dcf6e226816d9de0
41,145
def get_translation(pp): """Separate intrinsic matrix from translation and convert in lists""" kk = pp[:, :-1] f_x = kk[0, 0] f_y = kk[1, 1] x0, y0 = kk[2, 0:2] aa, bb, t3 = pp[0:3, 3] t1 = float((aa - x0*t3) / f_x) t2 = float((bb - y0*t3) / f_y) tt = [t1, t2, float(t3)] return ...
1058fdc718b05369e338ee1102b5784d8d2704c4
41,146
def is_multiline(s): """Return True if a str consists of multiple lines. Args: s (str): the string to check. Returns: bool """ return len(s.splitlines()) > 1
6c1eca6f1d3d449bff6661b2ab3b9cd8695fbf90
41,147
def _agg_scores_by_key(scores, key, agg_mode='mean'): """ Parameters ---------- scores: list or dict list or dict of {'precision': ..., 'recall': ..., 'f1': ...} """ if len(scores) == 0: return 0 if isinstance(scores, list): sum_value = sum(sub_scores[key] for su...
f289ddcd298b4ce6dbe701e8e729e37fc6d8ea69
41,148
def get_rows_to_keep(mode, df, grp, samp_grps, qthreshold, min_child_non_leaf, min_child_nsamp, min_peptides, min_pep_nsamp): """ Use checking to find the rows (taxonomic or functional terms) that satisfy all of the filtering conditions for the specified group :param mode: either 'f...
353c0b0d2717018f60178f37d777be25bbcf2193
41,149
def send(r, stream=False): """Just sends the request using its send method and returns its response. """ r.send(stream=stream) return r.response
7350fe337450e55744ee82541b90d5204868fff0
41,150
from pathlib import Path from datetime import datetime def unique_path(parent: Path, stem: str, suffix: str, seps=('_', '-'), n: int = 1, add_date: bool = True) -> Path: """ :param parent: Directory in which a unique file name should be created :param stem: File name without extension :param suffix: F...
872ec8ad2e24e51edb37a1722f16b85abeb96614
41,151
def remove_indices_from_range(ixs, max_ix): """From the indices 0:max_ix+1, remove the individual index values in ixs. Returns the remaining ranges of indices and singletons. """ ranges = [] i0 = 0 for ix in ixs: i1 = ix - 1 if i1 < i0: i0 = ix + 1 elif i1...
df71db04b7e521815042237000f036735fbbe0f3
41,152
def maybe_append(df1, df2): """ If both data frames are available, append them and return. Otherwise, return whichever frame is not None. """ if df1 is None: return df2 if df2 is None: return df1 return df1.append(df2)
aaabcc0f175fc913f0dbce575888cf08ff625c98
41,153
def max_subarray(nums): """ Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. Args: nums: list[int] Returns: ...
8660758cc758f85ea4750e491f249b08c0dfdd00
41,154
def pandas_table_to_nested_list(df): """ Converts pandas table df to nested list """ table_data = [["" for x in range(df.shape[1])] for y in range(df.shape[0]+1)] # Columns names for i in range(df.shape[1]): table_data[0][i] = df.columns[i] for i in range(df.shape[0]): ...
fc5aa04de82dcacab5ae6f6c64f22417d3d9318f
41,155
def viz_white_wrap(body, char, bgcolor="white"): # pylint: disable=unused-argument """Wrap body with hidden text for graphviz""" return ( '<FONT COLOR="{bgcolor}">' ' <FONT COLOR="black">{body}</FONT>' '{char}</FONT>' ).format(**locals())
8131fc58c42c2878a2cbb4f7f69ab1b5054774e0
41,156
def cescape(string): """Escapes special characters needed for color codes. Replaces the following symbols with their equivalent literal forms: ===== ====== ``@`` ``@@`` ``}`` ``}}`` ===== ====== Parameters: string (str): the string to escape Returns: (str): the st...
48aef7c95851f9a7ae475d3ba38db55ce09fb5de
41,158
import os def get_svgs(names: list, root: str, folders: list) -> list: """Get svgs from multiple folders. :param names: The names of the svg files. :param root: The root folder that the folders are in. :param folders: A list of folder names :return: list """ svgs = [] if len(...
eb59bf08c1726067bcb56a1c9775e74388f37ae1
41,159
def closest_pair_strip(cluster_list, horiz_center, half_width): """ Helper function to compute the closest pair of clusters in a vertical strip Input: cluster_list is a list of clusters produced by fast_closest_pair horiz_center is the horizontal position of the strip's vertical center line half_wi...
d6966ec785d6ca5053ab8f91661735cbe0083dc5
41,160
def tb_args(exc): """Easily format arguments for `traceback` functions.""" return (type(exc), exc, exc.__traceback__)
d5c65e67556c28de3a97742fb4115cf8bddfb6a4
41,163
def flatten_list(cols_list, recursive=True): """Take a list of lists and return a flattened list. Args: cols_list: an iterable of any quantity of str/tuple/list/set. Example: >>> flatten_list(["a", ("b", set(["c"])), [["d"]]]) ["a", "b", "c", "d"] """ cols = [] for i ...
d8e16a99b2e5f61ce53813ca7424e1b01cb1cddf
41,164
def get_digit(number): """ 숫자로 변환하는 지 확인 True로 나오면 통과 """ result = number.isdigit() return result
4f3a70802ef66eb6f99946bb39bda69f9420a1a6
41,167
def table_entry_size(name, value): """ Calculates the size of a single entry This size is mostly irrelevant to us and defined specifically to accommodate memory management for lower level implementations. The 32 extra bytes are considered the "maximum" overhead that would be required to rep...
fb05f2299bd264d3ae8143307d9c428aad18d5d7
41,168
def z_array(s): """ Z-algorithm used in BM-Search :param s: the string from which to extract :return: a list of the length of prefix-substring """ assert len(s) > 1 n = len(s) z = [0] * n z[0] = n l, r = 0, 0 for i in range(1, n): if i > r: # i > r, i is ...
fa0eb3ab7ccc9f9cf7bf42fbea63a1fb13d4cf45
41,171
import os def _find_image_bounding_boxes(filenames, image_to_bboxes): """Find the bounding boxes for a given image file. Args: filenames: list of strings; each string is a path to an image file. image_to_bboxes: dictionary mapping image file names to a list of bounding boxes. This list contains 0+ ...
ce818f99928686d5cb6a5caa8d5534af3a934d95
41,172
import os def testcase(): """Try to locate the test case that comes with cadishi. Works for a check-out (or tarball) of the source files as well as for an installation. Returns the full path to the testcase including a trailing slash.""" file_path = os.path.dirname(os.path.abspath(__file__)) test...
772be140397f9314498069ec79e665aa143c39a4
41,173
def bitparity(x): """return the bit parity of the word 'x'. """ assert x >= 0, "bitparity(x) requires integer x >= 0" while x > 0xffffffff: x = (x >> 32) ^ (x & 0xffffffff) x ^= x >> 16 x ^= x >> 8 x ^= x >> 4 return (0x6996 >> (x & 15)) & 1
0ccc04cf8df450b1bfd67334e006a57f4f6c53bc
41,174
def x_times(a): """ Multiply the given polinomial a, x times. """ return (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
b25bb58abdebf1f83bbf9c206b616c3420ec713c
41,175
def global_video_success(row, weights=None): """Create a video success measurement based on basic video stats.""" metric_cols = ["commentCount", "dislikeCount", "favoriteCount", "likeCount", "viewCount"] if weights is None: weights = [1 for _ in metric_cols] weights[1] = -1 ...
49ca735b7efe54b49f29ba79be6c5aee250d64ba
41,176
def has_converged(mu, oldmu): """ A boolean indicating whether or not a set of centroids has converged Parameters: mu - the latest array of centroids oldmu - the array of centroids from the previous iteration Returns: A boolean indicating whether or not the old and new centroid...
35234531a15baaf4f1df2f196e6abcec40fade59
41,177
import copy def merge_config(new_config, old_config): """Merge the user-defined config with default config""" config = copy.deepcopy(old_config) if new_config is not None: config.update(new_config) return config
0d6d3f4b1df504485b991d6edc63d675439ab6d0
41,178
def make_range(chain_range_dic): """Expand a chain dictionary into ranges.""" chain_ranges = {} for chain in chain_range_dic: min_idx = min(chain_range_dic[chain]) max_idx = max(chain_range_dic[chain]) chain_ranges[chain] = (min_idx, max_idx) return chain_ranges
718f1acfae09fb0651cd351d232359f8b8ff7dfc
41,179
def track_links(soup): """ Replace links with tracking links. """ # For each link in the email for link in soup.findAll('a'): # Check to ensure it has an href attribute. if link.has_attr('href'): # Only track online.msstate.edu links if 'https://online.msstate.edu/'...
2557501cd38b49dc0c9600be9a5f8883ebe3a834
41,181
def healthcheck(): """Low overhead health check.""" return 'ok', 200
d29c4c9f20d8041e781af2db0b83c40af5410143
41,182
def readable_conversion_file(url): """Reads the provided url as a conversion file""" conversion_dict = [] with open(url, 'r', encoding='utf-8') as f: lines = f.readlines() assert len(lines) == 9, "The conversion file must have exactly 9 lines detailing the 9 conversion categories" f...
d0cb9c6b5c6c4486e1b8400085d46b70c28efe70
41,183
def format_generic(value): """ Generic values with space in them need to be quoted """ value_str = str(value) if " " in value_str: return '"%s"' % value_str return value_str
850d1969f68cc8b5dd132a51e616862393d61513
41,184
import math def calculateHeading(origin, destination): """ Calculate the heading direction between two coordinates. It returns the heading in degrees, where 0 deg is North. (This is not very accurate but good enough for us.)""" x1 = destination[0] y1 = destination[1] x2 = origin[0] y2 = or...
b114c6c4c028e148fe87f828128d2bd2766f0c61
41,185
def for_factorial(num): """Iterative solution""" result = 1 for i in range(2, num + 1): result *= i return result
55371d55161bb9bf3547eb9a03f636364b86bc5c
41,190
def extract_unique_series(sessions): """ Presently, the user will have to choose a subject that has the most representative number of scans to constitute a 'complete' series. This function determines completeness based on the number of unique series that a subject possesses. It would be better ...
e19c7ae15f871ce5d903ebb6cba6e13bc1889152
41,191
import math def smoothedsigmoid(x, b=1): """ English: b controls smoothness, lower = smoother Japanese: b は緩やかさを調整します。b が小さいほど緩やかに(変化が小さく)なります。 """ return 1 / (1 + math.exp(- b * x))
014bec11a761fcf19c9e5885a1fa870115b90a00
41,192
def diff_lists(list1,list2, option=None): """ if option equal 'and', return a list of items which are in both list1 and list2. Otherwise, return a list of items in list1 but not in list2. """ if option and option == 'and': return [x for x in list1 if x in list2] else: return [x...
2ffe6656d638d1ce185501361288266158ead09f
41,193
from typing import Sequence def boolListToString(binary : Sequence[bool]) -> str: """Convert a boolean list to a string Parameters ---------- binary : Sequence[bool] Sequence of booleans representing a binary number in big endian form Returns ------- str String r...
9a0eda92124336b66ca74304efabdf1c7f1b082e
41,194
def print_messages(original_func): """ Print loading messages to display for user. :param original_func: A function :precondition: original_func must be a well-formed function :postcondition: Successfully invoke the wrapper function :return: wrapper_printer """ def wrapper_printer(*ar...
348d242c94aef178af34b794287cad1cfffc3b9d
41,195
import os def _getName(path, synapse_dir, local_root, depth): """ Finds the name of files in local directory. :param path: :param synapse_dir: :param local_root: :param depth: :return: name of file and it's associated parent location/benefactor """ path_no_root = path[len(os.path....
719862832d7ca6570eb59564311bebca107c4f5b
41,197
def frame_attrs_from_set(frame_set): """ A `dict` of all the attributes of all frame classes in this `TransformGraph`. Broken out of the class so this can be called on a temporary frame set to validate new additions to the transform graph before actually adding them. """ result = {} fo...
f29ce3ea6422f49b34104ce396162f7e76ca851d
41,200
def get_n_params(model): """ DESCRIPTION: Function to count number of parameters. """ np=0 for p in list(model.parameters()): np += p.nelement() return np
3d30935a1a58eddf79a1b124584ee7aae0079360
41,201
def process_passport(passport): """Turn a passport list into a dictionary.""" pass_string = ' '.join([n.strip('\n') for n in passport]) pass_list = pass_string.split(' ') pass_dict = {} for n in pass_list: key, entry = n.split(':') pass_dict[key] = entry return pass_dict
30e5d0943f8b34fd5c02dad70af143070348331d
41,202
def is_valid_dsl(query): """Simple text check""" if not "return" in query: raise Exception("\n----\nYour DSL query does not include a `return` statement. Should end with: '.. return publications[id+concepts_scores]'") q = query.split("return")[1] if "concepts" in q: return True ...
53be3514358754d02e321a07d016fa826beb00ce
41,203
def upilab6_3_3 () : """6.3.3. Exercice UpyLaB 6.8 - Parcours vert bleu rouge Écrire une fonction store_email(liste_mails) qui reçoit en paramètre une liste d’adresses e-mail et qui renvoie un dictionnaire avec comme clés les domaines des adresses e-mail et comme valeurs les listes d’utilisateurs correspondantes, t...
8b4afbc8cba36967fa2a95588830c188e761204b
41,204
import re def course_url(course_id): """ Given a course id string, returns the URL for the link to that course's website. """ if course_id.startswith("math"): return "https://www.wellesley.edu/math/curriculum/current_offerings" elif course_id.startswith("cs"): return "https://c...
8c2e7ce8409c359ed6bd3ae81c5a0a0141217eef
41,205
import random def make_cat_string(categories=(None,)): """Function that generates a value for a StringType field that can only take a limited number of values. Parameters ---------- categories : list or tuple of strings Sequence of strings to select values from Returns ------- ...
2f46e462e5f37c68af096f3b1d25e270380ebf0c
41,207
def one_to_all_bfs(start, num_vertexes, edges, INF=9223372036854775807): """ when all cost is 1, BFS is faster (ABC170E) """ distances = [INF] * num_vertexes distances[start] = 0 to_visit = [start] while to_visit: next_visit = [] for frm in to_visit: for to in edg...
5ab315f293fabf8ac281ac50ab8b55c0bde6fe46
41,208
def remove_none_items(adict): """Return a similar dict without keys associated to None values""" return {k: v for k, v in adict.items() if v is not None}
ddea6a77bc55ce33485f74c83a75e14f01d303a9
41,209
def read_atom_properties_file(filedir): """ Reads the text file "Dans Element Properties.txt" Returns a list of dicts containing atomic properites from multiple sources data = read_atom_properties_file(filedir) data[22]['Element'] :param filedir: location of "Dans Element Properties.txt" ...
4c8c6f31c2060aee8925b46f48984cdd836a66dd
41,210
import struct def unpack_info_packet(packet): """Unpack an informational packet.""" return struct.unpack("Ld", packet)
5976abc2b2fc1d072bf5434e639cbf27f3e69e58
41,211
def compute_input_history(history): """Slicing history in its second dimension.""" # no slicing for now return history[:, 2:5]
fdc8b8e2da55d12dd8b53ca8bedc300da6779341
41,212
def release_string(d_release): """ Produces a string describing a release Args: d_release (dict): dictonary containing the release data Returns: (string): representing the release Raises: (KeyError): if the data does not contain the field "basic_informa...
4ca448b4778fd0ef56bbcfc0c3dce1c60d157174
41,213
def makestamp(daynumber, timestamp): """Receives a Julian daynumber (integer 1 to 16777215) and an (HOUR, MINUTES) tuple timestamp. Returns a 5 digit string of binary characters that represent that date/time. Can receive None for either or both of these arguments. The function 'daycount' in dateutils w...
eaa939dca4cee0cebcccad3f16c892fef2b66ebf
41,215
import hashlib def findhash(path: str) -> str: """Calculates the MD5 Hash for the path specified""" h = hashlib.md5() filefrompath = open(path, 'rb') with filefrompath as file: chunk = file.read(1024) while len(chunk) > 0: h.update(chunk) chunk = file.read(10...
6402aa4c7eb50c77918ebb98b69c1027fa39bb45
41,217
def atleast_list(thing): """Make sure the item is at least a list of len(1) if not a list otherwise, return the original list Args ---- thing (any type) : thing to assert is a list Returns ------- thing (list) """ if not isinstance(thing, list): thing = [thing] ret...
e97b61266b76aa5ffea65541515e44807c57ba1a
41,218
def state_labels(): """ Define the state labels for the states in the MDP """ labels = {} labels[0] = 'New' labels[1] = 'Used' labels[2] = 'Bad' labels[3] = 'Broken' return labels
d050d3c4c6b167baa42a0d8d5f18d7b3d6ca3f90
41,219
import decimal def has_number_type(value): """ Is a value a number or a non-number? >>> has_number_type(3.5) True >>> has_number_type(3) True >>> has_number_type(decimal.Decimal("3.5")) True >>> has_number_type("3.5") False >>> has_number_type(True) False """ ...
d5db38736244af750ee881ceb83b5433eecd6bb9
41,220
def flat_list(x=None): """ Description: It returns a list that contains all the elements form the input list of lists. It should work for any number of levels. Example: >>> x = flat_list([1, 'k', [], 3, [4, 5, 6], [[7, 8]], [[[9]]]]) >>> x >>> [1, 'k', 3, 4, 5, 6, 7, 8, 9] ...
5b96d06192ac96530674042459277f9acfd6c707
41,221
def is_date_special(date): """ Is this particular date special """ return date.day * date.month == date.year % 100
2758b4604e4d88a32608c4def8a95b222f7bcef8
41,223
def street_check_fold_json( rus_check_json, benny_bet_json, rus_fold_json, oven_show_json ): """Expected JSON for street_check_fold model-fixture""" return { "actions": [ rus_check_json, benny_bet_json, rus_fold_json, oven_show_json, ] }
025fa8f618b14cfe59e8af6016ab8219e25b2ecf
41,225
import pipes def CommandToString(command): """Returns quoted command that can be run in bash shell.""" return ' '.join(map(pipes.quote, command))
e20a81b1336352e51b624e41aca3bea615cd030b
41,226
import re def _parse_parameters(script): """Parse parameters from script header""" params = {'profiles': [], 'templates': [], 'platform': ['multi_platform_all'], 'remediation': ['all']} with open(script, 'r') as script_file: script_content = script_file.re...
30c028dd1bbd8c4737a613c15bf311798ef8e816
41,228
def tokenize_multi_turn_dialog(dataset, tokenizer, special_tokens): """ Format > [[{'usr': <user utterance>, 'sys': <system utterance>}, ...],...] """ tokenized_dialogs = [] for i, dialog in enumerate(dataset): print('\r %.4f...' % ((i+1)/len(dataset)), end='') tokenized_turn = [] ...
510340af2383277ff03a31746b0a5a52d4792570
41,229
def channel1json(): """Return a dict for a channel Name: test_channel """ c = {"mature": False, "status": "test status", "broadcaster_language": "en", "display_name": "test_channel", "game": "Gaming Talk Shows", "delay": 0, "language": "en", ...
bdeef1f6f44c27e90d06885ccd7d8e2a0483a95d
41,231
def get_communicator(episode, agents, alternate=False): """ This function selects the communicator. :param episode: The current episode. :param agents: The agents in the game. :param alternate: Alternate the leader or always the same. :return: The id of the communicating agent and the communicat...
fb0939abe003f4aba04e58870a1266982921dec1
41,232
def _get_language(uid, query): """ Returns ui_locales of a language :param uid: of language :param query: of all languages :return: string """ return query.get(uid).ui_locales
914d0a1e59ea34a5732b8baee13bf5899a10cc3f
41,234
from typing import OrderedDict import collections def tokenize_annotations(annotations): """Function to tokenize & convert a list of genes GO term annotations to their equivalent list of GO term annotation ids""" go_terms = [] for annotation in annotations: go_terms.extend(annotation.split()) ...
25e1ebf7482e58d0c0f61d2fa3e3cae039c12a22
41,235
import torch def ridge_regularize(network, lam): """Apply ridge penalty at linear layer and hidden-hidden weights.""" return lam * ( torch.sum(network.linear.weight ** 2) + torch.sum(network.rnn.weight_hh_l0 ** 2) )
29e46f10b0ee63f0bda090836b95b1f0b4b1664c
41,236
def build_grid(filename): """Scrapes a formatted text file and converts it into a word search grid. Args: filename: A text file containing rows of alphabetical characters, optionally separated by spaces or commas. Each row must contain the same number of letters. Returns: ...
0bed89308de1ba3c6fb1d0372364305deb5d0856
41,237
import string def make_a_valid_directory_name(proposed_directory_name): """In the case a field label can't be used as a file name the invalid characters can be dropped.""" valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) directory_name = "".join(c for c in proposed_directory_name if ...
8e1d04d4c5c629a123f38ef95fecafc1e4f7f7d0
41,238
def read_experiment_data(f): """Read data from stdin""" commands = [] lines = f.readlines() for l in lines: s = l.split() if len(s) > 0: commands += [s] return commands
9d6c5f6d76eef0f5feb6cabfb128c169949e4016
41,240