content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import ipaddress def is_default_route(ip): """ helper to check if this IP is default route :param ip: IP to check as string :return True if default, else False """ t = ipaddress.ip_address(ip.split("/")[0]) return t.is_unspecified and ip.split("/")[1] == "0"
321c610c02484f8231bf050bc9b6a39c8c48386a
685,430
import inspect def get_class_that_defined_method(method): """ Returns the class that defined the method Got implementation from stackoverflow http://stackoverflow.com/a/25959545/3903832 """ # for bound methods if inspect.ismethod(method): for cls in inspect.getmro(method.__self__._...
c1e32bbcc180dae66bc9e6e2447a163eaee993a4
685,431
def expand_noderange(value): """Expand a given node range like: '1-10,17,19'""" ranges = value.split(',') nodes = [] for r in ranges: if '-' in r: start, end = r.split('-') nodes += [str(i) for i in range(int(start), int(end) + 1)] else: nodes.append(r...
5df0572ffb4f7b457038f90a81d02f6479fd1a8f
685,435
from datetime import datetime def datetimes_equal_minutes(dt1, dt2): """Assert that two datetimes are equal with precision to minutes.""" return datetime(*dt1.timetuple()[:5]) == datetime(*dt2.timetuple()[:5])
7d2ddd8fce7414d0ada4e95c93de552c5f7e49ec
685,439
import re def replcDeid(s): """ replace de-identified elements in the sentence (date, name, address, hospital, phone) """ s = re.sub('\[\*\*\d{4}-\d{2}-\d{2}\*\*\]', 'date', s) s = re.sub('\[\*\*.*?Name.*?\*\*\]', 'name', s) s = re.sub('\[\*\*.*?(phone|number).*?\*\*\]', 'phone', s) s = re...
5a877d752b72e38ac92435a83c3c20284f6ac8d1
685,440
def prep_words(name, word_list_ini): """Prep word list for finding anagrams.""" print("length initial word_list = {}".format(len(word_list_ini))) len_name = len(name) word_list = [word.lower() for word in word_list_ini if len(word) == len_name] print("length of new word_list = {}".format(len(word_li...
dc5525c1486ada171560b7dbe2c92cad59664762
685,442
def _pathlib_compat(path): """ For path-like objects, convert to a filename for compatibility on Python 3.6.1 and earlier. """ try: return path.__fspath__() except AttributeError: return str(path)
5f91c9f5653451e381167c307d473f735b1d69e0
685,443
def _GetEnumValue(helper, name_or_value): """Maps an enum name to its value. Checks that a value is valid.""" if isinstance(name_or_value, int): helper.Name(name_or_value) # Raises EnumError if not a valid value. return name_or_value else: return helper.Value(name_or_value)
10656c8073d5bafd0b846bbcc30fcce4e7274881
685,444
def get_opacity(spectrum, mean): """ Calculate the opacity profile for the spectrum. This simply divides the spectrum's flux by the mean. :param spectrum: The spectrum to be processed :param mean: The mean background flux, representing what the backlighting sources average flux. :return: The op...
13cdf27a020c066b57a8eb7b4a5957a3cced26de
685,445
import torch def _rezise_targets(targets, height, width): """ Resize the targets to the same size of logits (add height and width channels) """ targets = torch.stack(targets) # convert list of scalar tensors to single tensor targets = targets.view( targets.size(0), targets.size(1), 1, 1, ...
2cbb2db0bd11f0d3cab3c558516a46f8e1fb1b6e
685,447
import hmac import hashlib import base64 def get_uid(secret_key, email): """ This function calcualtes the unique user id :param secret_key: APP's secret key :param email: Github user's email :return: unique uid using HMAC """ dig = hmac.new(bytes(secret_key.encode()), email.encode(), hash...
d12b1abbec92f8767a347b9cab173af4031bcc83
685,448
from typing import Sequence from typing import Tuple def get_violations_count(individual: Sequence, queens_amount: int) -> Tuple[int]: """Get the amount of violations. A violation is counted if two queens are placed in the same column or are in the same diagonal. Args: individual (deap.creator.Si...
2c086cecfdf5545815b3431b9ade733b4eabc2ef
685,452
def custom_sort(x: str): """ All sorted lowercase letters are ahead of uppercase letters. All sorted uppercase letters are ahead of digits. All sorted odd digits are ahead of sorted even digits. """ return ( not str(x).isalpha(), not str(x).islower(), str(x).isdigit(), ...
8d869acb48ed75ee8174bd7a0606688df61a6ab4
685,455
def miles_to_kilometers(L_miles): """ Convert length in miles to length in kilometers. PARAMETERS ---------- L_miles: tuple A miles expression of length RETURNS ---------- L_kilometers: float The kilometers expression of length L_miles """ return 1...
bae2f8d6b11477461c84e098a90c6597cb986dad
685,459
import logging def check_element_balance(elements, species, reaction, limit=1e-5): """Check the given reaction for their element balance.""" elm_sum = {key: 0.0 for key in elements.keys()} for spc, spc_nu in reaction.reactants.items(): for key in species[spc].thermo.composition: elm_s...
fbc760606a2d6cb2f1c9108c8896e44811f22cbd
685,467
def get_domain_class_attribute_names(ent): """ Returns all attribute names of the given registered resource. """ return ent.__everest_attributes__.keys()
4ba022426397270942ce176b97a655c63f647c1d
685,471
def load_descriptions(doc): """ Loads description (Captions) :param doc: Caption text files :return: Captions mapped to images """ mapping = dict() # process lines for line in doc.split('\n'): # split line by white space tokens = line.split() if len(line) < 2: ...
77d8e960a46019bd2e803c9b54785ce984cc581b
685,475
def batched_index_select_nd_last(t, inds): """ Index select on dim -1 of a >=2D multi-batched tensor. inds assumed to have all batch dimensions except one data dimension 'n' :param t (batch..., n, m) :param inds (batch..., k) :return (batch..., n, k) """ dummy = inds.unsqueeze(-2).expand...
b90f0f07e666837c8abf818754f30111b26768fe
685,482
def gq_get_vertex_user(user): """Create the gremlin query that returns a Vertex for a user given its uuid """ query = "g.V().hasLabel('user').has('uuid', '{}')".format(user.uuid) return query
52509c27280a3e0fd4eb57b44fe5fbec8c0c3b20
685,483
def remove_duplicates(list_with_duplicates): """ Removes the duplicates and keeps the ordering of the original list. For duplicates, the first occurrence is kept and the later occurrences are ignored. Args: list_with_duplicates: list that possibly contains duplicates Returns: A list ...
e72e26e69f9476669906ba2aa7864cec9eaf64d4
685,484
import torch def negate_bounds(bounds: torch.Tensor, dim=-1) -> torch.Tensor: """Negate a bounds tensor: (1 - U, 1 - L)""" return (1 - bounds).flip(dim)
f04725b6a6cc4b1a612f801c1c6252845c4a3a8e
685,485
import glob def get_all_file_path_in_dir(dir_name): """ dir内の全てのファイルのパスを取得する関数 Args: dir_name (str): directory name Returns: All file path name str list """ all_file_path_list = [r for r in glob.glob(dir_name + '/*')] return all_file_path_list
87cfac66ea4d3d52fff7222f3b5363026fac213c
685,487
import ast def check_funcdefaultvalues(node): """ Returns if there are function definitions with default values. """ class Visitor(ast.NodeVisitor): def __init__(self): self.found = False def visit_FunctionDef(self, node): self.gener...
d30f8c9f6115fb7a000c024c27e3cff108529a18
685,489
def adjust_height(v1, height): """ Increases or decreases the z axis of the vector :param v1: The vector to have its height changed :param height: The height to change the vector by :return: The vector with its z parameter summed by height """ return (v1[0], v1[1], v1...
5cc53853a6e93ec5c046b9937fceb6ca9262619d
685,490
import base64 def encode_array(array): """Encodes array to byte64 Args: array (ndarray): array Returns: byte64: encoded array """ # Encoding of 3darray to save in database encoded_array = base64.b64encode(array) return encoded_array
8c5fde55762ed3520de48bf5197012f1ac925192
685,495
def _create_facilities(handler, facilities=None): """Initialize a facilities dictionary.""" if facilities is None: facilities = dict() for facility in handler.facility_names.keys(): if getattr(handler, 'LOG_%s' % facility.upper(), None) is not None: facilities[facility] = handler...
51f273005d2c685101366c0c5405568a19ffb925
685,499
def isRequest(code): """ Checks whether a code indicates a request. :param code: code the code to check :return: True if the code indicates a request """ return 1 <= code <= 31
6bb336aee1393e296d0bd06d70f12d8d6b64ecb1
685,503
import re def uc_sequence(x: str)-> str: """ Input: String Output: String Check if there is any word exists with first alphabet uppercase and else lower case. """ c = re.findall("[A-Z][a-z]*",x) if c: return "Yes" else: return "No"
2e5e3d118aa1cb2742a2803b7a3023911dc51e7a
685,505
def set_bit(a, order): """ Set the value of a bit at index <order> to be 1. """ return a | (1 << order)
e67f538dba4fc93d2a9511a116e7f30fbc16d0a2
685,506
def ensure_iterable(obj): """ Ensures that the object provided is a list or tuple and wraps it if not. """ if not isinstance(obj, (list, tuple)): obj = (obj,) return obj
f26dce0b19f5428179e0b8af058e675f81540edd
685,508
def gen_matchups(n): """ generate seed pairs for a round >>> gen_matchups(4) [(1, 4), (2, 3)] """ seeds = range(1, n+1) games = [] for i in range(n/2): low = seeds[i] hi = seeds[-(i+1)] games.append((low, hi)) return games
5fa0ba698764f8fcc4685d1c84a3679985217f3f
685,514
import re def regex_token_replace(sentence: str, token: str, replacement: str) -> str: """ replace all occurrences of a target token with its replacement :param sentence: input sentence to be modified :param token: target token to be replaced :param replacement: replacement word for the target tok...
ac63e2a85be1b4f05b98be8b6f42d1eb8f334961
685,515
def build_catalog_url(account: str, image_digest: str) -> str: """ Returns the URL as a string that the policy engine will use to fetch the loaded analysis result from the catalog :param account: :param image_digest: :return: """ return "catalog://{}/analysis_data/{}".format(account, image_d...
cdcdd003e05c5d51ddcd7e05a6279897a226fd59
685,519
def has_common_element(a, b): """ Return True if iterables a and b have at least one element in common. """ return not len(set(a) & set(b)) == 0
d684000f89807e15150fc591e5ad1a5c9c459ada
685,525
import inspect def my_caller(up=0): """ Returns a FrameInfo object describing the caller of the function that called my_caller. You might care about these properties of the FrameInfo object: .filename .function .lineno The `up` parameter can be used to look farther up the...
e4ef0d3ab6bd4aac43d931d2c23bb84cfe5cce38
685,526
def non_negative_int(s: str) -> int: """ Return integer from `s`, if `s` represents non-negative integer, otherwise raise ValueError. """ try: n = int(s) if n < 0: raise ValueError return n except ValueError: raise ValueError('Must be non-negative inte...
5df9c1b340afc4251a288cded079ff4c15b05730
685,530
import torch from typing import Sequence def crop(data: torch.Tensor, corner: Sequence[int], size: Sequence[int], grid_crop: bool = False): """ Extract crop from last dimensions of data Parameters ---------- data: torch.Tensor input tensor [... , spatial dims] spatial dims can be arbitrar...
d917400cf078659c7ae0d83f9e5a6974f0d48fd0
685,531
def get_page_by_uid(uid, pages): """ Get a page by its UID Args: uid (str): The page UID to search for pages (list of dict): list of pages Returns: dict: The matching page if any """ page_info = [page for page in pages if page["uid"] == uid] if page_info: r...
d343ca403bd15972afaa634668165f1c1ed88b1f
685,533
def union_contiguous_intervals(arr): """ Union contiguous intervals. arr = list of [(st,ed),...] """ arr = sorted(arr) def _gen(): st0,ed0 = arr[0] for st1,ed1 in arr[1:]: if ed0 < st1: # ed1<st0 new interval yield [st0,ed0] st0,ed0 = st1,e...
05371de6b55c80c51dbb2ba95c30a76b07a8d7ab
685,535
from typing import List from typing import Tuple def compare_triplets(a: List[int], b: List[int]) -> Tuple[int, ...]: """ >>> compare_triplets((5, 6, 7), (3, 6, 10)) (1, 1) """ zip_ab = tuple(zip(a, b)) # alice, bob = 0, 0 # for x, y in zip_ab: # if x > y: # alice += 1 ...
1ce3d19c0eace387ed96d2f282e7144b4e225510
685,537
def is_client_error(code): """Return that the client seems to have erred.""" return 400 <= code <= 499
178d642f9c694fb5a488320626dddb32694ef45c
685,547
def cmd_resolve_strings(lresolver, resolve_strings): """Handle resolve-string command.""" for string in resolve_strings: print(lresolver.resolve_string(string)) return 0
6770bef9988334fedab1d5dcf5999372fdc44eb0
685,548
def get_dims(shape, max_channels=10): """Get the number of dimensions and channels from the shape of an array. The number of dimensions is assumed to be the length of the shape, as long as the shape of the last dimension is inferior or equal to max_channels (default 3). :param shape: shape of an array. ...
bcffcc217226291963def5c8dba89ef4ebfa08fd
685,549
from typing import List def get_shrink_board( board: List[List[str]], is_flatten: bool ) -> List: """ Get only the building placeholder. (Note: In other word, remove the row and column header.) Parameters ---------- board: List[List[str]] 2D array conta...
9428bca63e87d02f45e88f88bdb5b2baa9c34929
685,551
def same_lists(first, second): """Do the 2 input lists contain equivalent objects?""" nobjs = len(first) if len(second) != nobjs: return False # This is a bit of a brute-force approach since I'm not sure whether # ExposureGroups will get ordered consistently by a sort operation if # the...
1da33a0c5428406933a21faf0c3eb024b4785943
685,557
import _ast def simpleAssignToName(node): """If a simple assignment to a name, return name, otherwise None.""" if isinstance(node, _ast.Assign) and len(node.targets) == 1: targetNode = node.targets[0] if isinstance(targetNode, _ast.Name): return targetNode.id else: ...
4edf036527e7dbb7bb325eaea17cbb675c5b5b62
685,560
def request(url_request): """ Generate the URI to send to the THETA S. The THETA IP address is 192.168.1.1 All calls start with /osc/ """ url_base = "http://192.168.1.1/osc/" url = url_base + url_request return url
983f8164c547cafe7d7dcc6f06cc5ff469a1d7af
685,563
def parse_denormalized(line): """Parse one line of the original dataset into a (user, item, rating) triplet of strings.""" id_, rating = line.strip().split(',') user, item = map(lambda x: x[1:], id_.split('_')) return user, item, rating
e4534972527ae7ffc21d571191694f3accf099d2
685,565
def printpath(P, u, w): """ Given modified path cost matrix (see floydwarshall) return shortest path from i to j. """ path = [u] while P[u][w][1] != -1: path.append(P[u][w][1]) u = P[u][w][1] return path
8d2d55023b8835f43a014dc79679b182e03da616
685,566
import re def remove_tags(html, tags): """Returns the given HTML with given tags removed. ``remove_tags`` is different from ``django.utils.html.strip_tags`` which removes each and every html tags found. ``tags`` is a space separated string of (case sensitive) tags to remove. This is backported ...
59e8e0cfdb34d24766b9be995ffc49532fdea56a
685,569
def generate_colorbar_label(standard_name, units): """ Generate and return a label for a colorbar. """ return standard_name.replace('_', ' ') + ' (' + units + ')'
a42c97ec673c882aabaeb54090e253a6bb46d645
685,570
def safe_repr(x): """ A repr() that never fails, even if object has some bad implementation. """ try: return repr(x) except: name = getattr(type(x), "__name__", "object") return f"<{name} instance>"
a726e339973f089165a2d2032e87c2c82ad96f4c
685,573
def read_tsp(path): """ Read and parse TSP from given file path Args: path (string): location of *.tsp file Returns: data (dict): {city_index: {"x": xvalue, "y": yvalue}, ...} """ data = {} with open(path, "r") as f: # Specification block for line in f: ...
415c9f7c415f593a7823e0bab4863926aab15b49
685,577
def complete_graph(vertices_number: int) -> dict: """ Generate a complete graph with vertices_number vertices. @input: vertices_number (number of vertices), directed (False if the graph is undirected, True otherwise) @example: >>> print(complete_graph(3)) {0: [1, 2], 1: [0, 2], 2: [0...
2ad1165635e962acc59b1fb21fa0dced732a6565
685,578
def is_hyponym(syn1, syn2): """ Checks if syn1 is a child of syn2 """ while syn1 != syn2: hypernyms = syn1.hypernyms() if len(hypernyms) == 0: return False syn1 = hypernyms[0] return True
0102da3dadb5aa1ee9c3b0c0f4f14082c51d28ac
685,579
def api_date(a_datetime, time=False): """Return datetime string in Google API friendly format.""" if time: return ('{0:%Y-%m-%d %H:%M:%S}'.format(a_datetime)) else: return ('{0:%Y-%m-%d}'.format(a_datetime))
ddbebcfd6d6041f76ff5983f5257f71ba2963165
685,580
def Choose(index, *args): """Choose from a list of options If the index is out of range then we return None. The list is indexed from 1. """ if index <= 0: return None try: return args[index-1] except IndexError: return None
62fd7dc5fb4128167e5ff59271356bef6b68a297
685,582
def ids_to_payload(ids: list[tuple[str, str]]) -> list[dict]: """ Convert a list of (type, id) tuples to a list of dicts that can be used as payload for the kptncook api. """ payload = [] for id_type, id_value in ids: if id_type == "oid": payload.append({"identifier": id_valu...
b11db5581c6d1cba96be241f4e6cd0746b80bf98
685,583
import json def read_json(pathname): """Read json from a file""" with open(pathname) as data_file: try: json_data = json.load(data_file) except: print(f"Error reading file {pathname}") return None return json_data
e3e350e4da11f887f7861b39c0d9291316501636
685,584
def merge_dicts(d0, d1): """Create a new `dict` that is the union of `dict`s `d0` and `d1`.""" d = d0.copy() d.update(d1) return d
55a72d1a10939d69528b2fadcdca0ab93d2bbc28
685,585
def find_keys_with_duplicate_values(ini_dict, value_to_key_function): """Finding duplicate values from dictionary using flip. Parameters ---------- ini_dict: dict A dict. value_to_key_function : function A function that transforms the value into a hashable type. For example ...
5ee901fe560ffa95c2d11ccce22b6f12b552a606
685,587
def get_cfg(cfg_label, cfg_dict): """ Get requested configuration from given dictionary or raise an exception. :param cfg_label: Label of configuration to get :param dict cfg_dict: Dictionary with all configurations available :raises: At :return: Config from given structure ...
aa3ea21d5470a563b7e5e934135d3e29c2b5012c
685,590
def _get_improper_type_key(improper, epsilon_conversion_factor): """Get the improper_type key for the harmonic improper Parameters ---------- improper : parmed.topologyobjects.Dihedral The improper information from the parmed.topologyobjects.Angle epsilon_conversion_factor : float or int ...
c76479b9d48ead0aec9b034a26e0366a8731fd59
685,593
def _combine_counts(count1, count2): """ Sum two counts, but check that if one is 'unknown', both are 'unknown'. In those cases, return a single value of 'unknown'. """ if count1 == 'unknown' or count2 == 'unknown': assert(count1 == 'unknown' and count2 == 'unknown') return 'unkn...
cfd896a291d12c489ae7b193992eea80f5a1f886
685,597
def formatDirPath(path): """Appends trailing separator to non-empty path if it is missing. Args: path: path string, which may be with or without a trailing separator, or even empty or None Returns: path unchanged if path evaluates to False or already ends with a trailing separator; otherwise,...
bc9b14c862fac02d3254ade1e1bbd710f6aa91ba
685,598
def clean_thing_description(thing_description: dict) -> dict: """Change the property name "@type" to "thing_type" and "id" to "thing_id" in the thing_description Args: thing_description (dict): dict representing a thing description Returns: dict: the same dict with "@type" and "id" keys ar...
6c4ba9cf74b17b920156f4cb745485ef68a87b74
685,599
def get_geo(twitter_msg): """ Generates GoogleMap link if msg has location data. :param twitter_msg: Twitter Status Object :return: string with gm link if possible or empty string otherwise """ try: x, y = twitter_msg.place["bounding_box"]["coordinates"][0][0] return "https://www...
037262c8d8bfae2f280b66f1fa13467d4cda1e9d
685,606
import math def yield_strength(impactor_density_kgpm3): """ Yield strength equation for breakup altitude calculation. Only valid for density range 1000 to 8000. :param impactor_density_kgpm3: Impactor density in kg/m^3 :returns: Yield Strength in Pascals. :Reference: EarthImpactEffect.pdf, Equatio...
b09c8011acc396eb3e43fbefe956bf52074bb619
685,607
from pathlib import Path def open_txt_doc(filename): """Opens texts in docs folder that go in front end of app""" path = Path(__file__).parent / 'docs' / 'app' / filename with open(path, 'r') as txtfile: text = txtfile.read() return text
9eb396e76f1337adf010589e557fac310b6d49e7
685,608
def combine_split_result(s): """Combines the result of a re.split splitting with the splitters retained. E.g. ['I', '/', 'am'] -> ['I', '/am']. """ if len(s) > 1: ss = [s[0]] for i in range(1, len(s)//2+1): ii = i-1 ss.append(s[i] + s[i+1]) return ss ...
5f054342484d598a6d85ec7a7c8751ba98c527f8
685,609
def clean_elements(orig_list): """Strip each element in list and return a new list. [Params] orig_list: Elements in original list is not clean, may have blanks or newlines. [Return] clean_list: Elements in clean list is striped and clean. [Example] >>> clean_e...
c33403d28380246eed9a0f9a8eda2580d561e2ac
685,610
from typing import List def load_bookmarks(bookmark_path: str) -> List[int]: """ VSEdit bookmark loader. load_bookmarks(os.path.basename(__file__)+".bookmarks") will load the VSEdit bookmarks for the current Vapoursynth script. :param bookmark_path: Path to bookmarks file :return: ...
668da5b806e596cf91aa941e70b00a3c219ab0cd
685,611
def _overall_output(ts, format_str): """Returns a string giving the overall test status Args: ts: TestStatus object format_str (string): string giving the format of the output; must contain place-holders for status and test_name """ test_name = ts.get_name() status = ts.get_overall_...
c16e4f7cc7d610a08c59af21abd5d295fad7ddbc
685,612
def is_json(file_path): """ Checks if a certain file path is JSON. :param file_path: The file path. :return: True if it is JSON, False otherwise. """ return file_path.endswith('.json')
59f15d76f618e3d2a16cf66d0f69a8a7f81290ab
685,613
def get_relation_id(relation): """Return id attribute of the object if it is relation, otherwise return given value.""" return relation.id if type(relation).__name__ == "Relation" else relation
d2aa5cb725e87ac20e75ca97d70e0032e0f31223
685,619
def get_sample_region_coverage(sample_tabix_object, region_dict): """ get_sample_region_coverage ========================== Get the coverage values for a specific sample at a specific region interval. A list containing per base coverage values will be returned. Parameters: ----------- ...
3d94dd5559a089a0d8037a5d71734a6b24769154
685,625
import string def case_iteration(header, iteration): """ Modifies a string to determine the correct case for each individual character in the string. A character will be uppercase if the bit representing it in the iteration value is set to 1. For example, the string "hello" with an iteration...
e5b0cb2fcf9953eeb1da78b038846b5030493b02
685,628
def get_ca_atoms(chain): """ Returns the CA atoms of a chain, or all the atoms in case it doesn't have CA atoms. Arguments: - chain - Bio.PDB.Chain, the chain to get the atoms """ result = [] if chain.child_list[0].has_id("CA"): for fixed_res in chain: if fixed_res.ha...
7ed4cade8bdf76f8ee4f2e11b3bb2f3c8c603ea4
685,630
def calculate_senate_bop(race, data): """ "total": The total number of seats held by this party. Math: Seats held over (below) + seats won tonight "needed_for_majority": The number of seats needed to have a majority. Math: 51 (majority share) - total. "total_pickups": The zero-indexed to...
a63cb4dae968bbec98a27e67c8a6338421f7b4a6
685,632
def find_best_thresh(preds, scores, na_probs, qid_to_has_ans, unanswerable_exists=False): """ Find the best threshold to determine a question is impossible to answer. Args: preds (dict): Dictionary with qa_id as keys and predicted answers as values. scores (dict): Dictionary with qa_id as k...
3cc63c79e5fba945c92411de929b566a990b8a4c
685,633
def evaluate_prediction(y, y_hat): """ This is a function to calculate the different metrics based on the list of true label and predicted label :param y: list of labels :param y_hat: list of predictions :return: (dict) ensemble of metrics """ true_positive = 0.0 true_negative = 0.0 ...
daba4222eaa261521e9645b0de042189c621a90b
685,634
def xi_func_theory(xi0, T, Tc, nu): """ Parameter --------- xi0 : float correlation length 0 (in m) T : float lattice constant of the cubic unit cell (in K) Tc : float critical temperature of the system (in K) nu : float critical exponent of the correlatio...
03558350125322be0ff18753fb83c6a664bd0b51
685,635
def sigma_z(state, site): """ Returns `(sign, state)` where `sign` is 1 or -1 if the `site`th bit of the int `state` is 0 or 1 respectively. Can also accept numpy arrays of ints and gives numpy arrays back """ return (-1.0) ** ((state >> site) & 1), state
d2c128d08fedf684683bca8cd4902ab8a785587f
685,636
from datetime import datetime def dateFormat(timestamp): """ Format timestamp (nb of sec, float) into a human-readable date string """ return datetime.fromtimestamp( int(timestamp)).strftime('%a %b %d, %Y - %H:%M')
090f0b8da439c15918f48aa37aa5effbcc3e101a
685,637
def to_dict(key, resultset): """ Convert a resultset into a dictionary keyed off of one of its columns. """ return dict((row[key], row) for row in resultset)
aad419aeb1b7d81d14ab9ef2e70791d23b2a9082
685,638
def get_language(file_path): """Return the language a file is written in.""" if file_path.endswith(".py"): return "python3" elif file_path.endswith(".js"): return "node" elif file_path.endswith(".rb"): return "ruby" elif file_path.endswith(".go"): return "go run" elif file_path.endswith(".c") or file_...
2f34390227932c7add58967dbe9bfc3834526b8e
685,639
def make_iter_method(method_name, *model_names): """Make a page-concatenating iterator method from a find method :param method_name: The name of the find method to decorate :param model_names: The names of the possible models as they appear in the JSON response. The first found is used. """ def ite...
67623ab63930a899a1e6ce91c80e49ec41779079
685,640
def parr_to_pdict(arr, measures_optimized): """Convert BO parameter tensor to parameter dict""" if measures_optimized: d = { 'p_stay_home': arr[0].tolist(), } return d else: d = { 'betas': { 'education': arr[0].tolist(), ...
50623f2aae87a5326b4524f249bf28eb093aa7c0
685,643
def trapply_calib(trin): """Apply calibration values to data-points in a trace object""" return trin.apply_calib()
cf19889be308fa8ad86a4a822202aa76185357e6
685,644
def all_names(command): """Return a list of all possible names in a command""" return [command.name, *command.aliases]
53460c0b93adf0c9ea80a67a2362c841e90da258
685,646
import string def get_printable(text): """ Return string if printable, else None """ try: if all(c in string.printable for c in text): return text except TypeError: if all(chr(c) in string.printable for c in text): return text return None
e6b14e2c59b1d90dfcfbdda82298c6a4624aee6c
685,647
import time def is_noncomplex(obj): """Returns True if *obj* is a special (weird) class, that is complex than primitive data types, but is not a full object. Including: * :class:`~time.struct_time` """ if type(obj) is time.struct_time: return True return False
c5066e98af5556d331b64ff997d124f4e8110983
685,649
def split_index(index, n=8): """Split a conversions index, which is a list of tuples (file position, number of lines, alignment position), one for each read, into `n` approximately equal parts. This function is used to split the conversions CSV for multiprocessing. :param index: index :type ind...
61e783c1fe15fc12727f3fca4059735f6d7f78da
685,650
from typing import Counter import pickle def build_dict(examples, filepath, max_words=50000): """ Build a dictionary for the words in `sentences` and a dictionary for the entities. Only the max_words ones are kept and the remaining will be mapped to <UNK>. """ documents, questions, answers...
c9fd84f7c574249c6e9d250cd403de68594aa41e
685,651
def get_value(input: int) -> str: """Given an int it return Fizz, Buzz or FizzBuzz if it is a multiple of 3, 5 or both""" if input % 15 == 0: return "FizzBuzz" elif input % 3 == 0: return "Fizz" elif input % 5 == 0: return "Buzz" else: return f"{input}"
4121f16d70f3890e986ffee5a7e677e580f28120
685,652
import copy def get_topic_with_children(prefix, children): """ Reuse the three-nodes sequence form sample_children to create a topic node. Modify `node_id`s and `content_id`s to make sure nodes are different. """ topic = { "title": "Topic " + prefix, "node_id": prefix, "con...
a6797e400d044f82700d0b4c25ca0886cde441a2
685,657
def chi2fn_2outcome_wfreqs(N, p, f): """ Computes chi^2 for a 2-outcome measurement using frequency-weighting. The chi-squared function for a 2-outcome measurement using the observed frequency in the statistical weight. Parameters ---------- N : float or numpy array Number of sampl...
a9975542d26aa17f08e57730b4ad71c9e1dbb020
685,664
def get_wikidata_id(wikidata_uri): """ Returns Wikidata ID (e.g. "Q92212") given Wikidata entity URI, or None. """ wikidata_base_uri = "http://www.wikidata.org/entity/" if wikidata_uri.startswith(wikidata_base_uri): wikidata_id = wikidata_uri[len(wikidata_base_uri):] else: wikida...
9b505dfb65a48ae4ca515483733f3f732aa88aac
685,665
def get_feature_code(properties, yearsuffix): """ Get code from GeoJSON feature """ code = None if 'code' in properties: code = properties['code'] elif ('lau1' + yearsuffix + 'cd') in properties: code = properties['lau1' + yearsuffix + 'cd'] return code
1c068245e2551a2b35824c526a7b491538b387f0
685,666
def key_check(line,keyword): """ For ARGS, checks if a line of the input file has a keyword on it """ if keyword in line: return True ...
9d0698d84648bab263b2b676ad2ef9838dce89bd
685,671