content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def convertLUtoUN(s):
"""Capitalize a string and remove any underscores.
If 'hello_world' is given, it will return 'HelloWorld'.
"""
return ''.join([word.capitalize() for word in s.split('_')]) | f37623bbc49ed452f4a5c83fce20f6ccb5665679 | 623,072 |
import torch
def compute_ece(predictions, labels, num_bins=None):
""" Compute the expected calibration error with binning
Args:
predictions (tensor): a batch of categorical predictions with shape [batch_size, num_classes]
labels (tensor): a batch of labels with shape [batch_size]
num... | 8ab95edd4eef159334e1f86b5e09776d2f6d1ea6 | 623,075 |
def genRef(ref):
"""Returns input as function"""
def r():
return ref
return r | c402ef4dd2147627dbb7028d8b0eff795c856a11 | 623,076 |
def kcorrect_calc(
d: float, oldflux: float, z1: float, z2: float, a: float
) -> float:
"""Performs the k-correction calculation given the required arguments.
Args:
d: The distance modulation, in terms of a factor. E.g. a value of 10
would indicate a distance change of 10x.
oldf... | d83e27511785d052c5f39ae2b527fc03114c2152 | 623,078 |
from typing import List
def _read_line() -> List[int]:
"""Read an input line, split it and convert to ints."""
return list(map(int, input().split())) | 46aa9a398fbf6417d72146cf1c190d16ea7791ba | 623,081 |
from pathlib import Path
def _deduce_images_and_annos_paths(root_path, subset):
"""Deduces paths for images and annotations. It returns the root path
that contains all the sequences belonging to the specific subset.
Args:
root_path (str): Root directory path to the UA-DETRAC dataset.
subs... | 0c1f72b21d86cc5827231a279d93d30fd5d65af1 | 623,083 |
def linscale(seq, minval=0.0, maxval=1.0):
"""Linearly scales all the values in the sequence to lie between the given values.
Shifts up to minval and scales by the difference ``maxval-minval``
If all values are identical, then sets them to `minval`."""
m, M = min(seq), max(seq)
def sc(s, m=m, M=M):
... | b4d58c7efc5d4fc66f89a7c115f764615f1be60f | 623,086 |
import copy
def add2dict(key: str, val, dict: dict):
"""Add key/value pair to dict"""
new_dict = copy.deepcopy(dict)
new_dict[key] = val
return new_dict | 33cc6db0fae08dee1476cfff71957055006deb63 | 623,088 |
def rotate_counter_clockwise(shape):
"""Given a shape, rotates it counter clockwise"""
return [
[shape[y][x] for y in range(len(shape))]
for x in range(len(shape[0]) - 1, -1, -1)
] | 3991bfed91b2876b3b04520cd573d2c737a435cd | 623,090 |
def event_counter(object_type: str) -> str:
"""Return db key for the event counter for the object type.
The value stored at this key is used to generate a unique event id.
Args:
object_type (str): Type of object.
Returns:
str, database key for the event counter
"""
return 'ev... | eb1ad15af86d70e7aaf9415707201aef934ca1fc | 623,091 |
import re
def remove_tags(text: str) -> str:
"""
Removes tags and extracts text inside square brackets [] and angle brackets <>.
Also removes 'cleartext' 'CLEARTEXT' or 'Cleartext' as well as language attributes
(2 letter uppercase sequences following 'cleartext' and space(s) or dash(es)).
:param... | ce3a5f0bdbe3e588ee82b354cd3bfd26abe9031a | 623,093 |
def is_every_letter_guessed(word, guesses):
"""Returns if every letter in the target word is accounted for in
the user's guesses.
"""
# It's easier to check the converse; are we missing anything? Check
# if any one of the letters in the target word *isn't* guessed.
for letter in word:
i... | 27238a9e8c6e4cbbb4f37a364b48648602d95491 | 623,094 |
def parse_timedelta_from_api(data_dict, key_root):
"""Returns a dict with the appropriate key for filling a two-part timedelta
field where the fields are named <key_root>_number and <key_root>_units.
Parameters
----------
data_dict: dict
API json response containing a key matching the key_r... | 467130e50d3d5d0a224eed83822d352713ef11c2 | 623,095 |
def construct_api_params(
business_unit=None,
event_type=None,
limit=None,
page_token=None
):
"""
Constructs the parameters object for the API call. Note that startDateUtc and
endDateUtc are not listed here (although they are parameters); this is because
they are included... | 36f4de8a30d6cbf6aff72b08130553843b7eec7d | 623,096 |
import requests
def get_json(name, *args, **kwargs):
"""Retrieve JSON from a (REST) API server after checking correct response."""
r = requests.get(*args, **kwargs)
assert r.ok, "%s access failed: %s" % (name, r.reason)
return r.json() | 59dc53615b7ca6e48d0d9a83536ea9ca8d81577f | 623,103 |
def parse_geometry(geometry):
"""Parse a geometry string and returns a (width, height) tuple
Eg:
'100x200' ==> (100, 200)
'50' ==> (50, None)
'50x' ==> (50, None)
'x100' ==> (None, 100)
None ==> None
A callable `geometry` parameter is also supported.
"""
if n... | 650d7537161e1f739df397d9231ab5f0f28a3a89 | 623,104 |
def signed_shift(val, shift):
"""Bit shifts the value val. +ve values shift left and -ve shift right.
Args:
val (int): Value to be shifted
shift (int): Number of bits to shift by
Returns:
int: Shifted result
"""
return val << shift if shift >= 0 else val >> -shift | 88f0361e7e2d7cf4a46a1ee6e3ce71c322aaf735 | 623,106 |
import logging
def get_logger(sub_module, log_name):
"""
Get logger by name and sub module.
Args:
sub_module (str): Sub module name, type is string.
log_name (str): Log file name, type is string.
Returns:
Logger, logger instance named by sub_module and log_name.
"""
... | 0dd97feaa812b933147f0ef1a45bd2af752d8af6 | 623,110 |
def module_exists(module_name):
""" Check if a module can be imported. """
try:
__import__(module_name)
except ImportError:
return False
else:
return True | b73bf8b0273460814c15029697c7936ce78257fb | 623,113 |
def match_ans(input_guess, current_guess, ans):
"""
Matching new guess alphabet to each answer char if equals, and return the replaced hint of latest guess.
:param input_guess: str, the new guess alphabet.
:param current_guess: str, the hint of current guess.
:param ans: str, the hidden random word.... | 46670d7bd17458e336694bc0015c1b58e97914b3 | 623,115 |
import struct
def octet(value):
"""Encode an octet value.
:param value: Value to encode
:rtype: bytes
:raises: TypeError
"""
if not isinstance(value, int):
raise TypeError('int type required')
return struct.pack('B', value) | b166b9b0eeff33b3e680b3dd9808ec0d6b24a4a3 | 623,116 |
def processFile(fileName: str):
"""
Processes the file and returns the amount of vertices in the graph, as well
as the adjency matrix representation of the graph.
"""
file = open(fileName, "r+")
lines = file.readlines()
if(len(lines) < 2):
raise Exception("File must have atleast two... | c3cdb70780fbf91ad5c0d68706d9b00411c44eb9 | 623,118 |
def cart2wind(cart_angle):
""" 0deg is North, rotate clockwise"""
cart_angle = 90. - cart_angle #rotate so N is 0deg
cart_angle =cart_angle % 360.
return cart_angle | 208bf5ae3059a19730615807fdb76233594c5e6f | 623,119 |
from typing import Iterable
def to_abs_coord(v, mat):
"""
Change the local vertices coordinate to absolute coordinate
:param v: vector or a list of vertices
:param mat: matrix_world
:return: the Absolute vertices
"""
if isinstance(v, Iterable):
list_verts = []
for i in v:
... | dea20a5e0e980beb41c5b4efc358958895336b20 | 623,120 |
def _get_weight_param_summary(wp):
"""Get a summary of _NeuralNetwork_pb2.WeightParams
Args:
wp : _NeuralNetwork_pb2.WeightParams - the _NeuralNetwork_pb2.WeightParams message to display
Returns:
a str summary for wp
"""
summary_str = ''
if wp.HasField('quantization'):
nbits = wp... | 63c1218487dadfea8e452aa1124bd7792085a71c | 623,125 |
def ringIsClockwise(ringToTest):
"""
determine if polygon ring coordinates are clockwise. clockwise signifies
outer ring, counter-clockwise an inner ring or hole.
"""
total = 0
i = 0
rLength = len(ringToTest)
pt1 = ringToTest[i]
pt2 = None
for i in range(0, rLength - 1):
... | 5423f0f7ed51ac174af727e6a0195e696b803fee | 623,127 |
def all_attrs_missing(record):
"""Checks if all attributes have missing values, excluding ID and Class"""
return all(value == '?' for value in record[1:-1]) | 95edc3fcb42645e438b7c3267c4996f02085b0eb | 623,130 |
def is_expression(expression: list) -> bool:
"""Return True if the string is an expression, False otherwise.
A string is an expression if it starts with the "=" symbol.
Raises:
ValueError: Empty expression raises when the string is empty.
"""
if len(expression) == 0:
raise ValueErr... | 4a518eae610ac993c4454b622db56a200e9791f9 | 623,140 |
from datetime import datetime
def convert_date(raw_date: str):
"""
Convert raw date field into a value interpretable by the dataserver.
The date filtering API expects mm/dd/YYYYZ format.
"""
if raw_date.startswith("None"):
return None
try:
date = datetime.strptime(raw_date, "%... | 9f4c53ccd6c269f7f980c5103ef8d8a236f05b9a | 623,141 |
def normalise(x):
"""Normalise set of vectors by elementwise mean and standard deviation."""
x_mean = x.mean(0)
x_std = x.std(0)
return (x - x_mean) / x_std, x_mean, x_std | c12e529b1c422d65a93becd07e286d36502fed66 | 623,144 |
def any_in_any(a, b):
"""return true if any item of 'a' is found
inside 'b'
else return false
"""
if len([x for x in a if x in b]) > 0:
return True
else:
return False | e9333301b9bf1ae70cc329a5c76bacd7d80f6d67 | 623,148 |
def table_name_suffix(load_table_s3_prefix: str) -> str:
"""
Table name suffix should be '__ct' if the S3 prefix is from change tracking.
Parameters
----------
load_table_s3_prefix : str
The load's prefix as determined by its S3 key.
Returns
-------
str
"__ct" or "" dep... | 16df14ef505ea2bdc42d396510bd49ffa2fe33cf | 623,151 |
def get_portal_registration_status(self) -> dict:
"""Get current Orchestrator Cloud Portal registration status
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - spPortal
- GET
- /spPortal/registration
:return: Retur... | a4b2d587be8e76ccb672533dab8f3f38f4b41198 | 623,156 |
def reduce(combiner, seq):
"""Combines elements in seq using combiner.
>>> reduce(lambda x, y: x + y, [1, 2, 3, 4])
10
>>> reduce(lambda x, y: x * y, [1, 2, 3, 4])
24
>>> reduce(lambda x, y: x * y, [4])
4
"""
reduced = seq[0]
for x in seq[1:]:
reduced = combiner(reduced,... | 13453aa65cad538a32eaf148390b32031178209a | 623,157 |
def anglicize1to19(n):
"""
Returns the English equiv of n.
Parameter: the integer to anglicize
Precondition: n in 1..19
"""
if n == 1:
return 'one'
elif n == 2:
return 'two'
elif n == 3:
return 'three'
elif n == 4:
return 'four'
elif n == 5:
... | faa87aa7fa8db485da22715e7c754098babe5af2 | 623,159 |
import math
def dejmps_gates_and_measurement_alice(q1, q2):
"""
Performs the gates and measurements for Alice's side of the DEJMPS protocol
:param q1: Alice's qubit from the first entangled pair
:param q2: Alice's qubit from the second entangled pair
:return: Integer 0/1 indicating Alice's measure... | 97199b44981e109aa1b766f4e44b207cf6ee2728 | 623,163 |
def min_max_norm(x):
""" Performs min-max normalization --> scales values in range between 1 and 0
:param x (1-D array like)
:return: (1-D np.array) min-max normalized input
"""
mini = min(x)
maxi = max(x)
return (x - mini) / (maxi - mini) | 72b19fb7e5bf47fcf78d51676a9b89c3694bee44 | 623,166 |
from typing import List
import torch
def pad_sequences_from_list(array: List[List[int]]) -> torch.Tensor:
"""Performs post padding on sequences to make sequences same length.
Adds padding with id 0
Args:
array (List[List[int]]): List of list of token_ids
Returns:
torch.Tensor: Padded... | 78a33249e9d8e711170dadaee30dc7ca775968ff | 623,171 |
def clean_country_names(df):
"""
Given a dataframe with only 1 column 'country/region'
cleans country names
"""
cleaned_df = df.replace({'country/region':
{'US': 'United States',
'Taiwan*': 'Taiwan',
'Kor... | 1d6bd893bc1ceb666844042acf3fdeaef27db3f4 | 623,173 |
def get_cik_path(cik):
"""
Get path on EDGAR or S3 for a given CIK.
:param cik: company CIK
:return:
"""
return "edgar/data/{0}/".format(cik) | 93fe3e4015cec97e9360d94a2f8020fe7bc5b2bd | 623,174 |
def LCross(S1,S2):
"""
S1 and S2 are two element tuples of two element tuples of
x,y coordinates of the two lines:
Routine to check if two line segments intersect
returns 0 if they don't intersect, 1 if they intersect
"""
((px1,py1),(px2,py2)) = S1
((px3,py3),(px4,py4)) = S2
# First some utility f... | d0663b28377ab180de5b07e95264fb6334d2271d | 623,177 |
import csv
def parse_csv(csv_file):
"""Parses an individual CSV file into a set of data points
Args:
csv_file (File): a csv file
Returns:
List[List[int,int,float]]: A list of data points.
Each data points consist of
... | e2040af9ab9ff2036fb402484450d447f38de310 | 623,180 |
def set_whole_node_entry(entry_information):
"""Set whole node entry
Args:
entry_information (dict): a dictionary of entry information from white list file
Returns:
dict: a dictionary of entry information from white list file with whole node settings
"""
if "submit_attrs" in entry_... | 650068343620696f5e16126cb08fb156219d23ec | 623,188 |
import imp
def ModuleAvailability(module_name):
"""
Checks if a module is installed/available on the current system.
Args:
module_name: [str] name of the module to check for availability.
Returns:
A boolean indicating whether the module is available.
"""
try:
imp.fin... | 58e2cac69d0d50f9869c19639ab90c4f034ff635 | 623,191 |
def transform_test(true, pred):
"""Transform true and predicted raster data sets to
flat arrays.
Parameters
----------
true : array-like
Testing data set raster as a 2D NumPy array.
pred : array-like
Predicted values as a 2D NumPy array.
Returns
-------
y_true : arr... | 91a756cd8a2c7f6bff4f1f0664c20af942848312 | 623,192 |
import hashlib
def hash_pass(password, salt):
"""Returns the hash of `password` with salt `salt`"""
return hashlib.pbkdf2_hmac('sha512', password.encode(), salt, 100000) | cf2048d1b3226ef85110768f5bc241bdb0813053 | 623,194 |
from typing import Any
def is_false_schema(schema: Any) -> bool:
"""True if the value of `schema` is the always reject schema.
The `false` schema forbids a given value. For writers this means the value
is never produced, for readers it means the value is always rejected.
>>> is_false_schema(parse_js... | 6c86d26213182bcb8012d42274f0f9c12247ee36 | 623,195 |
def get_tfidf_score(tf_vocab, idf_vocab):
"""Calculate the tfidf score for an article
:param tf_vocab: a dict that maps a word into its tf value
:param idf_vocab: a dict that maps a word into its idf value
:returns: a list of tuple, where the first element is the word,
the second element i... | b6fdd90d5688cdc71804e0dfb11387efbeda1a96 | 623,196 |
def format_output(header, content):
"""
Formatted the result header and content, separated by double newlines.
"""
if content is not None:
if type(content) == str:
content = [content]
return "\n\n".join([header, *content])
else:
return header | 4bc8d935c78dec32d1a5bfbd84431787dc226c1c | 623,198 |
import codecs
def _get_encoding(enc, read=False):
"""Check if encoding exists else return utf-8."""
try:
codecs.lookup(enc)
except LookupError:
enc = 'utf-8'
# If reading utf-8, lets just read with utf-8-sig
# so we don't have to worry about an accidental BOM
if read and enc.... | 3d6f82398244e75dce1837796de427dacdc4655d | 623,199 |
def get_tensor_data(tensor_data_array, tensor_name):
"""Find the tensor data for this tensor by its name."""
for i in range(len(tensor_data_array.data_array)):
if tensor_data_array.data_array[i].name == tensor_name:
return tensor_data_array.data_array[i]
return None | 84d078b58142a879c37899e519fc5c9e728a66ee | 623,200 |
def is_identical_aggregation(aggr_x: dict, aggr_y: dict) -> bool:
"""
Checks whether two aggregated signals are identical
Both signals are checked on and therefore *must* contain the following keys:
- type
- subject
- handler
:param aggr_x: Aggregation x
:param aggr_y: Aggregation y
... | 86ce783478c9307ddd08f8cbbbf5813077b95bc6 | 623,204 |
def collect_defines(file_name):
"""
Collect all XCB defines from file.
"""
defines = []
with open(file_name, "r") as f:
for line in f.readlines():
line = line.strip()
if not line.startswith("#define XCB"):
continue
defines.append(line)
... | 63e18552edc074068e7e5ef3b5c3322ef1cd1e21 | 623,205 |
def MMAX_POSITION_FROM_ID(ID):
"""
Extract the position from a MMAX ID
"""
return int(str(ID).split('_')[-1]) | 9b0556868b3185204caec88992809eb231a97c9d | 623,207 |
def unpad(img, pads):
"""
img: numpy array of the shape (height, width)
pads: (x_min_pad, y_min_pad, x_max_pad, y_max_pad)
@return padded image
"""
(x_min_pad, y_min_pad, x_max_pad, y_max_pad) = pads
height, width = img.shape[:2]
return img[y_min_pad:height - y_max_pad, x_min_pad:width ... | 7e68ba934ecacbdecc29d35c74965c53abe1e45a | 623,208 |
def token_in_list_ignore_case(token: str, list_check: list) -> bool:
"""Function that checks if the given token is in the list of tokens ignoring the case.
Args:
token: Token to be searched in the list.
list_check: List of tokens within which to search.
Returns:
Boolean value:
... | 38647ea5b9216a7a85996a164c4377efd6476c98 | 623,209 |
def remove(base, string):
"""Remove a substring from a string"""
return base.replace(string, '') | 02e6132cfb7801e7fccb9c92ef7fac9d592f7442 | 623,214 |
def sum_to_num(max_number):
"""
Returns the sum from 0 to max_number inclusive.
>>> from gender_novels.testing import tests
>>> x = tests.sum_to_num(3)
>>> x
6
>>> x = tests.sum_to_num(100)
>>> x
5050
"""
sum_result = 0
for n in range(max_number + 1):
sum_result... | 3a659654f0c46d29c0e749bb675618666902740e | 623,215 |
def recombination(temperature):
"""
Calculates the case-B hydrogen recombination rate for a gas at a certain
temperature.
Parameters
----------
temperature (``float``):
Isothermal temperature of the upper atmosphere in unit of Kelvin.
Returns
-------
alpha_rec (``float``):
... | 25c719497f961ae7f3e2071fe675e37ea623e9be | 623,216 |
def all_of(pred, iterable):
"""
Returns ``True`` if ``pred`` returns ``True`` for all the elements in
the ``iterable`` range or if the range is empty, and ``False`` otherwise.
>>> all_of(lambda x: x % 2 == 0, [2, 4, 6, 8])
True
:param pred: a predicate function to check a value from th... | e0fcf8acb36518f636b8d2527f5c89aa696aef1c | 623,220 |
def distance(coord_a, coord_b):
"""
Calcuate the distance between 2 coordinates.
Arguments:
coord_a (array): coordinate of point a
coord_b (array): coordinate of point b
Return:
dist (float)
"""
assert len(coord_a) == len(coord_b)
dim = len(coord_a)
sum_square_d... | 01d7c93c50d90a8e2089a754399431de4eacf962 | 623,226 |
import math
def parallax(
emission1: float, gndaz1: float, emission2: float, gndaz2: float
) -> float:
"""Returns the parallax angle between the two look vectors described
by the emission angles and sub-spacecraft ground azimuth angles.
Input angles are assumed to be radians, as is the return v... | 3289d898183f012591b994c89d03a820f1b0f7f2 | 623,228 |
def _time_string(minutes):
"""Time D-hh:mm:ss format."""
minutes = max(minutes, 0)
seconds = int(round((minutes % 1) * 60))
hours, minutes = divmod(int(minutes), 60)
return f'{hours:02}:{minutes:02}:{seconds:02}' | 504d2a4f255350e87428b3dfb32783e0d931ea31 | 623,231 |
def ackermann(m: int, n: int) -> int:
"""Implement Ackermann function recursively.
Raise:
- TypeError for given non integers
- ValueError for given negative integers
"""
if type(m) is not int or type(n) is not int:
raise TypeError("m and/or n isn't integer")
if m < 0 or n < 0:
... | 513e83363b4c063486bc0956755b71293654a149 | 623,232 |
def validate_unit(unit: str) -> str:
"""
Validates the unit of an object.
:param unit: The unit of the object.
:return: The validated unit.
"""
if not unit:
raise ValueError("Unit must not be empty.")
if len(unit) > 100:
raise ValueError("Unit must not be longer than 100 cha... | e10e066f766d36d11e038c318add4dc62088600e | 623,234 |
from typing import Callable
from typing import Set
import click
from typing import Union
from typing import Optional
def make_existing_cluster_id_option(
existing_cluster_ids_func: Callable[[], Set[str]],
) -> Callable[[Callable[..., None]], Callable[..., None]]:
"""
Return a Click option for choosing an ... | 5c9832e669dde8d3b538f0cb7ca47a5ebbaac9f6 | 623,240 |
def wcPy(f):
"""Count up lines in file 'f'."""
return sum(1 for l in f) | 8ad3d97fc0fde9906817175e70c5e2feb1fcde1e | 623,241 |
def pop(array, index=-1):
"""Remove element of array at `index` and return element.
Args:
array (list): List to pop from.
index (int, optional): Index to remove element from. Defaults to
``-1``.
Returns:
mixed: Value at `index`.
Warning:
`array` is modified... | 0d71b80117fc4d808b91d0bfe866f2c6052f7c7a | 623,242 |
def get_tags(html_soup):
"""
Extracts keywords of the article from content
Input : Content in BeautifulSoup format
Output : List of keywords of the article
"""
tags = html_soup.findAll('a', attrs = {"class" : "tag"})
all_tags = []
for i in tags:
all_tags.append(i.get_text())... | eb7d0241545b60b290a2b622327698d30e56164c | 623,243 |
def bprop_sub(x, y, dz):
"""Backpropagator for primitive `sub`."""
return (dz, -dz) | 77ef9d321b5b776b2512f70f67541beea3afda00 | 623,244 |
def load_input(filename):
"""
Load input ciphertext
"""
with open(filename) as f:
return [int(token) for token in f.readlines()[0].strip().split(",")] | 7e9fa192ad71083a98750b285ababa9e30a1b4a9 | 623,250 |
def get_unique_name(new_name, name_list, addendum='_new'):
"""
Utility function to return a new unique name if name is in list.
Parameters
----------
new_name : string
name to be updated
name_list: list
list of existing names
addendum: string
addendum appended to new... | 0125eb8e6330ac0dfe6ef7a4e6581c52ddd869ec | 623,256 |
def twitter_id_from_timestamp(ts: float) -> int:
"""Get twitter id from timestamp
Args:
ts (float): time stamp in seconds
Returns:
int: twitter id representing the timestamp
"""
return (int(ts * 1000) - 1288834974657) << 22 | 2eb6f394e217f28d5950d9fe6d03d868d4696ffb | 623,257 |
def node_vertex_name(mesh_node, vertex_id):
"""
Returns the full name of the given node vertex
:param mesh_node: str
:param vertex_id: int
:return: str
"""
return '{}.vtx[{}]'.format(mesh_node, vertex_id) | b9b419638544455827b6e5d2dbe69efd23e7399f | 623,262 |
def AES_read_key(filepath):
"""Read in the key to use for encryption / decryption"""
fh = open(filepath, 'r')
# read and encode to bytes
key = fh.read().encode("utf-8")[0:32]
fh.close()
return key | c7f127ab27c0c29b605db2e6f29231e21b9144df | 623,268 |
def pivot_area_cluster(df, cluster, aggfunc=sum):
"""Convert long data into a matrix, pivoting on `cluster`
For example, take BRES/IDBR data at Local authority (LAD) geographic level
and SIC4 sectoral level to create matrix with elements representing the
activity level for a given LAD-SIC4 combination.... | cff2308bd7ca5810f3245e1069009c044dc561ef | 623,269 |
def get_user_input(question='Enter your transaction amount: '):
"""
Returns the user input
Parameters
----------
question : str
The question the user sees
"""
return float(input(question)) | 5c867e4ae997bbc22bab212678addd463d2b240b | 623,281 |
def is_int(arange):
""" Check if a range is int
Args:
test_range ([int/float, int/float]): range to test
Returns:
.boolean
"""
if (isinstance(arange[0], int)
and isinstance(arange[1], int)):
return True
return False | e9869e87f8b5111b8e6fe0ac5aca8b1f5412805a | 623,287 |
import re
def GetExamplesTextFromDocOptText(DocOptText):
"""Get script usage example lines from a docopt doc string. The example text
line start from a line containing `Examples:` keyword at the beginning of the line.
Arguments:
DocOptText (str): Doc string containing script usage examples l... | 0e3cbfa7d23dc4f92f1938212bd67f11d31ccf06 | 623,288 |
def two_sided_midpoint_PV(dist, s, out_dir, PVs_file):
"""
two-sided midpoint PV - Hohna et al. 2017
:param dist: simulated distributions
:param s: current original statistic to compare
:param out_dir: where to write results to
:param PVs_file: the calculated two-sided midpoint p-values
:ret... | 5e6a6d14bbc02a339f7b9eba72910cc023d571f3 | 623,290 |
def _repr_column_dict(dumper, data):
"""
Represent ColumnDict in yaml dump.
This is the same as an ordinary mapping except that the keys
are written in a fixed order that makes sense for astropy table
columns.
"""
return dumper.represent_mapping(u'tag:yaml.org,2002:map', data) | ee4efea312ff5085b553e8975f143ee37124b949 | 623,292 |
def _dict_of_targetid(submitid, charid, journalid):
"""
Given a target of some type, return a dictionary indicating what the 'some
type' is. The dictionary's key will be the appropriate column on the Report
model.
"""
if submitid:
return {'target_sub': submitid}
elif charid:
... | db4698f0732cd30a116c92d2b6350e798527af70 | 623,296 |
from typing import List
from typing import Dict
def _normalise_map(unformatted_map: List[List[str]]) -> Dict[str, str]:
"""Input format: [[value1,key1,key2],[value2,key4]]
Output format: {key1:value1, key2: value1, key3:value2}"""
normalised_map = {}
for group in unformatted_map:
value = grou... | c81634fc8eb1893175b77a7b54ecfb4f1cf92d3f | 623,298 |
def get_class_name(node):
"""
Simple wrapper to get a _class knob off a node so that you can use standard nuke nodes like group, NoOp etc, but
give them their own "class".
Args:
node (nuke.Node): A node object we want to get a class from.
Returns:
str: The node class.
"""
... | 09027c082a9f45fdbdd15b0cc9bbd7fa6694c7cb | 623,302 |
import torch
def categorical_accuracy(y, y_pred):
"""Calculates categorical accuracy.
# Arguments:
y_pred: Prediction probabilities or logits of shape [batch_size, num_categories]
y: Ground truth categories. Must have shape [batch_size,]
"""
return torch.eq(y_pred.argmax(dim=-1), y).s... | 7d14853b2ce1770619d9bfc45fb7f42934435988 | 623,304 |
def remove_stop_words(input_str):
"""Removes stop words from query string"""
remove_list = ['a', 'an', 'and', 'of', 'as', 'in', 'for', 'on', 'the', 'near', 'not', 'to', 'is']
word_list = input_str.split()
cleaned_str = ' '.join([i for i in word_list if i.lower() not in remove_list])
return cleaned_s... | 30060363608a4bddd2d88a3f0c2e233d467a4545 | 623,306 |
def turc(tmean, rs, rh, k=0.31):
"""Evaporation calculated according to [turc_1961]_.
Parameters
----------
tmean: pandas.Series
average day temperature [°C]
rs: pandas.Series
incoming solar radiation [MJ m-2 d-1]
rh: pandas.Series
mean daily relative humidity [%]
k:... | 031562746fab9a875b9214e38aaff0f1a7259256 | 623,307 |
import math
def rms_error(seq1, seq2):
"""Returns the RMS error between two lists of values"""
assert len(seq1) == len(seq2)
return math.sqrt(sum((x - y) ** 2 for x, y in zip(seq1, seq2)) / len(seq1)) | de846eb1b318e24563319ce11013f6a0ca7583c5 | 623,309 |
def get_sample_rate(header):
""" get sample frequency from header """
sample_rate = int(header[0].strip().split()[2])
return sample_rate | 18e5d87d80fd709ed7ae5210e33eb95754686d0d | 623,313 |
def _any_trits(left: int, right: int) -> int:
"""
Adds two individual trits together and returns a single trit
indicating whether the result is positive or negative.
"""
res = left + right
return (res > 0) - (res < 0) | dbf94b4a650cb06eb851c26b25f0e114d93b3868 | 623,318 |
def fields_allocation(MINUTES=200, size=5):
""" Allocate an empty fields value with "." everywhere
"""
return [
[["." for _ in range(size)] for _ in range(size)]
for _ in range(MINUTES * 2 + 3)
] | 72ff45713994bee184e67f63e381f81ca913ac82 | 623,320 |
def get_task_from_request_form(request):
"""
Parses a request from the API endpoint attempting to extract the JSON information and transform
it on a python dict
Returns
-------
dict
a dictionary obtained from the provided json
Raises
------
ValueError
If a required ... | 1e33639469f7f24103d1f495f8c90b62d3a1af9b | 623,322 |
def format_sentences_BERT(_row,weak_supervision=False):
""" Given dataframe input row, formats input sentence for tokenization:
appends context to each sentence (repeats target word if weak_supervision)
and appends [CLS] and [SEP] tags.
"""
if not weak_supervision:
return '[CLS] '+_row.lo... | d7c14ba0603320af8f74803e4f5683f4dfbc5344 | 623,324 |
import re
def getFuncNames(funcNamesStr):
"""
Gets a list of function names from the string provided, where
the function names are separated by whitespaces or commas.
Arguments:
funcNamesStr:
String of function names.
Returns:
List of function names in the string.
... | 1488f8a1e6cc78c9811d1f479f299c132982f0f1 | 623,326 |
def fix_encoding(training_data):
"""Fix utf-8 file encoding after word2phrase mangles it (happens sometimes).
:param training_data: file containing text with encoding that needs fixing
:return: filename of repaired text file
"""
out_fname = training_data.replace('.txt', '.utf-8.txt')
with open(... | a37fc2428dcc7ada12df221f057c605456a98671 | 623,328 |
def make_cluster_values_adjacent(in_clustering):
"""
Reduces a cluster distribution to one where every cluster number is adjacent to another, starting at 0.
This means that if there are n=10 clusters, every cluster will be guaranteed to be the values 0 to 9.
Parameters
----------
in_clustering ... | 5c465ecf958cb1a87a53a118561da2e9e9c33792 | 623,330 |
def insert (source_str, insert_str, pos):
""" Inserts insert_str at source_str[pos], displacing the rest."""
if pos == 0:
source_str = insert_str + source_str[pos:]
else:
source_str = source_str[:pos] + insert_str + source_str[pos:]
return source_str | c81dddb000bac5d273558f67c42d52a00bc61bff | 623,332 |
def get_alg_shortcode(alg_str):
"""
Get shortcode for the models, passed in as a list of strings
"""
if alg_str == "adahedged":
return "ah"
else:
return alg_str | fb1dd7750d6995058a5a3c8f042d7aeb8033e3bf | 623,333 |
def _get_pdr_module_dict(ps_data, module_id, key_name=None):
"""
Returns the first occurrence of a module entry from PDR participant data for the specified module_id
:param ps_data: A participant data dictionary (assumed to contain a 'modules' key/list of dict values)
:param module_id: The name / ... | 9249ab43e561866aaf4cefe448250925d6d87c76 | 623,335 |
def num_params(model):
"""
Function that outputs the number of total and trainable paramters in the model.
"""
numTotalParams = sum([params.numel() for params in model.parameters()])
numTrainableParams = sum([params.numel() for params in model.parameters() if params.requires_grad])
return numTot... | 83341f50dba4ca5bbb130ba6a11bb66592224c07 | 623,337 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.