content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def filter_month(city, month):
"""Filter city data by month of the year.
INPUT:
city: pandas.DataFrame. The pandas DataFrame of city data.
month: str. The month of the year.
OUTPUT:
city data filtered by month of the year.
"""
# create new column for month of the year from Start Time a... | b306bb5f40bd6b722ebef7d9a8916ab0d5d268d0 | 614,261 |
def length_at_least(n):
"""Returns a function that checks whether a list has length at least ``n``.
Args:
n: The length to check against.
Returns:
A function that takes in a list ``l`` and returns ``True`` if
``len(l)`` is greater than or equal to ``n``.
"""
return lambda l... | 0820849aef611e931e108873abf05bcfa85f3601 | 614,264 |
def comput_iou(box1, box2):
"""
box1 : 代表的是第一个框的坐标(left, top, right, bottom)
box2 : 代表的是第二个框的坐标(left, top, right, bottom)
最后返回iou值
"""
# 首先计算第一个框和第二框的面积
box1_area = (box1[2] - box1[0]) * (box1[1] - box1[3])
box2_area = (box2[2] - box2[0]) * (box2[1] - box2[3])
# 接下来计算并的面积
uion_... | a40238397223f8e74c82bcedfa56800652198d54 | 614,268 |
import mpmath
def variance(k, lam):
"""
Variance of the noncentral chi-square distribution.
"""
k = mpmath.mpf(k)
lam = mpmath.mpf(lam)
return 2*(k + 2*lam) | d9a19f101071318ac1b95d2b867c81c2f522830d | 614,274 |
def permute_to_nchw(t):
""" for 4D tensors, convert data layout from NHWC to NCHW """
res = t.permute(0, 3, 1, 2).contiguous() if t.dim() == 4 else t
return res | b489410324c12002fde78a7dec41d9d3ca6a0ade | 614,276 |
def wood_cut(l, k):
"""
Cur woods into k pieces with maximum length
:param l: list of wood length
:type l: list[int]
:param k: number of pieces
:type k: int
:return: maximum cut length
:rtype: int
"""
if sum(l) < k:
return 0
left, right = 1, max(l)
while left + ... | 9d5d6cc0ac4748a34904599a50ce708994f411aa | 614,284 |
def clean_fielding(df):
"""
Clean the fielding dataset.
Remove unused columns.
- df: fielding dataframe
- return: cleaned dataframe
"""
#Remove unused columns:
df = df.drop(["PO", "A", "E", "DP", "PB", "WP", "SB", "CS", "ZR",
"InnOuts"], axis=1)
return d... | b04c237244f9dac3c777a2a3bb8ba6c2dce462e1 | 614,285 |
def genNDigitPalindrome(n, base=10):
"""
Generate all n-digit palendromes in requested base, in sequential order
"""
def _incrementPalinVec(palinVec, base):
# Increment a list of digits that encodes a palindrome number
n = 0
palinVec[n] += 1
while palinVec[n] == base:
palinVec[n] = 0
... | 7b9317e0aa8477d30c342fb4fe1687a12d9c41d5 | 614,292 |
import time
def unix_now_ms() -> float:
"""Return the current time in milliseconds since the Unix epoch."""
return time.time() * 1000 | 3de576ee97e888dc3422f0810bd7fac6d4db9439 | 614,295 |
from typing import Any
def is_list_type(arg: Any) -> bool:
"""Checks if 'arg' is of list type. Returns Boolean."""
return isinstance(arg, list) | 9affd5eb574aee6471e1084f7ee549b321a1ca17 | 614,299 |
def weighted_avg_forecast(source: list, window_size: int, num: int, weight: float=1.0):
"""
Forecast new values from a list of existing values using a weighted average delta formula.
Noticeably faster than linear regression while producing similar results.
Arguments:
source: List of data... | 7fc065554d7e12fea4bb2b26c1b5e0459ae4c130 | 614,302 |
def _intersect(lst_a, lst_b):
""" return the intersection of two lists """
return list(set(lst_a) & set(lst_b)) | 9540a6449cfdbbd5aebf4c42b8e63edd9f911a3f | 614,308 |
import re
def jsonp_is_valid(funcname):
"""Returns whether the jsonp function name is valid
:arg funcname: the name of the jsonp function
:returns: True or False
"""
func_regex = re.compile(
r"""
^[a-zA-Z_\$]
[a-zA-Z0-9_\$]*
(\[[a-zA-Z0-9_\$]*\])*
(\.[a-z... | a09acaef1fc54da661edfbff62cc39312faad25e | 614,309 |
def _match(doc, query):
"""Decide whether doc matches query."""
for k, v in query.items():
if doc.get(k, object()) != v:
return False
return True | e66d68f6f75e7c9f4907f13831675a9e385187e6 | 614,310 |
def is_even(x):
"""True if x is even, False if x is odd"""
return x % 2 == 0 | dcc48edf328b11a40c12d4199741da6138ce9b78 | 614,313 |
def _check_columns(df, columns):
""" Utility function to test for columns in dataframe
Parameters
----------
df : pd.DataFrame
columns : list
Returns
-------
bool
"""
for col in columns:
if col not in df.columns:
return False
return True | 8b12cb321787c93777f842ca05325f80004f0382 | 614,318 |
from typing import Set
def placeholders(text: str) -> Set[str]:
"""Get the set of names for all placeholders in the given string.
Placeholders start with '$' following the string.template syntax.
Parameters
----------
text: string
Template string.
Returns
-------
set of stri... | 85bc43b57f1f052d2c3324f10c7c234851550268 | 614,323 |
def get_author_avatar_upload_dir(instance, filename):
"""Determine upload dir for author avatar image files.
"""
return '/'.join(['authors', instance.user.username, filename]) | a49f0d6841ee2ee9abf701840616ee45bd2b1e13 | 614,324 |
def make_renderable(data: str) -> str:
"""
Modify a given string to allow it to display in Discord.
:param data: String with formatting characters.
:return: String with the appropriate escape characters to render string correctly.
"""
markup_characters = {
"_": "\\_",
"*": "\\*"... | e0198a73699603845ee62f0f1ae4ee0e68f91cdc | 614,331 |
def as_path(*args: str) -> str:
"""Converts strings to lowercase path-like string
Take variable order of string inputs
:param args: variable-length of strings
:return: string
"""
strings = []
for arg in args:
if arg is None:
continue
strings.append(str(arg).strip(... | b58d0b06f57ec93549431c23be00498aaf3bf5e4 | 614,334 |
import requests
def get_search_space(id_, url):
"""Perform a GET request and return the search space json."""
params = {"id": id_}
r = requests.get(url, params)
r.raise_for_status()
search_space_json = r.json()
return search_space_json | 4288b8f6764780a2ec5a8c971bf051bb6e4d625d | 614,337 |
import string
def class_to_int(k):
"""
Converts class id string into an integer. Note that this is the
inverse of cremona_letter_code.
EXAMPLES::
sage: import sage.databases.cremona as cremona
sage: cremona.class_to_int('ba')
26
sage: cremona.class_to_int('cremona')
... | e9d7e9dad1546a06b7d2c9e54d3444d780da12b7 | 614,339 |
def elapsed(delta):
"""
Return a pretty representation of an elapsed time.
"""
minutes, seconds = divmod(delta, 60)
hours, minutes = divmod(minutes, 60)
return "%d:%02d:%02d" % (hours, minutes, seconds) | 323cf47343dfb807061bc2825f62b0b49876e747 | 614,342 |
def key_value_list_to_map(list):
"""A function to transform key values lists into maps"""
m = {}
for k,v in list:
m[k] = v
return m | bcc80e5f4fff54ed7ff5f19b1bb9f434dcbf2c9c | 614,343 |
import csv
def loadAnnotationsFromFile(filename, sample_name, csv_separator):
""" loadAnnotationsFromFile(): Loads ORF annotations from a specified file and returns the relevant fields for each ORF
Parameters:
- filename: name of the file to load annotations from
- sample_name: name of t... | d7a45d0d42c14930e7ff9298b725fa822ae29a04 | 614,349 |
def producto_punto(vector_a, vector_b):
"""
(list, list) -> num
calcula el producto escalar entre dos vectores
>>> producto_punto([1,2], [1,2])
5
>>> producto_punto([2,2,2], [2,2,2])
12
:param vector_a: el primer vector
:param vector_b: el segundo vector
:return: num el escal... | 35fe9585706dff8f511fa40f58903dfa86dfd4c8 | 614,351 |
def decode_fizz_buzz(i, prediction):
"""Function to decode model prediction
Parameters
----------
i: int
Input number
prediciction: int
Label predicted by the neural network
Returns
-------
str
Decoded ouput of either the number, fizz, buzz or fizzbuzz
"""
... | 26a1b8bf2a45eac14793100d9381e73117ba8f7a | 614,353 |
def experimental(func):
"""
Decorator for marking APIs experimental in the docstring.
:param func: A function to mark
:returns Decorated function.
"""
notice = (
" .. Note:: Experimental: This method may change or "
+ "be removed in a future release without warning.\n\n"
... | 501f8477849486c7daeae4b613eac3e195010cf0 | 614,354 |
import operator
def ordered_values(iterable):
"""Return ordered list of values for iterable of OrderAndValue instances."""
return [
x.value for x in sorted(iterable, key=operator.attrgetter('order'))] | bed1a9e2be083ffe42d76c2ef551c901c83d86c4 | 614,355 |
def connect_points(pts1, pts2):
"""
Connects each point in the first list with all points in the second.
If the first list has N points and the second has M, the result are 2 lists
with N*M points each, representing the connections.
Parameters:
* pts1 : list
List of (x, y) coordinates ... | df1e89fda7cee228db31bfc14a5a5c50459f3e6e | 614,356 |
import importlib
def requires_module(module):
"""
Decorator that takes a module name as an argument and tries to import it.
If the module imports without issue, the function is returned, but if not,
a null function is returned. This is so tests that depend on certain modules
being imported will no... | 6fec997e82f0acadca0fb4a7e5215ece17857180 | 614,358 |
def isPrime(x):
"""Returns whether or not the given number x is prime.
A prime number is a natural number greater than 1 that cannot be formed
by multiplying two smaller natural numbers.
For example:
- Calling isPrime(11) will return True
- Calling isPrime(71) will return True
- Calling is... | e0041eb370ce15d5811a708469a20dc3fc2ca3a4 | 614,361 |
def extract_dims(array, ndim=1):
"""Decrease the dimensionality of ``array`` by extracting ``ndim`` leading singleton dimensions."""
for _ in range(ndim):
assert len(array) == 1, len(array)
array = array[0]
return array | e51661bdce5029ecc58db892b761820c5f6de7e8 | 614,364 |
def transient_calc(tup1, tup2):
"""
tup1 and tup2 should be tuples of broadcastable form (R, T, A)
tup1 is ground and tup2 is excited state spectra
returns dR/R, dT/T, and dA spectra.
"""
dRR = (tup2[0] - tup1[0]) / tup1[0]
dTT = (tup2[1] - tup1[1]) / tup1[1]
dA = tup2[2] - tup1[2]
r... | 42c5990fbeb068c7f555d7407be4abd769d3e2a3 | 614,369 |
import json
import click
def json_to_dict(ctx, param, value):
"""Convert JSON to dictionary"""
if value is None:
return {}
try:
return json.loads(value)
except ValueError:
raise click.BadParameter('Invalid JSON for {0}: {1}'.format(param, value)) | 68a72977be6dc48e82bcf7e82f19e3d1259f02af | 614,376 |
from typing import Optional
import re
def _id_from_xpath(string: str) -> Optional[str]:
"""Return a service id from a given xpath string.
Parameters
----------
string: str
String to check
Returns
-------
Optional[str]
Return env variable name if the pattern is detected
... | 6efc900d8ae6c59911b65ab00f9813bc66bf4131 | 614,377 |
def removeBadBands(spectrum, wavelengths, bbl):
"""
Remove bands that are marked as bad in bbl list.
Parameters
----------
spectrum : list of int
Spectrum as a list.
wavelengths : list of int
List of measured wavelength bands
bbl : list of str/int/bool
List of bbl va... | 63aeb612c66398f4a0962ebecfe12e467899922b | 614,379 |
def int_to_rgb(num):
""" Convert color from 24-bit integer to RGB """
color = bin(num)[2:].zfill(24)
b = int(color[:8], 2)
g = int(color[8:16], 2)
r = int(color[16:], 2)
return r, g, b | 8109ab54496a755710410b007c80acb37c04d912 | 614,380 |
from typing import Dict
from typing import Any
from typing import Optional
from typing import List
def create_query(
document: Dict[str, Any],
mutable: Optional[List[str]] = None,
joined: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""
Create a query document by shallow copying document and e... | 178826150993d793eddc24582fbc2a4e4b6dfb2f | 614,382 |
def wheastone(V_0, R1,R2,R3,R4):
"""
Wheastone formula function
Params :
- V_0 working voltage
- R1, R2, R3, R4 the resistances
"""
Vs = V_0 * (R4/(R1+R4)-R3/(R2+R3))
return Vs | d73ee0b291f10557d29620acb4cefbaac2aad7ec | 614,384 |
def create_graph(liveness):
"""Takes the liveness and transforms it to a graph (dict with key node, value set of edges"""
g = {}
for l_set in liveness:
for item in l_set:
s = (g[item] if item in g else set()) | l_set
if item in s: # remove self edge
s.remove(... | 05823b4e4d4372b5bce1f6a85c134677e7fa7e5c | 614,388 |
def single_splits(words=None):
"""Generate list of single splits of words excluding empty sequence.
words can be a sequence of strings or a string to to be split
into words delimited by whitespace
single_splits('a b c') returns [('a', 'b c'), ('a b', 'c')]
"""
if words is None:
return... | 25da20cbf1ba5775975d679086a94e5613cf4cb1 | 614,389 |
from typing import TypeVar
def is_type_var(t):
"""
Checks if t is a typing.TypeVar.
Args:
t (type):
Returns:
bool
"""
return isinstance(t, TypeVar) | a8e596100b96be668e2d3843f9e3f26f244d5f15 | 614,396 |
def quote_val(value):
"""Double quote a string value, if it's a string"""
quote_char = '"'
if isinstance(value, str):
# Is it already quoted?
if len(value) >= 2:
if value[0] == quote_char and value[-1] == quote_char:
# Yes, already quoted
return va... | 71e2212afad3cbdabc9c1875f0efe7e6d593fd4c | 614,397 |
def _concat_ngram_list(ngram_list):
"""Concatenates a list of n-grams.
Adjacent n-grams in the list are expected to be overlapping, and the
overlap is not duplicated in the returned concatenation. The contents of the
n-grams will not be checked however to verify the overlap.
E.g.
With ngram_list = ["abc",... | e7c502e752b1715b2b4f560d55b38b88cb85bb9a | 614,400 |
def latex_float(f, fmt='{:.1e}', phantom=False):
"""Convert float to LaTex number with exponent.
Parameters
----------
f : float,int,double
fmt : str
Python format string. Default: '{:.1e}'
phantom : bool
Add phantom zeros to pad the number if it does not fill the format string.... | b075035786d0e5468a15f34379817b85636f2bf8 | 614,403 |
def _align_center(to_align: str, length: int) -> str:
"""
Aligns a string so that it has a certain length and is center-justified.
:param to_align: The string to align.
:param length: The target length of the string. We will pad the string
on either side with spaces to reach this length.
:return... | dfe68eee6153aecbaf8d52da97500b5100b00fc4 | 614,404 |
def set_or_default(a, b):
"""If a is None, default of b is returned instead
"""
if a is not None:
return a
else:
return b | a7c5672307e4e67492b990d1e04fd87a9829f856 | 614,406 |
def flatten(alist):
"""Flatten a list. Each element in the list must itself be a list"""
return [x for y in alist for x in y] | 6e71492b73f8a4f15a5f5cb02cd712551b66a86b | 614,407 |
def get_all(futures, timeout=None):
"""
Collect all values encapsulated in the list of futures.
If ``timeout`` is not :class:`None`, the method will wait for a reply for
``timeout`` seconds, and then raise :exc:`pykka.Timeout`.
:param futures: futures for the results to collect
:type futures: ... | 14880bfcb1f964ec30ed8fdc19a789bab76e67b4 | 614,408 |
def slashAtTheEnd(url):
"""
Adds a slash at the end of given url if it is missing there.
:param url: url to check and update
:returns: updated url
"""
return url if url.endswith('/') else url + '/' | 344a557357b1b446548bb6d67b19efe1c393e62a | 614,411 |
def legal(a, b):
""" Returns True if the given index is on the board
- that is, both indices in the range 0 -> 7
"""
return a in range(8) and b in range(8) | d58bbc49ef0729ab9ad4309c274708a22d5c5557 | 614,413 |
def _minSec(*t):
"""Return a tuple of (mins, secs, ...) - two for every item passed."""
l = []
for i in t:
l.extend(divmod(int(i), 60))
return tuple(l) | cabf71ee50bceec9465b2e72b2218930ff80e70f | 614,414 |
import sympy
def round_sympy_expr(expr, decimals):
"""Returns the expression with every float rounded to the given number of decimals."""
rounded_expr = expr
for a in sympy.preorder_traversal(expr):
if isinstance(a, sympy.Float):
rounded_expr = rounded_expr.subs(a, round(a, decimals))
... | c1108fcae6f4c1697f30eebedd60373aafbd46a0 | 614,424 |
def is_context_manager(leaf):
"""
Returns true if the leaf is the beginning of a context manager
"""
has_suite_parent = False
parent = leaf.parent
while parent:
if parent.type == 'suite':
has_suite_parent = True
if parent.type == 'with_stmt':
return not ... | d5d61e042c562e96e8e15e72c4c3a431b4da58e3 | 614,425 |
def center_crop(x, y=None, crop_size=None, data_format='channels_last'):
"""
Takes a pair of numpy arrays (image and label) and returns a pair of matching center crops
:param x: image in numpy array format
:param y: label in numpy array format
:param crop_size: (height, width) tuple
:param data_... | 37ccee7858a74da8d95f1dcdb934550fa525e8a9 | 614,427 |
import bisect
def find_le(a, x):
"""Find rightmost value less than or equal to x.
General helper, adapted from <http://docs.python.org/2/library/bisect.html#searching-sorted-lists>.
"""
i = bisect.bisect_right(a, x)
if i:
return a[i - 1]
raise ValueError | 7782ec8ea23095d6337a165b312f5ec821615427 | 614,432 |
def rsa_crt_dmq1(private_exponent, q):
"""
Compute the CRT private_exponent % (q - 1) value from the RSA
private_exponent and q.
"""
return private_exponent % (q - 1) | 7286ba0c87836c4c48dce3364abcc57667ac81d7 | 614,434 |
import math
def is_prime_bf(n):
"""
Tests whether an integer is prime through brute force. A wheel (mod 6)
is used to test potential candidates.
Arguments:
n (:int) - the integer to be tested
Returns:
True if 'n' is prime and False otherwise
Examples:
>>> is_prime_bf(20)
>>> False
>>> is_prime_bf(... | 1b40d61496292a95fc9981a38046b653f78711a8 | 614,435 |
import math
def get_pen_width(significance, correlation):
"""
To calculate the pen width for graph edges.
:param significance: significance of the edge
:param correlation: correlation of the edge
:return: an integer between 0 to 5, rounding to ceiling side.
"""
return math.ceil(((signifi... | 099d5b9290f23b62436456af13dfa471399b2e75 | 614,436 |
def bl_kick_to_BACT(bl_kick, l=None):
"""Convert the bl_kick attribute (T*m) for a corrector into SLAC BACT compatible kG*m units"""
return -bl_kick*10.0 | 7aa9add49804eed3691d919be520a543c0178257 | 614,442 |
def _index_to_alphabet(index):
""" Convert the index to the alphabet.
"""
return chr(ord("A") + index) | 39d7f3fd5429bb69012f2c5bf3071dcaecbd6c26 | 614,444 |
def quadout(x):
"""Return the value at x of the 'quadratic out' easing function between 0 and 1."""
return -x*(x-2) | 26be2601051cb5b7e7a6a8c2e4c496c4d5d8d9e7 | 614,445 |
def post_json(session, url, python_obj):
"""Send a json request and decode json response."""
with session.post(url, json=python_obj) as response:
response.raise_for_status()
return response.json() | da96371b070c2d2b7b6fec8aa7b80a9073fbd6e7 | 614,452 |
def get_start_end_idx(waveform):
"""
Take a raw waveform and return the indices when the signal actually
begins and ends, i.e. the indices of the first non-zero elements in the
(reversed) waveform.
Args:
waveform: A raw waveform, i.e. one that still is zero-padded.
Returns:
sta... | ed234de0bc3d95eab514cc4927f55e5342171951 | 614,453 |
def rstrip_word(text, suffix):
"""Strip suffix from end of text"""
if not text.endswith(suffix):
return text
return text[:len(text)-len(suffix)] | 6649c16845cea3dd3f714163c9714a6344f4f026 | 614,454 |
def _replace_reserved_char(s):
"""Return the given string with all its brackets and # replaced by _."""
for c in '()[]{}#':
s = s.replace(c, '_')
return s | 32b74b3a36577378ca23e8982e001595599f4c48 | 614,456 |
def is_vaccine_available_18(df):
"""
Return True if vaccine is available for 18 plus else return False.
Parameters
----------
df : pandas.core.frame.DataFrame
Pandas Dataframe containing data received from the API.
Returns
-------
bool
True if vaccine is available for 1... | 5447e76732ced3447452634b9327ad9a0853827b | 614,458 |
def convert_composition_vector_to_dict( g, Xv ):
"""Convert a composition vector Xv into a dict, for a given gas g"""
Xd = {}
for iv, v in enumerate(Xv):
if v > 0.0:
Xd[g.species_name(iv)] = v
return Xd | e4a8f362f279f99009fdc8d078c44ca5fb883de5 | 614,459 |
from typing import Tuple
def compute_patch_y_offset(patchXSize: Tuple, patchYSize: Tuple,
patchInnerStride: Tuple, predictionDelay: int) -> Tuple:
"""
Compute the offset of the Y-patch relative to the X-patch.
"""
patchYOffset = [0] * len(patchXSize)
for dim in range(len... | 7800834f1300dec6ba77fc02fbf57756fe09688a | 614,460 |
def rank(X):
"""
Return the rank of each element in X
"""
sorted_X = sorted(X)
rank = [0]*len(X)
for i in range(len(X)):
# since index is zero-based, plus 1 to get the rank
rank[i] = sorted_X.index(X[i]) + 1
return rank | bfca829b99a9fc85bcc65da3f56d05dc719776a5 | 614,461 |
def is_directory(entry):
"""Returns true if the given entry is a directory"""
return entry['nlink'] > 1 | 0d890a25e4b31d0974614f64ef93cd95d2c55ade | 614,463 |
def hrsize(size):
"""Return human-readable size from size value"""
if size < 1000:
return '%d%s' % (size, 'B')
for suffix in 'KMGTPEZY':
size /= 1024.
if size < 10.:
return '%.1f%sB' % (size, suffix)
if size < 1000.:
return '%.0f%sB' % (size, suffix)
... | b4d6336496fb6911469428e0a8767829d9bb6269 | 614,465 |
import yaml
def _load_file(path):
"""Load a yaml file."""
with open(path) as f:
return yaml.safe_load(f) | df8a4be4e96e4042620dee28f14ec9e0d29f8d7c | 614,470 |
from typing import Dict
def string_to_dict(s: str, delimit: str = "=") -> Dict[str, str]:
"""
Split a string containing key/value pairs into a dictionary
\f
Parameters
----------
s : str
String to split
delimit : str (default: "=")
character to use when splitting key/value... | ba891e5a69990cb516b10ee58c4924c48e18c21c | 614,471 |
import pytz
def datetime_to_utc_string (d):
""" Unlike everything else, take a DATETIME and produce
a string representing the datetime as UTC.
"""
d_utc = d.astimezone(pytz.timezone('UTC'))
return d_utc.strftime("%FT%H:%M:%SZ") | d9b4e5912a8c95281d271e82c24cb1f8ee486a18 | 614,472 |
def getFahrenheit(tempC):
"""Convert degrees Celcius to degrees Fahrenheit"""
return tempC * (9.0/5.0) + 32 | 50cd8a883d0e831e5edcb82586444607ff2568bb | 614,475 |
from typing import Dict
from typing import Union
def formula_dict_to_str(formula: Dict[str, Union[int, float]]) -> str:
"""
Converts a sum formula from a dictionary like {'C': 12, 'H': 6, 'O': 3} to a
string like C12 H6 O3
>>> formula_dict_to_str({'Elem_C': 12, 'Elem_H': 6.5, 'Elem_O': 3, 'Elem_Mn': ... | 9d3be94cb5136738382dd381b174d4f9e710c713 | 614,476 |
def gen_numvec(numb, length):
"""
Given a number return a vector of 1's and 0's corresponding to that
number's binary value.
"""
ovec = []
for _ in range(0, length):
ovec.append(numb % 2)
numb //= 2
return ovec | ab31a36cf6a303d3e9827774c089bff8b6713c9b | 614,477 |
def search_nodes(root, func=lambda x: True):
"""
Search nodes from the root in a BFS manner.
:param root: the root node.
:param func: a filtering function.
"""
nodes = []
queue = [root]
while queue:
cur_node = queue.pop(0)
for node in cur_node.node_vals:
if ... | bba267d43094e2130dd21d2e41b373ea60e414a9 | 614,478 |
def sigma_to_pdf_percentiles(sigma):
"""
Looks up the percentile range of Gaussian for a given
standard deviation.
Parameters
----------
sigma: [1, 2, 3, 4, 5]
The standard deviation to calculate a percentile.
Returns
-------
Lower: float
The lower percentile
Hi... | 5cf197b57828708e3849f5b1a1c1457ee401bec5 | 614,480 |
import re
def get_cell_name( content ):
"""
Get the cell name from an igor output file
:param content: The content to search
:returns: The cell name of the file
"""
name_search = 'X S_cellname="(.*)"'
match = re.search( name_search, content, flags = re.IGNORECASE )
if match is None:
... | e8c3c2e32da1f26e0a8f39ead04ef95d386930ca | 614,481 |
import unicodedata
def subst(table, text):
"""
Make string substitutions using a two-column table.
The table specified should already contain any uppercase and lowercase
variants that should be applied for substitution.
"""
text = unicodedata.normalize('NFC', text)
for term1, term2 in ta... | 5fa66950c1025ded89bb1e9ddc7cfc0b6b920300 | 614,487 |
def filter_samples(sample_dirs, changed_files):
"""Filers the list of sample directories to only include directories that
contain changed files."""
result = []
for sample_dir in sample_dirs:
if sample_dir.startswith('./'):
sample_dir = sample_dir[2:]
for changed_file in chang... | 9bf488bae52c37b69635a282ccf04d9821428bd5 | 614,488 |
def reverse_compl_with_name(old_seq):
"""Reverse a SeqIO sequence, but keep its name intact."""
new_seq = old_seq.reverse_complement()
new_seq.id = old_seq.id
new_seq.description = old_seq.description
return new_seq | 6b3e1fcbc4e27dc0420b55227df620cc045caa05 | 614,489 |
import math
def freq_to_slider(freq):
"""
convert frequency (20Hz-20kHz) to slider value
base-2 logarithmic slider
"""
return math.log2(freq) * 1e4 | 776e04f69d0facdb485598d2ec8d8eb04b47b347 | 614,490 |
def AllEnumValues(enum):
"""Return all enum values associated with an enum.
Args:
enum: {mojom.Enum} The enum type.
Returns:
{Set[int]} The values.
"""
return set(field.numeric_value for field in enum.fields) | 2ec6dd94701254197384ef6d72df34516d379c26 | 614,492 |
def get_edge(starting_node, ending_node, edges_dictionary):
"""
Get the edge_document which connects starting_node with ending_node.
:param starting_node: osm_id
:param ending_node: osm_id
:param edges_dictionary: {starting_node_osm_id -> [edge_document]}
:return: edge: edge_document
"""
... | f48210b36dd15324a228f5520ddf2e68327281d1 | 614,496 |
def GroupSelect(GroupCheckBool):
"""
GroupSelect is a function to select the all True group in GroupCheckBool.
If there are more than one group is all True, choose the group with more
Trues. Or choose the first all True group if the number of True are the
same. If there is no group is all True, retu... | 79e184ffb1991b06f0d3572b89e2c9a0dfd0089d | 614,497 |
def datasets_from_frame(dataframe, feature):
"""Creates a dict dataset from a dataframe
Given a categorical feature it creates a dict where each key is
a level of the feature and each value is a dataframe, then you
can use this datasets dict to plot graphs
Args:
dataframe (pandas.DataFrame... | 9423a32639b2db433f56517e1f98ea3c4e2e656c | 614,498 |
from typing import List
def hyphen_range(string: str) -> List[int]:
"""
Expands a string of numbers separated by commas and hyphens into a list of integers.
For example: 2-3,5-7,20-21,23,100-200
"""
list_numbers = list()
temporary_list = string.split(",")
for element in temporary_list:
... | 2a8ebd5a60c180e722db053e4e9d4c69808d8fc8 | 614,500 |
def ipath(i):
"""Returns path names '/test 1', '/test 2', ... """
return f"/test {i}" | 00017e48023b17fe6e2b3ad94220d1a5df0e703d | 614,502 |
import re
def keep_only_latin_characters(input):
"""keep only latin characters
Args:
input (string): text to apply the regex func to
"""
regex = re.compile("[^\u0020-\u024F]")
return regex.sub("", input) | 60e000e821002a4290697ca9cf2e6b42f825d108 | 614,504 |
def source(bot, trigger):
"""Simply replies with a link to my modules' source"""
url = "https://github.com/cottongin/sopel-modules"
return bot.say(f"You can find the source to my custom modules here: {url}") | e50c3c1200e7932dec8e6e2878d98043d824d03c | 614,505 |
import copy
def safe_deepcopy_env(obj):
"""
Perform a deep copy of an environment but without copying its viewer.
"""
cls = obj.__class__
result = cls.__new__(cls)
memo = {id(obj): result}
for k, v in obj.__dict__.items():
if k not in ['viewer', 'automatic_rendering_callback']:... | c09f38ad36e32ccb22cd7b9b22a68463f4eb165a | 614,507 |
import re
def parse_error(msg):
""" Parses MS SQL Server error messages into a dictionary.
The message information is returned as a dictionary with keys:
- SQLSTATE
- DRIVER
- DESCRIPTION = The detailed error description.
- CODE = The SQL Server error code
- CMD
... | d81c81a3e0a9d63c74ca1168c42dde5ffe739001 | 614,510 |
def normalize_feature(year, feature):
"""Normalize feature."""
feature = {**feature, "year": feature.get("year", year)}
return feature | a21eee89b01885508025786f1df3e8487aa843e6 | 614,511 |
import decimal
def _decimal2string(d):
"""Format a decimal to a human readable string."""
# https://stackoverflow.com/questions/11227620/drop-trailing-zeros-from-decimal/18769210#18769210
normalized = d.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent > 0:
normalized = decimal.Decimal((... | 9638ee1b0d22728da16b1e13de43377e61921458 | 614,512 |
def getExotStatus(cursor, id_tax):
"""
Get the alien/invasive status of a taxon, with the associated references and links
Parameters
-----------
cursor: psycopg2 cursor
cursor of the current operations in the postgres database (need to be of psycopg2.extras.RealDictCursor type, in order... | 32f4a8fd9477ee99ba261791a8d8b64e0ad35db8 | 614,515 |
def total_return_nb(total_profit, init_cash):
"""Get total return per column/group."""
return total_profit / init_cash | 7ccf811471ea2d12400b6c1f53bde1e28726321e | 614,517 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.