content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def request_class_attribute(req, attr): """ Grab `attr` attribute from class of `req`. """ return getattr(getattr(req, "cls"), attr)
13a5ebd2e1f8241a076de91bc28237fc9b38855f
94,237
def parse_version(v): """ Parses a version string into its component parts. String is expected to follow the pattern "0.1.1.dev0", which would be parsed into (0, 1, 1, 0). The first two components are required. The third is set to 0 if missing, and the fourth to None. Parameters ---------- v : str Version string using syntax described above. Returns ------- tuple with format (int, int, int, int or None) """ v4 = None if 'dev' in v: v4 = int(v.split('dev')[1]) v = v.split('dev')[0] # 0.1.dev0 -> 0.1. if (v[-1] == '.'): v = v[:-1] # 0.1. -> 0.1 v = v.split('.') v3 = 0 if (len(v) == 3): v3 = int(v[2]) v2 = int(v[1]) v1 = int(v[0]) return (v1, v2, v3, v4)
3dd02dc758ca519a4c22e98de9c9f62c4a3c7d6a
94,240
def extract_var(text, varname): """ Return the a single line attribute with variable named ``varname `` found in the ``text`` APKBUILD or an empty string. For example:: >>> t=''' ... pkgname=sqlite-tcl ... pkgrel=0 ... ''' >>> extract_var(t, 'pkgname') 'sqlite-tcl' """ try: variable = [ l for l in text.splitlines(False) if l.startswith(f'{varname}=') ][0] except Exception: variable = '' _, _, value = variable.partition('=') return value
60bcf8c772f42139f403c511b7cc2f21574ff1e7
94,243
from pathlib import Path import json def load_json_fixture(filename): """Load a fixture.""" path = Path(Path(__file__).parent.joinpath("fixtures"), filename) return json.loads(path.read_text())
1ebf5052c05e92d3d72ed499224b3b2b12cc97cc
94,246
def add_xy(ndarray, xy_pair): """ Add (x,y) to ndarray. Array can be of dimentsion N,2 or 2,N """ try: return ndarray + xy_pair except ValueError: return (ndarray.T + xy_pair).T
36ff5d3f36bf061146e07933f371ec848212a83f
94,247
def get_user_display(user) -> str: """ Display the name of the user. :param user: A ``User`` model instance. :type user: :class:`~django.contrib.auth.models.User` :return: The user's full name if available, otherwise the username. """ full_name = user.get_full_name() return full_name if len(full_name.strip()) else user.username
2721ce541647c1715d143f28ced20cd81f796d4f
94,252
def __isFloatType__(obj): """ Returns true if the obj is a float """ return isinstance(obj, float)
8b5172199dc5b3b75335f810fbd313a4f6529f95
94,260
def check_unit_compatibility(spec, region): """ Checks if the unit of a region is compatible with the unit of the spectral axis of the spectrum object. Parameters ---------- spec : :class:`specutils.Spectrum1D` The spectrum object with which to check compatibility. region : :class:`specutils.SpectralRegion` The region object with which to check compatibility. Returns ------- bool Whether or not units are compatible. """ spec_unit = spec.spectral_axis.unit if region.lower is not None: region_unit = region.lower.unit elif region.upper is not None: region_unit = region.upper.unit else: return False return spec_unit.is_equivalent(region_unit)
8d516987361adcd1237b472a210e7f996c2c5d5e
94,266
def replace_face(image, gan_preds, locations): """ Replace the face in the image with the generated predictions. Args: image (numpy.ndarray): Image to be replaced. gan_preds (numpy.ndarray): Predictions from the GAN. locations (list): Locations of the face in the image. Returns: numpy.ndarray: Image with replaced face. """ for (box, pred) in zip(locations, gan_preds): (startX, startY, endX, endY) = box image[startY:endY, startX:endX] = pred return image
a8a6c51f980f8f6f4d54c76c7791470275bb0b4e
94,269
from datetime import datetime def convert_date(date: str) -> datetime: """Convert a string representing a date and time to a datetime object""" date_object = datetime.strptime(date, '%Y-%m-%d %H:%M:%S') return date_object
7345a4afab18313aefe113524ec43c6e84129135
94,277
def read_file(name): """Given the path/nname of the file, return the list of the weights of the nodes. """ file = open(name,'r') data = file.readlines() weights = [0]*(int(data[0])+1) for index,line in enumerate(data[1:]): item = line.split() weights[index+1] = int(item[0]) return weights
a783ffbc6f2c77336e1c3435944eabdbc6eb6c9a
94,285
def _count_number_of_children_recursively(event): """Recursively steps down the children of an event to calculate the number of children. Args: event (json): Json representing the current event. Returns: The number of children of the current event. """ if len(event['children']) == 0: return 0 children = 0 for child in event['children']: children += 1 + _count_number_of_children_recursively(child) return children
30e2db8b16f0ea6acbbebe41ec44de4ed8b8239a
94,287
import math def _subject_score(uc_norm: float, aw_norm: float, emc_norm: float, df: float) -> float: """ Main subject detection formula """ return (2.0*uc_norm + aw_norm - emc_norm) / math.sqrt(df + 1.0)
85142342d24f286643729b54a04c84176d3b0be4
94,291
from typing import Union from typing import List from typing import Dict import time import json import requests def download(url: str) -> Union[List, Dict]: """ Download data from SRC API, with throttling """ print('[tools.py::download] Fetching', url) time.sleep(1) headers = {'user-agent': 'akleemans-gameboy-wr-bot/2.0'} content = json.loads(requests.get(url, headers=headers).text) data = content['data'] return data
c2ec21c2cd3e9f33ab113c9083ba394b4f018eb7
94,298
def get_w_gen_d_t(w_gen_MR_d_t, w_gen_OR_d_t, w_gen_NR_d_t): """(65a) Args: w_gen_MR_d_t: 日付dの時刻tにおける主たる居室の内部発湿(W) w_gen_OR_d_t: 日付dの時刻tにおけるその他の居室の内部発湿(W) w_gen_NR_d_t: 日付dの時刻tにおける非居室の内部発湿(W) Returns: 日付dの時刻tにおける内部発湿(W) """ return w_gen_MR_d_t + w_gen_OR_d_t + w_gen_NR_d_t
8166ea84c0adca839397fac35ee74d809bfe4b95
94,306
def sort_words(string_in): """ :param string_in: :return list_string: Takes a string and returns a sorted list of the string's contents If the input string is empty it returns an empty list """ if string_in == '': return [] split_string = string_in.split(' ', string_in.count(' ')) list_string = list(split_string) list_string.sort() return list_string
6ac6068d2cc89a9c2ff229caff77698a3a81b8dd
94,316
import math def dcg(gains, k=5): """Computes DCG for a given ranking. Traditional DCG formula: DCG_k = sum_{i=1}^k gain_i / log_2(i+1). """ dcg = 0 for i in range(0, min(k, len(gains))): dcg += gains[i] / math.log(i + 2, 2) return dcg
52080f0231e068e1d1099c107a80d9c4bc54c6fa
94,318
def UrlDepth(url): """The depth of the URL path""" pos = url.find('://') if pos >= 0: return url[pos+3:].count('/') else: return url.count('/')
bd6ec92a9f5b8358ee504cca5120a7143d8e3f86
94,319
def drop_GHGs(df): """ GHGs are included in some NEI datasets. If these data are not compiled together with GHGRP, need to remove them as they will be tracked from a different source """ # Flow names reflect source data prior to FEDEFL mapping flowlist = [ 'Carbon Dioxide', 'Methane', 'Nitrous Oxide', 'Sulfur Hexafluoride', ] df = df.loc[~df['FlowName'].isin(flowlist)] return df
602d194303126d27afa9ceb047be45bac3c28299
94,322
def get_channel_value(encodings, channel, r): """ Given encodings e, return the value in the tuple r that maps to the channel c """ return r[encodings[channel].field] if channel in encodings else None
a4759c495a3912eddebd6dab64dea9345abaf363
94,327
def lambda_curry2(func): """ Returns a Curried version of a two-argument function FUNC. >>> from operator import add, mul, mod >>> curried_add = lambda_curry2(add) >>> add_three = curried_add(3) >>> add_three(5) 8 >>> curried_mul = lambda_curry2(mul) >>> mul_5 = curried_mul(5) >>> mul_5(42) 210 >>> lambda_curry2(mod)(123)(10) 3 """ return lambda x: lambda y: func(x,y)
1736b8c9e4dfe62b8126a7f7187d2a00ff3436c7
94,331
def _add_batch_one(tensor): """ Return a tensor with size (1, ) + tensor.size :param tensor: 2D or 3D tensor :return: 3D or 4D tensor """ return tensor.view((1, ) + tensor.size())
ad3d00cce8c417ad81d79f1b601b033d401cd6f9
94,336
def _findx_shape(a, inds): """ Returns the shape of a fancy-indexed array (`a[*inds].shape`) """ shape = [] for ii, N in enumerate(a.shape): indx = inds[ii] if ii < len(inds) else None if indx is None: shape.append(N) elif isinstance(indx, slice): shape.append(len(range(*indx.indices(N)))) else: # assume indx is an index list or array shape.append(len(indx)) return shape
dd80d91d31ff8416279fe732acfdd4c253f04c36
94,339
import math import random def draw_poisson_inter_arrival_gap(lambda_mean_arrival_rate): """ Draw a poisson inter-arrival gap. It uses random as random source, so be sure to set random.seed(...) beforehand for reproducibility. E.g.: If lambda = 1000, then mean gap is 0.001 If lambda = 0.1, then mean gap is 10 :param lambda_mean_arrival_rate: Lambda mean arrival rate (i.e., every 1 in ... an event arrives) :return: Value drawn from the exponential distribution (i.e., Poisson inter-arrival distribution) """ return - math.log(1.0 - random.random(), math.e) / lambda_mean_arrival_rate
668988af46061d151f99e7587612d90b7255f1d6
94,341
def _is_fgroup(fgroup_tagged, element): """ This function checks if an atom or a bond is part of a tagged fgroup. Parameters ---------- atom: Openeye Atom Base fgroup_tagged: dict of indexed functional group and corresponding atom and bond indices Returns ------- atoms, bonds: sets of atom and bond indices if the atom is tagged, False otherwise """ try: fgroup = element.GetData('fgroup') atoms, bonds = fgroup_tagged[fgroup] return atoms, bonds except ValueError: return False
c1a85def63c6cab597cdfbda587d7d494eed75b6
94,342
def _create_product(product_name): """Given a product name, prompt for the price and quantity Return a new product record { "name": (str), "price": (float), "quantity": (int) } """ while True: try: product_price = float(input('What is the price for the item? ')) break except ValueError: print('Enter a valid price') while True: try: product_quantity = int(input('What is the quantity of the item? ')) break except ValueError: print('Enter a valid quantity') return { 'name': product_name, 'price': product_price, 'quantity': product_quantity }
6dbe3fd064a80e261018d4094e458c1bc22e6bf3
94,345
import functools def on_stage(stage: str): """decorator for callback methods so that they only run on a certain stage""" def wrapper(f): @functools.wraps(f) def wrapped(self, loop, *args, **kwargs): if loop.stage == stage: return f(self, loop, *args, **kwargs) return wrapped return wrapper
235198de1400717282c742af84940758f760abcf
94,349
import functools def union(iterable): """Return union of all sets in iterable.""" return functools.reduce(set.union, iterable, set())
0377c44ef13c8f2f04b6df0842b15c92a4d776a7
94,352
def GetABB(FCFCS): """ Return the S-57 abbreviation of the FCFCS """ return FCFCS[2]
b8bd9c4f405571ee615e44ad3f9552be5ee30268
94,354
import math def convert_time(x): """ Converts TIME field in the CSV to an integer representing what time of day it is (in number of 5min increments) from 0 to 287 eg - 00:00 -> 0 - 00:10 -> 2 - 02:20 -> 28 etc """ a = x.split('T') a = a[1].split(':') ans = math.floor((int(a[0]) * 12) + (int(a[1]) / 5)) return ans
9f5a4d522cafe660eb5a74fbd5ba02dff4eec288
94,360
def repeat_str(s, num): """ Repeat string :param s: string :param num: repeat number :return: string """ output = '' for i in range(0, num): output += s if len(output) > 0: output += ' ' return output
71c097459a299e591fe8ff8b045ca80a233bd24d
94,363
def getReadablePortion(lines: list) -> list: """Returns the portion of lines that starts with the line with text 'START'""" start = lines.index('START\n') return lines[start:]
1c81b924d4f555ac901b95ef4b26d38c8d5fa18e
94,366
import re def find_image_filename(input_image_dict, filename): """ Helper function to retrieve the full filename of the specified image using the provided dictionary. :param input_image_dict: the dictionary containing the full filename of available images. :param short_filename: the unique short filename of the image to use to look up the full filename in the dictionary. :return: the full image filename. """ short_filename = filename if "/" not in filename else re.split("([^/]+$)", filename)[1] return input_image_dict[short_filename]
92945b25e9c7f3f3d639015ed06478adbfc071b8
94,373
def is_correct_score(score): """ Check whether score is in [0.0, 10.0]. :param score: base score :return: True if valid """ return 0.0 <= score <= 10.0
b3be2464a720d2eddcdc6878f725946412b60606
94,374
def make_ascii(s): """ Convert text to ASCII """ return "".join(i for i in s if ord(i) < 128)
d1af8b008b9754a0cb0c17fcb0623308f88945dd
94,377
import base64 import hashlib def generate_zookeeper_digest(unique=False, user=None, credential=None): """Generate a zookeeper-compatible digest from username and password""" if user is None: raise RuntimeError('zk_digest(): user is not defined') if credential is None: raise RuntimeError('zk_digest(): credential is not defined') return base64.b64encode( hashlib.sha1(user + ":" + credential).digest() # nosec ).strip()
8fcc7b769cc7d970aec1653e19eb03e8bbbc712e
94,378
def clamp(x, minimum=0., maximum=1.): """ args: x: float minimum: float maximum: float returns: float between [minimum, maximum] """ return max(minimum, min(x, maximum))
4b45aafaf81c2dd2c27516f75b8ac0825e32346f
94,379
def grid_maker(grid_cells, grid_rows): """generate new grid with specified dimensions""" grid = [] cell_value = False for _x in range(grid_rows): row = [] for _y in range(grid_cells): row.append(cell_value) grid.append(row) return grid
20103f10dbd806093a9b71cc8b5191cf5b779be6
94,380
from pathlib import Path def get_project_root() -> Path: """Return Path for project root directory""" return Path(__file__).parents[1]
bc255cef4252e4357e95191763a21aeb2ab7d63d
94,382
def create_initial_assignments_model(species): """Create initial assignments for the model. Here only the formal type is defined. Assigning values to the parameters is done by :func:`create_parameters_model`. Parameters ---------- species : list of strings List containing the names of all species. Returns ------- assignments: dict Dictionary that contains the assignment names as keys and dicitonaries that contain the species' ids, and formulas as values. """ all_species = species.keys() assignments = {} for index_species in all_species: keys = f"assignment_{index_species}" assignments[keys] = { "species_id": index_species, "formula": f"{index_species}_t0", } return assignments
d2dcf87786ee528db3fabaa2926443915ebc9797
94,384
def height_fun(x, x0, A, xt): """ Model the height of a cantilevered microubule. The MT is fixed at x0 and pulled up. A is the shape giving/ scaling factor, equal to F/EI, where F ist the forc acting on the MT at xt, and EI is the flexural regidity of the mictotubule. """ def heaviside(x, x0): return 1 * (x >= x0) return heaviside(x, x0) * A * ((xt - x0) / 2 * (x - x0)**2 - ((x - x0)**3) / 6)
9157e1a037040b05a440000d8ff07493af05f8de
94,386
def sort_by_index(index, array): """ Sort the array with the given index and return a list of (<element>, <original index>, <new index>) tuples. Throw an assertion error (thrown by failed asserts automatically) if the arguments passed are invalid. >>> sort_by_index([ 0, 4, 2, 3, 1], \ ["zero", "four", "two", "three", "one"]) [('zero', 0, 0), ('one', 4, 1), ('two', 2, 2), ('three', 3, 3), \ ('four', 1, 4)] >>> sort_by_index([ 0.0, 4.0, 2.0, 3.0, 1.0], \ ["zero", "four", "two", "three", "one"]) Traceback (most recent call last): ... AssertionError >>> sort_by_index([ 0, 4, 2, 3, 0], \ ["zero", "four", "two", "three", "one"]) Traceback (most recent call last): ... AssertionError >>> sort_by_index([ 0, 4, 2, 3], ["zero", "four", "two", "three", "one"]) Traceback (most recent call last): ... AssertionError # My doctests # >>> sort_by_index([1, 4, 3, 2], ['one', 'four', 'three', 'two']) Traceback (most recent call last): ... AssertionError >>> sort_by_index([],[]) [] >>> sort_by_index([3, 2, 0, 1], ['three', 'two', 'zero', 'one']) [('one', 3, 0), ('zero', 2, 1), ('three', 0, 2), ('two', 1, 3)] """ assert isinstance(index, list) assert isinstance(array, list) assert len(set(index)) == len(array) assert all([isinstance(idx, int) for idx in index]) assert all([i in range(len(index)) for i in index]) return [(array[index[i]], index[i], i) for i in range(0, len(index))]
55f25b9355744b25ac0c24e17b649e2159a1a06c
94,387
from typing import Dict from typing import Any def from_strings_to_dict(data: Dict[str, Any]): """ Makes a model for a given list of string like : "mission.document.name": "test" => { mission: { document: { name: "test" } } } """ res = {} for key, value in data.items(): l = key.split('.') previous = [] end = len(l) - 1 for i, item in enumerate(l): d = res for prev in previous[:-1]: d = d[prev] if len(previous) > 0: d = d[previous[-1]] if item not in d: if i != end: d[item] = {} else: d[item] = value previous.append(item) return res
fe7291a0f9efed72ebbb600b55d33b5d31aae85c
94,389
def ones_complement_addition(x, y, bitsize=16): """ Add two numbers of any bitsize and carry the carry around. 11 + 10 = 101 => 10: >>> ones_complement_addition(3, 2, 2) 2 11 + 11 = 110 => 11: >>> ones_complement_addition(3, 3, 2) 3 00 + 10 = 10 => 10: >>> ones_complement_addition(0, 2, 2) 2 """ cap = 2 ** bitsize - 1 total = x + y if total > cap: total -= cap return total
2dc836fb1cbb3d7cdb55ba7620a783515a96e249
94,392
def is_sunday(dtobj): """True if dtobj is a Sunday""" return dtobj.weekday() == 6
3d1a76d6a00005fd5febc34edd298487a0eba270
94,394
def get_unsigned_value(obj): """ Returns unsigned integer from LLDB value. :param lldb.SBValue obj: LLDB value object. :return: Unsigned integer from LLDB value. :rtype: int | None """ return None if obj is None else obj.GetValueAsUnsigned()
4fa72a67b5ca09f2716c7e88489750869c6b199c
94,395
def check_extension(filename, extensions=("jpg", "jpeg", "png", "gif",)): """ Checks if the filename contains any of the specified extensions """ bits = filename.split(".") bits.reverse() ext = bits[0].lower() return ext in extensions
a1bcb9a3fa9e425da28e7ae5a915b9b59fb4a7f3
94,397
def lcs_len(x, y): """ Computes the length of the Longest Common Subsequence (LCS) between two lists using DP in O(nm). Implementation available on: https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_subsequence :type x: list of strings :param x: a sequence :type y: list of strings :param y: a sequence :return: the length of the LCS """ m = len(x) n = len(y) C = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if x[i - 1] == y[j - 1]: C[i][j] = C[i - 1][j - 1] + 1 else: C[i][j] = max(C[i][j - 1], C[i - 1][j]) return C[m][n]
320895b1f10858dafbfbd3a8908957f801f32c2d
94,402
def _RenderTestResourceId(spec): """Renders barebone resource_ids data based on |spec|.""" data = '{"SRCDIR": ".",' for i, tok in enumerate(spec.split(',')): num_star = len(tok) - len(tok.lstrip('*')) tok = tok[num_star:] meta = '"META":{"join": %d},' % (num_star + 1) if num_star else '' start_id = tok.split('+')[0] # Strip '+usage'. data += '"foo%d.grd": {%s"includes": [%s]},' % (i, meta, start_id) data += '}' return data
eaee6cd748da01e08681fa810f5637e87f5df6e3
94,403
def is_subdict(dict_super, dict_sub): """Return True if for each key in dict_sub, dict_super[key] >= dict_sub[key]""" for key, value in dict_sub.items(): # I could use "if dict_super.get(key, 0) < value return False" # but that assumes value is a positive numeric. # Using the code below, no such assumption, as long as '<' works if key not in dict_super: return False if dict_super[key] < value: return False # All satisfied return True
1bbdcff5c3f9760b69cc431ff4cfaf02f3d8309f
94,406
def is_option_arg(*name_or_flags) -> bool: """Returns whether the argument is an option arg (as opposed to a positional arg). :param name_or_flags: Either a name or a list of option strings, e.g. foo or -f, --foo. :return: True if the argument is an option arg, False otherwise. """ return any(name_or_flag.startswith('-') for name_or_flag in name_or_flags)
fd16d68d21f89d893c9a1268f48d3cd13a243e09
94,407
def is_alt_genotype(record, name): """Return if the named sample has a non-reference genotype call.""" sample = record.samples[name] indices = sample.allele_indices return not (not indices or None in indices or indices.count(0) == len(indices) or max(indices) >= len(record.alleles))
b1f38fb2fa5dd8c4b9b9940016a1988a3b2009ea
94,408
def generate_options(sequence, constraints): """ Generates options for each element of *sequence*, based on *constraints* :param seqence: The sequence to generate options for :type sequence: list or str :param constraints: The constraints to base the options on :type constraints: list of Constraint :return: A list of options :rtype: list of set of str """ options = [set() for _ in range(len(sequence) + 6)] for constraint in constraints: labels = constraint.label.split('-') for i, label in enumerate(labels): index = constraint.span[0] + i options[index].add(label) for option in options: if not option: option.add('_') return options
7fa79486add74f13d6a1b1f4bd7de4b8193b10d1
94,413
def lai(params: dict, states: dict) -> float: """ Calculates leaf area index Parameters ---------- params: dict sla: float Specific leaf area. [m2 {leaf} mg-1 {CH2O}] states: dict CLeaf: float Carbohydrates stored in the leaves [mg m-2] Returns ------- float LAI is a semi-state of the model. [m2 {leaf} m-2] """ lai_ = params['sla'] * states['CLeaf'] return lai_
291060be0787e77a87181c81c706af2558d4a5db
94,414
def to_dict_records(df): """ Pandas dataframe to dictionary (records method) Parameters --------------- df Dataframe Returns -------------- list_dictio List containing a dictionary for each row """ return df.to_dict('records')
5a033b4509492f02873c2bfe5bffea30da98364e
94,420
def Velocity(velocity, acceleration, i): """Defines the velocity at timestep i. Args: velocity (float): Initial velocity = 0. Recursively updates the velocity_new acceleration (float): From rocket.Acceleration(), Instantaneous acceleration. i (int): Iterator used for Euler's Method Returns: velocity_new (float): Updated velocity. Will replace velocity for next iteration """ # F = m*a TIME_STEP = .1 velocity_new = velocity + acceleration * TIME_STEP #v_x = velocity * np.sin(theta) # v_y = velocity * np.cos(theta) # acceleration = (thrust - drag) / mass_ship return velocity_new
72cc7cc91bdc2cd589c9012e7ed7bc6657e0833d
94,422
def divmod_min(a, b): """ return q,r such that a = qb + r, with minimum |r| """ q, r = divmod(a, b) # we will want to adjust r if # (|r| > |b/2|), which is equivalent to checking # (|2r| > |b|), # (|r| > |b| - |r|) # then using the fact that for python, # divmod will give |r| < |b| and r,b will have the same sign # (|r| > |b - r|) diff = b - r if abs(r) > abs(diff): q = q + 1 r = -diff return q,r
a59293b4c7013e8dd422c7044866d9a686d0ed0a
94,424
def MESeries(v): """ MExxxx series selector :param v: :type v: dict :return: :rtype: bool """ return v["platform"].startswith("ME")
1b18242e4392da9c24a5fa100bef3f244c324672
94,429
def get_cv_options_string(args): """ Create a string suitable for passing to another script with the cross-validation options """ args_dict = vars(args) s = "" if ('folds' in args_dict) and (len(args.folds) > 0): s = " ".join(str(f) for f in args.folds) s = "--folds {}".format(s) return s
eac6fc449c1be854d1cafd667b3ee64c496ee90c
94,430
def get_major_dot_minor_version(version): """ Convert full VERSION Django tuple to a dotted string containing MAJOR.MINOR. For example, (1, 9, 3, 'final', 0) will result in '1.9' """ return '.'.join([str(v) for v in version[:2]])
895891738e98f2f432a7a736af3ae7750b12db89
94,431
def accumulation_distribution(close, low, high, volume): """ Cumulative indicator that makes us of price and volume to assess whether an asset is being accumulated or distributed. :param close: closing price :param low: lowest price :param high: highest price :param volume: daily volume :return: ADI: Accumulation/Distribution Indicator """ # Calculate current money flow volume cmfv = (((close - low) - (high - close)) / (high - low)) * volume ADI = cmfv.cumsum() return ADI
f193d256322898bf9dd871fc9b6e8ec238d52f86
94,432
def List_num_activity(Counter_num_activity): """Gets list from counter of number each activity was performed per individual.""" num_activity = [k for k in Counter_num_activity.keys()] num_activity.sort() counts_num_activity = [Counter_num_activity[v] for v in num_activity] counts_num_activity_non_zero = sum([Counter_num_activity[v] for v in num_activity if v != 0]) return(num_activity, counts_num_activity, counts_num_activity_non_zero)
5d3a77fc48b0191ca6d88382cb9cd6ef43646afb
94,435
def _ruby_urls(path): """ Produce a url list that works both with ruby-lang.org, and stripe's internal artifact cache. """ return [ "https://cache.ruby-lang.org/pub/ruby/{}".format(path), "https://artifactory-content.stripe.build/artifactory/ruby-lang-cache/pub/ruby/{}".format(path), ]
7712981eb350d05088827c3123136d7d3ee4f0bd
94,440
def draw_board(board): """ Given a board it returns a string with the text representation. This is used to print results in console. """ res = '┌' res = res + '─' * board.n * 2 res = res + '┐\n' for i in range(0, board.n): res = res + '│' for j in range(0, board.m): if (i, j) in board.pieces: res = res + '{0} '.format(board.pieces[(i, j)]) else: res = res +'_ ' res = res + '│' res = res + '\n' res = res + '└' res = res + '─' * board.m * 2 res = res + '┘\n\n' return res
e09815a0a8e158750b337753dde2060da20a491d
94,442
def calculate_beta(weight_gap, weight_reference, weight_sample, gamma_gap, gamma_reference, gamma_sample): """ Calculates the factor \(\\beta\) that is needed to calculate the compensated moment of a sample. """ return ((weight_reference*gamma_reference)-(weight_sample*gamma_sample))/(weight_gap*gamma_gap)
bd5754b502a5b7ba69084ae4d8f7c1b7e0e0653a
94,448
def get_project_group_name(project_uuid): """Return project user group name""" return 'omics_project_{}'.format(project_uuid)
c027a997adf8f2e1c7477b21a8ba9681f02a6622
94,450
from typing import List def split_parts(key) -> List[str]: """ Split s3 key parts using "/" delimiter. Example:: >>> split_parts("a/b/c") ["a", "b", "c"] >>> split_parts("//a//b//c//") ["a", "b", "c"] .. versionadded:: 1.0.1 """ return [part for part in key.split("/") if part]
1f11a7c1f9c848956c3499797c8ee231b2f13107
94,460
def get_emails(plex): """ Retrieves a list of plex user accounts and returns each of their email addresses. """ users = plex.myPlexAccount().users() user_emails = [user.email for user in users] return user_emails
ba6ffbce9456667db0c22dd9b6486957c851d431
94,462
def table_header_filter(ptag): """ Validate p tag, to see if it's relevant. :param ptag: P tag. :type ptag: bs4.element.Tag """ valid = ptag.find("b") and "BlackBerry" in ptag.text and not "experts" in ptag.text return valid
927153809f1442d5b8db527f488cbbea08dffcd1
94,464
def get_preferred_title(transcript_id, nucleotide_change, gene_name='', amino_acid_change=''): """Method to return the variant preferred title. Examples given as below. `NM_015506.3(MMACHC):c.436_450del (p.Ser146_Ile150del)` NM: Chromosome 015506: Gene on chromosome (a gene produces certain protein) MMACHC: Symbol represent the gene c.436_450del: Nucleotide change p.Ser146_Ile150del: Name of the amino acid (protein) change ### Other Examples Regarding the title format, below gives another example: When both gene name and protein effect information are available, the format will be `NM_002496.4(Gene):c.64C>T (Amino-acid change)`. When protein effect is unavailable, the format will be `NM_002496.4(Gene):c.64C>T`. When both gene and protein effect not available, will fall back to hgvs format `NM_002496.4:c.64C>T`. When gene name is unavailable, amino-acid change is unavailable as well, so the format will fallback to hgvs as above. """ if not (transcript_id and nucleotide_change): return if not gene_name: return '{coordinate}:{nucleotide_change}'.format(coordinate=transcript_id, nucleotide_change=nucleotide_change) # when gene name is unavailable, then there will be no amino-acid change, where title will fall back to hgvs form, i.e. transcriptId:nucleotideChange if not amino_acid_change: return '{coordinate}({gene_symbol}):{nucleotide_change}'.format( coordinate=transcript_id, nucleotide_change=nucleotide_change, gene_symbol=gene_name ) return '{coordinate}({gene_symbol}):{nucleotide_change} ({amino_acid_change})'.format( coordinate=transcript_id, nucleotide_change=nucleotide_change, gene_symbol=gene_name, amino_acid_change=amino_acid_change )
3a1b6e8c6c9c4207708c98adc7f4fd838babe931
94,471
def _FetchAppEngineSDKSteps(api): """Fetches the App Engine SDK and returns its path. This uses a downloader script in the infra repo to download a script which is then used to download and unpack the SDK itself. """ script_content = api.gitiles.download_file( 'https://chromium.googlesource.com/infra/infra', 'bootstrap/get_appengine.py', step_name='Fetch SDK downloader', # This is a commit after the latest fix to the script, # which includes retrying requests. branch='fd119c547fd4e56eeab77d138b0426022ae1d159') api.python.inline('Run SDK downloader', script_content, args=['--dest=.']) return api.path['slave_build'].join('google_appengine')
3ba2a8130f3ae49f4904bc3c349a3b7523be42c9
94,473
def _read_file(filename): """ Returns the file content as as string """ with open(filename, 'r', encoding='utf8') as f: read_data = f.read() return read_data
b9562487d166a221dd396b678b85db4cd3893805
94,476
import opcode def _Opname(code): """Returns opcode.opname[code] or <unknown ###> for unknown opcodes.""" if code < len(opcode.opname): return opcode.opname[code] else: return "<unknown %s>" % code
573b51f463811c460b8d3ecb82a17d12ff9df0aa
94,477
def find_time_dim(da): """Find the time dimension in an xr.DataArray. Args: da: An xr.DataArray Returns: time_dim: Either 'time' or 'historical_time', depending on which is present in da. """ if 'time' in da.coords: time_dim = 'time' elif 'historical_time' in da.coords: time_dim = 'historical_time' else: time_dim = None return time_dim
c5c732a6930e5b3aaa994351fc6ae6963aea4d87
94,479
def ProfondeurMoyenne(tree): """Retourne la hauteur moyenne de l'arbre tree.""" return tree.av_leaf_height()
a59c9ed83bdd7f5a337a0ba82441cf2154df82a7
94,481
def get_voc_coords(string): """ convert PAGE record string coords into VOC coords :param string: a string containing the coordinates in PAGE format for example '168,146 476,146 168,326 476,326' :return: a tuple of (xmin, ymin,xmax, ymax) """ points = string.split() points = [point.split(",") for point in points] x_points = [int(point[0]) for point in points] y_points = [int(point[1]) for point in points] return min(x_points),min(y_points), max(x_points), max(y_points)
0c62cfc2e65bdbb468d720834ea824212c0e5604
94,485
def children(input_op): """Find successor ops for input_op. Args: input_op(tf.Operation): Input op. Returns: Collection of successors with a direct edge from the input_op. """ return set(child_op for out in input_op.outputs for child_op in out.consumers())
181e04120ff9a35d62f85fc21235c7ee489b22c6
94,490
from typing import Optional import inspect def find_method_docstring(klass, method: str) -> Optional[str]: """Look through a class' ancestors for the first non-empty method docstring. Since Python 3.5, inspect.getdoc is supposed to do exactly this. However, it doesn't seem to work for Cython classes. Examples -------- >>> class Parent: ... ... def foo(self): ... '''foo method''' >>> class Child(Parent): ... ... def foo(self): ... ... >>> find_method_docstring(Child, 'foo') 'foo method' """ for ancestor in inspect.getmro(klass): try: ancestor_meth = getattr(ancestor, method) except AttributeError: break if doc := inspect.getdoc(ancestor_meth): return doc
5ad60b5ced1798015e0115daa575f67e4f7c3bee
94,492
def innerHTML(element): """Returns the inner HTML of an element as a UTF-8 encoded bytestring""" return element.encode_contents()
626d343e1d0d6ae4e97c065831e42a188e5ff2af
94,494
def parse_journal(response, paper_id): """Parse journal information from a MAG API response. Args: response (json): Response from MAG API in JSON format. Contains all paper information. paper_id (int): Paper ID. Returns: d (dict): Journal details. """ return { "id": response["J"]["JId"], "journal_name": response["J"]["JN"], "paper_id": paper_id, }
0f5536e31fe586997af741ece1e41bdc132f2c8c
94,504
def unpack_vectors(vector_list): """ Takes a list of 2d vectors and returns two lists, each containing the corresponding components in association """ xs = [] ys = [] for v in vector_list: xs.append(v[0]) ys.append(v[1]) return xs, ys
7d2336d6291546af72f46774aa3a99098200d565
94,505
from typing import Counter def count_letters(x): """ Count how many chars are in a string """ counter = Counter() for word in x.split(): counter.update(word) return sum(counter.values())
0fcaad35197196626d8e917532364ce24f518d00
94,507
def indice(element, liste): """Renvoie l'indice de l'element dans la liste, -1 s'il n'est pas dedans.""" n = len(liste) for i in range(n): if liste[i] == element: return i return -1
56b8ab56eef6f9830cdcb389da3d7a997a9a8529
94,512
def total_fraction_scattered_intensity(R=1e-6,rho=0.4,wavelength=1e-10): """ calculated for sphere with constant e-density rho = electron density per ų (protein 0.43, water 0.33) R = radius in m """ rho = rho*1e30 # convert to m3 return 4.9*1e-25*wavelength**2*rho**2*R**4
31315327b5144582849da18a05ec143c62c5fdc5
94,513
def batches_shuffled(batch_list1, batch_list2): """ Ars: two lists of batches Returns True if the corresponding batches in lists are different Returns False otherwise """ for b1, b2 in zip(batch_list1, batch_list2): if b1 == b2: return False return True
56346e92a8ed84c1b4c56fcd5584e83f9fcb9f38
94,515
def strip_pointy(string): """ Remove leading '<' and trailing '>' from `str` :param string: string :return: cleaned up string """ return string.lstrip('<').rstrip('>')
d1c85af01fa7898d8e2566f7ff928f5d9c562a2d
94,519
import math def check_circle_collision(c0, c1): """Checks whether two circles collide.""" dx = c1[0] - c0[0] dy = c1[1] - c0[1] dist = math.sqrt(dx * dx + dy * dy) if dist < c0[2] + c1[2]: return True return False
1a3b9d9f64a4f3635472f6a68790158d5f943d52
94,521
def summarize_broken_packages(broken): """ Create human-readable summary regarding missing packages. :param broken: tuples with information about the broken packages. :returns: the human-readable summary. """ # Group and sort by os, version, arch, key grouped = {} for os_name, os_ver, os_arch, key, package, _ in broken: platform = '%s %s on %s' % (os_name, os_ver, os_arch) if platform not in grouped: grouped[platform] = set() grouped[platform].add('- Package %s for rosdep key %s' % (package, key)) return '\n\n'.join( '* The following %d packages were not found for %s:\n%s' % ( len(pkg_msgs), platform, '\n'.join(sorted(pkg_msgs))) for platform, pkg_msgs in sorted(grouped.items()))
61c190349ba934871739822435fd36c209c2eb7a
94,531
def zoom_center(img, sx, sy=None): """ Zoom by taking the sx × sy central pixels Parameters ---------- img : 2D numpy array The input data sx : int The number of pixels along the x-axis to take sy : int or None The number of pixels alongs the y-axis to take. If None take the same value as for sx """ if sy is None: sy = sx assert type(sx) is int assert type(sy) is int return img[ img.shape[0]//2-sy//2: img.shape[0]//2 + sy//2, img.shape[1]//2-sx//2: img.shape[1]//2 + sx//2]
901d315f9fb29f003f6f0b99d65eb44d75707b81
94,538
def is_within_interval(value, min_value=None, max_value=None): """ Check whether a variable is within a given interval. Assumes the value is always ok with respect to a `None` bound. If the `value` is `None`, it is always within the bounds. :param value: The value to check. Can be ``None``. :param min_value: The lower bound. :param max_value: The upper bound. :return: ``True`` if the value is ``None``. ``True`` or ``False`` whether the value is within the given interval or not. .. note:: A value is always within a ``None`` bound. Example:: >>> is_within_interval(None) True >>> is_within_interval(None, 0, 10) True >>> is_within_interval(2, None, None) True >>> is_within_interval(2, None, 3) True >>> is_within_interval(2, 1, None) True >>> is_within_interval(2, 1, 3) True >>> is_within_interval(2, 4, 7) False >>> is_within_interval(2, 4, 1) False """ checks = [] if value and min_value: checks.append(value >= min_value) if value and max_value: checks.append(value <= max_value) return all(checks)
8b82858d33b56fcd479f97a4077c03bd1392bb75
94,541
def strip_non_ascii(string): """ Remove all non-ascii characters from a string. Parameters ---------- string : str Text to be operated on Returns ------- str Copy of original text with all non-ascii characters removed """ return ''.join((x for x in string if ord(x) < 128))
bcde4b373dcaed56cb131f40b1b8b8cb229676aa
94,546
def unescape_single_quote(escaped): """ Unescape a string which uses backslashes to escape single quotes. :param str escaped: The string to unescape. :return: The unescaped string. :rtype: str """ escaped = escaped.replace('\\\\', '\\') escaped = escaped.replace('\\\'', '\'') return escaped
44d3f05ca60894fbf0d40f4aa29fffa8cfe29867
94,548
def parse_csv_data(csv_filename:str) -> list: """This function reads from a csv file and returns the content as a list. Args: csv_filename (str): Name of csv file to be opened Returns: list: Content of csv file """ parsed_data =[] with open(csv_filename) as csv_file: for line in csv_file: parsed_data.append(line) return parsed_data
779f7f5ea40e30c7be1d7497c69c740eedf6f9df
94,551
def restriction_sites(s1, s2): """ (str, str) -> list of int Precondition: s1 only contains characters from 'A', 'T', 'C' or 'G'. s2 is a recognition sequence. Return a list of all the indices where s2 appears in s1. >>> restriction_sites('GCTATCGAGGATCGA','TCGA') [4, 11] >>> restriction_sites('GGCCTAGAGGCCAGGCCGGC','GGCC') [0, 8, 13] """ result = [] a = s1.find(s2) if a != -1: while len(result) < s1.count(s2): result.append(a) a = s1.find(s2, a + 1) return result
c9d20a66f538db79749fa993e92f7566b3f6eb9b
94,553
def is_in_coverage(unixtime, weathers_list): """ Checks if the supplied UNIX time is contained into the time range (coverage) defined by the most ancient and most recent *Weather* objects in the supplied list :param unixtime: the UNIX time to be searched in the time range :type unixtime: int :param weathers_list: the list of *Weather* objects to be scanned for global time coverage :type weathers_list: list :returns: ``True`` if the UNIX time is contained into the time range, ``False`` otherwise """ if not weathers_list: return False min_of_coverage = min(weather.reference_time() for weather in weathers_list) max_of_coverage = max([weather.reference_time() \ for weather in weathers_list]) return unixtime >= min_of_coverage and unixtime <= max_of_coverage
800608d1b7b7634ee543ed557f658389bb96eba9
94,555
from typing import List def convert_to_line_items(my_products: List[dict]) -> List[dict]: """ Turn our data format into Stripe's line_items API. To accomplish this we must locate any existing Products or Prices registered on Stripe, or create them if they do not exist already. A Stripe Price is an object on Stripe that contains the price of 1 product; the Price object itself contains the Product object. The `line_items` output is a bundling of Prices, Products, and quantities for one specific checkout session. Documentation: https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-line_items """ return [ { "price": product["payment_uuid"], "quantity": product["quantity"], } for product in my_products ]
595f03f782cf32be5577594a387d45ad144da7f3
94,559
import torch def apply_linear_constraint(lin, a, x, *args, inequality=False, v=None, **kwargs): """Apply a linear constraint Parameters ---------- lin : Callable the linear constraint of the form lin(x, *args, **kwargs) = a that is linear in x inequality : bool assume that lin(x, *args, **kwargs) >= a Returns ------- y : Tensor x transformed to satisfy the constraint """ val_x = lin(x, *args, **kwargs) # use a constant adjustment # x - alpha * v if v is None: v = torch.ones(x.size(-1)) val_v = lin(v, *args, **kwargs) alpha = (val_x - a) if inequality: alpha = alpha.clamp(max=0) return x - v * (alpha / val_v)
e46de92b38a641373056ac5965120f84a35f7b70
94,565
def yes_no_prompt(prompt): """Asks a yes/no question, and returns a boolean response.""" selection = input('{} [y/n]: '.format(prompt)) return bool(selection.lower() == 'y')
0fee78cfe9ce3edb5957aeb88e8e6cd7756abacf
94,567
def get_num_increases(data: list[int]) -> int: """ Get the total number of times the value of the next element in the list is greater than the value of the previous element >>> get_num_increases([1, 3, 4, 2, 5]) 3 """ return sum(b > a for a, b in zip(data[:-1], data[1:]))
d57422eba4cdcee2cc16877af8aa82590a5716cc
94,571
def filter_pet_products(tesco_grocery_df): """Filter out pet products""" return tesco_grocery_df[tesco_grocery_df["l2y_group"] != "G3 PET PRODUCTS"]
51fe39b1f4c52ea4cc9edf419163618da19eeddc
94,576