content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def cents_to_pitchbend(cents, pb_range) -> int: """ Convert cent offset to pitch bend value (capped to range 0-16383) :param cents: cent offset :param pb_range: pitch bend range in either direction (+/-) as per setting on Roli Dashboard / Equator :return: """ pb = 8192 + 16384 * cents / (pb_...
8f9f55efc411d4f53846c8ef3a91fe8bc34cd2b5
652,676
def add_book_to_csv(): """ 111 Create a .csv file that will store the following data. Call it “Books.csv”. :return: """ with open("docs/books.csv", "w") as f: f.write("To Kill A Mockingbird, Harper Lee, 1960\n") f.write("A Brief History of Time, Stephen Hawking, 1988\n") ...
c31bafa03cc46fc35bc63753dfdba3e5a03cf04c
652,677
import ctypes import os import traceback def isUserAdmin(): """@return: True if the current user is an 'Admin' whatever that means (root on Unix), otherwise False. Warning: The inner function fails unless you have Windows XP SP2 or higher. The failure causes a traceback to be printed and this fun...
d29c4e9ead79af36b9529e3024e43eee3f033bed
652,678
import functools def _numel(arr): """ Returns the number of elements for an array using a numpy-like interface. """ return functools.reduce(lambda a, b: int(a) * int(b), arr.shape, 1)
6c51e35f7d753f7b0acde02543c93671395b1c80
652,679
def mean(v): """ mean function of bounch of values """ return sum(v) / len(v)
58ebb831c2d75108e79dc68f31631845e34365ad
652,680
def reconstruct_dataframe(df): """Reconstruct dataframe row by row and convert to list of dictionaries """ docs = [] for row in df.itertuples(): doc = { "title": row.title, "text": row.text, "url": row.url } docs.append(doc) return docs
defb5b18a9fbcca2004a4b3b00755c7e776cf7a5
652,681
def get_seat_differences(current_election, previous_election): """ This function takes two lists of lists as arguments, with each list representing a party's election results and returns a list of tuples, with each tuple representing a party's name and the seats they lost or gained between the current a...
115cd993bff16f84528c6ba21f0d7f1815cfafc9
652,682
import os def name_from_url(url): """ Return the project name from the url. Assume the project name is always in the form "foo/bar.git" >>> name_from_url("git@git:foo/bar.git") 'foo/bar.git' """ if url.startswith("file://"): sep = "/" if os.name == 'nt' and "\\" in url:...
642f8cdb5066d697943c0ad834e7207c0b4f1dad
652,683
def ellipsis(): """Ellipsys: 3 dots for user defined syntax.""" return ...
628f5bee4f2c586ea13334d85f6f2121001d2a0d
652,684
import platform def get_architecture() -> str: """Return the Windows architecture, one of "x86" or "x64".""" return "x86" if platform.architecture()[0] == "32bit" else "x64"
ef7fcb690061e72900e999464fc1a716d27fdc87
652,685
def dynamic_index(list_instance, index): """ Accepts a list of weeks materials and return a specific index according to week_number value. """ try: return list_instance[index] except: return ''
171073286c37af90b5dedfc5e5de4d11474d0203
652,686
def _get_numbers(directive): """ Retrieve consecutive floating point numbers from a directive. Arguments: directive: A 2-tuple (int, str). Returns: A tuple of floating point numbers and the remainder of the string. """ num, line = directive numbers = [] items = line.spl...
ebade379e4f879b39a4072a308281ca89f12fd53
652,688
import math def format_amount( amount_pence, trim_empty_pence=False, truncate_after=None, pound_sign=True ): """ Format an amount in pence as pounds :param amount_pence: int pence amount :param trim_empty_pence: if True, strip off .00 :param truncate_after: if a number of pounds, will round in...
d805ad380986097cf7be118558bfa127a0c00386
652,689
def bonferroni(false_positive_rate, original_p_values): """ Bonferrnoi correction. :param false_positive_rate: alpha value before correction :type false_positive_rate: float :param original_p_values: p values from all the tests :type original_p_values: list[float] :return: new critical value...
a920d44fc04670eaf776444b4e39f105e685de80
652,690
def find_category_name(booleans): """ Find the category name for the list of booleans. """ vals = list(map(lambda val: val == 'True', booleans.split(','))) if all(vals): return 'DBE, MBE, and WBE' elif vals[0] and vals[1]: return 'DBE and MBE' elif vals[1] and vals[2]: ...
18ff81bc55de9fb6e12e949504c58cb2d192b0f8
652,691
import numpy def quaternion_conjugate(quaternion): """Return conjugate of quaternion. >>> q0 = random_quaternion() >>> q1 = quaternion_conjugate(q0) >>> q1[0] == q0[0] and all(q1[1:] == -q0[1:]) True """ q = numpy.array(quaternion, dtype=numpy.float64, copy=True) q[1] = -q[1] q[2...
a4d96a22a8c6be2b27e6864e89fb44b488fdd529
652,692
def diagSmooth(s,d1,d2, k): """ Input: 4x4 area Output: 7x7 interpolated area (Only diagonals used) """ w1 = 1 / (1 + d1**k) w2 = 1 / (1 + d2**k) weight1 = w1 / (w1 + w2) weight2 = w2 / (w1 + w2) downRightPixel = (-1 * s[0,0] + 9 * s[1,1] + 9 * s[2,2] - 1 * s[3,3]) / 16 upRight...
8c491337b065ebbc76bef8c47e51e0f44d510a12
652,693
from numpy import log def Vacuum_dV(motor_isp, wet_mass, dry_mass): """Calculates the total available vacuum-dv by the Tsiakovlsy rocket equation Args: motor_isp (float): The ISP rating of the motor_isp wet_mass (float): Total mass of the fully fueld Rocket dry_mass (float): Mass of th...
c9e162e56cb13418b185318b629f6c82304121a0
652,695
from typing import List import torch def get_all_available_gpus() -> List[int]: """ Returns: a list of all available gpus """ return list(range(torch.cuda.device_count()))
acf06402582f52e92e06538d1284cfdf271b3f9a
652,697
def get_max_vals(tree): """ Finds the max x and y values in the given tree and returns them. """ x_vals = [(i[0], i[2]) for i in tree] x_vals = [item for sublist in x_vals for item in sublist] y_vals = [(i[1], i[3]) for i in tree] y_vals = [item for sublist in y_vals for item in sublist] ...
7fc84ba468d8e53660cdd5252f669609adecbe92
652,698
def _value_postprocessor(_, key, value): """Post-process the string values parsed from the XML""" try: return key, int(value) except (ValueError, TypeError): return key, value
1e441885f09218046c20f8f87f57d26c40ab954a
652,699
def get_chunk_type(tok): """ Args: tok: id of token, ex 4 idx_to_tag: dictionary {4: "B-PER", ...} Returns: tuple: "B", "PER" """ tok_split = tok.split('-') return tok_split[0], tok_split[-1]
d26d3bd29c8f9209afe0d357972db21fc6c6623c
652,700
import re import unicodedata def vianame(name): """This is similar to string_vianame. The main difference is that under most circumstances, vianame returns an ordinal code point, whereas string_vianame returns a string.""" if not name: return None if (_m := re.match(r'^U\+([0-9a-fA-F]+)$', name)):...
19c1d8369e5f73f302d0b3b54aa5182252b30ba0
652,701
def get_between(haystack, starter, ender): """ Find text between a start flag and end flag. Get the location of the desired substring and the location of the entire field separately. Example: If starter is "line " and ender is " " and haystack contains "line 1 ", then the result is a dict w...
5af3352f285df86e8e1e7d444ca119e6c91d40e1
652,702
def subdif_gap_1d(w, x): """ Horrible code, but otherwise does not work with numba """ eps = 1e-10 if x < 0 - eps: d = w + 1 elif x > 0 + eps: d = w - 1 else: if -1 <= w <= 1: d = 0 elif w > 1: d = w - 1 else: d = -w...
b542017cdad444493e7cc308a7188edf5d2057bf
652,703
def scienti_filter(table_name, data_row): """ Funtion that allows to filter unwanted data from the json. for this case: * fields with "FILTRO" * values with the string "nan" * passwords anything can be set here to remove unwanted data. Parameters: table_name:str n...
03029587e43f4e8aad809b607c45f53149d94fa2
652,704
def test_piles(*assiettes): """ Retourne s'il est possible d'obtenir des piles d'assiettes de même hauteur. En paramètre, un nombre d'assiette par pile doit être fourni. """ return sum(assiettes) % len(assiettes) == 0
1526480fab206d425e69fd7776f57d139b6211ea
652,705
import math def compute_icns_data_length(ctx): """Compute the required data length for palette based images. We need this computation here so we can use `math.ceil` and byte-align the result. """ return math.ceil((ctx.width * ctx.height * ctx.bit_length) / 8)
af479039a5ac51561b5eeac5f9ef519ffa65b442
652,706
import math def getHeading(q): """ Get the robot heading in radians from a Quaternion representation. :Args: | q (geometry_msgs.msg.Quaternion): a orientation about the z-axis :Return: | (double): Equivalent orientation about the z-axis in radians """ yaw = math.atan2(2 * ...
4476051d48c6766aded3ad9308367960f77cead3
652,707
def read_root(): """ FastAPI GET route '/' Returns: dict: A dummy Hello World! dictionary """ return {"Hello":"World!"}
48ab18027ab3c493b15d1563edbe008ebc78b7a3
652,708
def wants_other_orders(responses, derived): """ Return whether or not the user wants other orders """ return 'Other orders' in derived['orders_wanted']
3ce624e5784ca8896d8cdc25d479e98761ce69af
652,710
def calc_dipole(charges, xyzs): """Calculates the dipole from coordinates and charges Args: charges (list): atomic charges xyzs (list): atomic coordinates Returns: list: dipole for each xyz in xyzs """ dipoles = [] for xyz in xyzs: charge_coord = [0,0,0] ...
c7162c21f6bda3ff00103a09a441689c8cf05bd3
652,711
def removeAlignmentNumber(s): """ If the name of the transcript ends with -d as in ENSMUST00000169901.2-1, return ENSMUST00000169901.2 """ s = s[:] i = s.find('-') if i == -1: return s else: return s[0:i]
f6509eacd414b1ff92fd3fb1a75e211f60c29ed8
652,712
def trim(s): """ Add any globle filtering rules here """ s = s.replace( "Python Enhancement Proposals!", "") s = s.replace( "PEP ", "PEP-") return s
1c0fceb66796771b174e7cdf6a50b9dfff257c6d
652,713
def output_dir(tmpdir): """Fixture. Create and return custom temp directory for test.""" return str(tmpdir.mkdir('templates'))
c9d8fb8960055aaae40f38acbe468ceb9bd3adba
652,715
def vecInt(vec): """Retruns something.""" return tuple([int(c) for c in vec])
842252f1e98b807f0110e7f2ef768468014d5c67
652,716
def freq_correction(freq_matrice, bg_freq, beta) : """ Corrige les frequences brutes avec les frequences background """ for i in range(freq_matrice.shape[0]) : #i est la position for j in range(freq_matrice.shape[1]) : #j est l'aa freq_matrice[i,j]=(freq_matrice[i,j]+(beta*bg_freq[j]...
861b88e493b00e65c0e9e5a47c1894a869052d39
652,717
import re def ctype_email_local(s): """close enough. no '.' because this is used for last char of. """ return re.match("^[a-zA-Z0-9_%+-]+$", s)
1933138b9eff2fecec807b739ccd040f96259b89
652,719
def _CanDownloadBuilds(master_name): """Checks whether bisecting using archives is supported.""" return master_name.startswith('ChromiumPerf')
e33b6a7b8432353c61692b82f39bd9de3cdb1923
652,720
def det(a: list) -> int: """ Calculates the determinant of a 2x2 Matrix, via the shortcut (a*d) - (b*c) :param a: The matrix A. :return: The determinant. """ d= (a[0][0] * a[1][1]) - (a[0][1] * a[1][0]) return d
462c0a9a400c69e0b8ade8f4153bc40143de9134
652,721
import argparse def get_args(): """Build arg parser and get command line arguments :return: parsed args namespace """ parser = argparse.ArgumentParser() parser.add_argument("--config-file", default="config/pu_config.json", help="Twitter account config file name") parser.add_argument("--dat...
76907a5a275e8b80f26541b7e9dbc024f7145587
652,722
def bubble_sort(num_list): """ バブルソートの関数 :param num_list: ソートする数列 :return: ソートされた結果 """ # 数列の個数分ループ # バブルソートでは、左の数値(ここではi)から順番に並べ替えが完了する for i in range(len(num_list)): # range(始まりの数値, 終わりの数値, 増加する量) for j in range(len(num_list) - 1, i, -1): if num_list[j-1] > ...
35b98880218638fbe9e5f6c56727cd96d7cbc05f
652,723
import subprocess import shlex def git_hash(): """Gets a hash for different runs to have unique logfile names.""" cmd = 'git log -n 1 --pretty="%h"' ret = subprocess.check_output(shlex.split(cmd)).strip() if isinstance(ret, bytes): ret = ret.decode() return ret
a9c23cd9561e954bbb5720bae3ee345cadd91d19
652,724
from typing import Sequence from pathlib import Path from typing import List def make_batches(paths: Sequence[Path], batch_size: int) -> List[Sequence[Path]]: """ Group utterances into batches for decoding. """ return [paths[i:i+batch_size] for i in range(0, len(paths), batch_size)]
9a05d3af9239dc144c8742a568e6510f4d37a6e8
652,726
def nom_ID(nom): """Convertis un nom en ID discord """ if len(nom) == 21: ID = int(nom[2:20]) elif len(nom) == 22: ID = int(nom[3:21]) elif len(nom) == 18: ID = int(nom) else: ID = -1 return(ID)
3312506104d6309d2a123e1d839824c68759ef9c
652,727
def collatz(n): """ Vrne dolžino collatzovega zaporedja, ki se začne z n. """ i = 1 while n != 1: if n % 2 == 0: n = n / 2 i += 1 else: n = 3 * n + 1 i += 1 return i
894136d287d790a86bf50170f1f8c600329ce42f
652,728
def native_dtype(dtype): """ Convert a dtype to native dtype. A helper function. Do not use. """ return dtype.newbyteorder('=')
1aa3decafe453e264b2aa405b0c00509c08a885b
652,730
def MagnetMaterial(main): """ Function to load the information about the PM material to ANSYS. Args: main (Dic): main object used to upload the information. Returns: Dic: The same initial dictionary """ MaterialsPM = main['ANSYS']['Materials']['PM'] # oDefiniitonManager oD...
830e3e08f0f711a2d821d213f201aa9e05ad5a4e
652,731
def _intify_keys(d): """Make sure all integer strings in a dictionary are converted into integers.""" assert isinstance(d, dict) out = {} for k, v in d.items(): if isinstance(k, str) and k.isdigit(): k = int(k) out[k] = v return out
21eca39f20dcfbb65bee80df3cef711eb632791c
652,733
def get_job_state_str(job): """Get string representation of a job.""" if not hasattr(job, 'next_run_time'): # based on apscheduler sources return 'pending' elif job.next_run_time is None: return 'paused' else: return 'active'
fc44db5560bc94a8d48988b2bf36656037bafc72
652,734
import functools def once(func): """Decorator that wraps the given async function such that it is executed only once.""" first = True @functools.wraps(func) async def wrapper(*args, **kwargs): nonlocal first if first: first = False await func(*args, **kwargs) ...
743d64bc077d3070d3848a254b0883955d2d9ad4
652,735
import torch def normalize_pointcloud_transform(x): """ Compute an affine transformation that normalizes the point cloud x to lie in [-0.5, 0.5]^2 :param x: A point cloud represented as a tensor of shape [N, 3] :return: An affine transformation represented as a tuple (t, s) where t is a translation an...
06c2178a92d8e5a1b585249e9aa1e1bd4c4e3d5d
652,736
def is_json(_path) -> bool: """Return True if file ends with .json, otherwise False.""" if _path.endswith(".json"): return True else: return False
ba2a3ec6b93675dc86d07fbd626fac7c75a14585
652,737
def hello_world(): """ Basic function to return raw HTML content. Served on the root URL. WARN It seems like it's not a good idea to reference raw variables directly in returned HTML. WARN This is due to the possibility of XSS exploits created from such implementation. WARN Escape them with escape()...
7a3a865cdb16cac80c06258e447d3fe013ec1484
652,738
def pageSizeCount(counts,pagesize,pagenum): """ 页码计算 counts:总数 pagesize:一页显示几条数据 pagenum:第几页 """ nums = str(counts/pagesize).split(".") allpagenum = int(nums[0]) if int(nums[1]) > 0: allpagenum = allpagenum + 1 if pagenum <= allpagenum: startnum = (pagenum-1)*page...
e419d81f74af382256c0ffa6f48b577e2995f21f
652,739
import six def choose_item(prompt, items): """Asks the console application user to choose an item from a list The user is expected to enter the n'th item from items, 1-based. If the user enters a wrong value, an error is printed and has to choose again. Args: prompt (str): The question ...
d9bc71f162dd274f12edde3d64a2ba9724e8130e
652,740
def _and_lambda(b1: bool, b2: bool) -> bool: """ private function to describe a AND BiFunction Note: lambda are not used in order to be compatible with multiprocessing (lambda are not serializable) """ # lambda b1, b2: b1 and b2 return b1 and b2
d219b93fda4dd4a4b937e5da36a4957eaecef728
652,741
def headline_changes(value): """changes headline according to pressed button on sidebar""" return 'Please select Subject/Hemisphere' if value is None else 'Rotation: {}'.format(value)
8e2b82843c1ace1eed7327e6d551b87f58e4abfd
652,742
def overlap(reg1, reg2, equal=True): """ reg1 and reg2 are lists, such as reg1 = [t1, t2] reg2 = [t3, t4] equal=True means that if reg1 = [10,20] reg2 = [20,40], output will be 1 since 20's are the same """ if type(reg1) != list: reg1 = list(reg1) if typ...
d6d5a3cefff91c75223c35249f7c1916c216a46a
652,743
def get_next_tile(thisTile, neighboringTile): """ Look 1 tile over in the direction specified by the value passed in neighboringTile (north, south, ..., etc.) """ row, column = thisTile # thisTile[i, j] row_neighboringTile, column_neighboringTile = neighboringTile # neighborTile[k, l], where [k, l] is the dir...
99e828afa60dc1bbeaced0cd223a57e5d5ca1c4a
652,745
def remove_bad_words(words): """Remove naughty words that might come from wordnet synsets and lemmata. Args: words (list): The list of words Returns: list: An updated word list with bad words removed. """ bad_words = ["nigger", "wop", "kike", "faggot", ...
c4ca0a1ba3fba6d7abc8745ddf79629025f31400
652,746
import sys import sysconfig import os def _get_python_lib_link(): """Get name of python library used for linking""" if sys.platform == "darwin": ld_library = sysconfig.get_config_var("LIBRARY") else: ld_library = sysconfig.get_config_var("LDLIBRARY") if ld_library is not None: ...
22008aad94ac353e9cfaeb63f2baee8b12dea59e
652,747
import argparse def parse_args(): """Parse CLI flags.""" parser = argparse.ArgumentParser( description='Run generic HMC.' ) parser.add_argument('--json_file', dest='json_file', type=str, default=None, required=False, help='json file containing H...
ccdd77a32b6a5e63b85ca58578153758bae3a595
652,748
def grouped(sequence, key=None, transform=None): """ Parse the sequence into groups, according to key: >>> ret = grouped(range(10), lambda n: n % 3) >>> ret[0] [0, 3, 6, 9] >>> ret[1] [1, 4, 7] >>> ret[2] [2, 5, 8] """ groups = {} if not key: ...
ee73afaff8de674d2132971a78d507320b50d42e
652,749
import os import json def config_for_framework(framework): """Loads the JSON config for the given framework.""" fname = os.path.join(os.path.dirname(__file__), "image_uri_config", "{}.json".format(framework)) with open(fname) as f: return json.load(f)
afd4d058552a2bf87cd599a0d394934f06c86d5c
652,750
def _is_typing_object(type_object): """Checks to see if a type belong to the typing module. Parameters ---------- type_object: type or typing._GenericAlias The type to check Returns ------- bool True if `type_object` is a member of `typing`. """ return type_object._...
43c5326e158639f288e266f146a16ce8d35c7e2c
652,751
import argparse def __parse_args(): """ Parse all parser arguments that are provided when the script is running in a terminal. Returns ------- args: Namespace The parsed parser arguments. """ parser = argparse.ArgumentParser() parser.add_argument('-f', '--force', action=...
6c5812e511f31777711815b87f4f75a6b3337de5
652,752
def merge_dicts(*dictionaries): """Return a new dictionary by merging all the keys from given dictionaries""" merged_dict = dict() for dictionary in dictionaries: if not dictionary: continue merged_dict.update(dictionary) return merged_dict
310285cff7fb854abf3e39ef506d2bdd9f66002e
652,753
def read_conll(input_file, label_nr=3): """Reads a conllu file.""" ids = [] texts = [] tags = [] # text = [] tag = [] idx = None for line in open(input_file, encoding="utf-8"): if line.startswith("# sent_id ="): idx = line.strip().split()[-1] ids.appen...
24d72c49c7e2bdaa9492c52b74e54ce7afe668f6
652,754
import torch def get_optimizer(opts, model): """ Create optimizer and scheduler according to the opts """ opt_name = opts.optimizer.name.lower() if opt_name == "adam": opt_class = torch.optim.Adam else: raise NotImplementedError("Unknown optimizer " + opts.optimizer.name) o...
a670c7e07454eb04b1072bbc4b226251ef52e2f2
652,755
def convert(input_grid): """ Convert to digit string """ dct = { " _ | ||_| ": "0", " | | ": "1", " _ _||_ ": "2", " _ _| _| ": "3", " |_| | ": "4", " _ |_ _| ": "5", " _ |_ |_| ": "6", " _ | | ": "7", ...
e1ac565654f3da52af7c945aa59c9f0b3b2969b8
652,756
import math def define_joint_angle_list(shoulder_pan_joint, shoulder_lift_joint, elbow_joint, wrist_1_joint, wrist_2_joint, wrist_3_joint): """ This function takes float values for each joint and returns a list. :param shoulder_pan_joint: shoulder pan joint angle :param shoulder_lift_joint: shoulder l...
05010c00fc9440ac732938692e741e0825f86935
652,757
def NestedMultiplication(x, xValues, coeff): """Evaluates Newton Polynomial at x in nested form given the interpolating points and its coefficents""" n = coeff.size y = coeff[n-1] for i in reversed(range(n - 1)): y = coeff[i] + (x - xValues[i]) * y return y
143729cfab7bfd61e76b6195d505e34e81366ad9
652,758
import json def readJson(fname): """ Reads a Json file in: file name out: length of file, dictionary """ try: with open(fname, 'r') as f: data = json.load(f) return data except IOError: raise Exception('Could not open {0!s} for reading'.format((fname)))
b32ebe541d3475babb52f7570667820945926276
652,759
def get_max_draw_down(fund_ts): """ @summary Returns max draw down of fund time series (in percentage) @param fund_ts: pandas time series of daily fund values @return Max draw down of fund time series """ MDD = 0 DD = 0 peak = -99999 for value in fund_ts: if (value > peak): ...
b1972d84e09069a10f7fc319440e732cf7fc1773
652,760
def datetime_to_integer(dt_time): """Función que permite cambiar el formato de una fecha 'dt_time' a un número entero. El formato de 'dt_time' es datetime.date(año, mes, dia)""" integer = 10000*dt_time.year + 100*dt_time.month + dt_time.day return integer
5ae223699acc5a3789567a7d63314110ced8b46d
652,762
def __check_overlap_loop(d_i, all_images, am, invert): """ Helper function for multiprocessing """ D, I = d_i # Index 0 is always the reference video, so we keep that one. new_D = [D[0]] new_I = [I[0]] # Then loop index 1+ to look for videos that are not the same. for d, i in zip(D[...
a0a11d81dac398baee554855f8ce2151b1e1c145
652,763
def default_if_empty(value, arg): """ Set default one if the value is empty. String: None, '' Integer: None, 0 """ if not value: return arg return value
cf5575704c4aee50e7baefa5be93e248ddd24c11
652,764
def exitCodeToOutcome(exit_code): """convert pytest ExitCode to outcome""" if exit_code == 0: return "passed" elif exit_code == 1: return "failed" elif exit_code == 2: return "interrupted" elif exit_code == 3: return "internal_error" elif exit_code == 4: r...
caf15830c44353cc46ecdf0a322b39c71ae3dda9
652,765
import os def get_dataset_files(dateset_info, root): """Generates lists of files for a given dataset version.""" basepath = dateset_info.basepath base = os.path.join(root, basepath) num_files = dateset_info.size template = '{:0%d}-of-{:0%d}.tfrecord' % (4, 4) return [ os.path.join(base...
93df9a0e1b149c5b0f917f4c9be5b1fbfd0d4b35
652,766
def prep_ortho_and_graph(dir_cache, overviews, db_option, gdal_option, change): """Preparation for computation of ortho and graph""" print(" Préparation") # Calcul des ortho et graph args_create_ortho_and_graph = [] level = str(overviews["dataSet"]["level"]["max"]) for level in overviews['dataS...
41e6cb0bbd3bc1cf380d4102eea1bb933613d66e
652,767
def update_set(current_value, new_value): """Set Updater Returns: The value provided in ``new_value``. """ return new_value
2bffc6a8ab4eb42cca94ed311de4b0612c9ad154
652,769
from typing import Any def is_false(x: Any) -> bool: """ Positively false? Evaluates: ``not x and x is not None``. """ # beware: "0 is False" evaluates to False -- AVOID "is False"! # ... but "0 == False" evaluates to True # https://stackoverflow.com/questions/3647692/ # ... but comparison...
027ab344b5b646c6324fed3c2d441634082e4bce
652,770
def rosenbrock(x): """ Rosenbrock function (2-D). Global Optimum: 0.0 at (1.0, 1.0). Parameters ---------- x : array 2 x-values. `len(x)=2`. `x[1]` bound to [-5, 5]. `x[2]` bound to [-2, 8]. Returns ------- float Value of Rosenbrock function. ""...
d7df19ee764136b590702194d1deb27d5b10d18d
652,771
from typing import Iterable import click def _get_options_flags(options: Iterable[click.Option]): """ Given a list of options, produce a list of formatted option flags, like "--verbose/-v". """ return ", ".join(["/".join(opt.opts) for opt in options])
69e68aeeea5a36810b7c6a62374cbb9bd785024d
652,772
import ast from typing import Callable def bin_op(op: ast.operator) -> Callable[[ast.expr, ast.expr], ast.BinOp]: """Generate an ast binary operation""" def _bin_op(left: ast.expr, right: ast.expr) -> ast.BinOp: return ast.BinOp(left=left, op=op, right=right) return _bin_op
efe8f8fb7a23a53e304da67ab3ce9c6c5cfce42a
652,773
from argparse import ArgumentTypeError def timeout_check(value): """Проверка: время ожидания ответа сайта. Проверка опцией "--timeoutout" на достоверность. Аргумент - указание в секундах. Возвращаемое значение - число в секундах, которое используется для timeoutout-а. Примечание: Возникает ис...
2380b898b205e759f4a16e32fff1bc47b941894a
652,774
import math def norme_vecteur(vect): """Calcul de la norme d'un vecteur en dimension 2""" return math.sqrt(math.pow(vect[0],2)+math.pow(vect[1],2))
eb304827420403e75cece88a324a2e026c122bef
652,775
def gradient_descent(wb, dwdb, optimizer_args): """ The simple gradient descent update. Parameters ---------- wb : dict A dictionary of the weights/biases for each layer. dwdb : dict A dictionary of the gradients with respect to the weights and biases. optimizer_args...
ab6f626d4b6066e7105b074d2bb9581277044307
652,776
from datetime import datetime def now(request): """ Add current datetime to template context. """ return {'now': datetime.now()}
8d3d0ab4edcd1bc2dafbd6f3cdc14c6e27385a02
652,777
import random def roll_dice(sides=6) -> int: """Simulate Rolling a die. Uses random.randrange to calculate the roll. sides defaults to 6 sides. :param sides: number of sides the die has. :return: the int value of the roll. """ sides += 1 # Include the last number for randrange. roll...
21326f5505222c0351fcc41907d4bd50353b90c2
652,778
import os def local_download_path_lp(media, lp_size, download_dir): """ Retruns the full download path to a live photos video path including size e.g.: img1234.mov, img1234-small.mov, etc. """ if "Video" not in lp_size: raise Exception("ERROR: live photo size does not contain 'Video'") ...
dbf6234cf01902cb3270d25efa9488456c0c4012
652,779
import imp def flatten_post_config(slug): """ Returns a copy of post_config containing only configuration variables. """ config = {} post_config = imp.load_source('post_config', 'posts/%s/post_config.py' % slug) # Only all-caps [constant] vars get included for k, v in post_config.__...
09d83a4041e358bf687cc536432e36720b3fe656
652,780
def get_tw_refs(tw_refs_by_verse, book, chapter, verse): """ Retrurns a list of refs for the given book, chapter, verse, or empty list if no matches. """ if book not in tw_refs_by_verse: return [] if chapter not in tw_refs_by_verse[book]: return [] if verse not in tw_refs_by_vers...
d2a9379c9242d063a511dbd6d30666043dddb977
652,781
def assignFirstFive(l=['A', 'B', 'C', 'D', 'E']): """ task 0.5.19 use the list 'l' in and express that uses range and zip, but not using a comprehension """ return list(zip(range(len(l)), l))
f77a9d8dd314c18cf8dc9dc55686a647d78a90fc
652,782
def filter_dataset(dataset, is_pseudo_labelling): """Filter dataset depending on task (inference or pseudo_labelling)""" if is_pseudo_labelling: MIN_POINTS_NB_FOR_PSEUDO_LABELLING = 2000 return { plot_id: cloud_data for plot_id, cloud_data in dataset.items() i...
40ec0a5812979c5022c809180494ea10db8a6618
652,783
def diff_list(first, second): """Computes the difference between two input sets, with the elements in the first set that are not in the second. """ second = set(second) return [item for item in first if item not in second]
c67611f8f8080b4dada415680958855b82fdfb4e
652,785
def map_to_idx(data_list, vocab): """ Map a list of tokens to idx. """ if isinstance(data_list[0][0], list): # is a list of list of list data_by_idx = [] for d in data_list: data_by_idx.append(list(map(vocab.map, d))) return data_by_idx # is a list of list...
f7b96b0f10f22557a6458d66959d6f28e1fe8aa4
652,787
def pure_list(comma_list): """ Transform a list with items that can be comma-separated strings, into a pure list where the comma-separated strings become multiple items. """ pure_items = [] for comma_item in comma_list: for item in comma_item.split(','): pure_items.append(ite...
4de2e624a042ab8fa48d8a913ed545f65a8eb9ce
652,788
def wmo_correction(R_raw): """Apply WMO calibration factor to raw rain rate parameters ---------- R_raw : array like Rain rate in mm/h return ------ R_calib : pandas.DataFrame Corrected rain rate in mm/h """ R_calib = (R_raw / 1.16) ** (1 / 0.92) return R_ca...
a32efccbe669f2b5a8f4dc57685633e820679c9f
652,789