content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def normalize_query_param(query_param): """Normalize query parameter to lower case""" return query_param.lower() if query_param else None
9bb21d79b774c5d5ff735c7b2ff46739d1c9e3c8
660,510
def disconnect_or_wait(): """ This function ask for the player if he wanna disconnect(return 1) otherwise he will wait for message of winner @param None:None @return :int 1 if wanna disconnect , 0 if wanna wait """ print("Type 1 if you wanna disconnect of game, 0 if you wanna waiting for know the winner") en...
caa5e3b547e50fef091732fa730fb5cb0920610f
660,511
def scoreboard(board, depthleft, alpha, beta, evaluate, maximising_player): """ https://youtu.be/l-hh51ncgDI """ if depthleft == 0: # Return end leaf score = evaluate(board) return_score = score if maximising_player else -score ...
40d5ab1dc2edfcffc4630f518b55aee4729ee16c
660,513
def flush_log_bkp(args_array, server): """Function: flush_log_bkp Description: flush_log_bkp function. Arguments: (input) args_array (input) server """ status = True if args_array and server: status = True return status
6c27891aa4b1ecf077f3a5ac2b85b84619b0c479
660,514
def y_n_to_bool(str_arg): """Convert Rinnai YN to Bool""" if str_arg == "Y": return True return False
225e5948f642a07b09516ffcd9e80b675d8c3b8a
660,515
def signature_for_type_name(type_name): """Determine the JNI signature for a given single data type. This means a one character representation for primitives, and an L<class name>; representation for classes (including String). """ if type_name == "void": return "V" elif type_name == ...
3a9a230b2386c4c83b50e6f9919e7683734f0ce4
660,516
def layer_name_to_dict(min_zoom: int, max_zoom: int, name: str) -> dict: """Convert layer name to dict for conversion.""" return dict( directory=name + "/{z}/{y}/{x}.png", name=name, min_zoom=min_zoom, max_zoom=max_zoom + 5, max_native_zoom=max_zoom, )
02b75e2b58d5504cc52c1c8fadbf078910f3b154
660,517
import pytz from datetime import datetime def convert_unix_ts(timestamp, timezone = "Europe/Berlin"): """Utility function to help converting flespi utc unix time output to human readable. Parameters: ----------- timestamp: int Unix time generated py flespi platform. timezone: str ...
0f869f311e41b26cc897c2c63611b9a09e4ddcb2
660,519
def get_mask(gt_np, label_np, pred_np): """ Args: gt_np: the GT label label_np: the CAM pseudo label pred_np: the prediction Returns: the mask of different type """ wrong_mask_correct = (gt_np != label_np) & (pred_np == gt_np) wrong_mask_memorized = (gt_np != label_np)...
209dc6114e967d54cad23d6bb5e060da63bad104
660,520
def check_is_contained(array1, array2, start_idx): """ :param array1: sublist :param array2: list :param start_idx: the start index used to search :return: Whether list contains sublist Time complexity: O(n * m) """ n = len(array2) for idx, value in enumerate(array1): if star...
d7d22fcc927dd2db8c6164f2a13c6abfdf793cb0
660,522
import json def dump_args(args: tuple, kwargs: dict) -> str: """Util to make hashable function arguments.""" return json.dumps(args) + json.dumps(kwargs, sort_keys=True)
0dc013159bfc7896a1c2c4b723e7ecbf16acc9e4
660,523
def siunitx_format_unit(units, registry): """Returns LaTeX code for the unit that can be put into an siunitx command.""" def _tothe(power): if isinstance(power, int) or (isinstance(power, float) and power.is_integer()): if power == 1: return "" elif power == 2: ...
6a8f522e01c64f04ec0fd0f8422a1482a7029bac
660,524
import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suff...
c82c8d0deb35904f00d4f30a1beb1283d9aba82d
660,525
import click def _call_in_source(dag, method_name, message, kwargs=None): """ Execute method on each task.source in dag, passing kwargs """ kwargs = kwargs or {} files = [] results = [] for task in dag.values(): try: method = getattr(task.source, method_name) e...
fe1ad53e19e8aaa1265d27124d2d56eb61c689c0
660,526
def escape_curly_brackets(url_path): """ Double brackets in regex of url_path for escape string formatting """ if ('{' and '}') in url_path: url_path = url_path.replace('{', '{{').replace('}', '}}') return url_path
ce6562abecee0c5759db8cffc36c14f9ca90e233
660,527
def isA(instance, typeList): """ Return true if ``instance`` is an instance of any the Directive types in ``typeList`` """ return any(map(lambda iType: isinstance(instance,iType), typeList))
c9b7ff32080042fd33146c802688b39fe7864698
660,528
def readIDS(f): """reads a one column file in and stores the ids in a dictionary that is returned at the end""" ret = dict() with open(f, "r") as file: for line in file: line = line.strip() if(line not in ret): ret[line] = 1 return ret
1d4687db1a354583df3456425ee3a03f0c16ea82
660,531
def padlist(container, size, default=None): """Pad list with default elements. Examples: >>> first, last, city = padlist(["George", "Costanza", "NYC"], 3) ("George", "Costanza", "NYC") >>> first, last, city = padlist(["George", "Costanza"], 3) ("George", "Costanza", None) ...
bea4c2971dfe8d1cd5a2c678f1b8f8eadd15ced0
660,532
def fast_exponentiation(a, p, n): """A fast way to calculate a**p % n""" result = a%n remainders = [] while p != 1: remainders.append(p & 1) p = p >> 1 while remainders: rem = remainders.pop() result = ((a ** rem) * result ** 2) % n return result
e492e0c29048db787f000b1cea7c803c2a8caa78
660,533
import itertools def unpack_fields(fields): """ Flattens the given fields object into a flat list of fields. Parameters ---------- fields : (list | dict) List or dict that can contain nested tuples and None as values and column names as keys (dict). Returns ------- li...
bee277f4665ac4a43baeb37a6289558e1b4c101f
660,534
import re def _sanitize_query(query: str) -> str: """ Remove some invalid characters from the query Parameters ---------- query : str A search query to be sanitized Returns ------- str A sanitized query """ query = re.sub(r'\s+', ' ', query) return query
130a5dbb9fd835809f68b039f40db4961a2d6ba9
660,535
import os import subprocess def merge_pair(fq_1, fq_2): """ Merges the two paired bam files and returns merged bam file string fq_1 -- String, the name of the accesion sample, ".fastq"-file fq_2 -- string, name of the accesion sample, does not have .fastq extention!!! """ Path_...
cec7d4afd2c2a992e59b1a186d84a2c7cbe4aad5
660,536
def parse_ini_file(fn): """Parse INI file and return dictionary""" ret = {} section = '' with open(fn) as infile: for line in infile: line = line.strip() if line == '' or line.startswith('#'): continue if line[0] == '[' and line[-1] == ']': ...
19003cd173a396b70d2e1f5c65af4ad5df432189
660,537
import requests def is_icontrol(): """Determines if the TMOS control plane iControl REST service is running""" try: return requests.get( 'http://localhost:8100/shared/echo', auth=('admin', '') ).json()['stage'] == 'STARTED' except Exception: return False
5175a1c3108a6275f5db321c64f3ab8a2bbe9b81
660,538
import os def path(location): """If location is a module or package, return its path; otherwise, return location.""" from_list = location.split('.')[:1] try: pkg = __import__(location, {}, {}, from_list) except ImportError: return location return os.path.dirname(pkg.__file__)
51bd207d6bc0b7f2b72fa9ae2d5047dfe14d0e3d
660,539
import io def peek_version_and_type_id(buffer: io.StringIO) -> tuple[int, int]: """ Reads the version and type id from the buffer before returning to the original buffer position """ position = buffer.tell() version = buffer.read(3) type_id = buffer.read(3) if version == '': raise...
33220f3c042ae0da97296af59eb55fa2c94f7aba
660,541
from typing import Tuple from typing import List def _get_lie_algebra(segment_sign: Tuple[int, int, int], radius: float) -> List[Tuple[float, float, float]]: """ Gets the Lie algebra for an arcline path. :param segment_sign: Tuple of signs for each segment in the arcline path. :pa...
791fb523f33652f6a5d8362e34b9ea582a7620e6
660,542
def simplify_matrix(matrix): """ If A owes B and B owes A back, then only a single transaction can settle both up. :param matrix: payment matrix :return: simplified payment matrix """ i_j_pairs = [[i, j] for i in range(4) for j in range(4) if i < j] for i_j_pair in i_j_pairs: i = i_j...
4d02e0fe31fb00430d569540b1ff931adf0b91f8
660,543
import argparse def _parse_arguments(): """Simply parse the port on which to run.""" parser = argparse.ArgumentParser() parser.add_argument( "-p", "--port", dest="port", default=5000, type=int, help="The port on which to run a node. Defaults to 5000.", )...
fe83d3ed21917d3264e9d5595ed96a09f4762fae
660,544
def rst_link_filter(text, url): """Jinja2 filter creating RST link >>> rst_link_filter("bla", "https://somewhere") "`bla <https://somewhere>`_" """ if url: return "`{} <{}>`_".format(text, url) return text
01fe0f88518611abbec3abd2f93d0cb4439cd225
660,545
def update_show_clade_defining(switches_value): """Update ``show_clade_defining`` variable in dcc.Store. This should be set to True when the clade defining mutations switch is switched on, and False when it is turned off. It is None at application launch. :param switches_value: ``[1]`` if the clad...
2905ec5ac8579b250df30c5f8bd629f1b7701965
660,546
def change_score(element, p=0.90): """ Function that iterates through the values parameter elements, converting them to positive (if necessary) and discarding those higher than the parameter value "p" (typically 0.90). It is useful to help the "knn" function (and the "corr_target" auxiliary function), w...
849604520657c4e7c061a3adc3f30b4ba24bf700
660,547
def gen_endpoint_scaling(endpoint_name, scaling_policy_name, scale_config): """ Generate the endpoint scaling resource """ endpoint_scaling = { "ScalingTarget": { "Type": "AWS::ApplicationAutoScaling::ScalableTarget", "Properties": { "MaxCapacity": scale_c...
05f1c48f0d4f3ce1e6efcfc58094a708c97044f8
660,548
def compileEnumPropertyList(iterable): """ Args: iterable: Returns: """ return ((a,) * 3 for a in iterable)
29f97b2293eaa1100401dc744b243a7c01878411
660,549
import re def sjekkdatoer( fra, til, dato): """ sjekker om datoe er innafor intervallet [fra, til> """ fra = int( re.sub( '\D+', '', fra ) ) til = int( re.sub( '\D+', '', til ) ) dato= int( re.sub( '\D+', '', dato ) ) if dato >= fra and dato < til: return True els...
191238ff2df0b6837196a6f4453b13f720962275
660,550
def get_sum(path, tree): """ Returns the sum of all the numbers in the path for the given tree. """ pathsum = 0 for i, row in enumerate(tree): pathsum += row[path[i]] return pathsum
018cc24c6a1dc20cd9dbf5b0db6e3b20e257c7e6
660,551
def hash_shard(word): """Assign data to servers using Python's built-in hash() function.""" return 'server%d' % (hash(word) % 4)
ab333bba1f93909369f6935786a268bbda984e9e
660,552
def push_row(matrix, row): """Pushes row with index row to the bottom of the matrix, and shifts all other rows up""" return [matrix[i] for i in range(len(matrix)) if i != row] + [matrix[row]]
f2b9b4d2a2e199c7ac66ab817931323d218ded5a
660,554
def _is_cuda_oom(e: RuntimeError): """Determines if error is CUDA Out of Memory and if adaptive_grad_accum is enabled.""" return 'CUDA out of memory' in str(e)
477c1f14157ed90ad1a7ff94585e52b933131a03
660,555
import statistics def training(population, goal): """Check if the population is doing good and nearing the goal""" avt = statistics.mean(population) return avt / goal
8d32fa269a39a81141f249f9800828f621a517e5
660,556
def fast_pow(x, e, m): """Performs fast modular exponentiation, saves RAM on small CPUs/micros. :param int x: Base :param int y: Exponent :param int e: Second exponent """ X = x E = e Y = 1 while E > 0: if E % 2 == 0: X = (X * X) % m E = E // 2 ...
c890905f96f13ba8c0138553c7a97b867b38549d
660,557
def build_mask(mask, used_features): """ Function used to complete the mask with unused features not available for feature selection """ for index, key in enumerate(used_features): if not mask[index]: used_features[key] = 0 return used_features
b22e2cd2c6dcdfaeb2b96fa3281ca2cff10b9192
660,558
import collections def are_lists_equal(list1, list2): """ Checks whether two lists are equal (contain exactly the same elements). Using Counter data structure allows duplicates to be considered i.e. [1, 1, 2] != [1, 2]. :param list1: the first list. :param list2: the second list. :return: tru...
cc3c1e3cee5f41361dfdd65f2ebcacc07b7540d6
660,559
def read_installer(myinstaller, log): """ reads the text of the current installer script and returns it as a string """ log.info(f"Reading current installer from {myinstaller}...") with open(myinstaller, "r") as f: text = f.read() log.info(f"\t=> found {len(text)} characters") return...
d063beb7def5ccd8ef2b6de64be297e541e59753
660,561
def requires_reload(action, plugins): """ Returns True if ANY of the plugins require a page reload when action is taking place. """ return any(p.get_plugin_class_instance().requires_reload(action) for p in plugins)
5cf26e1e22dc62f6b1280a7d5f664f30ee220e94
660,562
def abs(mat, target = None): """ Apply the logistic sigmoid to each element of the matrix mat. """ if not target: target = mat target.resize(mat.shape) target.numpy_array[:] = abs(mat.numpy_array) return target
f87f08b0c891a3e6b7bdb02694a8645d20773066
660,563
def flatten_tree(t): """ flattena a PTB tree, return: (a list of the text values, top node label) >>> t = parse('(4 (3 gorgeously) (3 (2 elaborate) (2 continuation)))') >>> flatten_tree(t) (['gorgeously', 'elaborate', 'continuation'], 4) >>> t = parse('(3 gorgeously)') >>> flatten_...
b7bfd4ffd090cd4c914df04a9107b9d5bfa1797f
660,564
def arr_apply(arr, func): """Apply function for values""" return func(arr)
600bfbc15124eabeaec93f8273bf69fd329d78c7
660,565
import random def gen_conds(cond_cols, rows): """ Args: cond_cols (TYPE): NULL rows (TYPE): NULL Returns: (col_id, col_name, col_name_original, value) Raises: NULL """ row_idx = random.randint(0, len(rows) - 1) active_row = rows[row_idx] return [col_info + (active_ro...
e9cd590a63b6c0dcca9305c1d959f8be18f4afc7
660,566
from typing import Union from pathlib import Path def file_variations( filename: Union[str, Path], # The original filename to use as a base. extensions: list, ) -> list: # list of Paths """Create a variation of file names. Generate a list of variations on a filename by replacing the extension with ...
b8f1953b7b59791ac1c2650aa959fef39ce53f1e
660,569
def sequential_search(array, element): """ General Sequential Search. Works on Unordered lists. """ # Start at position 0 position = 0 # Target becomes True if element is in the list found = False # go until end of list while position < len(array) and not found: # If match...
0097468498eb7d42fbc2dfdc66e5f0cafd89d5d2
660,570
import os def read_file(rel_path, *args, **kwargs): """Function to read the contents of a file located in the subfolder tests/resources into a string :param rel_path: the relative path to the file from tests/resources""" path = os.path.join(os.path.dirname(__file__), "resources", rel_path) with open(...
c257f3f0c9f69ceddd98e866656d9358118d499f
660,571
import torch def get_subclassed_model_definition(): """ Defines a PyTorch model class that inherits from ``torch.nn.Module``. This method can be invoked within a pytest fixture to define the model class in the ``__main__`` scope. Alternatively, it can be invoked within a module to define the class in ...
d46c37a2ab630d538107bb99d9c6c67116b57de7
660,572
import glob def get_lastest_model (model_folder, k): """ get_lastest_model Get the lastest model of a current folder Input : model_folder : str, path of the folder containing the models k : number of models to get Ouput : path of the lastest mode...
50441ceda2cdd2045dcfc02af79f9d300d9973ce
660,573
from typing import Dict from typing import Optional import operator import inspect import os def _linkcode_resolve( domain: str, info: Dict[str, str], organization: str, project: str, revision: Optional[str] ) -> Optional[str]: """ Resolve the given Python module and fully-qualified entity name to a URL...
3774c912bb57c7a7c816347a26706575f0e43227
660,574
def is_kaprekar_number(num): """ Returns true if n is a Kaprekar number, else false A Kaprekar number is a number whose square when divided into two parts and such that sum of parts is equal to the original number and none of the parts has value 0 :param num: :return: """ string_num = ...
0614ec8bb0a8b1c0a54e96a21cc3b94160ce8ec0
660,575
def extract_data(file_name, version): """Saves the extracted data into a dictionary to be inserted in the table.""" file_version_data = {"file_name": file_name, "version": version} return file_version_data
b58314959a9d7878850054a0475d9df9ca1711d7
660,576
def languages(): """Returns list of supported languages. This should correspond to the existing translations and needs to be updated when new translation is added. Returns ------- languages : `list` [ `str` ] """ return ['en', 'ru', 'pl', 'cz']
f3fefe77ca85910588f916dd443ee0ee76444b10
660,577
def compile(self): """Compile TokenNode.""" return "%s" % self.tok
09f6878ef1d8b41e8a811853a795884364e20626
660,581
def unofficer(bot, input): """Remove Officer Alt""" if not input.admin: return False if not input.group(2): return nick = input.group(2).lower() if nick in bot.config.officers: bot.config.set_del('officers', nick) bot.reply("Removed {0} from officer list".format(nick)...
19f8afcab3fae83600176d159b2bb7e2f8575c32
660,582
def convert_to_ast(state, data_e, size_e=None): """ Make an AST out of concrete @data_e """ if type(data_e) is str: # Convert the string into a BVV, *regardless of endness* bits = len(data_e) * 8 data_e = state.se.BVV(data_e, bits) elif type(data_e) in (int, int): dat...
20cf0921dd9ca279429bb9b6b58e1c98e576230b
660,584
def and_(*preds): """Check if all of the passed predicates are true. >>> from legendlore.test import aobj >>> numand = and_(contains(1), contains(2), contains(3)) >>> numand('a', aobj([1, 2, 3])) True >>> numand('a', aobj([4, 5, 6])) False >>> numand('a', aobj([1, 5, 6])) False ...
1f8bd4f5e52d9555187c68cbae7bf54644c57a33
660,585
def missing_label(set1, set2): """ Subtraction between two sets""" missing_list = list(set(set1) - set(set2)) return missing_list
764fa5c8994b8c5cf67f720d0e4f7a195ab8aedc
660,586
def to_sorted_subfloats(float_string): """Convert string of floats into sorted list of floats. This function will first remove the "TSH" and turn the string of floats into the list of floats and sort them from smaller to larger. Args: float_string (str): A string begin with "TSH" and followed ...
7764b648449c4ca79a8fe9aecd8a1b3b73acee1c
660,587
def data_formatting(merged_df): """ This function formats the merged dataframe so that it can be used to frame the given time series data as a supervised learning dataset. Args: merged_df(dataframe): The merged dataframe which can be obtained by using the function 'cx2_file_reader' ...
63a50a1facd86b00e1afb1dcbb2da9def370725b
660,588
import os def load_germline_muts(indir): """ Load germline mutations for all subjects in a directory into a dictionary G{subject}{allele} = [mut, ...]""" G = {} for f in os.listdir(indir): if f.startswith("germline_muts_V6_Full_subject") and f.endswith(".txt"): p...
dafa65845420e5224125a400f943d3c7ea1b74a5
660,589
def get_hash(example): """Get hash of content field.""" return {"hash": hash(example["content"])}
79e404ad99d87dd1151f4bd88ffba112ade82f4f
660,590
def f2odds(f): """Convert fraction B117 to odds ratio B117/other.""" return f/(1-f)
2dcf0b3516691b7c353ab80fedb19689c17791fb
660,591
def scale_between(minval, maxval, numStops): """ Scale a min and max value to equal interval domain with numStops discrete values """ scale = [] if numStops < 2: return [minval, maxval] elif maxval < minval: raise ValueError() else: domain = maxval - minval ...
4e21d0ed391776ad5ba85dad189b0ae46dfbf0ec
660,592
def inet_ntoa(packed_ip: bytes) -> str: """字节数组转换为ip地址""" ip = '' for i in packed_ip: if len(ip) == 0: ip += str(i) else: ip += '.' + str(i) return ip
de7c897ca88417442203e5bcc1937a7b66ae535e
660,593
import os def _convert_forward_slash(path): """Convert forward slashes with backslashes This function replaces forward slashes with backslashes. This is necessary using Microsoft Windows for location of files in the option files. Returns a string """ if os.name == 'nt': nmpath = ...
498d3657851c7dfa84a3e7d4f0f257dd6188f561
660,594
def progress_bar_width(p): """Compute progress bar width.""" p = int(p) return 15.0 + p * 0.85
1ea83fdc3d87a4b52920d1b94f3c2e08dc063b9e
660,595
from typing import Optional import logging def get_module_logger(module_name: str, format_str: Optional[str] = None): """Get a module logger from builtin logging library. To use this, do "logger = get_module_logger(__name__)" """ logger = logging.getLogger(module_name) handler = logging.StreamHandler(...
6e541282799ea2025ae06f2fe68a13dc014a7cdc
660,596
def var_ex_model(ng, nf, params): """ Variance Excess Model Measured pixel variance shows a slight excess above the measured values. The input `params` describes this excess variance. This funciton can be used to fit the excess variance for a variety of different readout patterns. """ return 1...
db71b1a987a5c2fe660ba349072d221716ce58b8
660,597
import os def pass_env(*args): """ By-pass non-empty ENV variables with their values for the input list. :param args: List of ENV variables to include :type args: ``list`` :return: ENV variables with values to bypass :rtype: ``dict`` """ return {k: v for k,v in os.environ.items() if k...
ab374dbbd5f2ec3e960e4eabd2430554fc0283c6
660,599
def binomial_coefficient(n: int, k: int) -> int: """ Since Here we Find the Binomial Coefficient: https://en.wikipedia.org/wiki/Binomial_coefficient C(n,k) = n! / k!(n-k)! :param n: 2 times of Number of nodes :param k: Number of nodes :return: Integer Value >>> binomial_coefficient(4, ...
6925e0cdeec9e982d3349576b043994bd7794fbf
660,600
import os def temporary_dir(): """ Returns path to temporary dir from CARS_TEST_TEMPORARY_DIR environment variable. Defaults to /tmp """ if "CARS_TEST_TEMPORARY_DIR" not in os.environ: # return default tmp dir return "/tmp" # return env defined tmp dir return os.environ["CA...
24194456a88f14b74dcb11f3f63e1f4aaf88d785
660,601
import uuid def generate_group_id(): """Generate a random UUID hex string to group launched instances.""" return uuid.uuid4().hex
5f009395ec860431642b683fb27343729d9f2564
660,602
def _files(*paths): """Files for PyDoIt (It doesn't allow pathlib2, only str or pathlib).""" return [str(x) for x in paths]
48ce9ce052283024ac800ea5f1199fa0ca77aded
660,603
def read_article(article_location): """ Read article's filtered context. :param article_location: The article's file location. :type article_location: str :return: The context of file. :rtype: str """ article_text = '' with open(article_location, 'r', encoding='utf-8') as file: ...
788bd30ff778cdc2bd93372d0b073fb95e1797d4
660,604
import time def long_calculation(sleep_time: int) -> int: """ Will be executed in another process. Simulates a long calculation, and returns the 'result'. """ time.sleep(sleep_time) return sleep_time
d1897f45ca58bbfb6bcd05e73ddef0acc6dd0600
660,605
def parse_history(raw_history): """ Parse smoldyn output from `molcount` command. Returns ------- {Species: timeseries} """ keys = raw_history[0].split() history = {key: [] for key in keys} for line in raw_history[1:]: for k, v in zip(keys, line.split()): history[k]...
593f0ce9bcb4cbfc6ef0d9f984e6eaae393cfb28
660,606
import textwrap def _parse_definitions() -> str: """ Generate the code that defines the general parsing structures. :return: generated code """ return textwrap.dedent( '''\ /** * represents an error occurred while parsing. */ struct Error { //...
b4848762bfb9ed0bfd385909d4c551c9f2625d8a
660,607
def ndim(x): """Returns the number of exes in a tensor, as an integer.""" dims = x.get_shape()._dims if dims is not None: return len(dims) return None
a654a17081663d091acd761e61c3bccc06b801cf
660,608
def cfun(xdf, ydf): """ :param ydf: DataFrame, model states :param ydf: DataFrame, model outputs :return: float """ Q = (ydf['qr']**2).sum() return Q
74626e67ebc6d3d9b9fc2fda5ccaeb57e3716cac
660,609
def _slice(index, i, nneighbors, lim): """ A partir de l'indice `index`, renvoie les `nneighbors` indices suivants dans la dimension `i` (y compris `index`, qui est le premier élément de la liste). Si certains des indices calculés sont supérieurs à `lim` dans la dimension `i`, renvoie une liste...
afb34b36d1c5217ee2be89e5ef738b62099f1ea6
660,610
def get_classifier_name(clf, name="None"): """ Get classifier name recursivley (for nested classifiers) """ name = clf.__class__.__name__ if name == "None" else name if hasattr(clf, "classifier"): clf_name = clf.classifier.__class__.__name__ name = "_".join([name, clf_name]) return g...
810d9eac6698002e27823fbd7ede21dccc1c13c0
660,611
import re def canonicalize(a): """ >>> canonicalize("460 W San Ysidro Blvd, San Ysidro, CA 92173, United States") '460 west san ysidro boulevard, san ysidro, ca 92173' >>> canonicalize("1208 WEST REDONDO BEACH BOULEVARD, GARDENA, CA 90247") '1208 west redondo beach boulevard, gardena, ca 90247' ...
b72183f141eae13bbf1fc68df2f6aa849bba618a
660,612
def pivotFlip(string, pivot): """Reverses a string past a pivot index.""" flip = list(string[pivot:]) flip.reverse() return string[:pivot]+''.join(flip)
1e00ea9526e6484e7072763cb7b1b55708261426
660,613
def det(x): """ Return the determinant of ``x``. EXAMPLES:: sage: M = MatrixSpace(QQ,3,3) sage: A = M([1,2,3,4,5,6,7,8,9]) sage: det(A) 0 """ return x.det()
8e74bb3c1f8c99ea25b4868690813b11ac47087f
660,614
import requests def get_yahoo_page(query,index): """ Fetch the yahoo search results Returns : Results Page """ header = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36'} payload = {'p': query,'b' : in...
c87b4d9e061211be30392c7295183b749ad3fc3a
660,615
def is_match(word, cword, mapping): """Check if a word could be a match under current mapping""" if len(word) != len(cword): return False # make a copy mapping to work with mapping = {c : a.copy() for c, a in mapping.items()} for pc, cc in zip(word, cword): # if the ciphertext ch...
0edfdebf0b5f89d55bf3fbf295c709aebf820c66
660,616
def format_float(float_number, precision=2): """ :param float_number: :param precision: :return: """ return str(round(float_number, precision)).replace(".", "")
8103dd123e8525f2a6bd8a3c67b217901fe83309
660,617
import logging import sys def convert_n_reads(unit): """For strings representing a number of bases and ending with k, K, m, M, g, and G converts to a plain old number Args: n (str): a string representing a number ending with a suffix Returns: float: a number of reads """ logge...
fcf29d8eaf73dda666aeedf9272466255b7a25e6
660,619
def fields_sort_key_factory(fields, field_order): """Return a function to sort `fields` by the `field_order`.""" raw_field_order = [x[0] for x in fields] def key(key): name, field = key try: return field_order.index(name) except ValueError: return 100000 + ra...
5aae7150aa34d1fe9aafe943ef62b054a3bcf83d
660,620
def cropImage(img, margin): """根据边界裁剪图片""" u, r, d, l = margin # img[0:u, :] = 0 # img[d:-1, :] = 0 # img[:, 0:l] = 0 # img[:, r:-1] = 0 return img[u:d, l:r]
d9824b6d5e19f0664336477f29316aceefef62c1
660,621
import itertools def unique_dashes(n): """Build an arbitrarily long list of unique dash styles for lines. Parameters ---------- n : int Number of unique dash specs to generate. Returns ------- dashes : list of strings or tuples Valid arguments for the ``dashes`` parameter...
dfa88e1aa3b7c34cacdab3455947e59760e69891
660,622
def escape(pattern: str, special_chars: bytes = b"\\;,\":") -> str: """Escape special characters in a string. This is an adaptation from Python's own re library. See more at: https://github.com/python/cpython/blob/3.10/Lib/re.py#L269-L277 """ return pattern.translate({c: "\\" + chr(c) for c in ...
56a5cd5a402e841625f197e6d58baf822fca3e34
660,623
import importlib def get_agent(agent, environment, **kwargs): """Get default agent.""" agent_module = importlib.import_module("rhucrl.agent") agent = getattr(agent_module, f"{agent}Agent").default(environment, **kwargs) return agent
42d1bdefa448df6f9cfd25c634c64d6d0c704570
660,624
import uuid def generate_id() -> str: """ Generate an uuid to be used as id """ return str(uuid.uuid4())
51fdc5edc567457e6f7fce9acf39619f0ab45da1
660,625