content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def set_initxval(constr_func, constr_values):
""" Calculates the initial value of xval.
Args:
constr_func (:obj:`list`): constraint functions applied.
constr_values (:obj:`list`): Values of constraint functions applied.
Returns:
initial_xval (:obj:`float`): First value of xval
... | 58,100 |
def rms_rfft(spectrum, n=None):
"""
Use Parseval's theorem to find the RMS value of an even-length signal
from its rfft, without wasting time doing an inverse real FFT.
spectrum is produced as spectrum = numpy.fft.rfft(signal)
For a signal x with an even number of samples, these should produce the
... | 58,101 |
def unpickle(file):
"""
Each of the files from the CIFAR-10 dataset is a Python "pickled" object produced with cPickle
This routine opens such file and returns a dictionary
"""
import pickle
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict | 58,102 |
def task_docs():
"""Docs"""
return {'actions': [(build_sphinx, [SphinxOutputType.HTML,
docs_dir,
build_docs_dir])],
'task_dep': ['deps']} | 58,103 |
def collect(
volumes,
workLocation,
volumeType=None,
volumeFeature=None,
mergeTypes=None,
featureMeta=None,
silent=False,
overwrite=False,
):
"""Creates a work out of a number of volumes.
The volumes are individual TF data sets, the work is a new TF data set.
You may pass a... | 58,104 |
def yearly(
records: Iterable[Transaction], *, year: int, months: int = 12
) -> Iterable[Transaction]:
"""Return an iterator for records dated within a given year.
Optionally only include records up to (and including) a given month.
For example, if months=5, only include records daten between January
... | 58,105 |
def copy_directory(src_path, dst_path, verbose_output=False, verbose_copy=False, verbose_skip=False, match_func=lambda path: True):
"""Copies directory in 'src_path' to 'dst_path' maintaining the directory
structure. https://docs.python.org/3.5/library/shutil.html#shutil.copytree can't
be used in this case ... | 58,106 |
def get_timeseries_deaths(api: ArcGisFeatureServer) -> List:
"""
Get a timeseries of deaths.
"""
# First build a lookup table for records with no collection date.
data = api.query(CASES_SERVICE,
where='DtDeath <> NULL',
outFields='DtDeath,COUNT(*) AS deaths'... | 58,107 |
def deep_dictionary_check(dict1: dict, dict2: dict) -> bool:
"""Used to check if all keys and values between two dicts are equal, and recurses if it encounters a nested dict."""
if dict1.keys() != dict2.keys():
return False
for key in dict1:
if isinstance(dict1[key], dict) and not deep_dicti... | 58,108 |
def migration_step_11():
""" Add sensors, rename *_type fields to protocol. """
ID_FIELD = 'id INTEGER NOT NULL PRIMARY KEY DEFAULT randid_{table_name}()'.format(table_name='sensors')
ACCOUNT_ID_FIELD = 'account INTEGER NULL REFERENCES accounts(id) ON DELETE CASCADE'
with db.cursor() as c:
c.exe... | 58,109 |
def crop_relevant_image_parts(output_dir: str, image_df: pd.DataFrame,
copy_img_without_obj: bool = False):
"""Iterates over all images in the dataset and takes their
object detections to crop the image to only contain the relevant parts,
e.g. streets. The images are saved in a folder "cropped" in the give... | 58,110 |
def _extract_lesson(podcast_file):
"""Extract the lesson number from the podcast file.
Return:
tuple - {pathlib obj} path of podcast file, {str} lesson number.
"""
file_path = pathlib.Path(podcast_file)
extract_lesson = "_".join(file_path.name.split('_')[4:6])
try:
lesso... | 58,111 |
def stat(filename):
"""Returns file statistics for a given path.
Args:
filename: string, path to a file
Returns:
FileStatistics struct that contains information about the path
Raises:
errors.OpError: If the operation fails.
"""
return stat_v2(filename) | 58,112 |
def odd_ext(x, n, axis=-1):
"""Extends `x` along with `axis` by odd-extension.
This function was previously a part of "scipy.signal.signaltools" but is no
longer exposed.
Args:
x : input array
n : the number of points to be added to the both end
axis: the axis to be extended
"""
if n < 1:
... | 58,113 |
def unshared_copy(inList):
"""perform a proper deepcopy of a multi-dimensional list (function from http://stackoverflow.com/a/1601774)"""
if isinstance(inList, list):
return list( map(unshared_copy, inList) )
return inList | 58,114 |
def run(context): # pylint: disable = unused-argument
"""[summary]
Args:
context ([type]): [description]
"""
cadtris_addin.run_app() | 58,115 |
def samplesheet_mip_pool_dilution(lims, process_id, output_file):
"""Create manual pipetting samplesheet for smMIP pool dilution"""
process = Process(lims, id=process_id)
# Write header
output_file.write('{sample}\t{ul_sample_10}\t{ul_EB_10}\t{ul_sample_20}\t{ul_EB_20}\t{ul_sample_40}\t{ul_EB_40}\t\n'.... | 58,116 |
def show_cache():
"""Show the cf specs cache file"""
print(USER_CF_CACHE_FILE) | 58,117 |
def SEARCH(find_text, within_text, start_num=1):
"""
Returns the position at which a string is first found within text, ignoring case.
Find is case-sensitive. The returned position is 1 if within_text starts with find_text.
Start_num specifies the character at which to start the search, defaulting to 1 (the fi... | 58,118 |
def GetDefaultAndCustomPreset(presets):
""" Get the default and custom preset values from the saved property group"""
defaultPreset = ''
customPreset = ''
if presets:
for p in presets:
if p.name == 'Default':
defaultPreset = p.value
if p.name == 'Custom':
... | 58,119 |
def getvaluelist(doclist, fieldname):
"""
Returns a list of values of a particualr fieldname from all Document object in a doclist
"""
l = []
for d in doclist:
l.append(d.fields[fieldname])
return l | 58,120 |
def admissiblenums(n=1e9):
"""generates a set of all admissible numbers not exceeding 1e9"""
admissibleset=set()
for i in range(len(pr)):
nth_admissible_prime=set(loop(n,i))
admissibleset|=nth_admissible_prime #union of admissibles up to nth prime
return admissibleset | 58,121 |
def to_sources(settings: ApplicationConfiguration) -> Dict[str, str]:
"""Transform the current settings into representation of sources.
:param settings: The current settings
:returns: The settings sourced represented as a dictionary of path, source
"""
sources = {}
for entry in settings.entries... | 58,122 |
def nhanesi(display=False):
""" A nicely packages version of NHANES I data with surivival times as labels.
"""
X = pd.read_csv(cache(github_data_url + "NHANESI_subset_X.csv"))
y = pd.read_csv(cache(github_data_url + "NHANESI_subset_y.csv"))["y"]
X_display = X.copy()
X_display["Sex"] = ["Male" if... | 58,123 |
def zenkey_oidc_service(required_params, optional_token_request_params, id_token_validator_params):
"""
Execute entire flow necessary to:
- discover provider configuration (based on mccmnc)
- exchange auth code for an access token
- use that access token to request user info
Returns user's zenk... | 58,124 |
def concat_vec(x1, f2):
"""Concatenates numpy vectors
"""
x2 = np.load(f2)
x = np.concatenate((x1, x2), axis=1)
return x | 58,125 |
def nullColumns_detection(
spark,
idf,
list_of_cols="missing",
drop_cols=[],
treatment=False,
treatment_method="row_removal",
treatment_configs={},
stats_missing={},
stats_unique={},
stats_mode={},
print_impact=False,
):
"""
This function inspects the column quality a... | 58,126 |
async def async_test_host(hass: HomeAssistant, type: ArgoDeviceType, host: str):
"""Return true if host seems to be a supported device."""
try:
session = async_create_clientsession(hass)
client = ArgoApiClient(type, host, session)
result = await client.async_sync_data(ArgoData(type))
... | 58,127 |
def _merge_a_into_b(a, b):
"""Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a.
"""
if type(a) is not edict:
return
for k, v in a.iteritems():
# a must specify keys that are in b
if not b.has_key(k):
... | 58,128 |
def binned_to_2x2_image(coverage_start: str, table_id: int, img_binned):
"""
Convert binned detector data to image (1024, 1024)
"""
try:
bin_ckd = BinningTables()
bin_ckd.search(coverage_start)
except Exception as exc:
raise RuntimeError from exc
return bin_ckd.unbin(tab... | 58,129 |
def FulfillISqlInsertOrder(work_order_file: str,
isql_path: str,
user: str,
password: str,
named_graph: str,
isql_port=1111,
virt_folder="/tmp/",
... | 58,130 |
def set_brightness(brightness, channel=None):
"""Set the brightness of all pixels
:param brightness: Brightness: 0.0 to 1.0
"""
setup()
if brightness < 0 or brightness > 1:
raise ValueError("Brightness should be between 0.0 and 1.0")
if channel is None or channel == 0:
for x ... | 58,131 |
def get_foreign_key_desciptors(obj):
"""
finds all :class:`~django.db.models.fields.ForeignRelatedObjectsDescriptor` in obj.
:param obj: A model instance or class.
"""
return _get_members_of_type(obj, ForeignRelatedObjectsDescriptor) | 58,132 |
def plot_components_heatmaps(probabilities, x_test, path):
"""Plots the component heatmaps.
The component heatmaps are the probabilities after the evaluation of
the detection probabilities. The heatmaps visualizing the response to
the component at the respective position. Moreover, this visualization
... | 58,133 |
def create_client(
url: str = CONFLUENCE_URL, token: str = CONFLUENCE_TOKEN
) -> Confluence:
"""Create the Confluence client.
Parameters
----------
url : str
The confluence URL.
token : str
The token with read/write permissions.
"""
s = requests.Session()
s.headers[... | 58,134 |
def test_structure_literal_error(converter_cls):
"""Structuring a class with a literal field can raise an error."""
from typing import Literal
converter = converter_cls()
@define
class ClassWithLiteral:
literal_field: Literal[4] = 4
with pytest.raises(Exception):
converter.str... | 58,135 |
def save_kml_string_to_file(kml_file_path, kml_str):
""" Save a KML String to a KML file for a given path
"""
with open(kml_file_path, 'w') as kml_temp:
kml_temp.write(kml_str)
return | 58,136 |
def error(msg: str, onerrorexit: bool = True, call=None) -> None:
""" Standard error logging. """
if call:
call()
logger.error(msg)
if onerrorexit:
globals.KILLSIG = True
logger.error("Exiting due to error")
sys.exit(1)
return | 58,137 |
def get_unspents(address, blockchain_client=ReddcoinComClient()):
""" Get the spendable transaction outputs, also known as UTXOs or
unspent transaction outputs.
"""
if not isinstance(blockchain_client, ReddcoinComClient):
raise Exception('A ReddcoinComClient object is required')
url = R... | 58,138 |
def to_cpu_async(array, stream=None):
"""Copies the given GPU array asynchronously to host CPU.
Args:
array: Array to be sent to GPU.
stream (~pycuda.driver.Stream): CUDA stream.
Returns:
~numpy.ndarray: Array on CPU.
If given ``array`` is already on CPU, then this functio... | 58,139 |
def make_time(t_str: str) -> Time:
""" Returns Time instance from given t_str.
REQUIRES: t_str is in format 'hh:mm:ss,mms'
"""
hr = int(t_str[:2])
mins = int(t_str[3:5])
sec = int(t_str[6:8])
ms = int(t_str[9:])
return Time(hr, mins, sec, ms) | 58,140 |
def alarm(context):
"""Send the alarm message."""
task = context.result()
bot.send_message(task['chat_id'], text=task['message']) | 58,141 |
def test_mk_to_list(self):
"""Test MK to Python list function."""
mk = "../data/kernels/mk/vco_v01.tm"
ker_mk_list = mk_to_list(mk, False)
self.assertTrue(ker_mk_list)
mk = "../data/kernels/mk/msl_v29.tm"
ker_mk_list = mk_to_list(mk, False)
self.assertTrue(ker_mk_list) | 58,142 |
def get_auth_token(filepath):
"""A function to retrieve a CAM authentication token
Uses a CAM Deployment Service Account JSON file to request a CAM authentication token.
Args:
filepath (str): the location of CAM Deployment Service Account JSON file
Returns:
string: a string for... | 58,143 |
def wide_limit_2l(q: np.ndarray) -> np.ndarray:
"""Compute the limit between resonant and wide-separation caustics.
Args:
q: list of lens mass ratios.
Returns:
limit as a function of q.
"""
cw = (1.0 + q**(1.0 / 3.0))**3 / (1.0 + q)
dw = np.power(cw, 0.5)
return dw | 58,144 |
def force_origin():
"""
changes axis limits so that it will contain the origin
"""
force_axis_to_contain('x', 0)
force_axis_to_contain('y', 0) | 58,145 |
def plot_images(ds,
nr_rows: int,
nr_cols: int,
title: str,
inference_fn: Optional[Callable] = None):
"""Plots a grid of images with their predictions.
Params:
ds: a tensorflow dataset from where to pick the images and labels.
nr_rows, nr_cols... | 58,146 |
def write_24b(filename, rate, data):
"""
Shortcut to write 24 bit audio
:param filename:
:param rate:
:param data:
:return:
"""
assert data.dtype == numpy.uint8
shape = numpy.shape(data)
assert len(shape) == 3
assert shape[2] == 3
_write(filename, rate, data, bitrate=24) | 58,147 |
def get_properties_data():
""" Returning a parser which will be used to read
application.properties file data """
parser = ConfigParser()
parser.read('./application.properties')
return parser | 58,148 |
def getclasstree(classes, unique=False):
"""Arrange the given list of classes into a hierarchy of nested lists.
Where a nested list appears, it contains classes derived from the class
whose entry immediately precedes the list. Each entry is a 2-tuple
containing a class and a tuple of its base classes.... | 58,149 |
def init_pylab(font_kwargs={}):
"""Initialise and clean up the look and feel of the plotting area.
Returns:
``None``.
"""
mpl.rc("lines", linewidth=px2pt(1))
mpl.rc("xtick", **{"direction" : "out" })
mpl.rc("ytick", **{"direction" : "out" })
mpl.rc("legend", frameon=False, fontsize=font_kwargs["size"], nump... | 58,150 |
def float_input(msg):
"""
This methods should be used to request a float value from the user. This
method will not return until the user inputs a valid float value.
:param str msg: Message to be displayed to the user.
:return: Returns the float value inserted by the user.
:rtype: float
"""
... | 58,151 |
def set_option(*opt):
"""
Use this for setting debug flags to libHLC using the same options
available to LLVM.
E.g -debug-pass=Structure
"""
inp = [create_string_buffer(x.encode('ascii')) for x in (('libhlc',) + opt)]
argc = len(inp)
argv = (c_char_p * argc)()
for i in range(argc):
... | 58,152 |
def preprocess_depth(depth_data):
""" preprocess depth data
This function "reverses" the original recorded data, and
convert data into grayscale pixel value.
The higher the value of a pixel, the closer to the camera.
Parameters
----------
depth_data : numpy.ndarray
The data coming from the depth c... | 58,153 |
def show_image_with_boxes(img, objects, calib, show3d=True):
""" Show image with 2D bounding boxes """
img1 = np.copy(img) # for 2d bbox
img2 = np.copy(img) # for 3d bbox
color = (0, 255, 0)
for obj in objects:
if obj.type == 'DontCare':
continue
# if obj.t[2] < 25:
... | 58,154 |
def create_movie():
"""Route handler for the endpoint for creating a new movie.
Returns:
response: A json object representing info about the created movie
"""
try:
movie = Movie(
title=request.json.get("title"),
release_date=request.json.get("release_date"),
... | 58,155 |
def bubble_sort(arr): # Function that performs the bubbleSort
"""
The bubble_sort funtion takes an array as an argument
and then sorts the elements present in that array.
:param arr: A array for sorting
"""
n = len(arr) # Finding the length of the array using the len function
for i in ran... | 58,156 |
def get_client_name_message_map() -> Dict[str, Client]:
"""Gets a dictionary mapping Client names to Client messages.
Returns:
A dictionary mapping Client names to Client messages.
"""
return get_message_maps()[1] | 58,157 |
def groupby_topk(
df: pd.DataFrame,
groupby_column_name: Hashable,
sort_column_name: Hashable,
k: int,
sort_values_kwargs: Dict = None,
) -> pd.DataFrame:
"""
Return top `k` rows from a groupby of a set of columns.
Returns a DataFrame that has the top `k` values grouped by `groupby_colu... | 58,158 |
def changed_keys(a: dict, b: dict) -> list:
"""Compares two dictionaries and returns list of keys where values are different"""
# Note! This function disregards keys that don't appear in both dictionaries
return [k for k in (a.keys() & b.keys()) if a[k] != b[k]] | 58,159 |
def get_interfaces_by_status(dut, status, cli_type=''):
"""
:param dut:
:type dut:
:param status:
:type status:
:return:
:rtype:
"""
cli_type = st.get_ui_type(dut, cli_type=cli_type)
output = get_status(dut, None, cli_type=cli_type)
retval = []
match = {"oper": status} if... | 58,160 |
def test_time_unit_conversion_from_sec(num, from_unit, to_unit, result):
"""Test conversion from seconds."""
assert (
datetimefunc.time_unit_conversion(num, from_unit=from_unit, to_unit=to_unit)
== result
) | 58,161 |
def _negation(value):
"""Parse an optional negation after a verb (in a Gherkin feature spec)."""
if value == "":
return False
elif value in [" not", "not"]:
return True
else:
raise ValueError("Cannot parse '{}' as an optional negation".format(value)) | 58,162 |
def get_all_stealth_cards():
"""Returns a list of all the Stealth Cards"""
class StealthCard:
def __init__(self, card_info):
self.name = card_info["Name"]
self.img_url = card_info["ImageUrl"]
self.cost = card_info["Cost"]
self.description = card_info["Car... | 58,163 |
def add_adsorbate_fractional(surf, adsorbate, x, y, z, mol_index):
"""Add an adsorbate to surf at the fractional coordinates x and y."""
cell_parameters = surf.get_cell()
ax, ay, az = cell_parameters[0]
bx, by, bz = cell_parameters[1]
ase.lattice.surface.add_adsorbate(
surf, adsorbate, z,
... | 58,164 |
def discover_movies(options: dict):
"""Discover movies by different types of data like
average rating, number of votes, genres and certifications.
See available options:
https://developers.themoviedb.org/3/discover/movie-discover
Returns a generator. Each item is a `Movie` object.
"""
para... | 58,165 |
def create_edgelist_from(pairs):
"""
Function to create edgelists for "speaking-in-turn" pairs
Returns results in a way that will be useful in Gephi
"""
# Create edgelist using defaultDict
edges = defaultdict(int)
for people in pairs:
for personA in people:
for personB i... | 58,166 |
def authenticated_session(username, password):
"""
Given username and password, return an authenticated Yahoo `requests`
session that can be used for further scraping requests.
Throw an AuthencationError if authentication fails.
"""
session = requests.Session()
session.headers.update(header... | 58,167 |
def hourly_spatial_agg(date, hour_range=(0,23), cols=["temperature", "pressure", "humidity", "magnetic_tot"]):
"""
For a certain date, get hourly aggregations and count for the desired columns. For available hours.
Parameters
----------
hour_range: int or tuple of int, default (0,23)
Range ... | 58,168 |
def iam_user_info(aws_config=None, username=None):
"""
@type aws_config: Config
@type username: str
"""
iam_client = get_client(client_type='iam', config=aws_config)
try:
user_response = iam_client.get_user(UserName=username)
user = user_response['User']
user_access_keys... | 58,169 |
def create_table(conn, table_format):
""" create a table from the passed table format
and database connection
:param conn: connection object
:param table_format: a CREATE TABLE string
"""
try:
c = conn.cursor()
c.execute(table_format)
except Error as e:
print(e) | 58,170 |
def config_to_ext(conf: Any) -> str:
"""Find the extension(flag) of the configuration"""
if isinstance(conf, dict):
return "dict"
conf = Path(conf)
out = conf.suffix.lstrip(".").lower()
if not out and conf.name.lower().endswith("rc"):
out = "rc"
if out in ("ini", "rc", "cfg", "... | 58,171 |
def escreve_corpus(lista_de_sentencas,nome):
"""A partir de lista de sentenças anotadas, onde cada sentença é uma lista de pares ordenados do tipo de ('palavra','N'), escreve corpus em arquivo de texto 'nome' em que os tokens são etiquetados da forma canônica palavra/N."""
#f=open(os.path.join(USUARIO,nome),"w"... | 58,172 |
def unique_raster_values(dataset):
"""Get list of unique integer values within given dataset.
Args:
dataset: a gdal dataset of some integer type
Returns:
unique_list (list): a list of dataset's unique non-nodata values
"""
band = dataset.GetRasterBand(1)
nodata = band.GetNoData... | 58,173 |
def test_add_iso_entries_to_dict():
"""
Given:
- Dict containing entries with epoch time.
When:
- Adding to entries with epoch time entries with iso time.
Then:
- All 'usecs' keys in the dict are replaced with 'iso time' entries with correct iso values.
"""
tested_dict = {usec_e... | 58,174 |
def random_rat(
nvars: int = 10,
ndegree: int = 20,
nterms: int = 50,
ncoeffbits: int = 32,
seed: int = 42,
) -> RationalFunction:
"""Return a random rational function."""
while True:
r1 = random_poly(nvars, ndegree, nterms, ncoeffbits, seed)
r2 = random_poly(nvars, ndegree, ... | 58,175 |
def _user_can_merge(gh, org, repo, username, addons_dir, target_branch):
"""
Check if a user is allowed to merge.
addons_dir must be a git clone of the branch to merge to target_branch.
"""
gh_repo = gh.repository(org, repo)
if github.github_user_can_push(gh_repo, username):
return True... | 58,176 |
def get_clean_path(path_string, check_for_file=False):
# type: (Union[str, Path], Optional[bool]) -> str
"""
Returns a trimmed, normalized, and expanded path string from the provided one
"""
return_filename = path.expanduser(path.expandvars(path.normpath(str(path_string).strip()))) # type: str
#... | 58,177 |
def start_end_date_for_period(period, default_start_date=False, default_end_date=False):
"""Return the start and end date for a goal period based on today
:param str default_start_date: string date in DEFAULT_SERVER_DATE_FORMAT format
:param str default_end_date: string date in DEFAULT_SERVER_DATE_FORMAT f... | 58,178 |
def encode_pandas_to_tfrecords(df,
feature_keys_spec,
tf_records_path,
example_key=None):
"""Write a pandas `DataFrame` to a tf_record.
Args:
df: pandas `DataFrame`. It must include the fields that are part of
fe... | 58,179 |
def get_status_messages(connection, uid, timeline='home:', page=1, count=30):
"""默认从主页从时间线获取给定页数的最新状态消息,另外还可以获取个人时间线"""
# 获取时间线上最新的状态消息ID
statuses = connection.zrevrange('%s%s' % (timeline, uid),
(page - 1) * count, page * count - 1)
pipe = connection.pipeline(True)
... | 58,180 |
def new(key,mode=MODE_ECB,IV=None,counter=None,segment_size=None):
"""Create a new cipher object
CAST using pycrypto for algo and pycryptoplus for ciphermode
key = raw string containing the keys
mode = python_AES.MODE_ECB/CBC/CFB/OFB/CTR/CMAC, default is ECB
IV = IV as a raw string, de... | 58,181 |
def json(paths_file: str):
"""Load a file with a list of paths, get a json record of some things"""
tei_list = verbapie.tei_list(paths_file)
sys.stdout.buffer.write("{\n".encode('utf8'))
xsl_file = os.path.join(os.path.dirname(__file__), 'cts_json.xsl')
xsl_dom = etree.parse(xsl_file)
transfo = ... | 58,182 |
def validate_obm_settings(client, identifier):
"""
The OBM objects are obtained for the requested node. They are then searched to
determine if at least one has OBM settings.
:param client: reference to config.api2_0_config
:param identifier: ID of node object
return: True - node have OBM sett... | 58,183 |
def run(agent_name=None):
"""
Agent startup procedure
Reads options, sets the environment, does other good things
:param agent_name: str agent name
"""
try:
from setproctitle import setproctitle
proctitle = '%s-agent' % agent_name
setproctitle(proctitle)
except Impor... | 58,184 |
def ensure_all_columns_are_used(num_vars_accounted_for,
dataframe,
data_title='long_data'):
"""
Ensure that all of the columns from dataframe are in the list of used_cols.
Will raise a helpful UserWarning if otherwise.
Parameters
-----... | 58,185 |
def plot_cumulative_pl(positions: Positions) -> None:
"""Plot cumulative pl"""
pl = calculate_pl(positions)
pl.cumsum().plot() | 58,186 |
def with_role_slash_option(
name: str, description: str, /, *, default: typing.Any = _UNDEFINED_DEFAULT, pass_as_kwarg: bool = True
) -> collections.Callable[[_SlashCommandT], _SlashCommandT]:
"""Add a role option to a slash command.
For information on this function's parameters see `SlashCommand.add_role_... | 58,187 |
def gaussian_timeseries(
mean: Union[float, np.ndarray] = 0.0,
std: Union[float, np.ndarray] = 1.0,
start: Optional[Union[pd.Timestamp, int]] = pd.Timestamp("2000-01-01"),
end: Optional[Union[pd.Timestamp, int]] = None,
length: Optional[int] = None,
freq: str = "D",
column_name: Optional[str... | 58,188 |
def routes():
"""
Return all available endpoints in JSON format
"""
routes = []
for rule in app.url_map.iter_rules():
routes.append({
"name": rule.rule,
"method": rule.methods,
"desc" : rule.endpoint
})
app.logger.debug(json_util.dumps(routes))
return(json_util.dumps(routes)) | 58,189 |
def ppipe(
records: Iterator[dict],
*funcs,
records_in_memory: int or None = None,
processes: int or None = None,
) -> Iterator[dict]:
"""
A multi-threaded parallel pipe (or ppipe) which pipes records through it in parallel. Note that each record is still
handled by a chain o... | 58,190 |
def tar_file(file_to_tar, destination_dir, tar_name=''):
"""
tar a file into a desintation dir.
:param file_to_tar:
:param destination_dir:
:param tar_name: optional tar name.
:return:
"""
def _reset_tarinfo(tarinfo):
"""Set all tar'd files to be world-readable, so that other ser... | 58,191 |
def get_specs():
"""
Get FSM specifications stored in this file.
"""
from fsm.fsmspec import FSMSpecification
spec = FSMSpecification(
name='lessonseq',
hideTabs=True,
title='Take the courselet core lessons',
pluginNodes=[START, LESSON, ASK, ASSESS, ERRORS, END],
... | 58,192 |
def test_get_average_user_success_rate():
"""
Author: John Andrée Lidquist
Date: 2017-11-27
Last Updated: 2017-11-27
Purpose: Assert that the average success rate is retrieved from the DataManager correctly
"""
# PRE-CONDITIONS
watched = 9999
not_watched = 8888
average_user_succ... | 58,193 |
def at_least_major_version(major):
"""is the major version (e.g. X, for version X.Y.Z) greater than or equal to the major version integer supplied?"""
return MAJOR >= int(major) | 58,194 |
def test_create_command_executers(mocker, action):
"""
Given:
the action to perform (allow or block)
When:
Calling `create_command_wrappers` to get all the command wrappers for the script.
Then:
Ensure the right commands wrappers are being returned.
"""
from IsolationAss... | 58,195 |
def set_tensornetwork_backend(backend: Optional[str] = None) -> None:
"""
set the runtime backend of tensornetwork
:param backend: numpy, tensorflow, jax, pytorch
:return:
"""
if not backend:
backend = get_default_backend()
backend_obj = get_backend(backend)
for module in module... | 58,196 |
def arrayizeDict(g):
"""Transforms a dict with unique sequential integer indices into an array"""
mk = max(g.keys())
ga = [None] * mk
for k, v in g.items():
ga[k - 1] = v
return ga | 58,197 |
def send_certificate_data(obj, request):
"""Send the zipped certificate data as email.
Verify that the given object has all the flags set, create a zipfile and mail it to the
email address from the certificate.
"""
# Check that email flag is set in the DB
if obj.email:
zip_f = build_zip... | 58,198 |
def wait_for_xvfb(xdisplaycheck, env):
"""Waits for xvfb to be fully initialized by using xdisplaycheck."""
try:
subprocess.check_call(
[xdisplaycheck],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env)
except OSError:
print >> sys.stderr, 'Failed to load %s with c... | 58,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.