content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def check_if_module_installed(module_name):
"""Check if a module is installed.
:param module_name: Name of Module
:return: Bool if module is installed or not
"""
distribution_instance = filter(None, (getattr(finder, 'find_distributions', None) for finder in sys.meta_path))
for res in distributi... | 8,600 |
def __virtual__():
"""Only load if grafana4 module is available"""
return "grafana4.get_org" in __salt__ | 8,601 |
def setup( key=None, force=False ):
"""Do setup by creating and populating the directories
This incredibly dumb script is intended to let you unpack
the Tcl/Tk library Togl from SourceForce into your
PyOpenGL 3.0.1 (or above) distribution.
Note: will not work with win64, both because the... | 8,602 |
def update_gateway_information(GatewayARN=None, GatewayName=None, GatewayTimezone=None):
"""
Updates a gateway's metadata, which includes the gateway's name and time zone. To specify which gateway to update, use the Amazon Resource Name (ARN) of the gateway in your request.
See also: AWS API Documentation
... | 8,603 |
def categories_report(x):
"""Returns value counts report.
Parameters
----------
x: pd.Series
The series with the values
Returns
-------
string
The value counts report.
str1 = False 22 | True 20 | nan 34
str2 = False (22) | True (20) | nan (34)
... | 8,604 |
def train(total_loss, global_step, train_num_examples):
"""Train model.
Create an optimizer and apply to all trainable variables. Add moving
average for all trainable variables.
Args:
total_loss: Total loss from loss().
global_step: Integer Variable counting the number of training steps
... | 8,605 |
def config_module_add():
"""Add module for configuration
Add an available module to the config file. POST json object structure:
{"action": "add", "value": {
"module": "modulename",
"moduleprop": ...
}}
On success, an object with this structure is returned:
... | 8,606 |
def command_add(fname, ctype, **kwa):
"""returns (str) command to add consatants from file to the DB,
ex.: cdb add -e testexper -d testdet_1234 -c test_ctype -r 123 -f cm-confpars.txt -i txt -l DEBUG
"""
exp = kwa.get('experiment', None)
det = kwa.get('detname', None)
runnum ... | 8,607 |
def ustobj2songobj(
ust: up.ust.Ust, d_table: dict, key_of_the_note: int = None) -> up.hts.Song:
"""
Ustオブジェクトをノートごとに処理して、HTS用に変換する。
日本語歌詞を想定するため、音節数は1とする。促音に注意。
ust: Ustオブジェクト
d_table: 日本語→ローマ字変換テーブル
key_of_the_note:
曲のキーだが、USTからは判定できない。
Sinsyでは 0 ~ 11 または 'xx' である。
... | 8,608 |
def detect_ol(table):
"""Detect ordered list"""
if not len(table):
return False
for tr in table:
if len(tr)!=2:
return False
td1 = tr[0]
# Only keep plausible ordered lists
if td1.text is None:
return False
text = td1.text.strip()
... | 8,609 |
def read_dataset_test(data_dir, transforms=None):
"""
Read the Mini-ImageNet dataset.
Args:
data_dir: directory containing Mini-ImageNet.
Returns:
A tuple (train, val, test) of sequences of
ImageNetClass instances.
"""
return tuple([_read_classes(os.path.join(data_dir, 'test'), transforms)]) | 8,610 |
def analyze_syntax(text):
"""Use the NL API to analyze the given text string, and returns the
response from the API. Requests an encodingType that matches
the encoding used natively by Python. Raises an
errors.HTTPError if there is a connection problem.
"""
credentials = GoogleCredentials.get_... | 8,611 |
def _parseArgs(args: List[str]) -> Arguments:
"""
Parse the arguments. Terminates the script if errors are found.
"""
argLen = len(args)
# Initialize the argument values
inputPath: str = None
sheetName: Optional[str] = None
outputPath: Optional[str] = None
# Check if the input path... | 8,612 |
def test_repr_linear(model_class, model_class_repr):
"""Check __repr__ method of LinearPerSegmentModel and LinearMultiSegmentModel."""
kwargs = {"copy_X": True, "positive": True}
kwargs_repr = "copy_X = True, positive = True"
model = model_class(fit_intercept=True, normalize=False, **kwargs)
model_r... | 8,613 |
def kabsch_numpy(X, Y):
""" Kabsch alignment of X into Y.
Assumes X,Y are both (Dims x N_points). See below for wrapper.
"""
# center X and Y to the origin
X_ = X - X.mean(axis=-1, keepdims=True)
Y_ = Y - Y.mean(axis=-1, keepdims=True)
# calculate convariance matrix (for each prot in th... | 8,614 |
def save_trade_history_hdf(df, market, update):
"""
Saves a dataframe of the trade history for a market.
"""
filename = TRADE_DATA_DIR + market + '.hdf5'
if update:
df.to_hdf(filename, 'data', mode='a', complib='blosc', complevel=9, format='table', append=True)
else:
df.to_hdf(fi... | 8,615 |
def _decode(value):
"""
Base64 解码,补齐"="
记得去错多余的“=”,垃圾Docker,签发的时候会去掉
:param value:
:return:
"""
length = len(value) % 4
if length in (2, 3,):
value += (4 - length) * "="
elif length != 0:
raise ValueError("Invalid base64 string")
if not isinstance(value, six.bina... | 8,616 |
def header_elements(fieldname, fieldvalue):
"""Return a sorted HeaderElement list from a comma-separated header string.
"""
if not fieldvalue:
return []
result = []
for element in RE_HEADER_SPLIT.split(fieldvalue):
if fieldname.startswith('Accept') or fieldname == 'TE':
... | 8,617 |
def p_expression_logical_op(p):
"""Parser
expression : expression AND expression
| expression OR expression
"""
result, arg1, op, arg2 = p
if op == '&' or op == ',':
result = lambda: arg1() and arg2()
elif op == '|':
result = lambda: arg1() or arg2()
p[... | 8,618 |
def line2dict(st):
"""Convert a line of key=value pairs to a
dictionary.
:param st:
:returns: a dictionary
:rtype:
"""
elems = st.split(',')
dd = {}
for elem in elems:
elem = elem.split('=')
key, val = elem
try:
int_val = int(val)
dd[k... | 8,619 |
def transform(walls, spaces):
"""svg coords are in centimeters from the (left, top) corner,
while we want metres from the (left, bottom) corner"""
joint = np.concatenate([np.concatenate(walls), np.concatenate(spaces)])
(left, _), (_, bot) = joint.min(0), joint.max(0)
def tr(ps):
x, y = ps[... | 8,620 |
def test_irls_init():
"""
test that all distributions have irls initalizers
"""
dists = [Gamma, Gaussian, InverseGaussian, Binomial, NegativeBinomial,
Poisson]
for dist in dists:
assert hasattr(dist, 'irls_init') | 8,621 |
def get_json(partition: str,
start: float = 0.0,
end: float = 1.0,
return_data: bool = False) -> Union[Path, Dict[Any, Any]]:
"""path, gender, age, result
result=-1 for test set
Example
-------
```
JSON_TRAIN = get_json('train', start=0.0, end=0.8)
JSON_VALID = get... | 8,622 |
def isolate(result_file, isolate_file, mode, variables, out_dir, error):
"""Main function to isolate a target with its dependencies.
Arguments:
- result_file: File to load or save state from.
- isolate_file: File to load data from. Can be None if result_file contains
the necessary information... | 8,623 |
def check_structure(struct):
"""
Return True if the monophyly structure represented by struct is
considered "meaningful", i.e. encodes something other than an
unstructured polytomy.
"""
# First, transform e.g. [['foo'], [['bar']], [[[['baz']]]]], into simply
# ['foo','bar','baz'].
def d... | 8,624 |
def batchify_with_label(input_batch_list, gpu, volatile_flag=False):
"""
input: list of words, chars and labels, various length. [[words,biwords,chars,gaz, labels],[words,biwords,chars,labels],...]
words: word ids for one sentence. (batch_size, sent_len)
chars: char ids for on sente... | 8,625 |
def symbolicMatrix(robot):
"""
Denavit - Hartenberg parameters for n - th rigid body
theta: rotation on «z» axis
d: translation on «z» axis
a: translation on «x» axis
alpha: rotation on «x» axis
"""
return np.array([[0, 0, 0, 0],
[robot.symbolicJointsPositions[0, 0]... | 8,626 |
def magnitude_list(data: List) -> List:
"""
:param data:
:return:
"""
if data is None or len(data) == 0:
return []
if isinstance(data, str):
try:
data = json.loads(data)
except:
data = data
try:
input_data = np.array([i for i in data... | 8,627 |
def generate_keypair(passphrase):
""" Create a pair of keys with the passphrase as part of the key names """
keypath = '/tmp/test_{}_key'.format(passphrase)
command = 'ssh-keygen -t rsa -b 4096 -C "{p}" -P "{p}" -f {k} -q'
command = command.format(p=passphrase,
k=keypath)
... | 8,628 |
def main():
"""
Produces the figure and saves it as a PDF.
"""
plt.clf()
axes = setup_axes()
visuals.plot_output_4axes(axes,
"../../simulations/sudden_5Gyr_5e9Msun_schmidt", "crimson", "O")
visuals.plot_output_4axes(axes,
"../../simulations/sudden_5Gyr_5e9Msun_ts1p0_schmidt", "deepskyblue",
"O")
visuals.p... | 8,629 |
def lookup_axis1(x, indices, fill_value=0):
"""Return values of x at indices along axis 1,
returning fill_value for out-of-range indices.
"""
# Save shape of x and flatten
ind_shape = indices.shape
a, b = x.shape
x = tf.reshape(x, [-1])
legal_index = indices < b
# Convert indice... | 8,630 |
async def test_full_flow(
hass: HomeAssistant,
hass_client_no_auth: Callable[[], Awaitable[TestClient]],
aioclient_mock: AiohttpClientMocker,
current_request_with_host: None,
mock_geocaching_config_flow: MagicMock,
mock_setup_entry: MagicMock,
) -> None:
"""Check full flow."""
assert awa... | 8,631 |
def delete_compute_job():
"""
Deletes the current compute job.
---
tags:
- operation
consumes:
- application/json
parameters:
- name: agreementId
in: query
description: agreementId
type: string
- name: jobId
in: query
description: I... | 8,632 |
def default_init_weights(module, scale=1, nonlinearity="relu"):
"""
nonlinearity: leaky_relu
"""
for m in module.modules():
if isinstance(m, M.Conv2d):
M.init.msra_normal_(m.weight, mode="fan_in", nonlinearity=nonlinearity)
m.weight *= scale
if m.bias is n... | 8,633 |
def cli_modules_remove(
ctx: typer.Context,
module_name: str = typer.Argument(
...,
help="The module name to remove",
),
):
"""
Remove a module.
"""
p = Path("./modules") / Path(module_name)
if not p.is_dir():
typer.echo(
f"{ctx.obj['style']['error']} ... | 8,634 |
def load_dict(dict_path):
"""
Load a dict. The first column is the value and the second column is the key.
"""
result_dict = {}
for idx, line in enumerate(io.open(dict_path, "r", encoding='utf8')):
terms = line.strip("\n")
result_dict[idx] = terms
return result_dict | 8,635 |
def project(x, n):
""" http://www.euclideanspace.com/maths/geometry/elements/plane/lineOnPlane/"""
l = np.linalg.norm(x)
a = normalize(x)
b = normalize(n)
axb = np.cross(a,b)
bxaxb = np.cross(b, axb)
return l * bxaxb | 8,636 |
def topologicalSort(roots, getParents):
"""Return a topological sorting of nodes in a graph.
roots - list of root nodes to search from
getParents - function which returns the parents of a given node
"""
results = []
visited = set()
# Use iterative version to avoid stack limits for large d... | 8,637 |
def resources(ctx, job, gpu):
"""Get experiment or experiment job resources.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples for getting experiment resources:
\b
```bash
$ polyaxon experiment -xp 19 resources
```
For GPU resources
\b
```bash
$ polyaxon experim... | 8,638 |
def get_headers(metric_resource: MetricResource):
"""
Get the headers to be used in the REST query for the given metric.
"""
headers = {}
# no headers will be used
if metric_resource.spec.headerTemplates is None:
return headers, None
# initialize headers dictionary
for item in me... | 8,639 |
def visualize(images: dict, images_originals: dict, max_images: int = 5):
"""
Generate the bokeh plot of the input batch transformation
:param images: list of transformed items (dict of image and other objects)
:param images_originals: list of original items (dict of image and other objects)
:par... | 8,640 |
def indra_upstream_ora(
client: Neo4jClient, gene_ids: Iterable[str], **kwargs
) -> pd.DataFrame:
"""
Calculate a p-value for each entity in the INDRA database
based on the set of genes that it regulates and how
they compare to the query gene set.
"""
count = count_human_genes(client=client)... | 8,641 |
def log(*args, host="127.0.0.1", port=3001, surround=3, **kwargs) -> bool:
"""
Create `Log` object and send to codeCTRL server in cbor format.
The codectrl.log function collects and formats information about
the file/function/line of code it got called on and sends it to
the codeCTR... | 8,642 |
def _take_photo(gopro_instance, interval_secs = 600):
""" Take a photo, this function still in dev """
try:
img = gopro_instance.take_photo();
return img
except TypeError:
tl.send_alert()
return False
except:
tl.send_alert( message = \
'🆘*E️rror desc... | 8,643 |
def evaluate(
forecaster, cv, y, X=None, strategy="refit", scoring=None, return_data=False
):
"""Evaluate forecaster using cross-validation
Parameters
----------
forecaster : sktime.forecaster
Any forecaster
cv : sktime.SlidingWindowSplitter or sktime.ExpandingWindowSplitter
Spl... | 8,644 |
def euler(step, y0):
"""
Implements Euler's method for the differential equation dy/dx = 1/(2(y-1)) on the interval [0,4]
"""
x = [0]
index_x = 0
while x[index_x] < 4:
x.append(x[index_x] + step)
index_x += 1
index_y = 0
y = [y0]
def yprime(y):
yprime = 1 / (2... | 8,645 |
def download_wikipedia_pageids(config, out_file):
"""download and save a summary of all wikipedia pages in a category
:param config: argparse object.
Must have config.wikipedia_category and config.wikipedia_sleep
:param out_file: string, file to save page ids into
"""
category = config.wik... | 8,646 |
def cd_chdir():
"""Sample pytest fixture. """
os.chdir(Path(__file__).parent) | 8,647 |
def get_fileinfo(url: str, proxy: str = '', referer: str = '') -> (str, str, requests.Response):
"""
获取待下载的文件信息
Gets information about the file to be downloaded
:param url: 文件url
:param proxy: 代理
:param referer: 绕反爬
:return: 真实url,文件名,http头部信息 (headers中键值均为小写)
"""
import re
imp... | 8,648 |
def generate_random_solution():
"""generate_random_solution() Generates a random solution of random characters from [ ,!,..A..Z..a..z...~]."""
global answer
#codes for chars [ ,!..A..Z..a..z..~]
chars = list(range(32,127))
solution = []
while len(solution) < len(answer): #generate random so... | 8,649 |
def entrypoint_module(config):
"""Lazily returns the entrypoint module defined in a qaboard config"""
import importlib.util
entrypoint = config.get('project', {}).get('entrypoint')
if not entrypoint:
click.secho(f'ERROR: Could not find the entrypoint', fg='red', err=True, bold=True)
click.secho(f'Add to... | 8,650 |
def getTV_Info():
"""
获取TeamViewer的账号和密码信息
使用 Spy++ 读取特定程序中子窗口及各个控件类的信息,
然后 使用 win32 api 读取文本框中的内容
注意:
# FindWindowEx() 只能查找直接子窗口,因此需要逐级查找
# 该函数的第二个参数用于表示在哪个子窗口继续查找,用于查找包含两个相同类名的子窗口
参考:
https://github.com/wuxc/pywin32doc/blob/master/md/win32gui.md#win32guifindwindowex
... | 8,651 |
def tokenize_words(text):
"""Word segmentation"""
output = []
sentences = split_2_short_text(text, include_symbol=True)
for sentence, idx in sentences:
if is_chinese_string(sentence):
import jieba
output.extend(jieba.lcut(sentence))
else:
output.extend... | 8,652 |
def p_expr(p):
"""
expr : comparer
"""
p[0] = p[1] | 8,653 |
def segmentation_model_func(output_channels, backbone_name, backbone_trainable=True):
""" Creates a segmentation model with the tf.keras functional api.
Args:
output_channels: number of output_channels (classes)
backbone_name: name of backbone; either: 'vgg19', 'resnet50', 'resnet50v2', 'mob... | 8,654 |
def EventAddKwargs(builder, kwargs):
"""This method is deprecated. Please switch to AddKwargs."""
return AddKwargs(builder, kwargs) | 8,655 |
def generate_sidecar(events, columns_selected):
""" Generate a JSON sidecar template from a BIDS-style events file.
Args:
events (EventInput): An events input object to generate sidecars from.
columns_selected (dict): A dictionary of columns selected.
Returns:
dict: A... | 8,656 |
def start_rasa_server(run_event):
""" write endpoints file and start rasa server """
print('START RASA SERVER')
if os.getenv('RASA_ACTIONS_URL') and len(
os.getenv('RASA_ACTIONS_URL')) > 0:
# ensure rasa endpoints file matches RASA_ACTIONS_URL env var
endpoints_file = open(
... | 8,657 |
def eurosense_to_unified(eurosense: IO, unified: IO):
"""
Do the XML conversion from the Eurosense format to the Unified format. Note
that this only deals with XML and doesn't convert other things like synset
ids. For the full conversion pipeline see eurosense2unified in
`pipeline.py`.
"""
w... | 8,658 |
def _filter_artifacts(artifacts, relationships):
"""
Remove artifacts from the main list if they are a child package of another package.
Package A is a child of Package B if all of Package A's files are managed by Package B per its file manifest.
The most common examples are python packages that are in... | 8,659 |
def get_augmented_image_palette(img, nclusters, angle):
"""
Return tuple of (Image, Palette) in LAB space
color shifted by the angle parameter
"""
lab = rgb2lab(img)
ch_a = lab[...,1]
ch_b = lab[...,2]
theta = np.deg2rad(angle)
rot = np.array([[cos(theta), -sin(theta)], [sin(theta), ... | 8,660 |
def autodetect(uri: str, **kwargs) -> intake.source.DataSource:
"""
Autodetect intake source given URI.
Keyword arguments are passed to the source constructor.
If no other source is more suitable, it returns an instance of :class:`intake_io.source.ImageIOSource`, which uses
`imageio <https://githu... | 8,661 |
def test_send_activation_token_to_user(default_settings, user):
""" Deliver a contact email. """
with current_app.test_request_context():
with mail.record_messages() as outbox:
send_activation_token(user)
assert len(outbox) == 1
assert "/auth/activate" in outbox[0].... | 8,662 |
def squeeze__default(ctx, g, self, dim=None):
"""Register default symbolic function for `squeeze`.
squeeze might be exported with IF node in ONNX, which is not supported in
lots of backend.
"""
if dim is None:
dims = []
for i, size in enumerate(self.type().sizes()):
if s... | 8,663 |
def _call_create_pref(a, t, e):
"""
Handler for pref() and user_pref() calls in defaults/preferences/*.js files
to ensure that they don't touch preferences outside of the "extensions."
branch.
"""
if not t.im_self.filename.startswith("defaults/preferences/") or len(a) == 0:
return
... | 8,664 |
def pig_action_utility(state, action, utility):
"""The expected value of choosing action in state.Assumes opponent also plays with optimal strategy.
An action is one of ["roll", "hold", "accept", decline", "double"]
"""
if action == 'roll':
one = iter([1])
rest = iter([2, 3, 4, 5, 6])
... | 8,665 |
def to_canonical_url(url):
"""
Converts a url into a "canonical" form, suitable for hashing. Keeps only scheme,
domain and path. Ignores url query, fragment, and all other parts of the url.
:param url: a string
:return: a string
"""
parsed_url = urlparse(url)
return urlunparse([
... | 8,666 |
def find_and_get_references(arg: Any) -> tuple[OutputReference, ...]:
"""
Find and extract output references.
This function works on nested inputs. For example, lists or dictionaries
(or combinations of list and dictionaries) that contain output references.
Parameters
----------
arg
... | 8,667 |
def get_fdr_thresh(p_values, alpha=0.05):
"""
Calculate the false discovery rate (FDR) multiple comparisons correction threshold for a list of p-values.
:param p_values: list of p-values
:param alpha: the uncorrected significance level being used (default = 0.05)
:type p_values: numpy array
:type alpha: float
... | 8,668 |
def ProcessHighlightColorsRandomOption():
"""Process highlight colors random option"""
OptionsInfo["HighlightColorsRandom"] = None
OptionsInfo["HighlightColorsRandomType"] = None
OptionsInfo["HighlightColorsRandomList"] = None
HighlightColors = "colorclass,table-primary,table-success,table-danger,... | 8,669 |
def _rescue_filter(
flags: RescueRenderFlags, platform_filter: typing.Optional[Platforms], rescue: Rescue
) -> bool:
"""
determine whether the `rescue` object is one we care about
Args:
rescue:
Returns:
"""
filters = []
if flags.filter_unassigned_rescues:
# return whe... | 8,670 |
def penalty(precision, alpha, beta, psi):
"""Penalty for time-varying graphical lasso."""
if isinstance(alpha, np.ndarray):
obj = sum(a[0][0] * m for a, m in zip(alpha, map(l1_od_norm, precision)))
else:
obj = alpha * sum(map(l1_od_norm, precision))
if isinstance(beta, np.ndarray):
... | 8,671 |
def all_ctd_descriptors(
G: nx.Graph, aggregation_type: Optional[List[str]] = None
) -> nx.Graph:
"""
Calculate all CTD descriptors based seven different properties of AADs.
:param G: Protein Graph to featurise
:type G: nx.Graph
:param aggregation_type: Aggregation types to use over chains
... | 8,672 |
def get_report_hash(report: Report, hash_type: HashType) -> str:
""" Get report hash for the given diagnostic. """
hash_content = None
if hash_type == HashType.CONTEXT_FREE:
hash_content = __get_report_hash_context_free(report)
elif hash_type == HashType.PATH_SENSITIVE:
hash_content = _... | 8,673 |
def parse_json_file(json_file_path, allow_non_standard_comments=False):
"""
Parse a json file into a utf-8 encoded python dictionary
:param json_file_path: The json file to parse
:param allow_non_standard_comments: Allow non-standard comment ('#') tags in the file
:return: Dictionary re... | 8,674 |
def update_softwaretitle_packages(api, jssid, pkgs):
"""
Update packages of software title
:param jssid: Patch Software Title ID
:param pkgs: dict of {version: package, ...}
:returns: None
"""
logger = logging.getLogger(__name__)
data = api.get(f"patchsoftwaretitles/id/... | 8,675 |
def get_balances(session: Session, redis: Redis, user_ids: List[int]):
"""Gets user balances.
Returns mapping { user_id: balance }
Enqueues in Redis user balances requiring refresh.
"""
# Find user balances
query: List[UserBalance] = (
(session.query(UserBalance)).filter(UserBalance.user... | 8,676 |
def set_pixel(pixel_num, brightness):
"""Set one pixel in both 16-pixel rings. Pass in pixel index (0 to 15)
and relative brightness (0.0 to 1.0). Actual resulting brightness
will be a function of global brightness and gamma correction."""
# Clamp passed brightness to 0.0-1.0 range,
# apply gl... | 8,677 |
def kmeans(observations: ndarray, k: Optional[int] = 5) -> Tuple[ndarray, ndarray]:
"""Partition observations into k clusters.
Parameters
----------
observations : ndarray, `shape (N, 2)` or `shape (N, 3)`
An array of observations (x, y) to be clustered.
Data should be provided as:
... | 8,678 |
def encloses(coord, points):
""" """
sc = constants.CLIPPER_SCALE
coord = st(coord.to_list(), sc)
points = st(points, sc)
return pyclipper.PointInPolygon(coord, points) != 0 | 8,679 |
def cli_transpose_mat_vec(mat_shape, vec_shape, optimize, **kwargs):
"""``A -> A^T, A^Tx = b``."""
i, j = dimensions('i j')
A = Function(name='A', shape=mat_shape, dimensions=(i, j))
x = Function(name='x', shape=vec_shape, dimensions=(j,))
b = Function(name='b', shape=vec_shape, dimensions=(i,))
... | 8,680 |
def arpls(y, lam, ratio=1e-6, niter=1000, progressCallback=None):
"""
Return the baseline computed by asymmetric reweighted penalized least squares smoothing, arPLS.
Ref: Baseline correction using asymmetrically reweighted penalized least squares smoothing
Sung-June Baek, Aaron Park, Young-Jin Ahn a... | 8,681 |
async def test_function_raised_exception(dut):
"""
Test that exceptions thrown by @function coroutines can be caught
"""
@cocotb.function
async def func():
raise ValueError()
@external
def ext():
return func()
with pytest.raises(ValueError):
await ext() | 8,682 |
def dismiss_notification_mailbox(notification_mailbox_instance, username):
"""
Dismissed a Notification Mailbox entry
It deletes the Mailbox Entry for user
Args:
notification_mailbox_instance (NotificationMailBox): notification_mailbox_instance
username (string)
Return:
bo... | 8,683 |
def knn(x, y, k, predict_x):
"""
knn算法实现,使用欧氏距离
:param x: 样本值
:param y: 标签
:param k: 个数
:return:
"""
assert isinstance(y, np.ndarray)
y = y.flatten('F')
def cal_distance(a, b):
return np.sqrt(np.sum(np.power(a - b, 2), axis=0))
dists = {
}
f... | 8,684 |
def piano():
"""A piano instrument."""
return lynames.Instrument('Piano', abbr='Pno.', transposition=None,
keyboard=True, midi='acoustic grand',
family='percussion', mutopianame='Piano') | 8,685 |
def extract_fields(obj: Any) -> Dict[str, Any]:
"""A recursive function that extracts all fields in a Django model, including related fields (e.g. many-to-many)
:param obj: A Django model
:return: A dictionary containing fields and associated values
"""
sub_content = {}
if obj is not None:
... | 8,686 |
def test_student_group(student_group):
""" Студенческая группа """
assert str(student_group) == 'Б-ИВТ-19-1'
assert student_group.get_education_year(4040) == 1
assert student_group.get_education_year(4041) == 2 | 8,687 |
def test_non_empty_group(test_file_name,compression_kwargs):
""" Test if attempting to dump to a group with data fails """
hickle.dump(None, test_file_name,**compression_kwargs)
with pytest.raises(ValueError):
dump(None, test_file_name, 'r+',**compression_kwargs) | 8,688 |
def decomposeM(modified):
"""Auxiliary in provenance filtering: split an entry into name and date."""
splits = [m.rsplit(ON, 1) for m in modified]
return [(m[0], dtm(m[1].replace(BLANK, T))[1]) for m in splits] | 8,689 |
def main():
"""
This function is where the program begins.
It is the general menu for the hotel.
"""
clear()
print("Welcome. This is Summer Square Hotel\n")
while True:
print("\nWhat may we offer you today?\n")
print("1. View our rooms")
print("2. Look at o... | 8,690 |
def update(data):
"""
TODO:
find a way to call collection.findOneAndUpdate(), currently pymodm .update()
only returns the number of updated record.
"""
try:
required_fields = ['id']
validator.validate_required_fields(required_fields, data)
cleaned_data = user_pre... | 8,691 |
def get_2d_peaks_coords(
data: np.ndarray, size: int = None, threshold: float = 0.5
) -> np.ndarray:
"""Detect peaks in image data, return coordinates.
If neighborhoods size is None, default value is the highest value
between 50 pixels and the 1/40th of the smallest image dimension.
Detection thre... | 8,692 |
def border_positions_from_texts(texts, direction, only_attr=None):
"""
From a list of textboxes in <texts>, get the border positions for the respective direction.
For vertical direction, return the text boxes' top and bottom border positions.
For horizontal direction, return the text boxes' left and rig... | 8,693 |
def progress(self):
"""Check if foo can send to corge"""
return True | 8,694 |
def write_sample_sdf(input_file_name, valid_list):
"""
Function for writing a temporary file with a subset of pre-selected
structures
:param input_file_name: name of input file
:param valid_list: list of indexes of pre-selected structures
:return: name of subsampled file
"""
sample_fil... | 8,695 |
def rotx(theta, unit="rad"):
"""
ROTX gives rotation about X axis
:param theta: angle for rotation matrix
:param unit: unit of input passed. 'rad' or 'deg'
:return: rotation matrix
rotx(THETA) is an SO(3) rotation matrix (3x3) representing a rotation
of THETA radians about the x-axis
r... | 8,696 |
def _table(*rows: Sequence) -> str:
"""
>>> _table(['a', 1, 'c', 1.23])
'|a|1|c|1.23|'
>>> _table(['foo', 0, None])
'|foo|||'
>>> print(_table(['multiple', 'rows', 0], ['each', 'a', 'list']))
|multiple|rows||
|each|a|list|
"""
return '\n'.join([
'|'.join(['', *[str(cell o... | 8,697 |
def test_workflow_preprocessors_not_list_error() -> None:
"""
preprocessors should be of type [`PluginFn`](../../plugin/test_plugins.html)
"""
with pytest.raises(TypeError):
_ = Workflow(preprocessors=10, postprocessors=[]) | 8,698 |
def trunc(s, n):
"""
Truncate a string to N characters, appending '...' if truncated.
trunc('1234567890', 10) -> '1234567890'
trunc('12345678901', 10) -> '1234567890...'
"""
if not s:
return s
return s[:n] + '...' if len(s) > n else s | 8,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.