content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def time2seconds(time):
""" delta time string to number of seconds
time: e.g. '2d' for 2 days, supported units: d-day, h-hour, m-minute, s-second
return: integer number of seconds
Note: Month and year duration varies. Not worth doing for the sake of simplicity.
"""
assert len(re.fi... | 6cde282b6b6b1f3ff435bfe6d46279a780dafa85 | 42,737 |
import torch
def calc_au(model, test_loader, delta=0.01):
"""compute the number of active units
"""
means = []
for datum in test_loader:
batch_data, _ = datum
mean, _ = model.encode_stats(batch_data)
means.append(mean)
means = torch.cat(means, dim=0)
au_mean = means.me... | 33887036354c48d202baeff82690e4ee6eb44a64 | 42,738 |
import sys
def get_dataset_vars(dataset, met_vars, in_file=False):
"""get the names of dataset variables for each dataset
:dataset: gridded dataset name
:met_vars: list of met variables (must match know variables)
:returns: returns dictionary of variables as named in the dataset file
"""
if ... | b64a909bb6c325fcf44053447706a52b651a2d9a | 42,739 |
import os
import json
def mock_threat_intel_query_results():
"""Load test fixtures for Threat Intel to use with rule testing
Fixture files should be in the following JSON format:
[
{
"ioc_value": "1.1.1.2",
"ioc_type": "ip",
"sub_type": "mal_ip"
... | 530c39e41babf8631479738aa9e5fd8a50740483 | 42,740 |
def initial_subtract(pixels, width, height):
"""
Find the mean and sample standard deviation of border
pixels. Subtract the mean intensity from every pixel.
Return the sample standard deviation.
"""
boundary = [0.] * (height + height + width + width - 4)
# top and bottom boundaries
bou... | 956f0f9e509ee80e974163a384f801ab02008d98 | 42,743 |
def filter_dict(field, dict, level = 2):
"""
Filter through nested dictionarys like one would do with
arrays. Only works if sub-dictionaries all have same
kwargs as desired by 'field'
"""
return [(x,dict[x][field]) for x in dict.keys()] | 83c8226c83dafad277a4defe78080e3087d56f01 | 42,744 |
def convert_little_endian(string):
"""
>>> convert_little_endian('C0 00')
'00 C0'
"""
lst = string.split(" ")
lst.reverse()
return " ".join(lst) | 052edfde996ed022b5a0f5076dcfb52866716456 | 42,745 |
def getPointIndex(x, y, pointsPerWidth, pointsPerHeight):
"""Returns the index of the given point in a poinsPerWidth*pointsPerHeight grid.
pointsPerWidth and pointsPerHeight should be odd numbers"""
# These calculations take the top left corner as the (0;0) point
# and both axes increase from that po... | bbf375689dabb9407d9eca3dcd517f5eab4fe0f8 | 42,746 |
def prepare_input(input_str, from_item):
"""
A function for preparing input for validation against a graph.
Parameters:
input_str: A string containing node or group identifiers.
from_item: Start processing only after this item.
Returns:
A list of node identifiers.
"""
... | b0545f0d58ad9788fa8a1538e163d0959965dc8a | 42,747 |
def read_word():
""" Method for reading in the word """
word = str()
while True:
word = input("Input the word to be tested or \'-1\' to quit: \n")
if (word.isalpha() and word.__len__() <= 16) or word == "-1":
break
else:
print("The word must contain only alph... | 4167e20499f94094ed631cf610b14c05814a9c71 | 42,748 |
import uuid
def get_uuid_from_query_params(request, param):
"""
return uuid from a given queryset after parsing it.
"""
param_field = request.query_params.get(param, None)
if param_field:
try:
return uuid.UUID(param_field)
except ValueError:
return None
... | 1c8e3b2ffbe7020f6d1d796aeae55d53d0b39867 | 42,749 |
def sanitize(s: str) -> str:
"""Something like b64encode; sanitize a string to a path-friendly version."""
to_del = [" ", ";", ":", "_", "-", "/", "\\", "."]
s = s.lower()
for c in to_del:
s = s.replace(c, "")
return s | 813b3c743f57443dcebddef987bf71b58f94f73c | 42,751 |
import subprocess
def calledprocesserror_helper(*popenargs, **kwargs):
"""
Helper for the calledprocesserror test.
Lambdas can't raise exceptions, so this logic gets its own function.
"""
# Workaround so that the --version check doesn't throw a CalledProcessError
if "--version" in popenargs[0... | 045617b4478ebbdeca13fa07c9ba3e4001689519 | 42,752 |
import pickle
def _pickle(pickle_file):
"""
Loads a pickle file that works in both py 2 and 3
Parameters
------
pickle_file : str
path to pickle file to load
"""
try:
with open(pickle_file.as_posix(), "rb") as f:
return pickle.load(f)
except UnicodeDecodeEr... | f34f7649d0c0b0480e86fc1cb76eae74b1099113 | 42,753 |
def _aihub_coord_to_coord(coords):
"""Covert aihub-style coords to standard format.
>>> _aihub_coord_to_coord({
... "X좌표1": 602.004,
... "X좌표2": 571.004,
... "X좌표3": 545.004,
... "X좌표4": 531.004,
... "Y좌표1": 520.004,
... "Y좌표2": 505.004,
... "Y좌표3": 465.004,
... ... | fed881fe532442ccb2c13d44262a5ef12f5c5143 | 42,754 |
def even(n : int) -> bool:
""" """
return (n % 2) == 0 | 2b468707945d17cdf4bd3e6842a2cc2642e66e61 | 42,755 |
def f1_from_roc(fpr, tpr, pos, neg):
"""Calculate f1 score from roc values.
Parameters
----------
fpr : float
The false positive rate.
tpr : float
The true positive rate.
pos : int
The number of positive labels.
neg : int
The n... | d682ef92c8f3a43f1e88ab98125cb3f3d33cf189 | 42,756 |
def datetime_to_pretty_str(dt):
"""
Convert datetime object to string similar to ISO 8601 but more compact.
Arguments:
----------
dt: dateime object
... for which the string will be generated.
Returns:
--------
dt_str: string
The pretty string respresentation of the dat... | 24508950d6a2995247a0dd305ddb82086285bd18 | 42,757 |
def recursive_convert_sequences(data):
"""
recursively applies ``convert_sequences``
"""
if not hasattr(data,'keys'):
return data
if len(data.keys()) == 0:
return data
try:
int(data.keys()[0])
except ValueError:
tmp = {}
for key, value in data.items():... | a9ddea313d0f22413af37f411001c7db6f54d087 | 42,758 |
def convert_string_to_bool(string_value):
"""
simple method used to convert a tring to a bool
:param string_value: True or False string value
:type string_value: string - required
:return: bool True or False
:rtype bool
"""
if string_value == 'True':
return True
else:
... | 3e4113721df399408719ae7737136691f904ae78 | 42,762 |
def has_finite_length(obj):
"""
Return ``True`` if ``obj`` is known to have finite length.
This is mainly meant for pure Python types, so we do not call any
Sage-specific methods.
EXAMPLES::
sage: from sage.sets.set import has_finite_length
sage: has_finite_length(tuple(range(10))... | 483a5cbb69f197622373c224de41f9e0ddd149ec | 42,763 |
import numpy
def MakePoint(*args):
"""Makes a point from a set of arguments."""
return numpy.matrix([[arg] for arg in args]) | 19e165a357f0b8e6933459aca65fdc62714fd878 | 42,764 |
import csv
def cluster_keywords(input_file_path):
""" Cluster keywords based on the shorted version of the keywords read from the input file.
Args:
input_file_path: the path to the tsv file containing keywords and their shortened version.
Returns:
shortened_keywords_list: a dictionary with shortened key... | fb000bc9d36f901e09f3a958a42e555b90c9ae56 | 42,765 |
def find_percentage(lines, num_ahead):
"""
Function: find_percentage\n
Parameter: lines -> lines of current output file opened, num_ahead -> number of lines ahead where we get the percentage of edge similarity\n
Returns: edge similarity percentage in that file
"""
percentage = 0.0
if 'Follow... | 6fa880d1fff40bfb86b8eedb03085e6b4ffe978e | 42,766 |
def float_div(num1, num2):
"""Function: float_div
Description: Takes two numbers and does floating division. Returns zero
if the divisor is zero.
Arguments:
(input) num1 number -> First number.
(input) num2 number -> Second number.
(output) Return results of division or... | 372c1eb0fda84d066d7ed5c6a7990869380fffb8 | 42,767 |
from datetime import datetime
def parse_date(seconds):
"""Parse datetime from value received from fullcalendar.
"""
return datetime.utcfromtimestamp(int(seconds)) | 5c6d690ed3fb7b47602be38bde333c5b3b75f4d8 | 42,768 |
from functools import reduce
from operator import truediv
def analyze(sample_paragraph, typed_string, start_time, end_time):
"""Returns a list containing two values:
words per minute and accuracy percentage.
This function takes in a string sample_paragraph,
a string provided by user input typed_strin... | ac797542fc90cc800deec731209fa336a7181739 | 42,769 |
def filter_by_hardware_interface(ctrl_list,
hardware_interface,
match_substring=False):
"""
Filter controller state list by controller hardware interface.
@param ctrl_list: Controller state list
@type ctrl_list: [controller_manager_msgs/... | ce1dc94543b0fde61944f8a730fd4717b3c83da7 | 42,771 |
def convolve(X, Y):
"""
Convolves two series.
"""
N = len(X)
ss = []
for n in range(0, len(Y)):
s = 0
for l in range(0, len(X)):
s += X[l].conjugate()*Y[(n+l)%len(Y)]
ss.append(s)
return ss | 8a9f5d37d25cea175228a87428c516f2dec1f022 | 42,773 |
def _columnspace(M, simplify=False):
"""Returns a list of vectors (Matrix objects) that span columnspace of ``M``
Examples
========
>>> from sympy.matrices import Matrix
>>> M = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6])
>>> M
Matrix([
[ 1, 3, 0],
[-2, -6, 0],
[ 3, 9, 6]])
... | 4bc7b18b6781426ff4e0cb9b587836b46aef23b7 | 42,774 |
def _bounce(open, close, level, previous_touch):
"""
did we bounce above the given level
:param open:
:param close:
:param level:
:param previous_touch
:return:
"""
if previous_touch == 1 and open > level and close > level:
return 1
elif previous_touch == 1 and open < le... | cc4ca803325fcdf70976f5032c747e8b19d2acc0 | 42,775 |
import hashlib
def get_md5_hash(path):
"""
Calculates the md5 hash for a specific file.
"""
md5_hash = hashlib.md5()
md5_hash.update(open(path, 'rb').read())
return md5_hash.hexdigest() | 30120003948d334a11a0ca45fb6d22125e4b85ce | 42,776 |
def _error_function(param, x_vals, y_vals):
"""
The error function to use with the lestsq method in scipy.optimize.
:param list of floats param: current estimates of the intercept and slope
for the least squares line.
:param list of floats x_vals: the x-values at which ... | 7c144fde2974ba911c9b78829023e1c6b0e56f45 | 42,779 |
from datetime import datetime
def string_to_date(string):
"""
#把字符串转成date
:param string:
:return:
"""
return datetime.strptime(string, "%Y-%m-%d") | 6b554a2b9b23bc2e3a86809cd30e225f53db6d76 | 42,780 |
def mode_property(cls):
"""Generates a property that
- when read, determines whether a recipient mode specified by <cls>
is selected
- when set, updates the recipient_modes list by removing or adding
the mode specified by <cls>
"""
def _get_recipient(self):
for... | 414dd4a05dbcd6bdf211acc95dd81e069ab9f4b4 | 42,781 |
def get_indexes(cursor, table_name):
"""
Returns a dictionary of fieldname -> infodict for the given table,
where each infodict is in the format:
{'primary_key': boolean representing whether it's the primary key,
'unique': boolean representing whether it's a unique index}
"""
# This... | 7f71b0f2c493deb4d3ef6e0b73021575ba1e2ce1 | 42,782 |
def para_lda():
"""GridSearchCV parameteres for LDA."""
para_lda = [{
'solver': ['svd'],
# 'shrinkage': ['auto'],
'n_components': [5, 10, 15, 20, 25, 30],
# 'priors': [],
# 'store_covariance': [],
'tol': [1e-2, 1e-3, 1e-4]},
{
'solver': ['lsqr... | c1986a67000d4fd36a952a3642ae1b56e8909411 | 42,784 |
def make_chunks(l, n):
"""
Chunks a list into ``n`` parts. The order of ``l`` is not kept. Useful for
parallel processing when a single call is too fast, so the overhead from
managing the processes is heavier than the calculation itself.
Parameters
----------
l : list
Input list.
... | df0c3ddf67ed892ce47cd073f67003ed9e85b6d6 | 42,785 |
def pr(vp,vs):
"""
Computes the Poisson ratio
Parameters
----------
vp : array
P-velocity.
vs : array
S-velocity.
Returns
-------
pr : array
Poisson ratio.
"""
vpvs=vp/vs
pr = 0.5*((vpvs**2-2)/(vpvs**2-1))
return (pr) | bec82f868b847b85e39c90016f6787e20faa91ae | 42,788 |
def load_specman_exp(path):
"""
Import parameter fields of specman data
Args:
path (str) : Path to either .d01 or .exp file
Returns:
params (dict) : dictionary of parameter fields and values
"""
exp_file_opened = open(path, encoding="utf8", errors="ignore")
file_contents = ... | 59191161c30c274c35899b47bdec96128aca7102 | 42,789 |
import time
def timestamp_to_gmtime(ts):
"""Return a string formatted for GMT
>>> print(timestamp_to_gmtime(1196705700))
2007-12-03 18:15:00 UTC (1196705700)
>>> print(timestamp_to_gmtime(None))
******* N/A ******* ( N/A )
"""
if ts:
return "%s (%d)" % (time.strftime(... | 7e0dd51d2811c361c301ee92e62eb5b271539bf1 | 42,790 |
def to_positive_int(int_str):
"""
Tries to convert `int_str` string to a positive integer number.
Args:
int_str (string): String representing a positive integer number.
Returns:
int: Positive integer number.
Raises:
ValueError: If `int_str` could not be converted to a posi... | 322942f257ca390e5d7ae5d9f74c33d6b8623baf | 42,791 |
def get_module_url(module_items_url):
"""
Extracts the module direct url from the items_url.
Example:
items_url https://canvas.instance.com/api/v1/courses/course_id/modules/module_id/items'
becomes https://canvas.instance.com/courses/course_id/modules/module_id
"""
return module_items_url.re... | bf03e0139c07e1d43be8123e1966fac5fd68239a | 42,792 |
def horizontal_unfold(A):
"""
For a 3D tensor A(a,i,b), we unfold like: A(a,ib)
"""
S = A.shape
return A.reshape(S[0], S[1] * S[2]) | 59caaa3db71c868d08264c64a88401e85ce6136c | 42,793 |
def _excel_col(col):
"""Covert 1-relative column number to excel-style column label."""
quot, rem = divmod(col - 1, 26)
return _excel_col(quot) + chr(rem + ord('A')) if col != 0 else '' | 85488c0ef6594483e88e6d644189e4ffceaaea46 | 42,795 |
import re
def _verify_ip(ip):
"""Return True if ip matches a valid IP pattern, False otherwise."""
if not ip:
return False
ip_pattern = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
return ip_pattern.match(ip) is not None | e828c03726d09480dcc3a7caa509a465b9a7a97e | 42,796 |
def p_displace(bin_str):
"""
P 置换
:param bin_str: 32 位的密文
:return: 置换后的 32 位密文
"""
if len(bin_str) != 32:
raise ValueError("二进制字符串长度必须是 32")
displace_table = [16, 7, 20, 21, 29, 12, 28, 17,
1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27... | 3efb44f6d2667b65906dbce9af360107700fb8e1 | 42,797 |
import re
def match_dummies(item:str, rep_word:bool=True):
"""Replaces profanity with dummy word"""
bad_prefixes = ['nig', 'bitc', 'puss', 'fuc', 'shit', 'hoe', 'ass', 'cock', 'fag', 'tits', 'cunt', 'dick', 'piss']
if rep_word:
replace_prefixes = [f"expletive_{i}" for i in range(len(bad_prefixes))... | b55180e49efdb40b5919a518f08c61396751a2fb | 42,798 |
def available_moves(hex_board):
"""
Get all empty positions of the HexBoard = all available moves.
:param hex_board: HexBoard class object
:return: list of all empty positions on the current HexBoard.
"""
return [(i, j) for i in range(hex_board.size) for j in range(hex_board.size) if hex_board.i... | 4813cdc69c64c4260390bb8ee47f541eb274ae4d | 42,799 |
from typing import Dict
def parse_group_id(group_id: str) -> Dict:
"""
解析插件组ID
:param group_id: sub_1234_host_1
:return: {
"subscription_id": 1234,
"object_type": host,
"id": 1,
}
"""
source_type, subscription_id, object_type, _id = group_id.split("_")
return {
... | 8e5e773993b7bea728d85133794b246901bc8c66 | 42,801 |
def textContent(node):
"""Return the text in `node`, including that in the child-nodes. This is the
equivalence of the text_content() method for HTML nodes, but works for both
HTML and XML nodes.
"""
return ''.join(node.itertext()) | a6760b4855b4c674f38a4ad360faf9e1dd924f71 | 42,803 |
def compile_source(filepath):
"""
Compile the source file at *filepath* into a code object.
Code objects can be executed by an exec statement or
evaluated by a call to ``eval()``.
"""
# line endings must be represented by a single newline character ('\n'),
# and the input must be terminated ... | 8eef8201590b14832e6e617de10adb3d2b5ff3b7 | 42,804 |
def extract_impression_id(line, assert_first_line=False):
"""
Extracts the impression_id from a line
"""
if type(line) == bytes:
line = line.decode()
return line[:line.index("|")].strip() | 09f67f24e4e517c1ac66df5cc1fb8d7d359ad3c9 | 42,806 |
def file_exists (filename):
"""
Determine if a file with the given name exists in the current directory and can be opened for reading.
Returns: True iff it exists and can be opened, False otherwise.
:param filename: Filename to check.
:return True if file exists.
"""
try:
... | f8319ccbec0b3dc75d0428cbf7f1a65782d98005 | 42,808 |
def check_number_threads(numThreads):
"""Checks whether or not the requested number of threads has a valid value.
Parameters
----------
numThreads : int or str
The requested number of threads, should either be a strictly positive integer or "max" or None
Returns
-------
numThreads ... | a8d683d5c265f43567031e8c10314efad2411ec9 | 42,809 |
def permutations(arr, position, end, res):
"""
Permutate the array
"""
if position == end:
res.append(tuple(arr))
else:
for index in range(position, end):
arr[index], arr[position] = arr[position], arr[index]
permutation... | f101b5073052d394b402d8eb6c4d144047036b77 | 42,812 |
import os
import hashlib
def hash_file(filename):
"""
Calculate the md5 hash of a file. Used to check for stale files.
:param filename: The name of the file to check
:type str:
:return: A string containing the md5 hash of the file
:rtype: str
"""
if os.path.exists(filename):
h... | 0c317a92d8a94a96128a4be9dc86bd94980e135f | 42,813 |
def read_maze(maze_file):
""" (file open for reading) -> list of list of str
Return the contents of maze_file in a list of list of str,
where each character is a separate entry in the list.
"""
res = []
for line in maze_file:
maze_row = [ch for ch in line.strip()]
res.append(ma... | 2084ac891012932774d46d507f550e8070e3cc47 | 42,814 |
import os
def normPath(path):
"""
Convert to an normalized path (remove redundant separators and up-level references).
"""
return os.path.normpath(path) | 88f5ed57ffc823f8de6b547dfd5b84cf25242813 | 42,815 |
def can(obs, action_id):
"""Returns True if the specified action is available."""
return action_id in obs.observation.available_actions | 509e7baa411529114881d95c38684d232d71db5a | 42,816 |
def removeengineeringpids(pids):
"""Removing propcodes that are associated with engineering and calibration proposals"""
new_pids=[]
for pid in pids:
if not pid.count('ENG_') and not pid.count('CAL_'):
new_pids.append(pid)
return new_pids | 18a3f14f6645a2d27727192b045cfb7b64f959f3 | 42,818 |
def make_pin_name(port, index):
"""
Formats a pin name of a multi-bit port
"""
return "{}_b{}".format(port, index) | e3e7c3476583bd80a68b53e077399b278f501573 | 42,821 |
import os
def patch_mypy_prefix_module_discovery() -> bool: # no cov
"""
pip does not use a virtual environment for builds so we need to patch
Mypy in order for it to recognize installed build requirements
"""
# pip always sets this, but we cannot merely set MYPYPATH with it b/c we encounter:
... | 5f2ad005660207a2bdce497ac0a96f356be6ce24 | 42,822 |
import os
def grab_next_session(session_directory):
"""
Given an empy directoy create a bunch of folders.
session_01 and on.
:param session_directory: empty directory you wnat to put these folders in
:type session_directory: str
:return: the latest directory path
:rtype: str
"""
... | 41b92f14b17bbac5e13456eca656e16fae2243d6 | 42,823 |
import os
import hashlib
def calc_hashes(file_path, hash_names, start = 0, end = None):
""" Calculate hashes for a file. The 'file_path' argument is the file
to calculate hash functions for, 'start' and 'end' are the starting and
ending file offset to calculate the has functions for. The 'hash_names'
... | 0c7a576ec25085a1601f2797642643c00dbd38d6 | 42,824 |
def getTime(t):
"""
Returns a string after converting time in seconds to hours/mins/secs
Paramters:
t (float): time in seconds
Returns:
s (str): number of hours, if more than 1 hour
number of minutes and seconds, if more than 1 minute
number of seconds, o... | 8448c6f3d5216ab6585d2367e9bac07170ecd08b | 42,825 |
def make_tag_decorator(known_tags):
"""
Create a decorator allowing tests to be tagged with the *known_tags*.
"""
def tag(*tags):
"""
Tag a test method with the given tags.
Can be used in conjunction with the --tags command-line argument
for runtests.py.
"""
... | 80a97f0db5198629aa1f48163d14b2eae463e933 | 42,827 |
def variance(rv, *args, **kwargs):
"""
Returns the variance `rv`.
In general computed using `mean` but may be overridden.
:param rv: RandomVariable
"""
return rv.variance(*args, **kwargs) | 479175f7c101612ea14cef7caf3c5876c2714987 | 42,828 |
def param_nully(value) -> bool:
"""Determine null-like values."""
if isinstance(value, str):
value = value.lower()
return value in [None, '', 'undefined', 'none', 'null', 'false'] | 243ab7fdbd08f236a3382cc5e545f035557d8c53 | 42,829 |
def formatChapter(chapter):
"""A chapter (or section or whatever) number."""
try:
chapter = str(int(chapter))
except ValueError:
raise ValueError("Chapter %s is not a number" % chapter)
pass
return chapter | 4b7bffe56ca3e3db07f946a2a2e96f76372625b1 | 42,830 |
def assemble_cla_status(author_name, signed=False):
"""
Helper function to return the text that will display on a change request status.
For GitLab there isn't much space here - we rely on the user hovering their mouse over the icon.
For GitHub there is a 140 character limit.
:param author_name: T... | 9ea59337f1d3d04531c6fe3457a6c769327ab767 | 42,831 |
def has_optional(al):
""" return true if any argument is optional """
return any([a.init for a in al]) | 6c2bf7836afc34fa47408cbdb94c94335fa21b26 | 42,832 |
import struct
import math
def _sc_decode(soundcheck):
"""Convert a Sound Check string value to a (gain, peak) tuple as
used by ReplayGain.
"""
# SoundCheck tags consist of 10 numbers, each represented by 8
# characters of ASCII hex preceded by a space.
try:
soundcheck = soundcheck.repl... | fcdce4c73241e9de00f1a658b0635fc626ac6774 | 42,834 |
import pathlib
def stringify_path(filepath):
"""Attempt to convert a path-like object to a string.
Parameters
----------
filepath: object to be converted
Returns
-------
filepath_str: maybe a string version of the object
Notes
-----
Objects supporting the fspath protocol (Py... | 83fca05a40e3b0f518d6bed454848a4ba6ed14f9 | 42,835 |
def renderFKPs(landmarks) -> dict:
"""Extract facial keypoints
Args:
landmarks ([type]): [description]
Returns:
dict: {fkp: [x, y]}
"""
keypoints = {}
index = 0
for fkp in landmarks:
keypoints[index] = [fkp.x, fkp.y]
index += 1
return keypoints | c9c8a9efaa3f78fdba0bdad4bb22cd6d503ca2ad | 42,838 |
def validate_coverage(
route,
metric="node_coverage",
max_gap_sec=3 * 60 * 60,
min_node_coverage_percent=0.75,
):
"""
Make sure there is sufficient coverage of the planned route with live data
"""
if metric == "time":
last_update, live = None, []
for r in route:
... | 0257b7a746141425194c69ed50ac4e554cccb980 | 42,839 |
def schedule_bus_number(bus_stop_code, bus_selected):
"""
Message that will be sent when user wants to choose bus for their scheduled messahes
:return:
"""
return 'Bus Stop Code <b>{}</b>\nYou can select the bus numbers that you want to receive their arrival timings.' \
'\n\nIf you did no... | 0b23cb5b1ba8d92b623488459e794bf212904ff1 | 42,840 |
def alphabetic_score(name, list_position):
"""Function that calculates an alphabetic score for a name based on
ascii value and list position.
"""
score = 0
for character in name:
score += ord(character) - 64
return score * (list_position + 1) | e828d1bce66ea1a74515a64c3aecadc03a4e733b | 42,841 |
def mean_center_utilmat(U, axis=1, fillna=True, fill_val=None):
"""Gets the mean-centered utility matrix
Parameters:
U (DataFrame) : utilily matrix (rows are users, columns are items)
axis (int) : The axis along mean is evaluated,
{0/'index', 1/'columns'}, default 1
fillna... | dad6239843aa47e8894a04b49f87ef34e4bc2e7a | 42,842 |
def as_list(val):
"""return a list with val if val is not already a list, val otherwise"""
if isinstance(val, list):
return val
else:
return [val] | 484c4163ea8e3dd17c9c4372554b54f16434b995 | 42,843 |
def is_placeholder(x):
"""Returns whether `x` is a placeholder.
# Arguments
x: A candidate placeholder.
# Returns
Boolean.
# Examples
```python
>>> from keras import backend as K
>>> input_ph = K.placeholder(shape=(2,4,5))
>>> K.is_placeholder(input_ph)
... | 4c5974c66f196ff6ba7e62fff05c91d59d6e14ba | 42,846 |
def to_pixel_units(l, pixelwidth):
"""Scales length l to pixel units, using supplied
pixel width in arbitrary length units
"""
try:
return l / pixelwidth
except (TypeError, ZeroDivisionError):
return l | 4e8883cf3ff007858f122ac13433c5346c851211 | 42,847 |
import tempfile
def has_flag(compiler, flagname):
"""Return a boolean indicating whether a flag name is supported on
the specified compiler.
"""
with tempfile.NamedTemporaryFile("w", suffix=".cpp") as f:
print("Testing for flag %s" % (flagname))
f.write("int main (int argc, char **arg... | 68467b6424ac8eb7f3049f21812d877f0fbe7cd3 | 42,848 |
def comparer(ses_hash, usr_hash):
"""This provides a function to compare initially hashed flight times with doubly hashed stored flight times."""
total = 0
kmax = 0
for k in usr_hash.keys():
if k in ses_hash:
kmax += 1
total += (abs(int(ses_hash[k]) - int(usr_hash[k])) - 24)
score = 4.8 - (total/kmax) #4 m... | de184fce02712427afd7156dea5f9fc19804ffb7 | 42,849 |
def metadata(data):
"""Convert a dictionary of strings into an RST metadata block."""
template = ":%s: %s\n"
return ''.join(template % (key, data[key]) for key in data) | 8d47746df2a232ff043b5a60527917f6f75329ee | 42,850 |
def cli(ctx, group_id):
"""Get information about a group
Output:
a dictionary containing group information
"""
return ctx.gi.groups.show_group(group_id) | 5bb99f5d76ab7a4dd1e471ca39339f7082105849 | 42,852 |
from typing import Union
from typing import Tuple
import secrets
import hashlib
def wep_encypher_pw(password: str, salt: Union[None, str] = None) -> Tuple[str, str]:
"""
Hash and salt a password string and return the SHA-512 digest of the
hashed and salted string.
Args:
password: A password in... | ffbb5ec08b2e9f8c8c9567f254bcc90180f9d7f5 | 42,855 |
import sys
from datetime import datetime
def datetime_from_isoformat(value: str):
"""Return a datetime object from an isoformat string.
Args:
value (str): Datetime string in isoformat.
"""
if sys.version_info >= (3, 7):
return datetime.fromisoformat(value)
return datetime.strpti... | ffa0616d1896ef049b811206a7296438a000c150 | 42,856 |
import os
def find_in_dirs(filename, directories):
"""Find the file under given directories.
Args:
filename: File/Folder name to find.
directories: List of directories to search for.
Returns:
If found, return the combined path with directory and filename.
Return None, otherwise.
"""
for di... | 477e514d1309ad8f9a0c51ce11cb9da302208a00 | 42,857 |
def varint_to_blob_length(l):
""" Blob field lengths are doubled and 12 is added so that they are even and at least 12 """
if l == 0:
return 0
else:
return (l - 12) / 2 | 8638250edb42e6ee5e51f097104d4787f36c88ad | 42,858 |
def patient_form(first_name, last_name, patient_id, gender, birthdate):
"""OpenMRS Short patient form for creating a new patient.
Parameters OpenMRS form field Note
first_name personName.givenName N/A
last_name personName.familyName N/... | 98e41b828b1de828bf6925b24d9c9e321c4c4cfa | 42,859 |
import os
import subprocess
def show_annotated_feed():
""" Runs script to show annotated feed. Returns PID of process."""
pwd = os.path.split(os.path.abspath(__file__))[0]
loc = os.path.join(pwd, 'scripts', 'show_feed.py')
process = subprocess.Popen(['nohup', loc],
stdout=open('/dev/null', 'w'... | c1dd718622fd3e7152a03beae221afdd35f38825 | 42,860 |
def __check_flag__(all_vars, flag, requirements):
# type: (dict, str, list) -> list
""" Checks the given flag against the requirements looking for issues.
:param all_vars: All variables.
:param flag: Flag to check.
:param requirements: Flag requirements.
:returns: A list of issues (empty if non... | 0a19f0ffa55b95a7c4ee62e5ee5010a1e52c7848 | 42,861 |
def test_site_redirects(old_links, success_messages, error_messages):
"""
For each old link, verify that it gets a permanent redirect header and that the subsequent page is 200
"""
return success_messages, error_messages | f73c7aa4b8c41fa06eb58afffee6a4dac1c68dda | 42,862 |
def assemble_custom_shelflist(assemble_shelflist_test_records):
"""
Pytest fixture. Returns a utility function for creating a custom
shelflist at the given location code. Uses the
`assemble_shelflist_test_records` fixture to add the records to the
active Solr environment for the duration of the test... | fb432cce9c79997fba3f7670ff4b3bf97c26846a | 42,863 |
import random
def mutate_path(path):
"""
Gets a random index 0 to next to last element.
Copies path, swaps two nodes, compares distance.
Returns mutated path.
"""
# - will go out of range if last element is chosen.
random_idx = random.randint(0, len(path) - 2)
new_path = list(path)
... | 07484de90755aa275f3874ace247f3f8f8d8b4f6 | 42,864 |
import random
async def flip_coin():
"""Flips a coin."""
rand = random.randint(0, 1)
side = random.randint(1, 20)
if side == 20:
return {"message": "The coin landed on... its side?"}
elif rand == 0:
return {"message": "The coin landed on heads."}
elif rand == 1:
return ... | fc86cd2f7d8af48ce2a098df98ef639ca5a55c3b | 42,865 |
def middle(lst):
"""
Takes a list and returns a new list that contains all but the first and
last elements.
Input: lst -- a list
Output: new -- new list with first and last elements removed
"""
new = lst[1:] # Stores all but the first element
del new[-1] ... | ee065663b7ace7a8f582a6967096862585b9f599 | 42,868 |
def cluster_set_name(stem, identity):
"""Get a setname that specifies the %identity value.."""
if identity == 1.0:
digits = "10000"
else:
digits = f"{identity:.4f}"[2:]
return f"{stem}-nr-{digits}" | c23a71ef98cbaf7b5b11fc57893f3f0d4fa589b8 | 42,869 |
def find_underscores(edffilename):
"""
Utility function
:param edffilename:
:return:
"""
str_copy = list(edffilename).copy()
indices = []
ind = len(str_copy) - 1
# find indices of the '_'
while len(str_copy) > 0:
char = str_copy.pop()
if char == '_':
... | 4494389d1b4c9eede4e54cdb8febf18ffb64ed7f | 42,870 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.