content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import requests def snap(x, y, url, resource='/grid/snap'): """Determine the chip and tile coordinates for a point. Args: x (int): projection coordinate x y (int): projection coordinate y url (str): protocol://host:port/path resource (str): /grid/snap/resource (default: /gri...
c7f924095ae2d00edc5c372dc42c68ff717d7cd9
684,869
def object(): """Placeholder function to always return False. :returns: Always false. """ return False
aa22efc97c7a73479971d1c308b4c89af2b0078e
684,870
import struct def pack_bytes(payload): """Optimally pack a byte string according to msgpack format""" length = len(payload) if length < (2 ** 8): prefix = struct.pack('BB', 0xC4, length) elif length < (2 ** 16): prefix = struct.pack('>BH', 0xC5, length) else: prefix = struc...
0f5ef9879850593f523811fea3a4e2adf7d18e8e
684,872
import pkg_resources import os def coerce_resource_to_filename(fname): """Interpret a filename as either a filesystem location or as a package resource. Names that are non absolute paths and contain a colon are interpreted as resources and coerced to a file location. """ if not os.path.isabs...
3a8d433d3c29561c3b54b6a657a02144503aa557
684,873
import unittest def load_tests(dir_name): """ 从文件夹中加载测试用例 :param dir_name: 文件夹名字 :return: """ return unittest.TestLoader().discover(dir_name)
f46a53fca9095b824e9e6edcf7999f6465843c92
684,874
import os import pickle def export_model_and_tokens(tm, n:int, tokens:list, theta:list, dates:list, OUT_PATH:str, datatype:str): """Exports ...
aa3da3c6ed69e5060644b9173ded6acca355e88c
684,875
import ast def str_rep_to_list(s): """ convert a string representation of list to a python list object. :param s: :return: """ return ast.literal_eval(s)
24a0adbee342cb8288d8e34c370ec4e6551bf3ed
684,876
def _split_list_by_function(l, func): """For each item in l, if func(l) is truthy, func(l) will be added to l1. Otherwise, l will be added to l2. """ l1 = [] l2 = [] for item in l: res = func(item) if res: l1.append(res) else: l2.append(item) r...
3812a7b43cb103b746360943303441ae31122407
684,878
def print_time(time): """Format a datetime object to be human-readable""" return time.astimezone(tz=None).strftime('%m/%d')
d75deefac5f2326637fe73757b8baee95d0ac42b
684,879
def compute_eer(target_scores, nontarget_scores): """Calculate EER following the same way as in Kaldi. Args: target_scores (array-like): sequence of scores where the label is the target class nontarget_scores (array-like): sequence of scores where the ...
0bcd1235f02a6e84a82be6a6af82b76a8aeb0bbc
684,880
from typing import Tuple def get_module_and_func_names(command: str) -> Tuple[str, str]: """ Given a string of module.function, this functions returns the module name and func names. It also checks to make sure that the string is of expected 'module.func' format Args: command (str): String o...
6c69d3242d7c4c25d926f140fb14858ad13bab56
684,881
import numpy def toMatrix(f): """ :param f: input pose :type f: :class:`PyKDL.Frame` Return a numpy 4x4 array for the Frame F. """ return numpy.array([[f.M[0,0], f.M[0,1], f.M[0,2], f.p[0]], [f.M[1,0], f.M[1,1], f.M[1,2], f.p[1]], [f.M[2,0], f.M...
ce5f8ef13a14f8e662d8baede4e589899a1d6c04
684,883
def right_pad(xs, min_len, pad_element): """ Appends `pad_element`s to `xs` so that it has length `min_len`. No-op if `len(xs) >= min_len`. """ return xs + [pad_element] * (min_len - len(xs))
00282f75ca3c9763c565d4d136d5e4971e3012ee
684,884
def compte_vrai(f): """compte le nombre de VRAI dans la formule f""" n = f.nb_operandes() if n == 0: v = f.get_val() if v == "VRAI": return 1 else: return 0 elif n == 1: f2 = (f.decompose())[0] return compte_vrai(f2) else: [f2, ...
ae1540c7ef6cddbd0008e41c63571de35e0386d8
684,885
def get_lids(f): """get identifiers that specify an absolute location (i.e. start with '/')""" lids={} for ns in f.ddef.keys(): lids[ns] = [] structures = f.ddef[ns]['structures'] for id in structures: if id[0] == '/': lids[ns].append(id) return lids
e5ca9f0b4d9bc9328e6337e5de0256dc9129f397
684,886
def real2complex(rfield): """ convert raw qg_model output to complex numpy array suppose input has shape psi(time_step (optional), real_and_imag, ky, kx, z(optional)) """ if rfield.shape[-2]+1 == 2*rfield.shape[-3]: return rfield[...,0,:,:,:]+1j*rfield[...,1,:,:,:] elif rfield.sh...
aa8c1f4179f4817aabe496396c539e36ce2e5657
684,887
def point_from_pose(pose): """get the origin point from a pose Parameters ---------- pose : Pose [description] Returns ------- Point, np array of three floats [description] """ return pose[0]
97abd4b1bf26fa8da8f45f30623caa25c540518b
684,888
def strip_spaces(fields): """ Strip spaces and newline characters from a list of strings. Inputs ------ fields : list of strings Returns ------- list : modified input list where the characters ' \n' have been stripped Examples -------- strip_spaces(['hi ', 'zeven 1', 'yo\n...
4cba8e32d9889655181287d2984f64493c3704c1
684,889
def readable_keyword(s): """Return keyword with only the first letter in title case.""" if s and not s.startswith("*") and not s.startswith("["): if s.count("."): library, name = s.rsplit(".", 1) return library + "." + name[0].title() + name[1:].lower() else: ...
cda8151937feae49b69a945ae2f8feb8becb3d77
684,890
def _footer(point_xlate): """Create a footer to use for the chart. Args: point: DataPoint object Returns: result: Footer """ # Initialize key variables result = '' # Process for (meta, value) in point_xlate.metadata_translations: # Translate key text =...
2d8b2fe4a6f2ac6794fabd38c4604ac4713ed7e9
684,891
def _default_bounds(signal): """Create a default list of bounds for a given signal description If no bounds were specified, they default to [0, 0]: ['name', 0, 0, 0, 0] If no bits of the port were picked, the whole port is picked: ['name', x, y, x, y] A signal may use a slice of a port ...
42fec5f8af4b110ed4821c3509ddb187c8e1c24b
684,892
def accept_objects(func): """This decorator can be applied to functions whose first argument is a list of x, y, z points. It allows the function to also accept a list of objects which have x(), y() and z() methods instead.""" def new_func(objects, *args, **kwargs): try: points = [(x...
829e99a7d7a61ffe99e5cd82663eac2548c24d6f
684,895
def normalise_to_zero_one_interval(y, ymin, ymax): """Because I always forget the bloody formula""" if ymin > ymax: raise TypeError('min and max values the wrong way round!') return (y - ymin) / (ymax - ymin)
0caa7dc62b03f5021dc41a127041a6d98af762ce
684,896
def _filter_rows(df, min_ct=0): """Filter out rows with counts less than the minimum.""" row_sums = df.T.sum() filtered_df = df[row_sums >= min_ct] return filtered_df
7d6130836a87f3033613fa8a94a1b81f265a2cb9
684,897
def concat(*args): """:yaql:concat Returns concatenated args. :signature: concat([args]) :arg [args]: values to be joined :argType [args]: string :returnType: string .. code:: yaql> concat("abc", "de", "f") "abcdef" """ return ''.join(args)
6881def910f21dd13b241ea0cfd16cd9ebd29f06
684,898
def get_last_id(list_of_id, width): """ Gets the last identifier given a list of identifier. :param list_of_id: list of identifier :param width: the width of the identifier. :return: the last identifier. """ last_number = 0 for identifier in list_of_id: if identifier == "": ...
22bd3c7cc4fd5aaae1005d7317bbe29f407091b4
684,899
def get_list_by_separating_strings(list_to_be_processed, char_to_be_replaced=",", str_to_replace_with_if_empty=None): """ This function converts a list of type: ['str1, str2, str3', 'str4, str5, str6, str7', None, 'str8'] to: [['str1', 'str2', 'str3'], ['str4', 'str5', 'str6', 'str7'], [], ['str8']] "...
7702dd577145c910f4bedc67c85cae6fa7de0854
684,900
from typing import Coroutine from typing import Dict from typing import Any import asyncio from typing import Callable import inspect def gen_new_param_coro(coro: Coroutine, new_param_dict: Dict[str, Any]) -> Coroutine: """Return a new coro according to the parameters >>> async def demo(a: int, b: int) -> int...
43425458449b1cedd74d4dac5d2b484714e7b66b
684,901
import pathlib def get_configuration_path() -> str: """Returns project root folder.""" return str(pathlib.Path(__file__).parent.parent.parent) + '/configuration/conf.ini'
25e63ac08f3f938dccfebcdf8e5e3ca77df91741
684,902
def try_int(s, *args): """Convert to integer if possible.""" #pylint: disable=invalid-name try: return int(s) except (TypeError, ValueError): return args[0] if args else s
4b434d34bc4001795c923836789b2bfa529df1ee
684,903
def datetime_adapter(obj, request): """Json adapter for datetime objects.""" try: return obj.strftime('%d/%m/%Y %H:%M:%S') except: return obj.strftime('%d/%m/%Y')
6bd91b959d64aaafae835a1fceb6e06bc01cf89f
684,904
def central_difference(f, x, h=1e-10, **kwargs): """Central difference method for approximating the derivartive of f Args: f: a function taking x as input x: an int or float input to the function h: a float small constant used for finding the derivative Returns: f_prime: ap...
f9a4ffb481a52a3b9e143209f0e0f04071931e30
684,905
def parse_bearing(data): """ parses a bearing message contains the position and calculated bearings after a rotation """ # these are now comma separated values values = data.split(",") # extract the data msg = {} msg['bearing_cc'] = float(values[0]) msg['bearing_max'] = float(v...
0f2672847ba73212eeb618d99c1dea6740d22c20
684,906
import turtle import math import cmath def z_function(point_zero, point_pole,POINT_NUMBER, radians, radius): """ H(z) = (z - z00)*(z - z01) / (z - zp0)(z - zp1) H(z) == z_h1 / z_h2 z == e-jωT , T = 1/F , F is samplingrate In Programm z = 1.e-jωT z = complex (radians,radius): from input fun...
91466a3c6b671d8b3c6db4d08faddcdd69504430
684,907
import torch def planeXYZModule(ranges, planes, width, height, max_depth=10): """Compute plane XYZ from plane parameters ranges: K^(-1)x planes: plane parameters Returns: plane depthmaps """ planeOffsets = torch.norm(planes, dim=-1, keepdim=True) planeNormals = planes / torch.clam...
19c49bc9da68199940f296393ef7266daa50af89
684,908
def num_to_words(num, join=True): """ words = {} convert an integer number into words :param num: :param join: :return: """ units = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] teens = ['', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',...
7038a54d6f418707da44b64032fde2991d0783da
684,909
def validate_input_data(data): """ Takes in user input data Checks if all the keys are provided Raise key error if a key is missing Returns a validated data in a dict format """ cleaned_data = {} for key in data: if data[key] is None: assert False, key + ' key is miss...
bfbf144e9aab47557ad29fb747f7705e59a43e3a
684,910
import subprocess def ros_kill_all_processes() -> bool: """ Function to kill all running ROS related processes. :return: True if all processes were killed, False otherwise. :rtype: bool """ term_command = "killall -9 rosout roslaunch rosmaster gzserver nodelet robot_state_publisher gzclient"...
1459f0db339ff991a96d1e6006ba3f0d9af50151
684,911
def get_delegated_OTP_keys(permutation, x_key, z_key, num_qubits=14, syndrome_cnots = [[14, 0], [14, 2], [14, 4], [14, 6], [15, 1], [15, 2], [15, 5], [15, 6], [16, 3], [16, 4], [16, 5], [16, 6], [17, 7], [17, 9], [17, 11], [17, 13], [18, 8], [18, 9], [18, 12], [18, 13], [19, 10], [19, 11], [19, 12], [19, 13]]): """ ...
35054ac76220fd332738a1e071aca769fd006e6c
684,912
def split_fraction(f): """!Splits a fraction into components. Splits a fraction.Fraction into integer, numerator and denominator parts. For example, split_fraction(Fraction(13,7)) will return (1,6,7) since 1+6/7=13/7. @returns a tuple (integer,numerator,denominator)""" i=int(f) f2=f-i ...
96302db9eabdeae3547954c9ea4e96f1b4fdcdc3
684,913
import requests def get_user_api_token(logger, username, password): """ Generate iAuditor API Token :param logger: the logger :return: API Token if authenticated else None """ generate_token_url = "https://api.safetyculture.io/auth" payload = "username=" + username + "&password=" +...
b123a8515a4aff1977608e68502caef497777c73
684,914
def hopedale_average(file_with_values) -> float: """ (str) -> float Return the average number of pelts produced per year for the data in Hopedale file named filename. """ with open(file_with_values, 'r') as hopedale_file: #Read heading hopedale_file.readline() #Read comment...
34f1a74ce3ac5fdb3f51b410570cf398ed305542
684,915
from typing import List from typing import Any import fnmatch def get_elements_fnmatching(l_elements: List[Any], s_fnmatch_searchpattern: str) -> List[str]: """get all elements with type str which are matching the searchpattern >>> get_elements_fnmatching([], 'a*') [] >>> get_elements_fnmatching(['ab...
f19665b68afc0a158cadbeb4abeac641fd3cb78c
684,916
import argparse def parse_arguments(): """ Parses commandline arguments :return: Parsed arguments """ parser = argparse.ArgumentParser( 'Run behave in parallel mode for scenarios') parser.add_argument('--processes', '-p', type=int, help='Maximum number of proces...
93e869a824965e036e7eb9c3f9f91346e590f3dd
684,917
def factorial(num): """Calculates the factorial of a number. Use pre-test repetition to write a function that computes the factorial of a number. A factorial of a number is the product of all the positive integers less than it. For example 4 factorial is 4 x 3 x 2 x 1 = 24 Args: num: ...
2c2dd6635b3f7a696866e890179e979ef9af6129
684,918
import functools def defer_to(*nicks): """ If any of the given nicks are present in a channel, don't trigger this action. """ nicks = {nick.casefold() for nick in nicks} def defer_decorator(func): @functools.wraps(func) def _defer(bot, trigger, *args, **kwargs): if tri...
c577acdb4a7324a0bd27ba00af47368ac444b34d
684,919
import os def get_cpu_temp(): """ CPU temperature should be below 80C for normal operation. """ celcius = None temp = '/sys/devices/virtual/thermal/thermal_zone0/temp' if os.path.exists(temp): celcius = int(open(temp).read().strip()) / 1000 return celcius
ea135abc848cbbcec25adbf17a6c197032de6dd2
684,920
def find_path_part1( caves: dict[str, set[str]], start: str, path: list[str] ) -> list[list[str]]: """Recursively find a path starting in `start`, only visit small rooms once.""" path.append(start) if start == "end": return [path] paths = [] for room in caves[start]: if room.islo...
59ed8aabf881d53f543c888814883d1d34fa6e7b
684,922
def resolve_keywords_array_string(keywords: str): """ Transforms the incoming keywords string into its single keywords and returns them in a list Args: keywords(str): The keywords as one string. Sometimes separates by ',', sometimes only by ' ' Returns: The keywords in a nice list """ ...
d7a2e31c2202ec2080e50d6ceb9f2cb28bf72251
684,923
import requests def fetch_website(url="http://www.meteo.be/meteo/view/nl/123763-Huidige+maand.html"): """ Fetch the website containing the data from http://www.meteo.be/meteo/view/nl/123763-Huidige+maand.html Returns ------- str """ r = requests.get(url) if r.status_code == 200: ...
9ca77e8298647272e8a2f5d2f6b584998f4dc44b
684,924
import re def get_test_keys(data): """Return case keys from report string. Args: data(str): test case results Returns: list[str]: list of report keys """ keys_rules = re.compile('<success>(.*?)</success>') return keys_rules.findall(data)
cc762d02e25e93597c3b683a1ceee6b2105e6019
684,925
def get_return_assign(return_type: str) -> str: """ int foo() => 'int r =' void foo() => '' """ s = return_type.strip() if 'void' == s: return '' return '{} r ='.format(s)
4d89adb98104844f3af69650aa6583af5dcd4368
684,927
def max_subsequence(s1, s2): """最长公共子序列""" def equal(table, i, j): return table[i - 1][j - 1] + 1 def not_equal(table, i, j): return max(table[i][j - 1], table[i - 1][j]) table = [[0] * (len(s1) + 1) for _ in range(len(s2) + 1)] for i, row in enumerate(table[:-1]): for j, ...
9a488f0c2ab81cdd9ac26f8b26ddc9323da1a2db
684,928
from datetime import datetime def map_row_to_schema(row): """Associate a value from a Stat JSON object with the correct identifier from BQ schema. Daily ranking updates come from Stat's JSON API. This export is complex. We need to map values from Stat's data into the schema we've design to interf...
2943bbd90f3984d8d8477012ccd64f582c085e5c
684,929
def _get_headers(): """ Craft HTTP headers for request """ return {"Content-Type": "application/x-www-form-urlencoded"}
9a5a0622deb965a7b6eb56d3da96059bba5a2a97
684,930
def get_state_root(spec, state, slot) -> bytes: """ Return the state root at a recent ``slot``. """ assert slot < state.slot <= slot + spec.SLOTS_PER_HISTORICAL_ROOT return state.state_roots[slot % spec.SLOTS_PER_HISTORICAL_ROOT]
ecb1333a5ca8e0958a08aa03ac84e8fa11987caa
684,931
import sys def source(target, inputstream=sys.stdin): """ Coroutine starting point. Produces text stream and forwards to consumers :param target: Target coroutine consumer :type target: Coroutine :param inputstream: Input Source :type inputstream: BufferedTextIO Object """ for line i...
f4d357aaf469bc6bbaabeddf1bf24e0e583870c1
684,932
def get_test_values(alignments): """ @type alignments: C{dict} @param alignments: @return: @rtype: C{list} """ test_values = [] for hard_regions_index in alignments.keys(): soft_regions_list = [] for soft_regions_index in alignments[hard_regions_...
612f71b5adabbfb5c824fa50b35d17ad8d887c36
684,933
import torch def lsep_loss( input: torch.Tensor, target: torch.Tensor, average: bool = False ) -> torch.Tensor: """Log-sum-exponent pairwise loss Source: Kaggle""" differences = input.unsqueeze(1) - input.unsqueeze(2) where_different = (target.unsqueeze(1) < target.unsqueeze(2)).float() exps...
cd9824f9cf9ef17d66a9447c8b7a6bef6fe8e7d0
684,934
def apply_uv_coverage(Box_uv, uv_bool): """Apply UV coverage to the data. Args: Box_uv: data box in Fourier space uv_bool: mask of measured baselines Returns: Box_uv """ Box_uv = Box_uv * uv_bool return Box_uv
0049c9ce213769895f8f9b3b5a62d9ccd35fec70
684,935
def seeding_separate(c, p): """ Keep the markers separated if there are two previous markers on one current marker. Assuming foreground in c is always including foreground in p. """ dou_c = [] dou_p = [] both = [i for i in list(set(p[c > 0])) if not i == 0] # exists in previous and current...
6d7d195bd94d4b453dd6fcc89e7cef60149a2e61
684,936
def average(values): """Computes the arithmetic mean of a list of numbers. >>> print average([20, 30, 70]) 40.0 """ return sum(values, 0.0) / len(values)
0e9199635e54dad5511bddfe0c931b61cc3b2266
684,938
def fusion_vulnerability_dictionaries(dictionary_1, dictionary_2): """ Fusions data from two vulnerability dictionaries into one. :param dictionary_1: dictionary of vulnerabilities :param dictionary_2: dictionary of vulnerabilities :return: dictionary of vulnerabilities """ for qid in dicti...
8f8420ba1d558b6fc1b7c4d19d260a53b68781a3
684,939
import os import click def get_username(directory: str = ".") -> str: """Gets or prompts the user for the username.""" username = None # find the username in the cache for filename in os.listdir(directory): if filename[:6] == ".cache": if click.confirm(f"Use cached username '{filen...
824d5be39a118fbbb925d39fa4c4bec53528ccab
684,940
import torch def box_cxcywh_to_xyxy(x: torch.Tensor): """ Change bounding box format: w --------- xy------- | | | | h | xy | --> | | | | | | --------- -------xy """ x_c, y_c, w, h = x.unbind(1) ...
0b4972ff121786e2347374476222903232a8fbae
684,941
def replace_characters(content, down_step, right_step): """Replace specific characters.""" matrix = content.copy() down_max, right_max = matrix.shape for i in range(down_max): x = (right_step * i) % right_max y = down_step * i if y > down_max: break char = ...
e9fa93850709c5a7a3088520756e7ec0e09a32d8
684,942
import argparse def argumentsparsing(): """ """ parser = argparse.ArgumentParser() parser.add_argument("--method", required=True, type=str, dest="method", help="Available methods: discovery:volume, " + "discovery:disk, discovery:fc, discovery:cp,\n"...
ca6eb9553aea17d5287265674767162af5bf986d
684,943
import requests def post_vsummary_species(base_url, input): """Yield the response to a species summary of a query.""" url = base_url + 'vsummary/species' return requests.post(url, input)
9969e8ccdab6c9b905ee4038b93beed29bb042b1
684,944
def number_for_course_location(location): """ Given a course's block usage locator, returns the course's number. This is a "number" in the sense of the "course numbers" that you see at lots of universities. For example, given a course "Intro to Computer Science" with the course key "edX/CS-101/2014...
16868ff0cd1e80cd7bc43a61c71f001b40eac509
684,946
def validate_extra(value: dict, context: dict = {}) -> dict: """ Default extra validator function. Can be overriden by providing a dotted path to a function in ``SALESMAN_EXTRA_VALIDATOR`` setting. Args: value (str): Extra dict to be validated context (dict, optional): Validator context...
55b0996331c2dfafbebe62b882739f0f49dadc2c
684,947
def __compare_levelfiles(f1, f2): """compares the levelfile contents regardless of string format""" fs1 = open(f1, 'r') fs2 = open(f2, 'r') levels1 = [] lines = fs1.readlines() for line in lines: levels1.append(float(line)) levels2 = [] lines = fs2.readlines() for line in l...
9f8da1adc8fabc68b302024b958d7a18ad93a0e2
684,948
import numpy def array_equal(a1, a2, equal_nan=False): """ True if two arrays have the same shape and elements, False otherwise. For full documentation refer to :obj:`numpy.array_equal`. See Also -------- :obj:`dpnp.allclose` : Returns True if two arrays are element-wise equal ...
3bdbaeec4e0f6ee4e22373f366d794b8595014a0
684,949
import random def _distributeSD(dim, scale, scaleEff): """Returns a list of standard deviations between scale[0] and scale[1] randomly distributed based on the Type Precondition: scale is a 2d list with #'s>=0""" assert scale[0] > 0, "scale is not a valid list" sd = [] i = 0 if len(scaleEff) =...
1dd2cfc15b661846d02cc9ce3c421a96d064c0b8
684,950
def get_pose_count(data_dict): """ Calculates the number of poses in the dataset. A pose is one frame of a sequence, independent of cameras. In other words, each pose was taken from 4 cameras. """ pose_lens = {} for key in data_dict.keys(): subject, action, seq, camera = key if (...
744228f49113ee0eafda8eff53be4cae2bf49372
684,951
def is_timezone_aware(value): """Check if a datetime is time zone aware. `is_timezone_aware()` is the inverse of `is_timezone_naive()`. :param value: A valid datetime object. :type value: datetime.datetime, datetime.time :returns: bool -- if the object is time zone aware. :raises: TypeError ...
49ce85512778b348f0d74df4e3e179ebe0ff00ed
684,952
def remove_root_constant_terms_t(expr, variables, mode): """ Remove root constant terms from a non-constant SymPy expression. """ variables = variables if type(variables) is list else [variables] variables = [str(x) for x in variables] assert mode in ["add", "mul", "pow"] if not any(str(x) i...
82ae676850b89422d5d1094b1d7eac6af651ec0e
684,953
def clear_object_store( securityOrigin: str, databaseName: str, objectStoreName: str ) -> dict: """Clears all entries from an object store. Parameters ---------- securityOrigin: str Security origin. databaseName: str Database name. objectStoreName: str Ob...
f13e0f80d6c57bd624ca2d911af66d62026dcdee
684,955
def bytes_to_block(block_size: int, i: int) -> slice: """ Given the block size and the desired block index, return the slice of bytes from 0 to the end of the given block. :param block_size: The block size. :param i: The block index. :return: slice of bytes from 0 to the end of the specified bl...
333816aa8c8e22c5715e1c585c4d9c34813d46f2
684,956
from typing import Any def input_setter_fail(request: Any) -> Any: """Input fixture for failing setter tests.""" return request.param
986d7331ae02b986ab02105ee96749c952561bc8
684,957
import os def delete_workspace(workspace_location: str) -> bool: """ Deletes the temporary workspace """ os.rmdir(workspace_location) return True
1409c039db48d6e97af7b7773d0154641004c627
684,959
def extended_euclid_xgcd(a, b): """ Returns d, u, v = xgcd(a,b) Where d = ua + vb = gcd(a, b) """ s = 0 old_s = 1 t = 1 old_t = 0 r = b old_r = a while r != 0: quotient = old_r // r old_r, r = r, old_r - quotient * r old_s, s = s, old_s - quotient * s...
e1bf4a26dff387e72b728d9871d34127e83b44ff
684,960
def count_leap_years(year: int, month: int) -> int: """Returns the number of extra days incurred from leap years for a given date Args: year (int): Year value month (int): Month value day (int): Day value Returns: int: Number of leap years """ # Check if the current...
5ed67b2534269b904da0aaa88402296ffdce6006
684,961
import random def sample_from_dict(d, sample): """ Random sample from a dict """ key = random.choices(list(d.keys()), list(d.values()), k=sample) return key
f5dd449d758eeb47c21d9bcffa19bfc8ab7140c6
684,962
def sum_parameters(param): """ Sums the equation parameters which have the same exponent and polynomial term. (a, ni, bi) and (c, ni, bi) become (a + c, ni, bi). Parameters ----------- param: list list of tuples (Ai, ni, Bi) Returns ---------- out: list list of ...
be29ccc3894fe2f1d434d45e751459be09eda432
684,963
import os def _mkfile(f, message=None): """ Create a new, empty file. """ assert not os.path.exists(f), "File already exists: {}".format(f) with open(f, 'w'): if message: print("{}: {}".format(message, f)) return f
6371c8f17c7630fe5cea81e5fea9d00da8c7e5d6
684,964
def points_within_mesh_geometry(pts, mesh_geoms): """ Given a list of point geometries and a list of polygon geometries, returns a list of point geometries within the polygons """ pts_in_poly = [] for mesh_geom in mesh_geoms: for pt in pts.multipoint.get_points(): if mesh_ge...
a3f4fc681ec072a215b24f80b2505f2bed1ff61c
684,966
import torch def l2_norm(vec: torch.Tensor): """ :param vec: feature vector [D] or [N, D] """ vec /= torch.norm(vec, dim=-1, keepdim=True) return vec
1325b6c57b7d93b68118db711d1a0da3ee8b2738
684,967
def is_continuation(val): """Any subsequent byte is a continuation byte if the MSB is set.""" return val & 0b10000000 == 0b10000000
807f94ee51b143c2e5dbe2ce3d5d7f43e7e4947f
684,968
def filter_out_exact_negative_matches(tests, negative_matches): """Similar to filter_tests, but filters only negative match filters for more speed With globbing disallowed, we can use sets, which have O(1) lookup time in CPython. This allows for larger filter lists. negative_filters is a list of lists...
ec6201b76c8e1bb14f8defcae5da8ef6cf38f1fa
684,969
def number_keys(a_dictionary): """Return the number of keys in a dictionary.""" return (len(a_dictionary))
600f77617563add2a5763aa05c3861ee3d067cf1
684,971
def get_influencers(user_index, adjacency_matrix): """helper function to retrieve the influencing users for a certain user by passing the latter index to the function""" influencers = set() for e, col in enumerate(adjacency_matrix[user_index]): if adjacency_matrix[user_index][e] > 0: in...
09ee64edbd1baba0d88807b1ae317c7d5aa58b2e
684,972
def true_false_converter(value): """ Helper function to convert booleans into 0/1 as SQlite doesn't have a boolean data type. Converting to strings to follow formatting of other values in the input. Relying on later part of pipeline to change to int. """ if value == "True": return '1' ...
b81ac423f3b176e57cf9087c5bc241ff64fdcc85
684,973
def celcius_2_kelvin(x): """Convert celcius to kelvin.""" return x + 273.15
8370fa6add469fc455c6a39b741462a4b8ee2e88
684,974
def set_cutoff(bigdf, cutoff): """ Takes cutoff for maximum missing data points to subset dataframe to get ready to turn into X/y dataframes """ #How many NaNs are there in each column? nullcols = bigdf.isnull().sum(axis=0) #Subsetting data to just have predictors with <X missing observ...
e08950d060cc34ac3c6926c3c8867851a63c5014
684,975
from typing import Dict from typing import Union from typing import List from typing import Any from functools import reduce def getitems(obj: Dict, items: Union[List, str], default: Any = None) -> Any: """ 递归获取数据 注意:使用字符串作为键路径时,须确保 Key 值均为字符串 :param obj: Dict 类型数据 :param items: 键列表:['foo', 'bar'...
c05c86ecab0bd1a4f83ac1cffbe23ca03f20b0d5
684,977
def compute_range(word_size,bits_per_sample): """ Get starting positions in word for groups of bits_per_sample bits. Notes ----- | | **Example:** | | word_size=32 | bits_per_sample=4 | list(compute_range(word_size,bits_per_sample)) | >>> [0, 4, 8, 12, 16, 20, 24, 28]...
96a05ce64d5aab89df9a50aba1fe91fe87a08b99
684,978
def map_filter_bands(process): """ """ dict_item_list = [] if 'bands' in process['arguments'].keys(): load_bands = process['arguments']['bands'] # elif 'wavelenghts' in process['args'].keys(): # # add this option else: load_bands = 'all' dict_item = {'name': '...
903b2ad6c575c91639cda5a2710a9ceb75263555
684,979
def _get_shape_cardinality(shape): """Get the cardinality in a shape which can be int or tuple""" shape_cardinality = 1 if shape is None: return shape_cardinality if isinstance(shape, int): shape = (shape,) for cardinality in shape: shape_cardinality *= cardinality retu...
11f4fc71958b0b86065f54bffa938edfaf898605
684,980
import functools import json def json_body_loader(handler): """ Decorator which loads the JSON body of a request """ @functools.wraps(handler) def wrapper(event, context): if isinstance(event.get("body"), str): event["body"] = json.loads(event["body"]) return handler(e...
2bf6c4d05d6c2f621a59c26dfb80d215e7aae1a6
684,981
import os def cf_fpath(): """Initialize a reV gen cf test fpath.""" datadir = os.path.join(os.path.dirname(__file__), 'data/') cf_fpath = os.path.join( datadir, 'reV_gen/naris_rev_wtk_gen_colorado_2007.h5') return cf_fpath
29f6b3786edb3d6472f861ec1e9aaab47f7b8e12
684,983