content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import collections def _group_by_batches(samples, check_fn): """Group calls by batches, processing families together during ensemble calling. """ batch_groups = collections.defaultdict(list) extras = [] for data in [x[0] for x in samples]: if check_fn(data): batch = data.get("m...
5be10acf9c71b699b17640d3caf196f2e686666f
683,282
import os def ls(d=os.getcwd()) -> list: """Returns a list of files in a directory cwd is default""" return os.listdir(d)
91da158d0fd8fdcde6bf8cd479d6c58390c443d9
683,283
import random def generate_random_id(): """ Generates a 5 digit random number from 10000 to 99999 """ return random.randint(10000,99999)
84d25c448ead8c84aa76d38ed29dca4b76eaf9bf
683,284
import re def RemoveReportHeaderAndFooter(output): """Removes Google Test result report's header and footer from the output.""" output = re.sub(r'.*gtest_main.*\n', '', output) output = re.sub(r'\[.*\d+ tests.*\n', '', output) output = re.sub(r'\[.* test environment .*\n', '', output) output = re.sub(r'\[=...
e6d31ca116ff490533655de4d6800ff60776c669
683,285
def cgi_decode(s): """Decode the CGI-encoded string `s`: * replace "+" by " " * replace "%xx" by the character with hex number xx. Return the decoded string. Raise `ValueError` for invalid inputs.""" # Mapping of hex digits to their integer values hex_values = { '0': 0, '1': 1...
310519ac6edd52dc2131a32695e29aa5ad610f43
683,286
def should_apply_max_and_skip_env(hparams): """MaxAndSkipEnv doesn't make sense for some games, so omit it if needed.""" return hparams.game != "tictactoe"
ad2988a29386ae9c89a5ccf40ab404acfeb6d050
683,287
from pathlib import Path def norm_abs_path(path, ref_path): """\ Convert `path` to absolute assuming it's relative to ref_path (file or dir). """ path, ref_path = Path(path), Path(ref_path).absolute() ref_dir = ref_path if ref_path.is_dir() else ref_path.parent return ref_dir / path
91033a7cb3631616799c204259b5830c931035f0
683,288
from unittest.mock import Mock def service(): """ Create mock of service. """ service = Mock() service.log_dir = '' service.persistent_root = '' service.context.globals = {"cluster_size": 1} return service
a0cff8b3f790d1d2908928fe88442db5cb2c4cea
683,289
def scalar(query, default=None): """ A helper function that takes a query and returns a function that will query the database and return a scalar. """ def inner(model, *args, **kwargs): with model.engine.connect() as conn: val = conn.execute(query, *args, **kwargs).scalar() ...
17854357df154cff6d6bd361d81387083fe0a769
683,290
from typing import List def mako_local_import_str(package_name:str, key:str, imports:List[str])->str: """ Create an import string for mako template from the output_patterns.yml file, like `from docassemble.playground1.interview_generator import mako_indent, varname` """ return 'from ' + package_name + '.' +...
72d169114e38428caf2ecade3c6cfa8a83be416b
683,291
def _Refractive(rho, T, l=0.5893): """Equation for the refractive index >>> "%.8f" % _Refractive(997.047435, 298.15, 0.2265) '1.39277824' >>> "%.8f" % _Refractive(30.4758534, 773.15, 0.5893) '1.00949307' """ Lir = 5.432937 Luv = 0.229202 d = rho/1000. Tr = T/273.15 L = l/0.5...
f15203d04bf0ac8e4f83ffaa0f5409850c358e13
683,292
def echoByDavidKe(x): """ """ return x
b7f99f51be3ed0c668af42278362da608e2b635f
683,293
import subprocess def shell_output(command: str): """ Runs shell command and returns its output. Fails on exit code != 0. :param command: shell command :return: command's STDOUT """ process = subprocess.run( args=[command], capture_output=True, shell=True, text=...
4f9d3b44cae917d58cb6fe889157b959d473bc59
683,295
def get_user_choice(choices, choice_type, default_value=""): """ A common method to take user choice from a list of choices Args: (list) choices - list of choices (str) choice_type - Type of choice (boolean) default_value - Return default value in case wrong input Returns: ...
29ea8bb8eb0cb8e1bd7d1142fa08df2a77de3484
683,296
def partTypeNum(partType): """ Mapping between common names and numeric particle types. """ if str(partType).isdigit(): return int(partType) if str(partType).lower() in ['gas','cells']: return 0 if str(partType).lower() in ['dm','darkmatter']: return 1 if str(partType).l...
311f290a38c74052b8deb377d5b71e3f2683c154
683,297
import itertools def _split_list(lst, delim): """ 리스트를 delimiter로 split하는 함수 >>> _split_list(['가/JKS', '_', '너/NP'], '_') [['가/JKS'], ['너/NP']] Args: lst: 리스트 delim: delimiter Returns: list of sublists """ sublists = [] while lst: prefix = [x for...
9d10aa325109227e512bf30f5b04738b718cb11d
683,298
def save_omas_dx(odx, filename): """ Save an ODX to xarray dataset :param odx: OMAS data xarray :param filename: filename or file descriptor to save to """ return odx.omas_data.to_netcdf(filename)
6eb594d4247941f4b0b5407341740381d75a8cfe
683,299
import argparse def parse_args(): """parse command line arguments""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--gtf', type=str, he...
2fb5898bbd9782d1726f9950de676c2f39ee336a
683,301
import subprocess def run_command(args): """Run a command, returning the output and a boolean value indicating whether the command failed or not.""" was_successful = True # execute using a shell so we can use piping & redirecting proc = subprocess.Popen(args, stdout=subprocess.PIPE, shell=True) ...
f9e557c3e4cbd995a9ea687619f827bc920cc5d8
683,302
def lremove(s, prefix): """Remove prefix from string s""" return s[len(prefix):] if s.startswith(prefix) else s
b19235b643c3c0074e08f2b939353f05b6d0f630
683,303
def create_train_test_ranges(n_rows: int, h: int, v: int) -> object: """ Creates training and testing sets for dependent (i.e. temporal) datasets using hv-block cross validation, as described in: "Consistent cross-validatory model-selection for dependent data: hv-block cross-validation", by Jeff Racine,...
c6716cb3c9c992bb325499f60096681761935e08
683,304
def read_characteristic(device, characteristic_id): """Read a characteristic""" return device.char_read(characteristic_id)
3bc6394593fa50627b328d7670f92784f5a3901a
683,305
import requests from bs4 import BeautifulSoup def prelimSeeds(URL: str) -> dict: """Parses the prelim seeds page of a tournament Args: URL (str): the URL of the prelim seeds page of a certain division Returns: dict: a dict containing the parsed prelim data RETURN SCHEMA: ...
e508e4adf51392e5ed69e656db9dd9df92a836ab
683,306
import os import zipfile def python_zip(file_list, gallery_path, extension='.py'): """Stores all files in file_list into an zip file Parameters ---------- file_list : list of strings Holds all the file names to be included in zip file gallery_path : string path to where the zipfil...
7eaf83081224722705485c6e0798c58ef4a9b03d
683,307
def get_bbox_inside_image(label_bbox: list, image_bbox: list) -> list: """ Corrects label_bbox so that all points are inside image bbox. Returns the corrected bbox. """ xA = max(label_bbox[0], image_bbox[0]) yA = max(label_bbox[1], image_bbox[1]) xB = min(label_bbox[2], image_bbox[2]) yB...
c14d06796d1668d06d39ffec6f66e1bc6929b677
683,308
def date_to_string(date, granularity=0): """ Convert a date to a string, with an appropriate level of granularity. :param date: A datetime object. :param granularity: Granularity for the desired textual representation. 0: precise (date and time are returned) ...
8c560f4dd8dd6508e7ddf9aa7b6b649ab13a6008
683,309
def data(): """List of data items pytest fixture.""" return [-4, 0.5, None, "hey", [10]]
642b6b33993b5338ffe7b1342a888d1ac1604901
683,310
def flip_heatmap(heatmap, joint_pairs, shift=False): """Flip pose heatmap according to joint pairs. Parameters ---------- heatmap : numpy.ndarray Heatmap of joints. joint_pairs : list List of joint pairs shift : bool Whether to shift the output Returns ------- ...
7a7dacc310cdd6a0e4c86f448009c3b411b88e74
683,311
def fetch_ref_codon(ref_pos, curr_gene, curr_seq): """ Fetch codon within gene for given site """ # position of site in gene within_gene_pos = ref_pos - curr_gene['start'] if curr_gene['strand'] == '+' else curr_gene['end'] - ref_pos # position of site in codon within_codon_pos = within_gene_pos % 3...
0ee6454a76ade51950cacbd5f7f8859677b607a3
683,312
import numbers def _scale(scale): """ Given a numeric input, return a 2-tuple with the number repeated. Given a 2-tuple input, return the input >>> _scale(2) (2, 2) >>> _scale((1, 2,)) (1, 2) >>> _scale('nonsense') Traceback (most recent call last): ... TypeError: argu...
ac3bda11c58016b7a1db32ed47aa5d0a8e120b1c
683,313
import random def gen_color(): """ 为词云图生成随机颜色 """ return "rgb(%s,%s,%s)" % ( random.randint(0, 160), random.randint(0, 160), random.randint(0, 160), )
9fdcf491279ab92fffe0cd6c0c7b27336ba3c519
683,314
def checkValid(s, row, col): """ Returns True if a given cell is valid in a Sudoku puzzle, and False if not. A cell is valid if the number in that cell is not present in any of the cells in the same row, or the same column, or the same block. """ block_row = row // 3 block_col = col // 3 ...
50397a98099612b7c9e225748662f092beff5d1e
683,315
import subprocess def run_local_cmd(cmd): """ @summary: Helper function for run command on localhost -- the sonic-mgmt container @param cmd: Command to be executed @return: Returns whatever output to stdout by the command @raise: Raise an exception if the command return code is not 0. """ ...
a20a52b7ea106ae8c7e6be275844337ffa22453f
683,316
def isBoxed(binary): """Determines if a bit array contains the marker border box.""" for bit in binary[0]: if bit != 0: return False for bit in binary[7]: if bit != 0: return False c = 1 while c < 7: if binary[c][0] != 0 or binary[c][7] != 0: ...
3068ce2e522cb4a9a7ccdad4d9f9ecde185be660
683,317
def loss(K, y, alpha, L, h=0.5): """ Implements the huber hinge loss: """ _, n = K.shape z = 1 - y.reshape(-1,1) * K @ alpha z[(z < h) & (z > -h)] = ((z[(z < h) & (z > -h)] + h) ** 2) / (4 * h) z[z < -h] = 0 return L * alpha.T @ K @ alpha + (1 / n) * z.sum()
ad98442aa4aafe39051b7a51f99e6b5d7cf42f31
683,318
def fake_id_func(): """Fake identifier function that always returns '0000'.""" return '0000'
bbb036135ba466e5eac21d0d160cce98faf148d6
683,319
import socket def findMyIp(): """ A noddy function to find local machines' IP address for simple cases.... based on info from https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib returns an array of IP addresses (in simple / most cases there will only be one ...
40d15369bffa2373f8a2d7ebf576dfb59177db63
683,320
import numpy def _calcProportionaTieStrengthWRT(A,i): """ Calculates P from Burt's equation using only the intersection of each node's ego network and that of node i A is the adjacencey matrix """ num = A.copy() num = num + num.transpose() P = A.copy() mask = numpy.where(A,1,0) mask = mask[i] mask[0,...
d82db51342b1c6bbd189ac00bd63074cf5167448
683,321
import sys from io import StringIO import traceback def grabOutput(func, *args): """Calls ``func(*args)`` capturing and returning stdout and stderr. :param func: a function to call :param args: arguments for *func* """ ko, ke = sys.stdout, sys.stderr sys.stdout, sys.stderr = StringIO(), Strin...
8df8f5898756154f551e99b1428bc2d785616430
683,322
def convert_to_builtin_type(obj): """return a string representation for JSON conversation""" return str(obj)
bd3be8e59caae359a3821b3c7fa376f0dd2b9cf0
683,323
from typing import Any def _len(x: Any) -> int: """Return len of x if it is iterable, else 0.""" return max(1, len(x)) if isinstance(x, list) else 0
a79dfef8014152de222135fb65ce0e95d32d1489
683,324
def timedelta_to_seconds(td): """ Converts a timedelta to total seconds, including support for microseconds. Return value is (potentially truncated) integer. (This is built-in in Python >= 2.7, but we are still supporting Python 2.6 here.) :param td: The timedelta object :type td: :cla...
b53f200174a483321e4664af639f3677467e6bb1
683,325
def luhn_checksum(num: str) -> str: """Calculate a checksum for num using the Luhn algorithm. :param num: The number to calculate a checksum for as a string. :return: Checksum for number. """ check = 0 for i, s in enumerate(reversed(num)): sx = int(s) sx = sx * 2 if i % 2 == 0 e...
18b584959268e510877b2b26e9b968abcfcdc644
683,326
def p1_evl(x, coef, N): """ p1_evl Evaluates the given polynomial of degree N at x. Evaluates polynomial when coefficient of N is 1.0. Otherwise same as polevl(). In the interest of speed, there are no checks for out of bounds arithmetic. Parameters ---------- x: Argument of the polyno...
e7598784e4a6b2d8de04994da9084d3e2a5829ab
683,327
def mock_response1(): """Generate data for mock1 response.""" x = { "result": { "data": [ { "ecosystem": ["maven"], "name": ["io.vertx:vertx-web"], "latest_version": ["3.6.3"] }, { ...
bb05d944e5f49bc90bb5d82597af6a65e677c113
683,328
import time def create_record_commands_action(): """Create a list in which commands will be recorded when the `record_commands` function is given as an action to the routine. :return (list, callable): the list that actions are recorded in, and the function that causes them to be recorded """ reco...
fc67a972bc47ae5cf3d98c77640cbf8bd69938ea
683,329
def test_chess_cell(x, y): """ Source https://pythontutor.ru/lessons/ifelse/problems/chess_board/ Condition Two checkerboard squares are set. If they are painted the same color, print the word YES, and if in different colors - then NO. The program receives four numbers from 1 to 8 each, specifyi...
2f5d597fa869949ba0ca205c799aa3f98a2fa75d
683,330
import argparse def parse_arguments(): """Parses command line arguments specifying processing method.""" parser = argparse.ArgumentParser() parser.add_argument("--experiment_name", "-e", default="exp_fusion", type=str) parser.add_argument( "--dataset_name", default="acrim", type=str, choices=[...
28f7a7a732d8c6c262272d5d61421749e3584af5
683,331
import re def gen_atomic_statements(sentence): """ obsługuje sytuację (1) ..., (2) ... :param sentence: :return: """ rex = r"\([abcdefghi123456789]\)([A-z \n,–:;-]+(\(?(?=[A-z]{2,})[A-z]+\)?[A-z \n,-–;]+)+)" splits = re.split(rex, sentence) main_sentence = splits[0] if splits is not No...
10b3355e38fb051aa6c67a3ad94a3872c7deb0df
683,332
def get_default_stats(): """Returns a :class: `dict` of the default stats structure.""" default_stats = { "total_count": 0, "max": 0, "min": 0, "value": 0, "average": 0, "last_update": None, } return { "totals": default_stats, "colors": {...
7b340d18f03c25d58d4951d47ea31bca9a93bf46
683,333
import re def parse_description(dsc): """ Parse the given string into a hash. The string format is `key: value`, where key gets converted to upper case and value extends until a new line. A special last field `Abstract:` extends until the end of string. """ meta, abstract = re.split('a...
5a336706671a68f7b284e8a862441982a539f84b
683,334
def filter(c, v): """ :param c: curvature :param v: speed :return: Ture or False """ return v > 1 and c < 0.5
ac8a4e63dead1664db0a36ea6fb39d03beedda8d
683,335
def decode(packet): """ https://raw.githubusercontent.com/telldus/telldus/master/telldus-core/service/ProtocolOregon.cpp >>> decode(dict(data=0x201F242450443BDD, model=6701))["data"]["temp"] 24.2 >>> decode(dict(data=0x201F242450443BDD, model=6701))["data"]["humidity"] 45.0 """ if pack...
7b2030d4ae9a6f5773f7cd3aa305ba400c02e93a
683,336
def get_type_default_value(prop_type: str): """ Returns the default value of the given Haxe type. If the type is not supported, `None` is returned: """ if prop_type == "Int": return 0 if prop_type == "Float": return 0.0 if prop_type == "String" or prop_type in ( ...
bf7df4bd7f3ca70ac3773d12bd3dc72a54f83a85
683,338
import codecs def is_ascii_encoding(encoding): """Checks if a given encoding is ASCII.""" try: return codecs.lookup(encoding).name == "ascii" except LookupError: return False
34b7e9ff3bcab56607062740d2caa7cd5bbeecd3
683,339
import numpy def winning(matrix, connect=4): """Check if player 1 or 2 wins with the board return tuple with (winning true/false, player who won) """ rows = matrix.shape[0] columns = matrix.shape[1] #horizontal for x in range(rows): for y in range(columns-connect+1): if...
0e76bc6d93ccea68adf8d446bfc9bd3bc2fc42dd
683,340
import os def get_output_subdirectory(input_filename, output_dir=None): """ Get the output subdirectory for a specific input file. """ input_dir, filename = os.path.split(input_filename) fileroot, ext = os.path.splitext(filename) if output_dir is None: output_dir = input_dir output...
882a770078a65b0919b9bc41d363f42ae9b7936e
683,341
def _find_idx_without_numerical_difference(df, column1, column2, delta, idx=None, equal_nan=False): """ Returns indices which have bigger numerical difference than delta. INPUT: **df** (DataFrame) **column1** (str) - name of first column within df to compare. The values of df[c...
9ed9f34b1b8718ee213fd7b8832e5efe7365f116
683,342
def getDomainOnly(url): """Return the domain out from a url url = the url """ # print ("getDomainOnly : ", url) tmp = url.split('.')[-2] + '.' + url.split('.')[-1] tmp = tmp.split('/')[0] return tmp
568a056533e4a5014deb0c1a53ac08c994caf6ab
683,343
import logging def get_logging_level(): """get level for the named logger.""" return logging.getLogger('qiskit.aqua').getEffectiveLevel()
9fa3f0a20057d659d4d0d412d4aa31152737c21f
683,344
import os def find_dest_path_comp_key(files, src_path=None): """ This is a helper function that determines the destination path and compare key given parameters received from the ``FileFormat`` class. """ src = files['src'] dest = files['dest'] src_type = src['type'] dest_type = dest['...
5e43ae60e4561636412f4012a8f66a868d77834b
683,345
import time def sb_session_login(sb_session, sb_username, sb_password=None): """ login in to sb session using the input credentials. Checks to see if you are already logged in. If no password is given, the password will be requested through the command prompt. .. note:: iPython shells will echo...
62b9b605e0537054c09f4caebab66d250df1aaeb
683,346
import torch def calc_full_matrix(opt_vars, weights, x0, y0, yp, l, u, shapes, numerical=True): """ Note: all input parameters are detached for fast computation Return -S in dense torch.tensor representation :param opt_vars: gamma, lbdas, nus, etas, and s :param weights: Ws, and bs :pa...
c8b58210c4e59a8af8a847ab3577657e4f1294fe
683,348
def _find_root_linear(x1,x2,f1,f2): """Find root x1,x2 by using interpolation. @param x1: left border of range @type x1: float @param x2: right border of range @type x2: float @param f1: value for x1 @type f1: float @param f2: value for x2 @type f2: fl...
1eb755908b6c8efe3a36bc0558a21b9a443cea51
683,349
def _(s): """ Dummy function later to be replaced for translation. """ return s
26c0e691115e7103e5f6796df09c572a63a961a2
683,350
def subroutine_type(name): """Returns type of subroutine, 'setup' or 'teardown' if it has either of those names, or module setup or teardown, otherwise None.""" lowername = name.lower() if lowername == 'setup': subtype = 'global setup' elif lowername == 'teardown': subtype = 'global ...
e9675b3719b0fac8695d5251adf87e98dd1352b6
683,351
def permutation(s): """ @s: list of elements, eg: [1,2,3] return: list of permutations, eg: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]] """ ret = [] length = len(s) if length == 0: return ret if length == 1: return [s] curr = s[0] for prev in permutat...
bb49487012cd54f9c58ac7c1cce87c1c05eb33ed
683,353
from pathlib import Path import platform def change_homedir(monkeypatch): """Change home directory for all tests""" monkeypatch.setattr(Path, "home", lambda: Path(f"./tests/test_homedirs/{platform.system()}")) return platform.system()
ed90e5e18a3513d28660f722df36f6f6ad2e182c
683,354
def PScratch (inOTF, err): """ Create a scratch file suitable for accepting the data to be read from inOTF A scratch OTF is more or less the same as a normal OTF except that it is automatically deleted on the final unreference. inOTF = Python OTF object err = Python Obit Error/message sta...
71659feae595656bf5288487218c66db570f1ec1
683,355
import torch def rot90(input_, k=1, axes=(0, 1)): """Wrapper of `torch.rot90` Parameters ---------- input_ : DTensor Input dense tensor. k : int, optional Number of rotation times, by default 1 axes : tuple, optional The axes in which the input is rotated, by default (...
2b784a82ae7fa2d1b87dd687d0ba6ed796dda248
683,356
def camelize(s): """ >>> camelize('camel_case') 'CamelCase' """ return ''.join(ele.title() for ele in s.split('_'))
73bf0d337c13713e7dc99aa9c1725b8024d4deea
683,357
def _makeSetter(compiledName): """Return a method that sets compiledName's value.""" return lambda self, value: setattr(self, compiledName, value)
d74190723979d4671b2b25bae57b93219fa34046
683,358
import torch def get_optimizer(model, learning_rate, optimizer_state_dict=None, verbose=False): """ Returns an ADAM optimizer attached to the given model (and stored on the same device). If optimizer_state_dict is not None, it will fill in the optimizer state. However, learning_rate will override ...
404224341d137ae662a25d787b6c0b3cbb409448
683,360
def sort_on_columns(df, columns, ascending=True, algorithm='mergesort', na_position=None, **kwargs): """args_str is expected to be a comma-separated list of column names""" print('sorting on columns', columns, ascending) na_position = na_position if na_position is not None else ('last' if ascending else 'fi...
02466d94ebac6aee28e7a77c09021741cf7c9863
683,361
def inc(x): """ Returns a number one greater than num. """ return x + 1
2f74ab001252b295b8acd8effabb2c30e526b66a
683,362
import requests def get_latest_release_from_pypi(*, package: str) -> str: """Get the latest release of a package on pypi""" response = requests.get(f"https://pypi.org/pypi/{package}/json").json() return response["info"]["version"]
6f24b23f87c765a3e59d87cd4c1deb5414e64b1e
683,363
def medium_config(): """Medium config.""" return{ "init_scale" : 0.05, "learning_rate" : 1.0, "max_grad_norm" : 5, "num_layers" : 2, "num_steps" : 35, "hidden_size" : 650, "max_epoch" : 6, "max_max_epoch" : 39, "keep_prob" : 0.5, "lr_decay" : 0.8, "...
f4b78c1f17e680120e5c44907eb21f7c6e6638d6
683,364
def CodeChunk(text, width=72): """Split a line of text into a list of chunks not longer than width.""" chunkList = [] chunkStart = 0 chunkEnd = 0 lastSpacePosition = 0 shortWidth = width - 4 prefix = '' # suffix = ' \\' textLen = len(text) if width > textLen: chunkLis...
125d0e7fc60d90f802ced3da60d11d3823e65025
683,365
import os def get_source_files(sourcelist, appdir): """ Get sources from *.c files """ src = [] for item in sourcelist: if item.endswith(".c"): item = os.path.abspath(item).replace("\\", "/") tmp = item.replace(appdir + "/", "") if tmp: src.appen...
b8141b47e21a6c75668f4346c602efae28eafdc7
683,366
def division(x : float,y : float) -> float: """ Precondition : y != 0 """ return x / y
cca2e05b78a7d1996dfe921a9292fc4810907f6d
683,367
def verdicts_to_dictionary(verdicts): """ Translate FormulaTree instances into a dictionary. """ verdict_dict_list = [] for map_index in verdicts: for formula_tree in verdicts[map_index]: verdict_entry = {"timestamp_sequence": [], "configuration": None, "observations": None} ...
5b926c369f934dd571ef5b1dc013f641749090dd
683,368
def filter_to_sentry(event, hint): """filter_to_sentry is used for filtering what to return or manipulating the exception before sending it off to Sentry (sentry.io) The 'extra' keyword is part of the LogRecord object's dictionary and is where the flag for sending to Sentry is set. Example...
3efb1be247d4dd657ddce2c8c09b88618d1a2e24
683,369
def greatest_adjacent_product(target, window): """Find the greatest product composed of adjacent digits in the target. Arguments: target (int): A target number whose digits should be searched. window (int): The number of adjacent digits to consider. Returns: int: The greatest adjac...
be66d135dcdf9a604020fd8fc00813c300bd28ac
683,370
def dict_change(a: dict, b: dict): """Elements of b that are not the same in a""" return { **{k: v for k, v in b.items() if k not in a or a[k] != v}, **{k: None for k in a if a[k] is not None and k not in b}, }
5367269a12ffdcd0f7485bf407592a1c5b3a0f35
683,371
def _capture_callback(x): """Validate the passed options for capturing output.""" if x in [None, "None", "none"]: x = None elif x in ["fd", "no", "sys", "tee-sys"]: pass else: raise ValueError("'capture' can only be one of ['fd', 'no', 'sys', 'tee-sys'].") return x
79a905c5793fabe43475ecc8a46c162f01060250
683,372
def split_text(width, text, text_list=None): """ Splits the message of the GUI message panel if the message is too long. """ if not text_list: text_list = [] txt_length = len(text) if txt_length <= width and text_list: result = '\n'.join(text_list) + '\n' + text ret...
13d5d7ad03e7e80b462a286099b69b24512a499d
683,373
from typing import List def _expand_script(script_name: str, unique_ids: List[str]) -> List[str]: """ Expands the selected script name to unique id format. for example [scripta.py] to [script.modelB.AFTER.scripta.py, script.modelA.BEFORE.scripta.py] """ def contains_script_name(id: str): ...
ff76a713d55b1b97bdd720fca5e1974252470154
683,374
def compare(user_score, computer_score): """Compare the scores 0 = black jack (the sum of black jack is 21)""" if user_score > 21 and computer_score > 21: return "Computer win 🎲" if user_score == computer_score: return "It is a Draw 🎲" elif computer_score == 0: return "Com...
dfcd5587075231a28a2333cdcb7fc0a93835a079
683,375
def get_new_sol_file(test_nr): """ Get name of new solution file """ return "test/{0}-new.sol".format(test_nr)
99da7df153c741d2360529696ee9fcc129ed099c
683,376
def _SumRows(*rows): """ BRIEF Total each of the columns for all the rows """ total = [0.0]*len(rows[0]) for row in rows: for i, col in enumerate(row): total[i] += col return total
ebf53a09a26ba35d13c4b31a7bed1f2109091d27
683,377
def interlis_models_dictionary(*argv): """ Combine different interlis model dictionaries :param argv: several interlis model dictionaries :return: dictionary of combined model dictionaries """ combined_dictionary = [] for arg in argv: combined_dictionary = combined_dictionary + arg ...
54d111a62b9fb71f256115bd4c9e77a1a1f40ae6
683,378
def mult(M, v): """ function to multiply a matrix times a vector """ n = len(M) return [sum(M[i][j] * v[j] for j in range(n)) for i in range(n)]
a2d1ddd9b1a6b17580278a52e75660295a1eedfe
683,379
import requests def read_url(url): """Read given Url , Returns requests object for page content""" response = requests.get(url) return response.text
a5a228955ad844e4192d55675b7eebddbf9cf285
683,380
import torch def minSNRsdsdr(s,s_hat): """Computes the minimum between SNR and Scale-Dependant SDR as proposed in [1]_, obtaining a loss sensitive to both upscalings and downscalings. References ---------- .. [1] Le Roux, Jonathan, et al. "SDR–half-baked or well done?." ICASSP 2019-2019 IEEE Inte...
5934e639c8ac31889863d6d5af21060ff5d721e0
683,381
import re def unwrap_wrapped_text(text): """ Unwraps multi-line strings, but keeps paragraphs separated by two or more newlines separated by newlines. """ result = [] _re_indentation = re.compile(r'^[ \t]*|[ \t]*$', re.MULTILINE) for paragraph in re.split(r'\n{2,}', text): paragraph = ...
47e2006fd7617bc9d6b125a786eed5e953eb5bbb
683,382
def list_to_str(data=None): """ 解析列表,将所有的成员转换成列表,中间用空格分隔开 :param data: 需要解析的字符串 :return: string """ if data is None: data = [] str_data = "" for item in data: str_data = str_data + " " + item return str_data.strip()
5e679728c21f72ccf091b865d9f30ec9b0866b90
683,383
def _scatter_element_add_numpy(tensor, index, value): """In-place addition of a multidimensional value over various indices of a tensor.""" new_tensor = tensor.copy() new_tensor[tuple(index)] += value return new_tensor
6827449a5820196752dcc5a84b987b33a2700b2b
683,384
def _simplify_ast(raw_ast): """Simplify an AST that comes out of the parser As well as replacing pyparsing's ParseResults with bare lists, this merges adjacent non-condition words. For example, "a b" parses to ["a", "b"]. This function merges that to ["a b"]. The idea is that this will be much mor...
77091f287b58b03e5073a2cee5e1fb571747c5fc
683,385
def repo_health(request): """ pytest fixture used to see if repo health check is being run if repo_health is set to true: only repo health checks will be run else: no repo_health checks will be run, other tests may or may not be run """ return request.config.option.repo_health
941d65e3e901a51d1696c91b23c7085581e80cae
683,386
def test_hindcast_verify_brier_logical(hindcast_recon_1d_ym): """Test that a probabilistic score requiring a binary observations and probability initialized inputs gives the same results whether passing logical as kwarg or mapping logical before for hindcast.verify().""" he = hindcast_recon_1d_ym d...
f1d3dd92f65610ead5d154ffdc7d456364907ffb
683,387