content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remove_trailing_colon(id_value: str) -> str:
"""
Remove a trailing colon of id. It is need, for example, to search the last version of record.
:param id_value: Id value.
:return: Id value with no trailing colon.
"""
return id_value[:-1] if id_value.endswith(":") else id_value | 2808d6512797b2979492f65966bcffc4928f088d | 588,816 |
def count_pattern_in_list(lst, seq):
"""
Counts a specific pattern of objects within a list.
Usage:
count_pattern_in_list([1,0,1,2,0,1], [0,1]) = 2
"""
count = 0
len_seq = len(seq)
upper_bound = len(lst) - len_seq + 1
for i in range(upper_bound):
if lst[i:i + len_seq] ==... | f087d03c85019744c743dbd4aac257cc7aa51713 | 588,818 |
def get_taps(yaml):
"""Return a list of all taps."""
ret = []
if "taps" in yaml:
for ifname, _iface in yaml["taps"].items():
ret.append(ifname)
return ret | 0daf3efe09eb33f75dca26f2b9fd75b4f3e7e54c | 588,820 |
def is_tty(stream): # taken from catkin_tools/common.py # pragma: no cover
"""Returns True if the given stream is a tty, else False"""
return hasattr(stream, 'isatty') and stream.isatty() | dee3bb24aa2e7cd39fcbf0d63051c9c5a5980b52 | 588,826 |
def d4(x):
"""Evaluate the estimate 4*x**3+3*x**2+2*x+1."""
return ((4*x+3)*x+2)*x+1 | cb1391d2dc8f5241f4f3a2651210396d4c40ae11 | 588,829 |
from bs4 import BeautifulSoup
def soup(s, parser="lxml"):
"""
A wrapper function to handle BeautifulSoup defaults.
"""
return BeautifulSoup(s, parser) | 6c74f6f0d706b81ad9100fd522abf69d5c163636 | 588,835 |
import math
def angle_vector_2D(v1, v2):
"""
Return angle between two 2D vectors (i.e. use only x and y coordinate values)
Angle (from v1 to v2, positive angle of rotation) is in the range -pi < x < pi.
"""
dot = v1[0] * v2[0] + v1[1] * v2[1] # dot product
det = v1[0] * v2[1] - v1[1] * v2[0] #... | 33addb9c0cacbc0a391e4c6267af9dce486c46be | 588,839 |
import math
def ipart(x):
"""Floors x."""
return math.floor(x) | 313c822e7ecea506ee56c3a3f7d5262a0b6221ed | 588,841 |
def _mondict(n_hem=True):
"""
Get a dictionary of season and month string.
Parameters
----------
n_hem : Boolean
Default True. Indicates hemisphere of parcel launch and thus
actual season.
Returns
-------
season_month_dict : dictionary
Dictionary keyed by month... | e3b24bbfbc5e4ac9d25e47b94ff7f33440c331a2 | 588,842 |
def file_replace(filepath: str, old_string: str, new_string: str) -> bool:
"""
Replace all instances of old string in file with new string
Returns true if any updates were made, false otherwise
"""
if old_string == new_string:
return False
with open(filepath, 'r') as infile:
co... | 2765661b7efdd75bc2da128f589c7bca6d11e6aa | 588,843 |
def split_len(seq, length):
""" Returns a list containing the elements of seq, split into length-long chunks. """
return [seq[i:i + length] for i in range(0, len(seq), length)] | e15973c469235b2994e6696d7408d2e853e21d6d | 588,855 |
def provider_names(providers):
"""
Returns the names of the :providers:, separated by commas.
"""
return ", ".join([p.provider_name for p in providers]) | c89f7dc5c6d976753f4f44398d4fd906c32ec56a | 588,862 |
from pathlib import Path
def read_file(filename):
"""Read a text file and return its contents."""
project_home = Path(__file__).parent.resolve()
file_path = project_home / filename
return file_path.read_text(encoding="utf-8") | a17f99cd438a182c25e466e0f5c36af262dca5eb | 588,863 |
import ipaddress
def is_ipv6(ip):
"""
Returns a bool telling if the value passed to it was a valid IPv6 address
"""
try:
return ipaddress.ip_address(ip).version == 6
except ValueError:
return False | a9f4d72f7036b31b83d3caca1a21da0d3c6ce97d | 588,866 |
def validate_ticket_date(date):
"""
validate that the date is in YYYYMMDD format
:param date: date of the ticket
:return: True if valid, False otherwise
"""
year = date[0:4]
month = date[4:6]
#Changed day to accept end of string in format: "00"
day = date[6:8]
if len(date) != 8:
return False
if not date.is... | 79b5d0873d4ee9ac2d387f4e98c4b72090e47b25 | 588,868 |
def accuracy_score(y_true, y_pred):
"""Accuracy classification score.
In multilabel classification, this function computes subset accuracy:
the set of labels predicted for a sample must *exactly* match the
corresponding set of labels in y_true.
Args:
y_true : 2d array. Ground truth (correct)... | 80d50687529e0523f75cb1f6955fe6449e97d35c | 588,872 |
def render_graph(frames, canvas, frame=None):
"""
render the graph of intesities against time
Args:
frames ([FrameStats]): the frame statistics
canvas (mapplotlib.FigureCanvas): the canvas
frame (int): the frame number, if valid provided frame line will be added
... | 2391b73b4b07e8bb1811d18e5dfa6271a2611769 | 588,874 |
def numOfClasses (theDictionary):
"""Returns the number of classes a student is taking.
.. note::
Does not couple labs to classes. For instance, BIOL 150 and BIOL
150L are counted as separate classes.
:param dict[str, int] theDictionary: The student's class information
with the cla... | 14e4f32f9cfb26d52b040178582ec0d79b8cfb60 | 588,876 |
def rank(vals, x, norm=False, sort=True):
"""
Returns the rank of x in list vals
rank(x) = i if vals[i-1] <= x < vals[i]
x -- value to rank within values
vals -- list of values to compute the rank of
sort -- if True, vals will be sorted first
norm -- if True, return normalized ranks (i.e... | 72421e2b3f8f030891ec0235ee996ff24f4ba39b | 588,877 |
def _get_all_drivers(factory):
"""Get all drivers for `factory` as a dict name -> driver object."""
return {name: factory[name].obj for name in factory.names} | 1d9fa715abe38cc128f1b6d7b9bc15f65d164830 | 588,881 |
def list_from_range(k=None):
"""Return a list based of ints where k can be a range string or an int."""
if not k:
return []
if isinstance(k, int):
return [k]
bounds = [int(i) for i in k.split("-")]
return list(range(bounds[0], bounds[1])) | f8b9dfebad8f1232adb5f5157e5ae49ebf80d8df | 588,889 |
def classify_label_set(labelsets, labelset, lskey=None):
"""Add labels to a labelset or create a new set."""
found = False
for lsk in sorted(labelsets.keys()):
lsv = labelsets[lsk]
for l in labelset:
if l in lsv:
labelsets[lsk] = lsv | labelset
fo... | f5fca29ba24b6c8622c91ff465761ac2f47e7423 | 588,890 |
import ssl
def default_ssl_context() -> ssl.SSLContext:
"""Creates an SSL context suitable for use with HTTP/2. See
https://tools.ietf.org/html/rfc7540#section-9.2 for what this entails.
Specifically, we are interested in these points:
§ 9.2: Implementations of HTTP/2 MUST use TLS version 1.2 or ... | 4d1d46fef9f2350f2a10add1890332fcdb66f0ea | 588,891 |
import csv
def GetLinesFromDrivingLogs(dataPath, skipHeader=False):
"""
Returns the lines from a driving log with base directory `dataPath`.
If the file include headers, pass `skipHeader=True`.
"""
lines = []
with open(dataPath + '/driving_log.csv') as csvFile:
reader = csv.reader(csvF... | 5423e52f5e658bb3f3d590780484ada286fbd77b | 588,898 |
def normalized_frequency(f: float, sampling_freq: float) -> float:
"""
Returns a normalized frequency:
Args:
f: frequency :math:`f`
sampling_freq: sampling frequency :math:`f_s`
Returns:
normalized frequency
.. math::
f_n = f / (f_s / 2)
Princ... | e801036d24d7f447e79f434940d5550f564b2a0a | 588,902 |
from datetime import datetime
def acceptConnection(serverSocket):
"""Function to handle accepting new connections"""
conn, addr = serverSocket.accept()
print("[{}] Connection from {}".format(datetime.now(), addr))
conn.settimeout(1)
return conn, addr | 1858eeb9bb47b7dfd38896b206977bf0ea8f5ebe | 588,907 |
def get_key1(item):
"""
Args:
A tuple of 2 objects, where the second is an integer
returns:
The value of the second member of the tuple,
plus a value between 0 and 0.01 obtained from the first
member of the tuple. This second term is only useful
to break ties in a de... | 03cfe121b314278a6313713cf15a4200847304bc | 588,910 |
def phone_censor(value):
"""Censor phone number"""
phone = str(value)
prefix = phone[:3]
postfix = phone[-2:]
censor = '{}*****{}'.format(prefix, postfix)
return censor | f00020d8266640d397746ad3648f9a6d434b3920 | 588,911 |
def wraps_class(orig, suffix):
"""
Rename the decorated class to match the ``orig`` with a suffix added.
:see: `functools.wraps`
"""
def decorator(cls):
cls.__name__ = orig.__name__ + suffix
cls.__qualname__ = orig.__qualname__ + suffix
cls.__module__ = orig.__module__
... | 3293c90db7cf066b43a841a0139ef146ed326697 | 588,912 |
import re
def _short_name(long_name):
"""
Returns a short name for the branch name if found
"""
if not long_name:
return None
regexes = [
'(?:encd|sno)-[0-9]+', # Demos
'^v[0-9]+rc[0-9]+', # RCs
'^v[0-9]+x[0-9]+', # Prod, Test
]
result = long_name
... | 378a80cd18e09562bf9f4df4b8f1873f659de0b9 | 588,915 |
def diagonal_flip(img):
"""
Function to flip image diagonally
"""
return img[::-1, ::-1] | a10558434e5ff65ed278cbbb3767a2fc420f28db | 588,918 |
def ensemble_mean(ds, ensemble_dim="member"):
"""Return the ensemble mean of the input array
Parameters
----------
ds : xarray Dataset
Array to take the ensemble mean of
ensemble_dim : str, optional
The name of the ensemble dimension
"""
return ds.mean(ensemble_dim) | 8edcf1d77f0fc73d31b9a4b421b110fc6e45ba35 | 588,920 |
def uniques(some_list):
"""
Get unique values of a list
"""
new_list = []
for item in some_list:
if item not in new_list:
new_list.append(item)
return new_list | 8912948346a4f231018b8b72d758d9a1141002a5 | 588,922 |
def convert_to_text(batch, lengths, dico, lang_id, params):
"""
Convert a batch of sentences to a list of text sentences.
"""
batch = batch.cpu().numpy()
lengths = lengths.cpu().numpy()
bos_index = params.bos_index[lang_id]
slen, bs = batch.shape
assert lengths.max() == slen and lengths... | 46b505af1d73c080dce3a0ab2712f27a175a498b | 588,923 |
import wave
def wave_obj(filename):
""" Opens a given .wav file
:param filename: The name of the file to open.
:return: The wave object.
"""
return wave.open(filename, "rb") | 40eb91c5e8bf8ba72d4ef585f6cd281e23756b36 | 588,924 |
def range_splits(tensor, split_ranges, dim):
"""Splits the tensor according to chunks of split_ranges.
Arguments:
tensor (Tensor): tensor to split.
split_ranges (list(tuples(int,int))): sizes of chunks (start,end).
dim (int): dimension along which to split the tensor.
"""
return... | 67de1dd67a49e953dfc259031d852649be0e6343 | 588,925 |
def get_square(x, y, board):
"""
This function takes a board and returns the value at that square(x,y).
"""
return board[x][y] | 435cb856cbc7baca8d7e54f5df7971ff0afb8311 | 588,926 |
def int_to_page_alpha(pageno, base):
"""return uppercase alphabetic page numbers for PAGENO starting at BASE (a or A).
Adobe defines them as A to Z, then AA to ZZ, and so on.
Yes, that is somewhat wacky."""
(div, mod) = divmod( pageno-1, 26)
c = chr(mod + ord(base))
return c * (div+1) | 7e9585a65954d80678ff3302a4bb068273c660af | 588,928 |
def generate400response(error: str) -> dict:
""" A function that generates a '400-Bad Request' message and returns it as a dict """
return {
"status": 400,
"message": "Bad Request",
"error": error
} | 96915fc8a6ef5a092102f875560b230688c053c1 | 588,932 |
def get_stopwords(filename):
"""Read stopword list from file.
Assumes that the list is defined as a newline separated words. It is
a utility in case you'd like to provide your own stopwords list.
Assumes encoding ``utf8``.
:param filename: Name of the file containing stopword list.
:type filen... | 34c35c84d3dddeb4d262d4c3fea229d586464fa2 | 588,934 |
def join_string_lists(**kwargs) -> dict:
"""Convert named lists of strings to one dict with comma-separated strings.
:param kwargs: Lists of strings
:return: Converted dict.
Example:
>>> join_string_lists(foo=["a", "b", "c"], bar=["a", "b"], foobar=None)
{"foo": "a,b,c", "bar": "a,b"}
"""... | c5c93c0335ccedf37edf0d202a1fed4f5b7d0243 | 588,936 |
def is_int(msg):
"""Method used to check whether the given message is an integer
return int or raises an exception if message is not an integer
"""
try:
return int(msg)
except ValueError:
raise Exception("Unexpected message format (expected an integer). Message: %s" % (msg)) | 18861162c55789c8c64c4d4f4611c61927123966 | 588,938 |
def getH8ProdFile(thisTime, product, *,
pLe='L2', version='021',
pixelNum='02401', lineNum='02401',
area='FLDK'):
"""
get the Himawari-8 product filename.
Parameters
----------
thisTime: datetime
query time.
product: str
prod... | 3fe3a3081b96a506401bb8671c69c78d4ba98b95 | 588,939 |
from typing import Dict
def convert_null(record: Dict) -> Dict:
"""Convert any null values to -1"""
for k, v in record.items():
if v is None:
record[k] = -1
else:
continue
return record | e4fbd719acf654ce449529f21ea0141c053b23f4 | 588,942 |
import random
def read_pid_status(pid):
"""
Mocks read_pid_status as this is a Linux-specific operation.
"""
return {
"FDSize": random.randint(0, 999999999),
"Threads": random.randint(0, 99999),
"VmRSS": random.randint(0, 999999999),
} | 45f6f9cc52e6c8f2201f875eeac296de7a522d83 | 588,944 |
def __video_size(video_h, video_w, shortside):
"""
Check the video size and return the new values to get the wanted
video shortside
:param video_h: Original video height
:param video_w: Original video width
:param shortside: shortside
:return: New video height and width, and also a boolean t... | b2e8e2b84e15ac0454dccfc32108fa01709a3c51 | 588,946 |
def _punctuation_config_preset(kwargs):
"""Populates the config to use punctuations as separators in the prompt."""
return dict(
kwargs,
orig_input_prefix="",
exemplar_input_prefix="",
exemplar_output_prefix=" ## ",
exemplar_separator=" @@ ") | ca2133121b0958aa225c8604b473c566470c12f9 | 588,947 |
def truncate_day(tval):
"""Truncate tval to 0Z."""
return((int(tval)/86400) * 86400) | 7082d7ae388a96c059f5163834e80f568513f7d3 | 588,948 |
from pathlib import Path
import shutil
def prepare_workdir(workdir: Path):
"""Create necessary directories if needed, such as templates directiry, articles directory, etc.
:param workdir: Working directory, where the blog is generated.
:return: Working dir and Template dir Path objects
"""
workdi... | 57db53ead4fb2b1c520a1b84f87a6c1858229362 | 588,949 |
import time
def costly_compute(data, row_index=0):
"""Simulate an expensive computation"""
time.sleep(1)
return data[row_index,] | 0513e29ff9369dde0e62cb668923564711530a00 | 588,950 |
def make_entity_base_url(url):
"""
Returns an entity URL with a trailing "/" so that it can be used consistently
with urljoin to obtain URLs for specific resources associated with the entity.
>>> make_entity_base_url("/example/path/") == '/example/path/'
True
>>> make_entity_base_url("/example/... | 03cc4f9444d053e38b0286ba8ded669b9b657077 | 588,953 |
def _multiply(a: int, b: int) -> int:
"""Implements multiplication of `a` times `b` in GF256, i.e.,
multiplication modulo the AES irreducible polynomial `x**8 + x**4 + x**3 + x + 1`.
"""
IRREDUCIBLE_POLYNOMIAL = 0b100011011
product = 0
while b > 0:
# add (xor operation) `a` to the produ... | f910f0713789fcf123bf822c96517669c4bd64e3 | 588,955 |
def match_cluster(record, cluster, dist=300):
"""
Determine whether DiscPair cluster matches a VCF record of interest.
Checks if pairs exist which match the record's strandedness, then checks
whether the min/max coord of these pairs is within a specified distance
of the record's coordinates.
A... | f8fac1367efafed7a9a8b3de97d0155127d88758 | 588,959 |
def remove_duplicate_esp_diffs(dexlist, espdiffs, tol=0.01):
"""
Filters and removes duplicate electrostatic potential differences from atoms
supplied in dexlist.
This functions first finds all values in espdiffs that are unique. Then the function
removes espdiffs that differ from others by the tol... | 0d22a8e6e3dcd26e1ad2f03ff093d304c880d810 | 588,961 |
def append_to_fn(fn, append_str):
"""
Append string before the file ending
:param fn: (str) - filename
:param append_str: (str) - string to add to filename
:return new_fn: (str) - append string combined with filename
"""
fn_list = fn.split('.')
fn_list = '.'.join(fn_list[:-1]) + append_... | 1258682ec1ea2d8b1458ae4da2d0b6a9a7cf6815 | 588,962 |
def extract_by_primary_key(df, primary_keys,
primary_key_column = 'borehole_id'):
"""
:param df: pandas dataframe
:param primary_keys: sequence of primary key values
:param primary_key_column:
:return:
subset of data in pandas dataframe
"""
# If the param... | 2da6bb25b5491fbfd9a309cda5324e1facea05bf | 588,967 |
def find_difference(string1, string2):
""" Find the differing character between strings.
string2 must be one character longer than string1.
"""
assert len(string1) + 1 == len(string2)
char_array = list(string2)
# Iterates through the first string, popping characters out of the second
#... | 78548a02e292b58dbee7bc2abd8803b6f47f7b39 | 588,973 |
def theta_map(mat, z):
"""
Evaluates the conformal map "theta" defined by a matrix [a,b],[c,d]
theta = (a*z + b)/(c*z + d).
"""
[a, b], [c, d] = mat
return (a*z + b)/(c*z + d) | ab7fae009d93c8de0c4c8935600ce19588ed8a40 | 588,975 |
import six
import unicodedata
def clean_bin(s, keep_spacing=True):
"""
Cleans binary data to make it safe to display.
Args:
keep_spacing: If False, tabs and newlines will also be replaced.
"""
if isinstance(s, six.text_type):
if keep_spacing:
keep = u" \n\r... | c9921b3000f062678c0e333172071522a6fef5ca | 588,977 |
from typing import Dict
def inverse_vocab(vocab: Dict):
"""inverse the key-value pairs of the vocabulary."""
return {v: k for k, v in vocab.items()} | 46e8000fe70d08dfe2060e179553bb111a0930bb | 588,981 |
def add_dict(field, dict_of_values):
"""
Add a given dict of values to a given array field.
"""
def transform(element):
assert isinstance(element[field], dict), \
"add_dict called on a non-dict object. type(element[%s]) = %s" % (field, type(element[field]))
element[field].upd... | b565263578750845ae2a423141078783cd99b05c | 588,982 |
def format_rel_url(url):
""" Formats from the form path/to to /path/to, if required.
@return: formatted string
@rtype: string
"""
if not url:
return url
if not url.startswith('/'):
return '/%s' % url
else:
return url | 087983557e74d0cf1a79d3c59acae11c39cc2b9c | 588,984 |
import math
def cluster_variance(X, centroids, labels):
"""
Returns the within-cluster variance for a particular clustering solution.
Parameters
----------
X : ndarray
A 2D array of input data where each row represents a sample and
each column represents a feature.
centroids :... | 03799be48e8f5eb5744d173271465a0d125408af | 588,986 |
def mean(l):
"""Average over array like."""
return sum(l) / len(l) | af3d8941337e5a9a83198efdc320d5f07a586089 | 588,987 |
def str_to_bin(str_input):
"""
Convert character string to binary string
:param str_input: string input
:return: string containing bits.
"""
bit_str = ""
for ch in str_input:
bits = bin(ord(ch))[2:]
bit_str += '00000000'[len(bits):] + bits
return bit_str | 56c890516698a8e2fda7bb1270a1fac0ff6669e7 | 588,988 |
def get_dataset_parameters(opt):
"""Prepare specific parameters for different datasets"""
dataset2num = {
'elect': 370,
'flow': 1083,
'wind': 29
}
dataset2covariate = {
'elect':3,
'flow': 3,
'wind': 3
}
dataset2input_len = {
'elect':169,
... | 2e06119d91b5e519aab6f5ddfb9851df79b0665d | 588,990 |
def roman_main(args):
"""Convert first arg to roman numeral if <= 5000 else :return: second arg."""
num = int(float(args.get('1')))
# Return a message for numbers too big to be expressed in Roman numerals.
if 0 > num or num >= 5000:
return args.get('2', 'N/A')
def toRoman(n, romanNumeral... | 37876a86868cc12c9bfbb80bc38bfb98657b93e7 | 588,991 |
import yaml
def load_yaml(config_dir):
"""
Load a yaml config file into a python dictionary.
"""
with open(config_dir) as cfg_file:
cfg = yaml.load(cfg_file, Loader = yaml.FullLoader)
return cfg | f3e515ab83e7c7ec7e9854af2ed00f769dcb726c | 588,998 |
def concatenateString(data, delimiter='\t'):
"""
Concatenate string list by using proviced delimeter
Args:
data: list of strings
delimiter: symbol, default to ' ', used to separate text
Returns:
Concatenated strings separated by delimeter
"""
return delimiter.join(data... | fc1264bf3ecb4ac9cf5553039c2af25c5e7bcf37 | 588,999 |
import re
def replace_placeholder_in_string(str_value: str, keys: dict) -> str:
"""find in string ${placeholder} pattern and replaces it with item from keys dictionary"""
regex_template = '(?:\${)(\w+)(?:})'
matches = re.findall(regex_template, str_value)
if len(matches) > 0:
matches = set(mat... | 525bf360411e47f450e7a7d00aa3ef7c4bc724b9 | 589,000 |
def has_next(collection, limit):
"""Return whether collection has more items."""
return len(collection) and len(collection) == limit | 44599ee5bd2d73f031b702d722cd2b4bb2434226 | 589,001 |
import re
def remove_punctuation(string, hyphens_are_separators=True, keep_commas=False):
"""removes punctuation from a string (simple regex replacing everything but w and
s with nothing) and returns the string
Keyword arguments:
string -- the string to remove punctuation from
hyphens_are_separat... | 0cb9184d748fba00ed0a683a2328ddab3bd61a8a | 589,003 |
import six
def get_unicode_dicts(iterable):
"""
Iterates iterable and returns a list of dictionaries with keys and values converted to Unicode
>>> gen = ({'0': None, 2: 'two', u'3': 0xc0ffee} for i in range(3))
>>> get_unicode_dicts(gen)
[{u'2': u'two', u'0': None, u'3': u'12648430'},
{u'2':... | f5d96224b10aeeab99621d18ae2ec3b326dd8892 | 589,004 |
def generate_item_template(item, users):
"""Generates HTML code for the item and participant for the html body
Args:
item (List[str]): A list of item names
users (List[str]): A list of user participants
Returns:
str: HTML code to generate parts of the body.
"""
user_tem... | 8e037998dca6d078d3f87123db381a9d39b7a0bb | 589,008 |
def validate_gain(gain):
"""
Validate the gain in the image
Parameters
----------
gain: float or list of floats
gain value(s)
Returns
-------
missing: boolean
True if gain is missing or invalid
"""
missing = True
if not gain:
return missing
... | 9d26a9d4f00afe919a3891fb8fe0bb4f6f4b285b | 589,009 |
def github_url(pkg):
"""Link to a package file on github."""
url = 'https://github.com/spack/spack/blob/develop/var/spack/repos/builtin/packages/{0}/package.py'
return url.format(pkg.name) | 3790e46b08a64fc32bdf3d6378ff3d3148e25a93 | 589,010 |
def spam_cancel_button(packer, cancel=1):
"""
Creates a CAN message for the Ford SCCM buttons/switches.
Includes cruise control buttons, turn lights and more.
"""
values = {
"CcAslButtnCnclPress": cancel, # CC cancel button
}
return packer.make_can_msg("Steering_Data_FD1", 0, values) | 7efcb6969b2dfb914c3bd33821cfaf5c2795bd9a | 589,013 |
def compute_weights(xs: list) -> list:
"""Computes and returns the weights (as a list) used in the barycentric form
of the Lagrange polynomial.
This function avoids checking if the input list xs is well-formed for
performance reasons.
Time complexity: O(n²)."""
n = len(xs)
ws = [1] * n
... | debfa6206003e3e0e2c083a9b88f0157bca4df1a | 589,014 |
import logging
def update_classy_model(model, model_state_dict, reset_heads):
"""
Updates the model with the provided model state dictionary.
Args:
model: ClassyVisionModel instance to update
model_state_dict: State dict, should be the output of a call to
ClassyVisionModel.get... | 0bc165a68d355e10b5b297a4da547305fc7bae29 | 589,015 |
def get_pinned_version(ireq):
"""
Get the pinned version of an InstallRequirement.
An InstallRequirement is considered pinned if:
- Is not editable
- It has exactly one specifier
- That specifier is "=="
- The version does not contain a wildcard
Examples:
django==1.8 # pinne... | 98c4e8a4e57d8ca54cd3ad8cef7fa71b7c53714f | 589,019 |
from typing import Dict
from typing import Any
def make_resampling_test(
freq: str = "D", resample: bool = True, agg: str = "Mean"
) -> Dict[Any, Any]:
"""Creates a resampling dictionary with specifications defined by the arguments, for testing purpose.
Parameters
----------
freq : str
Va... | 2f6402a9c7929200b1cdd5b076b1e2e2133fb0c2 | 589,022 |
def first(collection, test, default=None):
"""
Return the first item that, when passed to the given test function,
returns True. If no item passes the test, return the default value.
"""
return next((c for c in collection if test(c)), default) | e31e77bb1698043701caee1be34ae994670f0fa9 | 589,023 |
def make_list(length):
"""
Creates and initializes a list in a safe manner (avoiding reference issues)
"""
return [None for x in range(length)] | f87fb65e3e0fcc2961abebe20ac20e9bba4e28cb | 589,026 |
def _get_error_messages(masks, error_info):
"""
Get list of error messages.
Parameters
----------
masks : list
List of pandas.Series with masked errors.
error_info : dict
Dictionary with error messages corresponding to different
validation errors.
"""
msg_list = ... | c6e8be080ecea1159b6367ebeca8a8aa84aa82ac | 589,029 |
def write_readmap(fh, rmap, namedic=None):
"""Write a read map to a tab-delimited file.
Parameters
----------
fh : file handle
Output file.
rmap : dict
Read-to-taxon(a) map.
namedic : dict, optional
Taxon name dictionary.
"""
# sort subjects by count (high-to-low... | e7da4b9fe8ea551d8d2fd4e35b514b60abee9d84 | 589,030 |
def _all_dependencies(node, dg):
"""Gets all the dependencies for the passed in node.
:param str node: The node to lookup dependencies for.
:param dict dg: The graph to lookup.
:return: Tuple of a list of pairs from parent to child dependencies and
the list of direct_dependencies.
:rtype: ... | 509da298ad0e1356fb4932a06bdbd02965aa2b45 | 589,031 |
import inspect
def accepts_kwarg(func, kwarg):
"""
Determine whether the callable `func` has a signature that accepts the
keyword argument `kwarg`
"""
signature = inspect.signature(func)
try:
signature.bind_partial(**{kwarg: None})
return True
except TypeError:
retu... | 4d302209a0b257c1ea76f055cc90f8150756e216 | 589,032 |
def exists_in_tree(node, n):
"""This function finds if an element exists in a BST or not by recursively traversing the tree
input : current node and the element to be found
output : returns True if it exists, False if not
Time complexity : O(log(n)), Space complexity : O(1)
"""
if no... | 0ee63f1ac251baac178d610783e7278ea2b5a25a | 589,035 |
def exponenciacao_recursiva(base, expoente):
"""
Implementação de um algoritmo de exponenciação.
Argumentos:
base: int. Base da operação
expoente: int. Expoente da operação
Retorna o resultado da operaçao de exponenciação.
"""
if expoente == 0:
return 1
return base... | 09423e2d604c84e042b9ffc150015324130ac2b5 | 589,038 |
import math
def magnitude(v):
"""
Magnitude is a length of a vector
:param v: The vector we want to find the magnitude of
:return: The magnitude of v
"""
return math.sqrt(math.pow(v[0], 2) +
math.pow(v[1], 2) +
math.pow(v[2], 2)) | 0ff2f29e83b3fa965abfe8010c0b3398dfda3dd2 | 589,039 |
import re
def _find_seed(x):
"""Grabs seed from image name.
if can't find seed, returns 'reference'
"""
try:
return re.findall('seed-(\d+)_', x)[0]
except IndexError:
return 'reference' | 376ff1a471bb757c928fc6f3dae66f3f86843806 | 589,040 |
def get_row_by_index(data_frame, index):
"""Returns all columns of a DataFrame for a given index.
Args:
data_frame (DataFrame): the Pandas DataFrame to use
index (int): the index to access the DataFrame
Returns:
Series: a Pandas Series containing all cols at the given index
"""... | a22973fa485901426d6dfd246d218761d8763b98 | 589,042 |
def _displayDuration(start, end):
"""
Display a human-readable time duration.
:param start: Time at the start
:param end: Time at the end
:return: The duration ``end - start``
"""
duration = end - start
days = duration.days
hours = duration.seconds // 36... | f95a407f2a31e717aa271b73e78ac2e8084f4033 | 589,043 |
def bbox_IOU(bbox1, bbox2):
"""
Calculate IOU of 2 bboxes. bboxes are in SSD format (7 elements)
bbox = [id, cls, prob, x1, y1, x2, y2]
Args:
bbox1 (bbox)
bbox2 (bbox)
Returns:
IOU value
"""
_xmin, _ymin, _xmax, _ymax = 3, 4, 5, 6
width_of_overlap_area = min(... | 0e62088110ac3ecf172b2b7e4ae5bdbfc70beb00 | 589,047 |
import hashlib
def compute_hash(api_key: str) -> str:
"""Computes SHA1 hash over input API key.
Args:
api_key: Key to be hashed.
Returns:
Hashed API key.
"""
hasher = hashlib.sha1()
hasher.update(api_key.encode())
return hasher.hexdigest() | 494cf4ff1ddc79fb32d12fe69d299e02ec61d088 | 589,048 |
def decode_tuple(encoded_tuple):
"""Turn tuple string back to tuple. """
s = encoded_tuple.split('/')
return int(s[0]), int(s[1]) | 6324cb95a8676ed61ec76711248da6803b805648 | 589,053 |
def _final_version(parsed_version):
"""Function copied from zc.buildout.easy_install._final_version."""
return not parsed_version.is_prerelease | 6954e36f9a276283241df9bdde09787322a84f7b | 589,055 |
def get_measurement_number(file):
"""Return a measurement number from a file's name.
Args:
file: A file as a "Path" object.
"""
return int(file.stem[-4:]) | fa2dbbf55a3d138f72139fadc61b0da7e8819264 | 589,058 |
import re
def get_cluster_sizes(connections):
"""
Returns a dictionary mapping clusters of servers (given
by their naming scheme) and the number of connections in
that cluster.
"""
expr = re.compile(r".*\.shard\d+$")
clusters = {}
for conn in connections:
if not expr.match(conn):
continue
c... | 1f84f0680338067a588071287c05d68ca88f2903 | 589,062 |
def to_data_string_with_default(value, arg=''):
""" Given a Python boolean value converts it to string representation so
we can use it in HTML data attributes. If value is None use given default
or '' if default is not provided.
----- ------
Value Output
----- ------
True ... | 8d5e3a3a4e0449b25db8c6cefb46d8064bd04f97 | 589,064 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.