content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def deubiquitinase():
"""Curate deubiquitinases."""
return _render_func(
get_dub_statements,
title="Deubiquitinase Curator",
description=f"""\
The deubiquitinase curator identifies INDRA statements using INDRA
CoGEx whose subjects are human deubiquitinase genes an... | b41bf1fb83c1bb16e1ca863ca65b01608ef39799 | 3,609,187 |
def mark(name=None) -> Node:
"""
Mark is a pseudonym of identity. The idea is to mark (associate a name) internal placeholders
(from the graph point of view).
:param name: The identifier of the identity node
:return:
"""
return Identity(name) | 9be9ed3e8f3b2009bc672a43d5a7c177c57b1611 | 3,609,188 |
def create_maf_record_from_vcf(sample_id, center_name, sequence_source, vcf_data, is_germline_data, matched_normal_sample_id, tumor_sample_data_col):
"""
Creates MAF record from VCF data.
"""
# init maf record
maf_data = init_maf_record()
# set easy to resolve values
maf_data["Tumor_Sam... | 07cec878d8f7d76226f9ffa4e779171323c057dc | 3,609,189 |
def disable_by_type(token, _type, disable=False, customerid=None):
""" Toggle a check so it is enabled or disabled.
Accepts an API token, the checkid of the check to be toggled,
whether it's enabled/disabled (disable by default), and the
customerid if the check is a part of a subaccount
:type toke... | c8bf31b5a4e44f6f0593aefc891416d10a1f2678 | 3,609,190 |
def delete_reports_endpoint():
"""A Flask route which accepts a list of report filenames and then deletes them
from the reports path.
This endpoint should be json and the body should be in
the format {"data":"filenames":["file1.xlsx","file2.xlsx", ...]}
This is a POST request but is a destructive ac... | 8f448ca529472c3bcef33cb656e7d3eebb8b643d | 3,609,191 |
async def deep_into(url, _list, get):
"""Test for getting references. Used for raw scan."""
try:
resp = await get(url)
new_resp = resp
if "uri" in new_resp:
new_resp["uri"] = remove_all_ip_occurs(resp["uri"])
if "id" in new_resp and new_resp["id"] == "/gateway/uuid":
... | d5cb6d4169c5653b5db6f132783bc6039de4756e | 3,609,192 |
def get_param_server_cache():
"""
Get a handle on the client-wide parameter server cache
"""
global _param_server_cache
if _param_server_cache is None:
_param_server_cache = ParamServerCache()
return _param_server_cache | 3c5b0547c263aefaebead7a63ac2ff4722bae9ca | 3,609,193 |
def sanitize (s):
"""
Removes HTML tags, replaces HTML entities and unescapes the text so that
only human generated content remains.
"""
s = preserve_quotes(s)
s = preserve_code(s)
s = replace_newlines(s)
s = remove_meta(s)
return unescape(s) | 5cf30686177ca2110a6170783f1694a51d2c8ec4 | 3,609,194 |
def get_auth_id_from_user_id(user_id):
"""Returns the auth ID associated with the given user ID.
Args:
user_id: str. The auth ID.
Returns:
str|None. The user ID associated with the given auth ID, or None if no
association exists.
"""
return platform_auth_services.get_auth_i... | b4d47ea370c81f1668f57642aa7fb43f08e9c31a | 3,609,195 |
def make_property(name, bit, size=1, type=bool, var="flags"):
"""Helper function for make_struct which defines properties based on
bit fields. This is called automatically for "flags" when passing a
list of flags to make_struct, but can also be added to init_exec to
handle flags in other variables if n... | c891e7bf87f3842fb6e0e1577f26b8906feadd86 | 3,609,196 |
def get_southwest_ray(bitboard: np.uint64, from_square: int) -> np.uint64:
"""
Returns a bitboard of southwest sliding piece attacked squares on an otherwise empty board
:param bitboard: The bitboard representing the southwest ray sliding attacks from `square`
:param from_square: The square from a south... | 546a2df681cec125890349e82d75c47c668b27b1 | 3,609,197 |
def register():
"""Register a user: produce form and handle form submission."""
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
user = User.register(username, password)
db.session.add(user)
db.session.commit()
... | 1f3a0ee30d816b70adf7dc69c638b5c8f3a8b841 | 3,609,199 |
def read_DICOM_files(lstFilesDCM):
""" Reads input DICOM Files.
Args:
----
lstFilesDCM (list): List containing the file paths of the DICOM Files.
Returns:
-------
files (list): List containing the pydicom datasets.
ArrayDicom (numpy.array): Image resulting from the stack of... | 10c6baaca287be2dceb26be05867f1500b779bcc | 3,609,200 |
def ecdsa_sign(sk, msg, k=None):
"""Sign ecdsa"""
sig = sk.sign(msg, hashfunc=sha3.sha3_256, k=k)
signature = util.sigdecode_string(sig, order)
return signature | 845b3749b8e3f10bd92dc33210c9aa0fcea8c854 | 3,609,201 |
def central_difference_of_log(f, argnum=0):
"""
5th order approximation of derivative of log(f). We take advantage of the fact:
d(log(f))/dx = 1/f df/dx
So we approximate the second term only.
"""
new_f = lambda x, *args: f(*args[:argnum], x, *args[argnum:])
def _central_difference(_, *ar... | 07f4c7134132891b5b7fabaa8ae155baebda06d0 | 3,609,202 |
def solve_tsp(V, c):
"""solve_tsp -- solve the traveling salesman problem
- start with assignment model
- check flow from a source to every other node;
- if no flow, a sub-cycle has been found --> add cut
- otherwise, the solution is optimal
Parameters:
- V: set/list of... | c89df17304aa2d389917842c952da1645729da6b | 3,609,203 |
def is_option(string):
"""Whether that string looks like an option to vim
>>> is_option('-p') and is_option('+/sought')
True
"""
end = 'finished'
if is_final_option(string):
setattr(is_option, end, True)
if getattr(is_option, end, False):
return False
return is_dash_opti... | 718a086233fae8046170c2d626e224da9056fc20 | 3,609,204 |
def get_sources(dataframe):
"""
extract sources
:param pandas.core.frame.DataFrame dataframe:
:rtype: set
:return: set of archive.org links
"""
sources = set()
for index, row in dataframe.iterrows():
sources.update(row['incident_sources'].keys())
return sources | 468c0cf6428833c9b05c06415917a516471189a5 | 3,609,205 |
def cleanupCallback(context=None):
"""Create a cleanup callback to clear context-specific storage for the current context"""
def callback(context=contextdata.getContext(context)):
"""Clean up the context, assumes that the context will *not* render again!"""
contextdata.cleanupContext(context)
... | 4368b39265cddea8842e98049f14836e34f63228 | 3,609,206 |
def rupture_name_to_id(rupture_names: np.ndarray, erf_ffp: str):
"""Converts the given ruptures names to rupture ids
Parameters
----------
rupture_names: numpy array of strings
erf_name: str
Returns
-------
numpy array of strings
"""
return np.char.add(rupture_names.astype(str)... | 5d43f460cb6a0e238b648cf3a6a8dbb5f07450d7 | 3,609,207 |
import sqlite3
def get_info(db: sqlite3.Connection) -> dict:
"""
Get all other information from the database, e.g. information about models,
decks etc.
Args:
db: Database (:class:`sqlite3.Connection`)
Returns:
Nested dictionary.
"""
return read_info(db, "col") | 66380b89162fde3c8a86c29705fca91343e64a21 | 3,609,209 |
import urllib
def postForm(url, headers=None, data=None):
"""
post form数据
:param url:
:param headers:
:param data:
:return: code, headers, data
"""
if data:
data = urllib.urlencode(data)
if headers:
headers['Content-Type'] = 'application/x-www-form-urlencoded'
... | 512961ae081f9cf4b4c34ee122e150202bc31c45 | 3,609,210 |
from datetime import datetime
def set_mediafile_attrs(mediafile, ufile, data, user):
"""
Copy metadata from uploaded file into Model
"""
mediafile.name = ufile.name
mediafile.original_filename = ufile.name
mediafile.filesize = ufile.size
mediafile.original_path = data['pathinfo0']
# Da... | e7c373dadb3cd0087184fc725fb749e1a13e0b57 | 3,609,211 |
def remove_bias(name='bias_correct'):
"""
This workflow estimates a single multiplicative bias field from the
averaged *b0* image, as suggested in [Jeurissen2014]_.
.. admonition:: References
.. [Jeurissen2014] Jeurissen B. et al., `Multi-tissue constrained
spherical deconvolution for im... | 31d7a0f4dbe0331cf06bd9828529e44e269dc572 | 3,609,212 |
def filter_dis(js, status):
"""Converts `json` to `DataFrame`
"""
data = []
filter_tits = ["Wildfires", "Severe_Storms", "Sea_and_Lake_Ice"]
for x in js["events"]:
tit = x["categories"][0]["title"].replace(" ","_")
if tit not in filter_tits:
continue
try:
... | 3bf73d631573d53fae241667076746b26dab63a2 | 3,609,213 |
from typing import Dict
from typing import Any
def _apply_templating_directives(
stringified_compose_spec: str,
services: Dict[str, Any],
spec_services_to_container_name: Dict[str, str],
) -> str:
"""
Some custom rules are supported for replacing `container_name`
with the following syntax `%%c... | e37054ac0dce220d70817c99614dc987c3b1aa30 | 3,609,214 |
import torch
def norm(x):
"""Compute RMS norm."""
if torch.is_tensor(x):
return x.norm() / (x.numel()**0.5)
else:
return torch.sqrt(sum(x_.norm()**2 for x_ in x) / sum(x_.numel() for x_ in x)) | ca260c04029699d5febef2717a18af133647cc77 | 3,609,215 |
def assume_role(credentials, account, role):
"""Use FAWS provided credentials to assume defined role."""
sts = boto3.client(
'sts',
aws_access_key_id=credentials['accessKeyId'],
aws_secret_access_key=credentials['secretAccessKey'],
aws_session_token=credentials['sessionToken'],
... | f2a728e3c4f2b7d9b51dee7af982e201d80feadb | 3,609,216 |
import ipaddress
def is_valid_ipv6_address(ip):
"""Return True if valid ipv6 address """
try:
ipaddress.IPv6Address(ip)
return True
except ipaddress.AddressValueError:
return False | 33f4785e768f5117c6fe43c320e2290791fc86a5 | 3,609,217 |
def create_nested_grid_samples(order, dim=1):
"""
Create samples from a nested grid.
Args:
order (int):
The order of the grid. Defines the number of samples.
dim (int):
The number of dimensions in the grid
Returns (numpy.ndarray):
Regular grid with ``sha... | 5238f4d58eb93ace74537c7a166a84cc21451e41 | 3,609,218 |
from typing import Union
from typing import Sequence
def validate_string_encoding(value: StringEncodingArgument) -> StringEncoding:
"""Validates and coerces a value to a StringEncoding.
Parameters
----------
value : StringEncodingArgument
The value to validate and coerce.
If this is a... | 8bcae2d31ae8ab51bd389291a267d23803f5e295 | 3,609,219 |
from typing import Optional
def get_link(prefix: str, identifier: str, use_bioregistry_io: bool = True) -> Optional[str]:
"""Get the best link for the CURIE, if possible."""
providers = get_providers(prefix, identifier)
for key in LINK_PRIORITY:
if not use_bioregistry_io and key == "bioregistry":
... | ec04920fca40f028b343d829fb074636a890a2f9 | 3,609,220 |
def calc_case_peaks_and_indices_fd(forces, disps):
"""
Calculates the cumulative change stored energy for an oscillating system at the peaks
Note: This quantity is double the area of the triangles in a full cycle, since positive and negative
triangles are counted.
>>> disp = np.array([0, 4, 0, -2,... | 2297916d7b580a74f141440d5bafb61cae5f0b30 | 3,609,222 |
def _smooth_spm(con, vcon, msk, sigma):
"""
Given a contrast image `con` and the corresponding variance image
`vcon`, both assumed to be estimated from non-smoothed first-level
data, compute what `con` and `vcon` would have been had the data
been smoothed with a Gaussian kernel.
"""
scon = _... | 9c362d74d021ded14b79c11da1546bcc12e1cfa5 | 3,609,223 |
import torch
def to_tensor(data: FeatureDataType) -> torch.Tensor:
"""
Convert data to tensor
:param data which is either numpy or Tensor
:return torch.Tensor
"""
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, np.ndarray):
return torch.from_numpy(data)... | 57532ce73e5bd595be1fad01968c1160968e5a88 | 3,609,225 |
import inspect
def case(pattern: str):
"""
Use `case` as a decorator for functions, with full unpacking of the argument(s).
```
@case("[x @ int|float, *y]")
def foo(x, y):
...
```
Guards are not supported at the moment.
"""
def decorate(f):
name = f.__code__.co_nam... | 9019fe77bbd3aec7d098d4be684830dce1947364 | 3,609,226 |
import random
def generate_chars(charset: tuple[int, int], count: int) -> str:
"""Character generation routine for execution in a process pool."""
characters = "".join(chr(random.randint(charset[0], charset[1])) for i in range(count))
return discord.utils.escape_markdown(characters) | ea98d0378f808f96cde73e7ae7f5f90ee4920496 | 3,609,228 |
from typing import Union
def get_simple_graph_from_multigraph(multigraph: Union[nx.MultiGraph, nx.MultiDiGraph]) -> nx.Graph:
"""Convert undirected graph from multigraph."""
graph = Graph()
for u, v, data in multigraph.edges(data=True):
u = get_label_node(u)
v = get_label_node(v)
... | 43dcc389988535be15946834303735a948cf0550 | 3,609,229 |
def get_list_view_name(model):
"""
Return list view name for model.
"""
return '{}-list'.format(
model._meta.object_name.lower()
) | 765f4b2456d319a6cc5657dbe1e04d3eab471b42 | 3,609,230 |
import warnings
import copy
from re import T
def PCA_latentFeatures(
spark,
idf,
list_of_cols="all",
drop_cols=[],
explained_variance_cutoff=0.95,
pre_existing_model=False,
model_path="NA",
standardization=True,
standardization_configs={"pre_existing_model": False, "model_path": "N... | 014ae67d51eea6d2cca6aed0900ac502a3083e1e | 3,609,231 |
def google_maps(maiden: str, center: bool = False) -> str:
"""
generate Google Maps URL from Maidenhead grid
Parameters
----------
maiden : str
Maidenhead grid
center : bool
If true, return the center of provided maidenhead grid square, instead of default south-west corner
... | 48c9596565e6d4d06eaba0745c35c2f668d93d38 | 3,609,233 |
def make_prompt(title, context=''):
"""
input:
a twee title ie
:: titlename
output:
a twee title surounded by GPT-3 readable start/end tokens
<begin tokens>:: titlename<end tokens>
"""
if context:
context = context.strip() + ENDCONTEXT
return BEGIN + context + title + ENDPROMPT | 6ffd4c7fdbbd3d115357e8af39e1b4f970b49b30 | 3,609,234 |
from typing import Callable
def warm_up_polynomial_schedule(
base_learning_rate: float,
end_learning_rate: float,
decay_steps: int,
warmup_steps: int,
decay_power: float,
) -> Callable:
"""Please see uncertainty_baselines.schedules.WarmUpPolynomialSchedule.
"""
poly_schedule = optax.polynomi... | 4ea2cce90b46e2980d5d3016c65be551a620aa54 | 3,609,235 |
import copy
def render_plugins(plugins, context, placeholder, processors=None):
"""
Renders a collection of plugins with the given context, using the appropriate processors
for a given placeholder name, and returns a list containing a "rendered content" string
for each plugin.
This is the mai... | 2217033cea70a0c88dd6ab378cfc60f71ccfaa4f | 3,609,236 |
def getkey(value, key):
"""
Return a dictionary item specified by key
"""
return value[key] | 708ee08610b97180be0e0c118646ff853bc7b2a6 | 3,609,237 |
import scipy
def direct_2d2(x, x_s, dx, dt, c, f):
"""Use the 2D Green's function to determine the wavefield at a given
location and time due to the given source.
"""
r = np.linalg.norm(x - x_s)
nt = len(f)
def func(tp, t):
return f[int(tp / dt)] / np.sqrt(c**2 * (t - tp)**2 - r**2)
... | bd85f4a2a7a3a826722dde593a03e30b57bf4c23 | 3,609,238 |
def spring1s(ep,ed):
"""
Compute element force in spring element (spring1e).
:param float ep: spring stiffness or analog quantity
:param list ed: element displacements [d0, d1]
:return float es: element force [N]
"""
k = ep
return k*(ed[1]-ed[0]); | 8253fcde40ecd1b66d7db99348297f2239faa23d | 3,609,239 |
def add_comment(msg, user_id):
"""Add a comment to our comments list."""
# Create comment entity in datastore and add comment fields to it
ds_comment = ds_create_comment(user_id)
ds_comment['commenter'] = msg.commenter
ds_comment['text'] = msg.text
ds_comment['time'] = msg.time
try:
... | c15ca5bee4569fe967a0e53ebdf19b67801bb5b2 | 3,609,240 |
import requests
def capture_payment(order_id, access_token, transaction_amount=0, transaction_text="Capture"):
"""
Captures the reserved payment for the provided order id.
:param order_id: ID for the transaction.
:param access_token: A token for authorizing the request to Vipps.
:param transactio... | b77759eee3d19e317b1b7bf955b43a814290dc79 | 3,609,241 |
from typing import List
from typing import NamedTuple
def get_user_models(creds: PostgresCredentials, uid: str) -> List[NamedTuple]:
"""DB function used to retrieve
models for a given user
Args:
uid (str): [
Returns:
List[NamedTuple]: [description]
"""
with get_cursor(creds)... | 473b11c78bc876b2f29380a75f1c6397d149c065 | 3,609,243 |
def distance(x_1, x_2, method='euclidean'):
"""Pairwise distance metric between two vectors.
The vectors are assumed to be rows.
Parameters
----------
x_1 : array-like
One of two vectors to compute distance between.
x_2 : array-like
One of two vectors to compute distance between... | 497318964daf10676bc928c85b1d700b1ecb59ff | 3,609,244 |
import copy
import re
def ip_match_replace(request, injectionstring):
"""
Simple match and replace of string within request
"""
newrequest = copy.deepcopy(request)
rawrequest = request.get_raw_request()
for r in INJECT_MATCH_REPLACE:
regex = re.compile(r)
if regex.search(rawreq... | 75911b68a9540d8d5a7b743bfdef4cd6eb02f38c | 3,609,245 |
def _putheader_wrapper(func, instance, args, kwargs):
"""
This is the wrapper of the function that called after that the http request was sent.
Note that we don't examine the response data because it may change the original behaviour (ret_val.peek()).
"""
kwargs["headers"]["X-Amzn-Trace-Id"] = Spans... | d2b24aa700bbcd407ac34ba2a69f49fea1ddfc19 | 3,609,247 |
def _validate_workflow_var_format(value: str) -> str:
"""Validate workflow vars
Arguments:
value {str} -- A '.' seperated string to be checked for workflow variable
formatting.
Returns:
str -- A string with validation error messages
"""
add_info = ''
parts = value.s... | 01f58acc27d9b04b59e4991094e2bda7f125f54b | 3,609,248 |
from typing import Literal
async def authenticate(
username: str, password: str
) -> Result[Literal[False], account_dao.Account]:
"""認証
"""
got_account = await account_dao.find(username=username)
if got_account is None or not verify_password(
plain_password=password, hashed_password=got_ac... | 720fc8c9bb6710b74dfc61e43f11ffed8e3d809b | 3,609,249 |
def mock_command_checker(mocker: MockerFixture) -> MockerFixture:
"""Fixture for mocking CommandChecker.check."""
return mocker.patch("git_portfolio.use_cases.command_checker.CommandChecker.check") | 7d78f340cfd53a1ddf43c57b50eac312858fe465 | 3,609,250 |
import imghdr
from datetime import datetime
def write_id3v2_header( data, fields ):
"""Add an ID3v2 header to the data assuming none already present"""
body = bytes()
if 'title' in fields:
title_bytes = b'\x03' + fields['title'].encode( 'utf_8' )
body += b'TIT2' + len( title_bytes ).to_bytes( 4, 'big' ) + b'\... | 1f146718be306f273e8dfd3fa2abc9d199e1ab1e | 3,609,251 |
def _calspec_file_parse_name_(stdname):
""" """
return stdname.replace("+","_").lower() | 43825c1a5b7b7c55a57031e15810a7b6b711d729 | 3,609,252 |
def getmodel(name: str) -> ba.Model:
"""getmodel(name: str) -> ba.Model
Return a model, loading it if necessary.
Category: Asset Functions
Note that this function returns immediately even if the media has yet
to be loaded. To avoid hitches, instantiate your media objects in
advance of when yo... | 9fc5e62d02b0296d0bef72528ba94df4d92257cf | 3,609,253 |
def calculate_jaccard(tp_fp_fn_dict: dict) -> np.array:
"""Calculate list of Jaccard indices.
Args:
tp_fp_fn_dict: {"true_positives": true_positives,
"false_positives": false_positives,
"false_negatives": false_negatives}
Returns:
"""
epsilo... | 2075865d456b284f63f54a6dc9d919a18b37c8c2 | 3,609,254 |
def make_reg_ex(seq):
"""Make regular expression for ambiguous DNA."""
return "".join(ambiguous_dna_re[letter] for letter in seq) | b893b72878709e6e9dbbb56f707c55b48a2bc624 | 3,609,255 |
def init_decorrelated_plsa(
dataset,
modalities_to_use,
main_modality,
num_topics,
model_params: dict = None
):
"""
Creates simple artm model with standard scores.
Parameters
----------
dataset : Dataset
modalities_to_use : list of str
main_modality :... | cbd05254deb154d6f6571b0032852e301eb26e6c | 3,609,256 |
from datetime import datetime
def today_recurrence(recurrence: dict, now_date=datetime.date.today()) -> bool:
"""
Checks the recurrence to know if today is a recurrence day.
:param recurrence: list Recurrence information
:param now_date: date Today date
:return: bool True if today is a day of the ... | fe6fb9b6e7792ebbc073a0d757e18e73812b7e8b | 3,609,257 |
import re
def remove_comments(codelines):
""" Removes all comments from codelines. """
lines_removed = []
for l in codelines:
# remove comments
lines_removed.append(re.sub("#.*", "", l))
return lines_removed | 50cbb10d14f111aac6ccc05fec6dd35842a272cd | 3,609,258 |
import pandas
def raw_difference_frame(raw_model,mean_frame,**options):
"""Creates a difference pandas.DataFrame given a raw NIST model and a mean pandas.DataFrame"""
defaults={"column_names":mean_frame.columns.tolist()}
difference_options={}
for key,value in defaults.items():
difference_optio... | 9af16e87791e23516e9ed7a3e287089716b6a98c | 3,609,259 |
def sdm_25d_point(omega, x0, n0, xs, xref=[0, 0, 0], c=None):
"""Point source by 2.5-dimensional SDM.
The secondary sources have to be located on the x-axis (y0=0).
Driving funcnction from :cite:`Spors2010`, Eq.(24)::
D(x0,k) =
"""
x0 = util.asarray_of_rows(x0)
n0 = util.asarray_of_ro... | 75e6e9e09194f90872c321b8f1ef56fbc12d9905 | 3,609,260 |
def predict():
"""Receives a url photo, process it and make a prediction using SVC model.
Args:
url (str): url containing the image.
"""
form = URLRequisition()
# Process the url to get and embedding representation of the face.
if form.validate_on_submit():
url = f... | b9707d7460e5b7d9b2efe98e4ccd732471ea490f | 3,609,261 |
def build_game_using_payoff_matrices(
lambda_2,
lambda_1_1,
lambda_1_2,
mu_1,
mu_2,
num_of_servers_1,
num_of_servers_2,
system_capacity_1,
system_capacity_2,
buffer_capacity_1,
buffer_capacity_2,
target,
payoff_matrix_A=None,
payoff_matrix_B=None,
alternative_... | b788368e3054b72f1844a7ce00bc6ceab674c5fb | 3,609,262 |
from unittest.mock import patch
from typing import List
def with_mock_subp(func):
"""Decorator that sets up a Popen mock.
Any function that uses this decorator should take a function as an argument. When
called wtih a series of return codes, that function will mock out subprocess.Popen,
and set it to... | 9c2608b98aa048bb2eecfc115aeebc0607dad8df | 3,609,263 |
def diff_2nd_xx(fp, f0, fm, eps):
"""Evaluates an on-diagonal 2nd derivative term"""
return (fp - 2.0*f0 + fm)/eps**2 | 8e46af3a52f75b3ad31ce93a9e12737b0a64872e | 3,609,264 |
def valid_client_request_body(initialize_db):
"""
A fixture for creating a valid client model.
Args:
initialize_db (None): initializes the database and drops tables when
test function finishes.
"""
return {'username': 'Leroy Jenkins', 'avatar_url': ''} | be2655fc5f338642d5e5901304195bb7d617528c | 3,609,265 |
def invert_map(variables):
"""Converts a dict(OS, dict(deptype, list(dependencies)) to a flattened view.
Returns a tuple of:
1. dict(deptype, dict(dependency, set(OSes)) for easier processing.
2. All the OSes found as a set.
"""
KEYS = (
KEY_TOUCHED,
KEY_TRACKED,
KEY_UNTRACKED,
'command... | 8d12032458a2b3e6115a09fffda37c89cd4e2993 | 3,609,266 |
def yolo_loss(args, anchors, num_classes, ignore_thresh=.5):
"""Return yolo_loss tensor
Parameters
----------
yolo_outputs: list of tensor, the output of yolo_body or tiny_yolo_body
y_true: list of array, the output of preprocess_true_boxes
anchors: array, shape=(N, 2), wh
num_classes: inte... | f1addd93a5bdc64474fb49caabcad2794752e583 | 3,609,267 |
def HexToRGB(hex_str):
"""Returns a list of red/green/blue values from a
hex string.
@param hex_str: hex string to convert to rgb
"""
hexval = hex_str
if hexval[0] == u"#":
hexval = hexval[1:]
ldiff = 6 - len(hexval)
hexval += ldiff * u"0"
# Convert hex values to integer
... | 8d6129c1b660a9d928584c8b2263019ca3b06865 | 3,609,268 |
def data_context_path_computation_context_path_comp_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_information_rate_get(uuid, local_id): # noqa: E501
"""data_context_path_computation_context_path_comp_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_information_rate_get
returns tap... | b37affd4331742f70d533df6dfbac83bd578ad3b | 3,609,269 |
import requests
def check_parent_login(username, dob):
"""
Checks if user input for their credentials is correct.
Parameters:
username -- student's PID (format: XXXNameXXXX)
where X - integers
dob -- student's date of birth (required to log into parent's portal)
"""
... | de2d8b2fcdd75e488bfd1cf07a1ca4d8e6fe4710 | 3,609,270 |
from typing import Optional
from typing import Sequence
from typing import Tuple
def isel(
axis: Optional[int],
chunks: Sequence[zarr.Array],
key: Optional[Sequence[slice]],
tensor_domain: Optional[Sequence[slice]],
) -> Tuple[Sequence[zarr.Array], Sequence[slice]]:
"""Select a subset of the chunk... | 5b74b74f642e84eb1b1f151ba8c447034c1bdf8b | 3,609,271 |
def MakeSavedQuery(
query_id, name, base_query_id, query, subscription_mode=None,
executes_in_project_ids=None):
"""Make SavedQuery PB for the given info."""
saved_query = tracker_pb2.SavedQuery(
name=name, base_query_id=base_query_id, query=query)
if query_id is not None:
saved_query.query_id =... | 7f6704e01f3f1809e5a3a950f08e7ab779ee70c6 | 3,609,272 |
def evaluate_nbests(nbests):
"""Return a single evaluation of list of n-best lists."""
evals = list(map(evaluate_nbest, nbests))
return sum_evals(evals) | 48a32e260916f4b240381a936601e26e9b936a56 | 3,609,273 |
from typing import Union
from pathlib import Path
from typing import Optional
def check_for_project(path: Union[Path, str] = ".") -> Optional[Path]:
"""Checks for a Brownie project."""
path = Path(path).resolve()
for folder in [path] + list(path.parents):
structure_config = _load_project_structur... | 937f17692dc608b1112fa773ca5fa841102e022a | 3,609,274 |
def _get_W(k, M, epsilon=2e-2):
"""
Evaluates the auxiliary function at particular value of the independent
variable.
Parameters
----------
k: float
Indepentent variable.
M: int
Number of revolutions
epsilon: float
Tolerance parameter. Default value as in the ori... | a85bd2e4f5a1dc7b825d1741d686e0b539999756 | 3,609,275 |
import requests
def return_figures(states=states_default):
"""Creates a plotly visualization using the COVID tracking API
(http://covidtracking.com/data/api)
# Example of the COVID API endpoint:
# https://api.covidtracking.com/v1/states/{state}/daily.json by state
Args:
state_... | b3c03e4fae767c5d00eb44a1482edb7aac9452ac | 3,609,276 |
def append_dict_key_value(
in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False
):
"""
Ensures that in_dict contains the series of recursive keys defined in keys.
Also appends `value` to the list that is at the end of `in_dict` traversed
with `keys`.
:param dict in_dict: The... | 663c70f173723e75fd1fb8ea5929d538579ee4cd | 3,609,277 |
def get_scheduler(params, optimizer, num_epochs=0):
"""Get scheduler.
Args:
params (dict): scheduler parameters, see `PyTorch documentation <https://pytorch.org/docs/stable/optim.html>`__
optimizer (torch optim):
num_epochs (int): number of epochs.
Returns:
torch.optim, boo... | c08a35ae9c78864e6709e5f0e90282efee1de004 | 3,609,280 |
def generate_pv_limits():
"""Get the control limits and precision values from the live machine for
all normal PVS.
"""
data = [("pv", "upper", "lower", "precision")]
lattice = atip.utils.loader()
for element in lattice:
for field in element.get_fields()[pytac.SIM]:
pv = eleme... | 841dbf203a46318a3bc52b221cac7cc4fd4faa4f | 3,609,281 |
def T2(a):
"""Rotation matrix about third axis
Assumptions:
N/A
Source:
N/A
Inputs:
a [radians] angle of rotation
Outputs:
T [-] rotation matrix
Properties Used:
N/A
"""
# T = np.array([[cos ,sin,0],
# [-sin,cos,0],... | 4354013660651c6fa4edce9080a1c7ad0b3c007a | 3,609,283 |
def train_step(data_iterator, model, optimizer, lr_scheduler,
args, timers,tokenizer):
"""Single training step."""
# Forward model for one step.
timers('forward').start()
lm_loss = forward_step(data_iterator, model, args, timers,tokenizer)
timers('forward').stop()
#print_rank_0(... | 31c64be63618200bb16e73b231c2646e438568b9 | 3,609,284 |
def getBoardStr(board):
"""Return a text-representation of the board."""
return '''
{}|{}|{} 1 2 3
-+-+-
{}|{}|{} 4 5 6
-+-+-
{}|{}|{} 7 8 9'''.format(board['1'], board['2'], board['3'], board['4'], board['5'], board['6'], board['7'], board['8'], board['9']) | 0bd05b2bf33477a7ba8115c3b5d9a7c8a4a1563c | 3,609,285 |
import random
def get_random_account():
"""Get data from random account"""
return random.choice(data) | 37f2523f0df89270f13b0a6baead727ee49586f0 | 3,609,287 |
def main(binary, axes=None):
"""Find and retunrs the coordinates of the 4 points of interest
Arguments
---------
binary : 2D array
Binarized and and cropped version of the butterfly
ax : obj
If any is provided, POI, smoothed wings boundaries and binary will
be plotted on it
... | 63c56f4fcf80cf9ab72930e9379353ab5b8e9116 | 3,609,289 |
def UnitVec3_getAs(p):
"""
UnitVec3_getAs(double const * p) -> UnitVec3
Parameters
----------
p: double const *
"""
return _simbody.UnitVec3_getAs(p) | d0e42e849759120e84eb951b956afbcdb22630e3 | 3,609,292 |
def seed_from_str(s: str) -> int:
"""
Obtains an integer seed from a string using the hash function
"""
return hash(s) % (2 ** 32) | 2fd808916f349102c15db945cc60b5d3793e50b7 | 3,609,293 |
def get_rend_as_mean(image_file_path: str) -> float:
"""Read image from given path and return mean of the pixels."""
array = get_rend_as_ndarray_wl(image_file_path)
return np.mean(array) | b49efeb4a8935764c2d8e132c026e3618934cedf | 3,609,294 |
def download_puppy_texture(load=True): # pragma: no cover
"""Download puppy texture.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returned.
Returns
-------
pyvista.Data... | 0620a1793a9c75718adbcb3a6ed9fb65cabde10d | 3,609,295 |
def compute_pca(image_set):
"""Calculates and returns PCA of a set of images
Args:
image_set: List of images read with cv2.imread in np.uint8 format
Returns:
PCA for the set of images
"""
# Check for valid input
assert(image_set[0].dtype == np.uint8)
# Reshape data into s... | b51fc4df1ef7996b9be266760b39e2cedc48947a | 3,609,296 |
import re
def cleanse_sentences(tweet_list: list) -> list:
"""
Runs checks for the tweets so that most special characters,
emojis, links and retweet tags are removed.
:param tweet_list: List containing tweets
:return: Cleansed list of strings.
"""
result = []
for tweet in tweet_list:
... | 11d0641ea747beb8569a4600c553268ee197cbd4 | 3,609,297 |
import torch
def reflect_conj_concat(kern, dim):
"""Reflects and conjugates kern before concatenating along dim.
Args:
kern (tensor): One half of a full, Hermitian-symmetric kernel.
dim (int): The integer across which to apply Hermitian symmetry.
Returns:
tensor: The full FFT ker... | b96e47a7739d6bef5c86741918d92c6ae53d0ca6 | 3,609,299 |
from typing import List
def log(df: pd.DataFrame, columns: List[str]) -> pd.DataFrame:
"""Apply log-transformation to numerical columns.
By defintion of the log operation, no negative values are supported.
A 1 is added to all values to make the transform work for 0 values as well.
"""
df[columns]... | bf0bccc83f3fd084a58072fb3545d933ab8c8130 | 3,609,300 |
def Pearson(endog, exdog):
"""
The def calculates the Pearson coefficient
:param endog: The dependent variable. DataFrame
:param exdog: The independent variable. Series
:return: pearson; Pearson coefficient
"""
pearson = exdog.corrwith(endog)
return pearson | cbb1e36c91cd969758b0d456d627fcb6798353de | 3,609,301 |
def gaussfitfun2D(fitparam, dummy, image):
"""
Calculate residuals of 2D Gaussian fit of 2D data
========== ===============================================================
Input Meaning
---------- ---------------------------------------------------------------
fitparam Vector with ini... | 870b34ff2d542c92ad4740c9fd2763a90dc94528 | 3,609,302 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.