content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def interpolate_zeros(x, f):
"""
For two float arrays of data, representing a 2d plot (x, f) in
order - determine all the locations of x at which f crosses zero
(using linear interpolation). Return as a list.
"""
assert len(x) == len(f)
xcross = []
for i in range(len(f) - 1):
x0, x1 = x[i], x[i + 1]
f0, f1 = f[i], f[i + 1]
if (f0 >= 0. and f1 < 0.) or (f0 <= 0. and f1 > 0.):
xcross.append(x0 - (x1 - x0) * f0 / (f1 - f0))
return xcross
|
89f6da8616b21661d1fac8b6bbbc06d97ceea31d
| 557,971 |
from torch import randperm
from torch._utils import _accumulate
def split_datasource(datasource, lengths):
"""
Split a datasource into non-overlapping new datasources of given lengths
"""
if sum(lengths) != len(datasource):
raise ValueError("Sum of input lengths does not equal the length of the input datasource")
indices = randperm(sum(lengths)).tolist()
return [[datasource[i] for i in indices[offset - length: offset]]
for offset, length in zip(_accumulate(lengths), lengths)]
|
2bc5ab8cbc7677309545669ec136b70ae2e57fc9
| 120,962 |
def is_subclass(obj, superclass):
"""Safely check if obj is a subclass of superclass."""
try:
return issubclass(obj, superclass)
except Exception:
return False
|
4812f0e245546446256d0d2e9a305167e87da08d
| 649,515 |
def get_games(event_sets: list) -> list:
"""
gets games from a list of sets
"""
games = []
for event_set in event_sets:
set_id = event_set['id']
for game_number, game in enumerate(event_set['games']):
if game['selections'] is not None:
game['setId'] = set_id
game['gameNumber'] = game_number
games.append(game)
return games
|
9ab6bc6a0f395496aad3e41ab4169ea0b9a0f467
| 472,870 |
from pathlib import Path
def pad_filename(filename):
"""
pyAudioAnalysis adds stuff like "131.700-132.850" and "14.200-26.500" to the output filenames
this doesn't sort properly because the numbers like 131 and 14 are not padded with zeros.
"""
time_range = Path(filename).stem.replace('2000-essential-korean-words-', '')
from_timestamp, to_timestamp = (float(ts) for ts in time_range.split('-'))
return f'{from_timestamp:08.3f}-{to_timestamp:08.3f}'
|
2d2be8eb643c025bd2b691383190c6de33326d92
| 179,356 |
def argsort(seq):
"""
Same as NumPy's :func:`numpy.argsort` but for Python sequences.
:param seq: a sequence
:return: indices into `seq` that sort `seq`
"""
return sorted(range(len(seq)), key=seq.__getitem__)
|
f203643aa1dd78490a2cc9d817e7a9fa6b2c6542
| 550,289 |
def make_matrix(num_rows, num_cols, entry_fn):
"""构造一个第 [i, j] 个元素是 entry_fn(i, j) 的 num_rows * num_cols 矩阵"""
return [
[
entry_fn(i, j) # 根据 i 创建一个列表
for j in range(num_cols)
] # [entry_fn(i, 0), ... ]
for i in range(num_rows)
]
|
e76598f8b87a50b99da6214cd18f37479ef64724
| 686,033 |
import json
async def _stream_next_event(stream):
"""Read the stream for next event while ignoring ping."""
while True:
last_new_line = False
data = b""
while True:
dat = await stream.read(1)
if dat == b"\n" and last_new_line:
break
data += dat
last_new_line = dat == b"\n"
conv = data.decode("utf-8").strip()[6:]
if conv != "ping":
break
return json.loads(conv)
|
ef4b03788ca9b0943cb6f2f5ecea49f98f0f8d9b
| 472,441 |
def divide(a, b):
"""
Divide two numbers
Parameters:
a (float): counter
b (float): denominator
Returns:
float: division of a and b
"""
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b
|
1ad6d5f5b542e197140797c0cf1d80372547782c
| 584,672 |
def expand_addrmask(addrmask):
"""Expands a masked memory address to a list of all the applicable memory
addresses it could refer to. That is, a string like "00X1010X" could stand
for the binary numbers 00010100, 00010101, 00110100, or 00110101, which
correspond to decimal values 20, 21, 52, or 53, respectively. So if you
give this function the string "00X1010X", it will output the list
[20, 21, 52, 53]. """
out = [""]
for d in addrmask:
if d == "X":
d = "01"
# wow python list comprehensions are awesome. It took me a while to
# futz my way to the correct syntax but this is really smooth
out = [a + i for a in out for i in d]
return out
|
696f110de8066ae7da27d6d8dba06285c7bc44b7
| 56,902 |
def compute_fibonnaci(n: int):
"""
Compute the nth term in the fibonacci sequence.
"""
if n == 0:
return 0
if n == 1:
return 1
return compute_fibonnaci(n-2) + compute_fibonnaci(n-1)
|
80011255abd2485bdc9e82651f63a274db7b319a
| 452,925 |
from typing import OrderedDict
import math
def clean_anime_details(information_dict):
"""
Cleans raw extracted data
Parameters
----------
information_dict: dict
The dictionary holding extracted data
"""
# Creating final dictionary from dictionary passed since hard to account for values (changes sometimes based on page).
clean_information_dict = OrderedDict()
# Removing whitespace
clean_information_dict["AltNameEnglish"] = information_dict["English"].strip() if "English" in information_dict else None
clean_information_dict["AltNameSynonyms"] = information_dict["Synonyms"].strip() if "Synonyms" in information_dict else None
clean_information_dict["MediaType"] = information_dict["Type"].strip() if "Type" in information_dict else None
# try-except due to type conversion
try:
clean_information_dict["EpisodeCount"] = int(information_dict["Episodes"].strip()) if "Episodes" in information_dict else None
except:
clean_information_dict["EpisodeCount"] = None
clean_information_dict["CurrentStatus"] = information_dict["Status"].strip() if "Status" in information_dict else None
clean_information_dict["Aired"] = information_dict["Aired"].strip() if "Aired" in information_dict else None
clean_information_dict["Premiered"] = information_dict["Premiered"].strip() if "Premiered" in information_dict else None
clean_information_dict["Broadcast"] = information_dict["Broadcast"].strip() if "Broadcast" in information_dict else None
clean_information_dict["Producers"] = ",".join(map(lambda x: x.strip(), information_dict["Producers"].split(","))) if "Producers" in information_dict else None
clean_information_dict["Licensors"] = ",".join(map(lambda x: x.strip(), information_dict["Licensors"].split(","))) if "Licensors" in information_dict else None
clean_information_dict["Studios"] = ",".join(map(lambda x: x.strip(), information_dict["Studios"].split(","))) if "Studios" in information_dict else None
clean_information_dict["Source"] = information_dict["Source"].strip() if "Source" in information_dict else None
clean_information_dict["Genres"] = ",".join(map(lambda x: x.strip()[0: math.floor(len(x.strip()) / 2)], information_dict["Genres"].split(","))) if "Genres" in information_dict else None
clean_information_dict["Duration"] = information_dict["Duration"].strip() if "Duration" in information_dict else None
clean_information_dict["Rating"] = information_dict["Rating"].strip() if "Rating" in information_dict else None
try:
clean_information_dict["Score"] = float(information_dict["Score"].strip()) if "Score" in information_dict else None
except:
clean_information_dict["Score"] = None
try:
clean_information_dict["ScoredByCount"] = int(information_dict["ScoredByCount"].strip()) if "ScoredByCount" in information_dict else None
except:
clean_information_dict["ScoredByCount"] = None
try:
clean_information_dict["Ranked"] = int(information_dict["Ranked"].strip()[1:]) if "Ranked" in information_dict else None
except:
clean_information_dict["Ranked"] = None
try:
clean_information_dict["Popularity"] = int(information_dict["Popularity"].strip()[1:]) if "Popularity" in information_dict else None
except:
clean_information_dict["Popularity"] = None
try:
clean_information_dict["MembersCount"] = int(information_dict["Members"].strip().replace(",", "")) if "Members" in information_dict else None
except:
clean_information_dict["MembersCount"] = None
try:
clean_information_dict["FavoritesCount"] = int(information_dict["Favorites"].strip().replace(",", "")) if "Favorites" in information_dict else None
except:
clean_information_dict["FavoritesCount"] = None
clean_information_dict["Title"] = information_dict["Title"].strip() if "Title" in information_dict else None
clean_information_dict["Synopsis"] = " ".join(information_dict["Synopsis"].strip().split()) if "Synopsis" in information_dict else None
clean_information_dict["MyAnimeListId"] = information_dict["MyAnimeListId"]
clean_information_dict["PromoVideo"] = information_dict["PromoVideo"].strip() if "PromoVideo" in information_dict else None
clean_information_dict["PromoVideoBackgroundImage"] = information_dict["PromoVideoBackgroundImage"][information_dict["PromoVideoBackgroundImage"].find("(") + 2: information_dict["PromoVideoBackgroundImage"].rfind(")") - 1] if "PromoVideoBackgroundImage" in information_dict else None
clean_information_dict["ImageSrc"] = information_dict["ImageSrc"].strip() if "ImageSrc" in information_dict else None
return clean_information_dict
|
596487db6c675aaa4a252e6cf0e2cb6a60f9f6b0
| 419,647 |
def _get_snapshot_id_and_previous_session_id(session_spec, data_store):
"""Retrieve the snapshot ID and previous session ID in a tuple.
Args:
session_spec: session_pb2.SessionSpec proto containing info about current
session to draw the previous session and snapshot from.
data_store: data_store.DataStore instance to retreive the snapshot object
from.
Returns:
snapshot_id, previous_session_id.
"""
if session_spec.snapshot_id:
snapshot = data_store.read_by_proto_ids(
project_id=session_spec.project_id, brain_id=session_spec.brain_id,
snapshot_id=session_spec.snapshot_id)
else:
snapshot = data_store.get_most_recent_snapshot(
session_spec.project_id, session_spec.brain_id)
if snapshot:
return snapshot.snapshot_id, snapshot.session
return '', ''
|
85493e3fa6ab1cf24d289d6d70372fb79cd218b6
| 594,947 |
def _compare_across(collections, key):
"""Return whether all the collections return equal values when called with
`key`."""
if len(collections) < 2:
return True
c0 = key(collections[0])
return all(c0 == key(c) for c in collections[1:])
|
453335cea7303b5c16a52550af09eb64df1f0b2e
| 95,849 |
def multivariate_regression_predict(X, w_opt):
"""Predict with multivariate regression.
Arguments:
X {DataFrame} -- Independent variables.
w_opt {ndarray} -- Parameter values.
Returns:
ndarray -- Predicted values.
"""
X = X.values
y_pred = X.dot(w_opt)
return y_pred
|
34a9d70dfc2a4a647184255413a792f5270004d0
| 649,986 |
def compute_direct_sort_map(lang):
""" Return a map from each sort s to a list of the objects that have s as their direct sort
(i.e. ignoring parent sorts). """
res = {s: [] for s in lang.sorts if not s.builtin}
_ = [res[o.sort].append(o) for o in lang.constants()]
return res
|
6c3428842ddb7f414b5863b36a391f2ef9c27f56
| 229,702 |
def is_new_subscription(doc):
"""
Returns `True` if `Subscription` has never generated an invoice
"""
return len(doc.invoices) == 0
|
b1359de9ff7233714354e7ce52348322c6d3f08f
| 207,863 |
from typing import List
import random
def training_room_names(random_order: bool = True) -> List:
""" return training room names in (random) order """
names = ['Trainings']
if random_order:
random.shuffle(names)
return names
|
57efe215ee1ae76e5e64271ee9f3c20913763f3e
| 465,373 |
def check_month(month_number, month_list):
"""
Check if a month (as integer) is in a list of selected months (as strings).
Args:
month_number: The number of the month.
month_list: A list of months as defined by the configuration.
Returns:
Bool.
"""
month_map = {
1: 'january',
2: 'february',
3: 'march',
4: 'april',
5: 'may',
6: 'june',
7: 'july',
8: 'august',
9: 'september',
10: 'october',
11: 'november',
12: 'december',
}
return month_map.get(month_number, '') in month_list
|
9ae09aa80536e37763efc7b6601c4c793e9afd3a
| 266,570 |
def is_valid_variable_name(varname):
"""
Tests if a variable name is valid.
Variable names must:
- begin with an alphabetic character
Variable names can:
- contain arbitrarily many single quotes as their final characters
x or x' or x''' but not x''yz
- contain any sequence of alphanumeric characters and underscores between
their first character and ending single quotes
Usage:
>>> is_valid_variable_name('x')
True
>>> is_valid_variable_name('x_')
True
>>> is_valid_variable_name('_x')
False
>>> is_valid_variable_name('df_1')
True
>>> is_valid_variable_name("cat''")
True
>>> is_valid_variable_name("cat''dog")
False
"""
varname_pieces = varname.split("'")
if len(varname_pieces) > 1:
if not all(piece == "" for piece in varname_pieces[1:]):
return False
front = varname_pieces[0]
return front[0].isalpha() and front.replace("_", "").isalnum()
|
11e5e4ae70cb801ba0da9847bb35363d48d61c4c
| 530,715 |
def _get_indices_dataset_notexist(input_time_arrays):
"""
Build a list of [start,end] indices that match the input_time_arrays, starting at zero.
Parameters
----------
input_time_arrays
list of 1d xarray dataarrays or numpy arrays for the input time values
Returns
-------
list
list of [start,end] indexes for the indices of input_time_arrays
"""
running_total = 0
write_indices = []
for input_time in input_time_arrays:
write_indices.append([0 + running_total, len(input_time) + running_total])
running_total += len(input_time)
return write_indices
|
f1a3f1946c972841eba01f2362a886b29d4250a1
| 82,387 |
from typing import Tuple
from pathlib import Path
def endswith(path, suffixes: Tuple[str, ...]) -> bool:
"""
Returns whether the path ends with one of the given suffixes.
If `path` is not actually a path, returns True. This is useful
for allowing interpreters to bypass inappropriate paths, but
always accepting streams.
"""
if isinstance(path, Path):
return path.suffix.lower() in suffixes
if isinstance(path, str):
return path.lower().endswith(suffixes)
return True
|
0feae633bede862ac839b95ebe0a9b3ffd16949d
| 642,147 |
def group_by_with_aggregation(
df,
by,
agg_column_names,
aggregators = ('mean', 'std')
):
"""Group by with aggregation.
Args:
df: Dataframe to perform group by on.
by: Which column to group by.
agg_column_names: Which columns to aggregate over. Have to be columns
containing numeric values.
aggregators: Which aggregation functions to apply.
Returns:
Multi-level dataframe where each row corresponds to a group and contains
aggregated values for specified agg_column_names and aggregators.
"""
agg_dict = {}
for col in agg_column_names:
agg_dict[col] = aggregators
return df.groupby(by, as_index=False).agg(agg_dict)
|
cea86b5d7c9cbcbfaae9d26eb52e58ecb2e8eb47
| 563,064 |
from typing import Dict
from typing import Any
import pprint
def describe_item(data: Dict[str, Any], name: str) -> str:
"""
Function that takes in a data set (e.g. CREATURES, EQUIPMENT, etc.) and
the name of an item in that data set and returns detailed information about
that item in the form of a string that is ready to be sent to Discord
"""
item = data.get(name)
if item is None:
return "I'm sorry. I don't know about that thing"
s = pprint.pformat(item, indent=2, sort_dicts=True)
return s
|
4df9e99f713effc00714342f54e2bd135b580675
| 20,777 |
def float_to_bin(num, length):
"""
Convert float number to binary systems
:param num: Number to change
:type num: float
:param length: The maximum length of the number in binary system
:type length: int
:return: Returns a number converted to the binary system
:rtype: string
"""
temp_2 = ''
temp = float(num)
for x in range(length):
temp = temp * 2
if temp < 1:
temp_2 += "0"
else:
temp_2 += "1"
temp -= 1
return temp_2
|
0f6c0f404ff0abb8251bd5f9b9370ab639cbcaad
| 436,566 |
def merge(left, right):
"""
再帰処理中で呼び出す、分割された配列を結合する関数
再帰処理中で呼び出すため、渡される配列はソート済み
:param left: 左側の配列
:param right: 右側の配列
:return: 結合された配列
"""
merged = []
l_i, r_i = 0, 0
# ソート済みの配列をマージするため、それぞれ左から見ていくだけで良い
while l_i < len(left) and r_i < len(right):
# ここで=をつけることで安定性を保っている
if left[l_i] <= right[r_i]:
# 左側の配列の要素の方が小さいとき
# つまり、この時点で並べ替えされてない要素では、
# この要素が最小である
merged.append(left[l_i])
l_i += 1
else:
# 右側の配列の要素の方が小さいとき
merged.append(right[r_i])
r_i += 1
# 上のwhile文のどちらかがFalseになったら終了するため、あまりをextendする
if l_i < len(left):
merged.extend(left[l_i:])
if r_i < len(right):
merged.extend(right[r_i:])
return merged
|
4c514ec29043b4fc0719d0fc110ef870fb7e9d4b
| 216,019 |
def extract_crops(image, size, stride=1):
"""Extract crops of size size from image using stride. Careful! This function only works for a batch_size = 1.
Args:
image: torch tensor, dtype = torch.float32.
expected dimensions: C X W X H,
e.g. torch.Size([3, 224, 224])
size: size of the returned crops
stride: number of pixels moved until next crop is extracted.
Here: 1 (Even though, by default, BagNet-33 was trained with stride 8 and uses stride 8 when used to predict classes.)
Returns:
crops: tensor of size number_of_crops x n_channels x crop_size x crop_size,
e.g. torch.Size([36864, 3, 33, 33])
type = torch.float32
"""
image_permuted = image.permute(1, 2, 0)
crops_unfolded = image_permuted.unfold(
0, size, stride).unfold(
1, size, stride)
crops = crops_unfolded.contiguous().view((-1, 3, size, size))
return crops
|
01d65d79a26eb15c5c2144b1b72f3bbabb80bad7
| 193,590 |
def tmask_blocks(tmask, min_block=0, sample_time=1):
"""
Return a list containing the indices of each valid block of a temporal
mask.
Parameters
----------
tmask
The temporal mask, in which 1 denotes valid observations and 0
denotes invalid or missing observations.
min_block
The minimum length of a block, in the same units as sample_time.
If sample_time is not set explicitly, then this is measured in
samples. If min_block is not set, then all blocks of valid data
will be returned.
sample_time
The sampling interval of the temporal mask.
Outputs
-------
blocks: list
A list whose length equals the number of valid blocks in the
temporal mask and whose entries are lists of the indices in each
block.
"""
def _check_block_length(block, blocks, min_block, sample_time):
if len(block) * sample_time > min_block:
blocks.append(block)
blocks = []
block = []
for i, t in enumerate(tmask):
if t:
block.append(i)
else:
_check_block_length(block, blocks, min_block, sample_time)
block = []
_check_block_length(block, blocks, min_block, sample_time)
return blocks
|
70bcb706a3a2ac51c92e8248e9fccc65d0d298d0
| 555,700 |
def get_iou(bb1, bb2):
"""
Gets the Intersection Over Area, aka how much they cross over
Assumption 1: Each box is a dictionary with the following
{"x1":top left top corner x coord,"y1": top left top corner y coord,"x2": bottom right corner x coord,"y2":bottomr right corner y coord}
"""
assert bb1['x1'] < bb1['x2']
assert bb1['y1'] < bb1['y2']
assert bb2['x1'] < bb2['x2']
assert bb2['y1'] < bb2['y2']
x_left = max(bb1['x1'], bb2['x1'])
y_top = max(bb1['y1'], bb2['y1'])
x_right = min(bb1['x2'], bb2['x2'])
y_bottom = min(bb1['y2'], bb2['y2'])
if x_right < x_left or y_bottom < y_top:
return 0.0
intersection_area = (x_right - x_left) * (y_bottom - y_top)
bb1_area = (bb1['x2'] - bb1['x1']) * (bb1['y2'] - bb1['y1'])
bb2_area = (bb2['x2'] - bb2['x1']) * (bb2['y2'] - bb2['y1'])
iou = intersection_area / float(bb1_area + bb2_area - intersection_area)
assert iou >= 0.0
assert iou <= 1.0
return iou
|
36594d11635c33a153b210ee550b1ad170f30210
| 531,201 |
from typing import List
def comment_lines(lines: List[str]) -> List[str]:
"""
Adds a multi line comment to a List of source lines.
:param lines: The source lines to be commented.
:returns: The commented List of of source lines.
"""
lines[0] = f'"""{lines[0]}'
if not lines[-1].endswith("\n"):
lines[-1] += "\n"
lines[-1] = f'{lines[-1]}"""'
return lines
|
dfa8425f810f40c5aea474a2543d88e9f151ee25
| 513,359 |
from typing import List
from typing import Counter
def _categorical_value_intersection(
all_chars: List
) -> bool:
"""
A method that finds if there are items that appear more than once in a list
:param all_chars: the list we want to check
:return: `True` if there is an intersection, `False` otherwise
"""
if len(all_chars) > 0:
maximum_count = max(Counter(all_chars).values())
return maximum_count > 1
else:
return False
|
48f1caa737494314d41d0f074e69dc08cd7d47eb
| 426,051 |
def project_list(d, ks):
"""Return a list of the values of `d` at `ks`."""
return [d[k] for k in ks]
|
62b82429e4c8e18f3fb6b1f73de72b1163f460bf
| 24,393 |
import hashlib
def getETag(data):
"""Gets the ETag for the specified data.
Args:
data: The data for which the ETag should be generated.
"""
md5 = hashlib.md5()
md5.update(data)
return md5.hexdigest()[-16:]
|
db7578c74551f5c507c3d7c0bcbf3cab2768ff1e
| 625,474 |
def filter_terms(p, degree_limit):
"""
This function gets the n-variable polynomial p and the number degree_limit
and returns the polynomial which consists of terms of degree at most degree_limit
:param p: n-variable polynomial
:param degree_limit: boundary for degree
:return: n-variable polynomial with terms of degree at most limit
"""
for m in p.monomials():
if m.degree() > degree_limit:
p -= m*p.monomial_coefficient(m)
return p
|
0b50d00bd058464319325a003ea8878313d5315b
| 109,824 |
import torch
def sig(x, a):
"""
Applies a sigmoid function on data in [0-1] range. Then rescales
the result so 0.5 will be mapped to itself.
"""
# Apply Sigmoid
y = 1. / (1 + torch.exp(-a * x)) - 0.5
# Re-scale
y05 = 1. / (1 + torch.exp(-torch.tensor(a * 0.5, dtype=torch.float32))) - 0.5
y = y * (0.5 / y05)
return y
|
0d92c567963fccbfe086e6c3d91b8caa103038ee
| 384,957 |
def rubygems_homepage_url(name, version=None):
"""
Return a Rubygems.org homepage URL given a ``name`` and optional
``version``, or None if ``name`` is empty.
For example:
>>> url = rubygems_homepage_url(name='mocha', version='1.7.0')
>>> assert url == 'https://rubygems.org/gems/mocha/versions/1.7.0'
>>> url = rubygems_homepage_url(name='mocha')
>>> assert url == 'https://rubygems.org/gems/mocha'
"""
if not name:
return
if version:
version = version.strip().strip('/')
return f'https://rubygems.org/gems/{name}/versions/{version}'
else:
return f'https://rubygems.org/gems/{name}'
|
424489bee6578c201ac84fa74aa09f5d1b5c7ef3
| 96,476 |
import random
def generate_password(length):
"""Generate a password of a desired length with numbers, symbols, upper
and lowercase letters"""
if length < 4:
raise ValueError('length must be 4 or greater')
lower_chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
symbols = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '_']
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
count = 0
password = ""
choices = ['lower', 'upper', 'symbols', 'digits']
while count < length:
if len(choices) == 0:
choices = ['lower', 'upper', 'symbols', 'digits']
current_char = random.choice(choices)
if current_char == 'lower':
password += random.choice(lower_chars)
choices.remove('lower')
elif current_char == 'upper':
password += random.choice(upper_chars)
choices.remove('upper')
elif current_char == 'symbols':
password += random.choice(symbols)
choices.remove('symbols')
elif current_char == 'digits':
password += random.choice(digits)
choices.remove('digits')
count += 1
return password
|
8fb47ef138f0cfc334edc9caf55cdc4cc3111559
| 612,096 |
def space_separated(value):
"""
Return a list of values from a `value` string using one or more whitespace
as list items delimiter. Empty values are NOT returned.
"""
if not value:
return []
return list(value.split())
|
f24a2949cfec1ae41173834e61013a459aee0e77
| 532,002 |
def is_private(key):
"""
Returns whether or not an attribute is private.
A private attribute looks like: __private_attribute__.
:param key: The attribute key
:return: bool
"""
return key.startswith("__") and key.endswith("__")
|
498e7522e95317dbb171961f0f5fe8350c29a69d
| 709,345 |
import math
def lin_srgb(rgb):
"""
Convert an array of sRGB values in the range 0.0 - 1.0 to linear light (un-corrected) form.
https://en.wikipedia.org/wiki/SRGB
"""
result = []
for i in rgb:
# Mirror linear nature of algorithm on the negative axis
abs_i = abs(i)
if abs_i < 0.04045:
result.append(i / 12.92)
else:
result.append(math.copysign(math.pow((abs_i + 0.055) / 1.055, 2.4), i))
return result
|
b2698655f57c244db03d4980a89e58fa5290f1e9
| 469,948 |
from datetime import datetime
import requests
import zipfile
import io
def get_shares_file(date):
"""
Download the file with the number of shares and returns bytes
Args:
date: Timestamp
Returns: bytes
"""
file_date = datetime.strftime(date, "%y%m%d")
file_url = f'http://www.b3.com.br/pesquisapregao/download?filelist=IN{file_date}.zip'
response = requests.get(file_url)
# original zipfile. Inside this one, there is another zipfile
zip_file = zipfile.ZipFile(io.BytesIO(response.content))
# The zipfile that is inside the original zipfile. Inside this one, is the XML file
zip_file2 = zipfile.ZipFile(io.BytesIO(zip_file.read(zip_file.namelist()[0])))
# Inside the zip_file2 there are 2 xml files. We need the latest one.
xml_bytes_data = zip_file2.read(max(zip_file2.namelist()))
return xml_bytes_data
|
f005d9ac2b8c31530f4c52d297b4982372023063
| 359,959 |
from typing import Any
from typing import Iterable
def is_iterable(obj: Any) -> bool:
"""check whether `x` is an iterable object but not string"""
return isinstance(obj, Iterable) and not isinstance(obj, str)
|
cfe091c3ab2a17703118f6db2e1f584a4ab3ebf5
| 223,131 |
def clan_url(clan_tag):
"""Return clan URL on CR-API."""
return 'http://cr-api.com/clan/{}'.format(clan_tag)
|
f2c05b8ecf71771e259874bd78d862356dc2b902
| 90,554 |
def broken_bond_keys(tra):
""" keys for bonds that are broken in the transformation
"""
_, _, brk_bnd_keys = tra
return brk_bnd_keys
|
f499a912e4b11bb4fd71e6bb1a9a8991e26f44bb
| 684,363 |
def xyxy2xywh(bbox):
"""Convert ``xyxy`` style bounding boxes to ``xywh`` style for COCO
evaluation.
Args:
bbox (numpy.ndarray): The bounding boxes, shape (4, ), in
``xyxy`` order.
Returns:
list[float]: The converted bounding boxes, in ``xywh`` order.
"""
_bbox = bbox.tolist()
return [
_bbox[0],
_bbox[1],
_bbox[2] - _bbox[0],
_bbox[3] - _bbox[1],
]
|
1a14e0d608f8bac182e415634a456c83f54125f4
| 559,456 |
from typing import Optional
from datetime import datetime
def get_dttm(date_time: Optional[datetime] = None) -> str:
"""
Get DTTM from datetime or actual time.
Args:
date_time: The input datetime or None for use now()
Returns:
dttm - str
"""
return (date_time or datetime.now()).strftime('%Y%m%d%H%M%S')
|
a81f967cf0afa49069977562d336c562ac5d3f7a
| 481,194 |
def convert_values_to_none(event, field_or_field_list, field_values=None):
""" Changes a field to None. If a field value is specified then only that value will be changed to None
:param event: A dictionary
:param field_or_field_list: A single field or list of fields to convert to None
:param field_values: The value to convert to None. If specified only these values are converted to None
:return: An altered dictionary
Examples:
.. code-block:: python
# Example #1
event = {'a_field': 'a_value'}
event = convert_values_to_none(event, field_or_field_list='a_field')
event = {'a_field': None}
# Example #2
event = {'a_field': 'a_value',
'another_field': 'another_value'
event = convert_values_to_none(event, field_or_field_list=['a_field', 'another_field'])
event = {'a_field': None,
'another_field': None}
# Example #3
event = {'a_field': 'a_value',
'another_field': 'another_value'
event = convert_values_to_none(event, fields=['a_field', 'another_field'], field_values='a_value')
event = {'a_field': None,
'another_field': 'another_value'}
# Example #4
event = {'a_field': 'a_value',
'another_field': 'another_value'
event = convert_values_to_none(event, fields=['a_field', 'another_field'], field_values=['a_value', 'another_value'])
event = {'a_field': None,
'another_field': None}
"""
if type(field_or_field_list) is not list:
field_or_field_list = [field_or_field_list]
if field_values is not None:
if type(field_values) is not list:
field_values = [field_values]
for field in field_or_field_list:
if field in event and field_values is None:
event[field] = None
elif field in event and event[field] in field_values:
event[field] = None
return event
|
d809980ab66c986357e46d78f8e4c01b420781e1
| 423,736 |
def power_law(deg_sep, ALPHA=1.0):
"""
Applies a power law model.
WEIGHT = DEG_SEP^(-ALPHA)
ALPHA: Parameter to control power law decay rate.
"""
return (deg_sep + 1) ** (- ALPHA)
|
92900eb12d87e6549f4ac2fb4fde85db5fcf1ab6
| 519,179 |
def swagger_escape(s): # pragma: no cover
"""
/ and ~ are special characters in JSON Pointers,
and need to be escaped when used literally (for example, in path names).
https://swagger.io/docs/specification/using-ref/#escape
"""
return s.replace('~', '~0').replace('/', '~1')
|
8f6e7112a565a6840fd046446cff77e11ee8425a
| 662,178 |
def open_r(filename):
"""Open a file for reading with encoding utf-8 in text mode."""
return open(filename, 'r', encoding='utf-8')
|
08086625a9c05738a3536001a158eff3b0718ddf
| 9,785 |
import signal
def convert_signal_name_to_signal(signal_name):
"""
>>> convert_signal_name_to_signal('-SIGUSR2')
<Signals.SIGUSR2: 12>
>>> convert_signal_name_to_signal('SIGUSR2')
<Signals.SIGUSR2: 12>
>>> convert_signal_name_to_signal('USR2')
<Signals.SIGUSR2: 12>
>>> convert_signal_name_to_signal('-USR2')
<Signals.SIGUSR2: 12>
>>> convert_signal_name_to_signal('KILL')
<Signals.SIGKILL: 9>
>>> convert_signal_name_to_signal('notasignal')
Traceback (most recent call last):
...
ValueError: Could not find a signal matching SIGnotasignal
"""
if signal_name.startswith('-'):
signal_name = signal_name[1:]
if not signal_name.startswith('SIG'):
signal_name = 'SIG' + signal_name
for signal_value in dir(signal):
if not signal_value.startswith('SIG'):
continue
if signal_name == signal_value:
return getattr(signal, signal_value)
raise ValueError("Could not find a signal matching {}".format(signal_name))
|
8bef3693775b1e64cc13b5a753e2aa69fd87cc73
| 217,779 |
def add_new_user(network, user, games):
"""
Creates a new user profile and adds that user to the network, along with
any game preferences specified in games. Assumes that the user has no
connections to begin with.
Arguments:
network: the gamer network data structure.
user: a string containing the name of the user to be added to the network.
games: a list of strings containing the user's favorite games, e.g.:
['Ninja Hamsters', 'Super Mushroom Man', 'Dinosaur Diner']
Returns:
The updated network with the new user and game preferences added.
The new user has no connections.
- If the user already exists in network, returns network *UNCHANGED*.
(does not change the user's game preferences)
"""
if user not in network:
network[user] = [[], games]
return network
|
68cc614074e489a4db04e12c4facc8b7445c0bf4
| 289,242 |
def cookie_repr(c):
""" Return a pretty string-representation of a cookie. """
return f"[key]host=[/key][cyan3]{c['host_key']}[/cyan3] " +\
f"[key]name=[/key][cyan3]{c['name']}[/cyan3] " +\
f"[key]path=[/key][cyan3]{c['path']}[/cyan3]"
|
26720d914481ec52c230be12602052ea61b736c0
| 73,195 |
def _transform_kwargs(kwargs):
"""
Replace underscores in the given dictionary's keys with dashes. Used to
convert keyword argument names (which cannot contain dashes) to HTML
attribute names, e.g. data-*.
"""
return {key.replace('_', '-'): kwargs[key] for key in kwargs.keys()}
|
12446fe5824f898a4dd406c860b664a9c326d75a
| 451,225 |
from typing import Union
def get_list_value(lst: Union[list, tuple], inds):
"""get value form index.
Args:
lst (Union[list, tuple]): target list.
inds (Any): value from index.
Returns:
list: result
"""
return [lst[i] for i in inds]
|
9b57377011b792714aaa21b90016e04ef85f68d1
| 73,215 |
from typing import Reversible
from typing import Any
def last(it: Reversible[Any]) -> Any:
"""
Get end of iterable object
Args:
it: Reversible(Iterable)) object
Examples:
>>> fpsm.last([1, 2, 3])
3
>>> fpsm.last('hello world')
'd'
"""
return next(iter(reversed(it)))
|
6af5359cc6fa1ee8e3bd30aa5e37cda0ba589359
| 508,837 |
def not_exonic(variant_class):
"""Check if SNV is exonic.
Args:
variant_class: the type of mutation
Returns:
True for not exonic, False otherwise.
"""
variant_classes = ["5'Flank", 'Intron', 'RNA', "3'Flank", "3'UTR", "5'UTR", 'IGR']
if variant_class in variant_classes:
return False
else:
return True
|
019fbd55b2fe34ab9954cfbf35429741addfb697
| 174,627 |
def strToFloatOrNone(str):
"""Returns float representation of str argument or None if empty string.
:param str: String to ne converted into float number
:return: Float representation of str or None.
>>> print strToFloatOrNone("36")
36.0
>>> print strToFloatOrNone("")
None
"""
if str:
return float(str)
else:
return None
|
44cfd02c9ab3263a48568ec51704146a1b4ae2e9
| 347,647 |
def _page_obj(json_object):
"""takes json input and returns a page object
Args:
json_object (dict): json data from api
Returns:
dict: json object for the 'pages' of an article
"""
query_object = json_object['query']
return(query_object['pages'])
|
b6fb7470ea394c2e230df2d6212e969cd75ea244
| 344,908 |
from typing import Dict
import binascii
import base64
import json
def _decode(encoded: bytes) -> Dict:
"""
Decode an dictionary (document) encoded as a base64-encoded string.
:param encoded: the base64-encoded string
:return: the dictionary (document) object
"""
dec_ascii: bytes = encoded
dec_ascii_bytes: bytes = binascii.a2b_base64(dec_ascii)
dec_bytes: bytes = base64.b64decode(dec_ascii_bytes)
return json.loads(dec_bytes.decode('utf-8'))
|
3787955ff3a188ccef44540c16f89da136a2b12b
| 506,426 |
def in_reduce(reduce_logic_func, sequence, inclusion_list) -> bool:
"""Using `reduce_logic_func` check if each element of `sequence` is in `inclusion_list`"""
return reduce_logic_func(elmn in inclusion_list for elmn in sequence)
|
746afeddf9d847dfa2aed9bb487199ba46f6b656
| 380,862 |
def eval_basic_op(l: str, op: str, r: str) -> str:
"""
Evaluate a basic arithmetic operation
:param l: Left operand
:param op: Operator
:param r: Right operand
:return: Result or a string representing the operation if it cannot be calculated
"""
if l.isdecimal() and r.isdecimal():
l_num = int(l)
r_num = int(r)
if op == '+':
return str(l_num + r_num)
if op == '-':
return str(l_num - r_num)
if op == '*':
return str(l_num * r_num)
return l + op + r
|
2b35ae9eeef624f709009ddcd63e79179d41d978
| 204,342 |
def getData(d):
"""Returns the data object used"""
return d
|
3ce72ad88a4a56a6292d76789489d1bba004ad6a
| 562,262 |
def mostly_tracked(df, track_ratios):
"""Number of objects tracked for at least 80 percent of lifespan."""
return track_ratios[track_ratios >= 0.8].count()
|
65f0389505484de4d289b465d70e6f981d02d039
| 332,869 |
def determiner_to_num(tag):
"""Converts a/an to 1."""
if tag[1] != "DET": return False, None
if tag[0].lower() in ("a","an"): return True, ("1","NUM")
return False, None
|
8f0acf76989d16204ce17f3f52dc4cd4a70794cb
| 491,599 |
from dateutil import tz
import dateutil.parser
def UTC_time(ISO_datestring):
"""Converts local ISO datastring to UTC date string"""
from_zone = tz.gettz('Pacific/Auckland')
to_zone = tz.gettz('UTC')
ISO_date = dateutil.parser.parse(ISO_datestring)
UTC_date = ISO_date.astimezone(to_zone)
UTC_date_str = UTC_date.isoformat(sep='T')
return UTC_date_str
|
6634fbc0b23ebb0ace5ea9d808e34cbfaf383e59
| 445,784 |
from typing import Union
from pathlib import Path
from typing import List
def get_list_of_directories(
directory_path: Union[str, Path], descending=False
) -> List[Path]:
"""Gets a list of directories in a directory.
Parameters
----------
directory_path : Union[str, Path]
The path to the directory.
Returns
-------
List[Path]
The list of directories.
"""
if isinstance(directory_path, str):
directory_path = Path(directory_path)
return sorted(
[directory for directory in directory_path.iterdir() if directory.is_dir()],
reverse=descending,
)
|
137a60b5dd3b635d74d25208bf9cab383442aca6
| 466,783 |
def get_xarray_group(dataset, group):
"""Get pseudo group from xarray.Dataset
Args:
dataset: A xarray.Dataset object with pseudo groups.
group: The name of the group (can also be a subgroup).
Returns:
A xarray.Dataset with the pseudo group.
"""
if not group.endswith("/"):
group += "/"
group_vars = [
var
for var in dataset.variables
if var.startswith(group)
]
if not group_vars:
raise KeyError(f"The group {group} was not found!")
return dataset[group_vars]
|
20d7caa004f97855f3f8932a9f5638eb007f8d63
| 546,090 |
def to_str(value, encoding):
"""Decode a :obj:`bytes` object into a str with UTF-8 encoding.
:param bytes value: The value to decode
:param str encoding: The encoding type to use
:rtype: str
"""
return value.decode(encoding)
|
cc18f8c0f8e64860f374444a5bd065952c1420be
| 452,936 |
def gray_to_binary(n):
"""Convert Gray codeword to binary and return it"""
mask=n=int(n,2) # Convert to int
while mask != 0:
mask >>= 1
n ^= mask
return bin(n)[2:]
# bin(n) returns n's binary representation with a '0b' prefixed
# the slice operation is to remove the prefix
|
7008f57aaddf744bd80d2d7ffd65e45216c73f7e
| 154,713 |
def format_duration_ms(ms):
"""Format milliseconds (int) to a human-readable string."""
def _format(d):
d = str(d)
if len(d) == 1:
d = '0' + d
return d
s = int(ms / 1000)
if s < 60:
return '00:{}'.format(_format(s))
m, s = divmod(s, 60)
return '{}:{}'.format(_format(m), _format(s))
|
751f233cb720b5365b1282d14e6b72fdb260689c
| 523,866 |
def _convert_timestamp(time):
"""Convert datetime.datetime to string in datetime64[s] format
:arg time: datetime.datetime object
:return datetime64: str in datetime64[s] format
"""
year, month, day, hour, minute, second = str(time.year), str(time.month), str(time.day), str(time.hour), str(time.minute), str(time.second)
if len(month) < 2:
month = '0' + month
if len(day) < 2:
day = '0' + day
if len(hour) < 2:
hour = '0' + hour
if len(minute) < 2:
minute = '0' + minute
if len(second) < 2:
second = '0' + second
datetime64 = '{}-{}-{}T{}:{}:{}'.format(year, month, day, hour, minute, second)
return datetime64
|
f4d817d21fd01f3b2a4d88058eb30fc2cd1b664a
| 179,541 |
import re
def has_symbol_usage(symbol: str, text: str) -> bool:
""" Determine whether a symbol occurs in a text. """
# star matches any non-whitespace character
symbol = symbol.replace('*', '\S*?')
# match any use of symbol as a stand-alone element
pattern = r'\b{0}\b'.format(symbol)
# we're happy if just one match is found
return True if (re.search(pattern, text) is not None) else False
|
66608d25d2dce555d471f504922f3fc5ecbfa6f5
| 498,186 |
def get_start_urls(base_url, webserver_map_entry):
"""
Extract the start URLs from the current webserver map results if available
"""
start_urls = []
for _, pages_node in webserver_map_entry.items():
for path in pages_node:
# base_url[:-1] to strip trailing slash, b/c path has a '/' in front
url = base_url[:-1] + path
start_urls.append(url)
return start_urls
|
c7dcc3c7a9285106f50578f72397c3c3d2555135
| 286,262 |
def get_title(section_div):
"""Return the fathead entry title.
Parameters
----------
section_div : bs4.BeautifulSoup
The BeautifulSoup object corresponding to the div with the "class"
attribute equal to "section" in the html doc file.
Returns
-------
title : Str
The fathead entry title.
"""
title = section_div.h1.text[:-1]
return title
|
fa090adc09ac446f272262a72798cd000c76aa51
| 378,225 |
def digraph_edge_hamming_dist(g1, g2):
"""Returns number of directed edge mismatches between digraphs g1 and g2."""
dist = 0
for e1 in g1.edges:
if e1 not in g2.edges:
dist += 1
return dist
|
bb33330dc5029964e36947e1b09583c8e17e5754
| 495,137 |
def count_by(x, n):
""" Return a sequence of numbers counting by `x` `n` times. """
return range(x, x * n + 1, x)
|
6bca9902f78f454da6a33cb40054a87f9832830a
| 139,415 |
import math
def calc_viz_lim(P):
"""
Eq. 4.4
Calculates the visibility limit of the satellite, which is dependent on
the satellite's altitude.
Parameters
------------
P : float
The projection parameter of the satellite
Returns
------------
ups : float
The visibility limit of the satellite
"""
rhs = 1/P
ups = math.acos(math.radians(rhs))
return ups
|
97fb81dee635c4efb853a99f922cbb68ac95adc2
| 405,230 |
def get_column_names(outcomes, races, genders, pctiles):
""" Generate column names for outcomes and factors selected"""
col_names = []
for outcome in outcomes:
for race in races:
for gender in genders:
for pctile in pctiles:
col_names.append(outcome + '_' + race + '_' + gender + '_' + pctile)
return col_names
|
8c5450508a7946eed6fb6935ed57e6c213c249c0
| 177,784 |
def get_and_check_wine_arch_valid(wine_arch: str = '') -> str:
"""
check for valid winearch - if wine_arch is empty, default to win32
valid choices: win32, win64
>>> import unittest
>>> assert get_and_check_wine_arch_valid() == 'win32'
>>> assert get_and_check_wine_arch_valid('win32') == 'win32'
>>> assert get_and_check_wine_arch_valid('win64') == 'win64'
>>> unittest.TestCase().assertRaises(RuntimeError, get_and_check_wine_arch_valid, wine_arch='invalid')
"""
valid_wine_archs = ['win32', 'win64']
if not wine_arch:
wine_arch = 'win32'
wine_arch = wine_arch.lower().strip()
if wine_arch not in valid_wine_archs:
raise RuntimeError('Invalid wine_arch: "{wine_arch}"'.format(wine_arch=wine_arch))
return wine_arch
|
6317c99f420a63c334ca0e353b815302876f8c35
| 434,155 |
import smtplib
def connect(smtp_server, smtp_port, email, password):
"""
Connect to the SMTP server to send emails.
:param smtp_server: Hostname or IP Address of the SMTP server
:param smtp_port: Port number of the SMTP server.
:param email: Valid email address for authentication.
:param password: Password of the email address for authentication.
:returns: server instance after login with the credentials.
:raises: None
"""
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(email, password)
return server
|
34ac16b58b86f0e99709e80829114c6753fbc1d3
| 671,913 |
import csv
def sj_out_to_jxs(sj_out):
"""Accepts STAR-generated SJ.out.tab file & returns list of its junctions.
Input: sj_out (str) string pointing to STAR output __SJ.out file containing
junction calls from a STAR alignment.
Returns a list of the file's unique junctions in 0-based closed coordinates
"""
all_junctions = []
strand_mapper = ['?', '+', '-']
with open(sj_out) as sj:
jx_file = csv.reader(sj, delimiter='\t')
for line in jx_file:
chrom, left, right, strand = line[0], line[1], line[2], line[3]
strand = strand_mapper[int(strand)]
if strand == '?':
continue
if 'chr' not in chrom:
chrom = 'chr' + chrom
left = str(int(left) - 1)
right = str(int(right) - 1)
jx = ';'.join([chrom, left, right, strand])
all_junctions.append(jx)
return list(set(all_junctions))
|
137b72d3b7b5fd2335ffa0ed4e6508d8dd271d0a
| 412,792 |
import re
def remove_non_numeric (value):
"""
Remove non-numeric characters from value.
:param value: The value to be modified.
:return Numeric value.
"""
return re.sub("[^0-9]", "", value)
|
4c84deeaee5759cb0029e4baf585d272667369ba
| 621,038 |
def get_major_version(version):
"""
:param version: the version of edge
:return: the major version of edge
"""
return version.split('.')[0]
|
c17e1b23872a25b3ce40f475855a9d1fe4eef954
| 688,639 |
def _create_docker_command(*args, **kwargs):
"""
Returns a string with the ordered arguments args in order,
followed by the keyword arguments kwargs (in sorted order, for
consistency), separated by spaces.
For example,
``_create_docker_command('./myprogram', 5, 6, wibble=7, wobble=8)``
returns ``"./myprogram 5 6 --wibble 7 --wobble 8"``.
"""
return " ".join([str(x) for x in args] +
["--{} {}".format(k, v)
for k, v in sorted(kwargs.items())])
|
46315ad7eb34c5a61bb2c3c740a5451841073205
| 444,935 |
def xor_string(string: str, xor_int_value=42):
"""Takes a given string and does an XOR operation on the converted ord() value of each character with the "xor_int_value", which by default is 42
Examples:
>>> string2encode = 'Now is better than never.'\n
>>> xor_string(string2encode)\n
'dE]\nCY\nHO^^OX\n^BKD\nDO\\OX\x04'
>>> xor_string('dE]\nCY\nHO^^OX\n^BKD\nDO\\OX\x04')\n
'Now is better than never.'
>>> chr(97)\n
'a'
>>> ord('a')\n
97
>>> hex(97)\n
'0x61'
>>> int('0x61', 16)\n
97
>>> xor_string(string2encode, xor_int_value = 97)\n
'/\x0e\x16A\x08\x12A\x03\x04\x15\x15\x04\x13A\x15\t\x00\x0fA\x0f\x04\x17\x04\x13O'
>>>
>>> xor_string('/\x0e\x16A\x08\x12A\x03\x04\x15\x15\x04\x13A\x15\t\x00\x0fA\x0f\x04\x17\x04\x13O', 97)\n
'Now is better than never.'
Args:
string (str): The string you want to XOR (each character will be XORed by the xor_int_value)
xor_int_value (int, optional): The integer value that is used for the XOR operation. Defaults to 42.
Returns:
str: Returns an XORed string
"""
xored_result = "".join([chr(ord(c) ^ xor_int_value) for c in string])
return xored_result
|
4e3dd51cd49a6f3df9491dd86d76e6fcecf6fc38
| 637,233 |
def word_count(text: str, word: str='') -> int:
"""
Count the number of occurences of ``word`` in a string.
If ``word`` is not set, count all words.
"""
if word:
count = 0
for text_word in text.split():
if text_word == word:
count += 1
return count
else:
return len(text.split())
|
f73ecbad4c81d9f5108c9a82756bd4caf5306a9a
| 93,940 |
def create_field_matching_dict(airtable_records, value_field, key_field = None, swap_pairs = False):
"""Uses airtable_download() output to create a dictionary that matches field values from
the same record together. Useful for keeping track of relational data.
If second_field is `None`, then the dictionary pairs will be {<record id>:value_field}.
Otherwise, the dictionary pairx will be {key_field:value_field}.
If swap_pairs is True, then dictionary pairs will be {value_field:<record id>(or key_field)}.
"""
airtable_dict = {}
for airtable_record in airtable_records:
if key_field == None:
key = airtable_record['id']
else:
key = airtable_record['fields'].get(key_field)
value = airtable_record['fields'].get(value_field)
if swap_pairs:
airtable_dict.update({key : value})
else:
airtable_dict.update({value : key})
return airtable_dict
|
df5fbf24edb7047fc569b10a73eec47fb1234fcd
| 687,184 |
def square_area(side):
"""Returns the area of a square"""
side = float(side)
if (side < 0.0):
raise ValueError('Negative numbers are not allowed')
return side**2.0
|
a68c76dbdbe2918805c4788783e20c8ccf82ea6f
| 296,025 |
import re
def string_to_list(s):
"""Return a list of strings from s where items are separated by any of , ; |"""
try:
return [text for text in re.split(r'\s*[,;\|]\s*', s) if text]
except TypeError:
if type(s) == list:
return s
raise
|
4e679bfaf0d51120a2194a4db173d34a9eaf47d0
| 30,834 |
def unzip(index, list):
""" Returns the item at the given index from inside each tuple in the list.
"""
return [item[index] for item in list]
|
887023728b3a9ddebd7b5667e6eb9a46e4537389
| 417,211 |
def get_unique_sublist(inlist):
"""return a copy of inlist, but where elements are unique"""
newlist = []
for val in inlist:
if not val in newlist: newlist.append(val)
return newlist
|
bc45dda0fd87d0c1b72f05db4fe72e3b312fe40c
| 638,160 |
from pathlib import Path
def get_page_number(filename):
"""Parses a page number from a filename.
Presumes that:
The page number is preceded by an underscore
The page number is immediately followed by either by `_m`, `_me` or `_se`,
or the file extension.
Args:
file (str): filename of a TIFF image file.
Returns:
4-digit page number from the filename with leading zeroes
"""
base_filename = Path(filename).stem
if "_se" in base_filename:
filename_trimmed = base_filename.split("_se")[0]
elif "_m" in base_filename:
filename_trimmed = base_filename.split("_m")[0]
else:
filename_trimmed = base_filename
return filename_trimmed.split("_")[-1].lstrip("0").zfill(4)
|
683ae951b0f8c0c397ec53ae8a33e014d61bd84f
| 262,655 |
def IsRegionalHealthCheckRef(health_check_ref):
"""Returns True if the health check reference is regional."""
return health_check_ref.Collection() == 'compute.regionHealthChecks'
|
4dea9aeaac365505555f3da0297920a1a57cec98
| 534,787 |
def element_wise_product(X, Y):
"""Return vector as an element-wise product of vectors X and Y"""
assert len(X) == len(Y)
return [x * y for x, y in zip(X, Y)]
|
e01ec3720ac6b2fa06cca1186cf1a5a4d8703d38
| 30,480 |
import torch
def flatten_grads(model):
"""
Flattens the gradients of a model (after `.backward()` call) as a single, large vector.
:param model: PyTorch model.
:return: 1D torch Tensor
"""
all_grads = []
for name, param in model.named_parameters():
all_grads.append(param.grad.view(-1))
return torch.cat(all_grads)
|
c23dc028f56a245ea9f7cfb5c0468eaabd23063f
| 486,961 |
import base64
def readDataOrPath(dataStr):
"""
Reads in either base64 data or a path.
"""
if dataStr.startswith('base64:'):
dataPath = None
dataContents = base64.b64decode(dataStr[7:])
else:
dataPath = dataStr
with open(dataStr, 'rb') as stream:
dataContents = stream.read()
return dataPath, dataContents
|
0b18eaa4affdb409455e7575a6938963df1f1db1
| 43,344 |
def get_adjusted_aspect(ax, aspect_ratio):
"""Adjust the aspect ratio
Parameters
----------
ax : :obj:`~matplotlib.axes.Axes`
A :obj:`~matplotlib.axes.Axes` instance
aspect_ratio : float
The desired aspect ratio for :obj:`~matplotlib.axes.Axes`
Returns
-------
float
The required aspect ratio to achieve the desired one
Warning
-------
This function only works for non-logarithmic axes.
"""
default_ratio = (ax.get_xlim()[1] - ax.get_xlim()[0]) / (ax.get_ylim()[1] - ax.get_ylim()[0])
return float(default_ratio * aspect_ratio)
|
8a28e08bf3bcfec03954278cb498f2d56e93d1d1
| 615,825 |
def cells_different(cell_a, cell_b, compare_outputs = True):
"""
Return true/false if two cells are the same
cell_a: (obj) JSON representation of first cell
cell_b: (obj) JSON representation of second cell
compare_outputs: (bool) whether to compare cell outputs, or just inputs
"""
# check if cell type or source is different
if (cell_a["cell_type"] != cell_b["cell_type"]
or cell_a["source"] != cell_b["source"]):
return True
# otherwise compare outputs if it is a code cell
elif compare_outputs and cell_b["cell_type"] == "code":
# get the outputs
cell_a_outs = cell_a['outputs']
cell_b_outs = cell_b['outputs']
# if different number of outputs, the cell has changed
if len(cell_a_outs) != len(cell_b_outs):
return True
# compare the outputs one by one
for j in range(len(cell_b_outs)):
# check that the output type matches
if cell_b_outs[j]['output_type'] != cell_a_outs[j]['output_type']:
return True
# and that the relevant data matches
elif((cell_a_outs[j]['output_type'] in ["display_data","execute_result"]
and cell_a_outs[j]['data'] != cell_b_outs[j]['data'])
or (cell_a_outs[j]['output_type'] == "stream"
and cell_a_outs[j]['text'] != cell_b_outs[j]['text'])
or (cell_a_outs[j]['output_type'] == "error"
and cell_a_outs[j]['evalue'] != cell_b_outs[j]['evalue'])):
return True
return False
|
c720a346550ca47b8841f0f60f8c566339b5e4aa
| 74,626 |
def get_overlap_region(s1,e1,s2,e2):
"""0-based system is used (like in Biopython):
| INPUT | RETURNS |
|-----------------------------|-----------------------------|
| | |
| s1=3 e1=14 | |
| |----------| | [9,14] |
| |---------| | |
| s2=9 e2=19 | |
| | |
"""
if s1 > e1 or s2 > e2:
raise Exception("Something is wrong with the intervals (%i,%i) and (%i,%i)" %
(s1,e1,s2,e2))
if s1 <= s2 <= e1 and s1 <= e2 <= e1:
# |----------------|
# |--------|
return s2, e2
elif s2 <= s1 <= e2 and s2 <= e1 <= e2:
# |--------|
# |----------------|
return s1, e1
elif s1 <= s2 <= e1 and s2 <= e1 <= e2:
# |------------|
# |-------------|
return s2, e1
elif s2 <= s1 <= e2 and s1 <= e2 <= e1:
# |-------------|
# |------------|
return s1, e2
else:
return None, None
|
3b71131ae68a30404a307d34351234a46b0eae5b
| 210,187 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.