content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def non_neg(x): """ return 0 if x is negative, else return x """ if x < 0: return 0 else: return x
c703b92a9481b44364ce98a64c940674da35f48d
624,885
import platform def is_windows(): """Determines if the system is native Windows (i.e. not Cygwin).""" return platform.uname()[0] == 'Windows'
ace82b2b6bf780105078df88c886767dd9e579eb
624,886
from typing import Iterable def getFileNameList(dir:Iterable, splitSequences = False, extraInformation = False, returnDirs=True, returnHidden=False): """ getFileNameList( dir, splitSequences = False, extraInformation = False, returnDirs=True, returnHidden=False ) -> str @param dir the directory to get seq...
fc26bf2f30317e52d8de2de28b81d28dab0f03a7
624,887
import glob def get_file_paths_from_glob_patterns(glob_patterns): """ Return a set of files matching the given list of glob patterns (for example ["./test.sql", "./other_tables/*.sql"]) """ file_paths = set() for glob_pattern in glob_patterns: file_paths |= set(glob.glob(glob_pattern)) ...
2ad59e698d08e550b508d7f606e2f48809c49a4b
624,889
def reduce_reflex_angle_deg(angle): """ Given an angle in degrees, normalises in [-179, 180] """ new_angle = angle % 360 if new_angle > 180: new_angle -= 360 return new_angle
10737eba3e6feda3788ea57df676146d65214fd6
624,890
def func(foo, bar): """Return the args.""" return foo, bar
7fe40009d89fbe63ee7f28f32de36e1d64e7ad9b
624,891
def pct_to_kelvin(pct, max_k=6500, min_k=2700): """Convert percent to kelvin.""" kelvin = ((max_k - min_k) * pct / 100) + min_k return kelvin
860a9716733249f3a4ee6076db5fad4926befc04
624,892
def manymissing(self,a=0.9,axis = 0): """ identify columns of a dataframe with many missing values ( >= a), if axis = 1 row either - the output is a pandas index """ if axis == 0: self = self.nacount(axis = 0) if axis == 1: self = self.nacount(axis = 1) return self[self['Napercen...
c2cfb994b44703968cd53b718d3e8c8ba1e56c1d
624,893
def es_par(numero: int) -> bool: """Determina si un número es par o no. :param numero: Número a evaluar. :type numero: int :return: True si el número es par, False si no lo es. :rtype: bool """ return numero % 2 == 0
6beebd3b895c35db5756ee6f6908890579961cdf
624,894
import torch def KLDIVloss(output, target, criterion, V, D): """ output (batch, vocab_size) target (batch,) criterion (nn.KLDIVLoss) V (vocab_size, k) D (vocab_size, k) """ ## (batch, k) index in vocab_size dimension ## k-nearest neighbors for target indices = torch.index_selec...
2778f681cdc95b542d0359cd1e6a0d719fbea4be
624,895
import os def SlashUnescapePackageName(response, unused_args): """Unescapes slashes in package name from ListPackagesResponse.""" ret = [] for ver in response: ver.name = os.path.basename(ver.name) ver.name = ver.name.replace("%2F", "/") ret.append(ver) return ret
47d2a93a347b3fa47c06d0c457a9c279f0f6ce11
624,896
import re def get_step_from_checkpoint_path(checkpoint_path): """Returns the global step for the checkpoint at `checkpoint_path`. **Note**: This function works for checkpoints that are saved in the TF format only. Assumes `checkpoint_path` corresponds to a file which contains the substring model.ckpt-{g...
d0b7bafe211cb0fd118bacd12b7974f0610d33c8
624,897
def merge_dictionaries(a, b): """ merging two dictionaries """ merged = {**a, **b} return merged
60abd66b0c63ed56edf759bf105d4aecfb558b9f
624,899
import hashlib import os def md5sum(fname): """ 计算文件的MD5值""" def read_chunks(fh): fh.seek(0) chunk = fh.read(8096) while chunk: yield chunk chunk = fh.read(8096) else: # 最后要将游标放回文件开头 fh.seek(0) m = hashlib.md5() if isinstance(fname,...
af63e47cc10edab249a7ec896dda5e274c74e331
624,900
def make_regalur_image(img, size=(128, 128)): """我们有必要把所有的图片都统一到特别的规格,这里选择128x128的分辨率。""" return img.resize(size).convert('RGB')
84713a322abf6d5536cee96cbb83df0609cf0015
624,901
def make_portfolio(df, date_level='date'): """ Make a portfolio of assets by grouping by date and summing all columns. Note: the caller is responsible for making sure the dates line up across assets and handling when they don't. """ return ( df .groupby(level=date_level) ...
000b543d712c6074a2d447d6ab66071a85d0c1e4
624,902
import os def get_code_scratch_file(s3_scratch_prefix: str, tar_hash: str) -> str: """ Returns s3 scratch path for a code package tar file. """ return os.path.join(s3_scratch_prefix, "code", tar_hash + ".tar.gz")
79c50a06e0b1e565d0bcae91e19170943e64ddeb
624,903
import torch def torch_max(output): """ :param output: batch * seq_len * label_num :return: """ _, arg_max = torch.max(output, dim=2) label = arg_max.view(arg_max.size(0) * arg_max.size(1)).cpu().tolist() return label
a62823a41c86f9c7e18acb88bebc70091d88301c
624,904
def _get_numbers_distance(num1, num2, max_=1): """ Get the distance of 2 numbers. The output is a number between 0 to the max. The reason is the When max is returned means the 2 numbers are really far, and 0 means they are equal. """ if num1 == num2: return 0 if not isinstance(num1, ...
87120a6b263c2e5b8bce25b0790258777e34a96d
624,905
def mie(r, eps, sig, m=12, n=6): """Mie pair potential. """ prefactor = (m / (m - n)) * (m / n) ** (n / (m - n)) return prefactor * eps * ((sig / r) ** m - (sig / r) ** n)
d9c9349b8b5e4f0544bd56a3000eeb12bf2508d0
624,906
import argparse def parse_args(args): """Parse training options user can specify in command line. Returns ------- argparse.Namespace the output parser object """ parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="Parse ...
0662161876574511e235f18322eb44f925123321
624,907
import json def read_config_file(config_file): """ Read a json configuration file :param config_file: path to a json file containing the algorithm parameters :type config_file: string :return: the configuration :rtype: dict """ with open(config_file, "r") as file: user_configu...
136a40ac0d64027387be863727d2566f4896d0b7
624,908
def is_safe_to_wait(lock_expiration, reveal_timeout, block_number): """ True if there are more than enough blocks to safely settle on chain and waiting is safe. """ # reveal timeout will not ever be larger than the lock_expiration otherwise # the expected block_number is negative assert block_nu...
7c56d94623f1268ba5858509112952bb374863c9
624,909
def PrintBox(loc, height, width, style='r-'): """A utility function to help visualizing boxes.""" xmin, ymin, xmax, ymax = loc[0] * width, loc[1] * height, loc[2] * width, loc[3] * height #pyplot.plot([xmin, xmax, xmax, xmin, xmin], [ymin, ymin, ymax, ymax, ymin], style) return [xmin, ymin, xmax, ymax]
4f1b9d40b26c21fd793f7ef9ca6922162723e13c
624,910
def _transpose(tree_list, width): """Transposes a tree list""" transposed = ["" for _ in range(width)] for row in tree_list: for idx, symbol in enumerate(row): transposed[idx] += symbol return transposed
c52a661063fef5d02ea43b604b8e4aacfdb129e8
624,911
def say_hello(): """Say hello""" return "Hello World"
c1cffcbc31f37abcb65f4f2e9b580c46b47ff611
624,912
from typing import OrderedDict def dictify(od): """Recursively replace OrderedDict with dict""" if isinstance(od, OrderedDict): return dict((k, dictify(v)) for k, v in od.items()) else: return od
886fc727dba02f9029945d5efa947d7573c3df19
624,913
def generate_list(iterable_a, iterable_b): """Return a list of a+b combinations""" result = [] for iter_a in iterable_a: for iter_b in iterable_b: result.append(iter_a+iter_b) return result
7056486507a4ac5810de42e58f5b7822a905de54
624,915
import torch def _roll_by_shifts(src: torch.Tensor, shifts: torch.LongTensor): """Roll tensor with different shifts for each row. Note: We assume the src is a 3 dimensions tensor and roll the last dimension. Example: >>> src = torch.arange(15).reshape((1,3,5)) >>> src tensor([[[...
d919ef903bda42897781efc280eb833d3a6de162
624,916
import numpy as np def moving_average(interval, windowsize): """ This is a smooth function interval is the original data windowsize can set 3~10 """ window = np.ones(int(windowsize)) / float(windowsize) re = np.convolve(interval, window, 'same') return re
05c7523e4f9636d1bd4a1ae5bb0c5ec8937f90b4
624,918
def __parse_args(cam_c): """Arrange class init params from conf file. Returns: a dict with values.""" user = None pswd = None name = None address = "{address}:{port}".format(**cam_c) if "user" in cam_c: user = cam_c["user"] if "pswd" in cam_c: pswd = cam_c["pswd"]...
6e9d7655082ce07ec72f718161cb090148f3c09e
624,919
def meta_cache(suffix): """real_length, real_count用のキャッシュデコレータ""" def cache(func): def cached(self, instance): cache_name = '_{}_{}'.format(self.name, suffix) caches = instance.__dict__ if cache_name in caches: return caches[cache_name] re...
37e22573853716fbe9c29c0c3dc37f13e32a6125
624,921
import os import glob def image_full_filenames_in_directory(directory): """ Return a list with full filenames of all images in the input directory, sorted in lexicographical order. Inputs: |directory|: path to input directory. """ image_format = '.png' image_filename_pattern = os.path...
81e61ed8838c488c241ad674e82657cc8c83c076
624,922
def alignto(alignment_value: int, bitposition: int) -> int: """ Aligns the bit size to the given alignment value. :param alignment_value: Value to align. :param bitposition: Current bit position where to apply alignment. :returns: Aligned bit position. """ if bitposition <= 0 or alignment_...
651d3d26c1f62192a891b3afd7e4a923d31c5aa2
624,923
import random def sqrt_mod_prime(a, p): """Return the square root of a modulo the prime p. Behaviour is undefined if a is not a quadratic residue mod p.""" # Algorithm from http://www.mersennewiki.org/index.php/Modular_Square_Root assert a < p #assert is_probable_prime(p) if a == 0: re...
679574a9b0f9ba9f4417ac84745f5fe7f4588f1f
624,924
def get_digit_b(number, digit): """ Given a number, returns the digit in the specified position, for an out of range digit returns 0 """ return number % 10**digit // 10**(digit-1)
2b444e1270a58bc3dd20525eb428f37ce56a655a
624,925
def entry_exit_rates(r_nuc = 2.5, r_cell = 6.0, D = 1.0): """ Computes the exit and entry rates out from and in to the nucleus. """ k_entry = D * (r_cell**3 - r_nuc**3) / (r_nuc**2*r_cell**3/3 - 3*r_cell**5/5 + r_cell**6/(3*r_nuc) - r_nuc**5/15) k_exit = D * r_nuc**2 / 6 return (k_entry, k...
dc51e30d1d1927c41ddd135254b7b774449264a4
624,927
def _to_np_mode(mode): """Convert padding modes from `ndi.correlate` to `np.pad`.""" mode_translation_dict = dict(nearest='edge', reflect='symmetric', mirror='reflect') if mode in mode_translation_dict: mode = mode_translation_dict[mode] return mode
d568cbb7624c9eb5a8a8939480aeaa2194d91bdf
624,928
def get_abc(V, E, dE, ddE): """ Given the volume, energy, energy first derivative and energy second derivative, return the a,b,c coefficients of a parabola E = a*V^2 + b*V + c """ a = ddE / 2. b = dE - ddE * V c = E - V * dE + V ** 2 * ddE / 2. return a, b, c
b415ef889c6e912842760b5d100f99786c202c20
624,929
import math def compute_r(x, y): """ Computes the Coefficient of Co-relation using Pearson's method """ n = len(x) numerator = n * ((x * y).sum()) - (x.sum() * y.sum()) denominator = (n * (x ** 2).sum()) - x.sum() ** 2 denominator *= (n * (y ** 2).sum()) - y.sum() ** 2 denominator = ma...
ed9e3f683e172389b09ee3651cd4eff4e483f20c
624,930
def validate_pre_plugin_load(): """Checks if the configuration variables are valid. If the configuration is invalid then the method will return an error message. If all is OK then it will return None. """ message = None return message
2f0acf977e63751db6c4b9d424d86ac8ec0c51c9
624,931
def compare_range(a, b): """ >>> compare_range(1, "-10") True >>> compare_range(1, "10-") False >>> compare_range(20, "-10") False >>> compare_range(1, "10-20") False >>> compare_range(1.0, "0-1.0") True >>> compare_range(100, "-") True >>> compare_range("b", "a-z...
89b9a7a01ea110d48c96f7aa4da15f47de5e7350
624,932
def clean_url(url, base_url, current_url): """Naive function to clean different urls.""" if url.endswith(":"): url = url.rstrip(":") if url.startswith('#') or url.startswith('tel:') or url.startswith('mailto:') or url.startswith('data:'): return current_url if url.startswith('http'): ...
d368cc39897682b52de9c533474ab37ebd2efda4
624,933
from functools import reduce import operator def product(seq, default=1): """like built-in sum()""" if len(seq)==0: return default return reduce(operator.mul, seq)
0887875403e38b81cea39bc48d6b5869f9ba72e9
624,934
def combine_address(source): """ Reformat address to combine them into one cell with multiple line Also show/hide optional questions """ tags = [] first_column = '<tr><td width="75%" style="padding-right: 5%">' second_column = '<td width="25%">' end_tag = '</td></tr>' addres...
1ffd9147dd4e2309fd5907eae8ca5cc2f3e7d9cb
624,935
from typing import Union from pathlib import Path import hashlib def compute_sha256(filename: Union[Path, str]): """Return SHA256 checksum of a file.""" with open(filename, 'rb') as f: return hashlib.sha256(f.read()).hexdigest()
11831d04e7ec00886bc1ff497c836ca547f041ba
624,936
from typing import Dict from typing import Any import os import json def _get_step_config() -> Dict[str, Any]: """Get the configuration from the environment. This variable will be passed to us by the Mahiru runtime. It contains a dictionary with items 'inputs' and 'outputs', both of which are diction...
d0bcdca3f1591e9c08eb828c1f01474b5b059424
624,937
def size_to_str(bytes): # real signature unknown; restored from __doc__ """ size_to_str(bytes: int) -> str Return a string describing the size in a human-readable manner using SI prefix and base-10 units, e.g. '1k' for 1000, '1M' for 1000000, etc. """ return ""
7604da655c8b1c3d974d7c440ba1b75472ffb988
624,938
import subprocess def DecodeFlacToWav(input_bytes): """Decode a FLAC byte string to WAV.""" p = subprocess.Popen( ['sox', '-t', 'flac', '-', '-t', 'wav', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate(input=input_bytes) assert p.re...
b139108d07db8fae3d49884bc8f484adb93c2e66
624,939
import time def get_lattice_metrics(): """ """ def compute_metrics(eval_preds): """ """ Achilles = time.time() sources, preds, labels = eval_preds# (num, length) np.array tp, fp, fn = 0, 0, 0 sent_p, sent_n = 0, 0 for i in range(len(sources...
5b78b855c1f00ad3a21ce0571567241a453dc72a
624,940
def is_int_even_v01(num): """ Use the modulo operator to evaluate whether an integer provided by the caller is even or odd, returning either True or False. Parameters: num (int): the integer to be evaluated. Returns: is_even (boolean): True or False depending on the modulo check ...
285f7ead88f3e8ba5e0ff62d52412f0023a9add3
624,941
import torch def get_cuda_memory_used(device): """ Get the free memory info of device. Notice that for CPU, this function will return 1/N of the total free memory, where N is the world size. """ ret = torch.cuda.memory_allocated() # get the peak memory to report correct data, so reset the ...
bf757ff6f3242c83522daa306c240e3cd4bc31fe
624,942
import json def load_templates_dict() -> dict: """Loads template strings dict from 'template_strings.json'. Should be hierarchy of dict->dict>values based on context. Important: Curly braces '{}' in template strings will be replaced with corresponding values using str.format For instance { ...
8c66711bd83ccd84da0735028aed15648a2b5d3b
624,943
def coord_map_inverse_2d(coord, x_step = 1, x_shift = 0, y_step = 1, y_shift = 0, mode = 'linear'): """ Maps input coordinates to output coordinates given parameters step (m) and shift (b) for inverse linear transformation x = (y - b) / m for each coordinate axis. Intended to...
e5dd608128cff32e3a833b71c34a137d07ef587c
624,944
from functools import reduce def _sum_sequence(seq): """ sums up a sequence """ def _add(x, y): return x + y return reduce(_add, seq, 0)
c392c1167f08c46c183d92d5e22ccc1c4547c9d7
624,945
def _get_high_quality_solutions(all_results, best_result, offset): """Filters solutions obtained from several runs to these with low approximation error.""" high_quality_solutions_params = [] best_objective_value = best_result['eigenvalue'].real + offset allowed_approximation_error = 0.01 # 1% approxim...
00acf1389161a49507660a0dcc860ae96b5c22ae
624,946
def _get_loc_item_node(loc_json: dict, key_to_find: str) -> dict: """ Return the item node of interest within the LOC results """ for node in loc_json: if node.get('@id', '') == key_to_find: return node return {}
8956065f74ea70470a42fbc5a89418b4ce8dee44
624,947
import os def list_files(dataset_path): """List files in a dataset directory with the format of the Medical Segmentation Decathlon. Parameters: dataset_path (str): path to a dataset Returns: lst(str): full file names """ train_img_path = os.path.join(dataset_path, 'imagesTr') fil...
cbee921ec774da7fd31203ca60992d8ead53d386
624,948
def in_between_points_on_list(points_list, divisions): """ This takes a list of numerical values (floats or ints) and a list of divisions of ints of (points_list) - 1. This method will then uses the number of sub divisions within the list of divisions to add new points to the points list where you have ...
b1d002af6c7dc37964a6d43615d26134bcd61a5f
624,949
def transform_package_responses(data, submission_id, long_field_names_map): """ Funtion to format flow results package data to flattened JSON for each submission and return a list of dictionaries. """ transformed_data = {"submission_uuid": submission_id} for i in data: transformed_data[...
c0e27a97ab76b3efe0f781ea18626c8917bf64e2
624,950
def fwhm(lambda_, d, alpha1=1.3): """ The nominal Full Width Half Maximum (FWHM) of a LOFAR Station beam. :param lambda_: wavelength in meters :param d: station diameter. :param alpha1: depends on the tapering intrinsic to the layout of the station, and any additional tapering which...
4dfe8718af7cf9912b31fdd55d6b6f4f8a131a51
624,951
def _to_yaml_defs(wrapped, instance, args, kwargs): """ New in v17 public decorator for yaml generator """ return wrapped(*args, **kwargs)
da38af047f3a265c237640b025e71941ec5dcb5f
624,952
import os def set_project_dir(): """ Looks for a .tensorforce.json file in the cwd and then all parent dirs (until root is hit) and sets the cwd to the first dir found. """ path = "" while True: if os.path.isfile(path + ".tensorforce.json"): if path != "": o...
5886f003adfa8f4a24cba3cadaf1bc92ac091cee
624,953
import calendar def datetime_to_unixtime(dt_obj): """Converts datetime timestamp into a unix timestamp (as an int) Args: dt_obj (datetime): a datetime object Returns: A unix timestamp as an int """ return calendar.timegm(dt_obj.utctimetuple())
1b29a12470541623f8e8e6e51670d2b2d39bd288
624,954
def user_warnings(): """No warnings exist for this extension. Anything you want to warn the user about, such as security risks in processing untrusted markdown, should go here. """ return []
a9413846414ad8dcb75a07c2f02dd0d1b8e5cdd0
624,955
def normalize(pair): """Convert the (count, species) pair into a normalized list of atomic and mass numbers. """ o_mass, o_atomic = pair if o_mass < 0: return [(o_mass, o_atomic)] if o_atomic == 0: return [(1, 0) for _ in range(o_mass)] if o_mass == o_atomic: return [...
22b09a836d3f971f7f6f10241a8bb96b9ab046ee
624,956
import os def find_subdir(input_dir): """Return the relative path of a directory Used by test fixtures to find resource files regardless of where pytests is from from (project_root, project_root/tests, etc). This didn't matter when i was just running pytests directly, but tox runs form teh project di...
fac136cc9eaa0e281fc8b6253980bd7dcb45168b
624,958
import re def is_palindrome(word): """Return if word is palindrome, 'madam' would be one. Case insensitive, so Madam is valid too. It should work for phrases too so strip all but alphanumeric chars. So "No 'x' in 'Nixon'" should pass (see tests for more)""" # [^0-9a-zA-Z]+ equals \W+ ...
a51687586118390464ba39d3df4173b54aaa62ee
624,959
def atomic_request(): """Returns an atomic Postman request dictionary.""" request = { "name": "test request", "request": { "method": "GET", "header": [], "url": { "raw": "{{target_url}}endpoint", "host": ["{{target_url}}endpoin...
556cc3970d80a6c5d6aff6fdd1cbd8d6979348e5
624,960
from pathlib import Path def localize_path(path_string): """Localize path for Windows, Unix, i.e. / or \ Args: path_string (str): path using / Returns: str: path depending on OS """ return str(Path(path_string))
71e5c3eaabfcad88001fba52914cf14aa890e34e
624,961
def merged_dict(itr): """ Create a merged dict of dict (of dict) based on input. Input is an iteratable of (keys, value). Return value is root dictionary Keys are successive dictionaries indicies. For example: (('a', 'b', 'c'), 1) would set: output['a']['b']['c'] = 1 This function...
eea694bb55f8af80d3b5018ea2b6201c20fffb41
624,962
def review_rating(review): """Return the number of stars given by the review, which is a floating point number between 1 and 5.""" return review[1]
191ea83d852dea149ba8a360695707080ca66fee
624,963
import math def calculate_speed(actor): """ Method to calculate the velocity of a actor """ speed_squared = actor.get_velocity().x ** 2 speed_squared += actor.get_velocity().y ** 2 speed_squared += actor.get_velocity().z ** 2 return math.sqrt(speed_squared)
4a2c045b6e3f0a6954e9abb0e841cecc398d4730
624,964
import codecs def read_vocabulary(vocab_inpath): """ Read a vocabulary file with one word per line. Args: vocab_inpath (str): Path to vocabulary file. Returns: set: Set of all words in vocabulary. """ vocab = set() with codecs.open(vocab_inpath, 'rb', 'utf-8') as vocab_in...
488098be0ae0ae282b04870ae929f2293d4f8aef
624,965
import time def is_entry_added_to_table(switch_inst, table_name, srch_params, timeout=1, expect_count=1, exist=True): """Check if entry with specified fields values is added to table Args: switch_inst(object): Switch instance to work with table_name(str): The name of table to perform search...
295f6de3b122592b1c96083ed23b648277825102
624,966
def probability_sum(probability, token_frequency, n): """Assigns score to document based on summation of probabilities. Args: probability (float): Previously calculated probability. token_frequency (float): Number of appearances of token in text. n (int): Length of text. Returns: ...
a86e8a66019e297805d4251789f71cd9140012ab
624,967
def FieldEncode(fn): """Encodes the field value using the specified function. If None, returns default value. """ def _Convert(value): if value is None: return None return fn(value) return _Convert
c3c0f7810b1ce3a3d3510a1e421bc9516287efbe
624,968
def get_meta_params(meta): """ Parse the metadata selections for querying """ duration = meta.get('duration', ['any']) views = meta.get('views', ['any']) upload = meta.get('upload', ['any']) meta_new = {} # Figure out the max duration requested if len(duration) == 3 or 'any' in duration: ...
ebed5fe5fe95226fdf2773babd71220764da932e
624,969
def extract_goal(goal_map): """Returns the goal location.""" for o in range(goal_map.shape[0]): for y in range(goal_map.shape[1]): for x in range(goal_map.shape[2]): if goal_map[o][y][x] == 1.: return (o, y, x) assert False
1642557163f7de95f76e0ffd2189ad8bbcd4f602
624,970
def arqexiste(arq): """ -> Verifica se existe o arquivo arq :param arq: Nome do arquivo a ser testado. :return: retorna True se o arquivo for encontrado, caso contrário False """ try: a = open(arq) except FileNotFoundError: # O arquivo não foi encontrado print('Arquivo não encontrado!') return False els...
0749a3a169e4ce9552c189fb81dae99599697f51
624,971
def calc_pid(seq1, seq2): """ Calculates the percentage ID (still as a decimal) between two sequences. Parameters ---------- seq1: str seq2: str Returns ------- pid: float """ alnlen = len(seq1) identical = 0 for i in range(0, len(seq1)): if seq1[i].isal...
31a82205b9cffa5ec7f566690ca17df635da640f
624,972
def mk_rank(rank, default_rank, level): """Create a rank from a result rank, a default rank, and a level level can be one of: "pass", "warning", "error", "open", "notApplicable", or "note". These don't correspond very well to traditional scoring, but they're all we've got. Note that the Sarif "rank" i...
339f92c186a69790cf2a5052525faf072bcd02fa
624,973
def swap(items, a, b): """swap between list/dict items values""" items[a], items[b] = items[b], items[a] return items
9d355ac35eb1c80ea0491dbc0a856a4fabb38301
624,974
def get_text_colour_analytics_sentiment(score): """ Returns RGB code text to represent the strength of negative or positive sentiment :param score: Sentiment score in range +/- 5.0 :return: Background RGB colour text string to use in sentiment text """ # Get our score into the range [0..4], whi...
c695ee55c97c3318c837390a1c7d505d621247d9
624,976
def _remove_prefix(names, graph_name): """ variables name (full name space) is too long, shorten the name by removing the prefix ```graph_name``` """ if isinstance(names, list): converted_names = [] for name in names: if name.startswith(graph_name): conver...
765d6a271dbf19f70649b96d18873ee351178d58
624,977
def duplicate_package_status(original_status, override_version=None): """ Given a status generated by parse_package_status(), duplicate it for a different source package. :param original_status: the status to clone :param override_version: the cloned package version (different) :return: new status (...
2deed6ac018b6f97ddcf4423f8b30fc40996f323
624,980
def is_private(obj): """Return True if object is private.""" if obj is not None: return isinstance(obj, str) and obj.startswith('_')
648c0b765c4f96f7687d97a6ec18779778642648
624,981
def get_board_as_string(game): """ Returns a string representation of the game board in the current state. """ board_str = """ {} | {} | {} -------------- {} | {} | {} -------------- {} | {} | {} """ return board_str.format(game["board"][0][0], game["board"][0][1],game["board"][0][2],ga...
02cdbd8c3867dfee17a39a97855b38ce84bd2ed2
624,982
import re def check_convert_chr_id(chr_id): """ Check and convert chromosome IDs to format: chr1, chr2, chrX, ... If chromosome IDs like 1,2,X, .. given, convert to chr1, chr2, chrX .. Return False if given chr_id not standard and not convertable. Filter out scaffold IDs like: GL000009.2,...
a09d8c49a5c53332bea9d3cdb2e107d5a65241e7
624,983
def _check_n_components(n_features, n_components): """Checks that n_components is less than n_features and deal with the None case""" if n_components is None: return n_features if 0 < n_components <= n_features: return n_components raise ValueError('Invalid n_components, must be in [1, %d]' % n_featur...
fb8d8bad0c2cecb5879477ab3c4c95606f85c9de
624,984
import numpy def getSpecialThreshold(cleft, segments, fraction, groups=None, identifiers=None): """ Return threshold closest to the Arguments: - cleft: (Groups) """ # get groups if groups is None: groups = list(cleft.keys()) # loop over groups ...
1a4e10dc22fe778abd534b3dd805463f79051a97
624,985
import collections def merge(qrels, run, queries): """Merge qrels and runs into a single dict of key: query, value: tuple(relevant_doc_ids, candidate_doc_ids)""" data = collections.OrderedDict() for query_id, candidate_doc_ids in run.items(): query = queries[query_id] relevant_doc_ids = set() if ...
59d88262ba69c8dbf71f5c92b114cb5cd9b8bfc9
624,986
def vpc_endpoint_type(endpoint_type): """ Property: VPCEndpoint.VpcEndpointType """ valid_types = ["Interface", "Gateway", "GatewayLoadBalancer"] if endpoint_type not in valid_types: raise ValueError( 'VpcEndpointType must be one of: "%s"' % (", ".join(valid_types)) ) ...
cf0653f9856529a89c94b3dba2a7abc9b939b3c5
624,988
import csv def get_contacts(filename): """A csv import dictionary function. Args: filename (csv): A comma delimited file. Returns: Dict: Keyed by email with first and last name, company, and category. Examples: >>> {'sjohns@aol.com': {'lname': 'Johns', ...
eee260de7dcf318e38cae8cbecc1a73310005024
624,989
def poisson_pipeline(infile, outfile, depth=8): """Makes a dictionary describing PDAL pipeline for generating Poisson surface mesh. Parameters ----------- infile : str, path to file input file to be converted into a mesh outfile : str, path to file output file for storing Poisso...
5a7ba19f815e3bfc5729cf6b02ae150621230f2a
624,990
def gpsfix2str(fix: int) -> str: """ Convert GPS fix integer to descriptive string. :param int fix: GPS fix type (0-5) :return: GPS fix type as string :rtype: str """ if fix == 5: fixs = "TIME ONLY" elif fix == 4: fixs = "GPS + DR" elif fix == 3: fixs = "3D...
5a422dec590e627edef641b2990c1c856c3f4c54
624,991
def supports_transactions(con): """A convenience function which will work across multiple django versions that checks whether or not a connection supports transactions.""" features = con.features vendor = con.vendor if features.supports_transactions: if vendor == 'mysql': engine ...
8f6bee12e023600d0da2ea0ab9f118db8c8c3710
624,992
def _try_conversion(val, to_type, verbose=True): """Try to convert `val` to type `to_type` by calling `to_type`.__call__. Returns unaltered `val` if conversion fails. Refuses to try conversions to types not in `only_try` """ if verbose: print("_try_conversion called with val " + ...
ff8a7f87b9b1781f28b0374930ccbff2e20a446a
624,993
def _get_exchange_key_ntlm_v2(session_base_key): """ [MS-NLMP] v28.0 2016-07-14 4.3.5.1 KXKEY Calculates the Key Exchange Key for NTLMv2 authentication. Used for signing and sealing messages. According to docs, 'If NTLM v2 is used, KeyExchangeKey MUST be set to the given 128-bit SessionBaseKey ...
e19a1b31b1a0ef638c8dd79dca476b4a3dca9366
624,994
def process_path(module_path): """ Method to obtain module and class_name from a module path Args: module_path(String): path in the format module.class_name Returns: tuple containing class_name and module """ if module_path == 'numpy.ndarray': return 'StorageNumpy', 'hec...
9e29b77351984d5a49562b179c52fe66e888acef
624,995