content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def error_general_details(traceback_str: str) -> str: """ Error message DM'ed to the user after a general error with the traceback associated with it. :param traceback_str: The formatted traceback. :returns: the formatted message. """ return f"Here is some more info on the error I encounte...
232f61f377c0a9883279a84c52867b63f5777744
662,895
import csv def get_genes(path): """Returns a list of genes from common results tables. Assumes the genes are in the first column.""" with open(path) as full_gene_list: full_gene_list = csv.reader(full_gene_list) gene_list = [row[0] for row in full_gene_list] del gene_list[0] # Remove ...
9262fee113decbbf249c0f87febed74fc99077a3
662,896
def pretty_bytes(b): """ Format a value of bytes to something sensible. """ if b >= 10 * (1024**3): # 10 GiB return '%0.0f GiB' % (float(b) / (1024**3)) elif b >= (1024**3): # 1 GiB return '%0.1f GiB' % (float(b) / (1024**3)) elif b >= 10 * (1024**2): # 10 MiB return '%0.0f MiB' % (float(b) / (1024**2)) e...
49dd88e055aa80a7b91e17c53233320ab2011372
662,899
import logging def mask_sanity_fail(mask, shape, description): """ Sanity check on training masks; shape needs to match. description affects the logging, on failure. """ if mask is None: logging.warn("{} : mask is None".format(description)) return True if mask.shape != shape: ...
b656a44dfaa87e00b3df0e0b1277f9f4ec59cf94
662,902
def get_error_score(y_true, y_predicted): """ Error score calculation for classification. Checks if the labels correspond and gives a score. An error score of 1 means that everything is falsly predicted. An error score of 0 means that everything is correctly predicted. Inputs: y...
e8b9c9b8bc7f76c974ac45c636aa7254967e3e26
662,903
import hashlib def get_consts(method): """ Create hash object and its integer upper bound. """ hasher = getattr(hashlib, method) max_plus_one = 2 ** (hasher().digest_size * 8) return hasher, max_plus_one
4b6d3fa9eb73a9efbbd9d32ae82ad73b03b9c98f
662,905
def remove_by_index(l, index): """removes element at index position from indexed sequence l and returns the result as new object""" return l[:index] + l[index + 1:]
1c55d35d6f37c1180de4eaf1244985734a73a033
662,908
def resdiv_r2(Vin, Vout, R1): """ Calculate the exact value of R1 with R2 given. """ return R1 / (Vin/Vout - 1)
7c83447a58c15b4a096164e45ff1571d8bdf34d6
662,911
def get_file_changes(commit, prev_commit): """ Perform a diff between two commit objects and extract the changed files from it. Args: commit(:class:`~git.objects.commit.Commit`): Commit object for commit with file changes prev_commit(:class:`~git.objects.commit.Commit`): Com...
8094032a2ff7a9759b120fe0d5e4a5d9cbc7e462
662,912
import random import string def random_string(length=25): """Generate a random string.""" return ''.join(random.choice(string.ascii_letters) for i in range(length))
912cb70351317c4bb6988123b442885379005aa7
662,919
def find_response_end_token(data): """Find token that indicates the response is over.""" for line in data.splitlines(True): if line.startswith(('OK', 'ACK')) and line.endswith('\n'): return True return False
07b9022803c1da0f9ebef06dc674dd1c05aff79e
662,921
def perc95(chromosomes): """ Returns the 95th percentile value of the given chromosomes. """ values = [] for peaks in chromosomes.values(): for peak in peaks: values.append(peak[3]) values.sort() # Get 95% value return values[int(len(values) * 0.95)]
670763d1c8823286fea97716a4a8a5a552bfdb5c
662,924
def is_square(arr): """ Determines whether an array is square or not. :param ndarray arr: numpy array :return: condition :rtype: bool """ shape = arr.shape if len(shape) == 2 and (shape[0] == shape[1]): return True return False
8a65d3c576bc159e1a0e83a9a1fb1560a6689ce4
662,926
import hashlib def string_hash(data: str) -> str: """Given a string, return a hash.""" md5 = hashlib.md5() md5.update(data.encode()) # Note: returning plain integers instead of hex so linters # don't see words and give spelling errors. return str(int.from_bytes(md5.digest(), byteorder='big'))
c2c2a432e72d9effe45dee2f41cabdaaf47e6468
662,927
def _escape_filename(filename): """Escapes spaces in the given filename, Unix-style.""" return filename.replace(" ", "\\ ")
9bb22a7ab928cbe88bfa3c9b48b2b33faa657fc9
662,933
def _parse_languages(value): """ Utility function to parse languages. >>> _parse_languages(None) is None True >>> _parse_languages("en") == frozenset(('en',)) True >>> _parse_languages('') '' >>> _parse_languages("en,es") == frozenset(('en', 'es')) ...
a430d37af90c2dd9262ce88db6f0b7b61dd868e3
662,934
import csv def read_csv(filename): """ Read values from csv filename and returns a list of OrderedDict for each row. """ csv_data = [] with open(filename, 'r') as f: csv_file = csv.DictReader(f) for row in csv_file: csv_data.append(row) return csv_data
ad031209f7d5a6e88dab4636fbf67c2795941b4d
662,935
def str_to_dpid (s): """ Convert a DPID in the canonical string form into a long int. """ if s.lower().startswith("0x"): s = s[2:] s = s.replace("-", "").split("|", 2) a = int(s[0], 16) if a > 0xffFFffFFffFF: b = a >> 48 a &= 0xffFFffFFffFF else: b = 0 if len(s) == 2: b = int(s[1])...
8aac064435d55412191344046daa109d5c0a2c53
662,940
import requests import click def _update_resource(url, token, data): """ Update a resource using a PATCH request. This function is generic and was designed to unify all the PATCH requests to the Backend. :param url: url to update the resource :param token: user token :param data: dict with t...
95a4f576f2489b01e99aeb8d1f72caa1837db241
662,942
def extended_euclidean(a, b, test=False): """ Extended Euclidean algorithm Given a, b, solve: ax + by = gcd(a, b) Returns x, y, gcd(a, b) Other form, for a prime b: ax mod b = gcd(a, b) = 1 >>> extended_euclidean(3, 5, test=True) 3 * 2 + 5 * -1 = 1 True >>> extended_euclidean(2...
330284588739d84372307df57040253ce8c1365b
662,944
def get_sample_name(sample, delimiter='_', index=0): """ Return the sample name """ return sample.split(delimiter)[index]
ba29852b1a85a20c882628be557c309b09eb005a
662,946
def negate_condition(condition): """Negates condition. """ return "not ({0})".format(condition)
72198a8a6ab86ba4196e4069c8d97a6b23002f57
662,950
from typing import Callable from typing import Dict def add_features(transform: Callable[[Dict], Dict], x: Dict) -> Dict: """ Takes the input, passes it to a transformation and merge the original input with the result of the transformation, can be used to augment data in the batch. .. note:: ...
ea62fb3fbd1987755d2abebfca6334beef93a560
662,954
def insertGame(gtitle: str, release_date: str="0000-00-00") -> str: """Return a query to insert a game into the database.""" return (f"INSERT IGNORE INTO game (title, release_date) " f"VALUES ('{gtitle}', '{release_date}');" )
9ab73633db7f2cda9ec69ab011e6d63d6a086ea0
662,958
import pathlib from typing import Tuple import ast def find_import_region(file: pathlib.Path) -> Tuple[int, int]: """Return the index of the first last import line that precedes any other code. Note: will not handle try/except imports file: pathlib.Path path to file to evaluate Return: Tuple[int, in...
5b2690d78b6172915c064ff7f0c133dc1c46c56b
662,959
def most_common_dict(a_dict: dict): """Returns the most common value from a dict. Used by consensus""" val_list = list(a_dict.values()) return max(set(val_list), key=val_list.count)
4651673d73e93d7a61fee222e976bfd3185487f9
662,974
def count_characters(array: list): """given a list:array of strings return the character count""" if len(array) == 1: # base case return len(array[0]) elif len(array) == 0: # edge case of empty array return 0 else: return len(array[0]) + count_characters(array[1:])
b0f4058ab38a6d221457ee1583000d71b5a4fa44
662,981
def filter_type(data, titletype: str): """ Filters the data so that it only returns rows with the defined value 'titletype' in the field titleType. Parameters: data = IMDb dataframe that contains the column 'titleType'. titletype = String value used to filter the data. Returns: A dat...
5da3499d9fdf6331ddfd4b2287d5f2fc0d685350
662,983
def concatenate_matrices(matrices): """ This function creates a concatenated matrix from a list of matrices Arguments: matrices: A list of tranformation matrices Returns: _transform: Concatenated matrix """ _transform = matrices[0] for i in range(1,len(matrices)): ...
2beaa3b99b4cd6dca8a1d2db58b3c91458f4559c
662,984
def is_overlapping(node2comm): """Determine whether a graph partition contains overlapping communities. Parameters ---------- node2comm : list of set of nonnegative integers **or** ndarray Community structure. A mapping from node IDs [0..NN-1] to community IDs [0..NC-1]. Examples ...
c2a2b2c8b396dd8117a2ce354b43fdea20176ce1
662,985
def find_io_by_name(input_list: list, name: str): """Retrieve an item from a list by its name attribute Arguments: input_list {list} -- A list of IO Items name {str} -- The name to filter for Raises: ValueError: No item with this name was found Returns: IOItem -- An IO...
7ad962935a04b20f813d6a822c0f770adb973beb
662,994
def get_tasks_args(parser): """Provide extra arguments required for tasks.""" group = parser.add_argument_group(title='tasks') group.add_argument('--task', type=str, required=True, help='Task name.') group.add_argument('--epochs', type=int, default=None, he...
598be6d15a341e6ed05e37d59c7bc81b88df4498
662,995
import torch def compute_fg_mask(gt_boxes2d, shape, downsample_factor=1, device=torch.device("cpu")): """ Compute foreground mask for images Args: gt_boxes2d: (B, N, 4), 2D box labels shape: torch.Size or tuple, Foreground mask desired shape downsample_factor: int, Downsample facto...
afc295bfd6fc9d2fa924474631dd0cc19bd301ae
662,996
def dict_to_tuple(dict): """Return RSA PyCrypto tuple from parsed rsa private dict. Args: dict: dict of {str: value} returned from `parse` Returns: tuple of (int) of RSA private key integers for PyCrypto key construction """ tuple = ( dict['modulus'], dict['publicExponent'], ...
f404f17051e4eb0280be18543c96f1c07a3999b0
663,001
def get_word_freq(word_list, normalize=True): """Returns a sorted list of (word,word count) tuples in descending order. The frequency is normalized to values between 0 and 1 by default.""" word_freq_dict = {} for w in word_list: if w in word_freq_dict: word_freq_dict[w] += 1 ...
42084d118456eec3a29d667bcb248330a82dd413
663,003
from operator import concat def concat_list(wire_list): """ Concatenates a list of WireVectors into a single WireVector :param wire_list: list of WireVectors to concat :return: WireVector with length equal to the sum of the args' lengths The concatenation order is LSB (UNLIKE Concat) """ ...
2938cae9ce26ba4e4507b42bea3c55d7a148ff21
663,006
def split_doc_num(doc_num, effective_date): """ If we have a split notice, we construct a document number based on the original document number and the effective date. """ effective_date = ''.join(effective_date.split('-')) return '{0}_{1}'.format(doc_num, effective_date)
57f3709955d5e5c49f40e1a9b2d0917304f6cab6
663,008
import re from typing import Tuple def parse_version_string(name: str) -> Tuple[str, str]: """Parse a version string (name ID 5) and return (major, minor) strings. Example of the expected format: 'Version 01.003; Comments'. Version strings like "Version 1.3" will be post-processed into ("1", "300"). The pars...
0680cd64e28c7ddb5c0aeae5cb868387c8bd5a35
663,011
def autocrop_array_shapes(input_shapes, cropping): """Computes the shapes of the given arrays after auto-cropping is applied. For more information on cropping, see the :func:`autocrop` function documentation. # Arguments input_shapes: the shapes of input arrays prior to cropping in ...
acf407935814ae9ffb77a8b7ff3dd747be04bb03
663,013
def degc_to_kelvin(x): """Degree Celsius to Kelvin Parameters ---------- x : float or array of floats Air temperature in deg C Returns ------- output : float or array of floats Air temperature in Kelvin """ return x + 273.15
52a7c242f08a0e0cb849fc8433ec143f4e19d4fb
663,014
def letter_count(word, letter): """ Returns the number of instances of "letter" in "word" """ return word.count(letter)
17121bb6820db0ece553cc0021ad4daba70df945
663,016
def make_reducer(delimiter): """Create a reducer with a custom delimiter. Parameters ---------- delimiter : str Delimiter to use to join keys. Returns ------- f : Callable Callable that can be passed to `flatten()`'s `reducer` argument. """ def f(k1, k2): if ...
7454e221e53abb915a0ba84badd618a6030e512c
663,017
def resource_is_object(resource): """Check if the resource is a simple object.""" if resource: return ( "metadata" in resource and "kind" in resource and "name" in resource["metadata"] ) return False
b543e1595d1862b1702404bef4d90105fc9bc75b
663,020
import warnings def div(a, b): """Divides a number 'a' by another number 'b' Parameters ---------- a: int or float Number to be divided b: int or float Number to divide by Returns ------- d: int or float Result of the division ""...
76c43818c6336d1b6d321fad2150f9b85e3d6774
663,025
def get_param_value(param_name, args, config): """Get value of a named command parameter either from args or from config. """ param_val = None # If param_name is available in config use it if config and config.get('default', None) and config['default'].get(param_name, None): param_val = conf...
f3e2b3b3a769d5ac3ef5fdb0677cc4d21a916452
663,029
def CO2_to_fCO2(CO2, Ks): """ Calculate fCO2 from CO2 """ return CO2 / Ks.K0
eb08fdf824047536eb47c9927f434d1f8ca499c5
663,030
def chr_start_stop_to_sj_ind(chr_start_stop, sj): """Transform a 'chr1:100-200' string into index range of sj dataframe Parameters ---------- chr_start_stop : str Genome location string of the format chr:start-stop sj : pandas.DataFrame Dataframe of splice junctions as created by re...
361a9a0c893059fbf5d51868826a7151b22fb59e
663,031
import time def to_timestamp(dtime): """Converts datetime to unix timestamp""" return int(time.mktime(dtime.timetuple()))
ad9267879f268ccb97a82a350e0fb9e2cf56696a
663,032
def nmc_LGM50_thermal_conductivity_ORegan2021(T): """ Wet positive electrode thermal conductivity as a function of the temperature from [1]. References ---------- .. [1] Kieran O’Regan, Ferran Brosa Planella, W. Dhammika Widanage, and Emma Kendrick. "Thermal-electrochemical parametrisation ...
3b7daa2e9a2be76a4b1ef7b92fb7f2800d77e542
663,034
def check_order(order: int) -> int: """Confirms the input is a valid parity order.""" if not isinstance(order, int): raise TypeError("`order` must be an integer.") if order <= 0: raise ValueError("`order` must be greater than zero.") return order
884bd95adbbcfcd5f6544bf981db50e269389408
663,038
def get_h5_dataset_shape_from_descriptor_shape( descriptor_shape, ep_data_key, ep_data_list ): """ Return the initial shape of the h5 dataset corresponding to the specified data_key. Initially the dataset will have length 0. It will be resized when data is appended. The descriptor shape will be eit...
b3f0f00d19bf56e82930c1f6ca705e853f8f0ad9
663,040
def uri_leaf(uri): """ Get the "leaf" - fragment id or last segment - of a URI. Useful e.g. for getting a term from a "namespace like" URI. Examples: >>> uri_leaf('http://example.org/ns/things#item') 'item' >>> uri_leaf('http://example.org/ns/stuff/item') 'item' >>> ...
05d9e512c9cea837344a5a331488a9e7698815d4
663,041
import asyncio async def wait_for_event(evt, timeout): # pylint: disable=invalid-name """Wait for an event with a timeout""" try: await asyncio.wait_for(evt.wait(), timeout) except asyncio.TimeoutError: pass return evt.is_set()
b8b2616f36f12db092c8f12a402115df863dff6f
663,043
def _GenerateJsDoc(args, return_val=False): """Generate JSDoc for a function. Args: args: A list of names of the argument. return_val: Whether the function has a return value. Returns: The JSDoc as a string. """ lines = [] lines.append('/**') lines += [' * @param {} %s' % arg for arg in ar...
ec8fd41661dadc011bd76c2cc3e51e50b46ee019
663,046
def metric_count_active(result, base_key, count): """Counts the number of chain active ("o") for the specified keys.""" active = 0 base_keys = base_key.split(",") for base_key in base_keys: for i in range(1, count): key = base_key.replace("[i]", str(i)) if key in result: ...
78cc02c7ac185752dc7bd1a62ff2c519ad491de9
663,048
def _testLengthBoundaryValidity(dataLength, tableDirectory): """ >>> test = [ ... dict(tag="test", offset=44, length=1) ... ] >>> bool(_testLengthBoundaryValidity(45, test)) False >>> test = [ ... dict(tag="test", offset=44, length=2) ... ] >>> bool(_testLengthBoundaryVal...
e5876302e2fdeb2cb1b708f49777b73183d2a938
663,052
def get_neighbor(rows, ele): """ :param rows: lst, letters get from user :param ele: lst, current letter position :return neighbor: lst, the location tuple next to ele """ neighbor = [] # find valid location tuples that in 3x3 grid centered by ele for x in range(-1, 2): for y in range(-1, 2): test_x = ele[...
265b71ba5c5b3415bfd7de2746ed3e370e66c467
663,053
def get_unset_keys(dictionary, keys): """ This is a utility that takes a dictionary and a list of keys and returns any keys with no value or missing from the dict. """ return [k for k in keys if k not in dictionary or not dictionary[k]]
8f9ef6d753a7db6d7ee1426de141ec27459c510f
663,055
from typing import List from typing import Any def get_search_result_path(search_response: List[Any]) -> str: """Extracts a search result path from a search job creation response :type search_response: ``List[Any]`` :param search_response: A search job creation response :return: A path to the search...
a973c31d9342e0e6da67e4ed265fc80560292581
663,056
def fichier2str(nom_fichier): """ Renvoie le contenu du fichier sous forme de chaîne de caractères. """ with open(nom_fichier, 'r') as f: chaine = f.read() return chaine
7d7296a8e0d8df5d3d2841cb398dd4379d6cee46
663,057
def remove_optgroups(choices): """ Remove optgroups from a choice tuple. Args: choices (tuple): The choice tuple given in the model. Returns: The n by 2 choice tuple without optgroups. """ # Check whether the tuple contains extra optgroup if isinstance(cho...
d02bf9d5da6717569c4a673b3d15d66f98a623f6
663,058
def is_valid_username(username): """Ensure username meets requirements. Returns True if successful.""" return bool(username and username.isalnum() and len(username) <= 30)
0eca6ce5fe448e3056532404ab9fe415541fc130
663,060
def remove_all(alist,k): """Removes all occurrences of k from alist.""" retval = [] for x in alist: if x != k: retval.append(x) return retval
c19240519d5bd66eda8f735e3469ce96ed36b621
663,063
def intensity(c, i): """Return color c changed by intensity i For 0 <= i <= 127 the color is a shade, with 0 being black, 127 being the unaltered color. For 128 <= i <= 255 the color is a tint, with 255 being white, 128 the unaltered color. """ r, g, b = c[0:3] if 0 <= i <= 127: ...
fbbb5582822b82e4e67fe6dc1e506e626bf39b37
663,064
def pixelfit(obs, i, times, series, timeslice=slice(None,None,None)) : """Fits a series object to the time series of data contained within a single pixel, optionally extracting the specified time period. Coefficients of the fit have been stored in the series. The rsquared of the fit is returned.""" ...
489a93409bc99366cb840cbf44e1dfee4a566df5
663,065
def is_dict(obj): """ Check if an object is a dict. """ return isinstance(obj, dict)
7424fa383aedacffaf0118efb5f55af6317d39bb
663,067
def get_iteration(nb, batch_size): """ Given total sample size and batch size, return number of batch. """ basic = nb//batch_size total = basic + (0 if nb%batch_size==0 else 1) return total
509805c4b9f6f05142b3f758ac134ec8c82fd087
663,070
def test_is_true(v): """ Helper function tests for a value that evaluates to Boolean True """ return bool(v)
21d84b0d4e93952921660b6afad9958d5fc78036
663,074
def generate_plus_grid_isls(output_filename_isls, n_orbits, n_sats_per_orbit, isl_shift, idx_offset=0): """ Generate plus grid ISL file. :param output_filename_isls Output filename :param n_orbits: Number of orbits :param n_sats_per_orbit: Number of satellites per orbit ...
c1da59a15ed7dd7dc769380c65ec5e96d41fd748
663,081
def unique_list(list): """ Returns a unique version of a list :param list: Input list :return: Unique list """ new_list = [] for i in list: if i not in new_list: new_list.append(i) return new_list
f04b2714b4c0c9c0ec8de10cf87167a696859969
663,083
def calculate_comment_to_code_ratio(production_code_metrics, test_code_metrics): """Calculate the ratio between the comments and the lines of code.""" lines_of_code = production_code_metrics["SUM"]["code"] + test_code_metrics["SUM"]["code"] comment_lines = production_code_metrics["SUM"]["comment"] + test_c...
48d7b991ecf19ebd7e97c2da3987abf7d2c8face
663,085
def lowercase_first_letter(s: str) -> str: """ Given a string, returns that string with a lowercase first letter """ if s: return s[0].lower() + s[1:] return s
e57810ec93482950c3e6563d1f9adbca732217e4
663,087
def _h_n_linear_geometry(bond_distance: float, n_hydrogens: int): # coverage: ignore """Create a geometry of evenly-spaced hydrogen atoms along the Z-axis appropriate for consumption by MolecularData.""" return [('H', (0, 0, i * bond_distance)) for i in range(n_hydrogens)]
f30d7008f64f586b952e552890cc29bb87c0544c
663,093
def split_alignments_by_chrom(alignments_file, get_temp_path): """Split an alignments file into several files, one per chromosome. get_temp_path is a function that returns a new temporary file path. Returns a dictionary, {chrom_name: alignmentfile_path}.""" paths = {} cur_chrom = None output_p...
6aa2a7caf200b15cdcefc855a779d59982b03e1f
663,094
def generate_occluder_pole_position_x( wall_x_position: float, wall_x_scale: float, sideways_left: bool ) -> float: """Generate and return the X position for a sideways occluder's pole object using the given properties.""" if sideways_left: return -3 + wall_x_position - wall_x_scale / 2 ...
4d31538547bb59b7b4115f772886d61b6e695e4b
663,097
def merge(ll, rl): """Merge given two lists while sorting the items in them together :param ll: List one (left list) :param rl: List two (right list) :returns: Sorted, merged list """ res = [] while len(ll) != 0 and len(rl) != 0: if ll[0] < rl[0]: res.append(ll.pop(0)) ...
0b88eea3733d0ac2739faff57b36faf6841d0446
663,103
def prep_reply_text(screen_name, text): """Replies have to contain the original tweeter's screen_name""" if screen_name in text: return text else: if "@" in screen_name: return screen_name + " " + text else: return "@{} {}".format(screen_name, text)
683fec84971e4350dcbb97483602c73a51b0fb35
663,111
def evaluate_probabilities(data): """Calculate accuracy of logistic regression model Args: data (pandas.DataFrame): dataframe with nudge success and probability Returns: int: accuracy in percentage """ check = round(data['probability']) == data['outcome'] correct = sum(check) ...
f8953f6fe3a934bdaea25f83828b9a9709e59974
663,113
def community_kwargs_from_role(role): """Parses community id and role from role name.""" args = role.name.split(':') if args[0] != 'community' or len(args) != 3: return None return dict( id_=args[1], role=args[2] )
4ce927f8c647190e7f1c5a2c7f875fd24c52b3c5
663,116
import torch def get_lengths_from_binary_sequence_mask(mask: torch.Tensor): """ Compute sequence lengths for each batch element in a tensor using a binary mask. Parameters ---------- mask : torch.Tensor, required. A 2D binary mask of shape (batch_size, sequence_length) to calcu...
f590d08ae8649a1ba9aaa2da70de377d0b397e4c
663,120
def _f_p_r_lcs(llcs, m, n): """ Computes the LCS-based F-measure score Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/ rouge-working-note-v1.3.1.pdf Args: llcs: Length of LCS m: number of words in reference summary n: number of words in candidate summary...
93700f51169b4c081b53412e133fc173392c3ea3
663,121
def flatten_frames(array): """ Flattens array of shape [frames, height, width] into array of shape [frames, height*width] Parameters ---------- array : np.array (frames, height, width) Returns ------- np.array flattened array (frames, height, width) """ _, heig...
6f1d3de5d6987ad46dca6de04647f5c2eab1f5cb
663,124
def check_valid_coors(coords): """Check if the given coords of the polygon are valid Parameters ---------- coords : numpy array a list of coordinates, shape = (8,) Returns ------ bool whether all coordinates are valid or not """ for i in coords: if i < 0: ...
0ad092cb34d3d2a51e5708e2ac60a6332eeb67e3
663,125
import configparser def _get_api_key() -> str: """ Retrieves the ADSBexchange API key from secrets.conf """ config = configparser.ConfigParser() config.read("secrets.conf") return config.get("adsbexchange", "key")
f0d01ba6acbab1cf1768b555365735313057d135
663,127
def removeNoneValues(dict): """ If value = None in key/value pair, the pair is removed. Python >3 Args: dict: dictionary Returns: dictionary """ return {k:v for k,v in dict.items() if v is not None}
0ef51c71e8b41e61dc7928db5393d959dc9a0f69
663,132
def subsampling(sequence, sampling_factor=5): """ Args: sequence: data sequence [n_samples, n_features] sampling_factor: sub-sampling factor Returns: sequence: sub-sampled data sequence [n_samples/sampling_factor, n_features] """ sequence = sequence[::sampling_factor] ...
ffdb254890525b7500852867359fdfd64869d485
663,137
def _get_local_explanation_row(explainer, evaluation_examples, i, batch_size): """Return the local explanation for the sliced evaluation_examples. :param explainer: The explainer used to create local explanations. :type explainer: BaseExplainer :param evaluation_examples: The evaluation examples. :...
b17f88b7f03d0ff40772102a88afc4449fee8035
663,142
def get_addons(objects): """Return tuple of required addons for a given sequence of objects.""" required = {} def _required_addons(objs): for addon in objs: if addon not in required: if addon.required_addons: _required_addons(addon.required_addons) ...
b2fb3450e07b0882fc8760d53691b6e14613baf8
663,143
def big_letters(sequence_of_sequences): """ Returns a new STRING that contains all the upper-case letters in the subsequences of the given sequence that are strings, in the order that they appear in the subsequences. For example, if the argument is: [(3, 1, 4), # not...
6df221024d634579b10cd8b05772a488cd64aafb
663,147
import secrets import string def random_name(length: int) -> str: """Get a random string suitable for a processes/consumer name""" return "".join(secrets.choice(string.ascii_lowercase) for _ in range(length))
0ed133e0bfdf35f5b5a01b9e87de1fe176966175
663,149
def pressure_at_model_level(ps, ak, bk): """computes pressure at a certain model level. Uses surface pressure and vertical hybrid coordinates. **Arguments:** *ps:* surface pressure *ak, bk:* hybrid coordinates at a certain level """ return ak + bk * ps
32fef19321c7d7802cf64105dcb7e0ffdf8db8c8
663,150
def is_valid_matrix(mtx): """ >>> is_valid_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) True >>> is_valid_matrix([[1, 2, 3], [4, 5], [7, 8, 9]]) False """ if mtx == []: return False cols = len(mtx[0]) for col in mtx: if len(col) != cols: return False r...
2e57455155cca8f37f738ef5ca7444ec118f1f6a
663,151
import re def handle_star(github_star): """ Get github repository star :param github_star: 1.1k or 100 :return: 1100 or 100 """ pattern = r'[^k]+' star = re.findall(pattern, github_star) if github_star[-1] == 'k': return int(float(star[0]) * 1000) else: return int(s...
e2f7337a347a94e2fdec2d9f44c2bb68fe4b3e39
663,155
def binary_to_hex(binary_data, byte_offset, length): """Converts binary data chunk to hex""" hex_data = binary_data[byte_offset:byte_offset + length].hex() return ' '.join(a+b for a,b in zip(hex_data[::2], hex_data[1::2]))
708f22a0a0165c97aee77557965d3e720b77729c
663,157
def generate_degradation_matrix(p, h_max): """ Generate an upper triangular degradation transition matrix. Parameters ---------- p : float The probability of degrading by one unit at each time step. h_max : int The index of the failed state. Returns ------- list o...
7fe3a551287e590bc361846e43f3bc08ae1e0907
663,160
def ncities(cost): """ Return the number of cities """ nc, _ = cost.shape return nc
31177b9b0ccbd252adbe39219c0c6ed0b5f78bd3
663,161
def overlap(a1, a2, b1, b2): """ Check if ranges a1-a2 and b1-b2 overlap. """ a_min = min(a1, a2) a_max = max(a1, a2) b_min = min(b1, b2) b_max = max(b1, b2) return a_min <= b_min <= a_max or b_min <= a_min <= b_max or \ a_min <= b_max <= a_max or b_min <= a_max <= b_max
d898b46122adbac0777defb0ab658587c0c1d367
663,164
def _combine_regex(*regexes: str) -> str: """Combine a number of regexes in to a single regex. Returns: str: New regex with all regexes ORed together. """ return "|".join(regexes)
a8488f80345e37a8123111164206f501800c5019
663,168
def ofp_instruction_from_jsondict(dp, jsonlist, encap=True): """ This function is intended to be used with fluxory.lib.ofctl_string.ofp_instruction_from_str. It is very similar to ofp_msg_from_jsondict, but works on a list of OFPInstructions/OFPActions. It also encapsulates OFPAction into OFPIns...
5071c826702bf96a52524fd09aba97a332348a08
663,169
def parse_return(data): """ Returns the data portion of a string that is colon separated. :param str data: The string that contains the data to be parsed. Usually the standard out from a command For example: ``Time Zone: America/Denver`` will return: ``America/Denver`` """ if ...
be91b07aa4ad0e17e6197aa38f7f4b37e8ce50a5
663,170