content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def reshape_list(l, shape=None): """Reshape list of (list): 1D to 2D or the other way around. Args: l: List or List of list. shape: 1D or 2D shape. Return Reshaped list. """ r = [] if shape is None: # Flatten everything. for a in l: if isinstance(a,...
1bf5b3e9c60a64fbd16ef589381b89bd8c587b4e
581,687
def verbose_print(verbose, print_function=None): """ Factory function that return a working print function if verbose is True. Otherwise it returns a dummy function that won't print anything. :param verbose: True to return print_function :param print_function: Optional print function to use. Uses '...
303f3c234c4cd5d54e49bc9571e65887c312c297
581,689
def letter_prob(c): """ if c is the space character (' ') or an alphabetic character, returns c's monogram probability (for English); returns 1.0 for any other character. adapted from: http://www.cs.chalmers.se/Cs/Grundutb/Kurser/krypto/en_stat.html """ # check to ensure that...
c4402c1a90ecf4fc7aa0eea674cdbbb8c921e586
581,693
import select def _fileno_can_read(fileno): """Check if a file descriptor is readable.""" return len(select.select([fileno], [], [], 0)[0]) > 0
7628e6bfa4cb93fabb950612d6233b54452ece66
581,694
def eval_filter(y_true, y_pred, threshold=0.5): """ Args: y_true (list): true execution labels y_pred (list): predicted execution probabilities threshold (float): if p<threshold: skip the execution Return: label_acc (float): inference accuracy, only punishes False Negative c...
334c30e11272093cd725339f4bd45769d32782de
581,699
def _apply_args_and_kwargs(function, args, kwargs): """Apply a tuple of args and a dictionary of kwargs to a function Parameters ---------- function: func function you wish to use args: tuple all args passed to function kwargs: dict all kwargs passed to function """ ...
9da4933968d1729ae62472cec915f12b97ae6455
581,703
def center_x(cell_lower_left_x, cell_width, word_length, correct_for_length=False): """ This function centers text along the x-axis :param cell_lower_left_x: Lower left x-coordinate :param cell_width: Width of cell in which text appears :param word_length: Length of plotted word :param correct_for_...
fdd898dd2d142ed1685053b5ad185a62f96aa3fc
581,706
def is_remote_path(path): """ Returns True iff the path is one of the remote formats that this module supports """ return path.startswith('gs://') or path.startswith('hdfs://')
e84cfd6e15bb3d03c7838bd8bce36c01efe11555
581,710
def running_clients(hlwm, running_clients_num): """ Fixture that provides a number of already running clients, as defined by a "running_clients_num" test parameter. """ return hlwm.create_clients(running_clients_num)
aa870031d87b3dfaeee1bdb8ddb5ffdaf986635d
581,719
def _is_empty(query): """Checks if the result table of a query is empty Parameters ---------- query : dict JSON of the result of the query Returns ------- bool TRUE if the result table is empty, else FALSE """ return len(query["bindings"]) == 0
df13463334eea9c0620e81d238e60cb9db9f6f7f
581,720
def insert_id_in_endpoint(endpoint, id): """Replace ID placeholder in the endpoint with ID.""" # type: (str, int) -> str return endpoint.replace("<id>", id)
d1540ff498604c35a2e439fea0e3b6305e4e0510
581,722
def get_labels(res): """ Get the record labels for the given track. **Parameters** - `res`: list of string of album record labels, e.g. ['Universal/Warner Bros.', 'None'] **Returns** A dictionary of record label, `{'album_label_{num}': label_name}`. """ if res...
17340f8c655a7beb4c96462b661df1fba00a8863
581,723
def format_time(seconds: float) -> str: """Formats time into mm:ss:xx""" minutes, seconds = divmod(seconds, 60) centi = "{:.2f}".format(seconds % 1)[1:] return "{:02d}:{:02d}{}".format(int(minutes), int(seconds), centi)
fdd1ab58f9e47bb1e179a19f3d80d3bf3d691960
581,732
import logging def maybe_stop_early(patience: int = 5, *, check: str = "better", counter: str = "_counter"): """A callback factory for early stopping. The returned calback keeps a counter in ``state[counter]`` for the number of times ``state[check]`` is ``False``. If this counter exceeds ``patience``, th...
657c1605855ca08ba01d879eb98765a8e0aab8d0
581,734
def get_most_reviewed_restaurant(restaurants): """ This function takes a list of dictionaries as an argument and returns a dictionary with the restaurant's name as value to the key 'Name' and the number of reviews as value to the key 'Reviews' Parameters: restaurants (list): A list of dictionaries,...
42c0b8a86e75a52e56676351d5aed8c15ac3eed0
581,735
import requests def get_tinyurl(url): """Create and return the tinyURL.""" tiny_url_api = f'http://tinyurl.com/api-create.php?url={url}' response = requests.get(tiny_url_api) return response.text
bad3420738c71b87947852b0640883e62550bd6f
581,737
import time def elapsed_since(timestamp): """Returns elapsed time since a given timestamp in seconds. It will always returns at least one.""" ret = time.perf_counter() - timestamp return ret if ret >= 1 else 1
10ca01ed19eb668f08ebce60ac7efd52417bfbd9
581,741
def prepare_input_parameters(input_layer_size, hidden_layer_size, number_of_labels, lambda_value): """Prepare input parameters as a dictionary""" input_parameters = {} input_parameters['input_layer_size'] = input_layer_size input_parameters['hidden_layer_size'] = hidden_laye...
064573447723597b5309caa81d86c80540815075
581,745
def sum_loop(n): """Sum all the numbers between 0 and n using a for loop""" sum = 0 for i in range(n): if i % 2 == 1: sum += i return sum
3bb8ff41abe1803f047afa3056da804cd4416a64
581,746
import re def get_book_ids(book_urls): """ Return a list of unique book ids from a list of book urls """ # Check if books are duplicated unique_list = {} num_processed = 0 for url in book_urls: # print('url=', url) all_nums = re.findall('[0-9]+', url) # if all_num...
c9ce5437f13fbcf0e2ee324da02bab016ffe32de
581,752
def diff_object_types_histograms(new_histo, old_histo): """ Returns a new histogram that is the difference of it inputs """ all_keys = set(new_histo.keys()).union(old_histo.keys()) dd = {k: new_histo[k] - old_histo[k] for k in all_keys if new_histo[k] - old_histo[k] != 0} return dd
c941e0b5f65551a76ef81f64a1f929cb1d473eaa
581,756
import re def clean_line(line): """ Strip line of new line element then return, replacing negative floats without a 0, -.{value} with -0.{value} :param line: Line in the log file :type line: str """ subbed = "".join([re.sub("\n", "", value) for value in line]) return [f"-0.{v[2:]}" if v[0...
3288f4e349c112321d5f19a1854f4594113bc8f5
581,757
from typing import Union from typing import Tuple def ofname_tif( column: Union[str, Tuple[str, str]], size_x: int, size_y: int ) -> str: """ Return a filename for an output GeoTIFF file. """ if isinstance(column, tuple): output_name = '_'.join(column) else: output_name = colu...
7d86783f1db6d3eab272f6701b4ded02a63c5bce
581,758
def inputfiles(otfile, instfile, toofile, prfile): """ Get input file info as list of strings. Example ------- >>> info = printer.inputfiles('observations.txt', 'instruments.txt', 'too.txt') >>> [print(line) for line in info] Observation information retrieved from observations.txt Instrume...
e0d85ce25fbee619b286c306e4457b9592a61c3d
581,759
def get_fiscal_year_period(calendar_date): """Convert calendar date to a federal fiscal year and period.""" if calendar_date.month in [10, 11, 12]: return calendar_date.year + 1, calendar_date.month - 9 else: return calendar_date.year, calendar_date.month + 3
5156e911f8c53a91d99b65c2386de081e64c1209
581,760
def solution(array): """ ret = max{a[i] + a[j] + i - j} = max{a[i] + i} + max{a[j] - j} """ # 假设 第一个观光点是 0 ret, aii = 0, 0 for j, aj in enumerate(array): # max{a[j] - j} ret = max(ret, aj - j + aii) # max{a[i] + i} aii = max(aii, aj + j) return ret
5a1d764ee583a47ac9ab4020505c1fe37af5b8c5
581,761
def generate_sub_arrays(array): """ Parameters ---------- array : list list of characters or number Returns ------- list A list of all sub arrays """ all_sub_arrays = [] def helper(end): if end == len(array): return for start in ra...
be9102260032e349707c4267606b77d2d381d987
581,762
from typing import Dict from pathlib import Path from typing import List def make_true_relatives( probes: Dict[str, Path], galleries: Dict[str, List[Path]] ) -> Dict[str, List[int]]: """ Make a list of true relatives for each probe. Each true relative faces will be represented by its index in the gall...
b34081e011d5617e560ffd409a60ab0d15e57165
581,767
def minuteToSample(value, frequency=250): """ Converts time in format mm:ss in number of samples based on the frequency. Parameters: value -- Time in format mm:ss type: String frequency -- Sampling Frequency type: int ...
216b68d8c92c8d88cd4976e7ff792136d0dd0a0d
581,770
def _strip_blank_lines(lines: list[str]) -> list[str]: """Remove lines with no text or only whitespace characters from the start and end of the list. Arguments: lines: Lines to be stripped. Returns: A list with the same contents, with any blank lines at the start or end removed. """ ...
bab815009e789d0532a94cd42c0b6084f75e7b58
581,771
def unaugment_position(xu): """Break apart an augmented position matrix into phase-space position and perturbation matrix.""" return (xu[0], xu[1:])
a8e1bd41f3601ae6d7f29820c90dcb285399971a
581,772
import itertools def head(stream, n=10): """Convenience fnc: return the first `n` elements of the stream, as plain list.""" return list(itertools.islice(stream, n))
97af4b27bf102ee72f7f2507109d97ad68b97964
581,775
def last_non_empty_cell(cells): """Returns the index + 1 for the last non-empty cell """ idx = len(cells) for cell in cells[::-1]: if cell.source: return idx idx -= 1 return idx
00e74f6eef5cae474ff9a7a7d29bf3e4327e7d26
581,778
def parsenums(linestring): """converts strings like '1-10; 15-17' into a list of ph0001.fits, ph0002.fits, etc""" ans = [] first=linestring.split(';') for thing in first: ans= ans + (list(range( int(thing.split('-')[0]), int(thing.split('-')[1])+1))) ...
80049232b26cbd9a6ec5db92687fd789196bbde2
581,781
import base64 def consume_event_notification(event, unused_context): """ consume_event_notification demonstrates how to consume and process a Pub/Sub notification from Secret Manager. Args: event (dict): Event payload. unused_context (google.cloud.functions.Context): Metadata for t...
d88481789c429de5a23daeb7de84a0c35e670926
581,782
def encode_for_summarization(story_lines, summary_lines, tokenizer): """Encode the story and summary lines, and join them as specified in [1] by using `[SEP] [CLS]` tokens to separate sentences. """ story_lines_token_ids = [tokenizer.encode(line) for line in story_lines] story_token_ids = [token...
a3a1dae7ae5973a9109b94d82baaaa0ddf48cc9c
581,783
def get_date(source): """Get birth and death date if available. Return empty strings otherwise.""" dates = [] for event in ["from", "to"]: if source["lifespan"][event].get("date"): date = source["lifespan"][event]["date"].get("comment", "") else: date = "" dat...
264ce02db2c8b80bbb4782f53f0414be23ce74f5
581,786
import click def set_org_name(required): """Generate a callback for processing the `org_name` option or argument `required` is a boolean for whether org_name is required """ # could be generalized to work for any mutex pair (or list) but no obvious need def callback(ctx, param, value): ""...
bb25cfe4bfc2bbda09ee719f37a9a6f3891bbb61
581,787
def XNOR( A, B ): """ Return the Exclusive-NOR of `A` and `B` """ return int( ( A or (not B) ) and ( (not A) or B ) )
b8aab05a3fe707fb29ff893b5debb75b6746fe20
581,788
def _compare_dicts(old_results: dict, new_results: dict) -> bool: """ Compare testing dictionaries for equality. Compare the dictionaries for equality while ignoring the 'directory' and 'command' keys since these will always differ amongst tests. If all other parameters are equal, it is assumed the...
9ac177f98b12f9aeef1620356f02062824f74295
581,791
def check_for_validation(request): """Check for validation error in request session.""" if request.method == "GET": validation_error = request.session.get('validation_error', None) if validation_error: del request.session['validation_error'] return validation_error r...
b56f73d13541f4bb4ca68cb2e4a7e5ef029a7d01
581,792
def is_version_head(version): """ Returns if the specified version is HEAD or MASTER. The comparison is case insensitive. :param version: Version to test. :returns: True if version is HEAD or MASTER, false otherwise. """ return version.lower() in ["head", "master"]
0fc37a43cc8bb6137596252a575b768b0b87b78e
581,793
def _hemi_direction(hemisphere): """Return `1` for 'north' and `-1` for 'south'""" return {'north': 1, 'south': -1}[hemisphere]
8305bafc5b3d4fb6039d28a2c7aa9fbf3d62ecb7
581,796
def is_mac(addr: str) -> bool: """ 检查addr是否为mac地址 Check whether addr is a mac address :param addr: string like '80:8f:1d:e2:f2:f5' :return: bool """ part = addr.split(':') if len(part) != 6: return False for i in part: if len(i) != 2: return False ...
51fb18c1356e11cb3d4670a4b3ccbc39400d4440
581,799
def rm(client, access_key): """Remove security credentials.""" credentials = client.user.credentials(method="DELETE", accessKey=access_key) return credentials
56b0ee79380a3b906cb5dd5f9d2f251d546b0f76
581,802
import gzip import pickle def load_zipped_pickle(file_name): """ Load a serialized python object from a zipped pickle file """ with gzip.GzipFile(file_name, 'rb') as handle: obj = pickle.load(handle) return(obj)
9552ff75e6cf443936d92a4048c020f7d02d3b05
581,805
import plistlib def parse_plist_file(file_path): """ Parse the given plist file returning a dictionary containing the data. :param file_path: Path to the plist file. :return: Return the parsed plist_file. """ with open(file_path, 'rb') as file_pointer: plist_file = plistlib.load(file_p...
fc849572428157b028e4d024de2819cdc2900481
581,813
def round_up(x, r): """ Round x up to the nearest multiple of r. Always rounds up, even if x is already divisible by r. """ return x + r - x % r
b44af8ecba92cf48305d7680c67e1187053a7bb1
581,814
import re def is_valid_basefilename(base_filename): """checks if a base filename is valid Args: base_filename (str): The base of the filename Returns: bool: True if the base filename is valid """ if re.match(r'^[A-Za-z_]+$', base_filename): return True else: r...
3668c8707f3e955882144a4148552e2c0ccd2a2c
581,815
def pascal_triangle(num_rows): """ Calculate the pascal triangle for a given number of rows. """ def get_elem(arr, idx, default): if idx < 0 or idx >= len(arr): return default else: return arr[idx] def generate_columns(previous_row, num_columns): for ...
dfdee21f9cc71d2350fd562118820b96ffa8e03a
581,816
import re def isValid(text): """ A valid input should be in the form of: currency <CUR1> to <CUR2> """ return bool(re.search(r'\bcurrency \w{3} to \w{3}\b', text, re.IGNORECASE))
e105f1be4da4972b3d4fa33598f8e44c065e10c0
581,822
def fast_movedim(input, source, destination): """Move the position of exactly one dimension""" dim = input.dim() source = dim + source if source < 0 else source destination = dim + destination if destination < 0 else destination permutation = list(range(dim)) del permutation[source] permuta...
26522de4d459abf0ddb1fe83126d21f5352b0a80
581,826
from typing import Dict from typing import Any def empty_params(*args, **kwargs) -> Dict[str, Any]: """Return an empty dict.""" return {}
13cfd50c435589619925d3a87a612f827a6ee3d6
581,828
def patched_file_serialize(mocker): """Patches function that deserializes file contents to website content""" return mocker.patch( "content_sync.backends.github.deserialize_file_to_website_content" )
477be05acd3f44088ee2d11ad627658419ffd2f0
581,834
def parseGithubUrl(fullUrl, stripDotGit=False): """ Get user/organisation and repository name from github remote name (optionally removing the trailing ".git") """ remote, repo = fullUrl.split(":")[-1].split("/")[-2:] if stripDotGit: repo = repo.strip(".git") return remote, repo
f8d3048e4a40b8a1aab11df55dda011d5a3c9d27
581,837
def parse_warning_code(warning_code, quiet=False, return_dict=False): """Parses warning code from `check_all_diagnostics()` into individual failures and prints results. Parameters ---------- warning_code : int When converted to binary, each digit in the code stands for whether or no...
0f1df6f9023d2722a8262d31a23ed4697c81c150
581,838
def search_key_for_client(client): """Generate a string search key for a client""" elements = [] if 'name' in client: elements.append(client['name']) # name of client if 'hostname' in client: elements.append(client['hostname']) # hostname of client if 'oui' in client: ele...
b4d2eb98021a67de351173f11b618c45a3763a5d
581,841
def romanFromInt(integer): """ Code taken from Raymond Hettinger's code in Victor Yang's "Decimal to Roman Numerals" recipe in the Python Cookbook. >>> r = [romanFromInt(x) for x in range(1, 4000)] >>> i = [intFromRoman(x) for x in r] >>> i == [x for x in range(1, 4000)] True """ co...
4c9cde62e637d73fa79b72972a3e3ca5dc1eda9a
581,842
def freeze(d): """Convert the value sets of a multi-valued mapping into frozensets. The use case is to make the value sets hashable once they no longer need to be edited. """ return {k: frozenset(v) for k, v in d.items()}
b8e3b287838e5f8e52c71eb2d10e41823896dfe0
581,843
import requests def getJumpFinalUrl(url: str, maxJump: int = 5) -> str: """ 获取一个URL最终重定向的URL :param url: 原来的URL :param maxJump: 最大重定向次数,最大为5 :return: 最终重定向的URL """ jump = 0 maxJump = min(maxJump, 5) # 最大重定向的值为5 while jump < maxJump: response = requests.head(url) if...
0149c9c0c321f76be2204dfdd6ac6e949ac81c35
581,844
def _convert_old_aldb_status(old_status): """Convert insteonplm ALDB load status to new ALDB load status. Old status values: EMPTY = 0 LOADING = 1 LOADED = 2 FAILED = 3 PARTIAL = 4 New status values: EMPTY = 0 LOADED = 1 LOADING = 2 F...
099587374d517176584140348ed856b5dae8cce0
581,849
def bin_range_strings(bins, fmt=':g'): """Given a list of bins, make a list of strings of those bin ranges Parameters ---------- bins : list_like List of anything, usually values of bin edges Returns ------- bin_ranges : list List of bin ranges >>> bin_range_strings((0...
ed9b97d86940d2b05e678fb17c31668f079dad6e
581,851
def parse_dimension(string): """Parses a dimension string to a tuple (key, value, expiration_secs).""" key, value = string.split(':', 1) expiration_secs = 0 try: expiration_secs = int(key) except ValueError: pass else: key, value = value.split(':', 1) return key, value, expiration_secs
3b61b02a93646a2bf05cf015ed69df650cfc8b04
581,853
def get_possible_values(list_of_probs, threshold=.10): """ [[digit, confidence]] -> [[digit], confidence] Each item in the list that has a confidence of higher than the threshold is taken into account as a possibility. All possible lists of digits are constructed (taking one digit per outer list) and gi...
ea511efd9ace65d32900a4ed7e40a32910c9b177
581,855
from pathlib import Path def make_output_dir(path_output): """ generate output directory if it does not exist """ if isinstance(path_output, Path) == False: path_output = Path(path_output) path_output.mkdir(parents=True, exist_ok=True) return path_output
3e3b0dbb56c52fe4bcd051f61388305e44f0e20f
581,859
import typing import random def sort(array: list) -> list: """Quick sort implementation with random pivot point. """ total_length: int = len(array) if total_length < 2: return array pivot: typing.Any = array[random.randint(0, total_length - 1)] less_pivot: list = [] more_pivot: lis...
466cf6b38479d8876bfe25bd7705caa669cfffaa
581,860
def get_query_res(db_model, **kwargs): """ Returns all kwarg matches in DB model as a list """ return db_model.query.filter_by(**kwargs).all()
606d5471a6b5bdc1ae030622c17635bf687a38d3
581,861
def merge(base, overrider): """ Override base dict with an overrider dict, recursively. """ for key, value in overrider.items(): if isinstance(value, dict): subitem = base.setdefault(key, {}) merge(subitem, value) else: base[key] = value return base
709ca05a09fd1da05872b16ac29ab36c075fdee8
581,862
def hertz_4_humans(count: int) -> str: """Returns a human friendly interpretation of hertz.""" # Hertz if 1000 > count >= 1: return f"{round(count, 2)} Hz" # Kilohertz if 1000 > count / 1000 >= 1: return f"{round(count / 1000, 2)} KHz" # Megahertz if 1000 > count / 1000 **...
d215d4f8473b9a5b87bab9b4b5ad1d9f4e7b7fa3
581,863
def get_gms_smtp_settings( self, ) -> dict: """Get Orchestrator SMTP configuration .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - gmsSMTP - GET - /gmsSMTP :return: Returns nested dictionary with smtp configur...
5637c72d90bf5bed31a602536a5a0360da92032f
581,866
def width(version): """ Calculates the width of a version The width of version 1 is 21, version 2 is 25, 3 is 29 etc. """ return 17 + 4 * version
45ef773fce010d6a07775fd0431fd0a46aab47a2
581,867
def pick_not(L,c): """ computes L(~c)""" x = [] for i in range(len(L)): if not i in c: x = x + [L[i]] return x
f72e5ba49091be4daa52f901574ace0ed275535e
581,870
def _partition(sequence, pivot): """Iterate through the sequence once, putting elements less than the pivot in the left list, equal in the middle, and greater than in the right. :param sequence: collection, list, tuple, etc. of values :param pivot: the value in which the sequence will pivot around ...
393f695a5c1c8ca72270099a67942273ac84830a
581,878
def get_epsilon_schedule(start, end, endt, learn_start): """ Generate a decreasing function that returns epsilon for each timestep. Parameters ---------- start : float The epsilon value for step 0. end : float The epsilon value for step n. endt : int The number of ti...
0efbd65afd5f20ac5bc520650a0707312809c38b
581,881
def string_deserializer(x): # pragma: no cover (nothing to test here) """ This is to be used to deserialize strings. """ return str(x)
ec267495769d2f2626a59c9052ccb95ecc9914bb
581,882
def rho_correction(goals_home, goals_away, home_exp, away_exp, rho): """ Applies the dixon and coles correction """ if goals_home == 0 and goals_away == 0: return 1 - (home_exp * away_exp * rho) elif goals_home == 0 and goals_away == 1: return 1 + (home_exp * rho) elif goals_home...
dfbe0c199f99ef412dafc4613d9e676f138da63d
581,883
import re def is_camel_case(s: str) -> bool: """ Determines whether a string is written in camel case Args: s: The string to check Returns: True if the string is camel case, False otherwise """ pattern = '([A-Z][a-z]*)+' if re.search(pattern, s): return True re...
0bb46286900b9137ea920a5606d11eaa0af92a16
581,885
def get_return_info(ret, annotation): """ Extract info from a node containing a return statement Args: ret: the return node annotation: the funcation annotation (may be None) Returns: tuple: type, expression after 'return' keyword """ ret_type = annotation.value if anno...
33e304ce8ba80d6be1c2efb4bcc319b0ba767320
581,887
def replace_password(d : dict) -> dict: """ Recursively replace passwords in a dictionary. """ _d = d.copy() for k, v in d.items(): if isinstance(v, dict): _d[k] = replace_password(v) elif 'password' in str(k).lower(): _d[k] = ''.join(['*' for char in str(v)])...
36ac1b535d1d4b3061aa830c9b555ae8d9990cc3
581,888
def get_tax(base_cost: float, tax_rate: float) -> float: """Return the tax on base_cost.""" tax = base_cost / 100 * tax_rate return tax
e4d51edce84c18bd9952da083f7f7af7e1268bb8
581,892
def load_label(csv_file): """ Label file is a csv file using number to mark gesture for each frame example content: 0,0,0,2,2,2,2,2,0,0,0,0,0 :param csv_file: :return: list of int """ with open(csv_file, 'r') as label_file: labels = label_file.read() labels = labels.split(",") ...
eefd27201cfda2b8bca76f08402c24b399daa024
581,894
import requests def send_msg_dding(msg, token, url=''): """ Send the nail message text to the nail group. :param msg: Message text. :param token: Rebot token. :param url: Nail request url. :return: Response content """ text = { "msgtype": "text", "text": { ...
ea84b2c1028f8ca7038431263182d0168e004454
581,897
def split_train_test(data_raw): """ splits data into 3:7 split :param data_raw: raw data :return: return train and test data """ data_train = data_raw[int(len(data_raw) / 10 * 3):] data_test = data_raw[:int(len(data_raw) / 10 * 3)] return data_train, data_test
8def1064a48ec7fe09aada6033c3dc8369c2f037
581,898
def Ignore_Long_Sentence(tokenized_sentence, max_tokens): """ Determines if tokenized_sentence should be ignored, if it has more than max_tokens """ if len(tokenized_sentence) > max_tokens: return True else: return False
9b0be0245979649a9b31a1be30471f0ac4ac0570
581,907
def cnt_evnt_typ(ptrn, typ): """ Args: ptrn - midi.Pattern typ - midi.events Type Returns: n_evnt - int, number of typ evnts in ptrn """ n_evnt = 0 for trck in ptrn: for evnt in trck: if isinstance(evnt, typ): n_evnt += 1 retur...
a6f7c2bb735c161e1a7e04abcd8e3276bedde399
581,913
def dof_within(samples): """ Get the degrees of freedom for within-group variability. Parameter --------- > `samples`: a tuple of lists, where each list is a sample containing all the values of that sample Returns ------- The degrees of freedom for within-group variability. """ k = len(samples) # number o...
1d716616cbae16ef69e4272c657eeaef0bb373b8
581,919
def check_property_differences(spec_properties, dev_properties, bidirectional): """Compare properties in the parsed YAML Parameters ---------- spec_data : list List of dictionaries with specification data properties E.g [{'name': 'AdminModeDefault'}, {'name': 'AsynchCmdRepl...
ddc4b66b1dbab9b88408815d3378709422c5520d
581,920
import uuid def is_valid_uuid(uuid_to_test, version=None): """ Check if uuid_to_test is a valid UUID. :param uuid_to_test: str :param version: int {1, 2, 3, 4} or None :return: True if uuid_to_test is from a valid UUID """ try: if version: uuid_obj = uuid.UUID(uuid_to_...
6233c5b96d41e7002a27e0d8d181da44d34094c2
581,921
import math def counting_example(n): """ What comes in: The sole argument is a non-negative integer n. What goes out: Returns the number of integers from 1 to n, inclusive, whose cosine is positive. Side effects: None. Examples: -- counting_example(2) returns 1 since t...
bdc2c19877c9eb5b36ad5347fa0263ed0d301477
581,922
def get_binary_tree_diameter_and_height(tree): """ Given a binary tree, returns the longest path of connected nodes & height O(n) time O(n) space for recursion """ # leaf node has 0 diameter & height (base case) if not tree: return 0, 0 # calculate the left and right sub tree ...
7b110245918e635ee51b71dc9038d0ded2737a97
581,925
def chi_square_distance(point1, point2): """! @brief Calculate Chi square distance between two vectors. \f[ dist(a, b) = \sum_{i=0}^{N}\frac{\left ( a_{i} - b_{i} \right )^{2}}{\left | a_{i} \right | + \left | b_{i} \right |}; \f] @param[in] point1 (array_like): The first vector. @param[in...
9eb9749bf8d1c0070a05105bd10d09d39c690521
581,929
import functools import shlex def repl_command(fxn): """ Decorator for :class:`cmd.Cmd` methods Parses arguments from the arg string and passes them to the method as *args and **kwargs. """ @functools.wraps(fxn) def wrapper(self, arglist): """Wraps the command method""" a...
2516d46de1904ae5481685b66d0c0e5db909e53f
581,933
def assembleValue(hierarchy, indexEstimations): """ Compute a simple sum over all index-wise contributions """ # Flatten nested list and sum return sum([est for estList in indexEstimations for est in estList])
70085ce70e1f4cacb7a607c3fe3a69caabbe7155
581,935
def prefix_average2(s): """Return list such that, for all j, a[j] equals average of s[0],...,s[j].""" n = len(s) a = [0.0] * n # create new list of n zeros for j in range(n): a[j] = sum(s[0:j + 1]) / (j + 1) # record the average return a
b05053738094e65f9dc0597cd68afca155a70029
581,938
def _fix_author_names(names): """Fix author names. Parameters ---------- names : list of tuple of (str, str) Author names, as (last name, initials). Returns ------- names : list of tuple of (str, str) Author names, as (last name, initials). Notes ----- Sometime...
2ba0ae5b147465f25956f8c5bc576f1d735e9e59
581,939
def find_notification(notification_name, notification_defs): """ Find a notification by name in a list of notification definitions. :param notification_name: the name of the notification to look for. :param notification_defs: a list of notification definitions. :return: the notification_def with matchi...
ff9234c44ca0c98d09acc16eed24a5100e94b248
581,940
import re def natural_sorted(iterable, key=None, *args, **kwargs): """Return sorted list of strings according to (sub)string numerical value. Parameters ---------- iterable : :term:`iterable` The data to be sorted. key : :term:`function` The sorting function. *args Var...
860ced680c6e97f202ab339d413b3a2c181cbd43
581,943
def is_read_day(this_date,option): """Returns True if today is a day to read in satellite data - either we're reading in daily data or we're doing monthly and it's the first day of the month""" if option.sat_time_res == "d": return(True) elif option.sat_time_res == "m" and this_date.day == 1: ...
ce28e70c45d4cec961036b564d5dfe062dad0e9e
581,944
def relative_pos_from_pixels(image_work, x_pixels, y_pixels): """ Transform a pixels position to a relative position :param image_work: Image where the object is detected :param x_pixels: coordinate X :param y_pixels: coordinate Y :return: """ return float(x_pixels) / image_work.shape[1]...
57282f9cc52d489a6876b5d056e2ae7a74fcf86a
581,946
def is_wildcard(string_path): """Return true if string_path contains { and }, used to contruct wildcard matching""" return "{" in string_path and "}" in string_path
12c8d33e34af8833472d8b87c57bdf51e0b87a90
581,950