content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def bson2bool(bval: bytes) -> bool:
"""Decode BSON Boolean as bool."""
return bool(ord(bval)) | dea3c0ba8b3c0078fca754b8ee71e8f2feb23c31 | 104,768 |
def part1(counts):
"""Part 1 asks us to add up the number of occurrences of any totally
safe ingredient.
Assumes `counts` has already had its unsafe ingredients discarded.
"""
return sum(counts.values()) | d83141780c26f50008d5a299cdea3e3cedb4bd4e | 104,772 |
def make_sgml_safe(s, reverse=False, keep_turn=True):
""" return a version of the string that can be put in an sgml document
This means changing angle brackets and ampersands to '-LAB-',
'-RAB-', and '-AMP-'. Needed for creating ``.name`` and
``.coref`` files.
If keep_turn is set, <TURN> in the i... | 8b7dedff97fe7e892be1c359164a94c8b415150b | 104,773 |
def pv_f(fv,r,n):
"""Objective: estimate present value
fv: fture value
r : discount period rate
n : number of periods
formula : fv/(1+r)**n
e.g.,
>>>pv_f(100,0.1,1)
90.9090909090909
>>>pv_f(r=0.1,fv=100,n=1)
... | 7496b8c5f30fed9afa02ef464c015cf1dde98b42 | 104,774 |
def cardValue(card):
"""Returns the value of a given card."""
if card[0] >= '2' and card[0] <= '9':
return int(card[0])
elif card[0] == 'T':
return 10
elif card[0] == 'J':
return 11
elif card[0] == 'Q':
return 12
elif card[0] == 'K':
return 13
elif car... | 56c3a4485d8f36b5616a853c842889c81568c9b5 | 104,777 |
import dis
import io
def distext(func):
"""
Like dis.dis, but returns the text
"""
file = io.StringIO()
dis.dis(func, file=file)
file.seek(0)
text = file.read()
return text | f2092df033052f4f37a0258aa47b8a5b3c6cc187 | 104,782 |
def cut_apply(variable, value, cut_type):
"""Create a function to apply a cut on a variable within the events dataframe.
Args:
variable (str): variable name to cut on
value (float): cut value
type (str): type (greater or lower)
Returns:
function: function to apply the cut t... | c5413980c0bc424f5d6aabc8d0861fe1860c2f7e | 104,783 |
def calc_risk_return_ratio(self):
"""
Calculates the return / risk ratio. Basically the
Sharpe ratio without factoring in the risk-free rate.
"""
return self.mean() / self.std() | a0728b5a7638b62ce4ab4d5c5723287f13b463bc | 104,785 |
import re
def extract_delex_placeholders(utt):
"""Extracts delexicalized placeholders from the utterance."""
pattern = '(name|near)_place'
return set(re.findall(pattern, utt)) | 341eb32b13726ea3ec7191c861814e9a5ff573f6 | 104,787 |
import torch
def depth_softargmin(cost, gamma):
"""Return a depth map with shape [N, 1, H, W].
Arguments:
cost: 3D cost volume tensor of shape [N, D, H, W]
gamma: discrete depth values [D]
Returns:
a depth map with shape [N, 1, H, W]
"""
return torch.sum(cost * gamma[:, N... | cf757a4d632368ed32e293d385f55f7c678022fc | 104,793 |
def IsValidFilename(filename):
"""IsValidFilename(filename) -> bool
Determines if the given filename is a valid filename. It is invalid if it
contains any of the characters found in the string return by
GetInvalidString().
arguments:
filename
string corresponding to th... | 82f8eb34b54bae194839e7555dc0044bb33c6fb7 | 104,795 |
import torch
def sphere_distance_torch(x1, x2, diag=False):
"""
This function computes the Riemannian distance between points on a sphere manifold.
Parameters
----------
:param x1: points on the sphere N1 x dim or b1 x ... x bk x N1 x dim
:param x2:... | 59075a9060714aaf1438c06242c28c786ff25f95 | 104,797 |
def capitalcase(string: str) -> str:
"""Capitalize the first letter of a string.
The casing of all the other letters will remain unaltered, e.g.,
``"fooBar"`` → ``"FooBar"``.
Args:
string (:obj:`str`):
The string to capitalize.
Returns:
:obj:`str`: The capitalized stri... | d21901bc8e492ef2cb000658da3edc4ae4999243 | 104,799 |
def dict_combine(*dict_list) -> dict:
"""Return the union of several dictionaries.
Uses the values from later dictionaries in the argument list when
duplicate keys are encountered.
In Python 3 this can simply be {**d1, **d2, ...}
but Python 2 does not support this dict unpacking syntax.
Returns... | 8d45bc362cb4aa505c47141173d907bc1ea7b15b | 104,800 |
import ipaddress
def is_same_subnet(addr1, addr2, subnet):
"""
Check whether two given addresses belong to the same subnet
"""
if ipaddress.ip_network((addr1, subnet), strict=False) == ipaddress.ip_network(
(addr2, subnet), strict=False
):
return True
return False | 742d173cd55999c37d8274a4fcacfd4b780f597e | 104,803 |
def _get_table_tags(dynamodb_client, table_arn):
"""
Extracts tags from the given DynamoDB table ARN
:param dynamodb_client: DynamoDB client to work with
:param table_arn: ARN of the source DynamoDB table
:return: List of Tags
"""
tags = []
kwargs = {}
while True:
response = ... | 5b6dc97c1c0ae109968f3c5fdd18508acb58e1e8 | 104,805 |
def launch_modes(launch_mode_conf):
"""Set of launch modes in which the tests will actually be run.
The value of this fixture depends on the value of `launch_mode_conf`:
- 'inprocess' -> {'inprocess'}
- 'subprocess' -> {'subprocess'}
- 'both' -> {'inprocess', 'subprocess'}
- None ... | ee9c37cc4d3a03f48ac58c3f9e0d5cf4ba49fd0d | 104,810 |
def convert_device_size(unformatted_size, units_to_covert_to):
"""
Convert a string representing a size to an int according to the given units
to convert to
Args:
unformatted_size (str): The size to convert (i.e, '1Gi'/'100Mi')
units_to_covert_to (str): The units to convert the size to ... | e173bf96c0bd095148b73991a256ecbd5a6a3949 | 104,814 |
def implemented(add_network=True, add_xgboost=True):
"""
Hard coded list of algorithms. Certain algorithms (such as e.g. keras)
are only sent in if flag allows it.
"""
algorithms = [
# Scikit-learn algorithms
('adaboost', 'MetaAdaBoostClassifier'),
('gbm', 'M... | 6ecdccadae3f3051ab040d3af45898d31ad5287d | 104,816 |
def build_kwargs_read(spec: dict, ext: str) -> dict:
"""Builds up kwargs for the Pandas read_* functions."""
col_arg_names = {'.parquet': 'columns',
'.xls': 'usecols',
'.xlsx': 'usecols',
'.csv': 'usecols'}
kwargs = {}
if 'columns' in list(s... | f691d964e9661407a26da6dfc8763d7c35ff658d | 104,817 |
def indiceStringToList(string):
"""
for example:
turns 1,2,63,7;5,2,986;305,3;
into [[1,2,63,7], [5,2,986], [305,3], []]
"""
output = [[int(char) for char in row.split(',') if char != ''] for row in string.split(';')]
return output | 3da7009df96266caa27fe3725110dcd8cab35903 | 104,821 |
import re
def remove_control_characters(text):
"""Removes all control characters
Control characters are not supported in XML 1.0
"""
return re.sub(r"[\x00-\x08\x0B-\x0C\x0E-\x1F]", "", text) if text else text | 75d0423ba51a3b6fd1ddd7e626cfc2a8978885d9 | 104,822 |
def is_merge(complete, part1, part2):
"""Checks if part1 & 2 can be merged into complete maintaining order
of characters."""
if len(part1) + len(part2) != len(complete):
return False
if part1 in complete:
ix = complete.find(part1)
remaining = complete[0:ix] + complete[ix + len(... | 2eb7d3884f205c6a1542aed43c2bad2f72be690e | 104,826 |
def GetClosestSupportedMotionBuilderVersion(Version: int):
"""
Get the closest MotionBuilder version that is supported
"""
if Version < 2018:
return 2018
if Version == 2021:
return 2022
return Version | 19b55726850ebc1c78b826c0b225e9fbc5108cef | 104,830 |
def format_terminal_output(result, stdout_key='stdout', stderr_key='stderr'):
"""
Output a formatted version of the terminal
output (std{out,err}), if the result contains
either.
:param stdout_key: where stdout is recorded
:param stderr_key: where stderr is recorded
:param result: result to... | fa94357cf22a570b8f86640c58d73cdc362bdfe7 | 104,835 |
def open_file(directory, name):
"""
Create a file object to interact with
w+ : create the file if it does not exist with a unique file name
:param directory:
:param name:
:return:
File Object
"""
return open(f'{directory}/{name}', "w+") | 7e68be543dbb28886be2eb066de0826050a42926 | 104,839 |
def template_class(this_object):
"""Dump the object's class."""
cls = this_object.__class__
return '<code>%s</code>' % str(cls) | fe54a334d20cc1811f51c8768e08ebb54b61db4b | 104,842 |
def worker_should_exit(message):
"""Should the worker receiving 'message' be terminated?"""
return message['should_exit'] | 485cca233544a2759453da73a451105cfc9f633e | 104,843 |
def replace_null(df, value, columns="*"):
"""
Replace nulls with specified value.
Parameters
----------
columns : optional list of column names to consider. Columns specified in subset that do not have
matching data type are ignored. For example, if value is a string, and subs... | 679fb4f84a3ccec7ec738f8ab43d5439f6e38668 | 104,845 |
from typing import List
import pickle
def load_pickle(dataset_dir: str) -> List:
"""Loading (reading) a pickle file
Parameters
----------
dataset_dir: str
It must be string file that shows the directory of the dataset.
Returns
-------
List
"""
assert isinstance(dataset_dir, str), "The dataset_... | e026258f59432e6e9dbe47e29f6224c22e407a14 | 104,850 |
def use_aws_kms_store(session, region, kmskeyid, access_id, secret,
encryption_pwd=None, old_encryption_pwd=None,
return_type=None, **kwargs):
"""
Sets the encryption password globally on the VPSA. This password is used
when enabling the encryption option for a v... | de478ab6633f0ab179511d24d2bc1e4b35408d4e | 104,851 |
import re
def rfc3339_datetime_re(anchor=True):
"""
Returns a regular expression for syntactic validation of ISO date-times, RFC-3339 date-times
to be precise.
>>> bool( rfc3339_datetime_re().match('2013-11-06T15:56:39Z') )
True
>>> bool( rfc3339_datetime_re().match('2013-11-06T15:56:39.123... | fabcd4259bc9d63b02fe1a322ed941d0559d9a75 | 104,853 |
def BVNeg(a):
""" Create a negation (two's complement) of a bit-vector
See also the __neg__ overload (unary - operator) for BitVecRef.
>>> x = BitVec('x', 32)
>>> BVNeg(x)
-x
"""
return -a | 6d888fadb1a93a06362cce11ba4b84f59492b0e6 | 104,857 |
import math
def VD_5111(jointType, boltHead, d, d3, lGew, Es, EBI):
"""
5.1.1.1 Axial Resilience
Joint type :
ESV - Tapped blind hole joint
DSV - Through bolted joint with nut
Bolt head :
socket
other
F : axial load
d : bolt diameter
d3 : bolt minor d... | dcdcb1fc67bf0857ae8e9724f5376b19fb6649cf | 104,859 |
def get_site_url(site):
"""Get a ``site`` URL
:param str site: the site to get URL for
:return: a valid site URL
:raise ValueError: when site is empty, or isn't well formatted
The ``site`` argument is checked: its scheme must be ``http`` or ``https``,
or a :exc:`ValueError` is raised.
If ... | c8a49fa57212e6b6819bb00e331f75b5ba0d0642 | 104,863 |
def pretty_print_seconds(seconds, n_labels=0, separator=" "):
"""
Converts a number of seconds to a readable time string.
Parameters
----------
seconds : float or int
number of seconds to represent, gets rounded with int()
n_labels : int
number of levels of label to show. For ex... | 19d6a38ad849ee8396093a987c1fb89f7165d987 | 104,866 |
def negate(func, name=None, doc=None):
"""Create a function which merely negates the result of 'func'.
N = func.negate(f)
N(x) # equivalent to... not f(x)
The name and docstring of the newly created function can be given through the 'name' and
'doc' arguments.
"""
def negate_func(... | a603e11e2c42658b42f1d1270f85b0d1cac5c579 | 104,868 |
def extract_file_name(file_path=None, include_suffix=True):
"""
Extract the file name with the file path string.
file_path: str
The file path
include_suffix: boolean
If True, includes full file name with suffix. If False returns the
file name without the suffix (e.g. "myfile.zip... | 0b544413dc085f5b54fee7af1dc982a23412ff92 | 104,870 |
def if_affirmative(needle: str):
"""
Returns True if needle is an affirmative string, False otherwise.
"""
assert isinstance(needle, str)
needle = needle.strip().lower()
return needle in {"true", "yes", "1", "ok"} | f1719d91240c486f879b9d2b10083957d53134e9 | 104,871 |
def get_vi_dtype(vi):
"""
This function returns value_info's data type
:param vi: graph.value_info
:return: graph.value_info.type.tensor_type.elem_type
"""
return vi.type.tensor_type.elem_type | e5139fe18eb7b0f2c91fd732dd6c361c5acb6ca4 | 104,875 |
def parse_course_info(course):
"""
Parse information of a course that is retrieved from Moodle.
:param course: A json statement, received as response on a Moodle call.
:type course: dict(str, list(dict(str, int)))
:return: The name of a course.
:rtype: str
"""
course_name = course['cour... | 67e27ffaf2d4a17556d9d2a6eb7185f7030f95c1 | 104,882 |
from typing import List
def score(
source_confidence: List[float], score: List[float], mentioned_feeds_count: int
) -> int:
"""
Function calculates final score for the IoC
Parameters:
source_confidence (List[float], 0..1) — a list `source_confindence` of all CTI feeds where the IoC h... | 0d268c5b23c8f82d1f507b2923acd41775d021aa | 104,884 |
import base64
import logging
def check_b64(b64):
""" Function checks if string is base64 and not empty
:param b64: base64 string
:raises TypeError: if input is not base64
:raises ValueError: if input is empty
"""
try:
if (base64.b64encode(base64.b64decode(b64)) == b64):
... | f3b451d3eeafaaef3473e5c6aa52731913866758 | 104,885 |
def get_srid(df):
"""Return srid from `df.crs`."""
if df.crs is not None:
return df.crs.to_epsg() or 0
return 0 | 63fd02217a9aee9e567a8d0decfe53bf23aad199 | 104,886 |
def merge_sort(arr):
"""
Returns the list 'arr' sorted in nondecreasing order in O(nlogn) time.
"""
r = len(arr)
if 1 < len(arr):
q = int(r/2)
L = merge_sort(arr[0:q])
R = merge_sort(arr[q:])
print(L,R)
i,j,k = 0,0,0
while i < len(L) and j < len(R):
... | 41678767f6daec2cd441e5f0cfb67ce21714cedd | 104,888 |
def _getWordCount(start, length, bits):
"""
Get the number of words that the requested
bits would occupy. We have to take into account
how many bits are in a word and the fact that the
number of requested bits can span multipe words.
"""
newStart = start % bits
newEnd = newStart + lengt... | a182c1fa89b3b95f1a654aeac8570eae42b88fa1 | 104,891 |
def _between_symbols(string, c1, c2):
"""Grab characters between symbols in a string.
Will return empty string if nothing is between c1 and c2."""
for char in [c1, c2]:
if char not in string:
raise ValueError("Couldn't find character {} in string {}".format(
char, string)... | 26e2d84eaaedcc4ca7b0b0a890368b6864994da0 | 104,902 |
from typing import Union
def _chunk_size_value(value: str) -> Union[int, str]:
"""Validate/cast chunk size."""
if value == "auto":
return value
else:
try:
size = int(value)
if size > 0 or size == -1:
return size
except ValueError:
... | 5cb64710c6bcdc1899ed8c6c3778533323860123 | 104,905 |
def tag_usage(err=''):
""" Prints the Usage() statement for the program """
m = '%s\n' %err
m += ' Default usage is to update 1 CR with a tag string:\n'
m += ' '
m += ' tagcr -t <CR> <tag value> \n'
return m | 89294ba569477dbf9f732bc25824018b07eee253 | 104,908 |
def __doc__(self):
"""Return the docstring for the class."""
cls_name = self.__class__.__name__
supercls_str, all_subclasses = {
"DictWithID": ["dict", ["MassSolution"]],
"OrderedDictWithID": ["OrderedDict", ["EnzymeDict"]],
}[cls_name]
return """A specialized {1} with an additional... | 8ef1c00bc8044d1a8cc421b9e1b7843a5ad60952 | 104,916 |
def expand(host):
""" expand the host (be it a single name or a dotted field).
It should be possible to run the unalias or expand in either order and get the
same result.
For example:
mongod --> mongod.0.public_ip
mongod.0 --> mongod.0.public_ip
mongod.0.publi... | 1d877973a2d44369b159e3cc7924b34d57f49772 | 104,918 |
def build_target_list(targets, target_ids, target_file):
"""
Build a list of the targets to be processed.
Parameters
----------
targets: str[]
List of the component names of possible targets.
target_ids: int[]
List of the numerical ids of the subset of targets to be processed.
... | 0c585bc0ee16c0634cf85ed96a99c40a00604f63 | 104,919 |
def velocity_from_acceleration(ax, ay, az, t):
"""
Estimate velocity from accelerometer readings.
Parameters
----------
ax : list or numpy array of floats
accelerometer x-axis data
ay : list or numpy array of floats
accelerometer y-axis data
az : list or numpy array of float... | 8433270bd6de0398e5bc92e98dfc6c7bb476fa1c | 104,921 |
def findStartPos(maze):
"""Returns the position of the start symbol in the grid."""
for row in range(maze.getHeight()):
for column in range(maze.getWidth()):
if maze[row][column] == 'S':
return(column, row)
return(-1, -1) | 620917486d2a3025c91e0ed3134c7e69cc1431a2 | 104,923 |
import six
def invert_dict(d, is_val_tuple=False, unique=True):
"""
Invert a dictionary by making its values keys and vice versa.
Parameters
----------
d : dict
The input dictionary.
is_val_tuple : bool
If True, the `d` values are tuples and new keys are the tuple items.
u... | 201c685dec5b177006b539330dbe2f9110197868 | 104,927 |
def any(iterable):
"""
any()
Purpose: Returns true if any element in the iterable evaluates to true otherwise, return false
Parameters: iterable [type=list,tuple]
Any item that can be iterated over
Returns: A boolean specifying whether any elements of the iterable evaluate ... | 5fbc793bd90055ea12156a54d551623dc20754d5 | 104,931 |
def _get_style_test_options(filename):
""" Returns (skip, ignores) for the specifies source file.
"""
skip = False
ignores = []
text = open(filename, 'rb').read().decode('utf-8')
# Iterate over lines
for i, line in enumerate(text.splitlines()):
if i > 20:
break
if... | 75ed451f8fd1ed1ab7c3d7f36cc2baace8bdb171 | 104,933 |
def cutoff_fn(good_mean: float, good_std: float, bad_mean: float, bad_std: float) -> float:
"""
Calculate the cutoff value
:param good_mean: Mean of the good samples
:param good_std: Standard deviation of the good samples
:param bad_mean: Mean of the bad samples
:param bad_std: Standard deviatio... | 569fcda1e0deeccc52b06d81b30f9f04b98eec95 | 104,936 |
def padding_method_2(data: bytes, pad_to: int) -> bytes:
"""
Pads data to n blocks using ISO/IEC 9797-1 Padding method 2
"""
data = data + bytes([0x80])
if len(data) % pad_to != 0:
data = data + bytes([0] * (pad_to - (len(data)) % pad_to))
return data | db6895d3662d52feebd9942341f03e5e6b83338a | 104,942 |
def vector_is_zero(vector_in, tol=10e-8):
""" Checks if the input vector is a zero vector.
:param vector_in: input vector
:type vector_in: list, tuple
:param tol: tolerance value
:type tol: float
:return: True if the input vector is zero, False otherwise
:rtype: bool
"""
if not isin... | dc541fa822363b68bda5518389301365dd71ff7a | 104,945 |
def get_mac_from_raw_query(request_raw_query: str):
"""
Get MAC address inside a matchbox "request raw query"
/path?<request_raw_query>
:param request_raw_query:
:return: mac address
"""
mac = ""
raw_query_list = request_raw_query.split("&")
for param in raw_query_list:
if "m... | 6e53d7bb80e46a730de39a1b5a74e0b89313713b | 104,946 |
def get_source_detail(sources):
"""
Iterate over source details from response and prepare RiskSense context.
:param sources: source details from response.
:return: List of source details which includes required fields from resp.
"""
return [{
'Name': source.get('name', ''),
'UuI... | 7d6bc9987a7dbd963e2ea29178d692afc6243ec4 | 104,947 |
def audio_fname(text):
"""
Function that converts a piece of text to the appropriate filename where
the audio mp3 will be cached.
"""
return f'audio_{hash(text)}.mp3' | e30e41f137cffc83aa4ee5723f13fb37b16a6984 | 104,950 |
def remove_headers(headers, name):
"""Remove all headers with name *name*.
The list is modified in-place and the updated list is returned.
"""
i = 0
name = name.lower()
for j in range(len(headers)):
if headers[j][0].lower() != name:
if i != j:
headers[i] = he... | 29302ea455f0f6c914523a5dd35be6b3d000ac29 | 104,951 |
import math
def computeProb(i, j, lf, le, lamb):
"""
Compute numerator
i,j : int
alignment of word i to j
lf, le: int
length of target sentence(lf) and source sentence(le)
lamb: float
Hyper parameters, currently set to be 4.0
"""
h = -1.0 * abs( float(j) / float(le) - float(i) / float(lf))
return mat... | cf430fa7dce5dd01ca7619cc578dc95f9a6c899b | 104,955 |
def find_first(data):
"""
>>> find_first([[0, 0], [0, 1]])
(1, 1)
>>> find_first([[0, 0], [0, 0]])
"""
for y_index, y_value in enumerate(data):
for x_index, x_value in enumerate(y_value):
if x_value == 1:
return (x_index, y_index)
return None | f5d2315f3249cb8a787e19009f481b55c56d65df | 104,960 |
import stat
def filetype(mode):
"""
Returns "dir" or "file" according to what type path is.
@param mode: file mode from "stat" command.
"""
if stat.S_ISLNK(mode):
return "link"
elif stat.S_ISDIR(mode):
return "dir"
elif stat.S_ISREG(mode):
return "file"
else:
return "unknown" | 95fb3d4d46a07ddf3fb5968f1892807603944635 | 104,962 |
def iterative_fibonacci(i):
""" Classic iterative implementation of the fibonacci function, where
recursive_fibonacci(i) returns the i-th element of the sequence.
time: O(n)
space: O(n)
"""
if i == 0:
return 0
last = 0
current = 1
for _ in range(1, i):
temp = current... | de38deaeb991b68eb2eec68c7cd8472575e4178f | 104,968 |
import importlib
def getModelDesc(model=None):
"""Returns a brief description of the selected model.
Parameters
----------
model : str
Name of the model to get the description of
Returns
-------
A string with the description of the model
"""
if model is No... | c75946da8d0b10949d77b007cbc8a30d0491837a | 104,970 |
def getCorrespondingWindow(index, windows):
"""
Finds the corresponding window to the each predicted anomaly
:param index (type:int): index of predicted anomaly point
:param windows (type list of tuples (start, end)): list of true anomaly windows
:return (typ: tuple): anomaly window if point lies in... | ab40559e6ed71e55a7ccd6a4cd82f66063dd383b | 104,972 |
def path(key, *path):
"""
Generate a path for redis.
"""
return ':'.join([key] + list(path)) | 632e6a046a48170ffeb770e68203b3f37fec86fe | 104,974 |
def make_coordinate(x_coord, y_coord):
""" Make a coordinate dictionary"""
return \
{
"x": x_coord,
"y": y_coord
} | d37ff106aadb6d4e4733437debf41f0a2b025890 | 104,978 |
import sqlite3
import collections
import itertools
def get_menu(campuses, dates):
"""
Retrieve the menu on the given dates for the given campuses from the database.
Args:
campuses: The campuses for which the menu is retrieved.
dates: The dates for which the menu is retrieved.
Returns... | 3ff78902218fc3816c0b97afbb6679c61e1af6e9 | 104,979 |
def create_activity(conn, activity):
"""
Create a new activity
:param conn:
:param activity:
:return: project id
"""
sql = ''' INSERT INTO Activities (activity, time_goal, time_done, user_id)
VALUES(?,?,?,?) '''
cur = conn.cursor()
cur.execute(sql, activity)
retur... | 74ee141cbeab8d60d5b8ddbc76a425f9adb3daa8 | 104,983 |
def _correct_searchqa_score(x, dataset):
"""Method to correct for deleted datapoints in the sets.
Args:
x: number to correct
dataset: string that identifies the correction to make
Returns:
The rescaled score x.
Raises:
ValueError: if dataset is none of train, dev, test.
"""
if dataset == ... | d92b992f98116d069456d7a9f34b2a95d93b5880 | 104,986 |
def istuple(x):
"""Is an object a python tuple?"""
return isinstance(x, tuple) | ffd87a4e01bd689358e444aca01be72cef4bb720 | 104,987 |
def tcpdump_capture(device,
interface,
port=None,
capture_file='pkt_capture.pcap',
filters=None):
"""Capture network traffic using tcpdump.
Note: This function will keep capturing until you Kill tcpdump.
The kill_process method ... | 0badc3c88ac9d6e7b2215b62e071ea34b1bd61e6 | 104,989 |
def get_standard_write(filename: str) -> str:
"""Return standard code for exec().writing."""
return f"""\n\nwith open("{filename}", "w") as dbfile:\n json.dump(data, dbfile)\n\n""" | 669c2263d84975b57dbb481338dc1179961a743c | 104,990 |
def get_page_list(paginator, page=1):
"""
Generate a list of pages used choose from to jump quickly to a page
This generates a list that shows:
* if near the start/end, up to 10 pages from the start/end
* if in the middle first two and last two pages in addition to the
+/- 5 from ... | 1637d9f7acd2140b45ad0633c306d883197e2aa2 | 104,991 |
def get_sum_rois_volume(list_results_row:list) -> float:
"""sum all ROIs volume
Args:
liste ([list]): [List of every ROI results row from CSV file]
Returns:
[float]: [Return the sum of ROIs volume]
"""
volume = float(0)
for i in range(len(list_results_row)):
volume += f... | 6783724f694182bc23dfc59cd201941318695ac6 | 104,999 |
def _resolveDotSegments(path):
"""
Normalise the URL path by resolving segments of '.' and '..'.
@param path: list of path segments
@see: RFC 3986 section 5.2.4, Remove Dot Segments
@return: a new L{list} of path segments with the '.' and '..' elements
removed and resolved.
"""
se... | 7aea457fbbc1485a3c0ed81b13a89e6c3d9fff8c | 105,000 |
def divup(a, b):
"""Divides a by b and rounds up to the nearest integer."""
return (a + b - 1) // b | 7ffd592f4caf53b806c1befaae792bad484fcea6 | 105,001 |
def mjd(year, month, day, hour=0, minute=0, second=0):
"""
Calculate the modified Julian date from an ordinary date and time.
Notes
-----
The formulas are taken from Wikipedia.
Example
-------
>>> mjd(2000, 1, 1)
51544.0
"""
a = (14 - month) // 12
y = year + 4800 - a
... | 10a255f96fdedd5ad2f659211348a03fc88bd7bf | 105,003 |
def get_text_from_response(response):
"""requests Response's text property automatically uses the default encoding to convert it to unicode
However, sometimes it falls back to ISO-8859-1, which is not appropriate. This method checks whether it
could be interpreted as UTF-8. If it is, it uses it. Otherwise, ... | ee8cd4f9a2dd479020db8b830bc9ac80be79fbbd | 105,004 |
def add_single(arr, val):
""" Return sum of array and scalar. """
return [i + val for i in arr] | f089514decec318d8df8954d423d90c2d5b63e0b | 105,005 |
import re
def load_eval_list_lines(path):
"""
Load and eval lines from given path, each line is a list that will be convert into a string.
Args:
path (str): Dataset file path
Returns:
list: List of lines
"""
lines = []
with open(path, encoding='utf-8') as f:
for ... | 29e72d2b39c7bfa8c6330038d49d659da3170cfd | 105,009 |
def conv(ip):
"""
Converts IP integer to human readable IP address
:param ip: integer IP Address in int form
:return: string IP Address
"""
return "%d.%d.%d.%d" % (
(ip >> 24) & 255,
(ip >> 16) & 255,
(ip >> 8) & 255,
ip & 255,
) | 6033378c1ab7175343ae3703eafda0d08f1af1b5 | 105,010 |
def get_env_name(model_dir):
"""
Args:
model_dir: str. Will be in the format model-name/env-name_run-date and might end in "/"
Return:
str with the env name as it appears in gym
"""
len_date = 20
if model_dir[-1] == "/":
len_date += 1
env = model_dir[:-20]
s = env.find("/")
env = env[s+1... | c6ec5ab541d4cdb1ce977e7db35e5bf1fb0f4940 | 105,014 |
def create_demag_params(atol, rtol, maxiter):
"""
Helper function to create a dictionary with the given
demag tolerances and maximum iterations. This can be
directly passed to the Demag class in order to set
these parameters.
"""
demag_params = {
'absolute_tolerance': atol,
'... | 9de9db696f5f022569ab31d8fe069e34b2d7dc08 | 105,016 |
import re
def strip_stars(doc_comment):
"""
Version of jsdoc.strip_stars which always removes 1 space after * if
one is available.
"""
return re.sub('\n\s*?\*[\t ]?', '\n', doc_comment[3:-2]).strip() | 29c490a972760f92465845c3f59a5e35a6a39fe0 | 105,022 |
def create_shot_coordinates(df_events):
"""
This function creates shot coordinates (estimates) from the Wyscout tags
Args:
df_events (pd.DataFrame): Wyscout event dataframe
Returns:
pd.DataFrame: Wyscout event dataframe with end coordinates for shots
"""
goal_center_idx = (
df_... | 7f1f9368c59e32f2d83696113318f4f6ef2fa146 | 105,025 |
def decimal_to_any(num: int, base: int) -> str:
"""
Convert a positive integer to another base as str.
>>> decimal_to_any(0, 2)
'0'
>>> decimal_to_any(5, 4)
'11'
>>> decimal_to_any(20, 3)
'202'
>>> decimal_to_any(58, 16)
'3A'
>>> decim... | 47aace04b2f0b8e6d3a511e4063550ac55533074 | 105,028 |
def get_id(document):
"""
Parameters
----------
document: dict
A covid article
Returns
-------
str
Unique Id of the article
Examples
--------
>>> get_id(toy_covid_article)
'thisismyid'
"""
return document.get('paper_id') | 07f8eb3113f93d98ffdca6230e8eb37eb7b4aab1 | 105,029 |
import hashlib
import six
def create_hash(inp, l=10, algo="sha256", to_int=False):
"""
Takes an arbitrary input *inp* and creates a hexadecimal string hash based on an algorithm
*algo*. For valid algorithms, see python's hashlib. *l* corresponds to the maximum length of the
returned hash and is limite... | 6fe468e8cb8dee587d804f207bd76080731f37df | 105,030 |
def check_obj(obj_out):
"""
Check that there are a minimum amount of stuff written into the .obj. If not, then the ISO level is wrong.
(obj_out is a string containing the output of emmaptosurf)
"""
for line in obj_out.split("\n"):
linesplit = line.split(" ")
if linesplit[0] == "Wrote... | 82da202b4f7ce6a684bf9a9daafba95c561eb865 | 105,031 |
def add(data,r=0.0,i=0.0,c=0.0):
"""
Add Constant
Parameters:
* data Array of spectral data.
* r Constant to add to read channel.
* i Constant to add to imaginary channel.
* c Constant to add to both channels.
"""
data.real = data.real + r + c
data.imag = ... | af4934c72aec0dfe25742494fcec0a7543ec785c | 105,034 |
def other_types_on_host(host_state, instance_type_id):
"""Tests for overlap between a host_state's instances and an
instance_type_id.
Returns True if there are any instances in the host_state whose
instance_type_id is different than the supplied instance_type_id value.
"""
host_instances = host... | 776cc2eabd35fc4eabc4d2a0842f90bd767b5de6 | 105,035 |
def cost(dic, PhoneCost, EmailCost, OverbondCost):
"""Calculates the cost by summing over all connections in the dictionary dic.
Note that this time only one of the vertices knows of the connection to
avoid redundancy.
"""
price = [OverbondCost, PhoneCost, EmailCost]
result = 0.0
for a... | ed70b1a30a4d84701a0c5e3fbf6e0fb927f43321 | 105,039 |
def traverse(dictionary, keys, default=None):
"""Find a deep value in a dictionary
Args:
dictionary (dict): The event port.
keys (tuple|str): The hiearchical list of keys.
default: The default value if not found.
Returns:
The value, or `default` if not found.
"""
i... | a9caa26eee447a0e410595b885828d49c355f3f5 | 105,044 |
def common_event_topics(num_topics=10, num_contracts=10, only_sigs=False):
"""This query aggregates the most common event signatures and their most common contract
addresses.
Usage:
es.search('ethereum', 'log', body=common_event_topics())
Params:
num_topics (int): maximum number of top... | f55d15847252512f1568340410dccb1f73425950 | 105,045 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.