content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
async def toggle_inline(m: Message):
"""Turn on | off inline mode of your bot"""
try:
await send_edit(m, "Processing command . . .", mono=True)
await app.send_message("BotFather", "/mybots") # BotFather (93372553)
await asyncio.sleep(1) # floodwaits
data = await get_last_msg(m)
usernames = list(data[0].re... | 55,100 |
def to_cartesian(r, coord_sys):
"""
Transforms an array of vectors from a coord_sys to the cartesian coordinate
system.
:param r: n x 3 matrix of position or any other vectors in spherical
coordinates
:param coord_sys: 'spherical' or 'cylindrical'
:return: n x 3 matrix of position vectors in... | 55,101 |
def pretty_duration(seconds):
"""Return a pretty duration string
Parameters
----------
seconds : float
Duration in seconds
Examples
--------
>>> pretty_duration(2.1e-6)
'0.00ms'
>>> pretty_duration(2.1e-5)
'0.02ms'
>>> pretty_duration(2.1e-4)
'0.21ms'
>>> pr... | 55,102 |
def plotLineStrings(lines,*args,**kwargs):
"""
Plot Polygons
"""
for line in lines:
line.plot(*args,**kwargs) | 55,103 |
def get_red_spot(utdt, jupiter):
"""
GRS:
System II: longitude = 9° (jan 2022), drifts 1.75°/month
best placed within 50m of transit time
"""
u0 = datetime.datetime(2022, 1, 1, 0, 0).replace(tzinfo=pytz.utc)
dd = utdt - u0
delta_longitude = 1.75 * dd.days/30.6001
# We could al... | 55,104 |
def set(key, value, expire=0, path='', filename='linuxfabrik-plugin-cache.db'):
"""Set key to hold the string value.
Keys have to be unique. If the key already holds a value, it is
overwritten, including the expire timestamp in seconds.
Parameters
----------
key : str
The key.
valu... | 55,105 |
def genericlog(log_enabled, pack_resp, is_user, is_clm_superuser, is_cm_superuser, fun, args, kwargs):
"""
Generic log is called by actor decorators defined in src.clm.utils.decorators :
- src.clm.utils.decorators.guest_log
- src.clm.utils.decorators.user_log
- src.clm.utils.decorators.admin_cm_log
... | 55,106 |
def add_page_to_db(title, url, image, category):
""" takes page details and adds a new page to the page model/db
Args:
title: string, the title of the page
url: string, the url of the page
image: string, path to the screenshot of the page
category: the Category class
Returns... | 55,107 |
def users_similarity_score(consumer, producer):
"""
Compute a similarity score between a consumer's and a producer's
signatures. The score is a float between 0 (complete similarity) and 1
(nothing in common).
"""
count_consumer = float(consumer.rated_statuses)
count_producer = float(producer... | 55,108 |
def flip_randomly(inputs, horizontally, vertically, name=None):
"""Flip images randomly. Make separate flipping decision for each image.
Args:
inputs (4-D tensor): Input images (batch size, height, width, channels).
horizontally (bool): If True, flip horizontally with 50% probability. Otherwise, don't.... | 55,109 |
def na2nc(args=None):
"""
Controller for conversion of NASA Ames file to NetCDF file.
"""
if args is None:
args = sys.argv[1:]
arg_dict = parseArgs(args)
nc_file = nappy.convertNAToNC(**arg_dict)
return nc_file | 55,110 |
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the template lights."""
async_add_entities(await _async_create_entities(hass, config)) | 55,111 |
def nested_seq_assert_close(a, b):
"""Assert close to scalar or potentially nested qequences of numeric types and others."""
if isinstance(a, (list, tuple)) or isinstance(b, (list, tuple)):
for a_v, b_v in zip(a, b):
nested_seq_assert_close(a_v, b_v)
else:
if isinstance(a, number... | 55,112 |
def _prepifg_multiprocessing(path, xlooks, ylooks, exts, thresh, crop, params):
"""
Multiprocessing wrapper for prepifg
"""
processor = params[cf.PROCESSOR] # roipac or gamma
if processor == GAMMA:
header = gamma.gamma_header(path, params)
elif processor == ROIPAC:
header = roip... | 55,113 |
def get_active_games(request):
"""Get info of selected game type."""
games = GameType.objects.filter(is_active=True).only(
'name', 'description', 'polls_count', 'image')
data = [
{
'id': game.id,
'name': game.name,
'description': game.description,
... | 55,114 |
def total_mastery(key, sID):
"""
Total Mastery
:param key: API key
:param sID: Summoner ID
:return: The total mastery score of a summoner as an int
"""
url = nabase + '/lol/champion-mastery/v3/scores/by-summoner/' + str(sID) + \
'?api_key=' + key
r = requests.get(url)
... | 55,115 |
def test_delete_tweet():
"""Test deletting from the database"""
#Work for Future Development
assert True | 55,116 |
def generateHitSpecfile(chromosome, pos, snp, GWAS_regions, file_HitSpec, QQplot_SNPexcludeList, disease_data_set_prefix_release_statistics):
""" """
try:
fh_w = open(file_HitSpec, "w")
except IOError, e:
print e
sys.exit(1)
sep = "\t"
fh_w.writelines("snp" +sep+\
... | 55,117 |
def find_entry_point_type(entry_point):
"""
Step 1: If not ENTRY_POINT is defined nor a value is passed, a default
value is used (pipeline.yaml for CLI, recursive lookup for Jupyter client).
If ENTRY_POINT is defined, this simply overrides the default value, but
passing a value overrides the default... | 55,118 |
def plot_time_dist(duration_labels, duration_count):
"""" Pie Chart """
fig = plt.figure(figsize=(16, 13)) # smaller 12, 10
sns.set(font_scale=1.2)
colors = ['#55A868', '#C44E52', '#DD8452', '#4C72B0']
total = sum(duration_count)
ax1 = fig.add_axes([0, 0, .5, .5], aspect=1)
ax1.pie(duratio... | 55,119 |
def sqrt(x: DNDarray, out: Optional[DNDarray] = None) -> DNDarray:
"""
Return the non-negative square-root of a tensor element-wise.
Result is a :py:class:`~heat.core.dndarray.DNDarray` of the same shape as ``x``.
Negative input elements are returned as :abbr:`NaN (Not a Number)`.
Parameters
--... | 55,120 |
def get_buffered_points(points, centroid=None, factor=2.0):
"""
Add buffer to points in a plane. For example, to expand a convex hull
param points: Points we want to buffer
param centroid: Centroid of the points
param factor: Defines scalar product for point vectors
return numpy array of new poi... | 55,121 |
def find_word(board, x, y, maybe_word, index_lst):
"""
:param board: a list that store all four rows
:param x: the x position of a alphabet
:param y: the y position of a alphabet
:param maybe_word: to see the combination of alphabet is in dictionary or not
:param index_lst: the index position of a alphabet
:retu... | 55,122 |
def test_ThreddsCatalog_simplecache_netcdf(thredds_cat_url):
"""Test that ThreddsCatalog allows simplecache:: in url if netcdf as source."""
import os
import fsspec
fsspec.config.conf['simplecache'] = {'cache_storage': 'my_caching_folder', 'same_names': True}
cat = intake.open_thredds_cat(f'simple... | 55,123 |
def roman(num):
"""
Examples
--------
>>> roman(4)
'IV'
>>> roman(17)
'XVII'
"""
tokens = 'M CM D CD C XC L XL X IX V IV I'.split()
values = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
result = ''
for t, v in zip(tokens, values):
cnt = num//v
res... | 55,124 |
def get_available_actions(node,dset):
"""
get next available actions according to dfg flow
"""
graph = get_dfg_graph(dset)
available_nodes = list(graph[node].keys())
return available_nodes | 55,125 |
def test_volume_source_space():
"""Test setting up volume source spaces
"""
fname_vol = op.join(data_path, 'subjects', 'sample', 'bem',
'volume-7mm-src.fif')
src = read_source_spaces(fname_vol)
temp_name = op.join(tempdir, 'temp-src.fif')
try:
# The one in the sam... | 55,126 |
def get_horizontal_angles():
"""Get horizontal visual angles (in °)."""
x = np.arange(0, _WIDTH)
x = x.astype(np.float)
x -= np.mean(x)
a_x = _ANGULAR_RESOLUTION * x
return a_x | 55,127 |
def clone(repo, branch=None, replace=None, skip_existing=None, target_dir=None):
"""
Clone files from a Git repository.
Only the files are copied, not the Git metadata. Can be run multiple
times to clone files from multiple repositories. Won't overwrite
any existing files unless `replace=True`.
... | 55,128 |
def get_pair_image(roidb, config):
"""
preprocess image and return processed roidb
:param roidb: a list of roidb
:return: list of img as in mxnet format
roidb add new item['im_info']
0 --- x (width, second dim of im)
|
y (height, first dim of im)
"""
num_images = len(roidb)
p... | 55,129 |
def create_url(url, data):
"""
Method which creates new url from base url
:param url: base url
:param data: data to append to base url
:return: new url
"""
return url + "/" + str(data) | 55,130 |
def test_item_path(fconfig: Config, db: SQLAlchemy):
"""
Tests that the URL converter works for the item endpoints of
the resources.
The following test has set an URL converter of type int, and will
allow only integers using the flask rules.
"""
DeviceDef, *_ = fconfig.RESOURCE_DEFINITIONS ... | 55,131 |
def is_side_effecting(node):
"""
This determines whether node is a statement with possibly arbitrary side-effects
"""
node = node.value
return isinstance(node, ast.Call) and isinstance(node.func, ast.Name) | 55,132 |
def read_wordlist_file(file_name):
"""
Reads a one-word-per-line list of words to accumulate (w,c) counts for. Duplicates
are collapsed via a dictionary.
"""
word_list = {}
f = open(file_name,'r')
lines = f.readlines()
for l in lines:
word = l.strip()
if len(word) > 0:
... | 55,133 |
def get_onto_class_by_node_type(ont: owlready2.namespace.Ontology, node_label: str):
"""Get an object corresponding to an ontology class given the node label.
`owlready2` doesn't make it easy to dynamically retrieve ontology classes.
This uses some (relatively unsafe) string manipulation to hack together a... | 55,134 |
def get_transceiver_sub_id(ifindex):
"""
Returns sub OID for transceiver. Sub OID is calculated as folows:
sub OID = MODULE_TYPE_PORT + ifindex * PORT_IFINDEX_MULTIPLE
:param ifindex: interface index
:return: sub OID of a port
"""
return (MODULE_TYPE_PORT + ifindex * PORT_IFINDEX_MULTIPLE, ) | 55,135 |
def create_conj_flows(port, conj_id, direction, ethertype):
"""Generate "accept" flows for a given conjunction ID."""
flow_template = {
'priority': 70,
'conj_id': conj_id,
'dl_type': ovsfw_consts.ethertype_to_dl_type_map[ethertype],
# This reg_port matching is for delete_all_port... | 55,136 |
def full_chunk_and_save(phase, examples, feat_spec, tokenizer, args: RunConfiguration):
"""Convert Examples to ListDataset, optionally truncate sequences if possible, and save to disk.
Args:
phase (str): string identifying the data subset (e.g., train, val or test).
examples (list[Example]): li... | 55,137 |
def flush_neighbors(duthost):
""" Clear ARP table to make sure that neighbors learning will be triggered """
duthost.command("sonic-clear arp") | 55,138 |
def delete_table(table_id, user_settings=None):
"""
Deletes a fusion table
:param str table_id: identifier of the fusion table
:param dict user_settings: optional, A dictionary of settings specifying credentials for appropriate services.
If one is not provided, then this met... | 55,139 |
def p_wordlist(p):
"""wordlist : wordlist token
| token"""
if len(p)==2:
p[0] = ['wordlist', ('TOKEN', p[1])]
else:
p[0] = p[1] + [('TOKEN', p[2])] | 55,140 |
def test_benchmark_mat_55():
"""Test benchmark mat[5, 5]."""
benchmark()
ic(benchmark.mat[5, 5])
assert benchmark.mat[5, 5] == 0.5 | 55,141 |
def read_g_cas(in_name):
"""
Read a Gaussian .log file for CAS calculations
Returns the total energy, and gradients for two states
Parameters
----------
in_name : str
Name of the file to read
Returns
-------
energy_e : float
Gaussian total calculated energy in Hartr... | 55,142 |
def query(primary_name, tables, where_clauses=None):
"""
Generates a MySQL SELECT statement to retrieve data. This function recursively
walks the tree of foreign key relationships to build a query that joins all
tables necessary to retrieve full data rows.
:param primary_name: The name of the prima... | 55,143 |
def cost2_lloyd_only_rref(p, et, resp):
""" Cost function for rref with sum of squared deviations """
return np.sum((resp-lloyd_only_rref_p(et,p))**2) | 55,144 |
def get_taxonomic_distribution(rfam_acc, DATA_PATH):
"""
Calculate the percentage of hits from each domain for a family.
Example:
{'Eukaryota': 45.51, 'Bacteria': 48.6, 'Other': 0.0, 'Viruses': 0.0, 'unclassified sequences': 0.0, 'Viroids': 0.0, 'Archaea': 5.9}
"""
data = {}
for domain in D... | 55,145 |
def set_ternary_axis_label(ax, label, position, rotation, event_names=None,
**kwargs):
"""
Sets axis labels and registers a callback to adjust text angle when the
user resizes or triggers a redraw in interactive mode. Not intended to
be called directly by the user.
Parame... | 55,146 |
def _pretty_excepthook(
type_: Type[BaseException], value: BaseException, traceback: TracebackType
) -> None:
"""The actual function that replaces sys.excepthook."""
# restore the original hook so not to paint ourselves in a corner
sys.excepthook = sys.__excepthook__
for line in _prettify_exception(... | 55,147 |
def add_locations(string, args):
""" Adds location links to a snippet string """
string = string.replace(' ', ' ')
locs = args[0]
text = args[1]
for loc in locs:
pattern = re.compile(r'(?<!=)\b{0}[a-zA-Z-]*\b'.format(loc['location']), flags=re.I)
for (match) in re.findall(pattern, s... | 55,148 |
def should_transition(issue):
"""
Return a boolean indicating if the given issue should be transitioned
automatically from "Needs Triage" to an open status.
"""
issue_key = issue["key"]
issue_status = issue["fields"]["status"]["name"]
project_key = issue["fields"]["project"]["key"]
if is... | 55,149 |
def _gaussian1d_no_bg_deriv(p, x):
"""
Required Arguments:
p -- (m) [A,x0,FWHM]
x -- (n) ndarray of coordinate positions
Outputs:
d_mat -- (3 x n) ndarray of derivative values at positions x
"""
x0 = p[1]
FWHM = p[2]
sigma = FWHM/gauss_width_fact
dydx0 = _gaussian1d_no_bg... | 55,150 |
def test_empty_value(check_include_response):
"""An empty value should resolve in no relationships being returned under `included`"""
request = "/structures?include="
expected_types = []
expected_reference_ids = []
expected_data_relationship_types = ["references"]
check_include_response(
... | 55,151 |
def extract_results(results, mode, limit=50):
"""extract result from json style list returned by download_results:
parameters:
results: json style - list with results
mode: str- "ppa" for questions, "organic" for link of answers
limit: int - max number of items per keyword
Returns list of list... | 55,152 |
def getSquareDistance(p1, p2):
"""
Square distance between two points
"""
dx = p1['x'] - p2['x']
dy = p1['y'] - p2['y']
return dx * dx + dy * dy | 55,153 |
def is_owner(func: typing.Awaitable):
"""
Checks if the user is the owner.
"""
func.is_owner = True
return func | 55,154 |
def convert_examples_to_features(examples, max_seq_length, tokenizer):
"""Loads a data file into a list of `InputBatch`s."""
print("#examples", len(examples))
features = [[]]
for (ex_index, example) in enumerate(examples):
tokens_a, tokens_a_speaker_ids, tokens_a_mention_ids = tokenize(example... | 55,155 |
def get_last_version():
"""Get the last version number in guids file if exists.
Returns:
version number.
"""
version_cmake_path = os.path.join(os.getcwd(), "cmake", "firebase_unity_version.cmake")
with open(version_cmake_path, "r") as f:
datafile = f.readlines()
for line in datafile:
if ... | 55,156 |
def grab_sysex_until_clock(port):
"""
generator/filter thing over an iterable of mido messages,
such as mido ports.
Discards all messages before the first SysEx,
then yields all the SysEx messages until a Clock message is sent.
"""
# discard messages until first sysex
for message in port... | 55,157 |
def generate_anatomical_volume_views(*actors, size=(600, 600)):
"""Generate anatomical (coronal anterior, sagittal right and axial
superior) views of the actor(s).
Arguments
---------
actors : vtkActor
Actor(s) to be displayed.
size : Tuple (int, int)
Size of each view.
Ret... | 55,158 |
def getsize(datadescriptor):
"""Get the size of a data descriptor tuple."""
if datadescriptor[0] == 'reg':
size = datadescriptor[1][2]
elif datadescriptor[0] == 'mem':
size = datadescriptor[1][1]
elif datadescriptor[0] == 'heap':
size = datadescriptor[1][2]
elif datadescriptor[0] == 'perp':
size = datade... | 55,159 |
def find_int_in_str(string=None):
"""
trouver les nombres entiers dans une chaine de caractere
en ignorant les signes
:param string: str
:reutrn: ['float', 'float', ...]
"""
response = []
if string: # si la chaine n'est pas vide
response = reg.findall("([0.0-9.9]+)", s... | 55,160 |
def jzczhz_to_jzazbz(jzczhz):
"""JzCzhz to Jzazbz."""
jz, cz, hz = jzczhz
hz = util.no_nan(hz)
# If, for whatever reason (mainly direct user input),
# if chroma is less than zero, clamp to zero.
if cz < 0.0:
cz = 0.0
return (
jz,
cz * math.cos(math.radians(hz)),
... | 55,161 |
def _encode_state_dict(state_dict):
"""Since dicts of (type, state_key) -> event_id cannot be serialized in
JSON we need to convert them to a form that can.
"""
if state_dict is None:
return None
return [(etype, state_key, v) for (etype, state_key), v in iteritems(state_dict)] | 55,162 |
def cleanup_for_test(test_case):
"""
Return a ``Datera Client`and register a ``test_case``
cleanup callback to remove any volumes that are created during each test.
:param test_case object
"""
config = datera_config_from_environment()
datera = DateraBlockDeviceAPI(
cluster_id=config.... | 55,163 |
def IC_SSG(mode, **kwargs):
"""function to compute the information content of a simple graph pattern as proposed in SSG
Args:
mode (int): 1 if pw, kw, nw is provided
2 if supergraph G is provided along with a linst of nodes in subgraph WL
3 if a subgraph pattern ... | 55,164 |
def main(gamepad=None):
"""Vibrate the gamepad."""
if not gamepad:
gamepad = inputs.devices.gamepads[0]
# Vibrate left
gamepad.set_vibration(1, 0, 1000)
time.sleep(2)
# Vibrate right
gamepad.set_vibration(0, 1, 1000)
time.sleep(2)
# Vibrate Both
gamepad.set_vibration(... | 55,165 |
def crossover(parent1, parent2, d):
"""One point crossover
Args:
parent1 (int, (int, int)[])[]): chromosome of parent1
parent2 (int, (int, int)[])[]): chromosome of parent2
d (int): Total duration, in durks, of song
Returns:
((int, int)[],(int, int)[]): returns two ... | 55,166 |
def _StringTraits_read_value_dataset(d, iss, sp):
"""_StringTraits_read_value_dataset(hid_t d, hid_t iss, hid_t sp) -> RMF::HDF5::StringTraits::Type"""
return _RMF_HDF5._StringTraits_read_value_dataset(d, iss, sp) | 55,167 |
def argmaxIndexWithTies(l, f = lambda x: x):
"""
@param l: C{List} of items
@param f: C{Procedure} that maps an item into a numeric score
@returns: the index of C{l} that has the highest score
"""
best = []; bestScore = f(l[0])
for i in range(len(l)):
xScore = f(l[i])
if xSco... | 55,168 |
def get_j2k_parameters(codestream):
"""Return some of the JPEG 2000 component sample's parameters in `stream`.
.. deprecated:: 1.2
Use :func:`~pydicom.pixel_data_handlers.utils.get_j2k_parameters`
instead
Parameters
----------
codestream : bytes
The JPEG 2000 (ISO/IEC 1544... | 55,169 |
def valid_table_shape(obj_file_name, iou_threshold=0.8):
""" Computes the xz bounding box of the vertices with the highest y value (and vertical normals)
and compares this with the xz bounding box of the entire table. If the IoU is high enough,
the table is mostly flat on top.
To filter out... | 55,170 |
def derivative(tensor, shape, dist_metric=DistanceMetric.euclidean, with_normalize=True, alpha=1.0, time=0.0, speed=1.0):
"""
Extract a derivative from the given noise.
.. image:: images/derived.jpg
:width: 1024
:height: 256
:alt: Noisemaker example output (CC0)
:param Tensor tens... | 55,171 |
def backbone_lite(inputs, is_training):
"""mobilenetv2( deleted the global average pooling )
Args:
inputs: a tensor with the shape (bs, h, w, c)
is_training: indicate whether to train or test
Return:
all the end point.
"""
endPoints = collections.OrderedDict()
exp = 6 # ... | 55,172 |
def get_partition_from_arn(arn):
"""Given an ARN string, return the partition string. This is usually `aws` unless you are in C2S or
AWS GovCloud."""
result = parse_arn(arn)
return result["partition"] | 55,173 |
def test_column_name_not_exists(dataframe):
"""Checks that an error is raised if the column to be counted does not exist
in df.
"""
with pytest.raises(
ValueError,
match="_foo_ not present in dataframe columns",
):
dataframe.count_cumulative_unique(
"_foo_",
... | 55,174 |
def _wrapConnect(callableObject):
"""Returns a wrapped call to the old version of QtCore.QObject.connect"""
logger.debug(">>_wrapConnect()")
@staticmethod
def call(*args):
logger.debug(">>call()")
callableObject(*args)
_oldConnect(*args)
return call | 55,175 |
def default_collate(batch: List[Any]) -> Any:
"""The :func:`flash.data.utilities.collate.default_collate` extends `torch.utils.data._utils.default_collate`
to first extract any metadata from the samples in the batch (in the ``"metadata"`` key). The list of metadata
entries will then be inserted into the col... | 55,176 |
def test_solve_with_default_arguments_solves_grid_silently(capsys):
"""Verifies that `solve` using default arguments solves a real grid silently."""
grid = Grid(((2, -1), (0, 0)))
assert solve(grid)
# Test all points in component-wise order
assert grid[0][0].child.location == (0, 1)
assert grid[... | 55,177 |
def to_lowercase(word_list):
"""Convert all characters to lowercase from list of tokenized word_list
Keyword arguments:
word_list: list of words
"""
lowercase_word_list = [word.lower() for word in word_list]
return lowercase_word_list | 55,178 |
def T_from_R_t(R, t):
"""Combine rotation matrix and translation vec into a transform."""
t = t[..., None]
o = np.zeros_like(R[..., -1:, :])
i = np.ones_like(t[..., -1:, :])
return np.concatenate(
[np.concatenate([R, t], axis=-1), np.concatenate([o, i], axis=-1)], axis=-2
) | 55,179 |
def x448(k, u):
"""
Perform point multiplication on X448 curve.
:type k: bytearray
:param k: random secret value (multiplier), should be 56 bytes long
:type u: bytearray
:param u: curve generator or the other party key share
:rtype: bytearray
"""
bits = 448
k = decodeScalar448... | 55,180 |
def lesser_gf_ongrid(energy_grid, ret_gf, sigma_les):
"""
Lesser gf on grid
"""
lesser_gf = np.array([np.dot(np.dot(\
ret_gf[:, :, en], sigma_les[:, :, en]), ret_gf[:, :, en].T.conj())\
for en in range(len(energy_grid))])
lesser_gf = np.swapaxes(lesser_gf, 0, ... | 55,181 |
def getSpecies(head):
"""
Returns the species when the head is given.
"""
for species in toonSpeciesTypes:
if (species == head[0]):
return species | 55,182 |
def sinkhorn_knopp_iteration(cost: np.ndarray, p_s: np.ndarray = None, p_t: np.ndarray = None,
a: np.ndarray = None, trans0: np.ndarray = None,
beta: float = 1e-1, error_bound: float = 1e-3,
max_iter: int = 50) -> Tuple[np.ndarray, n... | 55,183 |
def test_attributes():
"""Create a dict of Mode attributes."""
yield {
"revision_id": 1,
"hardware_id": 1,
"mode_id": 4,
"critical_item": 0,
"description": "",
"design_provisions": "",
"detection_method": "",
"effect_end": "",
"effect_local... | 55,184 |
def test_get_apps(fetch_proxy_mock, client):
"""
GIVEN an HTTP client
WHEN that client requests the /apps endpoint
THEN the client receives a dictionary containing a list of configured apps
"""
with mock.patch('dyno.app.api.control._fetch_proxy', fetch_proxy_mock):
res = client.get(url_f... | 55,185 |
def make_poly_ring(p):
"""
Arguments:
p - prime number >= 2.
Returns a class representing the ring of polynomials over the finite
field Z/(p) =: Zp.
"""
assert(isprime(p)), '%d is not a prime number' %p
class PolynomialsOverZp:
"""
A polynomial's attribute will... | 55,186 |
def get_data():
"""It returns the x and y data points of the plot."""
return h.x, h.y | 55,187 |
def convert_to_score(label_name, label_dict):
"""Converts the classification into a [0-1] score.
A value of 0 meaning non-toxic and 1 meaning toxic.
"""
if label_name=='non-toxic':
return 1-label_dict[label_name]
else:
return label_dict[label_name] | 55,188 |
def write_stream(script, output='trans'):
"""
:param script: Translated Text
:type script: Iterable
:param output: Output Type (either 'trans' or 'translit')
:type output: String
"""
first = operator.itemgetter(0)
sentence, _ = script
printer = partial(print, file=sys.stdout, en... | 55,189 |
def just_one_dot(text):
"""Some metrics can end up with multiple . characters. Replace with a single one"""
rx = re.compile(r"\.+")
return rx.sub(".", text) | 55,190 |
def get_config_file(*args):
"""Return specified args from `~/.plotly/.config`. as tuple.
Returns all if no arguments are specified.
Example:
get_config_file('plotly_domain')
"""
if check_file_permissions():
ensure_local_plotly_files() # make sure what's there is OK
return... | 55,191 |
def deterministic_sort(sequence: Iterable[T]) -> List[T]:
"""Private API that order a sequence of objects lexicographically (by
:obj:`deterministic_name`), removing duplicates, which is needed for determinism.
The main purpose of this function is to deterministically sort a sequence of
PyScaffold exten... | 55,192 |
def iterations(solver: GromovWasserstein,
prob: problems.QuadraticProblem) -> GWOutput:
"""A jittable Gromov-Wasserstein outer loop."""
def cond_fn(iteration, constants, state):
solver = constants
return solver.not_converged(state, iteration)
def body_fn(iteration, constants, state, compu... | 55,193 |
def _CheckFieldName(name):
"""Checks field name is not too long and matches field name pattern.
Field name pattern: "[A-Za-z][A-Za-z0-9_]*".
"""
_ValidateString(name, 'name', _MAXIMUM_FIELD_NAME_LENGTH)
if not re.match(_FIELD_NAME_PATTERN, name):
raise ValueError('field name "%s" should match pattern: %s... | 55,194 |
def inv(a: numpy.ndarray):
"""
usage.matplotlib: 2
usage.orange3: 1
usage.scipy: 13
usage.skimage: 7
usage.sklearn: 6
usage.statsmodels: 127
"""
... | 55,195 |
def test_zombie_cluster_vpc_endpoint():
"""
This method return all cluster vpc_endpoint
:return:
"""
assert len(zombie_cluster_resources.zombie_cluster_vpc_endpoint()) >= 0 | 55,196 |
async def netunnel_client_server(not_started_netunnel_client_server) -> Tuple[NETunnelClient, NETunnelServer]:
"""
Creates a client-server instance of netunnel and return a tuple of (client, server)
"""
client, server = not_started_netunnel_client_server
await server.start()
async with client as... | 55,197 |
def dpAdvisor(subjects, maxWork):
"""
Returns a dictionary mapping subject name to (value, work) that contains a
set of subjects that provides the maximum value without exceeding maxWork.
subjects: dictionary mapping subject name to (value, work)
maxWork: int >= 0
returns: dictionary mapping su... | 55,198 |
def auth0_bounce_login(auth0_setup, navigator, browser, auth0_user):
"""Login into 3scale via RHSSO using /bounce URL"""
bounce_url = auth0_setup[0].replace("/callback", "/bounce")
navigator.open(url=bounce_url)
provider = Auth0View(browser.root_browser)
provider.login(auth0_user["email"], "RedHat12... | 55,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.