content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_timeouts(builder_cfg): """Some builders require longer than the default timeouts. Returns tuple of (expiration, hard_timeout). If those values are None then default timeouts should be used. """ expiration = None hard_timeout = None if 'Valgrind' in builder_cfg.get('extra_config', ''): expirat...
4e519235a8b205621b8c99964e6fc7c4f4ab0175
675,216
import torch def _skip(x, mask): """ Getting sliced (dim=0) tensor by mask. Supporting tensor and list/dict of tensors. """ if isinstance(x, int): return x if x is None: return None if isinstance(x, torch.Tensor): if x.size(0) == mask.size(0): return x[mas...
320e96b24a703e5e5c976eda643c3f39efd04b1b
675,217
def get_columns(file): """ Se recogen las columnas "tipo_evento", "contenido" y "imagen" y se retornan """ tipo_evento = file.pop("Tipo Evento") contenido = file.pop("Contenido") imagen = file.pop(" Imagen") return tipo_evento,contenido,imagen
898d146f1da4a1841ee8f3241a87c29cc5e87f65
675,218
def get_identifier_string(model, pk): """This must match haystack.utils.get_identifier exactly!""" return u'%s.%s.%s' % ( model._meta.app_label, model._meta.module_name, str(pk).replace(' ', ''), )
e2d8cc8080160ae1e5b10847cbb8e46998fd7e2d
675,220
import glob def downloaded_long_ids(): """Returns a list of all xmls already dopwnloaded(longid).""" downloaded_files = glob.glob('xmls/*zip') long_ids = [] for download in downloaded_files: long_ids.append(download[5:21]) return long_ids
a0ad98af3aa63f392b88883cabc190a75df237fb
675,221
def index(): """ res = '###### manage.py:\n' with open('manage.py', 'r', encoding='utf8') as f: res = res + f.read() res = res + "###### database.py\n" with open('database.py', 'r', encoding='utf8') as f: res = res + f.read() res = res + '\n\n##### End...
74403885ca8aa495a6ec3f160fa532fb1b600b2a
675,222
def _get_zip_filename(xml_sps, output_filename=None): """ Obtém o nome canônico de um arquivo ZIP a partir de `xml_sps: packtools.sps.models.sps_package.SPS_Package`. Parameters ---------- xml_sps : packtools.sps.models.sps_package.SPS_Package output_filename: nome do arquivo zip Returns ...
2545fc02849d73da99a2d6c4bda3d69307f8afa1
675,223
def asic_cmd(asic, cmd, module_ignore_errors=False): """ Runs a command in the appropriate namespace for an ASIC. Args: asic: Instance of SonicAsic to run a command. cmd: Command string to execute. module_ignore_errors: Flag to pass along to ansible to ignore any execution errors. ...
76d7fe2f1ca79dc57c711c364bbd8fc76613e097
675,224
def get_annot_quality_int(ibs, aid_list, eager=True): """ new alias """ return ibs.get_annot_qualities(aid_list, eager=eager)
1571055e7f82f10111a7f13fa681a16c9a72d01a
675,225
import configparser def _config_ini(path): """ Parse an ini file :param path: The path to a file to parse :type file: str :returns: Configuration contained in path :rtype: Dict """ conf = configparser.ConfigParser() conf.read(path) return dict(conf)
12ee936fe64e89a8c6af0c44cbd6ab97f308bb8e
675,226
def read_messages_count(path, repeat_every): """ Count the predictions given so far (may be used in case of retraining) """ file_list=list(path.iterdir()) nfiles = len(file_list) if nfiles==0: return 0 else: return ((nfiles-1)*repeat_every) + len(file_list[-1].open().readlines())
c931bca2eeeefa2b02cc5770bc62c22f5e60a4b2
675,227
def text_string() -> str: """Use string as the input text.""" return "This is a text string."
086065d0ee24945b4648f0d4aecb5fdfa4b3b73b
675,228
def _rpm_long_size_hack(hdr, size): """ Rpm returns None, for certain sizes. And has a "longsize" for the real values. """ return hdr[size] or hdr['long' + size]
16326285cec0d148daaacf94b9765d673471e6e6
675,229
import math def percent(n, precision=0): """ Converts `n` to an appropriately-precise percentage. """ # 'or 1' prevents a domain error if n == 0 (i.e., 0%) places = precision - math.floor(math.log10(abs(n) or 1)) return '{0:.{1}%}'.format(n, places)
fe4690dcb6175bff6e5e19e88a87b6339892e8fd
675,230
import string import itertools def _my_alphabet(az: int): """Method used to make custom figure annotations. :param az: Index of the alphabet :return: corresponding letter """ alphabet = string.ascii_uppercase extended_alphabet = ["".join(i) for i in list(itertools.permutations(alphabet, 2))] ...
014bcae3706b2d5e97ed3c3eb3b5ed1bdf2eda1c
675,232
def Focal_length_eff(info_dict): """ Computes the effective focal length give the plate scale and the pixel size. Parameters ---------- info_dict: dictionary Returns --------- F_eff: float effective focal length in m """ # F_eff = 1./ (info_dict['pixelScale'] * #...
75d21f27c04193a5615c1877bed6d69ada2c3cad
675,233
from typing import List from typing import Tuple def __merge_closest_intervals(intervals: List[Tuple[float, float]]): """ Get the closest interval and merge those two, returnung exactly len(intervals)-1 many intervals. """ diff = [y[0] - x[1] for x, y in zip(intervals, intervals[1:])] argmin = diff.index(...
50afb7f0d44ae17eaad6934de45ab832a55b8d46
675,234
from typing import Any import textwrap import shutil def _gen_arg_msg(*args: 'Any', **kwargs: 'Any') -> str: """Sanitise arguments representation string. Args: *args: Arbitrary arguments. Keyword Args: **kwargs: Arbitrary keyword arguments. Returns: Sanitised arguments repre...
c71bb54a29cef8ab5b505f4fd99966420cd24c48
675,235
def drop_redundant_columns(df): """Given that the data has information coded as both rates and absolute values, we identified and dropped redundant information. df: original dataframe with both absolute values and rates. """ cols = list(df.columns) # identify redundant columns red...
0b6cc2f48e07fb9d4f66d57ffe936995a2899ffe
675,236
import numpy def _s(n, a, b): """Get all permutations of [a, b, ..., b] of length n. len(out) == n. """ out = numpy.full((n, n), b) numpy.fill_diagonal(out, a) return out
5ca6bb44a728de9bd8dcc9a83c1084c92b42793f
675,237
def problem_1_8(s1, s2): """ Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”). Solution: concat...
dbf2b4192b564768e98b89b8ce5368fdae3afd25
675,238
def irb_decay_to_gate_infidelity(irb_decay, rb_decay, dim): """ Eq. 4 of [IRB], which provides an estimate of the infidelity of the interleaved gate, given both the observed interleaved and standard decay parameters. :param irb_decay: Observed decay parameter in irb experiment with desired gate interle...
09f5b504ffffb047dc903a19bd51753c46cca7c2
675,239
async def send_with_reactions(ctx, embed, image): """ Sends message with reactions for member to browse data with """ # Send embed and image message = await ctx.channel.send( embed=embed, file=image ) # Add scroll control reactions reactions = [ u'\u23ee', u'\u23ea', u'\u25c0', u...
7d462f4d5a27694a97e693af04084ae1b91719dd
675,240
def get_unflat_case_tags(ibs, aids_list): """ Gets only aid pairs that have some reviewed/matched status """ ams_list = ibs.get_unflat_am_rowids(aids_list) tags = ibs.unflat_map(ibs.get_annotmatch_case_tags, ams_list) return tags
405278837ec192d0836517b705525ef12cee7c3e
675,241
def jaccard(words_1, words_2): """words_1 และ words_2 เป็นลิสต์ของคำต่าง ๆ (ไม่มีคำซ้ำใน words_1 และ ไม่มีคำซ้ำใน words_2) ต้องทำ: ตั้งตัวแปร jaccard_coef ให้มีค่าเท่ากับ Jaccard similarity coefficient ที่คำนวณจากค่าใน words_1 และ words_2 ตามสูตรที่แสดงไว้ก่อนนี้ Doctest : >>> words_1 = ['x', '...
0cc1c777f70360a4389558aef013116cc3bf50e7
675,242
def merge_list(old_list, new_list): """Merge the given 2 lists. :param list old_list: list which contains old items :param list new_list: list which contains new items :returns: merged list Merges the given 2 lists into 1 list, preferring items from *new_list* when collide. An item in the...
6fd13d72fa029dcd78d538119dd3e10a1afd849a
675,243
import json def get_rev_list_kwargs(opt_list): """ Converts the list of 'key=value' options to dict. Options without value gets True as a value. """ result = {} for opt in opt_list: opt_split = opt.split(sep="=", maxsplit=1) if len(opt_split) == 1: result[opt] = Tru...
26c5ea709245211b83bcaeccbff320d212fa32ea
675,244
def collectReviewTeams(reviewers): """collectReviewTeams(reviewers) -> dictionary Takes a dictionary as returned by getReviewersAndWatchers() or getPendingReviewers() and transform into a dictionary mapping sets of users to sets of files that those groups of users share review responsibilities for. The same user ...
3ab69a7c504592ad7f680b3e5af59536e76c4112
675,245
def _clean_semi_formatted_yaml(toclean: str): """ Our custom YAML formatter adds a bunch of stuff we need to clean up since it is working with and OrderdDict as the underlying structure. """ return toclean.replace('!!list ', '')
19c5d372c52f34acbf632ed761388ba254f7d76c
675,246
def int_to_lower_mask(mask): """ Convert an integer into a lower mask in IPv4 string format where the first mask bits are 0 and all remaining bits are 1 (e.g. 8 -> 0.255.255.255) :param mask: mask as integer, 0 <= mask <= 32 :return: IPv4 string representing a lower mask corresponding to mask ""...
d3029ac0e8dd63b1ae361e0351a1e2b8e29be39f
675,249
def roman_to_int(roman: str) -> int: """Convert Roman numeral string to int""" roman_lookup = { "I": 1, "IV": 4, "V": 5, "IX": 9, "X": 10, "XL": 40, "L": 50, "XC": 90, "C": 100, "CD": 400, "D": 500, "CM": 900, ...
9895d9f15a141d3e39976d3c0372c317848c556b
675,250
import os def canonicalize(path): """returns the canonical reference to the path that can be used for comparison to other paths""" return os.path.normpath(os.path.realpath(os.path.abspath(path)))
743fa42b0732538b8b3af4e002e77fe2dc07f1be
675,251
def zero_fill(value: bytearray) -> bytearray: """ Zeroing byte objects. Args: value: The byte object that you want to reset. Returns: Reset value. """ result = b'' if isinstance(value, (bytes, bytearray)): result = b'/x00' * len(value) result = bytearray(res...
e5ce1b6162071e3aed7d5adb3aa5b0a20fc526a7
675,252
def print_test_result(test_result, target_name, toolchain_name, test_id, test_description, elapsed_time, duration): """ Use specific convention to print test result and related data.""" tokens = [] tokens.append("TargetTest") tokens.append(target_name) tokens.append(toolchain_n...
60f3c7bb51f5ce2ea52e05994a3a9eed01b945fa
675,253
import pathlib def get_src_dir(file: str) -> pathlib.Path: """Returns the Path to this project's /src directory. Args: file: __file__ """ src_dir = str(pathlib.Path(file).parent.absolute()) if src_dir.lower().endswith("src"): return pathlib.Path(src_dir) else: raise V...
a75db7fcad531e6d68f7e443b54d7f7bdc46d3bd
675,255
def get_user_choice(choices): """ ask the user to choose from the given choices """ # print choices for index, choice in enumerate(choices): print("[" + str(index) + "] " + choice) # get user input while True: user_input = input("\n" + "input: ") if (user_input.isdig...
5b1c379524b6f66d315c20288487921258b302fa
675,256
def get_size_from_block_count(block_count_str, size_step=1000, sizes = ["K", "M", "G", "T"], format_spec=":2.2f"): """Transforms block count (as returned by /proc/partitions and similar files) to a human-readable size string, with size multiplier ("K", "M", "G" etc.) appended. Kwargs: * ``size_step``:...
5e9efdc7ed573b19a51ca8602b24e56726d40597
675,257
def ifp_change(seg, seq_len): """ mark the idx at which IpForwardingPattern changes, i.e. the beginning of a new segment Args: seg (list of PatternSegment): the out put of ifp change detection algos seq_len: the total length of the path sequence Returns: list of...
8880906a3e8e221cda89ec22ad3d304e04a4f864
675,258
import subprocess import json def oc_image_info(pullspec): """Get metadata for an image at the given `pullspec` :return: a dict with the serialzed JSON from the 'oc image info' call """ image_info_raw = subprocess.check_output( ['oc', 'image', 'info', '-o', 'json', pullspec]) return json....
b2ee3a42bad9e8b1fbc649036bc9b8af9f09986d
675,259
def max_sample_size(dataset): """extract the length of the smallest label""" result = float('inf') for label, points in dataset: result = min(result, len(points)) print("The maximum possible sample size for the dataset is {n}".format(n=result)) return result
980a7eaacbbb9223a558736824c6d5333a5873a2
675,260
def indent(text, amount=4): """Indent a string. :param text: The text to be indented. :type text: str :param amount: The number of spaces to use for indentation. :type amount: int :rtype: str .. code-block:: python from superpython.utils import indent text = "This text ...
2093d7f724adb1dc6fccfbb772e3def5037476a1
675,261
import functools def memoize(f): """ Minimalistic memoization decorator (*args / **kwargs) Based on: http://code.activestate.com/recipes/577219/ """ cache = {} @functools.wraps(f) def memf(*args, **kwargs): fkwargs = frozenset(kwargs.items()) if (args, fkwargs) not in cache: ...
c87499db6856f988db389afd54350b96f7334fd2
675,262
def get_restaurants_by_meal(city_data, meal_type): """Return a restaurant list based on meal type.""" # type: (Dict, str) -> List return [r for r in city_data["restaurants"] if meal_type in r["meals"]]
01af773916bb21f8b61af685a43a66f98349e50a
675,263
import cgi def check_api_v3_error(response, status_code): """ Make sure that ``response`` is a valid error response from API v3. - check http status code to match ``status_code`` :param response: a ``requests`` response :param status_code: http status code to be checked """ assert n...
ca1be2ac3cff99b06fc0aaba73a075ff90024c9b
675,264
def fail(s): """ A function that should fail out of the execution with a RuntimeError and the provided message. Args: s: The message to put into the error. Returns: A function object that throws an error when run. """ def func(): raise RuntimeError(s) return fu...
f7a3e886d671a5eca872620cb6117912573f9c81
675,265
import copy def vertex_needs_update(vertex_attrs, new_attrs): """remove attributes that already been set or deleted""" pattributes = copy.deepcopy(new_attrs) for key in new_attrs.keys(): if (key in vertex_attrs and vertex_attrs[key][0] == new_attrs[key]) or \ (key not in vertex_att...
718d3d10331ad7e43ef0716bd66f4875a28ab409
675,266
import click def multi_option(*param_decls, **attrs): """modify help text and indicate option is permitted multiple times :param param_decls: :param attrs: :return: """ attrhelp = attrs.get('help', None) if attrhelp is not None: newhelp = attrhelp + " (multiple occurrence permitt...
b417c0fd36bf6ec0c1ab3c909ad9004c2c6e755b
675,267
def _get_annotations(generator): """ Get the ground truth annotations from the generator. The result is a list of lists such that the size is: all_detections[num_images][num_classes] = annotations[num_detections, 5] # Arguments generator : The generator used to retrieve ground truth annota...
23287064b16e08566c7754dd9f6221ab42017428
675,268
def is_simple_locale_with_region(locale): """Check if a locale is only an ISO and region code.""" # Some locale are unicode names, which are not valid try: lang, sep, qualifier = locale.partition('_') except UnicodeDecodeError: return False if '-' in lang: return False # ...
f59af0a4d4b8d9905a2558facdbd863e879105aa
675,269
def format_output_mesmer(output_list): """Takes list of model outputs and formats into a dictionary for better readability Args: output_list (list): predictions from semantic heads Returns: dict: Dict of predictions for whole cell and nuclear. Raises: ValueError: if model outp...
5603ac838b9f31179577c81de4be4b72e62fdbd3
675,271
import torch def extract_torchmeta_task(cs, class_ids): """ Extracts a single "episode" (ie, task) from a ClassSplitter object, in the form of a dataset, and appends variables needed by DatasetDistance computation. Arguments: cs (torchmeta.transforms.ClassSplitter): the ClassSplitter ...
7a342b95d88a65b9103380b3ed08d9e28a3ca5bf
675,272
import re def match_and_rewrite_lines(pattern, file_body, version): """ Replace lines by regex """ lines = [] updated = False for line in file_body.splitlines(): re_out = re.sub(pattern, r'\1%s\3', line) if re_out != line: updated = True lines.append(re_...
9195d5c862a8e73f4064418daead7d8747afae38
675,273
import unicodedata def full2half(uc): """Convert full-width characters to half-width characters. """ return unicodedata.normalize('NFKC', uc)
2d41e41279f3b3a3a992097340aefb7b18333cfd
675,274
import os def sequence_exists(sceneflow_base_dir, sample_base_dir): """ Returns whether or not the path to a sequence exists :param sceneflow_base_dir: :param sample_base_dir: :return: """ sequence_path = os.path.join(sceneflow_base_dir, sample_base_dir) if os.path.isdir(sequence_path)...
5ceda99547447513f79c514f9b51c12279dc3e75
675,275
def simple_function(arg1, arg2=1): """ Just a simple function. Args: arg1 (str): first argument arg2 (int): second argument Returns: List[str]: first argument repeated second argument types. """ return [arg1] * arg2
ef302ed0b01af83ad373c90c6689a33ed8922ee1
675,276
def _object_type(pobj): ############################################################################### """Return an XML-acceptable string for the type of <pobj>.""" return pobj.__class__.__name__.lower()
9720d869a001416110932de33a7c6b0f57f76e02
675,278
import re def smi_tokenizer(smi): """ Tokenize a SMILES """ pattern = "(\[|\]|Xe|Ba|Rb|Ra|Sr|Dy|Li|Kr|Bi|Mn|He|Am|Pu|Cm|Pm|Ne|Th|Ni|Pr|Fe|Lu|Pa|Fm|Tm|Tb|Er|Be|Al|Gd|Eu|te|As|Pt|Lr|Sm|Ca|La|Ti|Te|Ac|Si|Cf|Rf|Na|Cu|Au|Nd|Ag|Se|se|Zn|Mg|Br|Cl|U|V|K|C|B|H|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/...
65cbb63fff66582be2da19f655d7cecd45fd2e9a
675,279
def b2s(binary): """ Binary to string helper which ignores all data which can't be decoded :param binary: Binary bytes string :return: String """ return binary.decode(encoding='ascii', errors='ignore')
c92a07c37545f259ee1ffa6252c9e9e337ee3a42
675,280
def get_intersection_difference(runs): """ Get the intersection and difference of a list of lists. Parameters ---------- runs set of TestSets Returns ------- dict Key "intersection" : list of Results present in all given TestSets, Key "difference" : list of Resu...
6a534749357027b8e11367a1956a6ffe2d438455
675,282
def Nxxyy2yolo(xmin, xmax, ymin, ymax): """convert normalised xxyy OID format to yolo format""" ratio_cx = (xmin + xmax)/2 ratio_cy = (ymin + ymax)/2 ratio_bw = xmax - xmin ratio_bh = ymax - ymin return (ratio_cx, ratio_cy, ratio_bw, ratio_bh)
7dc7e7fd36a5bea9606dfd2414199abc7de00190
675,283
def all_children(mod): """Return a list of all child modules of the model, and their children, and their children's children, ...""" children = [] for idx, child in enumerate(mod.named_modules()): children.append(child) return children
c132968d51f0f1cad5c356a1e6b52afbf82c145f
675,284
def sample_fetcher(base): """Factory for fetcher mock""" def fetcher(ticket): """Fetcher mock""" url = "https://example.com/%s?id=%s" % (base, ticket, ) # Simple cases if ticket == "KNOWN": return (url, "found %s ticket" % (base, )) if ticket == "UNKNOWN": ...
3b1d601267a6d0cef46ddf5142be010b652375fa
675,285
def get_ioi_site(db, grid, tile, site): """ Returns a prxjray.tile.Site object for given ILOGIC/OLOGIC/IDELAY site. """ gridinfo = grid.gridinfo_at_tilename(tile) tile_type = db.get_tile_type(gridinfo.tile_type) site_type, site_y = site.split("_") sites = tile_type.get_instance_sites(grid...
57069797c16c7c48e6ff906822e508594d666d51
675,286
import re def preprocess(nlp, strlist, min_token_len = 2, allowed_pos = ['ADV', 'ADJ', 'VERB', 'NOUN', 'PART', 'NUM', 'PROPN']): """ Pre-process texts and return lemmatized words params ---- nlp: Spacy en_core_web_sm model strlist : list of strin...
ae4290a3deeed9d2af5b4d71d5d9a9c7f670e114
675,287
def reverse(values): """ REVERSE - WITH NO SIDE EFFECTS! """ output = list(values) output.reverse() return output
5b80abd61bf4c06e15f644e60b8fea6dd023e615
675,288
def normalize_filename(filename): """Normalizes the name of a file. Used to avoid characters errors and/or to get the name of the dataset from a url. Args: filename (str): The name of the file. Returns: f_name (str): The normalized filename. """ if not isinstance(filename, str...
df3a511666e54d007fec514aa4eded24c90c001e
675,289
def bytes_to_num(data): """ *data* must be at least 4 bytes long, big-endian order. """ assert len(data) >= 4 num = data[3] num += ((data[2] << 8) & 0xff00) num += ((data[1] << 16) & 0xff0000) num += ((data[0] << 24) & 0xff000000) return num
8b8415c2fff3aa84c7828f47a13c9a691119df27
675,290
def find_double_newline(s): """Returns the position just after a double newline in the given string.""" pos1 = s.find(b'\n\r\n') # One kind of double newline if pos1 >= 0: pos1 += 3 pos2 = s.find(b'\n\n') # Another kind of double newline if pos2 >= 0: pos2 += 2 if pos1 >= 0:...
629b26df85ef068a6b390640c5ffbbde8ae7616b
675,291
def first_axis(*dfs, axis='index'): """DataFrames中第一个元素的轴""" if axis == 'index': return dfs[0].index else: return dfs[0].columns
af252a0f387f5e9e7c98475ca49fd976ae386722
675,292
import math def calculateDbWeighting(f): """ this function calculates the frequency-dependent weighting of A and C filters according to the IEC specifications: IEC (2002). "Sound level meters - Part 1: Specification," International Electrotechnical Commission, Geneva, Switzerland @param f: the freuqency [Hz] ...
861c37949a3470e2af3da21951509d0a2e332e4a
675,293
import re import os def grep_1(path, regex): """ wrapper around grep functionality """ regObj = re.compile(regex) res = [] for root, dirs, fnames in os.walk(path): for fname in fnames: if not fname.startswith("."): with open(root + "/" + fname, "r") as f: ...
11b728efbfb641053b18d1974eb8f1e84c29c8fd
675,294
import re def promote_trigger(source: list, trigger: str) -> list: """Move items matching the trigger regex to the start of the returned list""" result = [] r = re.compile(trigger) for item in source: if isinstance(item, str) and r.match(item): result = [item] + result else...
db5b3f8fa6e73be764f993132f85c05b8690176c
675,295
import time def get_date_string_tuple_from_git_log_msg(msg): """ identify date within each commit record from 'git log' """ ''' commit fc8fb8e9b3a5174303d3733e1646d53a3dc5f638 Author: naverdev <naverdev@naver.com> Date: Tue Mar 4 06:58:15 2014 +0000 initialized Git reposito...
a3a7964f3c37678c4361c01983b06379733ff19a
675,297
import torch def spmatmul(den, sp): """ den: Dense tensor of shape batch_size x in_chan x #V sp : Sparse tensor of shape newlen x #V """ batch_size, in_chan, nv = list(den.size()) new_len = sp.size()[0] den = den.permute(2, 1, 0).contiguous().view(nv, -1) res = torch.spmm(sp, den).view...
c37d7cf733f8f6ff776b4f4d1198e5014a194a82
675,298
def oscar_calculator(wins: int) -> float: """ Helper function to modify rating based on the number of Oscars won. """ if 1 <= wins <= 2: return 0.3 if 3 <= wins <= 5: return 0.5 if 6 <= wins <= 10: return 1.0 if wins > 10: return 1.5 return 0
31350d7ab5129a5de01f1853588b147435e91ab2
675,299
import math def initial_compass_bearing(lat1, lng1, lat2, lng2): """ Calculates the initial bearing (forward azimuth) of a great-circle arc. Note that over long distances the bearing may change. The bearing is represented as the compass bearing (North is 0 degrees) Args: lat1 (str): The l...
d49055401e3f3be7f8c87a9cc65cdf8747d706ce
675,300
def intersect(t1, t2): """Assumes t1 and t2 are tuples Returns a tuple containing elements that are in both t1 and t2""" result = () for e in t1: if e in t2: result += (e,) return result
af1007e7460224fcafea670e431993eb4c6832e6
675,301
import math def is_in_bound(x, bound=None): """Check if the value is within the limits.""" if bound == None: bound = math.inf # default to greater than zero if x > 0 and x < bound: return 1 else: return 0
13ea0b9f2412134f4ca2589e427326e56d3fd388
675,302
def WDiffPath(): """Path to the WDiff executable, which we assume is already installed and in the user's $PATH.""" return 'wdiff'
b4ca11a93a336d1387fb97df00d78ba449fee0e3
675,304
import base64 def get_svg(path): """Get an svg image into format to properly display This formats the svg image found at `path` into the str necessary for displaying in a dcc.Img component. from https://github.com/plotly/dash/issues/537 Parameters ---------- path : str path to t...
fa4583b15ffe5dbc0c795a05b5c68195e252989b
675,306
def clean_meta_args(args): """Process metadata arguments. Parameters ---------- args : iterable of str Formatted metadata arguments for 'git-annex metadata --set'. Returns ------- A dict mapping field names to values. """ results = {} for arg in args: parts = [x...
e0e55a759b0a563216350b14cd6bc0de648006f3
675,308
def _default_filter(meta_data): """The default meta data filter which accepts all files. """ return True
61a682e8cb3ef2ed39c365c78b3cf9d407bfceb4
675,309
import uuid def generate_fwan_process_id() -> str: """ Generates a new Firmware Analysis Process ID """ return str(uuid.uuid4())
7ab3262d4bd1c915c086d5df9f582628245aae58
675,310
def process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (dictionary) raw structured data to process Returns: Dictionary. Structured data with the following schema: { "kernel_name": string, "node_name": ...
15194aa4be7b290ba7225036e10822e07c440eb8
675,311
import numpy as np def arclength( lat1, lon1, lat2, lon2, radius=None ): """Arc-length distance in km Assumes angles in degrees ( not radians ). Todd Mitchell, April 2019""" if radius is None: radius = 6.37e3 # in km meanlat = np.mean( ( lat1, lat2 ) ) rcosine = radius * np.cos...
5f564f201c626423cc5322768e6d7b5d1be26017
675,312
from typing import Callable from typing import Any def uncurry_explicit(function: Callable, arity: int) -> Callable: """ The inverse of curry_explicit. :param function: curried function. :param arity: the number of arguments that the original function takes. :return: original (not curried) functi...
f70e51a5a051d28798fa984b141808d787e0632b
675,313
from shutil import copyfile import os def move(src, dst): """ Moves a file from path src to path dst. If a file already exists at dst, it will not be overwritten, but: * If it is the same as the source file, do nothing * If it is different to the source file, pick a new name for the copy that ...
770525283b4902f7f348e0568e5637445d23643b
675,314
import keyword def pykeyword(operation='list', keywordtotest=None): """ Check if a keyword exists in the Python keyword dictionary operation: Whether to list or check the keywords. Possible options are list and check. The default is 'list'. keywordtotest: The keyword to test for if the oper...
7e8e3e1792e347b7dd6ec88fcf7c2411a7b212f5
675,315
def validate(contacts, number): """ The validate() function accepts the contacts array and number as arguments and checks to see if the number inputted is in the range of the contacts array. It returns a number inputted by the user within that range. """ while number<1 or number>len(contacts): p...
f9dc7b4287e9f0bdc7c6da8240c49e0f4438c6c8
675,316
def thresh_hold_binarization(feature_vector, thresh_hold): """ Turn each value above or equal to the thresh hold 1 and values below the thresh hold 0. :param feature_vector: List of integer/float/double.. :param thresh_hold: Thresh hold value for binarization :return: Process and binarized list ...
b16d7d1b4e9700b41da82b2985a29eaa3f6d25ad
675,317
def transform_okta_user(okta_user): """ Transform okta user data :param okta_user: okta user object :return: Dictionary container user properties for ingestion """ # https://github.com/okta/okta-sdk-python/blob/master/okta/models/user/User.py user_props = {} user_props["first_name"] = o...
8a1379f1a72c8d4d665d1f4daeae8a02c86a4c13
675,318
import random def mutated_value(value, amplitude_mut): """return a randomly choosen mutated equivalent of given value""" return value + int((random.gauss(0, 1) * amplitude_mut))
73111dc041bbafd471a341105be6d361bdaea3b9
675,319
def _compare_fq_names(this_fq_name, that_fq_name): """Compare FQ names. :param this_fq_name: list<string> :param that_fq_name: list<string> :return: True if the two fq_names are the same """ if not this_fq_name or not that_fq_name: return False elif len(this_fq_name) != len(that_fq_...
69f3505ac1f5cdec0cd5824b86927a2f33ffb7bf
675,320
def chunk(string: str, width: int) -> list[str]: """Split the given string into a list of lines, where the length of each line is less than the given width.""" lines = string.splitlines() chunked = [] for line in lines: chunked.append("") words = line.split() if any(len(word) >= ...
029eb8f7f9785d4696f59f34a381e4775a7572f8
675,321
import os def load_plot(plot_name): """Load an svg from the plot directory, given a filename.""" svg_data = None with open(os.path.join("plot", plot_name), "r") as svg_file: svg_data = svg_file.read() return svg_data
130757c664e1b7da32bac1adf5a096a2de4ccaa1
675,323
def remove_element_from_list(x, element): """ Remove an element from a list :param x: a list :param element: an element to be removed :return: a list without 'element' Example: >>>x = [1, 2, 3] >>>print(arg_find_list(x, 3)) [1, 2] """ return list(filter(lambda a: a...
34b8fc375719c41a9ec31a0c086d9268e51be089
675,324
def field(key, required=False, default=None, restricted=False, readonly=True): """ property factory for primitives(string, int, ...) Args: - key: the key to access this field in json - required: if this field is required, would raise exception if corresponding field doesn't existed in...
f87848a5897705254ee0c938bba875f702b85220
675,325
import sys def set_scraper_variables(domain, website_list): """set which elements to extract content from based on the target website""" if domain == website_list[0]: title_wrapper = "h1" title_attr = "itemprop" title_attr_name = "headline" content_wrapper = "div" con...
e84f0c4a48c70c64201b0be9dec07183d88470a0
675,326
from typing import Optional import re def search_merge_regex(merge_regex: bytes, message: bytes) -> Optional[bytes]: """ :param merge_regex: The regex to search for :param message: The commit message :return: branch name, or None """ m = re.search(merge_regex, message) if not m: re...
cac0ec70057dc99713766ac7fc78e2c8b539bcd2
675,327
def merge_sort(nums): """Merge Sort""" if not nums: return None def merge(C, p, q, r): A = C[p:q+1] B = C[q+1:r+1] i = r j = len(A) - 1 k = len(B) - 1 while i >= p: if (j >= 0 and k >= 0): if A[j] > B[k]: ...
623f24f4e19d60a859caca0152c3fc6bb05990b6
675,328