content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def square(x):
"""square()"""
return x * x | 12a16315a0c82bfaf7a7a339f39787923368ff98 | 676,442 |
def get_gear_ratio(g: int, gear_ratios: dict):
"""get gear ratio
Args:
g (int): gear
gear_ratios (dict): mapping of gear to gear ratio
Returns:
[float]: gear ratio
"""
return gear_ratios[g]['ratio'] | 79554d5c9b3cab209a69209c2959d053974db0db | 676,444 |
def search(strings, chars):
"""Given a sequence of strings and an iterator of chars, return True
if any of the strings would be a prefix of ''.join(chars); but
only consume chars up to the end of the match."""
if not all(strings):
return True
tails = strings
for ch in chars:
tail... | d35911ed246928c8fba025c2727e08f0f17603dc | 676,445 |
import random
def unicode_encode_invalid():
"""
Generate invalid unicode data.
:return: a tuple of invalid unicode codepoint and empty bytes.
"""
def out_of_unicode():
return random.randint(0x110000, 0xFFFFFFFF)
def in_surrogate():
return random.randint(0xD800, 0xDFFF)
w... | 6884c10d354f20e2ac92ae5a9b3652989be7a58d | 676,446 |
def key_value_list(d):
"""
This function iterates over all the key-value pairs of a dictionary and
returns a list of tuples (key, value).
Parameters
----------
d : Union[dict, list]
The dictionary to iterate through
Return
------
str
A list of tuples (key, value).
... | eb1491450a12b02c20f35f31a9fca64308d1ee7c | 676,447 |
def fill_leaf_values(tree):
"""
Recursive function that populates empty dict leaf nodes.
This function will look for all the leaf nodes in a dictionary
and replace them with a value that looks like the variable
in the template - e.g. {{ foo }}.
>>> fill_leaf_values({'a': {}, 'b': 'c': {}})... | da9d576e3c3f574f7cbb08d8ab9b0a6193ef5e22 | 676,448 |
def process_xpath(xpath, trigger):
"""
Process the xpath to extract data from a trigger
@param xpath - xpath location in trigger
@param trigger - trigger metadata to extract XPath
"""
ret = trigger
parts = xpath.replace("xpath.", "").split(".")
for part in parts:
if ret is None ... | d02460e58886acbe593408f504ec0eb1aed967de | 676,449 |
def quadinterp(x, x0, x1, x2, y0, y1, y2):
"""
Quadratic interpolation
"""
L0 = (x-x1)*(x-x2) / ( (x0-x1)*(x0-x2) )
L1 = (x-x0)*(x-x2) / ( (x1-x0)*(x1-x2) )
L2 = (x-x0)*(x-x1) / ( (x2-x0)*(x2-x1) )
return y0*L0 + y1*L1 + y2*L2 | 624c172cc1fd924de6ee50a2da197389a2c6123c | 676,450 |
import json
import collections
def load_json_file(filename, use_ordered_dict=True):
""" Load a dictionary from a file
Parameters
----------
* filename: string
\tThe path to the saved json file.
* use_ordered_dict: bool
\tIf set to True dicts are read as OrderedDicts.
"""
tmp = Non... | c3730c7356689d4bc43c07f4e8c44755613965b4 | 676,452 |
def _all_none(*args):
"""Returns a boolean indicating if all arguments are None"""
for arg in args:
if arg is not None:
return False
return True | 102d3d73dc51d6dd851106e674a4e89a8d925a29 | 676,454 |
def _cuda_dot_product(a, b):
"""Calculate the dot product between two 1D arrays of length 3.
Parameters
----------
a : numba.cuda.cudadrv.devicearray.DeviceNDArray
b : numba.cuda.cudadrv.devicearray.DeviceNDArray
Returns
-------
float
"""
return a[0] * b[0] + a[1] * b[1] + a[2]... | 1cad81f54fd0521ed58ae8e1cc79743451482f6f | 676,455 |
def pad(block, block_length):
"""
Pads a block with padding bytes to make it
to the required length, in this case, 128 bits.
PKCS5 padding
Parameters
----------
block : string
Block to be padded written in hexadecimal as string.
block_length : int
Block length in ... | 1bc060071750d3e8892d789118eb008c70b26f3b | 676,456 |
import pickle
def load_pickled(filename: str) -> dict:
"""
The function loads pickled items / sessions object.
Parameters
----------
filename : str
Returns
-------
pickled_object : dict
"""
with open(filename, 'rb') as stored_data:
pickled_object = pickle.load(stored_... | 5aae003f8e75336d4b9ee35b417d7cec0eecea29 | 676,458 |
from datetime import datetime
def instantiate_datetime_object(datetime_stamps):
"""Takes a datestamp as a string and instatiates it into an object.
>>> datetime_stamps = [u'2016-09-10T15:35-07:00', u'2016-09-10T16:48-07:00']
>>> instantiate_datetime_object(datetime_stamps)
[datetime.datetime(2016, 9,... | 36f4c8a191bd7bdf3f3ae24f4162b53ed49ce3f0 | 676,459 |
import statistics
def average(numbers, averagetype='mean'):
"""
Find the average of a list of numbers
:type numbers: list
:param numbers: The list of numbers to find the average of.
:type averagetype: string
:param averagetype: The type of average to find.
>>> average([1, 2, 3, 4, 5], '... | 288346821ea92a75bb71e05c69a4d5e638382926 | 676,460 |
def hr_sub(match):
"""Matches a horizontal rule."""
return '\n\n<hr/>\n\n' | dd0c2f30ab899174df48ee31b81b21058626b7d5 | 676,461 |
def spin_inversion(x,N,sign_ptr,args):
""" works for all system sizes N. """
xmax = args[0]# maximum integer
return x^xmax | 1e5d5c7dd228dbf85b56227a270b256e9a2f154a | 676,462 |
def error(text):
"""
Error Function with Red Color texted retrun string
"""
return text | 8ad2ec068bcabb119953b4e5dc6c9ef9a79bd38b | 676,463 |
def make_cached_property(func, cache_on_class=False):
"""Helper function for cached_property and class_cached_property decorator."""
attr_name = "_cache_" + func.__name__
@property
def _cached_property(self):
obj = self.__class__ if cache_on_class else self
if not hasattr(obj, attr_nam... | a3f97f2535a1d6efd8b0e69afd148d5eab65006f | 676,464 |
from typing import Optional
from typing import List
def _media_option(
argument: Optional[str],
prefix: str,
*,
allow_auto: bool = False,
min_num: int = 1,
max_num: int = 12,
) -> List[str]:
"""Validate the number of columns (out of 12).
One or four integers (for "xs sm md lg") betwee... | 1b418be005c819fb316127579d7ae644c53716de | 676,465 |
def parse_line(line):
"""0 <-> 454, 528, 621, 1023, 1199"""
line = line.split(" ")
return {"id": int(line[0]), 'connected': list(map(lambda num: int(num.replace(",", "")), line[2:]))} | 1ac631ae29fadd06992913ff38f2c7e8b56f2b22 | 676,466 |
import math
def get_objectives(data):
"""Get a list of all first chromosomes' objective values."""
objectives = [math.log(population[0]["objective"]) for population in data]
# objectives = [population[0]["objective"] for population in data]
return objectives | 870138db39a0e4c2b3d9c95bdd236bab20f4935e | 676,467 |
def parse_group_benefits_in_kind(table):
"""
ukparl_groups
Parses the Benefits In Kind table
"""
headings = {
"0": "Source",
"1": "Description",
"2": "Value£sInbandsof£1,500",
"3": "Received",
"4": "Registered",
}
fields = {
"0": "interest_fr... | 4db9645b67619b1e6612c44b6f580928bbcdcfb2 | 676,468 |
import requests
def total_search(size=50, page=0):
"""Finn de første antallet = 'size' fra side 'page' og få ut json"""
size = min(size, 50)
r = requests.get(
"https://api.nb.no:443/catalog/v1/items",
params = {
'filter':'mediatype:bilder',
'page':page,
... | 77eb649eb36f9d96f035b75fc51eec98cc62fc94 | 676,469 |
def get_raw_instances(self):
"""
Documentation:
---
Description:
Associate each EC2 instance ID with its EC2 instance object.
---
Returns:
raw_instances : dict
Dictonary where the keys are EC2 instance IDs and the
values ar... | c689d9939e183d353ed8d3c0bc22332952fdbd0c | 676,470 |
import re
def camel_to_snake_case(camel_cased_string):
"""Convert the format of the given string from CamelCase to snake_case.
Args:
camel_cased_string: the string in CamelCase format.
Returns:
the same string, but in snake_case format.
"""
return re.sub(r"(?<!^)(?=[A-Z])", "_", cam... | 7c7e688681c701f1ba6dc0d597bfea4c3fb08f3b | 676,471 |
def assign_ctr(df):
"""calculate ctr and assign new col "position"
Arguments:
df -- source DataFrame
"""
return df.assign(ctr= lambda x: x.clicks / x.impressions) | 1039c32d95c38c3d61743d9fe42a64ad30746e25 | 676,472 |
import time
def get_date():
"""
gives you the date in form:
day - month - year
:rtype: str
"""
return time.strftime('%d-%m-%Y') | 68333a0bedf1ffbd830e79fbcb96b5b6a5e450bd | 676,473 |
import types
def is_function(obj):
"""Check if obj is function(lambda function or user defined method) or not"""
return isinstance(obj, (types.FunctionType, types.MethodType,
types.LambdaType)) | 1f912336a594cb4813c420914e3e550529eafe48 | 676,474 |
import os
import json
def load_pretrained_models_json():
"""
Loads pretrained_model.json data and returns it.
"""
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir, 'pretrained_models.json')) as json_file:
data = json.load(json_file)
return data['... | 5da9559069553267aefe14ca175c96be32f7a620 | 676,475 |
def is_not_phage_func(x):
"""
These are some annotations that are definitely not phages, but often look like them.
:param x: the function to test
:return: True if it is NOT a phage function.
Note that False suggests it maybe a phage function, but may not be (we are not sure)!
"""
x = x... | 0e9739f77349eec6f28563b48f42b7b7e61a62c9 | 676,476 |
def _LoadWords(dict_file):
"""Returns a set of all the words in the dict file."""
words = set(word.strip().upper() for word in open(dict_file))
# Remove all single letter words except A, I.
for c in 'BCDEFGHJKLMNOPQRSTUVWXYZ':
words.remove(c)
return words | e5d6e8d6d35177ef5f0ad0cc3a75a5b31c866899 | 676,477 |
def process(data, template_name_key, split_char=";", **kwargs):
"""
Function to split templates. e.g. if ``template_name_key`` value
contains several templates, this processor will split them using
``split_char`` and produce data item for each template coping data
accordingly.
:param data:... | 4b7c3255e1eed60ff4f72b21b9ad414f794c81ba | 676,478 |
import math
def Collision(cilantropicx, cilantropicy, chickenpicx, chickenpicy):
"""This function calculates the distance between chicken and a cilantro image on the screen to check if they "collided" and returns True or False. Since our images appear to accurately "collide" when their distance is 40 pixels, the ... | e2cf30cd73beadc3854a7ede46c8cc39151901a0 | 676,479 |
import numpy
def generateParentInfo(mlMesh):
"""
get array P[l,e] = e_c, where element e_c is the parent of element e
P[0,:] = -1
"""
#mwf now use new interface
P = mlMesh.elementParentsArrayList
P = {}
nLevels = len(mlMesh.meshList)
P[0] = numpy.ones((mlMesh.meshList[0].nEleme... | f76145bd0fa0c702c928076f2e318f0edd5ae1c1 | 676,480 |
def dt_name(value, member_id=None):
"""
Format name complex data type
:param value:
:param f_value
"""
if isinstance(value, str):
return value
f_value = ""
for n in value:
family_str = ""
given_str = ""
suffix_str = ""
if 'given' in n:
... | 6fea363b664d93137f1713cc6cb679314f87e64a | 676,481 |
def is_online():
"""
Being able to call this function means the server is online and able to handle requests.
:return: True
"""
return True | f17b9fe4c3447ab966acc7ebc616eaba81fffc8e | 676,482 |
import zipfile
import os
def unzip_delete(path,delete = True):
"""
Unzip a zip file and delete the .zip file.
"""
with zipfile.ZipFile(path, 'r') as zip_ref:
zip_ref.extractall(path.replace(".zip",""))
if delete == True:
os.remove(path)
return path.replace(".zip","") | c0e3e6259d421ca5718c9e89394015d24448f408 | 676,483 |
def filtermetadata(text):
"""Extract just the revision data from source text.
Returns ``text`` unless it has a metadata header, in which case we return
a new buffer without hte metadata.
"""
if not text.startswith(b'\x01\n'):
return text
offset = text.index(b'\x01\n', 2)
return tex... | 408dbdff971d8939fc48fb37188671c511a29b6f | 676,484 |
def get_required_attribute(el, key):
""" Get attribute key of element *el*.
:raises: :exc:`ValueError` if key not found
"""
val = el.get(key)
if val == None:
raise ValueError('required attribute missing: ' + key)
return val | 007156504130d90dc1001fd661d0094dfbf917e2 | 676,485 |
def calc_histograms(img_to_show):
"""Calculate histograms
Get R, G, B histogram values from an image.
Args:
img_array (image obj): image object to use
Returns:
r (list): list of histogram values for red pixels
g (list): list of histogram values for green pixels
b (list)... | db7fc32f7e29ee407c18a86c0ca920be1e0bd37b | 676,486 |
import os
def id_detect(d):
"""
Auto detect next free id in directory d
"""
mx = 0
for f in os.listdir(d):
if os.path.isdir(os.path.join(d, f)):
try:
i = int(f)
mx = max(mx, i)
except:
pass
print('Detected course I... | 189035e61f6f12f818af390334772a34f550ee0d | 676,487 |
def check_bounds(position, limit, buffer):
"""Check whether a co-ordinate is within a limit (including a buffer).
One dimensional, and assumes the lower limit is 0 (less the buffer)."""
if position < 0 - buffer:
return limit + buffer
elif position > limit + buffer:
return -buffer
e... | 0a3c0860e10b9d0988eacfd52e321768ae9fad69 | 676,488 |
def get_frame_index(d):
"""Get frame index from the whole dictionary
E.g.,
'{'index': 'data/Deploy/KLAC/KLAC0570/KLAC0570_12.jpg', 'prediction': ..., 'label': ...}'
==> (int) 12
"""
return int(d['index'].split('_')[-1][:-4]) | 4560b4255374784834c5c16c8b365d1b5b1d0fcd | 676,490 |
import re
def strip_project_url(url):
"""strip proto:// | openstack/ prefixes and .git | -distgit suffixes"""
m = re.match(r'(?:[^:]+://)?(.*)', url)
if m:
url = m.group(1)
if url.endswith('.git'):
url, _, _ = url.rpartition('.')
if url.endswith('-distgit'):
url, _, _ = url... | 1005ef4c62582eb848031e211e8faf435654a290 | 676,491 |
def q_normalize(q):
"""Return a normalized quaternion"""
mag = (q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3])
if mag != 0:
for i in range(4):
q[i] /= mag;
return q | 9ca0386a9f9c8e48658ba54c4ce619b175790590 | 676,492 |
import os
import io
def deal_with_empty_file_stream(data):
"""对于文件流的剩余长度为0的情况下,返回空字节流"""
if hasattr(data, 'fileno') and hasattr(data, 'tell'):
try:
fileno = data.fileno()
total_length = os.fstat(fileno).st_size
current_position = data.tell()
if total_len... | ef4d73aa401a73e6dbe8dc868a608d6c9770a7d6 | 676,494 |
def get_dc(si, name):
"""
Get a datacenter by its name.
"""
for dc in si.content.rootFolder.childEntity:
if dc.name == name:
return dc
raise Exception('Failed to find datacenter named %s' % name) | 12b075c78f0dd1d999cf783a7933a231e9af1785 | 676,495 |
def gen_poc(*args):
"""
Generate poc.
:param args:
:return:
"""
return '$$$$$$'.join(args) | 40bf971a3197182680ea069f94f1e5714a86a373 | 676,496 |
import os
import glob
def _get_ucf_files(path):
"""recursively search for ucf files"""
ucf_files = []
for base, dirs, _ in os.walk(path):
for d in dirs:
p = os.path.join(base, d)
ucf_files.extend(_get_ucf_files(p))
search_path = os.path.join(path, '*.ucf')
ucfs = g... | be1dd86c3c8f39dd5614caf75beec509c98fa35b | 676,497 |
def granularity_to_ms(time_string):
"""Returns millisecond representation of granularity time string"""
magnitude = int("".join([c for c in time_string if c.isdigit()]))
unit = "".join([c for c in time_string if c.isalpha()])
unit_in_ms = {
"s": 1000,
"second": 1000,
"m": 60000,
... | 91512755af5e990bb03fc225a83f7acd77c015d1 | 676,498 |
import argparse
def process_arguments():
""" Process command line arguments """
parser = argparse.ArgumentParser(description="Enron Corpus Parser")
parser.add_argument("-a", "--addressbook", help='path to e-mail addressbook',
type=argparse.FileType('r'), required=True)
parser.a... | 8c61fb15a4efb29373cad4c1c6f026a85cb14d93 | 676,500 |
def features_labels():
"""Give a name to each feature"""
return ["zrc", "energy", "en_ent", "centr", "spread"] + ["mfcc{}".format(i) for i in range(13)] | 9c59f9a402e32578e2717998c4ab221930ede406 | 676,501 |
def IIN_to_DOB(IIN):
"""
return DOG IIN provided
http://adilet.zan.kz/rus/docs/P030000565_
1 - для мужчин, родившихся в 19 веке;
2 - для женщин, родившихся в 19 веке;
3 - для мужчин, родившихся в 20 веке;
4 - для женщин, родившихся в 20 веке;
5 - для мужчин, родившихся в 21 веке;
6 -... | 560f6eaf6f12cfe9016a8804a12d2a554abf1c2b | 676,502 |
def is_curious_fraction(numerator, denominator):
"""
Determine if two numbers form a curious fraction.
A curious fraction is where removing a number common to the numerator and
denominator is equal to the original fraction.
:param numerator: The numerator of the fraction as an int.
:param den... | 346ba10f33725cd9058206c957cb72bd3bfef148 | 676,503 |
def available_bert_model():
"""
List available bert models.
"""
return ['multilanguage', 'base', 'small'] | 5ab7b17cda88a78cbc5571637440f0daf07b6c32 | 676,504 |
import requests
def get_files(master_url, pr_url, headers):
"""
Returns the contents of the current version of the file and
of the modified version of the file in a tuple.
Args:
master_url (str): URL to the current version of the file
pr_url (str): URL to the modified version of the f... | 04a7945136c24efd1d29ef780281a8851fbeb71d | 676,505 |
def contour(ax, x, y, z, labels=True, **kwargs):
"""
Wrapper around Matplotlib's contour plot.
We add a small convenience argument `labels` that allows to simply add
clabels with a simple `labels=True`.
"""
cs = ax.contour(x, y, z, **kwargs)
if labels:
ax.clabel(cs, inline=1, fontsi... | c8e2d87bbaffbf67750da2f1449854361dc9601e | 676,506 |
def bubble_sort(m):
"""
Sorts a list using the bubble sort algorithm.
m = The unsorted list.
Examples
bubble_sort([4,7,6,3,2,5,1])
# => [1,2,3,4,5,6,7]
Complexity: O(n^2)
Returns the sorted list.
"""
swaps = []
for j in range(len(m)):
for k in range(len(m) - 1... | e39fa4c2538ff285be04f5c319a542665534eeb6 | 676,507 |
def gc_content(seq):
""" GC content of a given sequence. """
seq = seq.upper()
return (seq.count('G') + seq.count('C'))/len(seq) | f631d38dca81df3a881c04e13628c68d62880786 | 676,508 |
def get_int(row, key, ignore_start=0, ignore_end=None):
""" row is the csv row to get an integer from,
key is that row's column that we want to cast as int,
start/end is the number of leading/trailing characters to ignore.
return 0 if could not convert
"""
try:
s = row[key][ignore_star... | 1d77fb3f4a0686b045894b4fd31d26c65b87ffd2 | 676,509 |
def binary(dataframe, entity_id, feature_id):
"""
Create binary feature dataframe using provided dataset, entity, and feature.
:param dataframe: Input dataframe to create binary features
:type dataframe: cudf.DataFrame
:param entity_id: Entity ID. Must be a column within `dataframe`
:type entit... | fd54366d6dc0949f701ee70d729f2d85d713bfd4 | 676,510 |
def filterl_index(predicate, List):
"""
Return the index of elements that satisfy the predicate function.
:param predicate:
:param List:
:return:
"""
result = []
for idx, e in enumerate(List):
if predicate(e):
result.append(idx)
return result | 8d71dad89271baedc7f233ef4fd9a8aa8579dece | 676,511 |
def parse_feats(feats):
"""
Helper function for dealing with the feature values that Stanza returns.
They look like "Case=Nom|Gender=Fem|Number=Sing" and we convert it to a dictionary with keys "Case" (e.g. "NOM"), "Gender" (e.g. "FEM"), "Number" (e.g. "SIN"). We capitalize the values and make them 3 charac... | 1d9858fe29220e319bcb92c494c65c719da68ce6 | 676,512 |
import random
def random_agent(network,agent1):
"""
Chooses a random agent relative to another agent. Meaning, if one
picks 'A' and wants another random agent to make a pair, 'A' will not
be chosen. Sets up a connection between two random agents.
Parameters
----------
network: Cayley netw... | b0c9750fda6a17bf85a06e4fc46c9f665f8d6776 | 676,513 |
def get_dna_base_from_reference(chr, start, num_seq=5, ref_fasta=None):
"""
Get the base of DNA from start-num_seq to start+num_seq, totally 2*num_seq+1
The center start is 0-based start position
:param chr:
:param start:
:param end:
:return:
"""
if ref_fasta is None:
raise... | ec29c8f935695b89f69d3f636936dbc4d9494230 | 676,514 |
from typing import List
def fibo(nth: int) -> List[int]:
"""Fibonacci numbers up to the `nth` term starting with 0 and 1."""
fibos = [0, 1]
for _ in range(nth - 2): # - 2 because we already have the first two
fibos.append(fibos[-1] + fibos[-2])
return fibos | e960cd5cf3520be0de343d2e615d7bf3e87d1bea | 676,515 |
def failing_tests_to_report(test_list_instance):
"""return failing tests to be reported for this test_list_instance"""
return test_list_instance.failing_tests() | c52f1b1886590b20ed8f1edfefd4f6640e2d1fc6 | 676,516 |
def parameterize_cases(argnames, cases):
"""
This is used for parametrizing pytest test cases.
argnames: a comma separated string of arguments that the test expects.
cases: a dictionary of test cases.
"""
argnames_list = [i.strip() for i in argnames.split(',')]
argvalues = [tuple(i[k] for k... | 9c5bd5a3c6ccbdf571291d97253945bcc2aaea45 | 676,517 |
def add_newlines_by_spaces(string, line_length):
"""Return a version of the passed string where spaces (or hyphens) get replaced with a new line if the accumulated number of characters has exceeded the specified line length"""
replacement_indices = set()
current_length = 0
for i, char in enumerate(st... | 326d59fe3d9db67545ed3b9fd4cff487cff51af1 | 676,518 |
def replace_insert(insert, compiler, **kw):
"""Allow replace into for insert command.
This only works for MySQL. It's not standard SQL. To enable this function,
the sql.flavor config must be set to mysql.
"""
s = compiler.visit_insert(insert, **kw)
if 'mysql_replace_insert' in insert.kwargs:
... | f302d2c6ba73595833a99a30a5bc9b67107015d2 | 676,519 |
from typing import Any
import inspect
def isdata(the_object: Any) -> bool:
"""Check if an object is of a type that probably means it's data."""
return not (
inspect.ismodule(the_object)
or inspect.isclass(the_object)
or inspect.isroutine(the_object)
or inspect.isframe(the_objec... | 89f0a81cdc63859409539ce5eed5153deff80e53 | 676,520 |
def bool_to_pass_fail(value:bool) -> str:
"""Converts a boolean True to "Pass" and False to "Fail"
Parameters
----------
value : bool
A boolean value representing True for Pass and False for Fail
Returns
-------
str
"Pass" or "Fail"
"""
if value:
return "Pa... | 804a343eddc872f704f60732019f74464846ce19 | 676,521 |
def get_logical_switch(client_session, logical_switch_name):
"""
:param client_session: An instance of an NsxClient Session
:param logical_switch_name: The name of the logical switch searched
:return: A tuple, with the first item being the logical switch id as string of the first Scope found with the
... | 970d5d052281091b8f7312dc39986bcd8af4da58 | 676,522 |
def euklid_vektor (vec):
"""berechnet die Länge eines Vektors
Vektor (Eingabe): Liste der Form [x1, x2, x3]"""
result = (vec[0]**2 + vec[1]**2 + vec[2]**2)**0.5
return result | 3be841a87a2381d1602a5e8e4638db62abcd176f | 676,525 |
def fill_headers(tree, table):
"""
tree -- header_tree returned from set_headers
table -- built Table
return -- col_leaves
"""
leaves = []
# sweep tree top to bottom, left to right.
depth = 0
current_sweep = tree.children
while current_sweep:
cols_to_left = 0
... | 324502516f390c2372949b9233d36a03d3cfa15d | 676,526 |
import json
def load_json(json_file):
"""
Opens json-file and returns it as dictionary
:param json_file: path to json-file
:type json-file: string
:returns: the content of the json file as dictionary
"""
with open(json_file) as infile:
content = json.load(infile)
ret... | 211623ba735fcc9bbc624814e9d1712eb9f156a1 | 676,527 |
import re
def sanitize_for_url(word):
"""
Sanitizing of a word with a regex search string - everything that is not alphanumeric, a space or a colon is
substituted by an empty set
Args:
word (str): Word to sanitize
Returns:
str: Sanitized string
"""
return re.sub('[^a-zA-Z\s:]', '', word) | e8f6aa8a1e471bd8af2533702bca84ea7f027e5b | 676,528 |
from typing import Counter
def normalize_counts(counts):
"""Return a normalized Counter object."""
normed = Counter()
total = float(sum(list(counts.values()), 0.0))
assert total > 0 # cannot normalize empty Counter
for key, ct in list(counts.items()):
normed[key] = ct / total
return n... | 159479a53d2a0de94f4528674ecb978b692d3df0 | 676,529 |
def set_icon_image(icon):
""" Set Icon image or set None """
# Icon message files: https://stackoverflow.com/questions/37783878/
# is-it-possible-to-get-tkinter-messagebox-icon-image-files
# ::tk::icons::warning
# ::tk::icons::error
# ::tk::icons::information
# ::tk::icons::question
if i... | eefee87244274e06b9ad67899d9d8fe5cb3743e5 | 676,530 |
def est_query(gen_data, att_select, value_select):
"""estimate aggregate result according to
att_select and value_select, return count()
"""
count = 0.0
lenquery = len(att_select)
# pdb.set_trace()
for record in gen_data:
est_value = 0.0
for i in range(lenquery-1):
... | ad503dc0884c14739cece7dc39ad4b9d6662eecc | 676,532 |
def read_seq_from_fasta(fasta):
"""retrieves the sequence of a fasta file, returns it as string
"""
with open(fasta, "r") as f:
seq = ""
for line in f:
if line:
if not line.startswith(">"): # ignore header
seq += line.strip()
return seq.up... | 52700ca370e76284bbd839785b14001b81de56fb | 676,533 |
def bump_build_number(d):
"""
Increase the build number of a recipe, adding the relevant keys if needed.
d : dict-like
Parsed meta.yaml, from get_meta()
"""
if 'build' not in d:
d['build'] = {'number': 0}
elif 'number' not in d['build']:
d['build']['number'] = 0
d['b... | d835b5e8467b5b8f02d96ef0f15408f281d880e0 | 676,534 |
import ast
def replace_ast_names(ast_tree, ast_param_dict):
"""Replace names in a tree with nodes in a dictionary.
Parameters
----------
ast_tree : ast.AST
tree to replace nodes in
ast_param_dict : Dict[str, ast.AST]
parameter dictionary mapping parameter name (name ID in the tree... | 0af95ddf47f3e676e6ee22680bc0577b62ef5df2 | 676,535 |
import re
def selfupdate(module, port_path):
""" Update Macports and the ports tree. """
rc, out, err = module.run_command("%s -v selfupdate" % port_path)
if rc == 0:
updated = any(
re.search(r'Total number of ports parsed:\s+[^0]', s.strip()) or
re.search(r'Installing ne... | 1977c5b2f401a1f7f0893fa828f173387b3c63a1 | 676,536 |
def reduce_score_to_chords(score):
"""
Reforms score into a chord-duration list:
[[chord_notes], duration_of_chord]
and returns it
"""
new_score = []
new_chord = [[], 0]
# [ [chord notes], duration of chord ]
for event in score:
new_chord[0].append(event[1]) # Append new note... | cbc363b4f7318bf1cf7823281ace8da61fac2195 | 676,537 |
import sqlite3
def run_query(db, sql, fetchone=False):
"""
Arguments:
- `sql`:
"""
data = {}
with sqlite3.connect(db) as con:
cursor = con.cursor()
cursor.execute(sql)
if fetchone:
data = cursor.fetchone()
else:
data = cursor.fetchall()
... | d3f6328ded70d7ffe5034337f87e79b34ae9c908 | 676,538 |
import math
def get_tile_name(x, y):
"""
Find which 5km National grid square contains the given point
:param x: Easting
:param y: Northing
:return: tile_name: 5x5 km nation grid tile
"""
# Ensure grid boundaries are correct
if y % 5000 == 0:
y = y - 1
# Get first letter
... | 9db42d9586e2bd5658aaab87a77043173268a241 | 676,539 |
def cast_value_type(value, dtype):
"""cast_value_type Cast Value Data Type
Cast value data type based on the datatype in TimeScaleDB
Args:
value ([type]): value to be casted
dtype ([type]): TimeScaleDB data type
Returns:
object: casted datatype
"""
try:
if dtyp... | 830e40b3d07c59d7361ca358867bbebed741ecbf | 676,540 |
def tim2str(t):
"""
方法: datetime类型转为固定格式字符串,用于从数据库取出时间转换
"""
try:
return t.strftime("%Y-%m-%dT%H:%M:%S+08:00")
except Exception:
return None | d23b851e639d58d525bfb43e9167be0a759d5058 | 676,541 |
def _get_package():
""" Workaround for missing ``__package__`` in Python 3.2
"""
if(('__package__' in globals()) and (__package__ is not None)):
return __package__
return __name__.split('.', 1)[0] | eea8a46cd52f08e35e4642579e092ec333f16899 | 676,542 |
def _get_prepped_model_field(model_obj, field):
"""
Gets the value of a field of a model obj that is prepared for the db.
"""
try:
return model_obj._meta.get_field(field).get_prep_value(getattr(model_obj, field))
except:
return getattr(model_obj, field) | ec376030896d996bf8e0133645d4e276f50bc7c1 | 676,543 |
import logging
def hhmm_to_seconds(inputtime:str):
"""Converts a time string in the from of Y-M-DTH:M to seconds"""
timelist = inputtime.split('T')
timenow = str(timelist[-1])
minutelist = str(timenow).split(':')
logging_string = "Converted " + inputtime + " to seconds"
logging.info(logging_st... | 4dba9efa3ec7dcd186ad1d9cee92828a3433d9b2 | 676,545 |
def substructure_vec_to_substructure_dict(substructure_vec):
"""convert the substructure vector to dictionary with degree as key"""
substructure_dict = {}
for i in substructure_vec:
# print(i,))
if str(len(i)) not in substructure_dict.keys():
substructure_dict[str(len(i))] = [i]
... | 9556e7a8c3449eb6027086cddd5d407d86b71b49 | 676,546 |
import re
def substitute(string, substitutions):
"""
Take each key in the substitutions dict. See if this key exists
between double curly braces in string. If so replace with value.
Example:
substitute("my name is {{name}}.",{version:1,name=John})
> "my name is John"
"""
for key, valu... | 8afc8fafcc34bf138598f8f5cb24a7da6a9b79cf | 676,547 |
from pathlib import Path
from typing import List
def get_candidate_paths(parent: Path, name: str) -> List[Path]:
""" Combines all of the candidate paths for each file for simplicity. The previous method of
defining candidates individually was getting complicated.
"""
candidates = [
# The usual locations for t... | 4cbf6d07d920d6049428e90709f251cb889e9815 | 676,548 |
import argparse
def create_parser():
"""Create parser to handle arguments from CLI.
:return:
"""
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title="Commands", dest="subparser_name")
subparsers.add_parser("generate-settings", help="Generate settings.json to install "
... | aa5516bd2be874899325bdadd9769a7f737947d6 | 676,549 |
import functools
def remove_all(string, substrs):
"""Removes a whole list of substrings from a string, returning the cleaned
string.
Args:
string (str): A string to be filtered
substrs (:obj:`list` of :obj:`strs`): The substrings to remove from the string
Returns:
str: string... | bac271131211e4ae03ff15b5c3ef5190502d001c | 676,550 |
def make_array_of_dicts_from_response_json(response_json, index):
"""
Makes array of dicts from stats.nba.com response json
:param dict response_json: dict with response from request
:param int index: index that holds results in resultSets array
:return: list of dicts with data for each row
:rt... | 33454154fa984d5622127b71ea24d2dcf18bc060 | 676,551 |
def poke_32(library, session, address, data):
"""Write an 32-bit value to the specified address.
Corresponds to viPoke32 function of the VISA library.
Parameters
----------
library : ctypes.WinDLL or ctypes.CDLL
ctypes wrapped library.
session : VISASession
Unique logical ident... | 04bd390c2539d02bd572680940b1d0d768d59f60 | 676,552 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.