content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import pytz
def get_time_zone(time_zone_str):
"""Get time zone from string. Return None if unable to determine."""
try:
return pytz.timezone(time_zone_str)
except pytz.exceptions.UnknownTimeZoneError:
return None | 820794b06728c23c4bd9fbb6a31367a40fc66dfb | 642,846 |
def number_format(number):
"""Formats numbers with thousands separators"""
return u'{:,}'.format(number) | 43880d5bd25d1ba94c5634e423a566568d7fca9a | 642,853 |
def files_exist(files):
"""Check whether all file names in a list are accessible for reading.
"""
for f in files:
with open(f, "r") as fi:
pass
return True | 23941ee752c965526567571cce894399c1e7a42f | 642,854 |
def recall_score_(y_true, y_pred, pos_label=1):
"""
Compute the recall score. The recall score is the ability to detect all
the positive examples.
Args:
y_true: a scalar or a numpy ndarray for the correct labels
y_pred: a scalar or a numpy ndarray for the predicted labels
pos_lab... | 8ccee6f09072cc52a46155702b1a1c04ed2173d9 | 642,857 |
import hashlib
def get_sha1_file( filename ):
"""
This module generates sha1sum for the given file
Args:
filename (str): Full path to the file
Returns:
sha1sum hash of the file
"""
hash_size = 256
sha1 = hashlib.sha1()
with open( filename, 'rb' ) as f:
while Tru... | bc270e386ea658187ba0a16c34097250a996b011 | 642,859 |
def check_keys(in_dict):
"""Checks which keys are present within the input dictionary
This function looks within the input dictionary and checks
which keys are contained within it. Then, with these
keys, it generates a list containing these keys and
returns this list as output.
Parameters
... | e38c1853b2a73a35c5b615e35980e2b6921825a4 | 642,860 |
def kmph_to_mps(kmph):
"""
Transform a value from kilometers-per-hour to meters-per-second
"""
return kmph * 0.277778 | e264cf6c676daca13bfde3e0e9e242c008e3d5aa | 642,862 |
import json
def reconciliation_period_reformat(lst):
"""
Reformat reconciliation period into From [dd/mm/yyyy] to [dd/mm/yyyy] format
"""
try:
lst = json.loads(lst)
except:
lst = []
period = ""
for f_date, t_date in lst:
period += "From " + f_date + " to " + t_d... | d982f1b3b095e9b4015b76fbba28aff6c78afbf6 | 642,870 |
def is_ratelimit(tweet):
"""
Returns True if the "tweet" is a rate-limit response.
If False, then it should be an actual tweet.
Works with raw tweet (as str) or de-JSONified tweet (as dict).
"""
if isinstance(tweet, dict):
# The tweet is a Python dictionary
if 'limit' in tweet... | 15f93ae7e2d2cca90c6c6af5efaed4d4b339c1f3 | 642,874 |
def sumsq(values):
"""
Calculates the sum of squares of a list of values.
"""
return sum(map(lambda x: x ** 2, values)) | a8edcba0f475300bd372f0c6b74f9e2e4eff6ad7 | 642,875 |
def orbreap(orb):
"""Get the next packet from an orb"""
return orb.reap() | 557ad1ac2af84c0c76cf8865ad560d9728803000 | 642,878 |
def _sort_key(item):
"""
Robust sort key that sorts items with invalid keys last.
This is used to make sorting behave the same across Python 2 and 3.
"""
key = item[0]
return not isinstance(key, int), key | 34f716c6e20e0646fd4aeb76650c170143cb3eca | 642,891 |
def prepare_kwargs(raw, string_parameter='name'):
"""
Utility method to convert raw string/diction input into a dictionary to pass
into a function. Always returns a dictionary.
Args:
raw: string or dictionary, string is assumed to be the name of the activation
activation functi... | 656baf750eac6c47a7ef4471c078fd67148c500b | 642,893 |
import ipaddress
def wrap_ipv6(ip_address):
"""Wrap the address in square brackets if it's an IPv6 address."""
if ipaddress.ip_address(ip_address).version == 6:
return '[{}]'.format(ip_address)
return ip_address | c33975f2ebf5deb482dd03d7f95692e61894e9f4 | 642,898 |
def iterate_pagerank(corpus, damping_factor):
"""
Return PageRank values for each page by iteratively updating
PageRank values until convergence.
Return a dictionary where keys are page names, and values are
their estimated PageRank value (a value between 0 and 1). All
PageRank values should su... | a2a9c929a4fbe70a1e4d129f68526481955e4a76 | 642,899 |
def isolate_rightmost_0_bit(n: int) -> int:
"""
Isolate the rightmost 0-bit.
>>> bin(isolate_rightmost_0_bit(0b10000111))
'0b1000'
"""
return ~n & (n + 1) | 1abac335b8570474121bbf307f52f7af2f0c736f | 642,901 |
def is_palindrome(num: int) -> bool:
"""Checks if a number is a palindrome."""
return str(num) == str(num)[::-1] | bb6b271a1fbf77efb08091b625acd0ee932f292d | 642,902 |
import re
def wiki_escape(s):
"""Detect WikiSyntax (i.e. InterCaps, a.k.a. CamelCase) and escape it."""
ret = []
for word in s.split():
if re.match(r"[A-Z]+[a-z]+[A-Z]", word):
word = "!%s" % word
ret.append(word)
return " ".join(ret) | 488cf89b2bc402fdd4eb89d23bb73076cd0f2472 | 642,903 |
def init_method_normalizer(name: str):
"""Normalizes the name of an initialization method."""
return name.lower().replace('_', '').replace('nodeembeddinginitializer', '') | 33178f4de0c01bb754516a68792aebef16fcfb6c | 642,905 |
import random
def mutate_value(value):
"""Randomly doubles or halves a value -- applied at "value" level"""
if random.random() < 0.5:
return value * 2
return value / 2 | e054ca4c8714168667733cef32091d5b65eb6cd0 | 642,909 |
def check_syllable(char):
"""Check whether given character is valid Hangul syllable."""
return 0xAC00 <= ord(char) <= 0xD7A3 | 109dfaa22b5dbff56c1f84fabaa2afa5b1b96141 | 642,911 |
import re
def clean_html(raw_html):
"""Remove HTML tags from a text"""
clean_regex = re.compile('<.*?>')
clean_text = re.sub(clean_regex, '', raw_html)
return clean_text
#def process_column(column_name, dataframe, process):
"""Define a method to apply the same process to every row in a
... | af05b910e5a86bcf881d0f218caf40a738bc98d7 | 642,914 |
def _get_last_nonempty_line(loglines, start_line):
"""Check loglines starting at index start_line and return the number of the last line that is not empty"""
last_line = len(loglines) - 1
for i in range(start_line, len(loglines)):
if len(loglines[i].strip()) == 0:
last_line = i - 1
... | bfdedbe0763b0a6320baee97b1b5ee8ad3c89b5f | 642,923 |
def reverse(s):
"""
Return reverse of 's'.
"""
r = "".join(reversed(s))
return r | e199c0ea220378abebb90fbaf8e3a299531c6a1f | 642,925 |
def format_range(low, high, width):
"""Format a range from low to high inclusively, with a certain width."""
if low == high:
return "%0*d" % (width, low)
else:
return "%0*d-%0*d" % (width, low, width, high) | 59fc9f38967541924e1d74799d655b07884d22fe | 642,926 |
def file_len(fname):
""" Get length of file """
return sum(1 for line in open(fname)) | bec5123bb225b4ee3d204fc1d9233a4bbaa16fc3 | 642,929 |
import math
def estimate_risk(entry_price: float, stop_price: float) -> float:
"""
estimates the risk per share
:param entry_price: float
:param stop_price: float
:return: float
"""
if math.isnan(entry_price) or math.isnan(stop_price):
raise TypeError()
return abs(entry_price... | f2ad204708b55834b70f607789c524598e1caf7e | 642,934 |
import struct
def get_terminated_strings(num, data):
"""Parse space- or *- separated strings of variable length
Parameters
----------
num : int
Number of substrings to be parsed
data : str
4C binary data file
Returns
-------
str
Truncated 4C binary file
li... | c72b1fa901dcfcdd2e817a4637465437f5c6431b | 642,936 |
def font_bold(mystring):
"""
Formats the string as bold, to be used in printouts.
"""
font_bold = "\033[1m"
font_reset = "\033[0;0m"
return font_bold + mystring + font_reset | 09aa81b94a2dd9470500b93b553bc97dc0302522 | 642,941 |
def scale(val, minx, maxx, minscale, maxscale):
""" Scales a value in one range to another. """
# https://stackoverflow.com/a/5295202
return (maxscale - minscale) * (val - minx) / maxx - minx + minscale | 0768fa72421a185aacb2bf78c04326422fb4a470 | 642,942 |
def gsutil_rm_rf_step(url):
"""Returns a GCB step to recursively delete the object with given GCS url."""
step = {
'name': 'gcr.io/cloud-builders/gsutil',
'entrypoint': 'sh',
'args': [
'-c',
'gsutil -m rm -rf %s || exit 0' % url,
],
}
return step | b41a56d2b3e8fd2efa6c46bbb3352d64a6a009d7 | 642,946 |
def find_disjoint_subsequences(li, seq):
"""
Returns a list of tuples (i,j,k,...) so that seq == (li[i], li[j], li[k],...)
Greedily find first tuple, then second, etc.
"""
subseqs = []
cur_subseq_inds = []
for (i_el, el) in enumerate(li):
if el == seq[len(cur_subseq_inds)]:
... | 7599f23042a5fc789e4ce26e444595134c7ad882 | 642,950 |
def average_named_tuple(named_tuple_):
"""Return an averaged named-tuple."""
return type(named_tuple_)(*map(lambda x: x.mean().item(), named_tuple_)) | 3d690814d4b5a7725b846ee29c93cdc3b4e076b4 | 642,951 |
def is_counting_line_passed(point, counting_line, line_orientation):
"""
To check if the point passed the counting line by the x coord if it left/right or y coord if it bottom/top.
:param point: the object location.
:param counting_line: the coordinates list of the area.
:param line_orientation: the... | 2a40fd0db9e2fd3e5c6c16eeb01cd77cd4606f69 | 642,957 |
def amin(a, axis=None, keepdims=False, initial=None, where=True):
"""
Returns the minimum of an array or minimum along an axis.
Note:
Numpy argument `out` is not supported.
On GPU, the supported dtypes are np.float16, and np.float32.
Args:
a (Tensor): Input data.
axis (... | 722eb4483b9cc55bf22db522594a740679a2ca37 | 642,959 |
def sortTable(tSkill):
""" Sort tSkill by decreasing total damage
"""
# Order of the skills by decreasing total damage
gDmgOrder = [ i[0] for i in sorted(enumerate([ float(t) for t in tSkill[2] ]), key = lambda x: x[1], reverse = True) ]
for i in range(len(tSkill)):
tSkill[i] = tSkill[i][gDm... | c62d624590a4cba2af7eb080500f62bf174c81c6 | 642,962 |
def siqs_choose_nf_m(d):
"""Choose parameters nf (sieve of factor base) and m (for sieving
in [-m,m].
"""
# Using similar parameters as msieve-1.52
if d <= 34:
return 200, 272
if d <= 36:
return 300, 546
if d <= 38:
return 400, 1094
if d <= 40:
return 500,... | c22ae4663fd4484622e477c8010bb165dac95808 | 642,965 |
def lookup_relevant(score):
"""Returns the string classifcation of the score"""
category = ""
if score > 2.0:
category = "RELEVANT"
elif score > 0.0:
category = "PARTIALLY RELEVANT"
else:
category = "NOT RELEVANT"
return category | c68f45afd16dfa67afd2415044f33c6187b88c03 | 642,966 |
def factorial(n):
"""
factorial: calculate factorial n!
:param n: input number
:return: n!
"""
fact=1
for i in range(1,n+1):
fact*=i
return fact | 4e99cc2924f5622f426c7f8114adf181ceb5e884 | 642,970 |
def object_id(identifier, keep_version=False) -> str:
"""
Returns the core object_id of a CURIE, with or without the version suffix.
Note: not designed to be used with a URI (will give an invalid outcome)
:param identifier: candidate CURIE identifier for processing
:param keep_version: True if the ... | 95583bb23147d211799ece2009ae9d0dda6de0b1 | 642,973 |
import re
def get_text(file):
"""Read text from a file, normalizing whitespace and stripping HTML markup."""
_text = open(file).read()
_text = re.sub(r'<.*?>', ' ', _text)
_text = re.sub('\s+', ' ', _text)
return _text | 9cc1bb58b2e29163d99d8012dd1206b9229600fa | 642,975 |
def listi(list_, elem, default=None):
"""
Return the elem component in a list of lists, or list of tuples, or list of dicts.
If default is non-None then if the key is missing return that.
Examples:
l = [("A", "B"), ("C", "D")]
listi(l, 1) == ["B", "D"]
l = [{"A":1, "B":2}, {"A"... | ac2866ddfd794a6bf4b02a4d1079963979d3f2d1 | 642,982 |
from typing import Tuple
def find_lines_from_points(
p0: Tuple[float, float],
p1: Tuple[float, float]
) -> Tuple[float, float]:
"""
Function calculating the line passing throught a pair of points.
Args:
p1 (Tuple[float, float]): First point.
p2 (Tuple[float, float]): Second point.... | de1d03a3df52c1007c3ae8cbfc1087197f27d412 | 642,983 |
def create_filename(file_name: str, extension: str) -> str:
"""
Replaces white spaces of the string with '-' and
adds a '.' and the extension to the end.
:param file_name: File name
:param extension: File extension
:return: str Transformed filename
"""
return file_name.replace(' ', '-') ... | 868c8dc3375bd65b13bbb06965e267e36c6fef6e | 642,984 |
def module_fuel(mass):
"""Calculate needed fuel for mass."""
return mass // 3 - 2 | f1070cc0f94f53f7e64a519544aaa60411d1294e | 642,986 |
def compute_set_difference_one(s1, s2):
""" Computes the set difference between s1 and s2 (ie: in s1 but not in s2)
PRE: s1 and s2 differ by one element and thus their set
difference is a single element
:arg s1 (set(T)): super set
:arg s2 (set(T)): subset
:returns (T): the s... | e4a0c1fb07195d6d87252811552d91613d2dbb3d | 642,987 |
import re
def Amatch(tmpl, strn):
"""
Test for AIPS match of string
A "?" matches one of any character, "*" matches any string
all blanks matches anything
Returns True or False
* tmpl = Template string
* strng = String to search for occurance of tmpl
"""
# All blank?
... | b5755be356c25554de899dab1ae4cc2841312f8e | 642,988 |
def distance1(x1, y1, x2, y2):
"""Retourner la "Manhattan distance" entre (x1, y1) et (x2, y2)."""
return abs(x1 - x2) + abs(y1 - y2) | 9bd234940badcedb04ff5313d033d3af4fd27cb5 | 642,990 |
def within_ID(idx, b0, b1):
""" Tests whether an object identifer is within the
remit of the shard bounds. """
return b0 <= idx < b1 | ea1c922f5e6da31f68907d4e404e80aab0ad6746 | 642,991 |
def merge_sort(array):
"""
Sort array in ascending order by merge sort
Merge Sort is a Divide and Conquer algorithm. Conceptually,
a merge sort works as follows:
1. Divide the unsorted list into n sub-lists, each containing
one element (a list of one element is considered sorted).
2. Repe... | 7edd3aa8dd72ef44b6afd7af57041167422b6df1 | 642,992 |
def parse_responsive_length(responsive_length):
"""
Takes a string containing a length definition in pixels or percent and parses it to obtain
a computational length. It returns a tuple where the first element is the length in pixels and
the second element is its length in percent divided by 100.
No... | 220b2c593621bf056d934214a8824fc1f692d702 | 642,993 |
def Pack(flatten, nmap_list):
"""Packs the list of tensors according to `.NestedMap` in `nmap_list`.
`Pack` is loosely the inverse of `Flatten`.
Args:
flatten: A list of tensors.
nmap_list: A list of `.NestedMap`.
Returns:
A list of `.NestedMap`, say ret is the returned list. We have
1. le... | 4c0caff454f269dc91715d4dbd8a9a35fafabf86 | 642,994 |
def ptime(s: float) -> str:
"""
Pretty print a time in the format H:M:S.ms. Empty leading fields are
disgarded with the exception of times under 60 seconds which show 0
minutes.
>>> ptime(234.2)
'3:54.200'
>>> ptime(23275.24)
'6:27:55.240'
>>> ptime(51)
'0:51'
>>> ptime(325)
'5:25'
"""
h: float
m: float... | d669ed4856d1cf7777ecfc84890f85ccee549e5c | 642,995 |
def knot_vector_uniform(num_points, degree, periodic=False):
"""Computes a uniform knot vector.
Parameters
----------
num_points : int
Number of points to compute parameters for.
degree : int
The degree of the curve.
Returns
-------
list of float
The knot vector... | e053765c7142b60a6d4b8b162f2314e7af3ce373 | 642,996 |
def stream_hashsum(ioobj, hasher, blocksize=65536):
"""Generate a hash sum from a filelike object using the supplied hashlib algorithm.
Example:
stream_hashsum(open('foobar.txt','rb'), hashlib.md5())
"""
while True:
block = ioobj.read(blocksize)
if len(block) > 0:
... | 95f7203992da8cb12454149456cf961c1d90508a | 642,998 |
import requests
def _fetch_seq_ensembl(ac, start_i=None, end_i=None):
"""Fetch sequence slice from Ensembl public REST interface.
Args:
ac (str): The accession of the sequence to fetch.
start_i (int, optional): The start index (interbase coordinates) of the subsequence to fetch.
D... | 407aeacd78826d13dc4634c0758baeb9f7cb4066 | 642,999 |
def non_valid_devs(host):
"""Inventory Filter for Nornir for all non-valid devices.
Return True or False if a device is not valid
Args:
host(Host): Nornir Host
Returns:
bool: True if the device do not have a config, False otherwise.
"""
if host.data["has_config"]:
return... | 020b7184d138357e169f0ac19b7e0d0f7ac56f73 | 643,001 |
import requests
def get_ics(url):
"""
Gets the ICS file residing at the given url.
:param url: the url from which to download the ics file
:type url: str
:return: string containing the ical file contents
"""
req = requests.get(url)
assert req.ok, "Failed to download the file"
retur... | a723757c39d8ecb5c40ce35d06d9bfb6a039bca2 | 643,002 |
def add_units(metric_name):
"""
Given a metric name, it adds the units according to its input.
Parameters
----------
metric_name : str
The name of the metric where the units will be added
Returns
-------
label : str
The new label of the metric containing the units that
... | 03ab1407fcae8c410741e9e9fb90536e6b1c444f | 643,003 |
import re
def pathsplit(p):
"""Split a path into a WebDataset prefix and suffix.
The prefix is used for grouping files into samples,
the suffix is used as key in the output dictionary.
The suffix consists of all components after the last
"." in the filename.
In torchdata, the prefix consists... | 2d667230d330f1e36bad80ff3be4ded695319a8c | 643,004 |
def get_distance(particle):
"""Get Manhattan distance of particle."""
return sum(abs(num) for num in particle['position']) | 15d4d513d7ce61b25d247c2960df5817db3a5efc | 643,005 |
def color565(red, green=0, blue=0):
"""
Convert red, green and blue values (0-255) into a 16-bit 565 encoding.
"""
try:
red, green, blue = red # see if the first var is a tuple/list
except TypeError:
pass
return (red & 0xf8) << 8 | (green & 0xfc) << 3 | blue >> 3 | 4c1f2c28313c35f839fa189b45fb15abfa715cd1 | 643,010 |
def is_url(url):
"""test for HTTP and HTTPS protocol in the string"""
if len(url) > 6 and (url[0:7] == "http://" or url[0:8] == "https://"):
return True
else:
return False | d2e9c27087455b78c44b63d5f5b93955d949043a | 643,011 |
import re
def replace_location(match: re.Match, location: str) -> str:
"""Replace location data in the warning string."""
text = match.string
start, end = match.span(2)
return text[:start] + location + text[end:] | 1260b7d42af59222bb2cc0be17f8349200f6c938 | 643,013 |
def q_learn(old_state_action_q_value, new_state_max_q_value, reward, learn_rate=0.01, discount_factor=0.9):
"""
Returns updated state-action Q_value.
:param old_state_action_q_value: Q_value of the chosen action in the previous state.
:param new_state_max_q_value: maximum Q_value of new state.
:para... | cfe2f70823dff79b43a426b2f9e0996ac5e507c1 | 643,016 |
def stripLabels(testFeatures):
"""
Strips label from a test sentence feature vector
"""
return [testFeatures[i][0] for i in range(len(testFeatures))] | 24308c4e3fb0d56256b77fe0310381d8017f41ee | 643,023 |
def find_pair_in_hits(
hits,
pair,
max_separation = None,
separation = None
):
"""Finds the locations where a pair of TFs bind in a sequence of hits
hits: The hits
pair: A tuple ( binder1, binder2, orientation1, orientation2 )
max_separation: If specified determines maxi... | bdefe55fdabff9c120b8b502e85e74abcb8ce851 | 643,025 |
import random
def make_act_type_data(act_tp):
"""
随机生成账号等级,提高高级别账号权重
:param act_tp: 账号类型
:return: 随机账号类别标识码,高级别账号权重较大
"""
if act_tp == "11":
act_typ = random.choice(["3", "3", "3", "2", "2", "1"])
elif act_tp == "211":
act_typ = random.choice(["1", "1", "1", "2", "2", "3"])... | 954a5e41665f9f06cf55e019be2391162c23955e | 643,027 |
def XCOMmaterial(massdic):
"""
Function to convert the mass percentages into XCOM readable input string
Parameters
----------
massdic : dict
Dictionary which stores the mass percentage for each element (which are the keys).
Returns
-------
xcomstr : str
String w... | 4fef10fe2d720c0ede53181d89e5ac26be36c56d | 643,028 |
from pathlib import Path
from typing import Tuple
def get_num_neutrinos(fpath: Path) -> Tuple[int, int]:
"""Get the number of neutrinos (both electrons and muons) from the MiniBooNE data text file
Args:
fpath: path to the text file
Returns:
Tuple of (num_electron, num_muon)
"""
... | 43df3017f2011b2d635dab937533b72948c440fa | 643,030 |
def factorial(num):
"""
Find the factorial of a number
:type num: integer
:param num: The number to find the factorial for.
>>> factorial(4)
24
"""
if num == 0:
return 1
return num * factorial(num - 1) | 1454262fc21e05d294e91aa3fba9182d4d23521d | 643,033 |
def empty_config_file(tmpdir):
"""produce an empty config file
Returns:
tuple -- Tuple containing following:
1. Path to an empty config file
2. A blank dictionary
"""
cfg = tmpdir.join('empty-config.yaml')
cfg.write('')
emptydict = {}
return (... | 2a215989997878b4b6165ad21fb9dcfbf962b8d7 | 643,036 |
def feature_test_qual_value(feature, **kwargs):
"""Test qualifier values.
For every feature, check that at least one value in
feature.quailfiers(kwargs['qualifier']) is in kwargs['attribute_list']
"""
for attribute_value in feature.qualifiers.get(kwargs['qualifier'], []):
if attribute_value... | 55fb2b354a9bc8d579ce0dc0f0e241ebd6159ad4 | 643,037 |
def gen_State(drone_id, battery, direction, position, status, speed):
"""Generate a State objects."""
state = {
"@type": "State",
"DroneID": drone_id,
"Battery": battery,
"Direction": direction,
"Position": position,
"Status": status,
"Speed": speed,
}... | 1a6a5e0ab629c3f6ffb4d627b7cce414476bfe59 | 643,046 |
import pickle
def predictSVM(X_test):
"""This function takes a dataset and predict the letter for each data point.
Parameters
----------
dataset: M X 128 numpy array
A dataset represented by numpy-array
Returns
-------
M x 1 numpy array
Returns a numpy array of letter that each data point represents
"""... | ce9f58301fbfdf242356b74b0c19743932d44c3b | 643,047 |
import json
def build_trace_dict(f, start_time, end_time):
"""Creates a python dictionary that has trace ids as keys and the
corresponding trace objects as values.
Input: python file object that points to a file with traces, written by
htrace-c's local file span receiver.
The exact format shouldn... | 4171feeebddf2554ed052616a76f3c25b816b945 | 643,054 |
from typing import Union
from typing import List
def check_filetype(estimated_filetype: str, allowed_types: Union[str, List[str]]) -> bool:
"""
Check if a file has an expected filetype.
param: estimated_filetype: The filetype that was estimated by magic.
param: allowed_types: A string or a list of st... | 344cf29a41faadb7dd1f9131bc1cb57c12e92a6a | 643,055 |
import torch
def correct(output, target, topk=(1,)):
"""Computes how many correct outputs with respect to targets
Does NOT compute accuracy but just a raw amount of correct
outputs given target labels. This is done for each value in
topk. A value is considered correct if target is in the topk
hig... | 8608bc5f555bdde96a021347fd32a1f0179b03cf | 643,059 |
def qs_opt_eq(qs, opt, value):
"""
Returns True if the query string option is equal to value.
"""
for opt_value in qs.get(opt, []):
if opt_value == value:
return True | 68dede185a9b1aa62e32a833db4b395ce6c4b1cd | 643,060 |
def all_input_tagged_nodes(
graph):
"""Gets all input-tagged nodes that are reachable in a graph.
An input-tagged node is considered reachable if there is a way to get to that
node by an edge of that input type.
Output will be ordered lexicographically, first by the node ordering in the
input graph's ke... | 0ac3956a3b3481f99f6461d3cda0bfc31f7ba466 | 643,066 |
import xml
def is_document_related(err):
"""Returns True for expat errors related to errors in the
document, which should not be reported as internal errors.
"""
errors = xml.parsers.expat.errors
err_str = xml.parsers.expat.ErrorString(err.code)
# All errors in the expat.errors-module in Pyt... | e435da14a7d8da0e923436260fe7aa7e0e0eb427 | 643,067 |
def get_blueprints(app):
"""Returns blueprints dict."""
return app.blueprints | 1cadcaca442d6f46f97d88aa4ac516defaf8f09f | 643,069 |
def int_from_digits(digits):
"""
Returns a positive integer ``n`` which is a decimal expansion of a
sequence of digits in descending order from the most significant
digit. The input can be a sequence (list, tuple) or a generator,
e.g.
::
[1,2,3] -> 1x10^2 + 2x10^1 + 3x10^0 = ... | 16f01a0dcd9be0b44680bc3fb503790bce848f95 | 643,073 |
def filter_valid_tournaments(df):
"""Filter for valid tournaments
Notes:
Excluding Tour championship for 2019 and 2020
due to rule change in score totals.
Args:
df (pd.DataFrame) : espn tournaments
Returns:
valid_df (pd.Dataframe) : valid espn tournaments
"""
... | b0251b557b7ee8f2d04109d84a392ac108b9a736 | 643,076 |
def global_dependencies(context):
"""
Dependencies that are loaded for all tethys gizmos (after gizmo dependencies).
"""
return('tethys_gizmos/css/tethys_gizmos.css',
'tethys_gizmos/js/tethys_gizmos.js') | 038b050a6ddbfeea3dd6208e34d08e80de8e3208 | 643,078 |
def subtract(x,y):
"""Subtract x from y and return value"""
return y-x | 708c3de6a50e7ca2fd08722133d901b79d8bac15 | 643,079 |
def calculate_points(prediction, outcome):
"""
Adjusted version of the Brier scoring function, as described at
https://fivethirtyeight.com/features/how-to-play-our-nfl-predictions-game/
"""
diff = (prediction / 100) - outcome
brier_score = diff ** 2
adjusted_score = -(brier_score - 0.25) * 2... | 575ff070100297cb7337951d48a3fc045bc18784 | 643,081 |
import functools
def rget(dict_obj, attrpath):
"""
A fancy version of `get` that allows getting dot-separated nested attributes
like `license.license_name` for use in tree comparisons attribute mappings.
This code is inspired by solution in https://stackoverflow.com/a/31174427.
"""
def _getnoe... | 67e623d8e457fe90787e18e604ef019c98918aad | 643,082 |
def integer_to_octet_string_primitive(length: int, integer: int) -> bytes:
"""Convert a nonnegative integer to an octet string."""
# https://tools.ietf.org/html/rfc8017#section-4.1
if integer >= 256 ** length:
raise ValueError(f"{integer} >= 256 ** {length}")
index = 0
digits = [0] * length
... | fca6962ff5b5208313e4bfd1d23bee626b998c7a | 643,083 |
def check_inorganic(struct):
"""
Checks if the structure contains inorganic atoms.
"""
ele = struct.geometry["element"]
metals = ['Ag', 'Al', 'As', 'Au', 'Ba', 'Be', 'Bi', 'Ca',
'Cd', 'Ce', 'Co', 'Cr', 'Cu', 'Dy', 'Er', 'Eu', 'Fe',
'Ga', 'Gd', 'Ge', 'Hf', 'Hg', 'Ho',... | 2864990a1d0c41429d663be0d56b4bdc308af74d | 643,084 |
def _errorr_input(endfin, pendfin, errorrout, mat,
ign=2, iwt=2, temp=293.6, iprint=False,
**kwargs):
"""Write acer input for fast data.
Parameters
----------
endfin : `int`
tape number for input ENDF-6 file
pendfin : `int`
tape number for inp... | 0fb45c33f3a63908dd1548d6974a498d42779659 | 643,086 |
import itertools
def sequence(start=0, step=1):
""":yaql:sequence
Returns an iterator to the sequence beginning from start with step.
:signature: sequence(start => 0, step => 1)
:arg start: start value of the sequence. 0 is value by default
:argType start: integer
:arg step: the next element... | 477cffac33412b0e09ab6ebcd7332cd8fe8061de | 643,089 |
import torch
def hermitify(kern, dim):
"""Enforce Hermitian symmetry.
This function takes an approximately Hermitian-symmetric kernel and
enforces Hermitian symmetry by calcualting a tensor that reverses the
coordinates and conjugates the original, then averaging that tensor with
the original.
... | 362a488b5ee94b1ac26f10932be8d423b00b4cd2 | 643,090 |
import re
def namespace_for_username(username: str) -> str:
"""
Get the Kubernetes namespace for a JupyterHub user.
Not all JupyterHub usernames are validate kubernetes namespaces, so we have to
# translate it somehow. This replaces lowercases the input and replaces
non-ascii alphanumeric charact... | e1b50b3e93705ee81aa5a99ea517207dfdc1bcca | 643,093 |
def isoformat(dt):
"""Return iso-formatted timestamp
Like .isoformat(), but uses Z for UTC instead of +00:00
"""
return dt.isoformat().replace('+00:00', 'Z') | 0184465e113093d535e335fabe92067da99d4338 | 643,095 |
def get_remote_orders(connection):
"""Returns orders from a remote player.
Parameters
----------
connection: sockets to receive/send orders (tuple)
Returns
----------
player_orders: orders given by remote player (str)
Raises
------
IOError: if remote player cannot be r... | d23c3a002e5a39ef1b9549d0dce20097bb8f52c3 | 643,097 |
def get_dx(p0, p1, smooth_line, cl_id, id_end, id_mid, id_start):
"""Get the displacement for the Voronoi point
Args:
p0 (ndarray): Point i on the old centerline.
p1 (ndarray): Point i on the new centerline.
smooth_line (bool): Turn on/off increasing curvuature.
cl_id (int): ID ... | 2dab59d1d7f28a87b63af95dbff222b4f406c19f | 643,100 |
def has_outputfile(records: dict) -> list:
""" Convenience function for finding output files in a dictionary of records"""
keys, has_outputs = [], []
# check to see which records have outputfiles
for key, record in records.items():
keys.append(key)
has_outputs.append(record['output'] is ... | d6716d4bd33029fd857abfdb590480d3659af354 | 643,101 |
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 No... | 574019f671d389f2dbf876156796266c57e9d550 | 643,103 |
def modes(nums):
"""Returns the most frequently occurring items in the given list, nums"""
if len(nums) == 0:
return []
# Create a dictionary of numbers to how many times they occur in the list
frequencies = {}
for num in nums:
frequencies[num] = 1 + frequencies.get(num, 0)
# How... | 014f4833d917e55f2d7e9909c1356e9620441283 | 643,108 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.