content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def clean(string): """ Cleans the string by making the case uniform and removing spaces. """ if string: return string.strip().lower() return ''
61ab1d486825b77108fbbdbbb2788dee1e31ad2a
674,552
def get_config(src): """ load device config """ with open(src, 'r') as handle: stream = handle.read() return stream
080645f85da131fc83dbc2fd8734bf28927dc8e4
674,553
import os def find_rit_file(outdir): """ Find a file ending in a dir, ending with 'rit.csv' :param outdir: string directory name :return: string w/ rit filename, None if not found """ rit_file = None if not os.path.exists(outdir): return None for f in os.listdir(outdir): ...
c7e654ef05c3fde899edea403983bdc425321519
674,554
def formatFloat(number, decimals=0): """ Formats value as a floating point number with decimals digits in the mantissa and returns the resulting string. """ if decimals <= 0: return "%f" % number else: return ("%." + str(decimals) + "f") % number
42b443bce700048521eec6fa7eb19782a71b2eab
674,555
def deserialize_tuple(d): """ Deserializes a JSONified tuple. Args: d (:obj:`dict`): A dictionary representation of the tuple. Returns: A tuple. """ return tuple(d['items'])
aa502d4e16e824b354b00e0055d782cd10fe6b48
674,556
def spark_worker_service(count, mem_limit, cores, image): """ :type count: int :type mem_limit: int :type cores: int :type image: str :rtype List(dict) :param count: number of workers :param mem_limit: hard memory limit for workers :param cores: number of cores this worker should us...
950714dc6bcfc8fb8c42c28444f1e90d5e4daf73
674,557
def plan_window(plan, ending_after, starting_before): """ Return list of items in the given window. """ window_tasks = [] for task in plan: if ending_after < task['end'] and task['start'] < starting_before: window_tasks.append(task) return window_tasks
876847a2fa00ebd508299bce2ded82a2073bdf84
674,558
def ExtractVarName(text): """ Read a string like 'atom:A ' or '{/atom:A B/C/../D }ABC ' and return ('','atom:A',' ') or ('{','atom:A B/C/../D ','}ABC') These are 3-tuples containing the portion of the text containing only the variable's name (assumed to be within the text), .....
170d8827c2d4f9d828294f574d74f6b4b9506784
674,559
def helper(A, k, left, right): """binary search of k in A[left:right], return True if found, False otherwise""" print(f'so far ==> left={left}, right={right}, k={k}, A={A}') #1- base case if left > right: # if empty list there is nothing to search return False #2- solve the subprob...
3df455e6bf232b7f427c2e0763de1e848e7245e5
674,560
def override(left, right, key, default): """Returns right[key] if exists, else left[key].""" return right.get(key, left.get(key, default))
f6f5da1840aa4fa70fe0db400be9bebd2f21e383
674,561
def price_multiplier_by_exchange(exchange: int): """ Return a price multiplier function """ if exchange in [1, 2, 4, 6, 7]: return lambda x: x / 100 else: return lambda x: x / 10000000
8b1b82fac3b6e184f5c39033abc122e9777b36eb
674,562
def delete_fit_attrs(est): """ Removes any fit attribute from an estimator. """ fit_keys = [k for k in est.__dict__.keys() if k.endswith('_')] for k in fit_keys: del est.__dict__[k] return est
a84c919868ff353ac91f3f7714492e1e17db2af9
674,563
def retrieve_arguments(args): """ Further parses arguments from CLI based on type and constructs concise object containing the parameters that will dictate behavior downstream :param args - arguments retrieved from call to parser.parse_args as part of argparse library :returns dictionary containing all...
11f5a7bac5d1780f7cc091f0d38b28ff2d1afbab
674,564
def set_voltage(channel: int, value: float): """ Sets voltage on channel to the value. """ return f"VSET{channel}:{value}"
b7c28f2253a5e5d63e806cc82d597aaba0690fb8
674,565
def linear_range_model(t_flow, r_flow, w=1., n=0.): """ Eq 5 in Franz & Krapp :param t_flow: translatory flow (wrt preferred direction) :type t_flow: np.ndarray :param r_flow: image motion flow :type r_flow: np.ndarray :param w: weight :type w: float :param n: noise :type n: floa...
4877c8f91e0d71e6141b11a7a3b988c1a6288515
674,566
import logging import subprocess def assume_saml_role(role_to_assume: str) -> bool: """ Use the saml2aws utility to assume a specific SAML role in the AWS environment """ logging.info(f"Assuming the SAML Role {role_to_assume}.") exec_command: str = f"saml2aws login --role={role_to_assume} --force ...
344d9fe8afe1cb2be3dcde0bc030bc7cb2ae5eab
674,568
def dedup_and_title_case_names(names): """Should return a list of names, each name appears only once""" return [name.title() for name in set(names)]
529e4fd64b8f24b5c41d440b546aea5d418166a4
674,570
def normalize_command_name(command_name): """ Normalises the given command name. Parameters ---------- command_name : `str` The command name to normalize. """ return command_name.lower().replace('_', '-')
1fd311b62edf91bca2e198bdf19b58bac2f8e776
674,571
def approx_goaldiff(line, ahc_home_odds): """ Approximates goal difference suggested by bookmaker's line and odds """ diff = (ahc_home_odds - 1.93) / 1.25 return round(line + diff, 2)
ed2d5abcf68634a3faed370a5f2193df0633d737
674,573
def split_name(name): """ Split a name in two pieces: first_name, last_name. """ parts = name.split(' ') if len(parts) == 4 and parts[2].lower() not in ('de', 'van'): first_name = ' '.join(parts[:2]) last_name = ' '.join(parts[2:]) else: first_name = parts[0] last...
c96acf0137975cb1c0dc5b5093a3769d546c67b6
674,574
import math def Eggholder(x): """ domain: -512 <= x1, x2 <= 512 optimum: x1 = 512, x2 =404.2319, f(x1, x2) = -959.6407 """ for t in x: if t <= -512 or t >= 512: return 10000000 return -(x[1] + 47) * math.sin(math.sqrt(abs(x[1] + 0.5 * x[0] + 47))) - x[0] * math.sin(math.sq...
039b5c7930aab041bc7ab6ebb58fb5d25c5bd6fc
674,575
def radix_sort_decimal_integers(arr): """Radix sort implementation for integers d = len(str(max_value)) k = 10 as decimals (base 10)""" max_value = max(arr) # use to know number of digits digits = len(str(max_value)) # fo...
8e5b20777317111d641e85f73c6584fdcb04370c
674,576
def jaccard_distance(text1, text2): """ Measure the jaccard distance of two different text. ARGS: text1,2: list of tokens RETURN: score(float): distance between two text """ intersection = set(text1).intersection(set(text2)) union = set(text1).union(set(text2)) return 1 -...
1a3095f086c648dfe8b334830a5d963e247cb92e
674,577
import re def parse_metadata(metadata): """Turn the |metadata| file into a dict.""" ret = {} re_field = re.compile(r'^(name|version): "(.*)"') with open(metadata, 'r') as f: for line in f: line = line.strip() m = re_field.match(line) if m: ...
12c8e8efca01d8f4936d550f6ea2b2f9705c8916
674,578
from typing import OrderedDict def format_item(item): """Present any item in more human parseable format""" i = OrderedDict() i['id'] = item.id i['name'] = item.name redacted = ['token', 'end_point', 'mock_data', 'mock_status', 'mocked'] details = item.__dict__.copy() for ...
00fc3e186faead48895419cceb54f45b80ce0253
674,579
import numpy def _get_skeleton_line_endpoint_length( row_indices, column_indices, x_grid_spacing_metres, y_grid_spacing_metres): """Returns end-to-end length of skeleton line. :param row_indices: See doc for `_get_skeleton_line_quality`. :param column_indices: Same. :param x_grid_spac...
aa01666d24694ae06be6aa60f2b662b0af092604
674,581
import subprocess def get_fps(source): """ Get fps of video file """ command = "ffprobe -v error -select_streams v -of default=noprint_wrappers=1:nokey=1 -show_entries stream=r_frame_rate " + source output = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).communicate()[0] return output #subpr...
d1d573f49d2d1e08e5eff8afaf43442827746fc0
674,582
def padtrim(buf, num): """ Calibate the length w.r.t. buffer parameter and pad the input if the calibrated length >= 0 (zero). Else trim (slice) the input using it. Arguments: buf (Any): Values to be inserted in EDF Header. num (int): Value used for padding/trimming the bu...
a684e9fc6964335d8646206b0804a8b055f826a0
674,583
import numpy def basins_from_cmip(cmip_basin_cube, lat_array, lon_array, pacific_lon_bounds, indian_lon_bounds): """Define basins using CMIP basin file information. CMIP definitions: land = 0, southern ocean = 1, atlantic = 2, pacific = 3, arctic = 4, indian = 5, mediterranean = 6, black s...
2aa97eed22462790311e41ecabe164f79c8aa7ab
674,584
def max_clique(dic): """Return the maximum clique in the given graph represented by dic. See readme for detailed description. Args: dic: dictionary{int : {'name' : str, 'edges' : a set of int}} Returns: list of int """ max_c = [] V = dic.keys() for v...
f05ed7baa38ebc6178dd0e4d30732ef90013de2d
674,585
def chunks(_list, n): """ Return n-sized chunks from a list. Args: _list - A list of elements. n - Number defining the size of a chunk. Returns: A list of n-sized chunks. """ return list(map(lambda i: _list[i:i + n], range(0, len(_list), n)))
eeee00ce773cd298954ecfed3da405b55aaecbb0
674,586
def is_isogram(string: str): """Check if a sentence or word is an isogram or not.""" read_chars = [] # read letters for ch in string.lower(): if ch.isalpha(): if ch in read_chars: # check if char pre exist in list return False read_chars.append(ch) retur...
42825c8f69deadef3a9ccb81725fe9c094f688bc
674,587
def objective_rule(model): """ Maximize the sum of all rewards of activities that are 'picked' (selected) """ return sum(model.CHILD_ALLOCATED[cr, ca] * model.child_score[ca] for (cr, ca) in model.cr_ca_arcs)
1c8469a12819c7cc461018a75d5d9ae29ce7ada5
674,588
def remove_spaces(string): """ Remove triple/double and leading/ending spaces """ while ' ' in string: string = string.replace(' ', ' ') return string.strip()
7c2e0534654374c31247fa542e59e3baabe2a479
674,589
from typing import Union from typing import Optional from pathlib import Path def check_for_project(path: Union[str, "Path"] = ".") -> Optional["Path"]: """Checks for a Brownie project.""" path = Path(path).resolve() for folder in [path] + list(path.parents): if folder.joinpath("brownie-config.jso...
026ccf715c7dbf9f1e7f3add2d84f7e661996928
674,590
def data_back_to_input_form(data, labels, data_valid, data_idx): """ "De"-collates data back into their form when originally passed. """ assert len(data) == len(labels) assert len(data_idx) == len(data_valid) data_input_form = [] num_duplicates, num_images = len(data), len(data[0]) for s...
424f0447c6fbdd8db32eb22eeb399abfc2e6ef00
674,591
def curveToKraken(curve): """Converts a curve in Softimage to a valid definition for Kraken. Args: curve (obj): Softimage nurbs curve Object. Returns: list: The curve definition in kraken format. """ crvList = curve.ActivePrimitive.Geometry data = [] for eachCrv in crvLi...
0376b4ff174f5652bd15843134ec332f5b35ea07
674,592
import colorsys def lighten_rgb(rgb, times=1): """Produce a lighter version of a given base colour.""" h, l, s = colorsys.rgb_to_hls(*rgb) mult = 1.4**times hls_new = (h, 1 - (1 - l) / mult, s) return colorsys.hls_to_rgb(*hls_new)
b03dbd8c5fbef2683367f43fcbbad177a2e0aa22
674,594
import sys def get_module_object_and_name(globals_dict): """Returns the module that defines a global environment, and its name. Args: globals_dict: A dictionary that should correspond to an environment providing the values of the globals. Returns: _ModuleObjectAndName - pair of module object & mod...
bde3cd033c9e227091f84bf9925cb21042085091
674,595
def recursive_length(item): """Recursively determine the total number of elements in nested list.""" if type(item) == list: return sum(recursive_length(subitem) for subitem in item) else: return 1.
597df9062da54a124711618eb21890997cd6cfa2
674,596
from typing import List def numeric_binary_search(ordered_numbers: List[int], search: int) -> int: """Simple numeric binary search Args: ordered_numbers(List[int]): an ordered list of numbers search(int): number to find Returns: int: found index or -1 """ assert isinstanc...
a543ff116d98fcb5b2b405ccd51d650b54692de4
674,597
import os def package(name): """If exists get pathname for a directory containing a command script and associated data distributed as part of the calling addon""" path = os.path.join(os.path.dirname(os.path.abspath(__file__)), name) if os.path.isdir(path): return path if os.path.isfile(path) a...
da91c849c7e5fb8cc7c015a6ff5b45274e51b894
674,598
import random def get_randints(lower, upper, exclude): """Generate a set of unique random numbers in a range (inclusive).""" numbers = [i for i in range(lower, upper, 1)] numbers.remove(exclude) random.shuffle(numbers) return numbers
ba272295bc9938f157b6b893632a3c8b9af96b3f
674,599
def knot_insertion_alpha(u, knotvector, span, idx, leg): """ Computes :math:`\\alpha` coefficient for knot insertion algorithm. :param u: knot :type u: float :param knotvector: knot vector :type knotvector: tuple :param span: knot span :type span: int :param idx: index value (degree-dep...
51e3e61eae5e562c47b67904873e4ffe327bb842
674,601
import os def get_image_score_from_groups(folders, image_scores): """ Get group lists of image files and scores :param folders: image folders :param image_scores: a dictionary of images and their MOS scores :return: two lists image_file_groups: a list containing image file groups, ...
6cbabfb1212e7ee64e4ab5916ab9dd70c7c5f191
674,602
def _filter_FG(ret, group): """ Function to filter hosts using Groups """ return ret.filter(filter_func=lambda h: h.has_parent_group(group))
24739476b3a54a8caf488158613581022ef80aaa
674,603
def pearsonchisquare(counts): """ Calculate Pearson's χ² (chi square) test for an array of bytes. See [http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test #Discrete_uniform_distribution] Arguments: counts: Numpy array of counts. Returns: χ² value """ np = sum(cou...
56440e7241451d66b67f7d55c7fa918cf758a5b7
674,604
from typing import Type import yaml def template_dumper(header_comment: str) -> Type[yaml.SafeDumper]: """Returns a custom dumper to dump templates in the expected format.""" class TemplateDumper(yaml.SafeDumper): def expect_stream_start(self): super().expect_stream_start() i...
38ca33a1478f0e548fef3a4fc456dec0fca2d2bc
674,605
import os def _outdir_files(outdir): """Recursively list `outdir`.""" result = [] for (dirpath, dirnames, filenames) in os.walk(outdir): for filename in filenames: fullpath = os.path.join(dirpath, filename) result.append(os.path.relpath(fullpath, outdir)) return result
a63efbc1a97809d740fd8134f8be7bfc6124b77f
674,606
def func_with_long(parameter): """ # pylint: disable=line-too-long aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcccccccccccccccccccccccccccccccccccccccccccccccccccc """ return parameter
1b54b7da914dbfaedd9916e62ce3beea1567ad11
674,607
import os def get_service_connection_string(service): """Given a container name this function returns the host and ephemeral port that you need to use to connect to. For example if you are spinning up a 'web' container that inside listens on 80, this function would return 0.0.0.0:23493 or whatever eph...
64cd7b1cdadcb07a66262e82e29c01d6db94aa86
674,608
def common_shape(imgs, axis): """ Find smallest height or width of all images. The value along `axis` will be `None`, the other will be the smallest of all values Args: imgs (list[np.array]): list of images axis (int): axis images will be concatenated along Returns: tup...
d0b357f20e955932e135aeedc318a969d7f9f883
674,609
def convert_image(img, coefs): """Sum up image channels with weights from coefs array input: img -- 3-d numpy array (H x W x 3) coefs -- 1-d numpy array (length 3) output: img -- 2-d numpy array Not vectorized implementation. """ x = img.shape[0] y = img.shape[1] re...
3f28eaf00a48ebb76e2b403750ee46b1c1930c38
674,610
def build_context(query, query_config): """Build context based on query config for plugin_runner. Why not pass QueryExecConfig to plugins directly? Args: query (str) query_config (QueryExecConfig) Returns: dict str -> str """ context = vars(query_config) context['query'] = query return c...
c1e6c93fd8d97e659eaa27e7b48494f600ebc8f9
674,611
def word_counter(words, text): """Vectorized string search""" total = [0]*len(text) # Empty list for i, txt in enumerate(text): for word in words: if word in txt: total[i] = total[i] + 1 return total
82f1dc592ddcbe925d09b900e45cd5efc8afde05
674,612
def index_to_coordinates(string, index): """ Returns the corresponding tuple (line, column) of the character at the given index of the given string. """ if index < 0: index = index % len(string) sp = string[:index+1].splitlines(keepends=True) return len(sp), len(sp[-1])
fc21d15cade5d005895a226ae992b2e9792372f5
674,613
import os def lst2files(lstpath, ext=None): """Read from a listing file and return a list of file paths.""" with open(lstpath) as fp: lines = fp.readlines() paths = [] for line in lines: fpath = line.strip() if ext is not None: fpath = "{}.{}".format(fpath, ext) ...
d4c774f8ec3892db9add764295f74222f15b1e6d
674,614
import os def _get_markdown_content(slug, page): """ Load a markdown file """ mdfile = os.path.join("static", slug, page + ".md") with open(mdfile, "r") as fo: data = fo.read() return data
31b14c8d921ae9c3f160d2e0b35ca78310423ab0
674,615
from typing import Iterable def binary_str_to_decimal(chars: Iterable[str]) -> int: """ Converts binary string to decimal number. >>> binary_str_to_decimal(['1', '0', '1']) 5 >>> binary_str_to_decimal('101010') 42 """ return int("".join(chars), base=2)
2dcd986c4c56c9a177ebf41138226f40464850a8
674,616
def mean(num_list): """ Return the average of a list of number. Return 0.0 if empty list. """ if not num_list: return 0.0 else: return sum(num_list) / float(len(num_list))
accfaf78a276654af94911ab0091d3a5650b49f3
674,617
import re def CheckContext(context:str) -> bool: """ contextのチェックをする。 """ regex = r'^https://w3id.org/openbadges/v2$' if (re.search(regex, context)): return True else: return False
071f463375c1f905972b420fdb23692414cc9bd5
674,618
import re def cnvt_to_var_name(s): """Convert a string to a legal Python variable name and return it.""" return re.sub(r"\W|^(?=\d)", "_", s)
b709f41809f863ccf5137e7ff4d0c444223ff31e
674,619
def quick_sort(collection: list) -> list: """ A pure Python implementation of quick sort algorithm :param collection: a mutable collection of comparable items :return: the same collection ordered by ascending Examples: >>> quick_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> quick_sort([]) ...
3ccf9a99e0434f80066f657e80c310b25ae11eae
674,620
def pow2(x): """Return the square of x :param float x: input value :rtype: float """ return x*x
955e83c526430582a542eb6c3b1d2ab92d7bff61
674,621
import re def is_mac_address(mac): """ Test for valid mac address :type mac: ``str`` :param mac: MAC address in the form of AA:BB:CC:00:11:22 :return: True/False :rtype: ``bool`` """ if re.search(r'([0-9A-F]{2}[:]){5}([0-9A-F]){2}', mac.upper()) is not None: return True ...
d67d20e85189307c35b6fdfaf42103128087691a
674,622
import sys def percent_progress(log=sys.stdout): """ :return: Convenience progress callback which updates a percentage on the specified output stream """ def _progress(done, total): complete = 100*done/total log.write("\b\b\b\b%3i%%" % complete) log.flush() return _progress
6227c81e26ad7b588114468c654a459286331844
674,623
def replyKBRow(*argv) -> list: """ Row of reply Keyboard buttons - *`argv` (`list`): Pass KeyboardButton objects to generate a list (This is unuseful, you an use [button1,button2] with the same result) """ result = list() for arg in argv: result.append(arg) return result
97f356cf770c8c3a06bcea835282000429b1d174
674,624
import json def create_label(name, color, repos, session, origin): """ Creates label :param name: name of the label :param color: color of the label :param repos: repository where label is created :param session: session for communication :param origin: repository where the label came fro...
c5f157673967c8f1b8928c3831abf4558ef5dc92
674,625
import os import requests def get_users_per_name(search_filter): """Retrievies users from Gitlab""" if 'GITLAB_ACCESS_TOKEN' not in os.environ: return {} headers = {'Private-Token': os.environ['GITLAB_ACCESS_TOKEN']} gitlab_api = "http://gitlab-srv/api/v4" users_db = {} # tries to matche a name/fullnam...
b089074e29749fa6c044337cca169d12dd299005
674,626
import argparse def get_p1_common_parser(parser): """Parse command-line arguments. Ignore if not present. Parameters ---------- parser : python argparse parser for command-line options """ # General behavior parser.add_argument("--train", dest='train_bool', action...
f1972c866d7dc89f71a6958ce3a8a2eaba8bd75a
674,627
def returnBaseFileName(fileName): """Overwrite this with OS stuff. """ try: main = fileName.split("/")[-1] except: main = fileName return main
84d48361d14ace1dc51fa32650cd981a007f6397
674,628
import re def strip_video(video_url: str) -> str: """ pull out video code from url, eg https://youtu.be/XnYaTgv7eMA?t=35 becomes XnYaTgv7eMA https://www.youtube.com/watch?v=rEq1Z0bjdwc becomes rEq1Z0bjdwc Apparently there are way more youtube formats than you'd expect https://gist.github.com/rodri...
4c8479cf812ece35cd383af11e48e38f45a652fa
674,629
import argparse def add_conf_args(run_mode): """ define the argument parser object """ parser = argparse.ArgumentParser() parser.add_argument('--batch_size', type=int, default=2, help='Set batch size for training.') parser.add_argument('--batch_size_for_inference', type=int, de...
bc3d2f89c133754a92ae3406bb26e8184d698da8
674,630
def partition_horizontal(value, n): """ Break a list into ``n`` peices, but "horizontally." That is, ``partition_horizontal(range(10), 3)`` gives:: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] Clear as mud? """ try: n = int(n) value = list(value) ...
fed3af5f5f57b32aa41662bd4cb4fe1b48876be3
674,631
import math def find_linear_point(x, y, threshold=0.00001): """this function will find 3 points with the highest distance on a single line to find elastic region. return shape is (mid point),(point1),(point2),mid_point_index, distance of two other points from mid point""" max_range = 0 max...
b0f6f3acbaff7fd6a3dd3179a8e9dc189b45f0a2
674,632
from jinja2 import Template def display_problem(file, seed): """ Constructs and sends a :class:`Problem <Problem>`. Returns :class:`Problem <Problem>` object. :param file: method for the new :class:`Request` object. :param seed: Seed number to used to base random number generation off of Usa...
bfa3aa2fad95e17425e44b930f2caaaa2876cf6b
674,633
def num_leading_spaces(str): """ Return the number of leading whitespaces of given string """ for i, c in enumerate(str): if c != ' ': return i return len(str)
eef26534aed7b782246542b1cf9eef5cd222eb7e
674,635
def memoize(f): """A simple memoize decorator for functions.""" cache= {} def memf(*x): if x not in cache: cache[x] = f(*x) return cache[x] return memf
f1b318f37cddabfdb8e508c4f18386e49e6c14ee
674,636
import json def parse_json_file(file_path: str): """utility method to read a json file and return json object Parameters ---------- file_path : str full path to json file that needs to be parsed Returns ------- [type] json object parsed from the file """ with open...
100968b80f165397628d8523821f245c5c779d17
674,637
def to_int(x): """Convert bytes to an integer.""" return int(x.hex(), 16)
523bb07b8900f9cf364904f90da393b736cbdeda
674,638
from typing import OrderedDict def custom_sort_exps(exps): """ Sort the experiments according to JIRA LCLSECSD-210 Active first, OPS next and then descending run period/alphabetical within that run period """ # Python's sort is stable; so we sort multiple times lowest attr first exps = Ordered...
dcd76be3ac6a0c9b8b60b87b1c48b0a2823a363e
674,639
def docs_modified(file_paths): """Report if any files in the Docs directory.""" for path in file_paths: if path.startswith("Doc"): return True return False
28d17f47d01f111d1fc89210cffc549c033dcf6c
674,640
def _match_some(regexes, line, n_line, n_col): """Match patterns in order. Returns a tuple of match and token type or raises SyntaxError.""" for regex, token in regexes: match = regex.match(line, n_col) if match is not None: return match, token error = "No rules to match inpu...
c5b2f9f3efdee10b44357f9d4f1e81a09553d22e
674,641
import turtle def createTurtle(): """ A fruitful function for creating a turtle. Returns a turtle. :return: a turtle object """ stamper = turtle.Turtle() stamper.shape("circle") stamper.color("green") stamper.penup() # raise the pen so that we do not have a trail ...
38cf90a4b4745a40d25a8f3ab3286e00e11ad55b
674,642
import operator def eval_product(parse_result): """ Multiply the inputs. [ 1, '*', 2, '/', 3 ] -> 0.66 """ prod = 1.0 current_op = operator.mul for token in parse_result: if token == '*': current_op = operator.mul elif token == '/': current_op = ope...
5f3552037e581da43f43b7e89e60cfb0dc88ae5e
674,644
def _E(p, kernel, _, __, ___, nghp=None): """ Compute the expectation: <diag(K_{X, X})>_p(X) - K_{.,.} :: RBF kernel :return: N """ return kernel(p.mu, full=False)
ea27b73f62179f8b3ed8e5be40368684a2176860
674,645
def simple_transform(x): """Perform a simple preprocessing of the input light curve array Args: x: np.array first dimension is time, at least 30 timesteps Return: preprocessed array """ out = x.clone() # out[:,:30]=1 # centering 标准化因为均值为1,方差约为0.04. out -= 1. ...
72facf19bea3d843e6b267d74c2d7d80414a3f7c
674,646
def seconds_for_analysis(duration, measurement_type, selector): """Get duration for specified measurement type and selector.""" if measurement_type in duration: data = duration[measurement_type] if selector in data: return data[selector].duration_seconds return 0
56364f70d018982bffe84089f58699752f0cb207
674,647
def duplicates_checker(source, new): """ Checking for duplicates in existing list of contacts """ for item in source: if new == item['phone']: return False return True
5a7c7315ef3d9655369d75109b9073b99aea9486
674,648
import subprocess def ipfsAddFile(fileName): """ Upload the file to IPFS network and return the exclusive fileHash value. """ ipfsAdd = subprocess.Popen(args=['ipfs add ' + fileName + ' | tr \' \' \'\\n\' | grep Qm'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8') ou...
186bf189b6068dd8c2e9565249ac2cf77787d585
674,649
def _multiplot_interval(from_date, to_date, points): """ Computes the size of the interval between points in a multiplot. :return: the multiplot interval size. :rtype: ``float`` """ if points < 2: return 0.0 return (to_date - from_date) / (points - 1)
3b475fb7a112d4cf11f0c8dc7648e99472015e5f
674,650
def wma(df, price, wma, n): """ The Weighted Moving Average calculates a weight for each value in the series. The more recent values are assigned greater weights. The Weighted Moving Average is similar to a Simple Moving average in that it is not cumulative, that is, it only includes values in the t...
bf1fb40987b1bafff01bcd408dc028b4ce02ece9
674,651
def reduce_vocab(word_vecs): """ just takes words already used, but reserves 0 """ uniques = set() for wv in word_vecs: uniques.update(wv) new2old = [0] # always map 0 to itself if 0 in uniques: uniques.remove(0) new2old.extend(sorted(uniques)) old2new = dict((w, i) f...
9d9bfd22750425419dc803615cd883d3e752bad7
674,652
def recurse_combine(combo_items: list, idx: int = 0) -> list: """Recursively expands 'combo_items' into a list of permutations. For example recurse_combine([[A, B, C], [D, E], [F]]) returns [[A, D, F], [A, E, F], [B, D, F], [B, E, F], [C, D, F], [C, E, F]] """ result = [] if i...
effab4c6f29e353d19f88b23f7d2a3bfa854d431
674,653
def show_hidden(str, show_all=False): """Return true for strings starting with single _ if show_all is true.""" return show_all or str.startswith("__") or not str.startswith("_")
a77b0b2a5b51abdb4b3e323c3c1af70c025f1a96
674,654
def _ask_yes_no(prompt: str) -> bool: """Simple function that prompts user until they answer 'y' or 'n'""" answer = input(prompt).lower() while answer not in ("y", "n"): answer = input("Please enter 'y' or 'n': ").lower() if answer == "y": return True else: return False
79edd6287d4026102a886c25879b50938deaa373
674,655
def to_upper(string): """:yaql:toUpper Returns a string with all case-based characters uppercase. :signature: string.toUpper() :receiverArg string: value to uppercase :argType string: string :returnType: string .. code:: yaql> "aB1c".toUpper() "AB1C" """ return st...
eafb08654c65893e43d2a79407f625e862fd7b7e
674,656
import uuid def _get_id(): """Get a short unique ID.""" return str(uuid.uuid4())
7219e7ac2df3074a63c47cc005c51b4f64b59d1e
674,657
def linspace(a, b, num_chunks): """Returns equidistant steps in [a, b] whose number matches num_chunks.""" assert isinstance(num_chunks, int) and num_chunks > 0, 'Number of chunks must be a natural number!' h = (b - a) / num_chunks return [a + i * h for i in range(num_chunks + 1)]
d752c0129287d9ce83265990deba6aa919e16d3f
674,658
def say(content:str="") -> str : """ context:str -> The text to be printed in chat """ if not isinstance(content, str): return "## Say command hasn't been configured properly ##" return f"say {content}\n" #def op(player:str="") -> str: """ player:str -> Ops the player given ""...
c635d3b3b78c372f1ba208b05713b0b850a4eff6
674,659