content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def fails_if_called(test, msg="This function must not be called.",
arguments=True):
"""
Return a new function (accepting any arguments)
that will call test.fail(msg) if it is called.
:keyword bool arguments: If set to ``False``, then we will
not accept any arguments. This ca... | a234b141a8e24a74a15a98929aee02a181721f5c | 677,002 |
def init_stats():
"""Initialize statistics that we want to accumulate."""
return {"step_time": 0.0, "exp_loss": 0.0, "grad_norm": 0.0, } | 2a0bf2ba23ea9670d5f080093d3e9709081f9274 | 677,003 |
def qualifiedClassName(obj):
"""
Utility method for returning the fully qualified class name of an instance.
Objects must be instances of "new classes."
"""
return obj.__module__ + "." + type(obj).__name__ | 47b2f9b05b4132ced64bff1b840a1ec6bde55b53 | 677,004 |
from pathlib import Path
def path_relative(fp):
"""Given a filepath returns a normalized a path"""
return str(Path(fp)) | a65d91e5023e49dbe285946421c485c8d2aaa95d | 677,005 |
import torch
def pairwise_distance(node_feature):
"""
Compute the l2 distance between any two features in a group of features
:param node_feature: a group of feature vectors organized as batch_size x channels x number_of_nodes
"""
batch_size = node_feature.shape[0]
node_feature = node_fea... | ea3017dccb6b7c5b9364407af1218a741ce3a85c | 677,006 |
def cels_from_fahr(fahr):
"""Convert a temperature i Fahrenhit to Celsius and retures
teh Celsius temprearature"""
cels = (fahr - 32) * 5 / 9
return cels | 66d9f11fdba180bc64277b60087a7800359deb85 | 677,007 |
def bound(x, m, M=None):
"""
:param x: scalar
Either have m as scalar, so bound(x,m,M) which returns m <= x <= M *OR*
have m as length 2 vector, bound(x,m, <IGNORED>) returns m[0] <= x <= m[1].
"""
if M is None:
M = m[1]
m = m[0]
# bound x between min (m) and Max (M)
retu... | 8617bb2012d768c6bb9c8911f61c9160f5a05191 | 677,008 |
from typing import List
import functools
def conjunction_for_group(lines: List[str]) -> int:
"""
Returns the number of questions that everybody in the group
answered yes to.
"""
sets = [set(line) for line in lines]
intersection = lambda a, b: a & b
return len(functools.reduce(intersection,... | 3d4d0886ef864d5ce4d79f07c86d1a4682230b50 | 677,010 |
from typing import Union
from typing import Any
import ast
def cast(value, ast_eval: bool = False) -> Union[int, str, Any]:
"""Casts values to native Python types.
lxml ETree return types don't do this automatically, and by using
ast.literal_eval we can directly map string representations of
lists et... | 9c7e8ebfc4436a4f2ab8f7f9b63c337bcd9717f2 | 677,012 |
import random
def make_deal(cards=[]):
"""
Deals 2 cards to player and 2 cards to dealer
"""
if cards:
return cards
for _ in range(4):
cards.append(random.randint(2, 11))
return cards | 6a651929016d480081a9da496b192266909aa7e0 | 677,013 |
def _parse_polarity_data(line_iter):
"""
1-4 a4 station name
7 a1 polarity:U,u,+,D,d,or-
8 i1 quality: 0=good quality, 1=lower quality, etc
59-62 f4.1 source-station distance (km)
66-68 i3 takeoff angle
79-81 i3 azimuth
83-85 i3 takeoff angle uncertainty
87-89 i3 azimuth angle unc... | 477974bdd12c4d088122dc87d2d29dba8c54a448 | 677,014 |
def is_six_band(frequency: int) -> bool:
"""determines if a channel frequency is in the 6.0-7.125 GHz ISM band"""
if frequency > 5900 and frequency < 7125:
return True
else:
return False | 0169d59720c6efee57fa8021a14d5117610d45b4 | 677,015 |
def setify(i):
"""
Iterable to set.
"""
return set(i) | c80798d64691333d54f4322b69897461f1243e58 | 677,016 |
import time
def with_connection(func, self, *args, **argd):
"""
with_connection: decorator; make sure that there is a connection available
for action. Set the connections 'last_used' attribute to current timestamp.
We always get a fresh connection from the CONNECTION REGISTRY since the
'extras' co... | 3eac295c253a387ebb2723c227e905871cdc2452 | 677,017 |
def forkpty():
"""Fork a child process, using a new pseudo-terminal as the child's controlling
terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
new child's process id in the parent, and *fd* is the file descriptor of the
master end of the pseudo-terminal. For a ... | fb2b71aa3fb0105645b4e76a7ae9d68489bd88f1 | 677,018 |
def to_snake(camel):
"""TimeSkill -> time_skill"""
if not camel:
return camel
return ''.join('_' + x if 'A' <= x <= 'Z' else x for x in camel).lower()[camel[0].isupper():] | 5a3cfe9ce0681a9e805d405a87cdfda927d7012e | 677,019 |
from typing import Set
def compute_number_of_edge_types(
tied_fwd_bkwd_edge_types: Set[int], num_fwd_edge_types: int, add_self_loop_edges: bool
) -> int:
"""Computes the number of edge types after adding backward edges and possibly self loops."""
return 2 * num_fwd_edge_types - len(tied_fwd_bkwd_edge_type... | ce806bf83ac60d287eb49d97794ab77e8c4bd310 | 677,020 |
import re
def uppercase_lowercase(a_string):
"""Assumes a_string is a string
returns a boolean, True is a_string contains one upper case letter
followed by lower case letters
else False
"""
regex = "[A-Z][a-z]+"
results = re.search(regex, a_string)
return bool(results) | cd0623fd885b1f6d4833b901852985f4317e9156 | 677,021 |
def _get_mean_dist(data: list):
"""
Calculates the average euclidian distance matrix from prior training c-means.
-----------------------------------------------------------------------------------
!!! For statistical evaluation !!!
------------------------------------------------------------------... | e192a9d406bf2da68933b3006a959b1f1b6401b4 | 677,022 |
def process_string(config, x):
""""Process a string.
This is necessary especially for the heavily used $DECOMP_ROOT variable.
"""
for key, item in config.variables.items():
x = x.replace(key, item)
return x | e2cc464e479f09e169087755122a9e60d57ad6ec | 677,023 |
import math
def calc_pb(j, params):
"""
Calculates probability of glass breakage (Pb, IM1).
"""
b = (params.k / (pow(params.a/1000 * params.b/1000, params.m - 1))) * (
pow(1000*params.E * pow(params.h/1000, 2), params.m)) * params.ldf * (math.exp(j))
pb = 1 - math.exp(-b)
return pb | 5afd9cec8ac2b98c2dcc0fe45dec78f474443b34 | 677,024 |
def gray_augment(is_training=True, **kwargs):
"""Applies random grayscale augmentation."""
if is_training:
prob = kwargs['prob'] if 'prob' in kwargs else 0.2
return [('gray', {'prob': prob})]
return [] | 072ca5bcd47dfebf38e6777608cbf4d105eacc63 | 677,025 |
def winsorize_at_explicit_input(x, lower_bound, upper_bound):
"""
Winsorizes the array x at the lower_bound and upper_bound.
:param x: a numpy array-like object
:param lower_bound: a scalar for the lower bound
:param upper_bound: a scalar for the upper bound
:return: the winsorized array
""... | 4aabf8a3fcc4f5b1ac301f69d622edc88d5923ed | 677,026 |
def chunk(iterable, num_chunks, fillvalue=(None, None)):
"""break list into num_chunks chunks. Ugly.
Stolen from the web somewhere.
"""
num = float(len(iterable)) / num_chunks
chunks = [iterable[i:i + int(num)] for i in range(0, (num_chunks - 1) * int(num), int(num))]
chunks.append(iterable[(nu... | b6ce276c676c329c49eb3acb150721f6a4af9324 | 677,027 |
import random
def randomIslandbourne():
"""
This function generate a random number, between a range that is present on the map of the game
@param None:
@return : (str) that represent a name, that are inside of the game
"""
islandNumb = random.randint(0,10)
nameisland = "island "+ str(islandNumb)
return name... | 85163924d03f7b6996de17c6e21585333a8306a7 | 677,028 |
import glob
import os
def get_files_directory(path, full_filenames=True, reverse_sort=False):
"""
Gets list of files from a directory
Given a path it will return a list of all files as a list
Parameters
----------
path: str
filepath to load files from, including wildcards will only l... | 205784963d4dcdcb954fe37a1efd0dc983090e6f | 677,029 |
def _parse_str_to_dict(x):
"""Convert "k1:v1,k2:v2" string to dict
Args:
x (str): Input string
Returns:
dict: Dictionary {"k1": "v1", "k2": "v2"}
"""
d = {}
for p in x.split(","):
if ":" in p:
k, v = p.split(":")
d[k] = v
return d | 5659b55900adddfd856a4c97d03406747a8e2603 | 677,030 |
def shifted_price_col(df, colname, dt):
"""
function to compute daily change in price and add to the dataframe
change = (price on day t) - (price on day t+1)
used as the target variable
:param df: pd.DataFrame of stocks. should at least include a closing price
columnn named 'Close'
... | b6a4922658236fcda48e13e5f600ada3b6f46080 | 677,032 |
def subject_tag_get_all(client, subject_id, session=None):
"""Get a list of tags for a specific subject."""
return client.subject_tag_get_all(subject_id=subject_id) | d6ed89494f98da75ae69c5c05e1565b97ff3f5a1 | 677,034 |
def _extract_fields_from_row(row, element):
"""Pluck data from the provided row and element."""
row_data = []
fields = row.find_all(element)
for raw_field in fields:
field = raw_field.text.strip()
row_data.append(field)
return row_data | 081473db76f139eab4687b60f309801b40f1c69a | 677,035 |
def normalize_brightness_dict(brightness_dict):
"""Usually the distribution of the character brightness for a given font
is not as diverse as we would like it to be. This results in a pretty
poor result during the image to ASCII art conversion (if used as-is).
Because of this it's much better to normal... | fa857be51d983c96ec03856da252935eb44cb6be | 677,036 |
def sorted_lines(filename):
"""Returns a list consisting of the lines of the file, sorted in alphabetical order."""
with open(filename, 'r') as input_file:
lines = input_file.readlines()
return lines.sort() | 20d5d4a6b33b531242495ea447b6e6117bf4bd11 | 677,037 |
def check_expr(check_output):
"""A function which takes an expression as a string, construct a B program
which evaluates the expression and prints it using putnumb and compares it
to an expected output."""
def _check_expr(expr, expected):
check_output('''
main() {
ext... | c9b8263e83da379a16e65bf4c002ac14e2fd867f | 677,038 |
def urlQuoteSpecific(s, toQuote=''):
"""
Only quote characters in toQuote
"""
result = []
for c in s:
if c in toQuote:
result.append("%%%02X" % ord(c))
else:
result.append(c)
return "".join(result) | 54eabf6885e8bc19aa717fe162eebf1ffe472ab6 | 677,039 |
def all_smaller(nums1: set, nums2: set) -> bool:
"""Return whether every number in nums1 is less than every number in num2.
You may ASSUME that:
- nums1 is non-empty
- nums2 is non-empty
- nums1 and nums2 contain only integers and/or floats
>>> all_smaller({2}, {3})
True
>>> all_... | 0676797b13b61f16a892159410d024b326ca2eb5 | 677,041 |
def reorder_cols_df(df, col_order, inpl=True):
"""reorder columns in dataframe """
cols = list(df.columns)
check = all(item in cols for item in col_order)
if check:
newdf = df[col_order]
if inpl==True:
df = newdf
return 1
else:
return newdf
... | 48ca2c67fe2c078d27823af2c8f7f29d04aaff8a | 677,042 |
def treasury_bill_price(discount_yield, days_to_maturity):
"""Computes price ot treasury bill"""
return 100 * (1 - days_to_maturity / 360 * discount_yield) | 339ea159edabd252a3f2cf3705226b7cc643cc19 | 677,043 |
import torch
def _get_test_data(with_boundary=True, identical=True):
"""
Produces test data in the format [Batch size x W x H], where batch size is 2, W=3 and H=3.
In the first batch the pixel at 3,2 is a boundary pixel and in the second pixel at 1,2
:param with_boundary: bool
if true there i... | bcc6699c4b15305e9fb031b4fd60719be49be581 | 677,044 |
def accelerated_step_size( f , guess , step=.01 ):
"""
accelerated_step_size( f , guess , step ).
This method finds the minimum of a function (f) using the accelerated step size search.
Parameters:
f (function): the function to minimize
guess (float): initial value to start the algorithm
s... | 36be14b651824fa6b11cf90449c1c81de6735b16 | 677,045 |
def _analyse_gdal_output(output):
"""
Analyse the output from gpt to find if it executes successfully.
Parameters
----------
output : str
Ouptut from gpt.
Returns
-------
flag : boolean
False if "Error" is found and True if not.
"""
# return false if "Error" is ... | ede18bb90358211b7cbcab1eea3a36222553ce49 | 677,046 |
import os
import re
def detect_requirements_txt(folder):
"""
detect requirements.txt from current folder
:rtype: List[str]
:return: path tot the requirements.txt
"""
files = os.listdir(folder)
# support requirement & requirements
selected = [f for f in files if re.match("requirements?... | cfdab46bba48b9280bdc92d3c38a9e91ea7b6148 | 677,047 |
def rundir(request):
"""
Directory to extract files to
"""
return request.config.option.rundir | fe4cb18d8b73337de9808e3519097456b0c6b070 | 677,048 |
def _parse_argument(s):
"""
"""
if s is None:
return s
if isinstance(s, int):
return s
if isinstance(s, float):
return s
try:
return str(s)
except Exception:
return s | b2a8869d73eabef42aae2b77af3aaac298f8d017 | 677,049 |
def normalized_current_date(datetime_col, min_date, max_date):
"""
Temporal feature indicating the position of the date of a record in the
entire time period under consideration, normalized to be between 0 and 1.
Args:
datetime_col: Datetime column.
min_date: minimum value of date.
... | 2947aa4de2aa5e98ec9c33c51fbda8716ff13e37 | 677,050 |
def _is_permutation_winning(my, result, count):
"""判断是否匹配(排列方式)
my: 排列数1
result: 排列数2
count: 匹配的位数
e.g.:
my = [9,9,8,5,6,3,8]
result = [2,0,3,5,6,4,9]
count = 2
return is True
"""
s, e = 0, count #逐个切片
while e <= len(result):
if my[s:e] == res... | db2f4658541b734ad346bc6a651c471551879cf6 | 677,051 |
import string
import random
def random_string_generator(size=10, chars=string.ascii_uppercase + string.digits):
"""
Generate a random string of `size` consisting of `chars`
"""
return ''.join(random.choice(chars) for _ in range(size)) | 836c182093f9e89c208d2db491cc889fc65efe22 | 677,052 |
import torch
def sequence_mask(lengths, maxlen, dtype=None):
"""
Exact same behavior as tf.sequence_mask.
Thanks to Dimitris Papatheodorou
(https://discuss.pytorch.org/t/pytorch-equivalent-for-tf-sequence-mask/
39036).
"""
if maxlen is None:
maxlen = lengths.max()
mask = ~(tor... | 7c6101bc1256a09b9dadcdfc421115be3f60c46d | 677,053 |
def ensure_list_or_tuple(obj):
"""
Takes some object and wraps it in a list - i.e. [obj] - unless the object
is already a list or a tuple instance. In that case, simply returns 'obj'
Args:
obj: Any object
Returns:
[obj] if obj is not a list or tuple, else obj
"""
return [ob... | 1b8e0365bc303f43f465feb77b88c2091bf943df | 677,054 |
import requests
def get_agents(url, agents_tag, headers):
"""Get the agents."""
req = requests.get(url + "/agents/", headers=headers)
if req.status_code != 200:
raise ValueError("Unable to get the token")
return [a for a in req.json()["results"] if agents_tag in a["parameters"]["tags"]] | fb9991c0a417b78f13a8f6d814cd9db8966905e1 | 677,055 |
def clean_args(args):
"""
Cleans up the args that weren't passed in
"""
for arg in args:
if not args[arg]:
del args[arg]
return args | 05ebdeef663d0f8cdc02ea60e21cdc8699bbfd62 | 677,056 |
import math
def get_num_length_for_fractional(number, base):
"""Given length of a fractional decimal number, return the length of the
equivalent representation in the new base.
Parameters:
number: float -- representation of number
base: int -- base to convert to
Return:
... | 958ea08d2a1a193a353908ede1750c6d79dc28fd | 677,057 |
def pd_subset_latest(df1, field_val, field_sortmax):
"""
# only keep the latest section with the latest size
# (eg if the ec2 had the size s1 then s2 then s1, only keep the latest)
"""
if df1.shape[0]==0: return df1
df2 = df1.sort_values(by=field_sortmax, ascending=True)
latest_val = df2[fi... | bca9d218de4a2938e60d10d0581b7859d7cb6c4f | 677,058 |
def section(name):
"""
Returns regex matching the specified section. Case is ignored in name.
"""
return r'(?<=\n)={2,} *' + fr'(?i:{name})' + r' *={2,}' | db0e196a3d3f095d4b0bd82ff9f3fc1c887ff6b6 | 677,059 |
import time
import re
def to_kubernetes_name(name, prefix=""):
"""
Returns a valid and unique kubernetes name based on prefix and name, replacing characters in name as necessary
see https://kubernetes.io/docs/concepts/overview/working-with-objects/names/
"""
unique_id = str(time.time()).replace(".... | 6cee3f8f9cc9ce8293ae3517ec66f38d55ccd9a2 | 677,060 |
def replace_frames(infile, reorders):
"""Put frames into the right order, returning a list of binary objects"""
return list() | 4563dcf8bf9b2bf0610cd3244d826294b6748310 | 677,061 |
from typing import Type
from typing import TypeVar
import inspect
def type_label(attr_type: Type) -> str:
"""
Generate the label to be used to describe an `attr_type` in generated
user documentation. Since we care about the output of this method when
`attr_type` points to a `spec_cls` decorated type, ... | c138c07368c673d5e8294d6f62081a6d9a78cbda | 677,062 |
def get_feature_lists():
"""This is a static function to DRY our code for feature categorization
Returns
-------
A tuple of lists of feature types with feature names in them.
numeric_features_general,
numeric_features_special,
categorical_features_general,
categorical_fe... | ea3b58149312f15f157f85ceaba83215010c6b38 | 677,063 |
def voltage_piv(power, current):
"""Usage: voltage_piv(power,current)"""
return power/current | 9fe1be7e7817beead1cf0e88e897961a6887608f | 677,064 |
def formata_processo(_processo: str) -> str:
"""
formata o numero do processo divindo o numero pelos devidos campos
:param _processo: str
:return: str
"""
return f'{_processo[-20:-13]}-{_processo[-13:-11]}.{_processo[-11:-7]}.{_processo[-7:-6]}.{_processo[-6:-4]}.{_processo[-4:]}' | c374310609d027f6b69f96d8c9f5e810ff240e32 | 677,065 |
def target_state(target_dict):
"""Converting properties to target states
Args:
target_dict: dictionary containing target names as keys and target objects as values
Returns:
dictionary mapping target name to its state
"""
if {} == target_dict:
return None
result = {}
... | 642463e545924758eae99706f5bb018e63a4a398 | 677,066 |
import argparse
def parse_fulltest(optlist=None):
"""Parse fulltest options.
This parses either sys.argv or a list of strings passed in. If passing
an option list, you can create that more easily using the
:func:`option_list` function.
Args:
optlist (list, optional): Optional list of ar... | 3f7acca46faa1fcc9940c4c5280d3e6ac2d7e023 | 677,068 |
def height_handler(length_value):
"""
:param length_value:
:return: the height of the triangle
"""
return length_value * 0.5 * 3 ** 0.5 | c8f78b0e63f4843b4237b22a685cfc790d4f4c68 | 677,069 |
def get_entity_by_id(entity_class, aid):
"""
通过主键获得 entity
:param entity_class:
:param aid:
:return:
"""
return entity_class.select().where(entity_class.id == aid).first() | e17de4068f322010af4795918a5fef670308e0a5 | 677,070 |
def F_calc(TP, FP, FN, beta):
"""
Calculate F-score.
:param TP: true positive
:type TP: int
:param FP: false positive
:type FP: int
:param FN: false negative
:type FN: int
:param beta: beta coefficient
:type beta: float
:return: F-score as float
"""
try:
resu... | 452894f75b9b3586ee686bb6d8cd5dcd71cbfeae | 677,071 |
def title_case(sentence):
"""
Capitalize the first letter of every word.
Parameters
----------------
sentence: string
The sentence to be put into title case.
Returns
----------------
capitalized: string
The input string in title case.
"""
if sentence == sentenc... | 1c886f4d6ca369313ee02d7e3d9b4d304032c2df | 677,072 |
def horner(a, x):
"""
T(n) = Theta(n^2) since we have to traverse a nested loop for each term
:param a: list of "n" coefficients
:x float: the value for which to compute the polynomial value
"""
y = 0
for i in range(len(a)):
temp = 1
print("temp= 1")
for j in ran... | 326ecc7ff0d273529c95df5d7c2abbfae7966112 | 677,073 |
import pickle
def pkl_data(stuff,pkl_file_name = "Quandl_data.pkl"):
"""
pkl_data = pkl_data(stuff,pkl_file_name)
where
INPUTS:
stuff is a Python object to pickle
pkl_file_name is a string that is the file name of the file to pickle
pkl_data pickles data and results in a binary file ... | bff66d1fdb02007c9552aaf693707f0afd2c972b | 677,074 |
def testme(si):
"""Revert a string, filtering out the vowel characters"""
so = ''.join([c for c in reversed(si) if c.lower() not in 'aeiouy'])
return so, len(so) | ea90c3e95139b51f5854a32c3602607e26fd3a6a | 677,075 |
def img_pred(path):
"""Sends a path to an image to the classifier, should return a
JSON object."""
if path == "https://michelangelostestbucket.s3.us-west-2.amazonaws.com/8bf0322348cc11e7e3cc98325fbfcaa1":
result = "{'frogs' : '3'}"
else:
result = {'sharks': '17'}
return result | 6dbbbbad106cc92cb2c0736ac7459bfd3f5c70c7 | 677,076 |
def status_readable_name_with_count(value, count):
"""Converts the underscore from a status name into a space and adds trait count for it"""
readable_name = value.replace('_', ' ')
return f"{readable_name} [{count}]" | 81c8b3bc59e958aa7b6276f0db9e6c851d5256c7 | 677,077 |
import hashlib
def get_md5(file: str) -> str:
"""
Get the md5code of file.
:param file: The path of file.
:return: The md5code of file
"""
m = hashlib.md5()
with open(file, 'rb') as f:
for line in f:
m.update(line)
md5code = m.hexdigest()
return md5code | 2a26ab60d6484f72e7e50ca1a01e8771916d1bb0 | 677,078 |
import pathlib
def get_test_materials_dir():
"""Returns the path of the test-materials directory."""
return pathlib.Path(__file__).parent / "test-materials" | f304c9f17f32c70432ad71e53962be9b26a91c18 | 677,079 |
def diz_oi():
"""Uma função simpes que retorna a string 'Oi!'"""
return 'Oi!' | ceeb1befa02c48e746c393d42a49e753842f8107 | 677,080 |
import os
def get_yosys():
"""Return how to execute Yosys: the value of $YOSYS if set, otherwise just
`yosys`."""
return os.getenv("YOSYS", "yosys") | c9a60d4c5aae97d28ba3aec2d341356c3e402bae | 677,081 |
import torch
import math
def phi2rphi(phi, radius):
"""
:param phi: in cube [0, 1] ^ d
:param radius: R, pi, ..., pi, 2pi
:return: r in [0, R], phi_i in [0, pi] for i in [1, d-2], phi_i in [0, 2pi] for i = d-1
"""
r = 0.5 * (1 - torch.cos(phi[:, 0:1] * math.pi)) * radius
if phi.size(1) > 2:
rphi = torch.ca... | c5370e4455eb77c8be5f4a2d589836a56734dd9e | 677,082 |
import argparse
def parse_args():
"""Parse command-line arguments to this script.
"""
desc = """Build Gaussian process models on wafer data. Expects ./train/ and
./test/ subfolders of current directory to have training and test data for
each wafer to predict.
"""
epilog = """Open-sourced ... | 7c546f75f9773830e21365245839942a91ba78b6 | 677,083 |
def mergeDicts(dict1, dict2):
"""Merge two dictionaries."""
res = {**dict1, **dict2}
return res | 32960e3b2a7b6864acf06d56cf6b0d7a0479b99c | 677,084 |
import re
def cleanup_page_name(title):
"""make page name from title"""
name = title.lower()
name = re.sub('[~!@#$%^&*+()<>,."\'\?]', '', name)
name = re.sub('[:/]', '-', name)
name = '-'.join(name.split())
# replace repeating hyphens
name = re.sub(r"(-)\1+", r"\1", name)
return name | d8264aae1bada7a8430df34a797707624d53b0e9 | 677,085 |
import numpy as np
import random
def get_random_odd_list(n):
"""
Creates a random list with only one element that occurs an odd number of times
:param n: Size of the resulting list
:return:
N-sized random list with only one element occurring an odd number of times
and the odd occurring element
""... | 921e6bbcb719af417365e352ce917960b31bcedc | 677,086 |
def dict_keys_lower(d):
"""list of dictionary keys in lower case"""
return list(map(str.lower, d.keys())) | 9cb29394bbff0efd5ebc44f638290fd2d1bb3a94 | 677,087 |
def expand(x, y, cals, shown, length, width):
"""
Expand empty position with no bombs surrounded
:param x: horizontal position
:param y: vertical position
:param cals: matrix of numbers
:param shown: list of positions shown
:param length: length of the board
:param width: width of the bo... | bd834c9dfb604260cc9e5eba8b5cbc19458dd1ce | 677,088 |
def encrypt(sk, x): #outputs cipher
"""
Performs the encrypt algorithm for IPE.
"""
(detB, B, Bstar, group, g1, g2) = sk
n = len(x)
beta = 1
c1 = [0] * n
for j in range(n):
sum = 0
for i in range(n):
sum += x[i] * Bstar[i][j]
c1[j] = beta * sum
for i in range(n):
c1[i] = g2 ... | 94bce86f1a34a532b74f715f60069e5a18d00c0f | 677,089 |
def test_remove_duplicates_from_sorted_matrix():
"""
Replace duplicate values of sorted matrix with zeros
"""
def redup(M):
p = None
x,y = None,None
for i in range(len(M)):
for j in range(len(M[i])):
if p is not None and M[i][j]==p:
M[i][j] = 0
M[x][y] = 0 # Paint ... | 8a2a1306fbb53c9e29a76aa3e0c27fe3f05d8a3e | 677,090 |
def get_batch_token_embeddings(layer_hidden_states, attention_mask, rm_special_tokens=False):
""" remove padding and special tokens
Args:
layer_hidden_states: (N, L, D)
attention_mask: (N, L) with 1 indicate valid bits, 0 pad bits
rm_special_tokens: bool, whether to remove special tokens... | 3945784b428df47adc628343c794271fb447e82a | 677,091 |
import copy
def get_social_config(env):
"""
Arguments:
env: Arena-Blowblow-Sparse-2T2P-Discrete
Returns:
[[0,1],[2,3]]
"""
xTxP = env.split("-")[-2]
T = int(xTxP.split("T")[0])
P = int(xTxP.split("T")[1].split("P")[0])
policy_i = 0
all_list = []
for t in ran... | 09781e93b2339ab0df262fdd6968aa94626f9ef2 | 677,092 |
def delete_at(my_list=[], idx=0):
"""
deletes an element from a list at a given index
"""
l_len = len(my_list)
if idx >= l_len or idx < 0:
return (my_list)
del my_list[idx]
return (my_list) | 63c1897eb87a2feed7c013c0b277bacd7d3f61d5 | 677,093 |
import random
def create_room(size_x=random.randint(1, 5), size_y=random.randint(1, 5)):
"""
Creates a rectangular box/room with size_x * size_y floor tiles
Requires: size_x, size_y > 0
"""
top_bottom_walls = ["# "] * (size_x + 2)
inner = ["# "] + ["_ "] * size_x + ["# "]
room = [top_bott... | 305d21b36b966ee8f964859a53eb1f4db7b47e38 | 677,094 |
import random
def _get_pin(length=5):
""" Return a numeric PIN with length digits """
return random.sample(range(10**(length-1), 10**length), 1)[0] | f24ce227d88a63a429475b07df761babb3d35c97 | 677,095 |
def swap_byte_order(arr_in):
"""Swap the byte order of a numpy array to the native one.
Parameters
----------
arr_in : `~numpy.ndarray`
Input array.
Returns
-------
arr_out : `~numpy.ndarray`
Array with native byte order.
"""
if arr_in.dtype.byteorder not in ("=", "... | ac583be80cdc417e990dd883ea5e7efd0dedcc4c | 677,097 |
def parallel(*items):
"""
resistors in parallel, and thanks to
duck typing and operator overloading, this happens
to be exactly what we need for kalman sensor fusion.
>>> assert parallel(1.0,2.0) == 1/(1/1.0+1/2.0)
"""
inverted = [item**(-1) for item in items]
return sum(inverted... | 9fc4a289b0aab45b3c7d788bbbef9c03b22468a5 | 677,099 |
def equatable(cls):
"""
Adds an __eq__ method that compares all the values in an object's __dict__ to all the values in another instance
of that object's dict. Note keys are NOT checked, however types are. Only *identical* types (not subclasses)
are accepted.
NOTE: this method will also set __hash_... | 3691a74bd878338dcdc494df0c7320202c470ca5 | 677,100 |
def applyToChildren(a, f):
"""Apply the given function to all the children of a"""
if a == None:
return a
for field in a._fields:
child = getattr(a, field)
if type(child) == list:
i = 0
while i < len(child):
temp = f(child[i])
if type(temp) == list:
child = child[:i] + temp + child[i+1:]
... | 86a4e5f63249e8c7999b6987da182704cdff5acd | 677,101 |
import re
def strip_control_characters(text):
"""
from http://chase-seibert.github.com/blog/2011/05/20/stripping-control-characters-in-python.html
"""
if text:
# unicode invalid characters
RE_XML_ILLEGAL = '([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])' +\
... | 1940fd57588ec4f1ec03cf18731fff1c4d237484 | 677,102 |
import configparser
import os
def get_config(config_path):
"""Read vaultlocker configuration from config file
:param: config_path: path to the configuration file
:returns: configparser. Parsed configuration options
"""
config = configparser.ConfigParser({'kv_version': '1'})
if os.path.exists(... | 1bcad92fca9aba10780d16aa86581cb15d62e9ce | 677,103 |
from typing import OrderedDict
def getIndexedODictLookUp(dictionary:OrderedDict):
"""
This getter returns a OrderedDict's key value look up.
:param dictionary:OrderedDict: given ordered dictionairy
"""
try:
ind= {k:i for i,k in enumerate(dictionary.keys())}
return ind
excep... | 704a38296582d19278447099ebdeddbc35d63f07 | 677,104 |
import math
def calculate_edge_weight(subscriber_cnt):
""" Keep weights relatively small despite large subscriber disparities """
if subscriber_cnt == 0:
log_cnt = 0
else:
log_cnt = math.log2(subscriber_cnt)
return str(log_cnt) | 1a7dfdce6a86bb1a86df28d543885e94bdb78610 | 677,105 |
def apply_casing_script(lemma: str, casing_script: str):
"""Applies a casing script to a string.
Assumes the string has already been lemmatized.
Args:
lemma (str)
casing_script (str, optional): casing script in string form
Returns:
str: string with applied casing
"""
... | 16312ca7f39ea53f4bd73b5e2c9c8d46b8e1c89d | 677,106 |
def determineTranslation(translation,reference_orientation):
"""
Convert a translation in the world reference frame to a translation in
the steroid reference frame.
"""
return translation*reference_orientation.I | 315905b96818f6474f6f27f3db9f91da1b8bf14a | 677,107 |
def is_empty(value: object) -> bool:
"""
Check if value is None or not empty in case if not None.
"""
return (value is None) or (not value) | 88b848e6a25da134a3408def4db83d258a031919 | 677,108 |
def replace_multiple(main_string, to_be_replaced, new_string):
"""replace extra elements in a text string"""
for elem in to_be_replaced :
if elem in main_string :
main_string = main_string.replace(elem, new_string)
return main_string | 429de26df3b02e17cd63f9caf25aff019412a3ff | 677,109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.