content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import numbers
def validate_float(datum, **kwargs):
"""
Check that the data value is a floating
point number or double precision.
conditional python types
(int, float, numbers.Real)
Parameters
----------
datum: Any
Data being validated
kwargs: Any
Unused kwargs
... | 8ced3fd09f35dc485cc9848eb0c6bcac1e3e047b | 182,332 |
def _generate_location(location, items, techs):
"""
Returns a dict for a given location. Dict keys for permitted technologies
are the only ones that don't start with '_'.
Args:
location : (str) name of the location
items : (AttrDict) location settings
techs : (list) list of avai... | 6e9f371379eeb8c827c2c8b26a3f4e442fc4b341 | 488,054 |
def get_single_rank(child_node):
"""
Extract MPI info from IPM XML child node (corresponding to one MPI rank)
child_node : xml.etree.ElementTree.Element
child of root node, i.e. ET.parse(filename).getroot()[i]
"""
i_regions = 6 # "regions" block under root.child
mpi_node = child_node[... | a3352761baf6daef95830953cb5a2cdb7b302f11 | 271,561 |
def _arg_no_mixin(num):
"""Return FindArgNoMixin for num."""
class FindArgNoMixin(object): # suppress(too-few-public-methods)
"""Mixin that provides generate() for finding args by number."""
def generate(self, # suppress(no-self-use)
sub,
other_transf... | f918a05183f265750490e62303173525134eb3ca | 634,961 |
import re
def _split_numeric_sortkey(
s, limit=10, reg=re.compile(r"[0-9][0-9]*\.?[0-9]*").search, join=" ".join
):
"""Separate numeric values from the string and convert to float, so
it can be used for human sorting. Also removes all extra whitespace."""
result = reg(s)
if not result or not limit... | 08023c180b74a066eaafe9726657e2c03d7d7c4c | 452,788 |
def add_shift_steps_unbalanced(
im_label_list_all, shift_step=0):
"""
Appends a fixed shift step to each large image (ROI)
Args:
im_label_list_all - list of tuples of [(impath, lblpath),]
Returns:
im_label_list_all but with an added element to each tuple (shift step)
"""
... | 63fc45bc14e54ec5af473ec955bd45602f3c7041 | 6,894 |
def parse_dhm_response(msg: str) -> int:
"""Parse server's DHM key exchange request
:param msg: server's DHMKE message
:return: number in the server's message
"""
return int(msg.split(':')[1]) | 065d16e8ae317d49ee2e29743b3004f8d79aadd2 | 587,132 |
def limit(value, limits):
"""
:param <float> value: value to limit
:param <list>/<tuple> limits: (min, max) limits to which restrict the value
:return <float>: value from within limits, if input value readily fits into the limits its left unchanged. If value exceeds limit on either boundary its set to t... | 55fb603edb478a26b238d7c90084e9c17c3113b8 | 6,485 |
from typing import Dict
from typing import Any
def keyword_format(**kwargs: Dict[str, Any]) -> str:
"""formats kwargs as comma joined key=value pairs.
Example:
>>> from torforce.utils.repr_utils import keyword_format
>>>
>>> keyword_format(a=1, b=2, c=3)
'a=1, b=2, c=3'
""... | f87677ffdb57eadca873ee52ea7321ee1c196bad | 408,488 |
from typing import Union
from typing import List
def remove_prefix_suffix(
x: str, prefix: Union[str, List[str]], suffix: Union[str, List[str]]
) -> str:
"""
Remove the prefix and suffix from a string,
prefix and suffix can be a string or a list of strings.
:param x: input string
:param prefix... | 17e44f24a361eb4f821221b2bef8b4c429f443a5 | 214,885 |
def __wrap_string_vales(_where_value):
"""This function wraps values going in the WHERE clause in single-quotes if they are not integers.
:param _where_value: The value to be evaluated and potentially wrapped in single-quotes
:returns: The value in int or string format
"""
try:
_where_value... | 7431cfd57caf3af9bc92ba8b559394136b21efe8 | 320,674 |
def is_float(value):
"""Check if value is a float."""
return isinstance(value, float) | a0b52166c42b6bceaffa18e8057f0408196acaab | 640,275 |
def mapify_iterable(iter_of_dict, field_name):
"""Convert an iterable of dicts into a big dict indexed by chosen field
I can't think of a better name. 'Tis catchy.
"""
acc = dict()
for item in iter_of_dict:
acc[item[field_name]] = item
return acc | e2b21fcd9bb311f467f81888becc2e8f1ad84444 | 79,852 |
def get_scope(scope):
"""Get scope for the labeler
Args:
scope (list): combination of issue_body, issue_comments, pull_requests or ["all"]
Returns:
list: list of scopes
"""
if "all" in scope:
scope = ["issue_body", "issue_comments", "pull_requests"]
return scop... | 43467bc2d4ab6838dfa9a264b92e871119ec7ce3 | 433,289 |
def job(priority, properties):
"""Creates a new job with the given priority and properties."""
return {
"priority": priority,
"properties": properties,
} | 2ad8130d5a6c4c36f3010329b15f4e9f3e826e26 | 158,583 |
def converts(*args):
""" A convenient decorator for the ModelConverter used to mark which
method should be used to convert which MongoEngine field.
"""
def _inner(func):
func._converter_for = frozenset(args)
return func
return _inner | cd999d76c896630d9afa87244a195029dec75281 | 58,715 |
def rmod(denom, result, num_range):
"""
Calculates the inverse of a mod operation.
The *denom* parameter specifies the denominator of the original mod (%)
operation. In this implementation, *denom* must be greater than 0. The
*result* parameter specifies the result of the mod operation. For obvious... | f3f62f70802d6a62c17e0feabbcb56790a8b43aa | 195,256 |
def redis_string_to_list(value, sep=','):
"""convert a comma (or sep) separated string to list.
Args:
value: byte, a redis string.
sep: string, which separator is used to separator items
Return:
a list of strings. Could be empty list if original string is None or
empty.
... | e81106294d1a87104e003ffe5827683c0c49036d | 561,694 |
import math
def calc_bragg_angle(d, energy_eV, n=1):
"""Calculate Bragg angle from the provided energy and d-spacing.
Args:
d (float): interplanar spacing (d-spacing) [A].
energy_eV (float): photon energy [eV].
n (int): number of diffraction peak.
Returns:
dict: the resul... | 2271fde28a30609dd41c1c3618132bfb368a122b | 470,384 |
def b_to_mb(byts: int, decimals: int = 1) -> float:
"""Convert a count of bytes into a count of megabytes.
Arguments:
byts {int} -- The count of bytes.
Keyword Arguments:
decimals {int} -- The number of decimal points to include in the count
of megabytes. (default: {1})
Re... | 412711c6db8e30701c3de5db251e9686cbf91aa2 | 510,067 |
def read_topology_file(data_path) -> str:
"""Reads the topology and returns the contents of the data file as a string."""
with open(data_path, "r") as f:
data_string = f.read()
return data_string | 6e3ea30cc11cb6f0e77ef3e3f34fe74bfbc59cfb | 469,808 |
def ocircle2(circle1, circle1_radius, circle2, circle2_radius):
"""
detects collision between two circles
"""
if (circle1.distance_to(circle2) <= (circle1_radius+circle2_radius)):
return True
else:
return False | a3811f83f99eeccedfea32bcbf99f1e518c644a4 | 80,604 |
import math
def obrien_fleming_cutoff(K, current_k, alpha):
""" Returns the cutoff value for O'Brien and Fleming's Test
Arguments:
K: An integer less than 10.
current_k: The current interm analysis number
alpha: The alpha level of the overall trial (0.01, 0.05 or 0.1).
Returns:
... | 411f91aa7d70265018f2e157cee22d31c90a0abb | 337,877 |
def expected(df, ts):
"""Modify *df* with the 'model' and 'scenario' name from *ts."""
return df.assign(model=ts.model, scenario=ts.scenario) | 742255d9b69d3ae27a0726402a46f8bdea525826 | 127,868 |
def readFile(fPath):
"""
Reads the Santander text file which is a bank statement file encoded in
ISO-8859-1.
:param fPath: The fPath to the input text file.
:return: A list containing all the lines of the file read correctly.
"""
with open(fPath, "r", encoding="ISO-8859-1") as inF:
... | 38af6361ff80557fd5cc1e5b0466394e6729b8c8 | 184,037 |
def factorial(n):
"""Calculate the factorial for N."""
t = 1
for i in range(1, n + 1):
t *= i
return t | 1cebbd139e1e7be177eb81455439913220775dc4 | 391,216 |
def calculate_curvature(fit, yeval, ym_per_pix):
"""
Calculate the curvature of the road given a fit to one
of the lane lines
"""
# Get the parameters of the fit
A = fit[0]
B = fit[1]
# calculate the curvature
curv = (1+(2*A*yeval*ym_per_pix+B)**2)**1.5/abs(2*A)
return curv | 20964502ca451408d3d5d4761321ad172e4b4989 | 229,819 |
from typing import Any
def index() -> Any:
"""Basic HTML response."""
return (
"<html>"
"<body style='padding: 10px;'>"
"<h1>Welcome to the API</h1>"
"<div>"
"Check the docs: <a href='/docs'>here</a>"
"</div>"
"</body>"
"</html>"
) | 03be914dc51ea9ae237ea71ff19daf0f5a0a936d | 211,164 |
def _create_signature_key(signature, rev):
"""Given a signature ID and revision, build the key we use to look up the signature in the redis db."""
return f'{signature}:{rev}' | d0c790bcd9a3ddfbbc45c5fc439513b310241685 | 245,260 |
def fst(xs):
"""Returns the first element from a list."""
return xs[0] | acbd8e6cacfd6b679621d14f5d959571dd4c1fdc | 487,314 |
import importlib
def import_modules(modules, path, attribute=None, fetch_attribute=False):
"""Import and return modules from a path if they have a given attribute
:param modules: Collection of modules to import or collection of tuples
containing (module, attribute).
:param path: impor... | 235734bdb293c1f4a8db8ceea47bdd447c38332e | 604,035 |
import warnings
def filt(signal, synapse, dt, axis=0, x0=None, copy=True):
"""Filter ``signal`` with ``synapse``.
.. note:: Deprecated in Nengo 2.1.0.
Use `.Synapse.filt` method instead.
"""
warnings.warn("Use ``synapse.filt`` instead", DeprecationWarning)
return synapse.filt(signal... | 8d2a8968599ebf70c23f0453a81427ce130a11c7 | 482,715 |
def filter_to_transform(filter_fn, df_name='atoms'):
"""Create transform function (which operates on dataset items) from filter function (which operates on dataframes). By default, applies filter_fn to ``atoms`` dataframe, but a different dataframe can be specified optionally.
:param filter_fn: Arbitrary filte... | a1435a495bcee19ee42985a653d6d8d18515a3e2 | 288,997 |
import math
def oersted_to_amps_per_meter(oersted):
"""Converts Oersted to \(\\frac{A}{m}\)"""
return (oersted*1e3)/(4*math.pi) | d964a86649da9fede19227f977af2384d6d84858 | 530,935 |
import re
def _version_from_tag(tag):
"""
Extracts the semver from the given tag (e.g: v0.1.0 -> 0.1.0)
:param tag:
:return:
"""
pattern = re.compile('v\d+.\d+.\d+')
if not pattern.match(tag):
raise Exception(f"{tag} is not valid semver")
return tag[1:] | f9364c189401673b9033ae38945b9e9c93adf005 | 516,672 |
def bitcount(num, length, value=1):
"""Counts the bits in num that are set to value (1 or 0, default 1)."""
one_count = 0
curr_length = length
while num and curr_length:
one_count += 1 & num
num >>= 1
curr_length -= 1
if value:
return one_count
else:
retur... | 6666c3a42a24316bd2952cc32477f0141807277d | 258,265 |
def ieplc(mapping):
"""
Returns the statistics for the number of inter-process logical communications (IePLC).
:param mapping: process-to-node mapping
:return: IePLC statistics
"""
weights = [d['weight'] for u, v, d in mapping.process_graph.edges(data=True)]
return sum(weights), sum(weights)... | 803846d2fdf3a1a696c53572a9019a18de6ebf9f | 560,238 |
def normalized_device_coordinates_to_image(image):
"""Map normalized value from [-1, 1] -> [0, 255].
"""
return (image + 1.0) * 127.5 | 39f244b32c18807f7eb87f529ebccf14adc895ad | 397,787 |
def keys_from_hash(hexdigest):
"""
Return a cache keys triple for a hash hexdigest string.
NOTE: since we use the first character and next two characters as directories, we
create at most 16 dir at the first level and 16 dir at the second level for each
first level directory for a maximum total of ... | ffa4a1685e92a1b9768ccf1efa206c4b7f8b0e85 | 617,115 |
def point_judge(center, bbox):
"""
用于将矩形框的边界按顺序排列
:param center: 矩形中心的坐标[x, y]
:param bbox: 矩形顶点坐标[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
:return: 矩形顶点坐标,依次是 左下, 右下, 左上, 右上
"""
left = []
right = []
for i in range(4):
if bbox[i][0] > center[0]: # 只要是x坐标比中心点坐标大,一定是右边
... | bb0d8eb6c4b056f8dc95493aa35c775045e0df90 | 597,058 |
def traffic_light(load):
"""Returns green, amber or red depending on the value of load."""
if load < 0.7:
return "green"
elif load < 0.9:
return "amber"
else:
return "red" | 5a0b3f29052ee52ec260899dbe817af15b042ede | 334,640 |
def create_multi_feedforward_parser(parser):
"""Add the multi-agent policy hyperparameters to the parser."""
parser.add_argument(
"--shared",
action="store_true",
help="whether to use a shared policy for all agents")
parser.add_argument(
"--maddpg",
action="store_true... | 3d3f16c077e37d775764626f8f8a43bb8351441e | 379,589 |
def get_aggregation_func(path, aggregation_functions):
"""Lookup aggregation function for path, if any.
Defaults to 'mean'.
:param path: Path to lookup
:type path: str
:param aggregation_functions: Aggregation function configuration
:type aggregation_functions: dict(<pattern>: <compiled regex>)... | c305e26e77fedd9b8b19845bb5fcd422be6f3542 | 441,154 |
def is_abs(field):
"""
Check if field is absolute value.
Parameters
----------
field : str
Field name.
Returns
-------
(bool, str)
Whether the field is absolute or not along with the basic field itself.
"""
if field[:4] == 'ABS(' and field[-1] == ')':
r... | 808d2e7d5531be1aba57fd68e8c17de3116b3649 | 327,732 |
def make_readable_pythonic(value: int) -> str:
"""Make readable time (pythonic).
Examples:
>>> assert make_readable(359999) == "99:59:59"
"""
return f"{value / 3600:02d}:{value / 60 % 60:02d}:{value % 60:02d}" | a091ef99b94cb2b4c3e0d657805a9e7b6418dd3a | 656,404 |
import math
def smaller2k(n):
"""
Returns power of 2 which is smaller than n. Handles negative numbers.
"""
if n == 0: return 0
if n < 0:
return -2**math.ceil(math.log2(-n))
else:
return 2**math.floor(math.log2(n)) | 0d0bbbf95cb22bf1b9ffb29012075534bcc9646d | 709,493 |
def _get_excluded_pids(exclude_file):
"""Reads the exclusion list and returns a
dict of lists of excluded patients"""
exclude_pids = {
'NCP': [],
'CP': [],
'Normal': []
}
with open(exclude_file, 'r') as f:
for line in f.readlines():
cls, pid = line.strip('... | 7c07615231896120373a1723db6901857502a68c | 209,596 |
import requests
def get_dnb_token(username, password, url="https://maxcvservices.dnb.com/rest/Authentication"):
"""Get a new authentication token.
See http://developer.dnb.com/docs/2.0/common/authentication-process
:param username: D&B username
:type username: str
:param password: D&B password... | b847c3e777811abc00aaf9fefce90784b90f6614 | 272,872 |
def runpath(tmp_path):
"""
Return a temporary runpath for testing. The path will not be automatically
removed after the test for easier investigation.
It takes a form like: /tmp/pytest-of-userid/pytest-151/test_sub_pub_unsub0
"""
return str(tmp_path) | df2d0caa4f4e834fb9f0577f143d79aa17649939 | 582,508 |
def _find_in_columncollection(columns, name):
""" Find a column in a column collection by name or _label"""
for col in columns:
if col.name == name or getattr(col, "_label", None) == name:
return col
return None | d7d72cb6b13a51b51770fcac13d8166c0a87ace3 | 371,008 |
from pathlib import Path
def input_custom_variables(string: str, dmvio_folder: str):
""" Replace the following environment variables in the given string.
if ${EVALPATH} is inside string it is replaced with the path to the evaltools (the folder where this file is
located).
${DMVIO_PATH} is replaced wit... | 0766874154192a885e49f50f14b5ab9038788ced | 18,588 |
from typing import AnyStr
def re_url_repl(sre) -> AnyStr:
"""Add space at the begging of the given URL.
Argument sre is the result of re.match() and re.search()"""
return ' ' + sre.group(0) | be0da8b1e2ce4fef1015671ec4c0729c1ab4c478 | 501,285 |
def _get_lines_from_file(filename, lines=None):
"""
If lines is None read the lines from the file with the filename filename.
Args:
filename (str): file to read lines from
lines (list/ None): list of lines
Returns:
list: list of lines
"""
if lines is None:
with ... | 4d4cf767bb5aaafc1ac2a396c1f4227e67268b99 | 336,870 |
import secrets
def secure_random(low: int, high: int) -> int:
"""Generates a random number from low (inclusive) to high (inclusive) using the secrets module.
DISCLAIMER: we are not security experts this may not be at all secure.
Parameters
----------
low : int
The inclusive lower bound
high : int
The incl... | 8bb90113ef83382e5224637713ca5c860f419d70 | 399,344 |
def cost(candidate, grid, distances_mx):
"""
Calculate the cost of a (candidate) solution.
Args:
candidate: The solution (frozenset).
grid: A list of MapBox objects.
distances_mx: A NumPy array.
Returns:
The solution's cost (float).
"""
c = sorted(candidate)
... | 636efedfb8b8751d09a55566c7d65223f85c36f8 | 157,264 |
def par2bool(s):
"""
Returns boolean (True, False) from given parameter.
Accepts booleans, strings or integers.
"""
if isinstance(s, str):
s = s.lower()
return s in ["true", "1", "on", True, 1] | 9f4d4c1e1de553b26cbfe0791d363fd00fc3b811 | 146,780 |
def get_last_id(file_name):
"""Retrieve last status ID from a file"""
try:
with open(file_name) as f:
last_id = int(f.read())
return last_id
except IOError:
return 0 | 0395cb0134c6c032a87b7370e0fcc47a3ab33619 | 283,908 |
def get_sql_dialect(session):
"""Return the active SqlAlchemy dialect.
Args:
session (object): the session to check for SqlAlchemy dialect
Returns:
str: name of the SqlAlchemy dialect
"""
return session.bind.dialect.name | f2de63abcfdf443893f230904ae72716b4a8fffa | 384,575 |
from typing import Dict
from typing import Any
import zlib
import base64
def _serialize_bytes(data: bytes, compress: bool = True) -> Dict[str, Any]:
"""Serialize binary data.
Args:
data: Data to be serialized.
compress: Whether to compress the serialized data.
Returns:
The serial... | c77236ef8d3e019d09d1c9de53627f87cb88b4b2 | 55,230 |
def visc(Tc, S, V = False):
"""
Calculate the viscosity of water or seawater
Reference:
Sharqawy et al. 2009
Thermophysical properties of seawater: a review of \
existing correlations and data
https://doi.org/10.5004/dwt.2010.1079
Eq 22 and Eq 23
viscosity... | b58ac72bd2454b05aa8facbc6132fc72456e13fe | 550,459 |
import hashlib
def checksum(fpath, hasher=None, asbytes=False):
"""Returns the checksum of the file at the given path as a hex string
(default) or as a bytes literal. Uses MD5 by default.
**Attribution**:
Based on code from
`Stack Overflow <https://stackoverflow.com/a/3431835/789078>`_."""
de... | 76d6ffb2c91a6706564cdbb269e256dae51e3139 | 224,112 |
from typing import Optional
import re
import click
def validate_version_string(ctx, param, value: Optional[str]) -> Optional[str]:
"""
Callback for click commands that checks that version string is valid
"""
if value is None:
return None
version_pattern = re.compile(r"\d+(?:\.\d+)+")
... | 22e084403cfa2ff72c003de53fe6b17c5dc03319 | 629,587 |
def max_sequence(arr):
"""Find the largest sum of any contiguous subarray."""
best_sum = 0 # or: float('-inf')
current_sum = 0
for x in arr:
current_sum = max(0, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum | d17f69534eda79649236438df7a1576ebbea789c | 78,330 |
def _transform(point, reference, projection):
"""Transform on point from local coords to a proj4 projection."""
lat, lon, altitude = reference.to_lla(point[0], point[1], point[2])
easting, northing = projection(lon, lat)
return [easting, northing, altitude] | 17dc2c1cc0ac1c0f01f09a790a8b9521d7d605ec | 467,617 |
from typing import List
import hashlib
def md5_hashsum(file_names: List[str]) -> str:
"""
Calculate md5 hash sum of files listed
Args:
file_names: list of file names
Returns:
hashsum string
"""
hash_md5 = hashlib.md5()
for file_name in file_names:
with open(file_n... | f3a5b854af1dd89c33d9f129a1998df572d330b0 | 404,733 |
def make_keyword_html(keywords):
"""This function makes a section of HTML code for a list of keywords.
Args:
keywords: A list of strings where each string is a keyword.
Returns:
A string containing HTML code for displaying keywords, for example:
'<strong>Ausgangswörter:</stro... | 71e35245ad7b2fe2c67f6a4c27d53374945089bd | 5,031 |
import math
def sigmoid(x):
"""Sigmoid function f(x)=1/(1+e^(-x))
Args:
x: float, input of sigmoid function
Returns:
y: float, function value
"""
# for x which is to large, the sigmoid returns 1
if x > 100:
return 1.0
# for x which is very small, the sigmoid r... | c65624784c34422ca41f14d118e3690990a05b47 | 688,818 |
from typing import List
def quick_sort(source) -> List[int]:
"""クイックソート. 計算量: O(n log n)"""
if len(source) <= 1:
return source
n = len(source)
# いったん中央の値を求める
median_value = source[n // 2]
# 分割する領域を作成
smalls, bigs, middles = [], [], []
# データソースの値を、3つの領域に振り分ける
for i in ra... | 0ce4eb05e8073d56e5134f5464b71317d0f0756b | 165,026 |
def smooth_avg(data: list[int]) -> list[int]:
"""
Generate a smoothed version of a data set where each point is replaced by the average of itself and immeadiately adjacent points
Args:
data (list[int]): A list of continuous data points
Returns:
list[int]: A smoother list of continuous ... | 593d1b43216229874c7fb7148392d7c2c922640a | 150,905 |
import re
def get_active_port(flows):
"""Find the active port name based on knowledge that down stream traffic is only output to the 'nic' interface.
Args:
flows (dict): Open flow details of the mux, result returned from function get_flows
Returns:
string or None: Name of the active port... | cfee2c86e0d22de37cf206249a91e565d328b875 | 81,394 |
from typing import Any
def to_str(obj: "Any") -> str:
"""
Convert any object to a string. This simply calls ``str`` on the object to produce a string
representation.
"""
return obj if isinstance(obj, str) else str(obj) | 3d069f3d444a454eda610729b37ca8c9a9c1dcf9 | 310,365 |
def getROI(img,x,y,ROI_size):
"""
crop square ROI from image with center x, y coordinate
Parameters:
-img: input image
-x,y: center coordinate of ROI
-ROI_size: size of ROI in pixel
Returns:
-imCrop: image of ROI
-x1,y1: coordinate of top left corner of the ROI
... | a501944996a786fa16cfc1e0c41168178c9837d5 | 480,464 |
def default_selection(random, population, args):
"""Return the population.
This function acts as a default selection scheme for an evolutionary
computation. It simply returns the entire population as having been
selected.
.. Arguments:
random -- the random number generator object
... | b1aedf4ae4835c745128ef0c93689821ee5a671a | 191,242 |
def extract_qa_bits(band_data, bit_location):
"""Get bit information from given position.
Args:
band_data (numpy.ma.masked_array) - The QA Raster Data
bit_location (int) - The band bit value
"""
return band_data & (1 << bit_location) | d911e75230e46f8571a0926b11c92a74e5da5496 | 270,363 |
def halt_after_time(time,at_node,node_data,max_time=100):
"""
Halts after a fixed duration of time.
"""
return time>=max_time | c1d2b82d5a8b2019be8ea845bf5b135ed7c5209f | 690,127 |
import copy
def revise_unanswerable(preds, na_probs, na_prob_thresh):
"""
Revise the predictions results and return a null string for unanswerable question
whose unanswerable probability above the threshold.
Parameters
----------
preds: dict
A dictionary of full prediction of spans
... | e8e6b008445421b3b226db56d8b61113d46d1ac5 | 238,943 |
def snake2camel(snake_str):
"""Convert a string from snake case to camel case."""
first, *others = snake_str.split('_')
return ''.join([first.lower(), *map(str.title, others)]) | 428cb49438bacb44f4fcfb05a3b0ea82cb5b65de | 141,028 |
import re
def countMultiQuestionMarks(text):
""" Count repetitions of question marks """
return len(re.findall(r"(\?)\1+", text)) | 5c0a1dd3838e414aae9a537add7fb120b29adf0b | 551,835 |
def join_host_port(host, port):
"""Joins a host and port"""
if ":" in host or "%" in host:
host = "[" + host + "]"
return "%s:%d" % (host, port) | bc1b7d76cbc61910402f1187c9723d6d23d03b3a | 601,280 |
def makeWennerArray(numElectrodes=32, id0=0):
"""
creates a schedule (A,B,M, N) for a Wenner array of length numElectrodes
"""
schedule=[]
for a in range(1, (numElectrodes+2)//3):
for k in range(0, numElectrodes-3*a):
schedule.append((k+id0, k+3*a+id0, k+1*a+id0, k+2*a+id0))
... | d95adba2679d812fed4b6d2a46b46a8a93868d34 | 512,526 |
def merge_var(*a):
"""Return a sorted list of the symbols in the arguments"""
result = []
for var in a:
for sym in var:
if not sym in result:
result.append(sym)
result.sort()
return result | aac4d02b63f3d02cf97e2f479c5c831b5174d208 | 170,868 |
def get_byte(buffer: bytes, offset: int) -> int:
"""
Gets the byte at the given offset.
:param buffer: The buffer to get from.
:param offset: The offset from the start of the buffer.
:return: The byte value.
"""
return buffer[offset] | ab37cc2dfa28669dca3e2b4482423bfad009994a | 396,352 |
def reverse_edge(edge):
"""Switches u and v in an edge tuple.
"""
reverse = list(edge)
reverse[0] = edge[1]
reverse[1] = edge[0]
return tuple(reverse) | 0690bac37188a38baf5cb56fe73dfff8187ff12a | 544,326 |
import requests
from bs4 import BeautifulSoup
def get_ansible_modules(url):
""" This function returns a dictionary which each key is the name of an ansible module and the value is its description """
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
span_list = soup.fin... | 453163c3fa01895ec8ed04331fd57c717f5454a9 | 575,265 |
def bytes_to_hex_str(bytes_hex: bytes, prefix="") -> str:
"""Convert bytes to hex string."""
return prefix + bytes_hex.hex() | 2ef7e57cbe0e96465543b966def31f5ce36bcbbe | 62,513 |
def solution(l):
"""
Solution 4 again passes all but the last test case. Try to speed things
up some using a dynamic programming-like approach.
This solution wound up passing all of the test cases -- the key here is to
uses a memorization/dynamic programming approach. A core component of this
... | 0387a39e6d087f381aece01db2718a9e90ba642c | 50,836 |
from string import punctuation
import re
def normalize_text(text, method='str'):
"""
Parameters
----------
text : str
method : {'str', 'regex'}, default 'str'
str: cleans digits and puntuations only ('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
regex : clean digits and all special chara... | 6baae1a8e352b4d2ec608fe3091d3f11a20f5d5d | 78,325 |
def isPrime(n: int)->bool:
"""
Give an Integer 'n'. Check if 'n' is Prime or Not
:param n:
:return: bool - True or False
A no. is prime if it is divisible only by 1 & itself.
1- is neither Prime nor Composite
We will use Naive approach.
. Check Divisibity of n with all numbers smaller tha... | 57eddd0aba0d53faa6ee1f4f5ff566a1c3b3ef85 | 63,172 |
def modify_pred_classes(y_pred_proba, y_pred_classes, thresh=.9):
"""
Modifies predicted classes to account for words not in command words set. Based on prediction confidence.
y_pred_proba: array of prediction probability output from Keras model
y_pred_classes: array of prediction classes from Keras mod... | 137b1435a2cebe0d7d2169b0d6f1904ba6606fda | 531,363 |
def unique_group(groups):
"""Find unique groups in list not including None."""
ugroups = set(groups)
ugroups -= set((None,))
ugroups = list(ugroups)
ugroups.sort()
return ugroups | ef147e4bbccf32f8e9d85954aced914f13b5ba06 | 253,147 |
import textwrap
def ftl(code):
"""Nicer indentation for FTL code.
The code returned by this function is meant to be compared against the
output of the FTL Serializer. The input code will be UTF8-decoded and will
end with a newline to match the output of the serializer.
"""
# The FTL Seriali... | 94b5b0aff62cf91afd1831db2e83a07fe4d197d2 | 488,167 |
def string_to_array(str_val, separator):
"""
Args
str_val : string value
separator : string separator
Return
List as splitted string by separator after stripping whitespaces from each element
"""
if not str_val:
return []
res = str_val.split(separator)
return ... | 925e369c578b8aeb4943e02f1371c53c846cf888 | 131,575 |
def ms_to_htk(ms_time):
"""
Convert time in ms to HTK (100 ns) units
"""
if type(ms_time)==type("string"):
ms_time = float(ms_time)
return int(ms_time * 10000.0) | fe3854dedddbed8ddb31cd4f5a8b8f77c9afb1e2 | 594,507 |
def flatten_processes_response(response):
"""Helper function to extract only pids and paths from the list processes command"""
return [{item['process_pid']: item['process_path']} for item in response] | bafa9b0368f78e69c6a40bf2234f585f24ec08c2 | 340,927 |
import requests
def read_in_s3_json(url):
"""Reads in a json file from S3 and returns a Python object"""
response = requests.get(url)
return response.json() | c697889a03d20b07b248e770e3ee828ce7e120a5 | 154,685 |
import math
def insertArrayShift(input_list, val):
"""Takes a list and a value and returns a new list with the value inserted at the middle index.
The input list is sliced into its left half, then the value is appended, then the right half is
added to the end.
"""
mid = math.ceil(len(input_list) /... | b6d5c5e583033a350ba7f8b4507244d66d504fc9 | 295,421 |
import math
def lrs_round(floatNumber):
"""
rounding floats to integers in a way that python 2 did
e.g. lrs_round(4.5) results in 5
:Parameters:
floatNumber: float to be rounded to integer
:Returns:
rounded number
"""
return floatNumber/abs(floatNumber) * math... | 6c4ce0035d2d14f016fd17df8153edc6a3527071 | 527,955 |
import logging
def metrics(time_dur, extremes, count, mean_hr, list_of_times,
time, voltages):
"""Create a dictionary with the specified metrics
Once all of the metrics have been determined, it is necessary to compile
them all together. This is done through the generation of a dictionary.
... | e9188d3b6119c44463a3403c570f6f1d567c50f7 | 31,196 |
from typing import Sequence
def timestamp_to_ms(groups: Sequence[str]):
"""
Convert groups from :data:`pysubs2.time.TIMESTAMP` match to milliseconds.
Example:
>>> timestamp_to_ms(TIMESTAMP.match("0:00:00.42").groups())
420
"""
h, m, s, frac = map(int, groups)
ms = fra... | 2928a0b14876e3b14ad8056bafbab5d540ead686 | 631,067 |
def _collect_providers(provider, *all_deps):
"""Collects the requested providers from the given list of deps."""
providers = []
for deps in all_deps:
for dep in deps:
if provider in dep:
providers.append(dep[provider])
return providers | 98855ea9f4997202b3462a941c06508c42f93c5d | 482,058 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.