content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_heatmap_y_sample_sizes(parsed_mutations, sample_sizes): """Get sample size y axis values of heatmap cells. :param parsed_mutations: A dictionary containing multiple merged ``get_parsed_gvf_dir`` return "mutations" values. :type parsed_mutations: dict :param sample_sizes: A dictionary co...
17453adb768fd2acc7ae82f5852a1c8e5eaf4cc7
681,790
def cloudfront_public_lookup(session, hostname): """ Lookup cloudfront public domain name which has hostname as the origin. Args: session(Session|None) : Boto3 session used to lookup information in AWS If session is None no lookup is performed hostname: name ...
f1d3914f5fa5035c6f3105af052bf3e605cbea7a
681,793
def check_queue(queue, config): """ Check length and policy of a single queue :param queue: Queue form rabbit :param config: Desired queue state :return: length of a queue and lists of warnings and errors """ warnings = [] errors = [] length = queue['messages_ready'] if length >...
aede6f76f87e62b7972f51d564d1f3080059a327
681,794
def news_dict(cleaned_articles): """ For the cleaned_articles data, extract only the headline and summary. :param cleaned_articles: List of dictionaries, extract only the target information. :return: dictionary of Headlines to Summary. """ temp_dict = {} for i in cleaned_articles: te...
bfde1ebdb1eda9dcba4211fd1bbc3b1f2611fa3a
681,796
import logging def _create_list_of_class_names(view, label_field): """Create list of class names from the label field. Args: view (voxel51 view object) - the voxel51 dataset label_field (str) - label field set in config Returns: class_names (list) """ logging.info("Extrac...
ee1ac11da75356461657379608648eae357b5864
681,797
def _ResolvePortName(args): """Determine port name if one was not specified.""" if args.port_name: return args.port_name if args.protocol == 'HTTPS': return 'https' if args.protocol == 'SSL': return 'ssl' if args.protocol == 'TCP': return 'tcp' return 'http'
020d253db9bc0a5ecf5d724206789c0e3880ae2b
681,801
def check_row(board, num_rows, num_cols): """check if any 4 are connected horizontally(in 1 row) returns bool""" won = False for row in range(num_rows): for col in range(num_cols - 3): start = board[row][col] if start == " ": continue won =...
8af52a5de8a744e90dfbfee730014540be474f0e
681,804
def chomp_lines(istream): """ Returns a lazy generator of lines without trailing newline characters from the specified input stream. """ return (line.rstrip('\n\r') for line in istream)
358d4c69bef724f871d573a43a68f59c8ed63853
681,805
import math import collections def get_number_of_letter_permutations(permute_word): """ Finds the number of permutations of letters in a given word :param permute_word: a word to find permutations of :return: number of permutations of letters in the word """ # find all letter combinations to g...
bf41297cd9aa4f2f6bd32d49443248c23cd15b1d
681,807
import json def load_hash(filepath): """ Load hashes from json file. Parameters ---------- filepath : str path to json file to be loaded Returns ------- dict { str : dict } """ with open(filepath, "r") as f: return json.load(f)
457cbdd6622e25d4db9fe92d04fc5ec61d14b60f
681,808
def _snake_to_dromedary_case(string): """Convert snake_case to dromedaryCase. >>> _snake_to_dromedary_case('snake_case') 'snakeCase' >>> _snake_to_dromedary_case('longer_snake_case_name') 'longerSnakeCaseName' """ words = string.split("_") if len(words) > 1: words[1:] = [w.title...
0bc40f5cfad61bb6421c3532207ba489b21da094
681,810
import math def rat_from_rtc(rtc_s): """ Turn a real-time clock value into a radio time value Args: rtc_s: real-time-clock in seconds Returns: rat_s: radio time in seconds rat_t: radio time in ticks """ # Updated assumed RAT tick based on RTC value (magic magic) # ...
b4ec1cc05d980d4dbea22e245995ba3d91a6893f
681,812
def _translate_keyname(inp): """map key names in settings file to key names in HotKeys """ convert = {'Escape': 'Esc', 'Delete': 'Del', 'Return': 'Enter', 'Page_up': 'PgUp', 'Page_down': 'PgDn', 'NUMPAD_ENTER': 'NumEnter'} if inp in convert: out = convert[inp] else: ou...
37fc8863bd9ab9cede86b1601e49f7ac51a90baa
681,813
from itertools import zip_longest def grouper(n, iterable, fillvalue=None): """ Split an iterable in groups of max N elements. grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx """ args = [iter(iterable)] * n if fillvalue: return zip_longest(fillvalue=fillvalue, *args) for chunk in zip_...
321a19905603b40b19cdce932b913905c2cf2d83
681,815
def andGate(a, b): """ Input: a, b Two 1 bit values as 1/0 Returns: 1 if both incoming bits are 1 otherwise 0 """ if a == 1 and b == 1: return 1 else: return 0
17c4f22a41946ef5193f7a9b38373fde2b87cae8
681,824
import torch def select_device() -> str: """Selects the device to use, either CPU (default) or CUDA/GPU; assuming just one GPU.""" return "cuda" if torch.cuda.is_available() else "cpu"
eead9233b86887847d6a4aa837a78cfe0bbabaae
681,828
def _normalize_integer_rgb(value: int) -> int: """ Internal normalization function for clipping integer values into the permitted range (0-255, inclusive). """ return 0 if value < 0 else 255 if value > 255 else value
1e765e74e1dfd029c14c8e6b9201bd814530b1ec
681,829
def count_descendents(graph, root): """ Inputs: A weighted directed acyclic `graph` with positive edge weights and a starting `root` node Let the weight of a path in the graph be the product of the weights of its constituent edges and 0 if the path is trivial with no edges Returns: The sum of the we...
54c7320c1a009a7686e44d0f3f22a6107b3d10bf
681,830
import re def applyRegexps(text, listRegExp): """ Applies successively many regexps to a text""" # apply all the rules in the ruleset for element in listRegExp: left = element['left'] right = element['right'] r = re.compile(left) text = r.sub(right, text) return text
50cc3b293eafd3be82c5ffae29dd316139d96802
681,831
def is_multiple(n, divide): """ >>> is_multiple(0, 1) False >>> is_multiple(10, 1) True >>> is_multiple(10, 2) True >>> is_multiple(10, 3) False """ return (0 != n) and (0 == (n % divide))
afa052d81f20542494b446faa95b52330833ce23
681,833
import csv def detect(stream): """Returns True if given stream is valid CSV.""" try: csv.Sniffer().sniff(stream, delimiters=',') return True except (csv.Error, TypeError): return False
92dfeb58c4505fd9843ec1463ba6ae88349dd8d9
681,834
from typing import List def rotate90(buttonsIdx: List[int]) -> List[int]: """ Rotate puzzle by 90 degrees counterclockwise. :param buttonsIdx: list with position index for each button and empty cell :returns: list with positions after rotation """ newButtonsIdx = [] for i in buttonsIdx: ...
2b7b09a1e5aec3f09e2226bc1bdd0363a4f13511
681,836
def get_equivalence_ratio( p_fuel, p_oxidizer, f_a_st ): """ Simple equivalence ratio function Parameters ---------- p_fuel : float or un.ufloat Partial pressure of fuel p_oxidizer : float or un.ufloat Partial pressure of oxidizer f_a_st : float or un...
c07a853bfc517ad980cc34f0a66a67a24b16fbc3
681,839
def sv_length(pos, end, chrom, end_chrom, svlen=None): """Return the length of a structural variant Args: pos(int) end(int) chrom(str) end_chrom(str) svlen(int) Returns: length(int) """ if chrom != end_chrom: return int(10e10) if svlen: ...
4a15ba3f718323fd52ce1b55157189b4978dee17
681,840
def sampling(generate_data, nb_samples): """ Generates nb_samples from generate_data :param generate_data: Function that takes takes an integer n and samples from a synthetic distribution. Returns an array of n samples. :param nb_samples: Number of samples to generate :retu...
c6cb5b133500f2292d3303db1c28c60c415c097e
681,846
def identity(x, name=None): """Returns a tensor with the same content as the input tensor. # Arguments x: The input tensor. name: String, name for the variable to create. # Returns A tensor of the same shape, type and content. """ return x.copy(name=name)
ca7da1887b4bcd8db740f7aabb8a36ae6fde2486
681,847
import math def same_padding(in_dim, kernel_dim, stride_dim): """ Calculates the output dimension and also the padding required for that dimension. :param in_dim: Width/Height of Input :param kernel_dim: Width/Height of Kernel :param stride_dim: Vertical/Horizontal Stride """ output_dim = ...
48c39b0f3b490028ae06b5474101f42db612b761
681,848
def parameters_equal(a, b): """Compares two parameter instances Checks full name, data, and ranges. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no parameter instances """ if (not b.v_is_parameter and not a.v_is_parameter): ...
0eb019fb340c5baeaf270c7c53ee4a2cb1b94eaa
681,849
def binary_string(number: int) -> str: """Number to binary string :param number: some number (an integer) to turn into a binary string :return: Some string which is the binary string :rtype: str .. doctest:: python >>> binary_string(200) '11001000' >>> binary_string(10) ...
aa22bcc4ddd5546805db333c9b0be2e7f0e1c703
681,850
def get_ytid2labels(segment_csv): """ compute the mapping (dict object) from youtube id to audioset labels. """ with open(segment_csv) as F: lines = F.read().split('\n') lines = [l for l in lines if len(l) > 0 and l[0] != '#'] ytid2labels = {l.split(',')[0]: l.split('"')[-2] for l in li...
9afcb0637f338977e7107dd6e5445ec8e29a0abe
681,852
def get_bind_addr(conf, default_port=None): """Return the host and port to bind to.""" return (conf.bind_host, conf.bind_port or default_port)
e7791a9eafd0b2386f92755a8a8d3dddd70d52ce
681,854
def _part(f): """ Return a character representing a partly-filled cell with proportion `f` (rounded down to width of nearest available character). """ return [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"][int(9*f)]
5919707099b8bd09467056a770a6b8904a991c32
681,855
def join_infile_path(*paths): """ Join path components using '/' as separator. This method is defined as an alternative to os.path.join, which uses '\\' as separator in Windows environments and is therefore not valid to navigate within data files. Parameters: ----------- *paths: all str...
5bd109b5708fe48c5f9a8e2e3c418ab62ace23bb
681,856
def get_latlon_from_cube(cube): """Return domain covered by cube, taking into account cell boundaries :param cube: target cube :return: tuple(lat_max, lat_min, lon_max, lon_min, nlat, nlon) """ for latlon in ['latitude', 'longitude']: if not cube.coord(latlon).has_bounds(): cube...
5c49a6fbfb94962f4d39061252898dc1f0776ad1
681,857
def trapezoid(poly, lower, upper): """Calculate trapezoid slice from two polynomial evaluations and step size""" lower_value = poly.evaluate(lower) upper_value = poly.evaluate(upper) return (upper - lower) * ((lower_value + upper_value)/2.0)
777a4f569506524e57f979192467414509318f95
681,859
def set_dict_indices(my_array): """Creates a dictionary based on values in my_array, and links each of them to an index. Parameters ---------- my_array: An array (e.g. [a,b,c]) Returns ------- my_dict: A dictionary (e.g. {a:0, b:1, c:2}) """ my_dict = {} i = 0 ...
c9e0b05f4eeeef04f1fc42cdc06cf61f0f9b2e70
681,862
def get_day_of_the_week_number_from_datetime(datetime_obj) -> int: """Does what the function title states.""" return datetime_obj.weekday()
f39ef66090501da260b698901bc35b23d224a363
681,865
import logging def setup_logging(args): """Setup logging for the application""" log = logging.getLogger(__package__) log.setLevel(args.loglevel) # disable root logger handlers root_logger = logging.getLogger() root_logger.handlers = [] # set log output destination if args.logfile: ...
ee28234842897f194b300878cdc7ca0ad738f1fd
681,874
def count(val, iterable): """ Counts how many times a value (val) occurs in an iterable, excluding `None` :param val: The value to be counted :param iterable: values to be counted over :type iterable: iterable :return: the count of values :rtype: int """ return sum(1 for x ...
59fc5ad8c8ad233f00c0f4d000242db92af6c457
681,875
def format_metrics(metrics, split): """Formats metrics for logging. Args: metrics: Dictionary with metrics. split: String indicating the KG dataset split. Returns: String with formatted metrics. """ result = '\t {} MR: {:.2f} | '.format(split, metrics['MR']) result += 'MRR: {:.3f} | '.format(m...
c3c42afb289149585506b0548910c213cf745222
681,880
def word_count(review_str)->int: """ count number of words in a string of reviews """ return len(review_str.split())
5a980f7252f3cd840d92726e475360d0b50fab05
681,888
def _kl_normal_loss(mean, logvar, storer=None): """ Calculates the KL divergence between a normal distribution with diagonal covariance and a unit normal distribution. Parameters ---------- mean : torch.Tensor Mean of the normal distribution. Shape (batch_size, latent_dim) where ...
343cf098c00be7407a0e48bb3c53e449228c32c7
681,889
import torch def index2points(points, idx): """Construct edge feature for each point Parameters ---------- points: (batch_size, num_dims, num_points) idx: (batch_size, num_points) or (batch_size, num_points, k) Returns ------- edge_features: (batch_size, num_dims, num_points) or (bat...
0a730ba273582ab1c82e8f743ba9ef96599c3c39
681,890
from typing import IO def read_line(in_fd: IO[str]) -> str: """ Reads a single line from a file in bytes mode :param in_fd: Input file descriptor :return: The line (from in_fd current position), without EOL """ result = [] while True: # Ignore the first line read_char = in...
310ab4f74d89f49cfa503aaa30dd08f252a09aaf
681,891
def compute_Cp(T,Cv,V,B0,beta): """ This function computes the isobaric heat capacity from the equation: :math:`Cp - Cv = T V beta^2 B0` where *Cp,Cv* are the isobaric and isocoric heat capacities respectively, *T* is the temperature, *V* the unit cell volume, *beta* the volumetric thermal...
68504262c4bd49ef87b4ffcb4f09f75722f788c0
681,893
def _architecture(target): """Returns architecture for current active target, e.g. i386, x86_64, armv7""" return target.GetTriple().split('-', 1)[0]
ad403b92ae3cb14379970a98f7eb6bcc69d2542f
681,895
import torch def _tokenize_str(string, char_tensor=None): """ Parses a utf-8 encoded string and assigns to ByteTensor char_tensor. If no char_tensor is provide one is created. Typically used internally by `tokenize_str_batch`. """ if char_tensor is None: char_tensor = torch.ByteTensor(len(string.encode())) f...
047fb42570978c0cb0613ddd93afebc52fb0a57f
681,898
import logging def is_encoded_image_spec(tensor_spec): """Determines whether the passed tensor_spec speficies an encoded image.""" if hasattr(tensor_spec, 'data_format'): # If tensor_spec is an ExtendedTensorSpec, use the data_format to check. return (tensor_spec.data_format is not None) and ( ten...
a5e5376961f8e26f088aef4db0aa8460673b2839
681,899
def colour_linear_interpolation(col_a, col_b, t): """ Linearly interpolates between two colours. """ col = tuple([a + (b - a) * t for a, b in zip(col_a, col_b)]) return col
411456a3ecdff685302d50b906f9933ff46aa931
681,901
def is_valid_instant(x): """ Returns true iff x is a well-shaped concrete time instant (i.e. has a numeric position). """ try: return hasattr(x, "inTimePosition") and len(x.inTimePosition) > 0 and \ len(x.inTimePosition[0].numericPosition) > 0 except TypeError: return ...
920aff48da7747aac4350a0a977f40899d57e1ca
681,902
def truncate_val(val, lower_bound, upper_bound): """Truncate val to be in the range [lower_bound, upper_bound].""" val = max(val, lower_bound) val = min(val, upper_bound) return val
fb5438c7687d7e69efbf4fd061c85178f9b2f9a1
681,906
def _access(*args, **kargs): """Assume access to the path is allowed.""" return True
99d8a326a34eed5bdeb1a32d285d81f14470af02
681,907
def write(file, lines): """ Write file from an array """ with open(file, 'w') as f: bytes_ = f.write('\n'.join(lines[0:]) + '\n') return bytes_
606e994b674798b853a306816451185884d8c868
681,918
def getQuestionLabels(task_question_answer_labels, task_uuid): """ Gets a list of question labels under the same task uuid """ series = task_question_answer_labels[task_question_answer_labels["quiz_task_uuid"] == task_uuid] return series["question_label"].unique().tolist()
4cb71f70367850d7f0ea4ef16415c3664a9a0356
681,919
def cli_cosmosdb_gremlin_database_throughput_migrate(client, resource_group_name, account_name, database_name, ...
2b768c0e443c4ce4324e2a3bfc2f685693a08d99
681,922
def contrib_xref(contrib_tag, ref_type): """ Given a contrib tag, look for an xref tag of type ref_type directly inside the contrib tag """ aff_tags = [] for child_tag in contrib_tag: if ( child_tag and child_tag.name and child_tag.name == "xref" ...
767a0af81bdfdf1aba16bc835d96597085d7462d
681,923
from typing import List import random import itertools def get_model_nncf_cat() -> List: """Test helper for getting cartesian product of models and categories. Returns: List: Returns a combination of models with their nncf support for each category. """ model_support = [ ("padim", Fal...
bf3db7892f3d1a2243a4fb7f324092e9ffeba1ef
681,930
def get_hyperhdr_device_id(server_id: str, instance: int) -> str: """Get an id for a HyperHDR device/instance.""" return f"{server_id}_{instance}"
fd89cfaf3a6e921924bf84d8da5f5c13336cbae0
681,932
def strict_forall(l, f): """Takes an iterable of elements, and returns (True, None) if f applied to each element returns True. Otherwise it returns (False, e) where e is the first element for which f returns False. Arguments: - `l`: an iterable of elements - `f`: a function that applies...
dac9d7e7ca7499475aa8daba52a71185f2e47d5b
681,934
import pyclbr def is_handler_subclass(cls, classnames=("ViewHandler", "APIHandler")): """Determines if ``cls`` is indeed a subclass of ``classnames`` This function should only be used with ``cls`` from ``pyclbr.readmodule`` """ if isinstance(cls, pyclbr.Class): return is_handler_subclass(cls....
631ff0c02b005d8127d2b76c505cd032ce8a29bf
681,939
def create_label_column(row) -> str: """ Helper function to generate a new column which will be used to label the choropleth maps. Function used to label missing data (otherwise they will show up on the map as "-1 SEK"). Parameters ---------- row : Returns ------- str C...
b790eb3614859ecb557d8e76a7075d7c42fa841f
681,940
import pathlib def derive_filepath(filepath, append_string='', suffix=None, path=None): """Generate a file path based on the name and potentially path of the input file path. Parameters ---------- filepath: str of pathlib.Path Path to file. append_string: str String to app...
174c439a5285441fcca7902bfd1c542348f6fb3d
681,942
def gather_pages(pdfs: list) -> list: """ Creates a list of pages from a list of PDFs. Args: pdfs (list): List of PDFs to collate. Returns: list: List of pages from all passed PDFs. """ output = [] for pdf in pdfs: for page in pdf.pages: output.append(pa...
18d80f2204dc6fd7eca51c5f6e83af9ed8403405
681,943
import torch def create_alternating_binary_mask(features, even=True): """ Creates a binary mask of a given dimension which alternates its masking. :param features: Dimension of mask. :param even: If True, even values are assigned 1s, odd 0s. If False, vice versa. :return: Alternating binary mask ...
a402a697e7bc0ab6c4249a57e7e3c12ca9873fea
681,948
def parse_none(*args): """Return tuple of arguments excluding the ones being None.""" return tuple(arg if arg is not None else "" for arg in args)
42e4822d29c3f9c7a62b345f7b64f74b0c16d250
681,953
def remove_dupes(items): """ make sure no item appears twice in list i.e. filter for any duplicates """ clean = [] for i in items: if not i in clean: clean.append(i) return clean
85efbd27be24292454cbc95b6bc465ae9c9ae699
681,954
def wordList(fname = 'dictionaryWords.txt'): """Generate list of possible words from the passed file.""" wordlist = [] with open(fname, 'r') as fin: for word in fin: word = word.rstrip() ; wordlist.append(word) return wordlist
443cb77df3082829091bd9ba4907d969832c43a8
681,955
def calc_electrons_from_photons(photons, quantum_efficiency): """ Calculate the number of electrons generated by incident photons. Returns ------- int : no units, a number of electrons """ return int(photons * quantum_efficiency)
c9538d777bdf2d8ae133c16fdff2af281b940c4f
681,957
def _gutenberg_simple_parse(raw_content): """Clean a project Gunteberg file content.""" content = raw_content # *** START OF THIS PROJECT GUTENBERG EBOOK THE RED BADGE OF COURAGE *** starts = [ '*** START OF THIS PROJECT GUTENBERG EBOOK', '***START OF THE PROJECT GUTENBERG EBOOK', '*** START O...
7927711ef919d08d40e2fd89e77f24c999a6e9ac
681,958
def counter_mean(counter): """Takes the mean of a collections.Counter object (or dictionary).""" mean = 0. total = 0. for k, v in counter.items(): if k <= 0: k = 200 mean += k * v total += v return mean / total
83c943ac279e515d8e8d6040f906bcd4b0f1e9aa
681,960
import torch def quat_conj(Q): """ Returns the conjugate of the given quaternion Parameters ---------- Q : Tensor the (4,) or (N,4,) quaternion tensor Returns ------- Tensor the (4,) or (N,4,) conjugate quaternion tensor """ return Q * torch.tensor([-1, -1, -...
9e64ea036e25cdd5fc15db6e6e5d672884ed15bc
681,961
def xauth(auth): """Expand authentication token >>> xauth(None) >>> xauth(('user', 'pass')) ('user', 'pass') >>> xauth('user:pass') ('user', 'pass') >>> xauth('apikey') ('apikey', '') """ if auth is None or isinstance(auth, tuple): return auth else: u, _, p ...
3c8be7c7caf7c7442971f28f1892420ef97dcbaf
681,962
import json def _get_codes(error_response_json): """Get the list of error codes from an error response json""" if isinstance(error_response_json, str): error_response_json = json.loads(error_response_json) error_response_json = error_response_json.get("error") if error_response_json is None: ...
86e73be80735df115f1d24b5a45f091b62db4d42
681,965
def get_channel_id(data: dict) -> str: """Return channel id from payload""" channel = data['channel'] return channel
74b9ff9ad70bacd25d7ebe9ad93ef3cd827d627e
681,968
def documentize_sequence(seqs, tag, nt_seq): """This function converts raw nucleotide or amino acid sequences into documents that can be encoded with the Keras Tokenizer(). If a purification tag is supplied, it will be removed from the sequence document. """ # setup 'docs' for use with Tokenizer ...
21929282187c020038978f0d3ae7dacbf00d8ca2
681,972
def _alg(elt): """ Return the hashlib name of an Algorithm. Hopefully. :returns: None or string """ uri = elt.get('Algorithm', None) if uri is None: return None else: return uri
ef232715263c72a21ffeefe7105c1f033d5d88d1
681,973
def wavelength_range(ini_wl, last_wl, step=1, prefix=''): """Creates a range of wavelengths from initial to last, in a defined nanometers step.""" return [f'{prefix}{wl}' for wl in range(ini_wl, last_wl + 1, step)]
66e8ea5e53cb6dbe107e4ebcc046c5cc310a9b86
681,976
def make_peak(width:int, height:float=100) -> list: """ This is an accessory function that generates a parabolic peak of width and height given in argments. width: integer width of the peak height: float height of peak Returns: list of values of the peak """ rightSide = [-x**2 for x i...
6153399fc5916339d1733c68a60cfb166d48da45
681,978
def filter_inputs(db, measure_inputs, retry=False): """ Filter a measure_inputs batch based on saved db results Parameters ---------- db: Database database object measure_inputs: Array of MeasureInput measure_inputs as expected in measure_batch retry: bool whether to...
721b7283eb856a8aa0a9f29c6d2034d357f5f636
681,979
def consume_next_text(text_file): """Consumes the next text line from `text_file`.""" idx = None text = text_file.readline() if text: tokens = text.strip().split() idx = tokens[0] tokens.pop(0) text = " ".join(tokens) return idx, text
9a0595580a9fa8d6b5f480d218e88c508e5cd197
681,983
def osavi(b4, b8): """ Optimized Soil-Adjusted Vegetation Index \ (Rondeaux, Steven, and Baret, 1996). .. math:: OSAVI = 1.16 * b8 - (b4 / b8) + b4 + 0.16 :param b4: Red. :type b4: numpy.ndarray or float :param b8: NIR. :type b8: numpy.ndarray or float :returns OSAVI: Index value ...
082bc515e9347520454030fb3560ab2496531b2b
681,989
def _build_mix_args(mtrack, stem_indices, alternate_weights, alternate_files, additional_files): """Create lists of filepaths and weights to use in final mix. Parameters ---------- mtrack : Multitrack Multitrack object stem_indices : list stem indices to include ...
4b53b3b636c6d587d0efd756fe5d281929be0727
681,990
def is_str_int_float_bool(value): """Is value str, int, float, bool.""" return isinstance(value, (int, str, float))
9b62a9d89ea5d928db048cd56aa1ee5986fcc79a
681,992
from typing import Any from typing import Union def to_int_if_bool(value: Any) -> Union[int, Any]: """Transforms any boolean into an integer As booleans are not natively supported as a separate datatype in Redis True => 1 False => 0 Args: value (Union[bool,Any]): A boolean val...
984a97ad94b8500c1506c978bde6dcb792d0288c
681,996
import fnmatch def ExcludeFiles(filters, files): """Filter files based on exclusions lists Return a list of files which do not match any of the Unix shell-style wildcards provided, or return all the files if no filter is provided.""" if not filters: return files match = set() for file_filter in filte...
5a37efa7402da1c6465aea40000266bf1483e454
681,998
def get_object_name(file_name): """ Get object name from file name and add it to file YYYY/MM/dd/file """ return "{}/{}/{}/{}".format(file_name[4:8],file_name[8:10],file_name[10:12], file_name)
437c286b2c14712d80f68f8f7b3d36ccf279da81
682,000
def binto(b): """ Maps a bin index into a starting ray index. Inverse of "tobin(i)." """ return (4**b - 1) // 3
c6744be554f3cee439ed2923490af63387d95af7
682,001
def _list_at_index_or_none(ls, idx): """Return the element of a list at the given index if it exists, return None otherwise. Args: ls (list[object]): The target list idx (int): The target index Returns: Union[object,NoneType]: The element at the target index or None """ if ...
46651d93140b63bcb85b3794848921f8ea42d7bf
682,002
def find_result_node(desc, xml_tree): """ Returns the <result> node with a <desc> child matching the given text. Eg: if desc = "text to match", this function will find the following result node: <result> <desc>text to match</desc> </result> Parameters ----- x...
42ac4958a6b5c45e26a58d09b8e7dfa701f7678e
682,004
def sort_by_pitch(sounding_notes): """ Sort a list of notes by pitch Parameters ---------- sounding_notes : list List of `VSNote` instances Returns ------- list List of sounding notes sorted by pitch """ return sorted(sounding_notes, key=lambda x: x.pitch)
ddb2485a807608b91925ce84e6be08011803dd12
682,006
def check_clusters(labels_true_c, labels_pred_c): """ Check that labels_true_c and labels_pred_c have the same number of instances """ if len(labels_true_c) == 0: raise ValueError("labels_true_c must have at least one instance") if len(labels_pred_c) == 0: raise ValueError("labe...
0ddba08bfa28724143a284017dc905cb4c3210e1
682,013
def observed_species(counts): """Calculates number of distinct species.""" return (counts!=0).sum()
8b534640541b58afc2840322c781be3c9c60d024
682,014
import torch def to_numpy(tensor): """ Converting tensor to numpy. Args: tensor: torch.Tensor Returns: Tensor converted to numpy. """ if not isinstance(tensor, torch.Tensor): return tensor return tensor.detach().cpu().numpy()
029f43c3836a6b96931f1992d2a809dd87e1326d
682,017
def lox_to_hass(lox_val): """Convert the given Loxone (0.0-100.0) light level to HASS (0-255).""" return (lox_val / 100.0) * 255.0
f7c61b8605bf3cd15b24e244b6724334d1128ce4
682,020
def bits_to_int(bits: list, base: int = 2) -> int: """Converts a list of "bits" to an integer""" return int("".join(bits), base)
3cbf131607eb0de8d6b46bc4c88c1414ebf00029
682,022
def _date_proximity(cmp_date, date_interpreter=lambda x: x): """_date_proximity providers a comparator for an interable with an interpreter function. Used to find the closest item in a list. If two dates are equidistant return the most recent. :param cmp_date: date to compare list against :par...
2e04a0609e0d46e021f64e24d0d76ed60fd00c13
682,024
def rescale(ys, ymin=0, ymax=1): """ Return rescaling parameters given a list of values, and a new minimum and maximum. """ bounds = min(ys), max(ys) ys_range = bounds[1] - bounds[0] new_range = ymax - ymin ys_mid = sum(bounds)*.5 new_mid = sum([ymax, ymin])*.5 scale = float(new_range)...
f3f11b4e8f964dc58b1efc8d6eb8895236ddf066
682,028
from typing import List import shlex def str_command(args: List[str]) -> str: """ Return a string representing the shell command and its arguments. :param args: Shell command and its arguments :return: String representation thereof """ res = [] for arg in args: if "\n" in arg: ...
4820c23472bbff0990932e25751e84ec4f827be4
682,029
def fib_memo(n, memo=None): """ The standard recursive definition of the Fibonacci sequence to find a single Fibonacci number but improved using a memoization technique to minimize the number of recursive calls. It runs in O(n) time with O(n) space complexity. """ if not isinstance(n, int): ...
9222e6d814dea2d6a4af5799080ba5569e93c893
682,032
import logging def get_logger(name): """ Proxy to the logging.getLogger method. """ return logging.getLogger(name)
615e8c281f3c30f69339eba4c4ac6b28a7b89b09
682,038