content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_vgci_warnings(tc): """ extract warnings from the parsed test case stderr """ warnings = [] if tc['stderr']: for line in tc['stderr'].split('\n'): # For each line if "WARNING" in line and "vgci" in line: # If it is a CI warning, keep it ...
d167c66374754e6099cb20d05e49c5ad609b472b
651,936
from pathlib import Path def get_reps_path(params, split): """Return path to directory where dialogue representations are stored.""" directory = Path(params.path_to_representations) path_r = f'{params.bot}Bot_{params.bot_version}_representations_{split}.h5' return directory / path_r
563aa05a90fe5c45b26954ebd6775aac886f8a42
651,937
import re def _include(path, includes, excludes): """ :params path: The file path to check whether to include :params includes: List of include regexs to apply :params excludes: List of exclude regexs to apply :returns True if the file path should be included, False """ if includes is No...
0e6c8c4c883537034d6a5a53dc57bb9e0936aa55
651,943
def inverted_y(coordinate_y, height): """反转y坐标。 Args: coordinate_y: y坐标。 height: 高度。 Returns: 新的y坐标 """ return abs(coordinate_y - height)
4d99fe184c567f3fb22c210357fbb6bec62ba4e8
651,944
import collections def graph_inputs(name, **kwargs): """Creates a namedtuple of the given keys and values. Args: name (string): Name of the tuple. kwargs (tf.Tensor): One or more tensor(s) to add to the namedtuple's values. The parameter names are used as keys in the n...
dbdafaf68d4540de8f1e10ccb71d8ae2aeb13ead
651,947
def _port_in_range(value): """Return True if port is in expected range.""" return 49512 <= value <= 65535
b8041e2e9c6b055577744c9ecc840ca55890c1ef
651,948
def results_summary(results_data): """ Return a summary of the results stored in a dataframe. Returns a dict containing unique entities in each column Ignores the exp_data, f_min, min_params and time columns """ unique_vals_dict = {} col_list = list(results_data.columns.values) ...
8de33c0d883d9e224a58e0316fa8109fa4f1edaa
651,951
def makeIntervals(evts): """From evts=[a,b,c], create a list of intervals: [(0,a), (b,c)] From evts=[a,b,c,d], create a list of intervals: [(0,a), (b,c), (d,1)]. Assumes all values in evts are in (0,1)""" if evts == []: return [(0.0, 1.0)] evts.sort() left = 0.0 intervals = [] for e in evts: if left >= 0.0: ...
093299058904966682e9df91d96c6cc7adc430f2
651,952
import re import keyword def is_valid_identifier(var, allow_unicode=False): """Return true if var contains a valid Python identifier Parameters ---------- val : string identifier to check allow_unicode : bool (default: False) if True, then allow Python 3 style unicode identifiers....
27e5f63de31d3f713395be5d0c9867cba0d62047
651,955
import re def is_rgb_code(s: str) -> bool: """ Returns True if `s` appears to be a single rgb escape code. """ pattern = '^\033\\[((38)|(48));2;\\d{1,3};\\d{1,3};\\d{1,3}m' return re.match(pattern, s) is not None
8e3c3e7b02c572786418cf4573ccaf9ed425a2dd
651,960
def props_of_this_event(event, ts_tuple, run): """ Find the set of propositions that correspond to an event. Parameters ----------- event: A tuple An event is a tuple of the form (agent_no, run_pos). This argument can either be a tuple of events (simultaneous events) or a tuple of integers (single event). ...
a0abab647967e1f777aa47797af0e18f61cba6bd
651,962
import site from pathlib import Path def find_pkg(name): """Find package in site-packages""" for p in site.getsitepackages(): pkg_path = Path(p) / name if pkg_path.exists(): return pkg_path return None
da22728cc30f4f4e817dcf4f8f647fe1361cc7fb
651,963
import json def readfile(filepath): """ reads a pipeline json file and returns the resulting dictionary """ with open(filepath, "r") as json_file: json_data = json.load(json_file) return json_data
0bc68952023ef779afcd6541780e66fa44fb6088
651,969
def points_to_region(region_pts): """ Reverse Voronoi region polygon IDs to point ID assignments by returning a dict that maps each point ID to its Voronoi region polygon ID. All IDs should be integers. :param region_pts: dict mapping Voronoi region polygon IDs to list of point IDs :return: dict ma...
880a2c3fb91f41a37dcb218ad09799399ddacc8e
651,973
def clean_file_name(filename): """Clean the filename for the client. If it has directory structure, purge it and give only the file name. :param filename: file name to be cleaned :return: cleaned filename """ if '/' in filename: filename = filename.split('/')[-1] return filename
2cbb37d68e45ac76fb17ae99504bcc7bae2d41f1
651,975
def mean_normalize(x, mean_x, max_x, min_x): """ Mean normalization of input x, given dataset mean, max, and min. >>> mean_normalize(10, 10, 15, 5) 0.0 >>> mean_normalize(15, 20, 30, 10) -0.25 Formula from: https://en.wikipedia.org/wiki/Feature_scaling """ # If min=max, all va...
30e38ddb6cfb73c5326d2620e0c4b10ab7074ddb
651,976
def calculate_centroid(gps_bounds): """Given a set of GPS boundaries, return lat/lon of centroid. gps_bounds -- (lat(y) min, lat(y) max, long(x) min, long(x) max) Returns: Tuple of (lat, lon) representing centroid """ return ( gps_bounds[0] + float(gps_bounds[1] - gps_bounds[0])/2...
d6a9d99f011f64958d9a7ac74d582be18294da92
651,981
import re def hasNewRating(filename): """ Checks if parameter file name already has a rating. Movie ratings are in the format (\d.\d) """ pattern = re.compile('\[IMDb [0-9].[0-9]\]') return pattern.search(filename) is not None
0acf113d86d764fc59c949addb678e0263243394
651,982
from typing import Iterable from typing import List def _resplit(parts: Iterable[str]) -> List[str]: """ Given a list of strings, returns a list of lines, by splitting each string into multiple lines where it contains newlines. >>> _resplit([]) [] >>> _resplit(['a', 'b']) ['a', 'b'] >...
b37d71f659858ad6f58bf68e679359b7e00fa65c
651,983
def remove_empty_kps(coco_context): """Returns a list of valid keypoint annotations Arguments: coco_context: The initialized cocoapi class Returns: processed_idx (list): List of images with valid keypoint annotations """ processed_idx = [] image_idx_list = coco_cont...
5979c14336590ba5adc57a44af7a8d587bb74f1e
651,985
from datetime import datetime def to_embed_timestamp(timestamp: int) -> datetime: """ Convert UNIX timestamp to datetime object for embed timestamps. :param timestamp: UNIX timestamp with seconds accuracy. :return: Timezone native datetime """ return datetime.utcfromtimestamp(timestamp)
acebe00defb27122a770f5b54fe59e3c8f4bc8d9
651,989
def make_inverted(m, n): """ Given two integers m and n, write a function that returns a reversed list of integers between m and n. If the difference between m and n is even, include m and n, otherwise don't include. If m == n, return empty list If m < n, swap between m and n and continue. Example 1: Input: ...
83692c924162bb595d01c9b7e1cb8c818497faf1
651,998
def visparamsListToStr(params): """ Transform a list to a string formated as needed by ee.data.getMapId :param params: params to convert :type params: list :return: a string formated as needed by ee.data.getMapId :rtype: str """ n = len(params) if n == 1: newbands = '{}'...
5606c4dca858f5b58acaecdd3266ae7b26560cbe
652,001
def get_asa_owners(indexer_client, asset_id, asa_min_balance=0): """Search for ASAs owners Args: indexer_client (IndexerClient): Indexer Client V2 asset_id (int): ASA Asset ID asa_min_balance (int): Optional; ASA minimum balance expressed as minimal int units Returns: ...
15fdcbfa9022eb6a0c738bcfa212a41bca40e76e
652,002
def coleman_liau_index(n_chars, n_words, n_sents): """https://en.wikipedia.org/wiki/Coleman%E2%80%93Liau_index""" return 5.879851 * (n_chars / n_words) - 29.587280 * (n_sents / n_words) - 15.800804
b81afdceb58c885c3e1eb1fa17a70031e6d7a555
652,003
def choose_box(group, plot_data): """Given a set of overlapping bounding boxes and predictions, just choose a closest to stem box by centroid if there are multiples""" if group.shape[0] == 1: return group else: #Find centroid individual_id = group.individual.unique()[0] stem...
6550422786370683808c60f8c5c33c39fe3fb255
652,005
def organize_edges(edges, borders=None, default_border='land'): """ Organize edges in to various collections specified by borders. Required Arguments ------------------ * edges : List of edges of the form (node_number, node_number, ... , edge_type) The sort...
e89f7e3d840ec6d593f6da9dfa3235cb6cffc238
652,008
def isstrlessthan(string, length): """Checks if string is below length""" return len(string) < length
a3da55155f8a9784ea3a3e5d504884907cbf5757
652,010
import re def _clean(text): """ Cleans the text: Lowercasing, trimming, removing non-alphanumeric""" return " ".join(re.findall(r'\w+', text, flags=re.UNICODE)).lower()
ff3496a0fcae32ed1ecb7ceb106bbe60c1da25ea
652,016
import json def read_config_file(filename): """ Read the json configuration file and return a map with the config entries """ with open(filename) as json_file: json_input = json.load(json_file) return json_input
2a94d44f1c204980049b7b865869e4f39af8cc68
652,018
def dim_col(d: int) -> str: """ Name of an dimension columns. Parameters ---------- d Dimension number. Returns ------- name: str Dimension name. Example ------- >>> from rle_array.testing import dim_col >>> dim_col(1) 'dim_1' """ return f"d...
e4f76bdba041535993aaea1ba613f1596d8e32e9
652,019
import math def s1diff(a,b): """Angle from a to b in an anticlockwise direction.""" if b < a: b += 2*math.pi return b - a
222c0b0ee661ac881582d2478bae9633b9e0d33f
652,026
def convert_length_in_minutes_to_hr_min_str(length_minutes=0): """ Convert minutes into something like 02h03m if given 123. Note that both hr and min are 0-padded """ hour = length_minutes // 60 minutes = length_minutes % 60 return "%02dh%02dm" % (hour, minutes)
606d8aa79302c255cc9188a0629f5e6fd3a9e37e
652,031
def check_type(dictionary): """ Checks if the lesson type is correct: lecture, online, seminar or workshop. If it is, returns True. Otherwise, returns the wrong lesson types. """ all_types = {"lecture", "online", "seminar", "workshop"} days = list(dictionary.values()) # didnt want to write...
6389d72bb37472225e4593a6bbbdab2ac3c34ac1
652,032
def solve_linear_system_LU(matrix, syms): """ Solves the augmented matrix system using LUsolve and returns a dictionary in which solutions are keyed to the symbols of syms *as ordered*. The matrix must be invertible. Examples ======== >>> from sympy import Matrix >>> from sympy.abc im...
f96eb0cc5511e9707a439a373c46e7e804912845
652,033
def PyDateTime_GET_DAY(space, w_obj): """Return the day, as an int from 1 through 31. """ return space.int_w(space.getattr(w_obj, space.newtext("day")))
1b750b59ba776ca13aa262ab7e1ec5c605900bfa
652,034
def freeze_parameters(model): """ Freezes all parameters from a given model. Args: model (any of nff.nn.models) """ for param in model.parameters(): param.requires_grad = False return model
666b265cc2ad680cccd22d8c13df6dd4a465974a
652,036
def get_stats(stat_int_list: list) -> list: """Return a list of stats in play. Argument(s): stat_int_list: list -- list of stat indices """ stat_list = [] for stat in stat_int_list: if stat == 0: stat_list.append("Hunger") elif stat == 1: stat_list.appen...
22d36dcd5cb7736c1591e635ad49650c2e51fcc5
652,039
def convert_numeral(string: str) -> str: """ Convert a assembly numeral into a hexadecimal numeral :param string: A string representation of a simpSim numeral :return: Hexadecimal representation of the numeral """ return_num: int = 0 is_pointer: bool = string.startswith("[") and string.endsw...
e50fa5a11fe19129a8edeedce3058ce6dfa0c96f
652,041
import string import random def generateCharacters(charCount): """Generates ASCII lowercase random characters""" # https://www.educative.io/edpresso/how-to-generate-a-random-string-in-python letters = string.ascii_lowercase result = "".join(random.choice(letters) for i in range(charCount)) return ...
d309e42c2692c017305eb348bc7263e255911154
652,042
def _pair_members_to_new_node(dm, i, j, disallow_negative_branch_length): """Return the distance between a new node and decendants of that new node. Parameters ---------- dm : skbio.DistanceMatrix The input distance matrix. i, j : str Identifiers of entries in the distance matrix to...
c195be1a682d6ff6d7c347338f7d641f67a59f73
652,043
def _sym_solve(Dinv, M, A, r1, r2, solve, splu=False): """ An implementation of [1] equation 8.31 and 8.32 References ---------- .. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point optimizer for linear programming: an implementation of the homogeneous a...
ed306a13e55e5d63c626e280153e38d282dca943
652,044
def root_app(expr): """Returns the pair (r, args) such that expr = r(*args) Arguments: - `expr`: an expression """ root = expr args = [] while root.is_app(): args.append(root.arg) root = root.fun #The arguments were collected in reverse order args.reverse...
500c3626cb777af28c4e58832d3ceb98751c873b
652,046
def get_file_download_details(file_response): """ Return the download_link from the file_response. Used for updating the message with a download button. """ download_link = file_response['file']['url_private_download'] return download_link
a875a14d29c20322b9efe2d986118c37498e4b04
652,047
def percentage(f): """ Return the percentage version of a float f """ return round(f * 100, 3)
cea866f21134d7d1ccc5a16c4d631c1b6d681a84
652,048
from pathlib import Path def create_module_scratch(module_name): """Create a scratch that is easily found (by developers) and removed, and doesn't clutter up the working directories. """ path = Path("~").expanduser() for path_part in ".idaes", "_scratch", module_name: path = path / path_pa...
32ba13f647805e26488cb8191afa40d5d1a02eb1
652,049
def recall(recs, truth, k=None): """ Compute recommendation recall. """ nrel = len(truth) if nrel == 0: return None if k is not None: nrel = min(nrel, k) recs = recs.iloc[:k] ngood = recs['item'].isin(truth.index).sum() return ngood / nrel
2b17beda9e4a408158ed280455d8e91fb457dd04
652,051
import torch def translation_error(pose_pred, pose_target): """ Angular error for rotation matrix :param pose_pred: shape (b, 3, 4), estimated pose :param pose_target: shape (b, 3, 4), target pose :return: float >>> import torch >>> pose_pred = torch.tensor([[1.0, 0, 0, 1], [0, 1, 0, 1],...
3ee46c5fa89fbaa4ed78be329d56f62bf95ec8d1
652,052
def _replace_match(text, match, replacement): """Expands a regexp match in the text with its replacement. Args: text: str. The text in which to perform the replacement. match: re.MatchObject. A match object that applies to "text". replacement: str. The string to replace the match wit...
a813704d4ed2d77d0f8150abe5e2917f22b93cb9
652,054
def parse(css): """Parse a CSS style into a dict.""" result = {} for declaration in css.split(";"): if declaration: key, value = declaration.split(":") result[key] = value.strip() return result
1feb5d015565920717f33536acfb2b4b81a0c261
652,056
def strip_whitespace(string_value): """ Return the input string without space, tab, or newline characters (for comparing strings) """ return ''.join( [c for c in string_value if c != ' ' and c != '\n' and c != '\t'] )
6cc68b1692bb39c66e5f09e2db009cd726526531
652,057
def amgxwrapper_poisson_read_runtimes(*filepaths): """Read the runtimes to solve the system for multiple runs. Parameters ---------- filepaths : tuple of strings or pathlib.Path objects Path of the files to read. Returns ------- runtimes : list of floats The runtimes. ...
dd5244b06737268d02dd4dc9496ae136c32e9a71
652,058
def set_device_orientation_override(alpha: float, beta: float, gamma: float) -> dict: """Overrides the Device Orientation. Parameters ---------- alpha: float Mock alpha beta: float Mock beta gamma: float Mock gamma **Experimental** """ return { ...
2113001cc29327fbadcb053c3270e32a6384ea82
652,060
def load_movies(path_movies='movies.csv'): """ Returns a dictionary mapping item_id to item_name and another dictionary mapping item_id to a list of genres """ data = {} genreMap = {} with open(path_movies, encoding = "utf8") as f_data: for line in f_data: parts = line.st...
ed0ea02ae2a676c5ff3e03f5f7bd01ec9505faca
652,061
def label_smoothing(x_onehot, epsilon=0.1): """ Label smoothing for one-hot type label. Args: x_onehot: Tensor with shape [..., depth] epsilon: float, default 0.1 The smoothing factor in range [0.0, 1.0]. Returns: Tensor with same shape as x_onehot, and its value ha...
78aaca96e940e244a6f12d97aa9bc246f2186269
652,067
def yesno(value, icaps=True): """ Return 'yes' or 'no' according to the (assumed-bool) value. """ if (value): str = 'Yes' if icaps else 'yes' else: str = 'No' if icaps else 'no' return str
9bff0a577c81c900159d9650e78a75c6869e94b9
652,071
def get_utt_id(segment): """ Gives utterance IDs in a form like: en_4156-a-36558-37113 """ return "{}-{}-{}-{}".format(segment.filename, segment.channel, int(segment.begin * 100), int(segment.end * 100),)
bfb8507a17e4a35f6daa0df8eebf06141d47f1a0
652,081
import re def GetCipdPackagePath(pkg_yaml_file): """Find CIPD package path in .yaml file. There should one line in .yaml file, e.g.: "package: chrome_internal/third_party/android_sdk/internal/q/add-ons" or "package: chromium/third_party/android_sdk/public/platforms" Args: pkg_yaml_file: The yaml file ...
9a2fcf348b98b7d8d8bc905f28e71d112a8393cf
652,082
def specific_gravity_to_gravity_points(sg, vol_gal): """Convert specific gravity to gravity points Parameters ---------- sg : float Specific gravity. vol_gal : float Wort volume, in gallons. Returns ------- gravity_points : float Gravity points. """ ...
f26ca42921ea44fd35573b93bebb5d5408dec377
652,084
def split_fullname(fullname: bytes): """ Split full backend string name into (namespace, box_id) tuple. >>> split_fullname(b'name.space.box_id') [b'name.space', b'box_id'] """ return fullname.rsplit(b'.', maxsplit=1)
81c274f96d9161cfda446516d7968c50239ebcb1
652,085
def _evaluate_results(results): """ Evaluate resulting assertions. Evaluation is OK if all assertions are true, otherwise it is KO Parameters ---------- results: list(bool) List of all assertion execution results. Returns ------- str 'OK' if all assertions are true, 'K...
331a5a46ec2e0b40197f28ba0a1f00000999077a
652,086
def sec_to_str(sec): """ Return a nice string given a number of seconds, such as 21:53. Takes into account hours, minutes, and seconds. """ s = "" if sec < 0: return "Unknown" hours = sec / 3600 min = (sec % 3600) / 60 sec = sec % 60 if hours: ...
25497dee3fe8e0898f69d0f545133f3f85c7aab0
652,089
def CreateZoneRef(resources, data): """Create zone reference from object with project and zone fields.""" return resources.Parse( None, params={'project': data.project, 'zone': data.zone}, collection='compute.zones')
7a974499626582e98301e8b020a7e0ca248f2532
652,090
def cost_of_equity_growth(div, Mv, g): """ Calculates the cost of capital or equity shareholder required rate of return for an investment in which dividend is expected to grow at a constant growth rate (dividend is about to be paid) parameters: ----------- d = dividend per share. Mv = ex-dividend share pri...
6ccc1b8d42e5b6f89dc22a4362eb8d6a10b898b3
652,092
def get_ground_truth(reader_study, display_set, question): """Get the ground truth value for the display_set/question combination in reader_study.""" ground_truths = reader_study.statistics["ground_truths"] return ground_truths[display_set][question]
e541eedfab9c46d325ffb328c573961053ef15c5
652,098
def find_columns(num): """Build the table headings for the assignment sections""" return ' '.join([str(i) for i in range(1, num + 1)])
f5f2a35cd91edb3cff5c7b1b3b523e85ebc42e81
652,102
def verify_interval_in_state_vector(statevector, start, finish): """ Verifies if there is at least one non zero entry in a given interval in the state vectors cells, and returns true if positive :param statevector: state vector to be processed :param start: start of the interval ...
31a49b6d3bec7f4cf5eded4197802f1d2ca94304
652,103
def absolute_latencies(relative_latencies): """ Compute absolute delay + stride for a each in a stack of layers. Arguments: ---------- relative_latencies: list of tuples each tuple is (rel_delay, rel_stride) Returns: -------- absolute_latencies: list of tuples each tupl...
f96384586f81b7d47dbe32f608f5f343eee91e13
652,105
def format_version(value, hero_version=False): """Formats integer to displayable version name""" label = "v{0:03d}".format(value) if not hero_version: return label return "[{}]".format(label)
5b8822b209c643e4891ea1043613fc83645d8006
652,107
def get_file_line_count(filename): """ Get the line count for the specified file """ with open(filename) as f: return sum(1 for _ in f)
85b8d93bed8aa517696abcb910a79c3d2c46b169
652,110
import copy def flatten_dict(data: dict, delimiter: str = "/") -> dict: """ Overview: flatten the dict, see example Arguments: data (:obj:`dict`): Original nested dict delimiter (str): Delimiter of the keys of the new dict Returns: - (:obj:`dict`): Flattened nested dict...
c3109116e6a486af748db787a77c833f6fc3c93b
652,114
def lowpass_filter_trace(tr, filter_order=5, number_of_passes=2): """ Lowpass filter. Args: tr (StationTrace): Stream of data. filter_order (int): Filter order. number_of_passes (int): Number of passes. Returns: StationTrace: Filtered...
dfc654860da13d9aef9f063be7afc0f0d2e70f63
652,116
def objects(obj_list): """Helper to return singular or plural of the word "object". Parameters: obj_list - any list Returns: string "object" or "objects" depending on the list length """ ret = 'objects' if len(obj_list) != 1 else 'object' return ret
5780624618de4abafaff321315d89c25d21cb6ae
652,121
def write_rex_file(bytes, path: str): """Write to disk a rexfile from its binary format""" new_file = open(path + ".rex", "wb") new_file.write(bytes) return True
4dccd6cc2dfe2fcfe7065b829803d325b4fcdfcb
652,124
def write_gao_weber_potential(parameters): """Write gao-weber potential file from parameters Parameters ---------- parameters: dict keys are tuple of elements with the values being the parameters length 14 """ lines = [] for (e1, e2, e3), params in parameters.items(): if ...
b65ceae808991cbe7a995f1dcf994d55c50ce9af
652,125
def symbol_filename(name): """Adapt the name of a symbol to be suitable for use as a filename.""" return name.replace("::", "__")
e26966e133874c5704aa7232b4abb27d2ed286e7
652,127
def viz_b(body): """Create HTML b for graphviz""" return '<B>{}</B>'.format(body)
3dfdf329977826b5ed791f1896538dacc18a041f
652,131
def op_table_md(op_sel, op_name, L1, L2): """Generate this (ish): | 6'h00 | add | a+b+d |(a+b+d) gte 2^16 | Addition | | 6'h01 | sub | a+~b+1 |(a+~b+1) gte 2^16 | Subtraction | | 6'h03 | abs |(a lt 0)? (0-a) : a | a[15] | Abso...
86525efc68baf2a0f8046a504fef430e07c05e08
652,132
def _unscale(x,rmin,rmax,smin,smax): """ Undo linear scaling. """ r = (smax-smin)/(rmax-rmin) x_ = smin + r * (x-rmin) return x_
bddba9da51c2b6a20f47d09bfc214989e6d6fb71
652,136
def _escape_filename(filename): """Escape filenames with spaces by adding quotes (PRIVATE). Note this will not add quotes if they are already included: >>> print _escape_filename('example with spaces') "example with spaces" >>> print _escape_filename('"example with spaces"') "example with ...
a27f4b1c9d5b8ad971a4e76441c6f30f05a86395
652,137
def validate_instructions(instructions, _): """Check that the instructions dict contains the necessary keywords""" instructions_dict = instructions.get_dict() retrieve_files = instructions_dict.get('retrieve_files', None) if retrieve_files is None: errmsg = ( '\n\n' 'no...
0b30579a633d6953c8cec5ac7a05cddef7e7d1df
652,146
from typing import Optional from datetime import datetime def from_litter_robot_timestamp( timestamp: Optional[str], ) -> Optional[datetime]: """Construct a UTC offset-aware datetime from a Litter-Robot API timestamp. Litter-Robot timestamps are in the format `YYYY-MM-DDTHH:MM:SS.ffffff`, so to get t...
a0b82c9d7a1b44ba4779efbe847cee4bad28e2e3
652,149
def calculate_score(move): """ Calculate the chance of this being a "good move" based on the following criteria: :moves_available: number of moves to choose between\n :move_num: how many moves we are into the game\n :num_pieces_self: how many pieces pieces we have left\n :num_pieces_opp: how ma...
a7aa720c47aba65115ee96e840bdbda6ccb1f67a
652,150
def upload_path(instance, filename): """Return path to save FileBackup.file backups.""" return f'examiner/FileBackup/' + filename
361e31f8618eb4476883f1c9bfe3a0dcdfe47d2c
652,152
def is_palindrome(number): """Check if number is the same when read forwards and backwards.""" if str(number) == str(number)[::-1]: return True return False
7ce67718a2e7ba0a1d9e276cd35b8d1b4c0e58cd
652,154
def convertAttributeProto(onnx_arg): """ Convert an ONNX AttributeProto into an appropriate Python object for the type. NB: Tensor attribute gets returned as the straight proto. """ if onnx_arg.HasField('f'): return onnx_arg.f elif onnx_arg.HasField('i'): return onnx_arg.i ...
e0a5b9629871a947714b81ca0a2527eb6458e4da
652,161
def simple_goal_subtract(goal, achieved_goal): """ We subtract the achieved goal from the desired one to see how much we are still far from the desired position """ assert goal.shape == achieved_goal.shape return goal - achieved_goal
bf35fa91fa848f070c813ba2313891672f005de9
652,170
from typing import Optional from datetime import datetime def determine_vaccine_date(vaccine_year: str, vaccine_month: str) -> Optional[str]: """ Determine date of vaccination and return in datetime format as YYYY or YYYY-MM """ if vaccine_year == '' or vaccine_year == 'Do not know': retur...
bec792faf0312ab5a7691af69b55b76a1f162267
652,173
import torch def renormalize(log_p, alpha): """ Take the model-computed log probabilities over candidates (log_p), apply a smoothing parameter (alpha), and renormalize to a q distribution such that the probabilities of candidates sum to 1. Return the log of q. """ alpha_log_p = alpha * log_p ...
54a1a215ad9c0442f3a7d9006dfe795d0ea05716
652,175
def format_table(table, key_space=5): """ Accepts a dict of {string: string} and returns a string of the dict formatted into a table """ longest = 0 for k in table: if len(k) > longest: longest = len(k) result = '' for k, v in table.iteritems(): k += (longest...
8c7966434e07992ad4c32fbadcc79df0206bb1ec
652,176
import json def loads(s): """Potentially remove UTF-8 BOM and call json.loads()""" if s and isinstance(s, str) and s[:3] == '\xef\xbb\xbf': s = s[3:] return json.loads(s)
95e403745c9738711813cf5ce2d23e54f290de0e
652,179
def query_hash(query_url): """ Generate a compact identifier from a query URL. This idenifier is then used for @ids of Ranges and Annotations. IIIF URI pattern: {scheme}://{host}/{prefix}/{identifier}/range/{name} {scheme}://{host}/{prefix}/{identifier}/annotation/{name} ...
16932924ef50437fd09b65afa6244645ae603d9e
652,182
import json def get_dataset_metadata(dataset_path: str): """ Many datasets outputted by the sklearn bot have a first comment line with important meta-data """ with open(dataset_path) as fp: first_line = fp.readline() if first_line[0] != '%': raise ValueError('arff data ...
2f0b2de4812ae1918ef3cc4bb677cdc8319a74dd
652,184
def _get_metric_value(metrics, metric_name, sample_name, labels): """Get value for sample of a metric""" for metric in metrics: if metric.name == metric_name: for sample in metric.samples: if sample.name == sample_name and sample.labels == labels: return s...
09cd422a4a536170004261ee1c5603eb1dff95ed
652,185
def tf(tokens): """ Compute TF Args: tokens (list of str): input list of tokens from tokenize Returns: dictionary: a dictionary of tokens to its TF values """ d = {} s = len(tokens) for w in tokens: if w not in d: d[w] = 1.00/s else: d...
c427fd282dd04624e7fbceed764116146e6c64ae
652,187
def find_range(nums): """Calculate the range of a given set of numbers.""" lowest = min(nums) highest = max(nums) r = highest - lowest return lowest, highest, r
0fc6275517e804a2eac018ee8474b6cddee8f898
652,192
def distance_calculator(focal_length, real_width_of_object, width_in_frame): """ This function is used to calculate the estimated distnace using triangle similarity :param1 (focal_length): The focal_length in the reference image as calculated :param2 (real_width_of_object): The real width of the ob...
8ca86eaba6eaaaa429c162b93a5ad95d2d46ec49
652,200
from pathlib import Path from typing import List def get_sorted_version_directories(changelog_path: Path) -> List[Path]: """Get all version directories and return them sorted as list.""" directories = [item for item in changelog_path.iterdir() if item.is_dir()] return sorted( directories, ...
30f8743f853af5efeb332c397e1b44fcdfdcbd99
652,203
def _shape_to_size(shape): """ Compute the size which corresponds to a shape """ out = 1 for item in shape: out *= item return out
54fbe7d2f630ebea39ea9c86ea321af445d11d78
652,205
def time_to_str(time_min:str, time_max:str): """ Replace ':' to '-' from the time variables. Parameters ---------- time_min: str Time variable with ':'. time_max: str Time variable with ':'. Returns ------- time_min_str: str Time vari...
0d7441d8b43d3d53d991033fd2aea0dc3c1c5690
652,206