content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _make_ngrams(l, n): """Auxiliar ngrams generation func. """ rez = [l[i:(-n + i + 1)] for i in range(n - 1)] rez.append(l[n - 1:]) return zip(*rez)
622199b177675faf8d448368d15a08505daa18b6
650,169
def inch_to_dxa(value): """1 inch = 72 * 20 dxa""" return int(value * 20 * 72)
ca89f52c12ddb31926b0e981884c63eaa2249703
650,170
import argparse def __parse_args__(): """Parse CLI arguments. """ parser = argparse.ArgumentParser(description='Create web server, pull persistence payloads, and run them.') parser.add_argument('-l', '--lhost', help='Local IP Address', required=True) parser.add_argument('-r', '--rhost', help='Remo...
7beb4fc21fb9dbd323e09e04e39d49192a8037ce
650,171
from unittest.mock import patch def patch_get_branch_info(): """ Sets a static response to get_branch_info method. """ def decorator(old_function): patcher = patch("insights.client.client.get_branch_info") return patcher(old_function) return decorator
0c7283707544b3f601df50cd7507d6461de5122d
650,172
def build_insert(table: str, to_insert: list): """ Build an insert request. Parameters ---------- table : str Table where query will be directed. to_insert: iterable The list of columns where the values will be inserted. Returns ------- str Built query strin...
ab9c0e9b0868429a684825fab9ca53820b19f63f
650,173
def clean_nodata(series, nodata=None): """ Given a series remove the values that match the specified nodata value and convert it to an int or float if possible Parameters ---------- series : pandas series nodata : string, int, or float Nodata placeholder Returns ------- pandas ...
848d6a1d2dd77a0af6ba69217f93566c8164af83
650,174
import os def get_include(): """ Return the directory that contains the RapidFuzz \\*.h header files. Extension modules that need to compile against RapidFuzz should use this function to locate the appropriate include directory. Notes ----- When using ``distutils``, for example in ``setup...
dbf773a876275f4aac54995853639fc0e04efb92
650,175
import csv def get_file(file_path): """ reads a csv file and returns a file file_id """ f = open(file_path, 'r') #open with read bike_reader = csv.reader(f) return bike_reader
1d13815208d1651ebb69ef381d8c3aca9adbea74
650,176
import argparse def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Compare different motion planners') parser.add_argument('-m', '--mail', help='Send an email when training finishes', action='store_true') args = parser.parse_args() return arg...
c656877f389a60e6b8c6056632bae2f4b2f948bf
650,177
def field_values_valid(field_values): """ Loop over a list of values and make sure they aren't empty. If all values are legit, return True, otherwise False. :param field_values: A list of field values to validate. :returns: False if any field values are None or "", True otherwise. """ for ...
44a1bd799bc3f36cc8695b8691640a140d3b29a8
650,178
def normalize_name(s): """Normalizes the name of a file. Used to avoid characters errors and/or to get the name of the dataset from a config filename. Args: s (str): The name of the file. Returns: new_s (str): The normalized name. """ if s is None: return '' s = s....
a0921b12ea2d6c855e5443ab81df33ba83d587c8
650,179
import torch def partial_hazard(model_class, x): """ Computes partial hazards :param model_class: a pytorch defined model """ assert hasattr(model_class, 'partial_hazard'), 'Your model does not have risk function' risk = model_class.risk(x) return -torch.exp(risk)
b46931b322fbd67ad8726d9af6c034ede865d721
650,180
from datetime import datetime def fromtimestamp(timestamp): """ Return datetime object from provided timestamp. If timestamp argument is falsy, datetime object placed in January 1970 will be retuned. """ if not timestamp: return datetime.utcfromtimestamp(0) return datetime.fromtimestam...
cfac5db5eeb11a71b4ca2109c682da8c5c2267f6
650,181
import os def get_trial_path(path): """Get the path for the directory to save the trial results in. Arguments: path: parent directory in which to save trial results. Returns: path for the trial results. """ # Create the results directory if it doesn't already exist if not os.p...
74ff3acd399b01316dd1ebee3021966088a38945
650,182
def readonly(f): """ Marks a class member as protected, allowing metaProtected to prevent re-assignation on the classes it generates """ f.__readonly__ = None return f
260d8e50df607a8515de3e883eb65f946dcd84b0
650,183
def root(): """Get and return root text response from API Parameters ---------- None Returns ------- None """ return 'Welcome ! The endpoint for images is at <b>/passport</b>, <b>/image</b> or <b>/barcode</b> the key is imagefile , The EndPoint of pdfs is <...
6a2519d95044e23fb749fe3fe68f37b0b6bf2a06
650,184
def encode_string_for_graph_label(val): """Encodes reserved graphviz characters""" return val.replace('{', '&#123;').replace('|', '&#124;').replace('}', '&#125;').replace('<', '&#60;').replace('>', '&#62;')
b889c0b617ecbc1e8ce5667155062381df0ecf53
650,185
def loadCalls(table, chrom, st, end): """Load jc4 data. Don't use chr """ header = ('pos', 'ref', 'calls', 'depth', 'altFrac', 'zygosity') resLs = [ '\t'.join([str(x['pos']), x['ref'].decode('UTF-8'), x['calls'].decode('UTF-8'), ...
dc26c142de7980b8c8e285708f47001502cc537c
650,186
import numpy as nptypes def _scalar_to_numpy(data, dtype): """ From scalar value to numpy type. """ dtype = getattr(nptypes, dtype) return dtype(data)
bf594b1cfcde0e2d13423bc8e0b88daa93dcf29a
650,187
def get_x_y_values(tg, num_words=50): """ Gets a list of most frequently occurring words, with the specific number of occurrences :param tg: (TermGenerator) Object with the parsed sentences. :param num_words: (int) Number of words to be processed for the top occurring terms. :return: (List) List of ...
9584851d7261f4c5d8d279fa721fbe281e40e5b6
650,188
import argparse def get_input_args(): """ Retrieves and parses the 3 command line arguments provided by the user when they run the program from a terminal window. This function uses Python's argparse module to created and defined these 3 command line arguments. If the user fails to provide some ...
3eeaede1bff9a61e625708f0696c655cd8281187
650,189
import select def wait(fd, timeout=2): """ Wait until data is ready for reading on `fd`. """ return select.select([fd], [], [], timeout)[0]
dfe41ab278db4c793f6436d6349754e648187230
650,190
import argparse def parse_args(): """ Parse command line arguments. Parameters: None Returns: parser arguments """ parser = argparse.ArgumentParser(description='LeNet model') optional = parser._action_groups.pop() required = parser.add_argument_group('required arguments') optional.add_argument('--print_...
36129e858c5c8d9d63300aa63371c67754ed4a60
650,191
def coordinate_bbox(coord, projection): """ """ ul = projection.coordinateLocation(coord) ur = projection.coordinateLocation(coord.right()) ll = projection.coordinateLocation(coord.down()) lr = projection.coordinateLocation(coord.down().right()) n = max(ul.lat, ur.lat, ll.lat, lr.lat) ...
b2126e3ae913c6fcbc6f4cf254bf4d6f4e75dc24
650,192
import re def remove_newlines(html_str: str): """ remove newlines """ html_str = re.sub(r'\n', '', html_str) return html_str
399a4065f57b218b67335bd0aa21942b1577e15f
650,193
def is_pos_conditional(enclosed: str) -> bool: """ True if {{$enclosed}} corresponds to the beginning of an 'if empty' statement on the Anki card template. """ return enclosed.startswith("#")
bd92e8626fc49a3f645d94be53184d335c928601
650,194
def presion_media_vapor(presion_tmax, presion_tmin): """ calcula la presion media del vapor en saturación kPa param: presion_tmax : presión del vapor en saturación a la tmax param: presion_tmin : presión del vapor en saturación a la tmin """ return (presion_tmax+presion_tmin)/2
8b859e825ad1d8ae1b6ca8c369b1cbfcf5352176
650,195
def parse_module(module, keyword): """ Returns a list of keywords for a single module :param module: list of strings :param keyword: Module keyword you are looking for :return: list of lines with the specified keyword """ keys = [] for line in module: keyw = line.split(" ")[0] ...
0ac00fb05983ad1306f09565a8f19aeb2f980696
650,196
from typing import Sequence def histogram(data: dict[int, float], bins: Sequence[float]) -> list[float]: """... An example. :: obs = ... # Observed values. exp = ... # Expected values. bins = np.linspace(min(obs), max(obs)) bins = np.logspace(log(min(obs), 10), log(max(...
412a5b8506cb9a5ebd46a7ad8b5c8934e3f68ac2
650,197
import typing import re def explode_line(raw: str) -> typing.List[str]: """ :param raw: :return: """ raw = re.sub('\s+', ' ', raw.strip()) out = [''] breaker = ' ' for index in range(len(raw)): c = raw[index] out[-1] += c if c == breaker: out[-1]...
dcc83bd5c1957aa775cb29b7beaee258d8f880ea
650,198
import struct def simple_urandom(length): """See https://xkcd.com/221/""" return struct.pack("!%ds" % length, b"")
5d048404b701ca2592764f2966474c45034a4cb9
650,199
from typing import Union from typing import Sequence from typing import Iterable def check_parity( bitstring: Union[str, Sequence[int]], marked_qubits: Iterable[int] ) -> bool: """Determine if the marked qubits have even parity for the given bitstring. Args: bitstring: The bitstring, either as a ...
f81b2e45611d987d14f50144068d7d596da7ca06
650,200
def get_node_with_value(node, value): """ Traverses tree starting at node, depth first Note the tree may be a subtree of a larger tree. The method may be called recursively. :return first node found with value. return None if node is None or if not found """ # if node is None: # ...
986bcbd91a01accfb1503e9f4e0ac8b02ff2e1e4
650,201
def determine_endpoint_type(features): """ Determines the type of an endpoint :param features: pandas.DataFrame A dataset in a panda's data frame :returns string string with a name of a dataset """ counter={k.name: v for k, v in features.columns.to_series().groupby(features.dtype...
a368a523e669287f45f4cb730620148d968b6b70
650,202
def fnv1a(data): """Fowler–Noll–Vo hash function; FNV-1a hash.""" hash_ = 2166136261 data = bytearray(data) for c in data: hash_ = ((hash_ ^ c) * 16777619) & 0xffffffff return hash_
4b4c39100430471bb55076d5bc2d721fd74f9f95
650,204
import ipaddress def _GetIpv4CidrMaskSize(ipv4_cidr_block): """Returns the size of IPV4 CIDR block mask in bits. Args: ipv4_cidr_block: str, the IPV4 CIDR block string to check. Returns: int, the size of the block mask if ipv4_cidr_block is a valid CIDR block string, otherwise None. """ networ...
99c4d575314a30863ca3a104ba0334d9886602b6
650,205
def get_preds(best_matches, query_gt_dict): """ See gets_preds_and_visualize(**args). It is the same function without any plots """ # Create python list to store preds preds = [] # Iterate through the best matches and find predictions for i, pic in enumerate(best_matches): ...
4edb832686f2d609e78673ecac146c9d25c395ec
650,206
import functools def memoize_full(func): """ >>> @memoize_full ... def f(*args, **kwargs): ... ans = len(args) + len(kwargs) ... print(args, kwargs, '->', ans) ... return ans >>> f(3) (3,) {} -> 1 1 >>> f(3) 1 >>> f(*[3]) 1 >>> f(a=1, b=2) () {'a...
a0dd196b701c2d6e18346f4db635b4086c37ac20
650,208
import re def rename_columns(name): """ converts the other cases of string to snake_case, and further processing of column names. 将字符串的其他情况转换为snake_case,并进一步处理列名。 """ name = name.split('.', 2)[-1].replace('.', '_') name = re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower() name = name.replace('c...
09b3a2e1c51ce33e6d5056c01b0e80e1da0b40ba
650,209
def SelectNormal(normal, poolnormal): """Select the best possible normal. :param str normal: str of match normal :param str poolnormal: str of pool normal :return: str with decision whether to run matched or unmatched :rtype: str """ filesToProcess = [normal, poolnormal] fcount = 0 ...
6b58f21cad501e2babf6a9fd3fd1cad95a825ebe
650,211
def find_period(i, zmat,hin, ijk): """ Rough way of determining internal symmetry number (Hydrogen counting) """ period = 0 if ijk and i == 0: hinatom = zmat[int(ijk[0])-1][0] for row in zmat: if len(row) > 6: if row[6] == hin: if row...
65e59fe71f160de3bbdc8f88c7934e2add519549
650,212
def max_sum_from_start(array): """ This function finds the maximum contiguous sum of array from 0 index Parameters : array (list[int]) : given array Returns : max_sum (int) : maximum contiguous sum of array from 0 index """ array_sum = 0 max_sum = float("-inf") for num in ar...
320632d92903ba745339a357cc0792469093fd95
650,213
def define_test_data(): """Read in the example data from the puzzle description Returns ------- test_data0: tuple A tuple of two strings containing the wire instructions for the worked example test_data1_list : list A list containing pairs of x, y coordinates that define a p...
0cf47a93a7f9ae0bd89eb5aba9a6f06b097ba62a
650,214
import typing import pathlib def parse_requirements_file (filename: str) -> typing.List: """read and parse a Python `requirements.txt` file, returning as a list of str""" with pathlib.Path(filename).open() as f: # pylint: disable=C0103 return [ l.strip().replace(" ", "") for l in f.readlines() ]
f5a3574b49d492d5671ceb0946df771673070d74
650,215
import textwrap import pprint def make_separator_str(text, header=None, width=100, char_v='#', char_h='=', char_corners=None): """ function wraps text between two lines or inside a box with lines on either side. FROM: my obstacle_tower project """ if char_corners is None: char_corners = ch...
8a7e7b7b767b4f0867faaa12bb69e3e830ac2e59
650,216
def get_file_type(file_name): """ Determine file type by extracting suffix of file_name """ if file_name is None: return None file_type = file_name.split(".")[-1].strip() if file_type == "nc": file_type = "netcdf" if file_type == "prmtop": file_type = "parm7" if ...
31013f549e8366bdc30822cf7678651b810834d3
650,217
import time import random def tcl_salt(): """ Generate salt value for TCL server tools. """ millis = round(time.time() * 1000) tail = "{0:06d}".format(random.randint(0, 999999)) return "{0}{1}".format(str(millis), tail)
31438f12cccaa34055134051f027105d6dbfeedd
650,218
def total_days(time_diff): """ Total time in units of days """ return (time_diff.days + (time_diff.seconds + time_diff.microseconds / (1000000.0)) / (24 * 3600.0))
642709dc4d8e1ed27d357516e66feafba0858d55
650,219
import platform def get_digits(): """获取操作系统位数(字符串)""" return platform.architecture()[0]
801679c5130d06c21c2259938fc847d52219b289
650,220
def replace(template,dic): """ Write lotus.f90 file by replacing the dic on the template and return a potential folder name """ f1 = open(template,'r') f2 = open('lotus.f90','w') for text in f1: for i, j in dic.items(): text = text.replace(i, j) f2.write(text) ...
e0af54134f205571cebc34a3c6cda190d2fbb13e
650,221
def dl1_tmp_path(tmp_path_factory): """Temporary directory for global dl1 test data""" return tmp_path_factory.mktemp("dl1")
9fb49713aff0edd9135de1ac1ba0df8d36c868fe
650,222
def PrintSeconds(seconds): """Return a string representing the given time in seconds.""" orig = seconds minutes = seconds // 60 seconds %= 60 hours = minutes // 60 minutes %= 60 days = hours // 24 hours %= 24 s = "" if days > 0: s += "%dd " % days if hours > 0: s += "%02dh " % hours if ...
0c0d40f8b5bea760a67b7739ca9738e1812b792f
650,224
def reverse_dotted_decimals(ipaddress): """Reverse the order of the decimals in the specified IP-address. E.g. "192.168.10" would become "10.168.192" Keyword arguments: ipaddress -- An IP address in dotted decimal notation """ return '.'.join(ipaddress.split('.')[::-1])
0224cffd63074a5783510d122497f0141333303e
650,226
def _prod(x): """Compute the product of an iterable.""" out = 1 for a in x: out *= a return out
b8c6f2dea83e629fef0ae7e882830777d089d22e
650,227
def isCMSSWSupported(thisCMSSW, supportedCMSSW): """ _isCMSSWSupported_ Function used to validate whether the CMSSW release to be used supports a feature that is not available in all releases. :param thisCMSSW: release to be used in this job :param allowedCMSSW: first (lowest) release that start...
48a58f74738b352d92a4d419b5eae554d828f983
650,228
def isInside(point, leftTop, rightBottom): """ return True if point is in the rectangle define by leftTop and rightBottom """ if not (leftTop[0] < point[0] < rightBottom[0]): return False if not (leftTop[1] < point[1] < rightBottom[1]): return False return True
f9727e5ac11011ea45d05d5db1a439848c882481
650,229
def find_sequentially(arr, item): """ Sequential Search Complexity: O(n) """ for value, i in enumerate(arr): # Check each item in the list if item == value: #Runs N number of times return True return False
bd9ee1d1da4d29f7fca7feac04aed50d97a23302
650,230
import yaml def read_label_definitions(filename: str) -> dict: """Read yaml file with label definitions. Format of YAML file: label_files: file1: location file2: location translate: old: new from_group: old: - new1 - new2 """ wit...
e83825a2ade4f54daf6c6350e5091c050514da93
650,231
import os def get_test_fname(fname): """Returns test data filename""" path, name = os.path.split(__file__) full_path = os.path.join(path, "test", fname) return full_path
864d6455a95ea942db4ffecf9b1fcaf525f2cb7c
650,232
def build_refseq(d): """ Uses parsed gene2acc file to build dict mapping (entrez_gene -> refseq status). """ refseq = {} for entrez_gene, status, taxid in d.get_eq_values(): target_pool = ['9606', '10116', '10090'] valid_status = ['REVIEWED', 'VALIDATED', 'PROVISIONAL', 'PREDICTED', ...
b241427a16c4309e05003db2f6223a774e364939
650,234
import random def tournamentSelection(population,popSize): """ Function to select some 'good' parents from the population using tournament selection. This implementation selection n pairs of parents, where n = population size // 2 Parameters: population (list) - list of solutions. po...
ba2a4d21b076d81f59e23886dd671ffc4bdb1c3d
650,235
def get_tags(sync_config): """ return a list of tags with, there name, and displayName """ tags = [] for tag in sync_config['tags']: tags.append({'name': tag['name'], 'displayName': tag['displayName']}) return tags
9872ea57726d033840b585508eccd8c91c6addd8
650,236
from datetime import datetime def first_day_of_month(month): """Returns the first day of the month in terms of the hour index Arguments --------- month : int The index of the month, 'Jan' = 1; 'Dec' = 12 Returns ------- hour_index : int """ start_year = 2017 start_mon...
6c35bca746286b3b9ddfe8ead420dd8e9e8e3077
650,237
def IsOperator(value): """ Check if the passed value is 'operator' """ if value != None and value == "operator" : return True return False
429eb0232bd4c1f93fc052ec3512958a9fcaa998
650,238
import re def check_operator_regex(code, operator): """ If an error has been found, return the column number of the operator, else return 0 """ regex_one = r'' + '\S+' + operator regex_two = r'' + operator + '\S+' #check to see if there is a non-whitespace character on either side of the oper...
ad86d98af359fc53e6098f2e5606d88b68eef70a
650,239
import math def get_width(string, bold=False): """ Assuming a standard 10-point Arial font, returns the width of the string, in BIFF column width units. """ char_widths = { '0': 262.637, '1': 262.637, '2': 262.637, '3': 262.637, '4': 262.637, '5': 26...
1b24086e3e4ad4231b96663a946826d614420e3d
650,240
def meth_time_biased2( ego, potentials): """global GH global GR global GP recruits = [] weights = [[] for i in range(2)] # potentials has all legal recruits # check each network by priority # until quota is satisfied rh = list((set(GH.neighbors(ego)).intersection(set(potentials))))...
016a1e6f4e8e3a7186e8153342f7acd1eede6df0
650,241
import collections def codon_count_from_sequences(list_of_dna_sequences): """Count occuring codons in a list of sequences. Non occuring codons are not in the output list""" codon_frequency = collections.Counter() if not list_of_dna_sequences: raise ValueError("Empty sequence passed") for s...
0316fb3ac00932f04a69fbf52498f7c4adc8d813
650,242
def _build_snapshot_tree(snapshots): """ Builds a tree fro the given snapshot. Parameters ---------- snapshots : `list` of ``BaseSnapshotType`` The snapshot to build tree from. Returns ------- snapshot_tree : `dict` of (``client``, `dict` of (`type`, ``BaseSnapshotType`...
913df7dde309e95ee2908087de36946acbc1c2da
650,243
import requests def all_versions(req): """Get all versions of req from PyPI.""" url = "https://pypi.python.org/pypi/" + req + "/json" return tuple(requests.get(url).json()["releases"].keys())
c5271b9d4a4dbddf59c199b8e019287cf6705436
650,246
def get_claves_alumnos(): """retorna una lista de las claves unicas de los alumnos""" return range(1, 100)
e9caf5d5eb1211d8a10f7bfb8ae1838c67320dab
650,247
from typing import Union from typing import List import re def process_zh( text: Union[str, List[str]], remove_nonchinese: bool = False, dedup: bool = False, # remove_stopwords: bool = False, ?na ) -> List[str]: # fmt: on """Normalize chinese text and insert spaces beteen char...
5074263da8c2bb20940dcaf1fbad3ae6bdcc71a6
650,249
def generate_moku_manager_params(drop_mode, moku_size, board_size, gpu_id, num_res_layers, num_channels, ckpt_path=None, ...
78170cb684dcf4e6c66720ae1f71c0dbb5fa7e52
650,250
def pis_map(diffn_img, index_low_b_val, index_high_b_val): """ Produces the physically implausible signal (PIS) map [1]. Parameters ---------- diffn_img index_low_b_val : int index into the DWI identifying the image with lower b-value. Usually 0 referring to the b=0 (non-DW) im...
b799bac8f7e6925db9592325519425fa7f3a3831
650,251
import json def read_shapefile_data(path,file_name, version): """ Reads in a json file containing the path to shapefiles, on regional, province and municipality level and crs foe encoding """ d = json.load(open(path+file_name)) path_shapefiles = d['path_shapefiles'] version=d[version...
82707f84764c4ff1792a85a19d0294127dc3e994
650,252
def count_slash_for(s): """ Returns the number of times '/' appears in string s Parameter s: the string to search Precondition: s is a (possibly empty) string """ # Accumulator count = 0 # Loop variable for i in range(len(s)): if s[i] == '/': count= coun...
9d0ef4f018eaa467daa00ad5dca077d806ba6e50
650,253
def get_labels(label_filename): """ Get the label of a given set The labels are read from a text file, and a dictionary is built. The key is the file stem and the value is the label (either 0 for an attack or 1 for banafide access). Parameters ---------- label_filename: str The path to the fi...
6aedacfd8edc7c720ffb62ca4f826531c691a932
650,254
def _CreateRetrievalSolution(): """Creates retrieval solution to be used in tests. Returns: solution: Dict mapping test image ID to list of ground-truth image IDs. """ return { '0123456789abcdef': ['fedcba9876543210', 'fedcba9876543220'], '0223456789abcdef': ['fedcba9876543210'], '0323456...
0a7993d74cc1b6350d327b93bd24d633065175ee
650,255
def composition_to_oxidcomposition(series, **kwargs): """ Adds oxidation states to a Composition using pymatgen's guessing routines Args: series: a pd.Series with Composition object components **kwargs: parameters to control Composition.oxi_state_guesses() Returns: a pd.Series ...
328cb00837e8c341792d13f088f0ceb714e869e2
650,256
def decrypt(data: bytes, key: bytes) -> bytes: """ Simple XOR decrypt for SquirrelWaffle :param data: Encrypted data :param key: Decryption Key :return: Decrypted data """ dec = b'' for i, b in enumerate(data): dec += chr(b ^ key[i % len(key)]).encode() return dec
32d0f9a832773a25bc24df32e7846566e38bae34
650,257
def update_available(data, recent_pick): """ Reduce available pokemon set by most recent pick. Parameter --------- data: DataFrame with available Pokemons recent_pick: Picked Pokemon name """ df = data.copy() return df.loc[df["Name_1"] != recent_pick]
96015add1b2689c933d9d32372de1bdde0ce4233
650,258
def real_part(z): """ Parameters ---------- z : complex or ndarray Notes ----- numpy ``.real`` works with complex numbers and ``ndarray``. """ return z.real
adf3b816b68a27792fac037af96e67d31e4d099b
650,260
import re def filter_example(result, features_regex): """Filters the dstat data by features_regex""" # Apply the dstat feature filter dstat_data = result['dstat'] col_regex = re.compile(features_regex) result['dstat'] = dstat_data[list(filter( col_regex.search, dstat_data.columns))] re...
53cb26d184f37d7ef29be9894052018cbc80571f
650,261
def _slider_verify(session, request_code, verify_data): """ 滑块风控验证 :param session :param request_code: :param verify_data :return: """ url = 'https://verify.meituan.com/v2/ext_api/merchantlogin/verify?id=71' session.headers.update({ 'Authorization': 'Bearer ' + request_code...
5908f4b9410bc008ca100524a007bac851aa28b7
650,262
def _create_style(parameter_list): """Formats and translated the provided parameters to an ANSI escape sequence""" return "\033[%sm" % ";".join(parameter_list)
ffd0e9960835a911805b8528082d26409c6cbd36
650,265
def filter_pheno_nan(x_species, y_pheno, pheno_name, verbose=False): """Filter X and Y to have same index and drop NANs """ y = y_pheno[pheno_name] y.dropna(axis=0, how='all', inplace=True) X = x_species X = X.reindex(y.index) return X, y
64d7f787d88d405821842d04dabc9b6003b9bcfd
650,266
def time_from_utc(utc_offset, time): """ (number, float) -> float Return UTC time in time zone utc_offset. >>> time_from_utc(+0, 12.0) 12.0 >>> time_from_utc(+1, 12.0) 13.0 >>> time_from_utc(-1, 12.0) 11.0 >>> time_from_utc(+6, 6.0) 12.0 >>> time_from_utc(-7, 6.0) 23.0 ...
9c8f05d09c6a9418d07178cabc24ba5c87ddd00b
650,267
def replace_u_to_t(seq): """Replaces the U's in a sequence with T's. Args: seq (str): A nucleotide sequence. Returns: str: The sequence with the U's replaced by T's. Examples: >>> replace_u_to_t("ACGU") 'ACGT' >>> replace_u_to_t(None) """ ...
a8210167b8b97ebbd7482d9d4382dbd4e052549d
650,268
def update_globs(new_path, globs): """ Depending if the repo is local or we downloaded it we need to update the globs to match the final version of the repo to use :param new_path: new_path to update the globs with :param globs: list of globs to update """ new_globs = [] for item in glob...
fd7d4bc84279435472556617c463b0143269251f
650,269
def get_max_release_version(version_id): """ Returns current release version of 3ds Max :param version_id: int, release ID of the current Max version :return: 3ds Max release version :rtype: long .. code-block:: python import MaxPlus from dccutils.max import app versi...
9f672b543c1642d30364240362cbfae7b3e42170
650,270
def extract(line): """Return a tuple (uin, nick) from 'O11111111 nickname'""" line = line.replace("\n", "") uin = line[1:line.find("\t")] # fix uin uin2 = "" for c in uin: if c.isdigit(): uin2 += c uin = uin2 nick = line[1+line.find("\t"):] nick = nick.replace("/", "_") nick = nick.replace(":", "_...
7a899d0a087a262fe153a72ae17f8042c49f21b6
650,271
def filetostr(filename): """ filetostr """ try: with open(filename, "r") as stream: return stream.read() except: return None
070b99f71269b63368ba12b24fb02d2f6d3ebbe8
650,272
import re def _split(string): """ Splits string at numbers, /s, and brackets. :param str string: A representation of the units as a string :returns: The string split at numbers, /s, and brackets. :rtype: list(str) """ # Split at numbers split_by_num = re.split('(\d+(?!\d+))', string) ...
d71cc9d4f33d78f8363a4c529ec780adaa810a3a
650,273
import glob import os def find_last_checkpoint(checkpoint_dir, ptrn="*_[0-9]*.hdf5"): """ Restore the most recent checkpoint in checkpoint_dir, if available. If no checkpoint available, does nothing. """ full_glob = os.path.join(checkpoint_dir, ptrn) all_files = glob.glob(full_glob) m...
74dd8af91cecca6678a7d0f244ba6a15f536142d
650,274
def _ConvertValueNameToChartAndTraceName(value_name): """Converts a value_name into the equivalent chart-trace name pair. Buildbot represents values by the measurement name and an optional trace name, whereas telemetry represents values with a chart_name.trace_name convention, where chart_name is optional. Thi...
7ca3e1371ef01084131890db1d0defb2769c4f1e
650,275
def summy(string_of_ints): """This function takes a string of numbers with spaces and returns the sum of the numbers.""" numbers = string_of_ints.split() answer = 0 for i in numbers: answer = answer + int(i) return answer
e04fae85798b899f511d797da77aa8a02ca5f5b4
650,276
def compare_pages(page_a, page_b): """ Function used to compare and sort PageData objects :param page_a: PageData :param page_b: PageData :return: int """ test1 = page_a.section_name + '/' + page_a.yaml_data['slug'] test2 = page_b.section_name + '/' + page_b.yaml_data['slug'] if te...
b871e9b563c598ad83dde35fb3a26c0fc8a24125
650,277
from typing import List import os def _interactive_opts(workdir: str) -> List[str]: """Returns the basic arguments we want to run a docker process locally. """ return [ "-w", workdir, \ "-u", "{}:{}".format(os.getuid(), os.getgid()), \ "-v", "{}:{}".format(os.getcwd(), workdir) \ ]
e564e1af307679d2e2c9b7e010300f02d62c8c0c
650,278
def get_min(current_min, input_score): """ compare two input numbers, and return smaller one. :param current_min: int, the current min score. :param input_score: int, the score just input. :return: int, compare two numbers and return smaller one. """ if current_min != 0 and current_min < inp...
6d5ab921a179e3629af766ceab43c4197961e9a5
650,280
def create_css_rule(selectors: list, properties: dict) -> str: """ Return CSS rule properly formated. Paramters --------- selectors : list of string list of the CSS selector to apply all the properties properties : dict dictionnary of CSS properties to apply Returns ---...
50a20e643de2d39f470931782d995219c40e64e2
650,281