content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def get_key_paths(data_dict,
keys_to_consider=None,
keys_not_to_consider=None,
root_path=None):
"""
Example:
get_key_paths({
'a' : {
'b': 1
},
'c' : 2
})
returns:
['a.b', 'c']
:param data_dict: (Nested) dict with metrics
:type data_dict: dict
:param keys_to_consider: list with (root) key names to focus
:type keys_to_consider: list
:param keys_not_to_consider: list with key names to discard (on any nesting level)
:type keys_not_to_consider: list
:param root_path: root path to prepend.
:type root_path: string
:return: list with key metric path strings
:rtype:
"""
if keys_to_consider is None:
keys_to_consider = list(data_dict.keys())
if keys_not_to_consider is None:
keys_not_to_consider = []
key_paths = []
for key in keys_to_consider:
if key in keys_not_to_consider:
continue
value = data_dict[key]
if root_path is not None:
current_path = f"{root_path}.{key}"
else:
current_path = key
path_list = []
if type(value) is dict:
path_list = get_key_paths(value,
keys_not_to_consider=keys_not_to_consider,
root_path=current_path)
if len(path_list) == 0:
path_list = [current_path]
key_paths += path_list
return key_paths
|
c3548b24aaf49e2e5f5632f503a5fd32d38eb00b
| 660,967 |
def update_guess_word(word, guess_word, guess):
"""
Updates the guess_word with the newly guessed letter.
By iterating over the word and comparing each character, we can find
all occurences of that letter and can replace the underscores in the
guess word for each found occurence.
E.g. if the word is 'hello' and the guess_word was ['_', 'e', '_', '_', '_']
and the guess was 'l', the result will be ['_', 'e', 'l', 'l', '_']
The function modifies the list in place.
Args:
word: the target word
guess_word: the current state of the guess word
guess: the guessed letter
Returns:
the updated state of the guess word. Though unnecessary, since lists
are passed by reference and altered directly.
"""
for i, letter in enumerate(word):
if letter == guess:
guess_word[i] = letter
return guess_word
|
f30bc7af577ce2b16d4a021e73d77f2e1f6cdb7b
| 298,650 |
def all_registry_hosts(
CallableRegistry, # noqa: N803
PropertyRegistry,
CachedPropertyRegistry,
CallableParamRegistry,
PropertyParamRegistry,
CachedPropertyParamRegistry,
):
"""All test registries as a list."""
return [
CallableRegistry,
PropertyRegistry,
CachedPropertyRegistry,
CallableParamRegistry,
PropertyParamRegistry,
CachedPropertyParamRegistry,
]
|
3af05ff3cd4d55e4a48f186387e6e15c436561bf
| 172,674 |
import math
def rounded_bez(angle):
"""
From https://math.stackexchange.com/questions/1671588/b%C3%A9zier-curve-approximation-of-a-circular-arc.
The control points of a cubic Bezier curve for approximating a circular arc with end points
P0, P1, radius R, and angular span A:
P0, P0+R*L*T0, P1-R*L*T1, P1
where T0 and T1 are the unit tangent vector of the circular arc at P0 and P1
and L = 4/3*tan(A/4)
:param angle:
:return:
"""
return 4/3 * math.tan(math.radians(angle/4))
|
b061c6e46eac5abb0a4f05788535e029a12856bc
| 598,199 |
def even_or_odd(s: str) -> str:
"""
Given a string of digits confirm whether the sum of all the individual
even digits are greater than the sum of all the indiviudal odd digits.
"""
sum_even, sum_odd = sum([int(i) for i in s if int(i) % 2 == 0]), sum([int(i) for i in s if int(i) % 2 != 0])
if sum_even > sum_odd:
return "Even is greater than Odd"
elif sum_even < sum_odd:
return "Odd is greater than Even"
return "Even and Odd are the same"
|
6d43137e1793ab03e4f317dd357bd63d0398649f
| 302,472 |
import re
def autolab_assignment_name(filename):
"""Extract the autolab assessment name for an autolab csv grade
file name.
"""
m = re.search("(.*)_(.*)_[0-9]{12}.csv", filename)
if m:
return m.group(2)
return None
|
f7e168d7aa4397062f2dd75d25f7f65a1492bb00
| 267,374 |
def get_P_cp_ss(pmp_type):
"""ソーラーシステムの循環ポンプの消費電力
Args:
pmp_type(str): ソーラーシステムの循環ポンプの種類 (省消費電力型,上記以外の機種)
Returns:
float: ソーラーシステムの循環ポンプの消費電力 (W)
"""
# 表3 ソーラーシステムの循環ポンプの消費電力の値と適用条件
table_3 = (40.0, 80.0)
if pmp_type == '省消費電力型':
return table_3[0]
elif pmp_type == '上記以外の機種':
return table_3[1]
else:
raise ValueError(pmp_type)
|
1025d09bd0622088866e6ebb79527c60c2fc2afa
| 226,607 |
import math
def current_passage_offset(scroll_size, passage_size, reading_every, seconds):
"""Get the offset of the current passage in a scroll. We assume that the scroll has been being
read since the beginning of time, where a new passage of `passage_size` characters is read every
`reading_every` seconds. We assume that after final passage in the scroll is read, the scroll is
started from the beginning, and so on. `seconds` represents the number of seconds since the
beginning of time. `scroll_size` represents the total number of characters in the scroll.
# From a 270-char scroll, we're reading 40-char passages every 4 seconds. Since we are at 0
# seconds, our offset is 0 -- the offset of the first passage.
>>> current_passage_offset(scroll_size=270, passage_size=40, reading_every=4, seconds=0)
0
# A second elapses. Since a full 4 second window has not yet elapsed, we are still at offset 0.
>>> current_passage_offset(scroll_size=270, passage_size=40, reading_every=4, seconds=1)
0
# Four seconds have elapsed. We are now reading from the second passage, at character 40.
>>> current_passage_offset(scroll_size=270, passage_size=40, reading_every=4, seconds=4)
40
# Five more windows (20 seconds) elapse. We are five passages (200 characters) further into the
# text. Note that the final passage in this case would not be a full length passage.
>>> current_passage_offset(scroll_size=270, passage_size=40, reading_every=4, seconds=24)
240
# Another four seconds elapse. We are back at the beginning of the scroll!
>>> current_passage_offset(scroll_size=270, passage_size=40, reading_every=4, seconds=28)
0
"""
num_passages_in_scroll = math.ceil(scroll_size / passage_size)
windows_elapsed = seconds // reading_every
current_passage_number = int(windows_elapsed % num_passages_in_scroll)
return current_passage_number * passage_size
|
2a976c9b406eb2648e1463fd10277c39e25f2d1f
| 270,885 |
def vertical_path(size):
"""
Creates a generator for progressing vertically through an image.
:param size: A tuple (width, height) of the image size
:return: A generator that yields a set of columns through the image.
Each column is a generator that yields pixel coordinates.
"""
width, height = size
return (((x, y) for y in range(height)) for x in range(width))
|
91d42be4bdd8f501405f226a0a158491932d6b2b
| 34,617 |
import base64
import textwrap
def encode_object_data(data):
"""
Encodes bytes using base64 and wraps the lines at 64 charachters.
:param bytes data:
the data to be encoded
:returns:
the line-wrapped base64 encoded data as a list of strings, one string
per line
:rtype: list(str)
"""
encoded_data = base64.b64encode(data).decode("ascii")
return textwrap.wrap(encoded_data, width=64, break_long_words=True)
|
69e8f14680f66b9afecaf851f26cf99efe5eb962
| 253,352 |
import requests
def getQuote(func, symbol):
"""
Gets JSON string for desired quote. Below is documentation for Alpha Vantage requests:
Available function:
INTRADAY
DAILY
DAILY_ADJUSTED
WEEKLY
WEEKLY_ADJUSTED
MONTHLY
MONTHLY_ADJUSTED
symbol -> Quote
"""
key = "JMHNDOFOZTWO5N9G"
url = "https://www.alphavantage.co/query?function=TIME_SERIES_{}&symbol={}.SA&apikey={}".format(func.upper(), symbol.upper(), key)
response = requests.get(url)
return response
|
3395df5834c5b27186d07732679250f5cf6dd7f7
| 142,955 |
def divide_list(a_list, divide_func):
"""Divide a list like object into two parts.
- a_list: list like object
- divide_func: the divide function to return True/False
Return two parts of the list.
Example:
divide_list([1, 2, 3], lambda x: x > 1) -> [2, 3], [1]
"""
suit, not_suit = [], []
for item in a_list:
result = suit if divide_func(item) else not_suit
result.append(item)
return suit, not_suit
|
f310b15b79c43b5e001db3ac7ea3d55a1292db3c
| 444,719 |
def escapeBelString(belstring):
"""Escape double quotes in BEL string"""
return belstring.replace('"', '\\"')
|
ef2efa04cd356dd17d44f1a2f0b9f518d7c13170
| 633,093 |
import requests
def make_get_request(uri: str, payload):
"""
Function to make a GET request to API Endpoint
:param uri:
:param payload:
:return:
"""
response = requests.get(uri, payload)
if response.status_code != 200:
return None
else:
return response.json()
|
cf7c97415658b3d7a059f862a7251b66ecf2ca59
| 681,182 |
def interval_pos(test_x, x0, x1):
"""
In 1D space:
x0 x1
############## ################## ##############
# ---- position 0 position + position
:param test_x:
:param x0:
:param x1:
:return:
"""
assert x1 >= x0
if test_x < x0:
return test_x - x0
if test_x > x1:
return test_x - x1
return 0.0
|
c24206d54c8b68594dcae1c35ffc44aa366373af
| 119,963 |
from typing import List
from typing import Dict
def _process(proc_data: List[Dict]) -> List[Dict]:
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured to conform to the schema.
"""
for entry in proc_data:
for key in entry:
# use normal int/float conversions since jc.utils.convert_to_int is too greedy
try:
if '.' in entry[key]:
entry[key] = float(entry[key])
else:
entry[key] = int(entry[key])
except Exception:
pass
if ('_option_' in key or '_route_' in key) and key[-1].isdigit():
for k in entry[key]:
try:
if '.' in entry[key][k]:
entry[key][k] = float(entry[key][k])
else:
entry[key][k] = int(entry[key][k])
except Exception:
pass
return proc_data
|
ce8a7e10ab12ba58b41c4e8286b054ea4f81dad0
| 664,967 |
import unicodedata
def isNumber(s):
"""
Determines if a unicode string (that may include commas) is a number.
:param s: Any unicode string.
:return: True if s represents a number, False otherwise.
"""
s = s.replace(',', '')
try:
float(s)
return True
except ValueError:
pass
try:
unicodedata.numeric(s)
return True
except (TypeError, ValueError) as e:
pass
return False
|
df43f7e83cab485c48b21bdb221cb8804e98596a
| 128,785 |
import torch
def create_window(window_size: int, sigma: float, channel: int):
"""create 1D gauss kernel
Args:
window_size (int): the size of gauss kernel
sigma (float): sigma of normal distribution
channel (int): input channel
"""
half_window = window_size // 2
coords = torch.arange(-half_window, half_window+1).float()
g = (-(coords ** 2) / (2 * sigma ** 2)).exp_()
g.div_(g.sum())
return g.reshape(1, 1, 1, -1).repeat(channel, 1, 1, 1)
|
a7674277e5977fd7cf80f24af319e28163d62e4f
| 410,632 |
def get_metafeatures_dim(metafeatures_spec):
"""Get dimensionality of metafeatures."""
return sum([len(m[2]) if m[1] is str else 1 for m in metafeatures_spec])
|
8b12e83a6a4db7813418509997b85f53cb57be5d
| 455,218 |
def gf_eval(f, x, p):
"""Evaluate f(x) over GF(p) using Horner scheme. """
result = 0
for a in f:
result *= x
result += a
result %= p
return result
|
2178a931d88b22690231d43652ba172e55d647f7
| 498,656 |
def _use_oss_fuzz_corpus(experiment_config: dict) -> bool:
"""Returns the oss_fuzz_corpus flag of the experiment described by
|experiment_config| as a bool."""
return bool(experiment_config.get('oss_fuzz_corpus'))
|
bfefd10f3e017479b3402466625ed33fced5a04f
| 133,204 |
def reynolds_number(v: float, d_hyd: float, kin_visco: float) -> float:
"""
Calculate Reynolds number.
**Parameters:**
- `v`: (*float*) = flow velocity [m/s]
- `d_hyd`: (*float*) = hydraulic diameter [m]
- `kin_visco`: (*float*) = kinematic viscosity [m^2/s]
**Returns:** (*float*)
"""
return v * d_hyd / kin_visco
|
b4d7a14facd9405910f64093a02e9b06221eb175
| 216,870 |
def extract_extension_attributes(schema: dict) -> dict:
"""Extract custom 'x-*' attributes from schema dictionary
Args:
schema (dict): Schema dictionary
Returns:
dict: Dictionary with parsed attributes w/o 'x-' prefix
"""
extension_key_format = 'x-'
extensions_dict: dict = {
key.replace(extension_key_format, '').replace('-', '_'): value
for key, value in schema.items()
if key.startswith(extension_key_format)
}
return extensions_dict
|
80829a1e222b7e55d41483592e20b06bb63ea8a2
| 692,654 |
def decline_invite_command(instance, player, arguments = None):
""" Remove a player from the invited list of an instance.
Args:
instance: The instance to uninvite player from.
player: The player wishing to decline an invite.
arguments: Not used, can be any value.
If the player wasn't actually invited to the game, nothing happens
and this method returns false.
Returns:
True if the player was previously invited to the game, False
otherwise.
"""
if player in instance.invited:
instance.invited.remove(player)
return True
return False
|
76f989a8d5ad93fb0078f305d70979a6d45471a9
| 526,462 |
def de_unit_key(key: str) -> str:
"""Remove the unit from a key."""
if key.endswith("f"):
return key[:-1]
if key.endswith("in"):
return key[:-2]
if key.endswith("mph"):
return key[:-3]
return key
|
dc71e36f3b51959beec6a659397df8199dca519c
| 291,025 |
import base64
import hashlib
def generate_short_url(original_url: str, timestamp: float):
"""generate_short_url generates an 8 character string used to represent the original url. This 8 character
string will be used to "unshorten" to the original url submitted.
parameter original_url: the url that the user passes to the api
parameter timestamp: the current datatime timestamp
returns: an 8 character string representing the shortened url"""
to_encode_str = f'{original_url}{timestamp}'
b64_encoded_str = base64.urlsafe_b64encode(
hashlib.sha256(to_encode_str.encode()).digest()).decode()
return b64_encoded_str[:8]
|
4704111df15e9eb0f71204732fc5cf2897904cf1
| 54,022 |
import re
import string
def normalize_string(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
text = " " + re.sub(r'(\[PAD\]|\[UNK\]|\[CLS\]|\[SEP\]|\[MASK\])', ' ', text) + " "
text = text.replace(" a ", " ").replace(" an ", " ").replace(" the ", " ")
return text
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
res = ""
for ch in text:
if ch in exclude:
res += " "
else:
res += ch
return res
return white_space_fix(remove_articles(remove_punc(s)))
|
0635e5db96ebed1b6236d18dc6e310322a3b116b
| 332,625 |
def _convert_kebab_to_snake(kebab_case_string: str) -> str:
"""
Convert a string provided in kebab-case to snake_case
"""
return kebab_case_string.replace('-', '_')
|
09e48afdd8bdd2ec1d88ede61b041e63f8682f2c
| 139,729 |
from typing import Callable
from typing import Set
from typing import Type
def is_quorum(is_slice_contained: Callable[[Set[Type], Type], bool], nodes_subset: set):
"""
Check whether nodes_subset is a quorum in FBAS F (implicitly is_slice_contained method).
"""
return all([
is_slice_contained(nodes_subset, v)
for v in nodes_subset
])
|
4a4af3af8ca5a3f969570ef3537ae75c17a8015c
| 699,202 |
def unicode_item_filter(item, action_dict):
"""
Filter table items by category and search string
action_dict has the following entries controlling filtering:
cat_filter - filter for the category. if None ignore filter. 'L*' filters any Letter category
name_filter is a keyword to find the the char name, None for no filter
item_data ['no_filter'] True then passes filter automatically
"""
try:
if item.item_data and item.item_data['no_filter'] is True:
return (False, True)
except KeyError:
pass
try:
cat_filter = action_dict['cat_filter']
in_name = action_dict['name_filter']
except (KeyError):
return (False, True)
cat1 = cat2 = None
if cat_filter is not None and len(cat_filter) == 2:
cat1 = cat_filter[0] if cat_filter[0] != '*' else None
cat2 = cat_filter[1] if cat_filter[1] != '*' else None
ch_name = item.values[1]
ch_cat = item.values[2]
try:
if (cat1 is None or ch_cat[0]==cat1) and (cat2 is None or ch_cat[1]==cat2) and (in_name is None or in_name in ch_name):
return (False, True)
except (IndexError, TypeError):
pass
return (True, False)
|
120bedd13cc45d385fe4bfb43bc8530040d8fe88
| 284,842 |
def tochannel(room_name):
"""Convert a Stack room name into an idiomatic IRC channel name by downcasing
and replacing whitespace with hyphens.
"""
return '#' + room_name.lower().replace(' ', '-')
|
be6c9a2427b5faa1f198b459915a26d9afeff158
| 402,718 |
import inspect
def _extract_method_kwargs(kwargs, method, remove=True):
"""Internal method to extract keyword arguments related to a given method.
Parameters
----------
kwargs : dict
A dictionary of keyword arguments
method : func
A function with keyword arguments
remove : bool
Whether to remove the extracted keyword arguments from the original dict (the default is True)
"""
method_params = inspect.signature(method).parameters
method_kwargs = {}
to_remove = []
for key in kwargs:
if key in method_params:
method_kwargs[key] = kwargs[key]
to_remove.append(key)
if remove:
for key in to_remove:
del kwargs[key]
return method_kwargs
|
8507756708974e2d5ae72de90e6880d052204273
| 274,082 |
import time
def epochtime_to_isodate(commit_time):
"""
>>> epochtime_to_isodate(1518450170)
'2018-02-12'
"""
return time.strftime("%Y-%m-%d", time.gmtime(commit_time))
|
c34208c4204068fa57c91fd2c5504aa05c947a16
| 449,917 |
import json
def string_to_dict(value):
"""str to dict, replace '' with None"""
if not value:
return None
values = json.loads(value)
for key in values:
if values[key] == "":
values[key] = None
return values
|
d9d11241f32dd2d3cddbd89c604da60c3e9a18b7
| 671,974 |
import copy
def copy_mode(mode):
"""
Return a copy the given build mode. Use a deep copy so that flags
can be appended to the new build mode.
"""
return copy.deepcopy(mode)
|
dc7dbe2a5d0e9195c2c54c511219d5b4884c8242
| 444,076 |
def DatabaseFlags(sql_messages,
settings=None,
database_flags=None,
clear_database_flags=False):
"""Generates the database flags for the instance.
Args:
sql_messages: module, The messages module that should be used.
settings: sql_messages.Settings, the original settings, if the previous
state is needed.
database_flags: dict of flags.
clear_database_flags: boolean, True if flags should be cleared.
Returns:
list of sql_messages.DatabaseFlags objects
"""
updated_flags = []
if database_flags:
for (name, value) in sorted(database_flags.items()):
updated_flags.append(sql_messages.DatabaseFlags(name=name, value=value))
elif clear_database_flags:
updated_flags = []
elif settings:
updated_flags = settings.databaseFlags
return updated_flags
|
02ad8bc7e8c7b9806fc145d0e2e049747719d8e8
| 563,343 |
import math
def get_acc(vehicle, meters=False):
"""
Compute acceleration of a vehicle.
Parameters
----------
meters : bool
Whether to use m/s^2 (True) or km/h^2 (False).
vehicle : carla.vehicle
The vehicle for which speed is calculated.
Returns
-------
acceleration : float
The vehicle speed.
"""
acc = vehicle.get_acceleration()
acc_meter_per_second = math.sqrt(acc.x ** 2 + acc.y ** 2 + acc.z ** 2)
return acc_meter_per_second if meters else 3.6 * acc_meter_per_second
|
aff2992f8c1c47cf3b54f4412b8450acf0b2f24c
| 260,773 |
def blocktrans_cen2side(cen_size):
""" Convert from center rep to side rep
In center rep, the 6 numbers are center coordinates, then size in 3 dims
In side rep, the 6 numbers are lower x, y, z, then higher x, y, z """
cx = float(cen_size[0])
cy = float(cen_size[1])
cz = float(cen_size[2])
sx = float(cen_size[3])
sy = float(cen_size[4])
sz = float(cen_size[5])
lx,ly,lz = cx-sx/2., cy-sy/2., cz-sz/2.
hx,hy,hz = cx+sx/2., cy+sy/2., cz+sz/2.
return [lx,ly,lz,hx,hy,hz]
|
8e2791c9cc5798f754c58caeac31251eeb9664eb
| 372,531 |
def _make_sql_url(hostname, database, **kwargs):
"""Build a URL for SQLAlchemy"""
url = hostname
if kwargs.get("port"):
url = "{}:{}".format(url, kwargs["port"])
if kwargs.get("user"):
credentials = kwargs["user"]
if kwargs.get("password"):
credentials = "{}:{}".format(credentials, kwargs["password"])
url = "{}@{}".format(credentials, url)
return "postgresql://{}/{}".format(url, database)
|
53e86dfac1782a655fc4f638501db6dc6a0ecb52
| 411,642 |
from typing import Iterable
from typing import Tuple
def sum_iter(x: Iterable[int], y: Iterable[int], s: int = 1) -> Tuple[int, ...]:
""" Returns the equation x + s * y for each element in the sequence x and y """
return tuple(a + s * b for a, b in zip(x, y))
|
33de4352a9d23a462ae98f91a602037aa631fad6
| 435,336 |
def set_passive_el(xmin, xval, passive_el):
""" Sets the values of passive elements.
Args:
xmin (:obj:`numpy.array`):
xval (:obj:`numpy.array`): Indicates where there is mass.
passive_el (:obj:`numpy.array`): Passive element nodes.
Returns:
A tuple with updated xmin and xval.
"""
if xmin is not None:
xmin[passive_el] = 0.99
if xval is not None:
xval[passive_el] = 1
return xmin, xval
|
f80101a4ea4abdfed5fc3caf20195263519d6074
| 438,259 |
def tknzr_exp_name(exp_name: str) -> str:
"""Tokenizer experiment name."""
return f'{exp_name}-tokenizer'
|
24014d31ca10599ad8e289a091d05362b609ce9c
| 254,595 |
def do_almost_nothing(value):
"""Do almost nothing."""
value += 1
return value
|
a95fddb574df02eda84c7e31b85bc239b2e087af
| 434,575 |
def fill_category_object(category_id, name, is_un_classified):
"""
category object:
{
category_id: category_id,
name: category_name,
is_un_classified: boolean
}
"""
return dict(category_id=category_id, name=name, is_un_classified=is_un_classified)
|
807485164d912c66cb40d8cdb8647ca1b985c33d
| 124,474 |
def get_detection_rate(stats):
"""Get detection rate as string."""
return f'{stats["malicious"]}/{sum(stats.values())}'
|
1b294eee3b2ddafddaf4851d5a256e63b4b80705
| 594,845 |
import pathlib
import json
def maybe_shim_old_cert_store(
old_path: pathlib.Path, new_path: pathlib.Path, master_url: str
) -> None:
"""
maybe_shim_old_cert_store will detect when an old v0 cert store is present and will shim it to
a v1 cert store.
"""
if not old_path.exists():
return None
# Only try to shim when ONLY the old path exists.
if not new_path.exists():
with old_path.open("r") as f:
pem_content = f.read()
store = {master_url: pem_content}
with new_path.open("w") as f:
json.dump(store, f, indent=4, sort_keys=True)
old_path.unlink()
|
88bbb9b152da1f3a4dfad4c48a40ce579282ff4f
| 281,515 |
def _swap_first_args(op):
"""
Given a binary operator function, return a function that applies it
but with argument order swapped for the first two arguments.
"""
def op_swapped(a, b, *args, **kwargs):
return op(b, a, *args, **kwargs)
return op_swapped
|
de070bcf22dc11fdd34f8507be14729dd5c0ceb2
| 595,878 |
def _version_to_tuple(version):
"""Converts the version string ``major.minor`` to ``(major, minor)`` int tuple."""
major, minor = version.split('.')
return (int(major), int(minor))
|
921a3855fd23a597f13dab27f660cf4b0113926b
| 47,620 |
def double_sum(x, y):
"""Returns twice the sum of the two arguments"""
return 2 * (x + y)
|
57386ce717e85f564e50dcc6e3dfa9def24f3975
| 547,340 |
def bytes_find_single(x: bytes, sub: int, start: int, end: int) -> int:
"""Where is the first location of a specified byte within a given slice of a bytes object?
Compiling bytes.find compiles this function, when sub is an integer 0 to 255.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object in which to search.
sub: The subsequence to look for, as a single byte specified as an integer 0 to 255.
start: Beginning of slice of x. Interpreted as slice notation.
end: End of slice of x. Interpreted as slice notation.
Returns:
Lowest index of match within slice of x, or -1 if not found.
Raises:
ValueError: The sub argument is out of valid range.
"""
if sub < 0 or sub > 255:
raise ValueError("byte must be in range(0, 256)")
if start < 0:
start += len(x)
if start < 0:
start = 0
if end < 0:
end += len(x)
if end < 0:
end = 0
if end > len(x):
end = len(x)
index = start
while index < end:
if x[index] == sub:
return index
index += 1
return -1
|
9e94788a4d9b6c102e56cc95422b5f367754b22e
| 683,939 |
def setup_none(lvl):
"""Set up default, empty smoother."""
def smoother(A, x, b):
pass
return smoother
|
9c4c91b6c6dd98436932442d595b8fb06e83de5e
| 81,215 |
from typing import Union
def get_cell_sizes(cell_size: Union[int, list, tuple]):
"""Handle multiple type options of `cell_size`.
In order to keep the old API of following functions, as well as add
support for non-square grids we need to check cell_size type and
extend it appropriately.
Args:
cell_size: integer of tuple/list size of two with cell size
in horizontal and vertical direction.
Returns:
Horizontal and vertical cell size.
"""
if isinstance(cell_size, int):
cell_size_vertical = cell_size
cell_size_horizontal = cell_size
elif isinstance(cell_size, (tuple, list)) and len(cell_size) == 2:
# Flipping coordinates, because first coordinates coresponds with height (=vertical direction)
cell_size_vertical, cell_size_horizontal = cell_size
else:
raise TypeError("`cell_size` must be integer, tuple or list with length two.")
return cell_size_horizontal, cell_size_vertical
|
b372c2a960f59d861f08eaecbbc2f7499226272e
| 74,874 |
def _fill_zero_counters_dict(counters_config, counters_dict):
""" A util function for filling counters dict with all counters set to 0.
Args:
counters_config: a tuple containing cumulative counters configuration.
counters_dict: an empty dict to fill with zero counters.
Returns:
a filled dictionary with zero counters.
"""
for counter_name, categorizer, _, _ in counters_config:
# Counters config can contain following types of items:
# - str, None, callable(summarizer), None
# - str, callable(categorizer), callable(summarizer), None
# - str, callable(categorizer), None, nested config(tuple)
if categorizer is None:
# Set single counter if key is str
counters_dict[counter_name] = 0
else:
# if categorizer
counters_dict[counter_name] = {}
return counters_dict
|
eecd724b49c97b200942285428ea4b98d7dc2f3c
| 548,320 |
import torch
def batch_gather(input, index):
"""Similar to tf.compat.v1.batch_gather.
Args:
input: (Batch, Dim1, Dim2)
index: (Batch, N_ind)
Returns:
output: (Batch, N_ind, Dim2)
output[i, j, k] = input[i, index[i, j], k]
"""
index_exp = index.unsqueeze(2).expand(-1, -1, input.size(2))
out = torch.gather(input, 1, index_exp) # (Batch, N_ind, Dim2)
return out
|
0e4d7e9d58ab799d562d1d1c44dee73c77c0c282
| 345,756 |
def average(numbers):
"""
Calculate average of a list numbers.
:param numbers: the number to be calculated.
:return: average of a list number.
>>> average([1, 2, 2, 3, 4, 7, 9])
4.0
>>> average(range(1, 11))
5.5
>>> average(range(1, 101))
50.5
"""
return sum(numbers) / len(numbers)
|
691758bf8f3bed887595295b264a83c24b434ddf
| 528,147 |
from typing import Dict
from typing import Optional
def dict_to_str(data: Dict, sep: Optional[str] = " ") -> str:
"""Converts the given dictionary to a string separated by the given separator.
Args:
data (dict): dict that needs to be transformed
sep (str): Separator to be used.
Returns:
(str) string value of the given data.
"""
rtn = ""
for key, value in data.items():
rtn += f"{key}={value};" if sep == ";" else f'{key}="{value}"{sep}'
return rtn.rstrip(sep)
|
f6d58949727bde9cf75b4fd2dd9c155a2a894ccf
| 335,127 |
from datetime import datetime
def print_weather_data(data, verbose):
"""Displays the weather data in human readable format.
Args:
data (dict): dictionary that contains the weather data.
verbose (boolean): if `True`, more detail will be printed about
the weather and the city.
"""
info = f"""
------------------------------
City : {data['name']}
Country : {data['sys']['country']}"""
if verbose:
info += f"""
Longitude : {data['coord']['lon']}
Latitude : {data['coord']['lat']}
Sunrise : {datetime.fromtimestamp(data['sys']['sunrise']).time()}
Sunset : {datetime.fromtimestamp(data['sys']['sunset']).time()}"""
info += f"""
------------------------------
Temperature : {data['main']['temp']}"""
if verbose:
info += f"""
Temp min : {data['main']['temp_min']}
Temp max : {data['main']['temp_max']}"""
info += f"""
Pressure : {data['main']['pressure']}
Humidity : {data['main']['humidity']}
Wind speed : {data['wind']['speed']}
Wind deg : {data['wind']['deg']}
------------------------------"""
return info
|
b2c08f6d678e689b8db05e111985ad77e24830d8
| 431,342 |
import requests
def get_citeas_apa_citation(resource):
"""
Returns a dict with a resource and generated CiteAs citation in APA format.
"""
r = requests.get("https://api.citeas.org/product/" + resource)
citation = r.json()["citations"][0]["citation"]
return {resource: citation}
|
f01516b54e80304b3b603470f97cb8fa8189f574
| 40,591 |
from pathlib import Path
def guess_zarr_path(path):
"""Guess whether string path is part of a zarr hierarchy.
Parameters
----------
path : str
Path to a file or directory.
Returns
-------
bool
Whether path is for zarr.
>>> guess_zarr_path('dataset.zarr')
True
>>> guess_zarr_path('dataset.zarr/path/to/array')
True
>>> guess_zarr_path('dataset.zarr/component.png')
True
"""
return any(part.endswith(".zarr") for part in Path(path).parts)
|
fa19bd7e233d98bde90629fc36a0843e2f0c0ca2
| 620,290 |
def dead_code_remark(dead_code):
"""Generate remark for dead code detection."""
if dead_code["display_results"]:
if dead_code["failed"] != 0:
return "<li>remove dead code</li>"
else:
return ""
else:
return "<li>setup dead code detection tool</li>"
|
cc122cb5398d5e737eacf418f125c8a0a0311c9b
| 451,693 |
def time_to_str(time_in_seconds):
"""
Takes a time in Seconds and converts it to a string displaying it
in Years, Days, Hours, Minutes, Seconds.
"""
seconds = time_in_seconds
minutes = None
hours = None
days = None
years = None
if seconds > 60:
minutes = seconds // 60
seconds -= (seconds / 60)
if minutes and minutes > 60:
hours = minutes // 60
minutes %= 60
if hours and hours > 24:
days = hours // 24
hours %= 24
if days and days > 365:
years = days // 365
days %= 365
s = ''
if years:
s += '{:d} Year(s), '.format(int(years))
if days:
s += '{:d} Day(s), '.format(int(days))
if hours:
s += '{:d} Hour(s), '.format(int(hours))
if minutes:
s += '{:d} Minute(s)'.format(int(minutes))
s += (', ' if hours else ' ') + 'and '
s += '{:0.3f} Second(s)'.format(seconds)
return s
|
ac79955ae1745180719de7260ad1f3e4e3f7f1e3
| 695,408 |
def limit_count(count, on_device):
"""
Handling of the optional "count" parameter, common in many commands.
Parameters:
- count -- desired number of elements
- on_device -- number of elements on device
If count is None or 0 return what's on device
If count > 0 use count, unless it is more than what's on device.
If count < 0 that means "abs(count) less than what's on device
Typical usage:
count = limit_count(count, mc.mgrp_get_count())
"""
if count is None:
return on_device
elif count > 0:
return min(count, on_device)
else:
return max(on_device + count, 0)
|
d2a12a04980038ff0880cedf9c29ac9df5a9eede
| 189,531 |
def calc_sensor_incident_power(camera_input_power,
optical_transmission_factor):
"""
Calculate the optical power incident on the sensor.
Returns
-------
double : Watts
"""
return camera_input_power * optical_transmission_factor
|
c679593c80a45d450e4377390d2b89d2d85192d8
| 297,369 |
def _squared_dist(point_a, point_b, metric):
"""Compute geodesic distance between two points.
Compute the squared geodesic distance between point_a
and point_b, as defined by the metric.
This is an auxiliary private function that:
- is called by the method `squared_dist` of the class
SpecialEuclideanMatrixCannonicalLeftMetric,
- has been created to support the implementation
of custom_gradient in tensorflow backend.
Parameters
----------
point_a : array-like, shape=[..., dim]
Point.
point_b : array-like, shape=[..., dim]
Point.
metric : SpecialEuclideanMatrixCannonicalLeftMetric
Metric defining the distance.
Returns
-------
_ : array-like, shape=[...,]
Geodesic distance between point_a and point_b.
"""
return metric.private_squared_dist(point_a, point_b)
|
8b7c47bec4fae15af5e653f45947658dda6fd916
| 461,649 |
import random
import string
def random_alpha(n):
"""How do I generate a random string (of length n, a-z only) """
return ''.join(random.choice(string.ascii_lowercase) for _ in range(n))
|
51d7edb2428fb8ca886aa55a3490e3a3cf71af5c
| 455,591 |
def maybe_remove_parens(s: str) -> str:
"""Remove parentheses from around a string if it has them."""
if (len(s) > 1) and (s[0] == "(") and (s[-1] == ")"):
return s[1:-1]
return s
|
4c9e128f868463d922808f159b19359d8f2296d2
| 521,835 |
def fofn_to_fns(fn):
"""Return a list of file names of files in input fofn filehandler.
...doctest:
>>> fn = op.join(op.dirname(op.dirname(op.dirname(__file__))), 'tests', 'data', 'bams.fofn')
>>> fofn_to_fns(fn)
['align_p.bam', 'align_m.bam', 'align_f.bam']
"""
return [f.strip() for f in open(fn, 'r') if len(f.strip()) != 0 and not f.startswith('#')]
|
6d95d2ae4c7146874c374d075135dca3d91e050b
| 409,479 |
from io import StringIO
import string
def rot_encode(data: str, n: int = 13) -> str:
"""ROT-encode the given string, shifting `n` places."""
if not 1 <= n < 26:
raise ValueError('n must be in range [1, 26)')
with StringIO() as digest:
for char in data:
if char in string.ascii_letters:
case = (string.ascii_lowercase
if char.islower() else string.ascii_uppercase)
digest.write(case[(case.index(char) + n) % 26])
else:
digest.write(char)
return digest.getvalue()
|
662c13fa03e37cf2efbcf20e3f71c7f2aeac9048
| 265,386 |
import pathlib
def get_mlflow_artifacts_path(client, run_id):
"""Get path to where the artifacts are located.
The benefit is that we can log any file into it and even
create a custom folder hierarachy.
Parameters
----------
client : mlflow.tracking.MlflowClient
Client.
run_id : str
Unique identifier of a run.
Returns
-------
path : pathlib.Path
Path to the root folder of artifacts.
"""
artifacts_uri = client.get_run(run_id).info.artifact_uri
path_str = artifacts_uri.partition("file:")[2]
path = pathlib.Path(path_str)
return path
|
51e7254a976c71446b062e660e35c2e219d67aa8
| 387,985 |
import torch
def step_function_perturbation(perturb, epsilon_0, alpha=1e-4, norm_type='inf', smooth_approx=False, temperature=0.01):
"""
Step function applied to the perturbation norm. By default, it computes the exact step function which is not
differentiable. If a smooth approximation based on the sigmoid function is needed, set `smooth_approx=True` and set
the `temperature` to a suitably small value.
:param perturb: Torch Tensor with the perturbation. Can be a tensor of shape `(b, d1, ...)`, where `b` is the batch
size and the rest are dimensions. Can also be a single vector of shape `[d]`.
:param epsilon_0: Radius of the smaller perturbation ball - a small positive value.
:param alpha: Small negative offset for the step function. The step function's value is `-alpha` when the
perturbation norm is less than `epsilon_0`.
:param norm_type: Type of norm: 'inf' for infinity norm, '1', '2' etc for the other types of norm.
:param smooth_approx: Set to True to get a sigmoid-based approximation of the step function.
:param temperature: small non-negative value that controls the steepness of the sigmoid approximation.
:returns: tensor of function values computed for each element in the batch. Has shape `[b]`.
"""
assert isinstance(perturb, (torch.Tensor, torch.autograd.Variable)), ("Input 'perturb' should be of type "
"torch.Tensor or torch.autograd.Variable")
s = perturb.shape
dim = 1
if len(s) > 2:
perturb = perturb.view(s[0], -1) # flatten into a vector
elif len(s) == 1:
# single vector
dim = None
if norm_type == 'inf':
norm_type = float('inf')
elif not isinstance(norm_type, (int, float)):
# example: norm_type = '2'
norm_type = int(norm_type)
norm_val = torch.linalg.vector_norm(perturb, ord=norm_type, dim=dim)
if not smooth_approx:
return torch.where(norm_val <= epsilon_0, -1. * alpha, 1.)
else:
return torch.sigmoid((1. / temperature) * (norm_val - epsilon_0)) - alpha
|
9cfcfbdc228696c19256b7d6258177ea7e5e22cb
| 522,721 |
def get_period_label(dt, data_frequency):
"""
The period label for the specified date and frequency.
Parameters
----------
dt: datetime
data_frequency: str
Returns
-------
str
"""
if data_frequency == 'minute':
return '{}-{:02d}'.format(dt.year, dt.month)
else:
return '{}'.format(dt.year)
|
d842c6a7f76f0c6109b590eb462dee25473c38ec
| 447,976 |
import torch
def rmse_loss(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""Root-mean-square error loss function."""
return torch.sqrt(torch.mean((x - y) ** 2))
|
f1a7fa2091693a8903241901d1fae40a549f617d
| 252,625 |
def _GrowTreeShape(unused_op):
"""Shape function for GrowTree Op."""
return [[None], [None, 2], [None], [None], [1]]
|
e884ca24e3a1e3372cf4947819a660c6d8892c93
| 243,479 |
def avg_num_friends(graph):
"""Average number of friends in graph."""
num_nodes = 0
num_friends = 0
for node in graph.nodes(data=True):
if 'friends_total' in node[1]:
num_friends += node[1]['friends_total']
num_nodes += 1
if num_nodes == 0:
return 0
else:
return num_friends / num_nodes
|
33ec3b692ea4eab45f976d9f24a4e7914c38bc2a
| 551,733 |
def unique_node_id(graph, prefix):
"""Generate a unique id starting by a prefix.
Parameters
----------
graph : networkx.Graph
prefix : str
Prefix that is prepended to the new unique name.
Returns
-------
str
New unique node id starting with a prefix.
"""
if prefix not in graph.nodes():
return prefix
idx = 0
new_id = "{}_{}".format(prefix, idx)
while new_id in graph.nodes():
idx += 1
new_id = "{}_{}".format(prefix, idx)
return new_id
|
78e67b7ae8c4c5051081f6df11c8baebbe6b345e
| 609,780 |
def average(lst):
"""
Calculates the average of a given list
:param lst: list of numbers
:return: average value
"""
return sum(lst) / len(lst)
|
aa84f1de98cca31d84ab0e3e2a77a22d46ad622f
| 670,574 |
def get_template_path (filename: str, path_dict: dict) -> str:
"""
Returns the absolute path to the directory with indicated `filename` template.
Parameters:
filename (str) : template file to be populated
path_dict (dict) : dictionary of paths per source directory
Returns:
path (str) : resulting path
"""
for dir_type in path_dict.keys():
if dir_type in filename:
path = path_dict[dir_type]
return path
raise ValueError('Filename should contain one of the keywords')
|
f7a212c160877d2d7175d1213431f872a60f10c6
| 194,114 |
import logging
def duration(time):
"""Calculates time span of ECG strip data
The time span of the provided data indicates for how long
the ECG test was administered and provides a benchmark
for the number of expected heart beats.
Args:
time (list): time data of the ECG strip
Returns:
float: time duration of ECG strip
"""
logging.info("Calculating time span of ECG trace")
timespan = time[-1] - time[0]
return timespan
|
c161b52d53fdc410e905b9b2f8757e363acb5850
| 407,437 |
def list_2_str(data_list, join_del=""):
"""Function: list_2_str
Description: Convert a list to a string. Will be joined together with a
join delimiter. The list can consist of strings or integers.
Arguments:
(input) data_list -> List to join.
(input) join_del -> Join delimiter for the string.
(output) join_str -> Join together string.
"""
return join_del.join(str(item) for item in list(data_list))
|
eecaa0799b9340b5c992f8b92e78cb7fdfbf78f3
| 128,194 |
def getTokens(userInput):
"""splits up the userInput via commas, strips spaces
Args:
userInput (string): comma seperated search tokens, filters
Returns:
list: of all tokens that were seperated via comma
"""
allTokens = userInput.replace(" ", "").split(',')
return allTokens
|
b9efc8e76c807b9858f948c35fb32d290313eacf
| 335,082 |
def divide(first_term, second_term):
"""Divide first term by second term.
This function divides ``first_term`` by ``second_term``.
Parameters
----------
first_term : Number
First term for the division.
second_term : Number
Second term for the division.
.. warning::
Should not be zero!
Returns
-------
result : Number
Result of the division.
Raises
------
ZeroDivisionError
If second term is equal to zero.
See Also
--------
add : Addition.
subtract : Subtraction.
multiply : Multiplication.
Examples
--------
>>> divide(1, 1)
1.0
>>> divide(1, -1)
-1.0
>>> divide(4, 2)
2.0
>>> divide(1, 2)
0.5
"""
result = first_term / second_term
return result
|
ee5bc7ef5b9c71e02c9e81571060587b2010160c
| 528,689 |
import math
def normalize_dict(dictionary, x, y):
"""
Normalize values in dictinoary to be in range [x, y]
:param dictionary:
:param x: range min
:param y: range max
:return: dict with values changed accordingly
"""
min_value = min(dictionary.values())
max_value = max(dictionary.values())
if max_value <= y and min_value >= x:
return dictionary
# normalize to [0, 1]
range1 = max_value - min_value
if not range1:
range1 = 1
for key in dictionary:
dictionary[key] = (float(dictionary[key]) - min_value) / range1
# then scale [x,y] and take ceiling
range2 = y - x
for key in dictionary:
dictionary[key] = math.ceil((float(dictionary[key]) * range2) + x)
return dictionary
|
79913c028998f0bcc347b77f4e6979fe3c13dc81
| 368,830 |
def humanize_duration(seconds):
"""Converts seconds into HH:MM:SS"""
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if hour > 0:
return "%d:%02d:%02d" % (hour, minutes, seconds)
else:
return "%02d:%02d" % (minutes, seconds)
|
96d31a92f5a941d1e83dc91396423b54af6ceeae
| 500,509 |
def check_collisions(x, y, collision_radius, objs):
"""
Checks if the position x,y collide with any obj in objs with a
collision_raidus of collision_radius
"""
epsilon = 0.2
for obj in objs:
if (obj.x - x)**2 + (obj.y - y)**2 <= \
(obj.collision_radius + collision_radius + epsilon)**2:
return False
return True
|
a4f12eb4da20b0b99632f70a9189ce4969802499
| 421,766 |
def get_frequency(fn: str, start: int = 0) -> int:
"""Takes frequency modulation file and returns final frequency"""
with open(fn) as f:
return start + sum(int(item) for item in f)
|
ceae0b22f114603a8491241321806cc8b6287db6
| 195,825 |
import json
def generate_config(competitor_count, stream_count):
""" Returns a JSON string containing a config. The config pits vector_add
against a number of dummy_streams instances, specified by competitor_count.
The vector_add plugin always does the same amount of work, so the intention
behind this test is to vary the number of streams it's competing against.
Values of streams_per_competitor over 4 shouldn't matter, unless the
GPU_MAX_HW_QUEUES environment variable is over 4. """
queue_count = competitor_count * stream_count
# The vector add plugin should launch exactly 10 blocks--since it has 1024
# threads per block and 10 * 1024 elements per vector.
measured_task_config = {
"label": str(queue_count),
"log_name": "results/test_oversub_vs_%d_queues.json" % (queue_count,),
"filename": "./bin/vector_add.so",
"thread_count": 1024,
"block_count": 1,
"additional_info": {
"vector_length": 10 * 1024,
"skip_copy": True
}
}
# I think it's a bit more realistic to trigger oversubscription using a
# large number of competitors rather than using CU masks to have a single
# competitor with tons of streams.
competitor_config = {
"filename": "./bin/dummy_streams.so",
"log_name": "/dev/null",
"thread_count": 1,
"block_count": 1,
"additional_info": {
"stream_count": stream_count,
}
}
# Create our list of plugins with the measured task and competitors.
plugin_list = [measured_task_config]
for i in range(competitor_count):
# We need to give each competitor a unique log name.
plugin_list.append(competitor_config.copy())
log_name = "results/dummy_streams_competitor_%d.json" % (i,)
plugin_list[i + 1]["log_name"] = log_name
name = "Vector Add Performance vs. Number of Queues"
overall_config = {
"name": name,
"max_iterations": 100,
"max_time": 0,
"gpu_device_id": 0,
"use_processes": True,
"do_warmup": True,
"omit_block_times": True,
"sync_every_iteration": True,
"plugins": plugin_list
}
return json.dumps(overall_config)
|
55ef4691955a5e296f386e451474d659e1e8b1b6
| 230,044 |
def _escape_html(text, escape_spaces=False):
"""Escape a string to be usable in HTML code."""
result = ""
for c in text:
if c == "<":
result += "<"
elif c == ">":
result += ">"
elif c == "&":
result += "&"
elif c == '"':
result += """
elif c == "'":
result += "'"
elif c == " " and escape_spaces:
result += " "
elif ord(c) < 32 or 127 <= ord(c) < 160:
result += '&#x{0};'.format(hex(ord(c))[2:])
else:
result += c
return result
|
cc501ea996fe971750a448c0b9589934f6b78b04
| 549,967 |
import shlex
def join_args(args):
"""Compose command line from argument list."""
return ' '.join(map(shlex.quote, args))
|
daec8c6a334c8a91ccaaad6c17d6b36ce566ffa7
| 129,890 |
import math
def CO2_Calc(PO2, T):
"""
Calculate CO2.
:param PO2: partial pressure [atm]
:type PO2 : float
:param T: cell operation temperature [K]
:type T : float
:return: CO2 [mol/cm^3] as float
"""
try:
result = PO2 / (5.08 * (10 ** 6) * math.exp(-498 / T))
return result
except (TypeError, ZeroDivisionError, OverflowError, ValueError):
print(
"[Error] CO2 Calculation Failed (PO2:%s, T:%s)" %
(str(PO2), str(T)))
|
727115f6d4c8deb70412abfcb06956a0dade1ba9
| 383,094 |
def split_comma(string):
"""Split the string at the comma and return the list."""
if type(string) is not str:
raise ValueError("This is not a string")
return string.split(',')
|
d5225af9ba1df728202ec1f6add7047840fdc691
| 497,084 |
def gradient(color_one, color_two, blend_weight):
"""
Blend between two colors with a given ratio.
:param color_one: first color, as an (r,g,b) tuple
:param color_two: second color, as an (r,g,b) tuple
:param blend_weight: Blend weight (ratio) of second color, 0.0 to 1.0
"""
if blend_weight < 0.0:
blend_weight = 0.0
elif blend_weight > 1.0:
blend_weight = 1.0
initial_weight = 1.0 - blend_weight
return (int(color_one[0] * initial_weight + color_two[0] * blend_weight),
int(color_one[1] * initial_weight + color_two[1] * blend_weight),
int(color_one[2] * initial_weight + color_two[2] * blend_weight))
|
7a3645acf3a83b093e96b706f8d118e47ef85c87
| 641,267 |
def bytes_from_hex(value):
"""There are many ways to convert hex to binary in python.
This function is here to attempt to standardize on a single method.
Additionally, it will return None of None is passed to it
instead of throwing an expected string exception
"""
if not value:
return None
return bytes.fromhex(value)
|
574019f671d389f2dbf876156796266c57e9d550
| 643,103 |
def encode_topic_name(original: str) -> str:
"""
Encodes a channel name into a valid SNS topic name. Common characters in topics are '*', '/', '.', ':'. Those are
translated into markers like '_WCD_'.
:param original: the original topic name (e.g., 'my.program/foo')
:return: encoded topic name safe for SNS (e.g., my_DOT_program_FWS_foo
"""
encoded = original
encoded = encoded.replace("*", "_WCD_")
encoded = encoded.replace("/", "_FWS_")
encoded = encoded.replace(".", "_DOT_")
encoded = encoded.replace(":", "_COL_")
encoded = encoded.replace("<", "_LT_")
encoded = encoded.replace(">", "_GT_")
return encoded
|
ae61877e95b6de287dfaa31efe126668f25fcb31
| 233,924 |
def predict_tf_lite(model, image):
"""
TFLite model prediction (forward propagate)
:param model: TFLite interpreter
:param image: Input image
:return: Numpy array with logits
"""
input_details = model.get_input_details()
output_details = model.get_output_details()
model.set_tensor(input_details[0]['index'], image)
model.invoke()
# n_outputs = len(output_details)
outputs = []
# import ipdb; ipdb.set_trace()
for i in range(len(output_details)):
tf_lite_output = model.get_tensor(output_details[i]['index'])
outputs += [tf_lite_output]
outputs = sorted(outputs, key=lambda x: x.shape)
return outputs
|
6f651f602498066024aa370531f9afe2f94f8a60
| 618,029 |
def _GetRequestParams(options):
"""Extracts request parameters which will be passed to PostTryJob.
Args:
options: The options object parsed from the command line.
Returns:
A dictionary with parameters to pass to PostTryJob.
"""
params = {
'user': options.user,
'name': options.name,
}
# Add other parameters if they're available in the options object.
for key in ['email', 'revision', 'root', 'bot', 'patch']:
option = getattr(options, key)
if option:
params[key] = option
return params
|
51d39b4a5640351b3b15fb9e6dd0a1f98cacf9f7
| 367,210 |
from typing import List
def midi_note_on(note: int, channel: int = 0, velocity: int = 64) -> List[int]:
"""MIDI 9nH message - note on.
>>> midi_note_on(70)
[144, 70, 64]
>>> midi_note_on(70, velocity=127, channel=15)
[159, 70, 127]
"""
status = 0x90 + channel
return [status, note, velocity]
|
76522963fc84dae8b60fb5b08317bd65a0d51c7f
| 511,405 |
import re
def remove_shape_from_input_value(input_value: str):
"""
Removes the shape specification from the input string. The shape specification is a string enclosed with square
brackets.
:param input_value: string passed as input to the --input command line parameter
:return: string without shape specification
"""
assert '->' not in input_value, 'The function should not be called for input_value with constant value specified'
return re.sub(r'[(\[]([0-9\.? -]*)[)\]]', '', input_value)
|
69c497c15172c97037e04dc10641c74f3f51dc4d
| 505,094 |
import re
def pretty_label(inStr):
"""
Makes a pretty version of our column names
"zone_1" -> "Zone 1"
"zone_2"-> "Zone 2
...
"zone_strength" -> "Strength"
"""
pattern = re.compile("zone_[12345]{1}|zone_1,2")
if pattern.match(inStr):
out = inStr
else:
out = inStr[5:]
return out.replace("_", " ").capitalize()
|
6ca7cb31e7d7996417ba06905cce0ae33709dd7e
| 251,088 |
def parse_ip(ip: str) -> tuple:
"""
Returns IP address from str as int tuple
eg: '192.168.43.1' -> (192, 168, 43, 1)
"""
splitted = ip.split('.')
if (len(splitted) != 4):
raise ValueError("Invalid IP format")
ret = []
for num in splitted:
ret.append(int(num))
if ret[-1] < 0 or ret[-1] > 255:
raise ValueError("Invalid IP format")
return tuple(ret)
|
6eb5d1601e6dd4672b83f3f8ff62603847cc4a65
| 175,204 |
def get_mother_attr(gen_dict, class_dict, key):
"""Get the list of the key value from the class, including mother ones.
Used to get all the properties or method of a class
Parameters
----------
gen_dict : dict
Dict with key = class name and value = class dict (name, package, properties, methods...)
class_dict : dict
Dictionnary of the class to generate (keys are name, package, properties, methods...)
key : str
Key to extract from the mother class(es) ("properties" or "methods")
Returns
-------
(all_list, mother_list) : tuple
all_list: List of all the "key" of the class including mother class(es) ones
mother_list: List of the "key" from the mother class(es) only
"""
# Load all the mother properties
all_list = list(class_dict[key])
mother_list = list()
while class_dict["mother"] != "":
class_dict = gen_dict[class_dict["mother"]]
mother_list.extend(class_dict[key])
all_list.extend(mother_list)
return (all_list, mother_list)
|
b7474c8a9f6d9da2848788ece8d99b24c17a523a
| 371,447 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.