content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def Total_Delims(str):
"""
Function to calculate the Total Number of Delimeters in a URL
"""
delim=['-','_','?','=','&']
count=0
for i in str:
for j in delim:
if i==j:
count+=1
return count | 1a25e74eb3d66078c321da0915f968bb6e26f74a | 122,381 |
def dice_coefficient(string1, string2):
""" Returns the similarity between string1 and string1 as a number between 0.0 and 1.0,
based on the number of shared bigrams, e.g., "night" and "nacht" have one common bigram "ht".
"""
def bigrams(s):
return set(s[i:i+2] for i in range(len(s)-1))
nx = bigrams(string1)
ny = bigrams(string2)
nt = nx.intersection(ny)
return 2.0 * len(nt) / ((len(nx) + len(ny)) or 1) | d4087c63b2225b6996d10b97f96831c858da84c2 | 122,384 |
def get_min_delta_mags(model):
"""Second smallest value minus smallest value of fitted Lomb Scargle model."""
return model['min_delta_mags'] | cf7baa56ec4ebf769920f2b37c93628953e4e71a | 122,385 |
def isqrt(n: int) -> int:
"""
ref: https://en.wikipedia.org/wiki/Integer_square_root
>>> isqrt(289)
17
>>> isqrt(2)
1
>>> isqrt(1000000 ** 2)
1000000
"""
if n == 0:
return 0
# ref: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Rough_estimation
x = 2 ** ((n.bit_length() + 1) // 2)
while True:
y = (x + n // x) // 2
if y >= x:
return x
x = y | 1d62cd172ff537ad9eef90c76334cd7c25bc3882 | 122,387 |
def percent(count, total): #-------------------------------------------------<<<
"""Return a percent value, or 0 if undefined.
Arguments may float, int, or str.
"""
if not count or not total:
return 0
return 100 * float(count) / float(total) | 06805a4622db36d019df711df250e3e14e8cebf0 | 122,391 |
def parse_int(text: str) -> int:
"""
Small postprocessing task to parse a string to an int.
"""
return int(text.strip()) | 060b22b8d88ef07622b14d200f8062a954635f17 | 122,392 |
import re
def remove_html(text):
"""Given string, remove html by regex."""
html=re.compile(r'<.*?>')
return html.sub(r'',text) | e36551ee63914116bc787b992cfba83ce6887f90 | 122,395 |
import six
def canonicalize_unimodalities(unimodalities):
"""Converts string constants representing unimodalities into integers.
Args:
unimodalities: unimodalities hyperparameter of `tfl.layers.Lattice` layer.
Returns:
A list of unimodalities represented as -1, 0, 1, or the value None if
unimodalities is None.
Raises:
ValueError: If one of unimodalities is not in the set
{-1, 0, 1, 'peak', 'none', 'valley'}.
"""
if not unimodalities:
return None
canonicalized = []
for unimodality in unimodalities:
if unimodality in [-1, 0, 1]:
canonicalized.append(unimodality)
elif isinstance(unimodality,
six.string_types) and unimodality.lower() == "peak":
canonicalized.append(-1)
elif isinstance(unimodality,
six.string_types) and unimodality.lower() == "none":
canonicalized.append(0)
elif isinstance(unimodality,
six.string_types) and unimodality.lower() == "valley":
canonicalized.append(1)
else:
raise ValueError(
"'unimodalities' elements must be from: [-1, 0, 1, 'peak', 'none', "
"'valley']. Given: {}".format(unimodalities))
return canonicalized | 35d6edc15b0dd7a2e8fcd3426c63444c11a5c854 | 122,396 |
def breakdown_df_shapes(global_tp, global_tn, global_fp, global_fn, col, val):
"""
Counts tp, fp, fn, tn on a subset
:param global_tp: Dataframe with all true_positives
:param global_tn: Dataframe with all true_negatives
:param global_fp: Dataframe with all false_positives
:param global_fn: Dataframe with all false_negatives
:param col: Candidate column
:param val: Value of the column
:return: tuple of of (tp, fp, fn, tn) computed on the subset
"""
return (global_tp[global_tp[col] == val].shape[0],
global_tn[global_tn[col] == val].shape[0],
global_fp[global_fp[col] == val].shape[0],
global_fn[global_fn[col] == val].shape[0]) | bd7376564e2b25ac97ede086294203a17a3a13eb | 122,400 |
def selection_sort(a: list) -> list:
"""Given a list of element it's return sorted list of O(n^2) complexity"""
a = a.copy()
n = len(a)
for i in range(n):
mni = i
for j in range(i+1, n):
if a[j] < a[mni]:
mni = j
a[i], a[mni] = a[mni], a[i]
return a | f1953069b98810a6121e9ea1c51833fcd2b0fe1f | 122,402 |
from typing import List
def parse_clist(s: str) -> List[int]:
"""
Parse commented station list
" 722(Brocken),5792(Zugspitze), 3987 (Potsdam) " -> [722, 5792, 3987]
:param s:
:return:
"""
stations = []
parts = s.split(",")
for part in parts:
if "(" in part:
stations.append(int(part[:part.index("(")].strip()))
else:
stations.append(int(part.strip()))
return stations | 10fb1afb013ee4209623c2522f8973d6151509e0 | 122,406 |
def pointgroup_has_inversion(number):
"""
Return True if the pointgroup with given number has inversion,
False otherwise.
:param number: The integer number of the pointgroup, from 1 to 32.
"""
if number in [2, 5, 8, 11, 15, 17, 20, 23, 27, 29, 32]:
return True
if number in [
1,
3,
4,
6,
7,
9,
10,
12,
13,
14,
16,
18,
19,
21,
22,
24,
25,
26,
28,
30,
31,
]:
return False
raise ValueError("number should be between 1 and 32") | bdd1c56b3af187714705b1ffd3eeb9a31c6f0b15 | 122,407 |
def _read_file(filepath):
""" Returns all content of a textfile as a single string.
:param str filepath: filepath of file to read contents from
:return: contents of file with given filepath
:rtype: str
"""
with open(filepath, "r") as f:
s = f.read()
return s | d545defac682a2f718de283df0687741e84ffd0b | 122,408 |
import ast
from typing import Dict
def _get_keyword_args_by_names(
call: ast.Call,
*names: str,
) -> Dict[str, ast.expr]:
"""Returns keywords of ``call`` by specified ``names``."""
keyword_args = {}
for keyword in call.keywords:
if keyword.arg in names:
keyword_args[keyword.arg] = keyword.value
return keyword_args | 98c2954bc0aefb933356760f8b0a36629bb07e71 | 122,409 |
def ccalc_viridis(x, rgbmax):
"""viridis colour map"""
r = [0.26700401, 0.26851048, 0.26994384, 0.27130489, 0.27259384, 0.27380934, 0.27495242, 0.27602238, 0.2770184, 0.27794143, 0.27879067, 0.2795655, 0.28026658, 0.28089358, 0.28144581, 0.28192358, 0.28232739, 0.28265633, 0.28291049, 0.28309095, 0.28319704, 0.28322882, 0.28318684, 0.283072, 0.28288389, 0.28262297, 0.28229037, 0.28188676, 0.28141228, 0.28086773, 0.28025468, 0.27957399, 0.27882618, 0.27801236, 0.27713437, 0.27619376, 0.27519116, 0.27412802, 0.27300596, 0.27182812, 0.27059473, 0.26930756, 0.26796846, 0.26657984, 0.2651445, 0.2636632, 0.26213801, 0.26057103, 0.25896451, 0.25732244, 0.25564519, 0.25393498, 0.25219404, 0.25042462, 0.24862899, 0.2468114, 0.24497208, 0.24311324, 0.24123708, 0.23934575, 0.23744138, 0.23552606, 0.23360277, 0.2316735, 0.22973926, 0.22780192, 0.2258633, 0.22392515, 0.22198915, 0.22005691, 0.21812995, 0.21620971, 0.21429757, 0.21239477, 0.2105031, 0.20862342, 0.20675628, 0.20490257, 0.20306309, 0.20123854, 0.1994295, 0.1976365, 0.19585993, 0.19410009, 0.19235719, 0.19063135, 0.18892259, 0.18723083, 0.18555593, 0.18389763, 0.18225561, 0.18062949, 0.17901879, 0.17742298, 0.17584148, 0.17427363, 0.17271876, 0.17117615, 0.16964573, 0.16812641, 0.1666171, 0.16511703, 0.16362543, 0.16214155, 0.16066467, 0.15919413, 0.15772933, 0.15626973, 0.15481488, 0.15336445, 0.1519182, 0.15047605, 0.14903918, 0.14760731, 0.14618026, 0.14475863, 0.14334327, 0.14193527, 0.14053599, 0.13914708, 0.13777048, 0.1364085, 0.13506561, 0.13374299, 0.13244401, 0.13117249, 0.1299327, 0.12872938, 0.12756771, 0.12645338, 0.12539383, 0.12439474, 0.12346281, 0.12260562, 0.12183122, 0.12114807, 0.12056501, 0.12009154, 0.11973756, 0.11951163, 0.11942341, 0.11948255, 0.11969858, 0.12008079, 0.12063824, 0.12137972, 0.12231244, 0.12344358, 0.12477953, 0.12632581, 0.12808703, 0.13006688, 0.13226797, 0.13469183, 0.13733921, 0.14020991, 0.14330291, 0.1466164, 0.15014782, 0.15389405, 0.15785146, 0.16201598, 0.1663832, 0.1709484, 0.17570671, 0.18065314, 0.18578266, 0.19109018, 0.19657063, 0.20221902, 0.20803045, 0.21400015, 0.22012381, 0.2263969, 0.23281498, 0.2393739, 0.24606968, 0.25289851, 0.25985676, 0.26694127, 0.27414922, 0.28147681, 0.28892102, 0.29647899, 0.30414796, 0.31192534, 0.3198086, 0.3277958, 0.33588539, 0.34407411, 0.35235985, 0.36074053, 0.3692142, 0.37777892, 0.38643282, 0.39517408, 0.40400101, 0.4129135, 0.42190813, 0.43098317, 0.44013691, 0.44936763, 0.45867362, 0.46805314, 0.47750446, 0.4870258, 0.49661536, 0.5062713, 0.51599182, 0.52577622, 0.5356211, 0.5455244, 0.55548397, 0.5654976, 0.57556297, 0.58567772, 0.59583934, 0.60604528, 0.61629283, 0.62657923, 0.63690157, 0.64725685, 0.65764197, 0.66805369, 0.67848868, 0.68894351, 0.69941463, 0.70989842, 0.72039115, 0.73088902, 0.74138803, 0.75188414, 0.76237342, 0.77285183, 0.78331535, 0.79375994, 0.80418159, 0.81457634, 0.82494028, 0.83526959, 0.84556056, 0.8558096, 0.86601325, 0.87616824, 0.88627146, 0.89632002, 0.90631121, 0.91624212, 0.92610579, 0.93590444, 0.94563626, 0.95529972, 0.96489353, 0.97441665, 0.98386829, 0.99324789]
g = [0.00487433, 0.00960483, 0.01462494, 0.01994186, 0.02556309, 0.03149748, 0.03775181, 0.04416723, 0.05034437, 0.05632444, 0.06214536, 0.06783587, 0.07341724, 0.07890703, 0.0843197, 0.08966622, 0.09495545, 0.10019576, 0.10539345, 0.11055307, 0.11567966, 0.12077701, 0.12584799, 0.13089477, 0.13592005, 0.14092556, 0.14591233, 0.15088147, 0.15583425, 0.16077132, 0.16569272, 0.17059884, 0.1754902, 0.18036684, 0.18522836, 0.19007447, 0.1949054, 0.19972086, 0.20452049, 0.20930306, 0.21406899, 0.21881782, 0.22354911, 0.2282621, 0.23295593, 0.23763078, 0.24228619, 0.2469217, 0.25153685, 0.2561304, 0.26070284, 0.26525384, 0.26978306, 0.27429024, 0.27877509, 0.28323662, 0.28767547, 0.29209154, 0.29648471, 0.30085494, 0.30520222, 0.30952657, 0.31382773, 0.3181058, 0.32236127, 0.32659432, 0.33080515, 0.334994, 0.33916114, 0.34330688, 0.34743154, 0.35153548, 0.35561907, 0.35968273, 0.36372671, 0.36775151, 0.37175775, 0.37574589, 0.37971644, 0.38366989, 0.38760678, 0.39152762, 0.39543297, 0.39932336, 0.40319934, 0.40706148, 0.41091033, 0.41474645, 0.4185704, 0.42238275, 0.42618405, 0.42997486, 0.43375572, 0.4375272, 0.44128981, 0.4450441, 0.4487906, 0.4525298, 0.45626209, 0.45998802, 0.46370813, 0.4674229, 0.47113278, 0.47483821, 0.47853961, 0.4822374, 0.48593197, 0.4896237, 0.49331293, 0.49700003, 0.50068529, 0.50436904, 0.50805136, 0.51173263, 0.51541316, 0.51909319, 0.52277292, 0.52645254, 0.53013219, 0.53381201, 0.53749213, 0.54117264, 0.54485335, 0.54853458, 0.55221637, 0.55589872, 0.55958162, 0.56326503, 0.56694891, 0.57063316, 0.57431754, 0.57800205, 0.58168661, 0.58537105, 0.58905521, 0.59273889, 0.59642187, 0.60010387, 0.60378459, 0.60746388, 0.61114146, 0.61481702, 0.61849025, 0.62216081, 0.62582833, 0.62949242, 0.63315277, 0.63680899, 0.64046069, 0.64410744, 0.64774881, 0.65138436, 0.65501363, 0.65863619, 0.66225157, 0.66585927, 0.66945881, 0.67304968, 0.67663139, 0.68020343, 0.68376525, 0.68731632, 0.69085611, 0.69438405, 0.6978996, 0.70140222, 0.70489133, 0.70836635, 0.71182668, 0.71527175, 0.71870095, 0.72211371, 0.72550945, 0.72888753, 0.73224735, 0.73558828, 0.73890972, 0.74221104, 0.74549162, 0.74875084, 0.75198807, 0.75520266, 0.75839399, 0.76156142, 0.76470433, 0.76782207, 0.77091403, 0.77397953, 0.7770179, 0.78002855, 0.78301086, 0.78596419, 0.78888793, 0.79178146, 0.79464415, 0.79747541, 0.80027461, 0.80304099, 0.80577412, 0.80847343, 0.81113836, 0.81376835, 0.81636288, 0.81892143, 0.82144351, 0.82392862, 0.82637633, 0.82878621, 0.83115784, 0.83349064, 0.83578452, 0.83803918, 0.84025437, 0.8424299, 0.84456561, 0.84666139, 0.84871722, 0.8507331, 0.85270912, 0.85464543, 0.85654226, 0.85839991, 0.86021878, 0.86199932, 0.86374211, 0.86544779, 0.86711711, 0.86875092, 0.87035015, 0.87191584, 0.87344918, 0.87495143, 0.87642392, 0.87786808, 0.87928545, 0.88067763, 0.88204632, 0.88339329, 0.88472036, 0.88602943, 0.88732243, 0.88860134, 0.88986815, 0.89112487, 0.89237353, 0.89361614, 0.89485467, 0.89609127, 0.89732977, 0.8985704, 0.899815, 0.90106534, 0.90232311, 0.90358991, 0.90486726, 0.90615657]
b = [0.32941519, 0.33542652, 0.34137895, 0.34726862, 0.35309303, 0.35885256, 0.36454323, 0.37016418, 0.37571452, 0.38119074, 0.38659204, 0.39191723, 0.39716349, 0.40232944, 0.40741404, 0.41241521, 0.41733086, 0.42216032, 0.42690202, 0.43155375, 0.43611482, 0.44058404, 0.44496, 0.44924127, 0.45342734, 0.45751726, 0.46150995, 0.46540474, 0.46920128, 0.47289909, 0.47649762, 0.47999675, 0.48339654, 0.48669702, 0.48989831, 0.49300074, 0.49600488, 0.49891131, 0.50172076, 0.50443413, 0.50705243, 0.50957678, 0.5120084, 0.5143487, 0.5165993, 0.51876163, 0.52083736, 0.52282822, 0.52473609, 0.52656332, 0.52831152, 0.52998273, 0.53157905, 0.53310261, 0.53455561, 0.53594093, 0.53726018, 0.53851561, 0.53970946, 0.54084398, 0.5419214, 0.54294396, 0.54391424, 0.54483444, 0.54570633, 0.546532, 0.54731353, 0.54805291, 0.54875211, 0.54941304, 0.55003755, 0.55062743, 0.5511844, 0.55171011, 0.55220646, 0.55267486, 0.55311653, 0.55353282, 0.55392505, 0.55429441, 0.55464205, 0.55496905, 0.55527637, 0.55556494, 0.55583559, 0.55608907, 0.55632606, 0.55654717, 0.55675292, 0.55694377, 0.5571201, 0.55728221, 0.55743035, 0.55756466, 0.55768526, 0.55779216, 0.55788532, 0.55796464, 0.55803034, 0.55808199, 0.55811913, 0.55814141, 0.55814842, 0.55813967, 0.55811466, 0.5580728, 0.55801347, 0.557936, 0.55783967, 0.55772371, 0.55758733, 0.55742968, 0.5572505, 0.55704861, 0.55682271, 0.55657181, 0.55629491, 0.55599097, 0.55565893, 0.55529773, 0.55490625, 0.55448339, 0.55402906, 0.55354108, 0.55301828, 0.55245948, 0.55186354, 0.55122927, 0.55055551, 0.5498411, 0.54908564, 0.5482874, 0.54744498, 0.54655722, 0.54562298, 0.54464114, 0.54361058, 0.54253043, 0.54139999, 0.54021751, 0.53898192, 0.53769219, 0.53634733, 0.53494633, 0.53348834, 0.53197275, 0.53039808, 0.52876343, 0.52706792, 0.52531069, 0.52349092, 0.52160791, 0.51966086, 0.5176488, 0.51557101, 0.5134268, 0.51121549, 0.50893644, 0.5065889, 0.50417217, 0.50168574, 0.49912906, 0.49650163, 0.49380294, 0.49103252, 0.48818938, 0.48527326, 0.48228395, 0.47922108, 0.47608431, 0.4728733, 0.46958774, 0.46622638, 0.46278934, 0.45927675, 0.45568838, 0.45202405, 0.44828355, 0.44446673, 0.44057284, 0.4366009, 0.43255207, 0.42842626, 0.42422341, 0.41994346, 0.41558638, 0.41115215, 0.40664011, 0.40204917, 0.39738103, 0.39263579, 0.38781353, 0.38291438, 0.3779385, 0.37288606, 0.36775726, 0.36255223, 0.35726893, 0.35191009, 0.34647607, 0.3409673, 0.33538426, 0.32972749, 0.32399761, 0.31819529, 0.31232133, 0.30637661, 0.30036211, 0.29427888, 0.2881265, 0.28190832, 0.27562602, 0.26928147, 0.26287683, 0.25641457, 0.24989748, 0.24332878, 0.23671214, 0.23005179, 0.22335258, 0.21662012, 0.20986086, 0.20308229, 0.19629307, 0.18950326, 0.18272455, 0.17597055, 0.16925712, 0.16260273, 0.15602894, 0.14956101, 0.14322828, 0.13706449, 0.13110864, 0.12540538, 0.12000532, 0.11496505, 0.11034678, 0.10621724, 0.1026459, 0.09970219, 0.09745186, 0.09595277, 0.09525046, 0.09537439, 0.09633538, 0.09812496, 0.1007168, 0.10407067, 0.10813094, 0.11283773, 0.11812832, 0.12394051, 0.13021494, 0.13689671, 0.1439362]
i = int(round(x * 255, 0))
return [r[i]*rgbmax, g[i]*rgbmax, b[i]*rgbmax] | 88a1a135c3f398d33bc8f5b3a56520ea8461c373 | 122,412 |
import requests
def my_requests_request(method, url, **kwargs):
"""
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
to add for the file.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send data
before giving up, as a float, or a :ref:`(connect timeout, read
timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return requests.request(method=method, url=url, timeout=10, **kwargs) | 8f86acea82c6cc8677f2a53ebcd30e4d0722c49d | 122,415 |
def get_credentials(args, logger):
"""Parses the credentials yaml file and gets user and token (simple yaml parser, key-value parser).
Parameters:
args: Object with command line arguments (credentials file)
logger: Function used for logging
Returns:
Credentials, user and token.
"""
data = {}
with open(args.credentials_file, 'r') as credentials_file:
logger('Reading the credentials file')
# parse line by line
for line in credentials_file.readlines():
# ignore comments
if line.startswith('#'):
continue
# split the line and take the key and value
values = line.split(':')
key = values[0].strip()
value = values[1].strip()
data[key] = value
if not 'user' in data:
raise Exception('There is no user found in the credentials file')
if not 'token' in data:
raise Exception('There is no token found in the credentials file')
logger('The credentials are read successfully')
return data | 511643510ad4df4006e5a959d3e4b6341c6ce0f4 | 122,420 |
def _server_max_message_size() -> int:
"""Max size, in megabytes, of messages that can be sent via the WebSocket connection.
Default: 200
"""
return 200 | b36c29c8e8b0f164bf18151d8090b4610f545af2 | 122,422 |
def bytestring(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a given string into a bytestring."""
if isinstance(s, bytes):
return s
try:
return s.encode(encoding)
except UnicodeError:
return s.encode(fallback) | d73ae1377c770d218585c51db216b21918d5d562 | 122,423 |
def pretty_file_size(size: float, precision: int = 2, align: str = ">",
width: int = 0) -> str:
"""Helper function to format size in human readable format.
Parameters
----------
size: float
The size in bytes to be converted into human readable format.
precision: int, optional
Define shown precision.
align: {'<', '^', '>'}, optional
Format align specifier.
width: int
Define maximum width for number.
Returns
-------
human_fmt: str
Human readable representation of given `size`.
Notes
-----
Credit to https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
""" # noqa: E501
template = "{size:{align}{width}.{precision}f} {unit}B"
kwargs = dict(width=width, precision=precision, align=align)
# iterate units (multiples of 1024 bytes)
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(size) < 1024.0:
return template.format(size=size, unit=unit, **kwargs)
size /= 1024.0
return template.format(size=size, unit='Yi', **kwargs) | 96d094a4959aa678a580686ff5ea20ed1f216f3a | 122,424 |
def to_bool(val):
"""
Interprets Boolean implication of any English string
>>> to_bool('True')
True
>>> to_bool('False')
False
>>> to_bool(' 1000')
True
>>> to_bool('0.0')
False
>>> to_bool('')
False
>>> to_bool(' ')
False
>>> to_bool('Belgium')
True
>>> to_bool(' yeS')
True
>>> to_bool(' NO ')
False
>>> to_bool('f')
False
>>> to_bool(None)
False
>>> to_bool(42)
True
>>> to_bool(0)
False
"""
if not val:
return False
val = str(val).strip().title()
if not val:
return False
try:
val = int(val)
return bool(val)
except ValueError:
try:
val = float(val)
return bool(val)
except ValueError:
if val in ('N', 'No', 'False', 'F'):
return False
return True | 97ed336f1d952f2a25fb5b5c13d41fed6fef34c5 | 122,427 |
def get_id_from_payload(payload):
"""
Get the alert id from an update request in Slack
"""
values = payload['view']['state']['values']
for value in values:
for key in values[value]:
if key == 'alert_id':
alert_id = values[value][key]['value']
return alert_id | d7362b691313c74ab25efeea0379b3c7f3eae60e | 122,431 |
import uuid
def create_writer_commands(
nexus_structure,
output_filename,
broker,
job_id="",
start_time=None,
stop_time=None,
use_hdf_swmr=True,
service_id=None,
abort_on_uninitialised_stream=False,
):
"""
:param nexus_structure: dictionary containing nexus file structure
:param output_filename: the nexus file output filename
:param broker: default broker to consume from
:param job_id: filewriter job_id
:param start_time: ms from unix epoch
:param stop_time: ms from unix epoch
:param abort_on_uninitialised_stream: Whether to abort if the stream cannot be initialised
:param service_id: The identifier for the instance of the file-writer that should handle this command. Only needed if multiple file-writers present
:param use_hdf_swmr: Whether to use HDF5's Single Writer Multiple Reader (SWMR) capabilities. Default is true in the filewriter
:return: A write command and stop command with specified job_id.
"""
if not job_id:
job_id = str(uuid.uuid1())
write_cmd = {
"cmd": "FileWriter_new",
"broker": broker,
"job_id": job_id,
"file_attributes": {"file_name": output_filename},
"nexus_structure": nexus_structure,
}
if start_time is not None:
write_cmd["start_time"] = start_time
if not use_hdf_swmr:
write_cmd["use_hdf_swmr"] = use_hdf_swmr
if abort_on_uninitialised_stream:
write_cmd["abort_on_uninitialised_stream"] = abort_on_uninitialised_stream
stop_cmd = {"cmd": "FileWriter_stop", "job_id": job_id}
if stop_time is not None:
write_cmd["stop_time"] = stop_time
stop_cmd["stop_time"] = stop_time
if service_id is not None and service_id:
write_cmd["service_id"] = service_id
stop_cmd["service_id"] = service_id
return write_cmd, stop_cmd | 09b90bef6532b40c28109ed8246b3584f3c19e48 | 122,438 |
from typing import Iterable
def join_with_double_quotes(names: Iterable[str], sep=", ", prefix="") -> str:
"""
Return string with comma-separated, delimited names.
This step ensures that our identifiers are wrapped in double quotes.
>>> join_with_double_quotes(["foo", "bar"])
'"foo", "bar"'
>>> join_with_double_quotes(["foo", "bar"], sep=", USER ", prefix="USER ")
'USER "foo", USER "bar"'
"""
return prefix + sep.join('"{}"'.format(name) for name in names) | 6ee5e6d3390ba4d2c5c6c5f0bd60bbfd3243cde7 | 122,439 |
def worldtocamera_torch(corners_global, position, rotation):
"""
corners_global: (N, 3), N points on X(right)-Y(front)-Z(up) world coordinate (GTA)
or X(front)-Y(left)-Z(up) velodyne coordinates (KITTI)
pose: a class with position, rotation of the frame
rotation: (3, 3), rotation along camera coordinates
position: (3,), translation of world coordinates
corners: (N, 3), N points on X(right)-Y(down)-Z(front) camera coordinate
"""
assert corners_global.shape[1] == 3, ("Shape ({}) not fit".format(
corners_global.shape))
corners = (corners_global - position[None]).mm(rotation)
return corners | 26d4d8242e5388ba22bb13c3cd0aaa27bad566fb | 122,441 |
def image_clone(image, pixeltype=None):
"""
Clone an ANTsImage
ANTsR function: `antsImageClone`
Arguments
---------
image : ANTsImage
image to clone
dtype : string (optional)
new datatype for image
Returns
-------
ANTsImage
"""
return image.clone(pixeltype) | 4c7ddd82c63a2baba5fe380397c372a314a0b863 | 122,451 |
def _toArchitectureDir(architecture):
"""Re-map 'x64' to 'amd64' to match MSVC directory names.
"""
return {'x64':'amd64'}.get(architecture, architecture) | 53f630829ea4c91c032401ba16f28d900c16e98a | 122,452 |
import hashlib
def hash_digest(data: bytes) -> str:
"""Compute a hash digest of some data.
We use a cryptographic hash because we want a low probability of
accidental collision, but we don't really care about any of the
cryptographic properties.
"""
# Once we drop Python 3.5 support, we should consider using
# blake2b, which is faster.
return hashlib.sha256(data).hexdigest() | fae7d5056ff214dfa08e9f42ae33226413c37720 | 122,458 |
def convert_dict_to_class(data: dict) -> object:
"""
Converts a dictionary to a class
Parameters
----------
data : dict
Data to put into a class
Returns
-------
object
An anonymous class with attributes from dictionary
"""
if isinstance(data, dict):
return type("Class", (object,), data)
raise TypeError("Data is not a dictionary") | c72fcfabb534923d458f8f95d5242f49d23e3548 | 122,459 |
from typing import Generator
def filter_by_type(sequence, type_) -> Generator[object, None, None]:
"""Filter sequence by type."""
return (
ele for ele in sequence
if isinstance(ele, type_)
) | cdbc88295681cc6f559c79c2945de29488cf9f37 | 122,468 |
def is_cscan_usable(cscan):
"""
Check to see if a CachedImageScan is usable
:param cscan: XnatUtils.CachedImageScan object
:return: True if usable, False otherwise
"""
return cscan.info()['quality'] == "usable" | 23ef35081387d8536327fe0209309e2317e043ed | 122,475 |
def get_password_length_input(min_length = 6, max_length = 15):
"""
Get the password length from the user , it needs to be a integer between
min_length and max_length, this length includes all the characters
(numbers, letters, special characters).
Args:
min_length (int): Minimum length of the password, 6 by default.
max_length (int): Maximum length of the password, 15 by default.
Returns:
int: The length of the password.
"""
try:
# Convert it into integer
pass_length = int(input("Enter the length of your password: ").rstrip())
except ValueError as e:
print("Password lenght must be an integer")
else:
# Skipped if there is an exception.
length_cond = pass_length in range(min_length, max_length + 1)
if length_cond:
return pass_length
else:
print('Password lenght is not valid.') | 6b59c67f463fbe345a0d110a1e72afd2ba9e8087 | 122,476 |
def luka_implication(x, y):
"""Performs pairwise the Lukasiewicz implication."""
return min(1, 1 - x + y) | ed97af0ec014e18138fcaf6967b6e901533a3492 | 122,482 |
def big_small(blocks) -> list:
"""
Return a list of minimum and maximum cordinates in the blocks.
Return Order:
[min_x, min_y, max_x, max_y]
"""
lst = [blocks[0]['x'], blocks[0]['y'], blocks[0]['x'], blocks[0]['y']]
for block in blocks:
if block['x'] < lst[0]:
lst[0] = block['x']
if block['y'] < lst[1]:
lst[1] = block['y']
if block['x'] > lst[2]:
lst[2] = block['x']
if block['y'] > lst[3]:
lst[3] = block['y']
return lst | d3a6e1b9f9cafb65373b6ff1052733803643ef8d | 122,485 |
def filter_fn(x):
"""Filter bad samples."""
if x["label"] == -1:
return False
if "premise" in x:
if x["premise"] is None or x["premise"] == "":
return False
if "hypothesis" in x:
if x["hypothesis"] is None or x["hypothesis"] == "":
return False
return True | 4c95964c7a14c1a7119dd464a1042869c480ff19 | 122,490 |
def listDifference(total, used):
"""
Return the remaining part of "total" after removing elements in "used". Each element will be removed only once.
Parameters
----------
total : list of any
The original list from which we want to remove some elements.
used : list of any
The elements we want to remove from total.
Returns
-------
list of any
The list total after removing elements in used.
"""
ret = list(total)
for x in used:
ret.remove(x)
return ret | c6928c312160cfaaa6c6ea461190d876c4798eb7 | 122,497 |
def fixtureid_cpcs(fixture_value):
"""
Return a fixture ID to be used by pytest, for fixtures returning a list of
CPCs.
Parameters:
* fixture_value (list of zhmcclient.Cpc): The list of CPCs.
"""
cpc_list = fixture_value
assert isinstance(cpc_list, list)
cpcs_str = ','.join([cpc.name for cpc in cpc_list])
return "CPCs={}".format(cpcs_str) | 864d76898452e74841497253e7799e763aac3c0b | 122,498 |
from typing import Union
from typing import Any
import torch
def check_scalar(x: Union[Any, float, int]) -> bool:
"""
Provide interface to check for scalars
Args:
x: object to check for scalar
Returns:
bool" True if input is scalar
"""
return isinstance(x, (int, float)) or (isinstance(x, torch.Tensor) and x.numel() == 1) | 13826ff0028d82dbaa20d601b30f14733f83aefc | 122,499 |
def _label_to_dependency(label):
"""Return the Label `label` as a single string."""
return "//" + label.package + ":" + label.name | 987e7f25edb6be128cd309a6a823cda67da073c6 | 122,500 |
def games_in_progress(cursor):
"""
Returns a list of GSIS identifiers corresponding to games that
are in progress. Namely, they are not finished but have at least
one drive in the database.
The list is sorted in the order in which the games will be played.
"""
playing = []
cursor.execute('''
SELECT DISTINCT game.gsis_id, game.finished
FROM drive
LEFT JOIN game
ON drive.gsis_id = game.gsis_id
WHERE game.finished = False AND drive.drive_id IS NOT NULL
''')
for row in cursor.fetchall():
playing.append(row['gsis_id'])
return sorted(playing, key=int) | 33a0c17e45c58c5d58b6f2a516ed35424567a27a | 122,503 |
def document_lookup(md_files):
"""
Given a list of MarkdownDocument files, create a dictionary keyed by
the filename (independent of the path). It will map the filename to
a list of potential files.
# Parameters
md_files:list(MarkdownDocument)
- The list of MarkdownDocument objects to create the lookup
dictionary
# Return
A dictionary keyed by a filename mapped to a list of
MarkdownDocument objects that have that filename but are on
different paths.
"""
reverse = {}
for md in md_files:
reverse.setdefault(md.filename.name, []).append(md)
return reverse | c99121debf71aaa1e9435b664016f70929241755 | 122,506 |
def create_help(header, options):
"""Create formated help
Args:
header (str): The header for the help
options (list[str]): The options that are available for argument
Returns:
str: Formated argument help
"""
return "\n" + header + "\n" + \
"\n".join(map(lambda x: " " + x, options)) + "\n" | cad6bc53151711804552169436304521de80c439 | 122,507 |
def cast_tuple_index_to_type(index, target_type, *tuples):
"""Cast tuple index to type.
Return list of tuples same as received but with index item casted to
tagret_type.
"""
result = []
for _tuple in tuples:
to_result = []
try:
for i, entry in enumerate(_tuple):
to_result.append(entry if i != index else target_type(entry))
except TypeError:
pass
result.append(tuple(to_result))
return result | eff957864cd531b70587daacaf71a4d5b973dcd8 | 122,508 |
def total_pixels_from_mask_2d(mask_2d):
"""Compute the total number of unmasked pixels in a mask.
Parameters
----------
mask_2d : ndarray
A 2D array of bools, where *False* values are unmasked and included when counting pixels.
Returns
--------
int
The total number of pixels that are unmasked.
Examples
--------
mask = np.array([[True, False, True],
[False, False, False]
[True, False, True]])
total_regular_pixels = total_regular_pixels_from_mask(mask=mask)
"""
total_regular_pixels = 0
for y in range(mask_2d.shape[0]):
for x in range(mask_2d.shape[1]):
if not mask_2d[y, x]:
total_regular_pixels += 1
return total_regular_pixels | 501e9e6811312e3e0f86436dbd6744fcdf3792fd | 122,516 |
import importlib
def get_class(full_python_class_path):
"""
take something like some.full.module.Path and return the actual Path class object
Note -- this will fail when the object isn't accessible from the module, that means
you can't define your class object in a function and expect this function to work
example -- THIS IS BAD --
def foo():
class FooCannotBeFound(object): pass
# this will fail
get_class("path.to.module.FooCannotBeFound")
"""
module_name, class_name = full_python_class_path.rsplit('.', 1)
m = importlib.import_module(module_name)
return getattr(m, class_name) | 822f43ff7840ee14b7ba196a5cc45b922efb6192 | 122,520 |
def label_residue(residue):
""" Return a string of the label of the biopython [1] residue object.
The label of the residue is the following:
Chain + Position
Parameters
----------
residue: Bio.PDB.Residue.Residue
The residue to be labeled.
Notes
-----
1. http://biopython.org/wiki/Biopython
"""
position = str(residue.id[1])
chain = residue.parent.id
return chain + position | 2e9a07b8e15e5b9118e7bd5b961ea4aeb9946163 | 122,528 |
def get_resource_path(resource):
""" Return the full path for the resource (with or without a parent).
"""
return ("%s/%s" % (resource.parent and resource.parent.id or '',
resource.id.lstrip('/'))).lstrip('/') | 2ece218a78f93050d008f5729839e68a9c1a4a06 | 122,533 |
def round_value(value):
"""
Round the given value to 1 decimal place.
If the value is 0 or None, then simply return 0.
"""
if value:
return round(float(value), 1)
else:
return 0 | fd5f7b447d0b677a8b88f6a87568191b05840173 | 122,542 |
def make_board(state):
"""Make a TicTacToe board from the cells"""
cells = [str(i) if c == '.' else c for i, c in enumerate(state, start=1)]
sep = '-------------'
tmpl = '| {} | {} | {} |'
return '\n'.join([
sep,
tmpl.format(*cells[0:3]), sep,
tmpl.format(*cells[3:6]), sep,
tmpl.format(*cells[6:9]), sep
]) | 02c85b727d96d3bcac4121055b5e58a6a23c40b8 | 122,543 |
def read_file(input_path: str) -> list:
"""
Reads a txt file.
Arguments:
---------
input_path: path to txt file
Returns
-------
list
"""
with open(input_path, 'r') as file:
text_list = file.readlines()
text_list = [line.replace('\n', '') for line in text_list]
return text_list | c9d8f5ebd2230ba49683d438ce7cda1afa12dff9 | 122,554 |
from typing import List
import torch
def generate_permutations(permutation_size: int, n_permutations: int) -> List[torch.Tensor]:
"""Function that generations n_permutations unique permutations of size permutation_size"""
permutations = [torch.randperm(permutation_size) for _ in range(n_permutations)]
while len(set(permutations)) != n_permutations:
permutations = [torch.randperm(permutation_size) for _ in range(n_permutations)]
return permutations | 8c4a7cf26f67dd9c5c969844b4e780b7f7ce3042 | 122,556 |
def sp_cls_count(sp_cls, n_seg_cls=8):
"""
Get the count (number of superpixels) for each segmentation class
Args:
sp_cls (dict): the key is the superpixel ID, and the value is the
class ID for the corresponding superpixel. There are n elements
in the sp_cls. Here, we use zero-indexing, which means the class
are in range [0, k)
n_seg_cls (int): number of segmentation classes
Output:
counts (list): a list for the count, where each index is the count
for the corresponding segmentation class. The length of the list
equals to the number of semantic segmentation classes.
"""
counts = [0] * n_seg_cls
for k in sp_cls.keys():
counts[sp_cls[k]] += 1
return counts | a9301743b43b269da303d027012c9811fc7c12f1 | 122,557 |
import torch
def flatten_grad(grad):
"""
Flattens the gradient tensor to a rank 1 tensor
"""
tuple_to_list = []
for tensor in grad:
tuple_to_list.append(tensor.view(-1))
all_flattened = torch.cat(tuple_to_list)
return all_flattened | 918bb1a87e6d6f319beba79f7bcec225d7ff5de2 | 122,558 |
import secrets
def generate_aipkey(length=64) -> str:
"""Generate a new LENGTH-string api-key."""
return secrets.token_urlsafe(length) | 0391b51c2ffe8a42781bd5da153f934dee440906 | 122,560 |
import string
import random
def random_string(search_query: str, valid: bool, string_length: int = 10) -> str:
"""
Generate a random string of fixed length
Keyword Arguments:
search_query {str} -- use query param for the search request
valid {bool} -- should searchable by the the query term
string_length {int} -- size of random string (default: {10})
Returns:
str -- random string
"""
letters = string.ascii_lowercase
if valid:
return "{} {}".format(
search_query, "".join(random.choice(letters) for i in range(string_length)),
)
while True:
random_str: str = "".join(random.choice(letters) for i in range(string_length))
if search_query not in random_str:
return random_str | 6d2955eae429a4f3228ca76494a5816c709b3147 | 122,562 |
def loop_noise_coupling_functions(olg, clp, chp, lock='active'):
"""Control loop coupling functions for a opto-mechanical cavity.
Inputs:
-------
olg: array of complex floats
Open loop gain
clp: array of complex floats
Cavity low pass
chp: array of complex floats
Cavity high pass
lock: string
Either "active", representing locking the laser to the cavity,
or "passive", representing locking the cavity to the laser.
Outputs:
--------
a_in: array of complex floats
Input frequency noise coupling to transmitted frequency noise
a_sense: array of complex floats
Sensing frequency noise coupling to transmitted frequency noise
a_disp: array of complex floats
Displacement frequency noise coupling to transmitted frequency noise
"""
if lock == 'active':
a_in = clp / (1 + clp * olg)
a_sense = clp * olg / (1 + clp * olg)
a_disp = clp**2 * olg / (1 + clp * olg) + chp
else:
a_in = clp * (1 + olg) / (1 + clp * olg)
a_sense = chp * olg / (1 + clp * olg)
a_disp = chp / (1 + clp * olg)
return a_in, a_sense, a_disp | 1ff646772254fe07435493f98c76570d303fc670 | 122,564 |
import requests
def get_nft_owner(token_uid: str, base_url="https://node.explorer.hathor.network/v1a") -> str:
"""Get the address currently holding the given NFT."""
tokensResponse = requests.get(
f"{base_url}/thin_wallet/token_history",
params={"id": token_uid, "count": 1},
)
res_json = tokensResponse.json()
transactions_output = res_json["transactions"][0]["outputs"]
address_holding_the_token = [
tx["decoded"]["address"]
for tx in transactions_output
if tx["token"] == token_uid
]
return address_holding_the_token[0] | d90f4021bf796392c91caf398f56cd71cead33cb | 122,569 |
import string
import random
def random_string(length):
""" Generate a random string of uppercase, lowercase, and digits """
library = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(library) for _ in range(length)) | 4c13f599ca721dbaab8c45244aa1ab8b945aa5e9 | 122,573 |
import json
def read_json(input_string):
"""
Read and parse the JSON input.
JSON Null -> Python None
"""
return json.load(input_string) | 2b0e5b9ccb16767553385b3b8a4ec40db4f25381 | 122,574 |
import base64
def encode_password(password: str) -> str:
"""Hash a password for storing.
:param password: String to hash
:return: Hashed string
"""
return base64.b64encode(password.encode("utf-8")).decode("utf-8") | a6d6fc9215b1ec0e7a1863ae5197087aa7add55e | 122,576 |
def custom_config_updated_params(changes, vers1):
"""Generates data frame of updated parameters in custom configuration.
Updated parameters have changed from the base default version.
Parameters
---------------
changes : pandas.DataFrame
vers1 : str
Returns
---------------
pandas.DataFrame
"""
vers2 = 'custom'
return changes[(changes[vers1] != changes[vers2])].dropna() | d3320f7e857f3b2b67a9282e6ace7864226c81ef | 122,580 |
def _substitute_window(seq, idx_freq_win, order=2):
"""
This function carries out substitution of the most frequent window with an
integer. Each window substitution reduces the length of the sequence by
(order-1) elements. The substituted integer is one greater than the largest
element in the sequence.
The substitution uses indices/locations of the most frequent window and
is carried out in 3 steps, for a single window:
1. Replace 1st element of seq at window index by integer (max(seq)+1)
2. Replace the next order - 1 elements with False
3. Filter list to eliminate all False elements
Iteration of first 2 steps happens together over indices in idx_freq_win
Parameters
----------
seq : list
Sequence of integers.
idx_freq_win : compress iterator or tuple or list
Indices that correspond to the occurence of the most frequent window.
The index of the window is the same as the index of the first element
of that window in seq.
order : int, optional
Number of elements in window for substitution.
The default is 2 for pairs.
Returns
-------
reduced_seq : list
Sequence of integers with most frequent window substituted.
len(reduced_seq) < len(seq)
"""
# Integer value to use for substitution
a = max(seq) + 1
# Iterate over indices/locations of most frequent window
for index in idx_freq_win:
# Substitute the first element of window, in seq, by integer
seq[index] = a
# Substitute the remaining elements of window, in seq, with False
for n in range(1, order):
seq[index + n] = False
# Filter out all False elements and return what's left
reduced_seq = [element for element in seq if element]
return reduced_seq | ba224621816eed206d885bc3636f61701335a49a | 122,582 |
def extract_speakers(all_dialog):
"""Get set of speakers from the extracted dialog."""
return set([speaker for speaker, _ in all_dialog]) | b32b5218361da9e3b579dfbcb11b980820e92463 | 122,584 |
def get_term_apparitions(index_name, es, term):
""" Return a text in ElasticSearch with the param id
:param index_name: ElasticSearch index file
:param es: ElasticSearch object
:param term: Term (Entity) to search
:return: str
"""
res = es.count(index=index_name, body={
"query": {
"match": {
"text": {
"query": term,
"operator": "and"
}
}
}
})
return res['count'] | c033822f002cc6a9ab1ccfd255d9a452ae21f686 | 122,585 |
import requests
def api(
method,
endpoint,
data=None,
token=None,
):
"""
Make an API call to skyportal
Arguments
----------
method : str
HTTP method to use
endpoint : str
Endpoint to call
data : dict
Data to send with the request
token : str
Skyportal token
Returns
----------
response : requests.Response
Response from skyportal
"""
headers = {"Authorization": f"token {token}"}
response = requests.request(method, endpoint, json=data, headers=headers)
return response | eda79813b5801692fc14ab1e923230432f1cc37f | 122,589 |
import math
def antenna_solid_angle(aperture_efficiency,geometrical_area,wavelength):
"""
Antenna solid angle of an antenna, assuming radiation efficiency = 1
Krauss, Radio Astronomy, sec. 6-2, cals this the beam solid angle.
Given the aperture efficiency (dimensionless) and the geometrical
area and wavelength in the same units (say, meters), this returns the
beam solid angle in steradians.
If the antenna has some losses, like not being totally reflective,
then the radiation efficiency is not 1 and it should be multiplied
with this result.
@param aperture_efficiency :
@type aperture_efficiency : float
@param geometrical_area : typically pi*(diam/2)^2, same units as wavelength
@type geometrical_area : float
@param wavelength : same units as antenna diameter
@type wavelength : float
@return: float
"""
return math.pow(wavelength,2)/geometrical_area/aperture_efficiency | 2f8b1e3383b32c8b921fc36e6c903ab466613ca1 | 122,590 |
def format_cookie(url, cookies):
""" Constructs a log message from a list of cookies and the host
where they're set
"""
prefix = "\n< COOKIES ({}{}) ".format(url.host(), url.path())
suffix = ", ".join(["[[{}{}] {} => {}]".format(cookie.domain(),
cookie.path(),
cookie.name(),
cookie.value())
for cookie in cookies])
return prefix + suffix | 3246f0f74251818670ab2a33b1044ebb01ad0acb | 122,598 |
import requests
def get_redirected_url(url: str):
"""
Given a URL, returns the URL it redirects to or the
original URL in case of no indirection
"""
with requests.Session() as session:
with session.get(url, stream=True, allow_redirects=True) as response:
if response.history:
return response.url
else:
return url | d62ce618ad994a92f18933b9fcdb3f12e5e01ec6 | 122,602 |
def parse_post_meta(raw_postmeta):
"""
Parse meta-data of a post contained in the special latex command
\postmeta{...}.
Example:
\postmeta{
Title: Compactness and Open Sets in $\mathbb{R}^{d}$
Date: 2014-06-29
Tags: topology, compactness
Slug: compactness_open_sets
}
Return a dictionary
"""
lines = raw_postmeta.split('\n')
D = {}
for i, l in enumerate(lines):
if l.strip() != '':
colon_splits = l.split(':')
key = colon_splits[0].strip()
val = colon_splits[1].strip()
D[key] = val
return D | 26b97249c73d7aebcd5d2b630d4c1f5bf4d898ad | 122,606 |
def int_to_digits(n,B=10,bigendian=False):
"""
Convert the integer n to its digits in base B
"""
n = abs(n)
D = []
while n != 0:
n,r = divmod(n,B)
D.append(r)
if bigendian:
return tuple(D)
else:
return tuple([i for i in reversed(D)]) | 10021390466a86240ece862f6ff5ab602cb01c93 | 122,610 |
def vertical_strip_gridmap(height, alternating=True):
"""
Returns a function that determines the pixel number for a grid with strips arranged vertically.
:param height: grid height in pixels
:param alternating: Whether or not the lines in the grid run alternate directions in a zigzag
:return: mapper(x, y)
"""
def mapper(x, y):
if alternating and x % 2:
return x * height + (height - 1 - y)
return x * height + y
return mapper | 9042071bfb440db663a3a0c123b79706cb051823 | 122,612 |
def snowmelt_rain_on_snow_heavily_forested(precipitation,
temperatures,
temperature_cutoff=32.0,
rain_melt_coeff=0.007):
"""Calculate the amount of snowmelt rain-on-snow situations in
heavily forested areas using a generalized equation for rain-on-snow
situations in heavily forested areas (the mean canopy cover is greater
than 80%). This snowmelt calculation is from the family of energy budget
solutions.
:param precipitation: Precipitation rates, in inches/day
:type precipitation: numpy.ndarray
:param temperatures: Temperatures, in degrees Fahrenheit
:type temperatures: numpy.ndarray
:param temperature_cutoff: Temperature when melt begins,
in degrees Fahrenheit
:type temperature_cutoff: float
:param rain_melt_coeff: Snowmelt coefficient when raining,
1/degrees Fahrenheit
:type rain_melt_coeff: float
:return snowmelt: Snowmelt values, in inches per day
:rtype snowmelt: numpy.ndarray
.. note::
Equation:
M = (0.074 + 0.007 * P_r) * (T_a - 32) + 0.05
where
M snowmelt, inches/day
P_r rate of precipitation, inches/day
T_a temperature of saturated air, at 3 meters (10 ft) level,
degrees Fahrenheit
Reference:
Engineering and Design - Runoff from Snowmelt
U.S. Army Corps of Engineers
Engineering Manual 1110-2-1406
Chapter 5-3. Generalized Equations, Rain-on-Snow Situations, Equation 5-20
https://www.wcc.nrcs.usda.gov/ftpref/wntsc/H&H/snow/COEemSnowmeltRunoff.pdf
"""
return (
(0.074 + rain_melt_coeff * precipitation)
* (temperatures - temperature_cutoff) + 0.05
) | 0d881e4e429a7ca3f8e5bab6fa8b3162347eb4a1 | 122,613 |
def td_to_dict(td):
"""
Takes a timedelta and returns a dict with the following keys:
* days
* hours
* minutes
* seconds
"""
return {
'days': td.days,
'hours': td.seconds // 3600 % 24,
'minutes': td.seconds // 60 % 60,
'seconds': td.seconds % 60,
} | 1162cd4a0c2a6a5973c064fa5f3465e03ad925f9 | 122,614 |
def is_valid(s):
"""
Using a conventional stack struct, validate
strings in the form "({[]})" by:
1. pushing all openning chars: '(','{' and '[', sequentially.
2. when a closing character like ')', '}' and '] is found
we pop the last opening char pushed into stack
3. check if popped char matches the closing character found.
If stack is empty and all comparisons are a match, returns
true. False otherwise.
s: string to be validaded
return True or False depending if string is valid or not
"""
if len(s) < 2:
return False
parent_map = {
'(': ')',
'{': '}',
'[': ']',
}
stack = []
for c in s:
# if opening char
if c in parent_map.keys():
stack.append(c)
else:
if not stack:
return False
# attempt matching opening and closing chars
if parent_map[stack.pop()] != c:
return False
return not stack | 1837d6c3a92ca2e4be845abd15eaefbf09c32e6b | 122,618 |
def capifyname(forcename):
"""
Return name of the class in camelCase.
"""
return forcename.replace('_',' ').title().replace(' ','') | b11e7e095721999a2d0e2303621de7f955d79846 | 122,620 |
import decimal
def round_half_up(money):
"""
Explicitly round a decimal to 2 places half up, as should be used for
money.
>>> exponent = decimal.Decimal('0.01')
>>> should_not_be_one = decimal.Decimal('1.005')
>>> should_not_be_one.quantize(exponent)
Decimal('1.00')
>>> round_half_up(should_not_be_one)
Decimal('1.01')
"""
return money.quantize(decimal.Decimal('0.01'), decimal.ROUND_HALF_UP) | e87199531ae45be4a17359751c68a5a15a8edecd | 122,623 |
def _propagate_self(self, *_, **__):
"""Some object methods, rather doing anything meaningful with their input,
would prefer to simply propagate themselves along. For example, this is used
in two different ways with Just and Nothing.
When calling any of the or_else and or_call methods on Just, there is
already a value provided (whatever the Just is) so these methods simply
ignore their inputs and propagate the Just along.
However, when filtering, fmapping, applying or binding a Nothing
(and also a Left), this method is used to signal some sort of failure in the
chain and propagate the original object along instead.
"""
return self | 294e282c8a706bc1638a6144422b590bab365601 | 122,625 |
import tempfile
def _create_tmp_mount(base_dir):
"""Create a tmp mount in base_dir."""
return tempfile.mkdtemp(dir=base_dir) | 5b498d8291c39ded966fb4cec25a99ce61fe7505 | 122,626 |
def rotate_strings(a: str, b: str) -> bool:
"""
Determine if you can rotate a string to get another string.
:param a: first string
:param b: second string
:return: True if the rotation is possible, and False otherwise.
>>> rotate_strings('abcde', 'cdeab')
True
>>> rotate_strings('abc', 'acb')
False
"""
if len(a) != len(b):
return False
if set(a) != set(b):
return False
for i in range(len(b)):
if a == b[i:] + b[:i]:
return True
return False | db9ce562ad464af1ecee04c180ad02265df3b771 | 122,629 |
def get_sentence_ranking(text, relative_word_frequency):
"""Return dictionary with sentences as keys and total value of relative word frequencies present in sentence."""
sentence_ranking = {}
for sentence in text.sents:
for word in sentence:
lower_word = word.text.lower()
if lower_word in relative_word_frequency.keys():
frequency = relative_word_frequency[lower_word]
if sentence in sentence_ranking.keys():
sentence_ranking[sentence] += frequency
else:
sentence_ranking[sentence] = frequency
return sentence_ranking | f209d9756087615402759af2d907dfa2103328a1 | 122,631 |
def instance(cls):
"""Create a new instance of a class.
Parameters
----------
cls : type
The class to create an instance of.
Returns
-------
instance : cls
A new instance of ``cls``.
"""
return cls() | 7c02b4f2f448f431529139796fc06ea4df5f5f6f | 122,640 |
def attribute_match_all(
attribute, length=None, data=None, value=None, endswith=None
):
"""
Check if an attribute matches all of the following specified conditions:
- Minimum length.
- Contains an item.
- Is exactly a value.
Note that only those conditions explicitly passed will be checked.
Parameters
----------
attribute : anything
The attribute to match against.
length : int, default is None
If specified, the attribute must reach this length (or higher).
data : anything, default is None
If specified, the attribute must contain this value.
value : anything, default is None
If specified, the attribute must be this value.
endswith : sequence, default is None
If specified, the attribute must end with this sequence.
Returns
-------
bool
Whether the attribute matches any condition.
"""
assert (
length is not None
or data is not None
or value is not None
or endswith is not None
), 'No condition passed! Will return True always...'
if length is not None and len(attribute) < length:
return False
if data is not None and data not in attribute:
return False
if value is not None and attribute != value:
return False
if endswith is not None and attribute[-len(endswith) :] != endswith:
return False
return True | dfb877ad574621e090b5fad08451ac2865c4069b | 122,642 |
import time
def wait_until_not_raised(condition, delay, max_attempts):
"""
Executes a function at regular intervals while the condition
doesn't raise an exception and the amount of attempts < maxAttempts.
:param condition: a function
:param delay: the delay in second
:param max_attempts: the maximum number of attemps. So the timeout
of this function will be delay*max_attempts
"""
def wrapped_condition():
try:
condition()
except:
return False
return True
attempt = 0
while attempt < (max_attempts-1):
attempt += 1
if wrapped_condition():
return
time.sleep(delay)
# last attempt, let the exception raise
condition() | dc7dd212ccf0a65564edcd5622f10d0d736a7ec7 | 122,653 |
def read_ppips(ppips_file):
"""
Loads and parses ppips_*.db file. Returns a dict indexed by PIP name which
contains their types ("always", "default" or "hint")
"""
ppips = {}
with open(ppips_file, "r") as fp:
for line in fp.readlines():
line = line.split()
if len(line) == 2:
full_pip_name = line[0].split(".")
pip_name = ".".join(full_pip_name[1:])
ppips[pip_name] = line[1]
return ppips | 13c6a26cdf181f41fd0cd565952e22f7896debd3 | 122,654 |
def _FormatPipelineErrorResult(result):
"""Formats a kpt pipeline error result.
Args:
result: The pipeline error result object.
Returns:
string. The formatted result string, including the resource, file, and
field that the result references, as applicable.
"""
prefix = ' - Error'
file = result.get('file')
if file and 'path' in file:
prefix += ' in file "{}"'.format(file.get('path'))
resource_ref = result.get('resourceRef')
if resource_ref:
resource = '{}/{}/{}'.format(
resource_ref.get('apiVersion'), resource_ref.get('kind'),
resource_ref.get('name'))
prefix += ' in resource "{}"'.format(resource)
field = result.get('field')
if field:
prefix += ' in field "{}"'.format(field)
msg = result.get('message')
return '{}:\n "{}"'.format(prefix, msg) | 8041ca02f8a19e02d9e08b6f1f9ddc58bce84e45 | 122,655 |
import inspect
def get_descriptor(cls, descname):
"""
Returns the descriptor object that is stored under *descname* instead of
whatever the descriptor would have returned from its `__get__()` method.
:param cls: class to find the descriptor on
:param descname: name of the descriptor
:return: the descriptor stored under *descname* on *instance*
"""
return inspect.getattr_static(cls, descname) | 02445b687d5d442c09b6473ca65823299f3f8ad6 | 122,656 |
def get_integer_from_response(response):
"""
Gets the value from a valid integer response.
str -> int
"""
return int(response) | 81dfabc4d8e70fc8477306b425591222c11d3d91 | 122,658 |
def get_author_data(includes):
"""
Gets the authors of the referenced tweets, and the number of followers of
all authors
Parameters
----------
includes: dict of lists of dict objects
The `includes` field of the API's response. Potentially contains the
fields `media`, `tweets`, `users`, and `places`. Represents all the
referenced data, users, and places in the tweets in the response
Returns
-------
ref_id2author_id: dict
Dictionary mapping tweet IDs of referenced tweets to their author IDs
author_id2n_followers: dict
Dictionary mapping author IDs (of all returned search tweets and their
referened tweets) to their number of followers
handle2author_id:dict
Dictionary mapping user handles to their author IDs
"""
# Get ref tweet -> author, user -> n followers ahead of time for efficiency
author_id2n_followers = {u['id']:u['public_metrics']['followers_count']
for u in includes['users']}
handle2author_id = {u['username']:u['id'] for u in includes['users']}
if 'tweets' in includes:
ref_id2author_id = dict()
for r in includes['tweets']:
try:
ref_id2author_id[r['id']] = r['author_id']
except KeyError:
# Note: you can have a referenced tweet that's not included if
# the author of the included tweet has their profile set to
# private. In that case just skip adding the referenced tweet
# details
continue
else:
ref_id2author_id = dict()
return ref_id2author_id, author_id2n_followers, handle2author_id | 6635dda788391fca9677d4fe99409d95b34e78a5 | 122,662 |
def get_car_price(make:str="Ford", model:str="Probe", year:int=1994):
"""
Return the predicted price of a vehicle based on Make, Model, and Year.
"""
price = 30000 - ((2020 - year) * 2000 )
return {"predicted_price": price} | 7802453fd00918b1450ea632b527fae2e6e186a1 | 122,664 |
from typing import Dict
from typing import List
def does_keychain_exist(dict_: Dict, list_: List) -> bool:
"""
Check if a sequence of keys exist in a nested dictionary.
Parameters
----------
dict_ : Dict[str/int/tuple, Any]
list_ : List[str/int/tuple]
Returns
-------
keychain_exists : bool
Examples
--------
>>> d = {'a': {'b': {'c': 'd'}}}
>>> l_exists = ['a', 'b']
>>> does_keychain_exist(d, l_exists)
True
>>> l_no_existent = ['a', 'c']
>>> does_keychain_exist(d, l_no_existent)
False
"""
for key in list_:
if key not in dict_:
return False
dict_ = dict_[key]
return True | 03deb2aad0ec1c034aab01b29fe06acea913701e | 122,667 |
def timedelta_to_seconds(td):
"""
Converts a timedelta instance to seconds.
"""
return td.seconds + (td.days*24*60*60) | abefa09045c5aee01b4144bc4b1781ef8fa9e0d7 | 122,668 |
import torch
def get_devices(x):
"""Recursively find all devices in state dictionary."""
devices = set()
if isinstance(x, dict):
for key, val in x.items():
devices.update(get_devices(val))
else:
if isinstance(x, torch.Tensor):
if x.device.type == 'cpu':
devices.add(-1)
else:
devices.add(x.device.index)
return devices | 4ee7e1052800873cebb10cf3575537f0eaecda3e | 122,669 |
import re
def parse_price(price_string):
"""
>>> parse_price('£16,000.00')
16000.0
>>> parse_price('-£16,000.00')
-16000.0
"""
return float(re.sub('[£,]', '', price_string))
match = re.match('(?P<amount>-?£[\d,]+(\.\d{2})?)', price_string)
if not match:
raise ValueError("Charge not in format '(-)£16,000(.00)' : {}".format(
repr(price_string)))
return float(re.sub('[£,]', '', match.group('amount'))) | bfe766c88dbea62c0bb5f4bd4f8aa6c5efe4f1d4 | 122,672 |
def createBoardConstraints(givenBoardCondition, variables, E, k):
"""Adds implication constraints to the logical encoding
Args:
givenBoardCondition: a list of strings representing the game board configuration
variables: a dictionary of Var type variables, where the key is a string of the variable name and the value is the matching variable
E: the logical encoding
k: an integer representing the maximum number of steps a solution may have
Returns:
E: the logical encoding with the implication constraints added
"""
for node in givenBoardCondition:
parts=node.replace(">>"," ").replace("&"," ").replace("|"," ").replace("("," ").replace(")"," ").split()
top = variables[parts[0]]
connectedNodes = []
for part in parts:
if part != parts[0]:
if int(part[3]) <= k+1:
connectedNodes.append(variables[part])
for node in connectedNodes:
E.add_constraint(node.negate() | top)
return E | b6a7a0bd2d98a88cc504530095f470995d1adf14 | 122,680 |
def inflate(mappings_list, root=None, dict_factory=dict):
"""
Expands a list of tuples containing paths and values into a mapping tree.
>>> inflate([('some.long.path.name','value')])
{'some': {'long': {'path': {'name': 'value'}}}}
"""
root_map = root or dict_factory()
for path, value in mappings_list:
path = path.split('.')
# traverse the dotted path, creating new dictionaries as needed
parent = root_map
for name in path:
#if path.index(name) == len(path) - 1:
if path[-1] == name:
# this is the last name in the path - set the value!
parent[name] = value
else:
# this is not a leaf, so create an empty dictionary if there
# isn't one there already
parent.setdefault(name, dict_factory())
parent = parent[name]
return root_map | dbd4a54a742f630624d8d6f89873459e767c56ba | 122,685 |
def _default_hashfunc(content, hashbits):
"""
Default hash function is variable-length version of Python's builtin hash.
:param content: data that needs to hash.
:return: return a decimal number.
"""
if content == "":
return 0
x = ord(content[0]) << 7
m = 1000003
mask = 2 ** hashbits - 1
for c in content:
x = ((x * m) ^ ord(c)) & mask
x ^= len(content)
if x == -1:
x = -2
return x | b1fafb3629854ebe3ddcaf702fe92bac3c2e17cd | 122,689 |
def ujoin(*args):
"""Join strings with the url seperator (/).
Note that will add a / where it's missing (as in between 'https://pypi.org' and 'project/'),
and only use one if two consecutive tokens use respectively end and start with a /
(as in 'project/' and '/pipoke/').
>>> ujoin('https://pypi.org', 'project/', '/pipoke/')
'https://pypi.org/project/pipoke/'
Extremal cases
>>> ujoin('https://pypi.org')
'https://pypi.org'
>>> ujoin('https://pypi.org/')
'https://pypi.org/'
>>> ujoin('')
''
>>> ujoin()
''
"""
if len(args) == 0 or len(args[0]) == 0:
return ''
return ((args[0][0] == '/') * '/' # prepend slash if first arg starts with it
+ '/'.join(x[(x[0] == '/'):(len(x) - (x[-1] == '/'))] for x in args)
+ (args[-1][-1] == '/') * '/') | f6a21ad3c365e9067e7a880e612b3882dfec705c | 122,691 |
import struct
def read_tfrecord(input):
""" Read a binary TFRecord from the given input stream, and return the raw
bytes. """
# Each TFRecord has the following format, we will only read the first 8
# bytes in order to fetch the `length`, and then assume the rest of the
# record looks correct.
#
# ```
# uint64 length
# uint32 masked_crc32_of_length
# byte data[length]
# uint32 masked_crc32_of_data
# ```
#
length_bytes = b''
while len(length_bytes) < 8:
buf = input.read(8 - len(length_bytes))
if not buf:
return None
length_bytes += buf
length = struct.unpack('<Q', length_bytes)[0] + 8
remaining = b''
while len(remaining) < length:
remaining += input.read(length - len(remaining))
return length_bytes + remaining | a0567f95bbdecc11678c2add07be31afdfcac383 | 122,704 |
def GetTRankineFromTFahrenheit(TFahrenheit: float) -> float:
"""
Utility function to convert temperature to degree Rankine (°R)
given temperature in degree Fahrenheit (°F).
Args:
TRankine: Temperature in degree Fahrenheit (°F)
Returns:
Temperature in degree Rankine (°R)
Notes:
Exact conversion.
"""
# Zero degree Fahrenheit (°F) expressed as degree Rankine (°R)
ZERO_FAHRENHEIT_AS_RANKINE = 459.67
TRankine = TFahrenheit + ZERO_FAHRENHEIT_AS_RANKINE
return TRankine | 20d54fd1e96d16a3d87aeff9ed8b9d3af6fc585d | 122,705 |
def get_trial_instance_name(experiment: str, trial_id: int) -> str:
"""Returns a unique instance name for each trial of an experiment."""
return 'r-%s-%d' % (experiment, trial_id) | 11a802b7f630611279d3a71d68e6a77f10034b59 | 122,712 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.