content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def read(channel):
"""This function returns the state of a specified GPIO pin."""
GPIO.setup(channel, GPIO.IN)
return GPIO.input(channel) | 89ac5add868935617ad7d4032fd38e91ce704622 | 33,868 |
def sortmerna_indexdb(input_fp, output_fp, params="", HALT_EXEC=False):
"""
"""
cmd = "indexdb_rna --ref %s,%s -v %s" % (input_fp, output_fp, params)
return call_cmd(cmd, HALT_EXEC) | 25c5321fc533a89b8524fe26ddcd1328d260a881 | 33,869 |
import copy
def _extract_original_opp_board(finished_board):
"""
This function removes all shots that have been fired on it, reverting sunken ships to normal. Notably, coordinates
that have hits, but no sunk ship will be set to be empty as the position of the original ship is unclear. The
motivation f... | 60a722909415ffa5bced6e6b4fb640a036dcecaa | 33,870 |
def pool():
"""Fixture that returns a Pool object."""
return MagicMock() | d9f661fb8ec67bdf1694d7d1d62603e8313fd479 | 33,871 |
def extended_gcd(a, b):
""" ----- THIS FUNCTION WAS TAKEN FROM THE INTERNET -----
Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb
"""
# r = gcd(a,b) i = multiplicitive inverse of a mod b
# or j = multiplicitive inverse of b mod a
# Neg return values for i or j are made posi... | 19cb82dcce75c60e4672ecb6de73719452952f2f | 33,872 |
def get_interp_BmV_from_Teff(teff):
"""
Given an effective temperature (or an array of them), get interpolated B-V
color.
"""
mamadf = load_basetable()
mamadf = mamadf[3:-6] # finite, monotonic BmV
mamarstar, mamamstar, mamateff, mamaBmV = (
nparr(mamadf['R_Rsun'])[::-1],
n... | ff7d2bef3daa68addcb0e3317a793d86a2ad0e57 | 33,873 |
import types
import importlib
async def _load_mfa_module(hass: HomeAssistant, module_name: str) -> types.ModuleType:
"""Load an mfa auth module."""
module_path = f"homeassistant.auth.mfa_modules.{module_name}"
try:
module = importlib.import_module(module_path)
except ImportError as err:
... | 115520c3c2f2cf00ae238d189817728f6129130d | 33,876 |
def model_metrics(key,codes="",nb=None,with_doc=False):
"""
param1: dictionary : AutoAI steps data
param2: string : Code syntaxs
param3: boolean : Whether to includer documentation/meta description for the following section
return: string : Code syntaxs
The function adds code syntax related to ... | 3893004b29edc53cdb780b3d6234b732365095a5 | 33,877 |
def so3_rotate_with_normal(batch_data):
""" Randomly rotate the point clouds to augument the dataset
rotation is per shape based along up direction
Input:
BxNx3 array, original batch of point clouds
Return:
BxNx3 array, rotated batch of point clouds
"""
rotated_da... | 90114e4110f0b9e54cc71a77339574ecfa98a194 | 33,878 |
def populate_from_file(filename, gap=0.1,
pool_intensity=4,
pool_capacity=None,
eps_diff=1e-7,
verbose=False):
""" Runs populate on a model file.
:param filename: the model file.
:param gap: MIP gap to use for the p... | f5e2ab7b5558a9f72593395055652b8e6d11eb94 | 33,879 |
def dihedral(p):
"""Praxeolitic formula 1 sqrt, 1 cross product"""
p0 = p[0]
p1 = p[1]
p2 = p[2]
p3 = p[3]
b0 = -1.0*(p1 - p0)
b1 = p2 - p1
b2 = p3 - p2
# normalize b1 so that it does not influence magnitude of vector
# rejections that come next
b1 /= np.linalg.norm(b1)
... | d6c1e2e0f1f4eb0fd10d34040371e1ba7dda8514 | 33,880 |
def mangle_varname(s):
"""Append underscores to ensure that `s` is not a reserved Python keyword."""
while s in _PYTHON_RESERVED_KEYWORDS:
s += "_"
return s | e679a0ff33c7df91c73f38c826c8f1a23dc185d9 | 33,881 |
def standard_prediction_error(x_data, y_data):
"""Return function to calculate standard prediction error.
The standard prediction error of a linear regression is the error when
predicting a new value which is not in the original data.
Parameters
----------
x_data : numpy.array
x coordi... | e11497c9c4385a07cdabab2b8ad72273f237fdfb | 33,882 |
import copy
def update_dict(original, new):
"""
Update nested dictionary (dictionary possibly containing dictionaries)
If a field is present in new and original, take the value from new.
If a field is present in new but not original, insert this field
:param original: source dictionary
:typ... | 1608d28321d294943f4c955e42939b054966751f | 33,883 |
from typing import Tuple
import yaml
from pathlib import Path
def parse() -> Tuple[Response, int]:
"""
Parse the inputs of a workflow.
"""
req_data = yaml.safe_load(request.get_data().decode("utf-8"))
wf_location = req_data.get("wf_location", None)
wf_content = req_data.get("wf_content", None)... | a45694c7498b36acc08353a379db665ad79480cd | 33,884 |
def try_which():
""" Locate hmmsearch on path, if possible
:return:
"""
try:
return str(local["which"]["hmmsearch"]()).rstrip("\r\n")
except ProcessExecutionError:
return "None" | 5360db37bf6f31ee560fefda8897688dcef5d739 | 33,885 |
def getCountryClubCreditMultiplier(countryClubId):
"""
Returns the skill credit multiplier for a particular mint.
mintId is the mint-interior zone defined in ToontownGlobals.py.
"""
return {
BossbotCountryClubIntA: 2.,
BossbotCountryClubIntB: 2.5,
BossbotCountryClubIntC: 3.,
... | c5ac7f3a9198beeeabd1390843449cf0dc594aef | 33,886 |
def get_world_rank() -> int:
"""Get the world rank of this worker.
.. code-block:: python
import time
from ray.air import session
def train_loop_per_worker():
for iter in range(100):
time.sleep(1)
if session.get_world_rank() == 0:
... | ab62942a269249f13c40d060fd597b62c473732f | 33,887 |
def solve():
"""
Replace this with a nice docstring
that describes what this function is supposed
to do.
:return: The answer required.
"""
return -1 | f054515e7bb23bb84ecfb1847410fa111ec431c6 | 33,888 |
def read_data(files, poscount, locidx):
"""Builds input data from a files list."""
locs = [] # One element per file; each is a list of location indexes.
vals = [] # One element per file; each is a parallel list of values.
labels = [] # One element per file: true for '.s', false for '.f'.
for fnam... | 6e64b8a445134b78498aefa9b8a87893ae16b35f | 33,889 |
def deterministic_dynamics(init_cond, dt, num_steps, init_time=0.0):
"""
Uses naive euler's method: x(t+dt) = x_k + F(x_k, t_k) * dt
"""
# prep arrays
states = np.zeros((num_steps, STATE_DIM))
times = np.zeros(num_steps)
# fill init cond
states[0, :] = init_cond
times[0] = init_time
... | 8d9ec7bc99dfb51b03d9c5844de233d59fc8945c | 33,890 |
def get_scope_and_reuse_disc(network_id, layer_id, num_separate_layers):
"""Return the scope and reuse flag.
Args:
network_index: an integer as the network index.
layer_id: an integer as the index of the layer.
num_separate_layers: an integer as how many layers are independent.
Ret... | 8a52cdf4af4a6d545c172565f8c2151176572076 | 33,891 |
import logging
def groups_list(access_token):
"""List FlexVM Groups"""
logging.info("--> List FlexVM Groups...")
uri = FLEXVM_API_BASE_URI + "groups/list"
headers = COMMON_HEADERS.copy()
headers["Authorization"] = f"Bearer {access_token}"
results = requests_post(uri, "", headers)
return ... | 7ec8a362e88349b28279f12d32319b9b1d8b5a45 | 33,892 |
def format_route(raw_route):
"""Cleans and formats route list into valid REXX input.
Arguments:
route {list} -- user input for route
Returns:
{bool} -- Flag indicating valid route.
{str} -- Error message.
{list} -- List of validated routes.
"""
raw_route_list = ... | c23708f8384d2947ad3a161bbfd33f189446f424 | 33,895 |
def gamma_lnpdf(x, shape, rate):
""" shape/rate formulation on wikipedia """
coef = shape * np.log(rate) - gammaln(shape)
dterm = (shape-1.) * np.log(x) - rate*x
return coef + dterm | 692ca281ea51f2f01ecddfb59eb16fcf6379f2c2 | 33,896 |
from functools import reduce
def get_total_variation(variable_img, shape, smoothing=1.5):
"""Compute total variation regularization loss term given a variable image (x) and its shape.
Args:
variable_img: 4D tensor representing the variable image
shape: list representing the variable image... | 83e5135bf9cba692a5fa40dae8a037f0a1749370 | 33,897 |
def dict_filter(d, keep):
"""
Remove all keys from dict except those specified in list 'keep'.
Recurses over values to remove keys from nested dictionaries
:param d: Dictionary from which to select key,value pairs
:type d: dict
:param remove: Keys to select
:type remove: list
:returns: dictionary with ke... | 20d4e5b86558be95d3b5cb31525407cbf98be3c1 | 33,898 |
def tf_depthwise_conv2d(input, w):
"""Two-dimensional depthwise convolution using TF.
Params same as in depthwise_conv2d.
"""
input_4d = tf.reshape(tf.constant(input, dtype=tf.float32),
[1, input.shape[0], input.shape[1], input.shape[2]])
# Set channel_multiplier dimension... | c8b78da33463271d3c42a401f68d09c961953972 | 33,899 |
def parse(puzzle_input):
"""Parse input"""
return [tuple(line.split()) for line in puzzle_input.split('\n')] | 42cb62348c5a6c9893480e71db7b60a6053ea4d0 | 33,900 |
def set_new_pw_extra_security_phone(email_code: str, password: str, phone_code: str) -> FluxData:
"""
View that receives an emailed reset password code, an SMS'ed reset password
code, and a password, and sets the password as credential for the user, with
extra security.
Preconditions required for t... | cc695d439d4c0bb6e7ebc6dff9a1049d948a3dd0 | 33,901 |
import getpass
def get_driver_and_zones(driver_name, account_name):
"""
Get the DNS driver, authenticate, and get some zones.
"""
secret_site = "libcloud/" + driver_name
cls = get_driver(driver_name)
pw = get_password(secret_site, account_name)
if not pw:
pw = getpass("Password:")... | 9217ff7082dbcd79154e278d97d47fecbaa574e9 | 33,902 |
def normalize(seed_url, link):
"""Normalize this URL by removing hash and adding domain
"""
link, _ = urldefrag(link)
return urljoin(seed_url, link) | 7e4d5bfbef2cb92869718d0d21acd86a5529aa1b | 33,903 |
def multi_lab_segmentation_dilate_1_above_selected_label(arr_segm, selected_label=-1, labels_to_dilate=(), verbose=2):
"""
The orders of labels to dilate counts.
:param arr_segm:
:param selected_label:
:param labels_to_dilate: if None all labels are dilated, in ascending order (algorithm is NOT orde... | fbc4f0a93cd9d80ef1f1cae23e79612881bcf5da | 33,904 |
from datetime import datetime
def POST(request):
"""Add a new Topology to the specified project and return it"""
request.check_required_parameters(path={'projectId': 'string'}, body={'topology': {'name': 'string'}})
project = Project.from_id(request.params_path['projectId'])
project.check_exists()
... | 9ee233a708b2093ee482bb3e80f25c70f8eed4ae | 33,906 |
import ray
def deconvolve_channel(channel):
"""Deconvolve a single channel."""
y_pad = jax.device_put(ray.get(y_pad_list)[channel])
psf = jax.device_put(ray.get(psf_list)[channel])
mask = jax.device_put(ray.get(mask_store))
M = linop.Diagonal(mask)
C0 = linop.CircularConvolve(
h=psf, i... | fc861fb6df2caa6a9dddce14d380c519f6bb84c1 | 33,907 |
def sell():
"""Sell shares of stock"""
if request.method == "POST":
symbol = request.form.get("symbol").upper()
shares = request.form.get("shares")
stock = lookup(symbol)
if (stock == None) or (symbol == ''):
return apology("Stock was not found.")
elif not sha... | 3328fba46393455be0baecffb05fdbf4d1a5c770 | 33,909 |
def _compute_third(first, second):
""" Compute a third coordinate given the other two """
return -first - second | 57ea03c71f13f3847d4008516ec8f0f5c02424af | 33,910 |
def decipher(criptotext):
"""
Descifra el mensaje recuperando el texto plano siempre y cuando haya
sido cifrado con XOR.
Parámetro:
cryptotext -- el mensaje a descifrar.
"""
messagedecrip = ""
for elem in criptotext:
code = ord(elem)^1
messagedecrip += chr(code)
return messaged... | c90fc56fda9e65690a0a03ea7f33008883feb3f4 | 33,911 |
def mag(initial, final):
"""
calculate magnification for a value
"""
return float(initial) / float(final) | ab996ee84ff588ce41086927b4da1a74e164278a | 33,912 |
def fetch_ids(product: str, use_usgs_ftp: bool = False) -> [str]:
"""Returns all ids for the given product."""
if use_usgs_ftp:
return _fetch_ids_from_usgs_ftp(product)
else:
return _fetch_ids_from_aws(product) | 10af69c7fe77255ff955c2f97b6056b41cd51d59 | 33,913 |
def to_be_implemented(request):
"""
A notice letting the user know that this particular feature hasn't been
implemented yet.
"""
pagevars = {
"page_title": "To Be Implemented...",
}
return render(request, 'tbi.html', pagevars) | 4ee786b35589a94c0ccb8fe20bae368a594b44f1 | 33,914 |
def ganache_second_account(smart_contracts_dir: str):
"""
Returns the second ganache account.
Useful for doing transfers so you can transfer to an
ethereum address that doesn't have anything to do with
paying gas fees.
"""
return ganache_accounts(smart_contracts_dir)["accounts"][1].lower() | 8845f0445c37f48f782dd72ce4be6a31d17502d6 | 33,916 |
def _parse_list_of_lists(string, delimiter_elements=',', delimiter_lists=':', delimiter_pipelines=';', dtype=float):
""" Parses a string that contains single or multiple lists.
Args:
delimiter_elements <str>: delimiter between inner elements of a list.
delimiter_lists <str>: delimiter between l... | d0d14efba74863ec95245255ca10db48fcfb7a01 | 33,917 |
from typing import List
def get_available_dictionaries() -> List[str]:
"""
Return a list of all available dictionaries
Returns
-------
List[str]
Saved dictionaries
"""
return get_available_models("dictionary") | 37c2b882fc443593a45329a2ddd44c517979c342 | 33,918 |
import requests
def get_unscoped_token(os_auth_url, access_token, username, tenant_name):
"""
Get an unscoped token from an access token
"""
url = get_keystone_url(os_auth_url,
'/v3/OS-FEDERATION/identity_providers/%s/protocols/%s/auth' % (username, tenant_name))
respons... | 252990f59f4bc254337dc0f7e13583b7a383d315 | 33,919 |
import numpy
def _pfa_check_stdeskew(PFA, Grid):
"""
Parameters
----------
PFA : sarpy.io.complex.sicd_elements.PFA.PFAType
Grid : sarpy.io.complex.sicd_elements.Grid.GridType
Returns
-------
bool
"""
if PFA.STDeskew is None or not PFA.STDeskew.Applied:
return True
... | 987c492e1210114bf8eb129f60711f280b116a75 | 33,920 |
import json
def get_peers_for_info_hash_s3(
info_hash,
limit=50
):
"""
Get current peers, S3.
"""
remote_object = s3.Object(BUCKET_NAME, info_hash + '/peers.json').get()
content = remote_object['Body'].read().decode('utf-8')
torrent_info = json.loa... | d1e0ee2112e399d76bdf31774abbf32dbca31526 | 33,922 |
def RGB_to_Lab(RGB, colourspace):
"""
Converts given *RGB* value from given colourspace to *CIE Lab* colourspace.
Parameters
----------
RGB : array_like
*RGB* value.
colourspace : RGB_Colourspace
*RGB* colourspace.
Returns
-------
bool
Definition success.
... | 6942134980f1b0e6ca37276c1d2becec23ba3a2f | 33,923 |
def ltl2ba(formula):
"""Convert LTL formula to Buchi Automaton using ltl2ba.
@type formula: `str(formula)` must be admissible ltl2ba input
@return: Buchi automaton whose edges are annotated
with Boolean formulas as `str`
@rtype: [`Automaton`]
"""
ltl2ba_out = ltl2baint.call_ltl2ba(str(... | 289178f071675cf62546b4403dc8751540c5633f | 33,924 |
def count_org_active_days(odf_day):
"""Return count of active days in org history"""
odf_not_null = org_active_days(odf_day)
return len(odf_not_null) | 13733482dd0a4dcad5cf7a7eb28add145a08dc2f | 33,925 |
import asyncio
import functools
async def update_zigbee_firmware(host: str, custom: bool):
"""Update zigbee firmware for both ZHA and zigbee2mqtt modes"""
sh = TelnetShell()
try:
if not await sh.connect(host) or not await sh.run_zigbee_flash():
return False
except:
pass
... | 00fe85632f55fe4a853ab55f9c2333263b3f6f86 | 33,926 |
def underdog(df):
"""
Filter the dataframe of game data on underdog wins
(games where the team with lower odds won).
Returns: tuple (string reason, pd dataframe)
"""
reason = 'underdog'
filt = df.loc[df['winningOdds']<0.46]
filt = filt.sort_values(['runDiff', 'winningScore'], ascending=[... | 11e8f54d5deb1d61b2feaac163c6c896839a9af8 | 33,927 |
def plot_sino_coverage(theta, h, v, dwell=None, bins=[16, 8, 4],
probe_grid=[[1]], probe_size=(0, 0)):
"""Plots projections of minimum coverage in the sinogram space."""
# Wrap theta into [0, pi)
theta = theta % (np.pi)
# Set default dwell value
if dwell is None:
dwell... | 0179fe192343dcb4ad25297b12981fa2049911f7 | 33,928 |
def divisors(n):
"""Returns the all divisors of n"""
if n == 1: return 1
factors = list(distinct_factors(n))
length = int(log(n, min(factors))) + 1
comb = [item for item in product(list(range(length + 1)), repeat=len(factors))]
result = []
for e in comb:
tmp = []
for p, c in zip(factors, e):
tmp.append(in... | ba6739d65e04c354fc8b52b592ba10e5502f407d | 33,929 |
import itertools
def compute_features_levels(features, base_level=0):
"""Adapted from dnafeaturesviewer, see https://github.com/Edinburgh-Genome-Foundry/DnaFeaturesViewer
Author: Zulko
Compute the vertical levels on which the features should be displayed
in order to avoid collisions.
`features` m... | 93db63a854c2cf237a46d971286bb07feec4c3c1 | 33,930 |
def normalize_answer(s):
"""Lower text and remove extra whitespace."""
def remove_articles(text):
return re_art.sub(' ', text)
def remove_punc(text):
return re_punc.sub(' ', text) # convert punctuation to spaces
def white_space_fix(text):
return ' '.join(text.split())
def... | 9c0c378ae6da3a81c88cb06795ae8f2b2c6eb656 | 33,931 |
def bq_db_dtype_to_dtype(db_dtype: str) -> StructuredDtype:
"""
Given a db_dtype as returned by BigQuery, parse this to an instance-dtype.
Note: We don't yet support Structs with unnamed fields (e.g. 'STRUCT<INT64>' is not supported.
:param db_dtype: BigQuery db-dtype, e.g. 'STRING', or 'STRUCT<column... | 5207c3eabaf424580f481d4433c8bf7716af59db | 33,932 |
def getPixelSize(lat, latsize, lonsize):
""" Get the pixel size (in m) based on latitude and
pixel size in degrees
"""
# Set up parameters for elipse
# Semi-major and semi-minor for WGS-84 ellipse
ellipse = [6378137.0, 6356752.314245]
radlat = np.deg2rad(lat)
Rsq = (ellips... | 3df8e6d17f377493e469fb01e6657eec464ca632 | 33,933 |
def success_response( message, code = 200 ):
"""Returns a JSON response containing `success_message` with a given success code"""
return jsonify( { 'success_message' : message } ), code | 64d3e46872fc17abb0825e8345bfc9929f97e74d | 33,934 |
def sensorsuite(w,q,Parameters):
""" Measurements by onboard sensors """
w_actual = w
q_actual = q
Q_actual = utils.quat_to_rot(q_actual)
bias = np.array([0.5,-0.1,0.2]) #np.zeros(3)
# Measurement of reference directions by Sun Sensor
rNSunSensor = Parameters['Sensors']['SunSenso... | cc78afe736ed61faed03e33a0354ece496ea82bb | 33,935 |
import requests
import time
def get_task_response(taskurl):
"""Check a task url to get it's status. Will return SUCCESS or FAILED, or timeout after 10 minutes (600s)
if the task is still pending
Parameters
----------
taskurl: str
URL to ping
Returns
-------
sta... | 470bad355fe0ce48081112e1b877524c6ba438d4 | 33,936 |
import tokenize
def align(gt, noise, gap_char=GAP_CHAR):
"""Align two text segments via sequence alignment algorithm
**NOTE**: this algorithm is O(N^2) and is NOT efficient for longer text.
Please refer to `genalog.text.anchor` for faster alignment on longer strings.
Arguments:
gt (str) : gr... | 7634349d49163e19235a49b1937e4fa26b3c26bd | 33,937 |
def get_similarity_order(labels, label_means, rank_proximity):
"""
This function take a dictionary of numeric data, and return the i-th closest data point
Parameters
----------
base_statistics : dict {label: (mean, covariance)}
each label is summurized by a mean and a covariance in the featu... | 183024f39fa714e1e427d3795203c257c24bfddf | 33,938 |
import json
def api_v1_votes_put():
"""Records user vote."""
# extract and validate post data
json_string = flask.request.form.get('vote', None)
if not json_string:
abort_user_error('Missing required parameter "vote".')
vote = json.loads(json_string)
post_uid = vote.get('uid')
if not post_uid:
... | e8cc7b9239d43af9a9f86b67ab7c34f27c81e197 | 33,939 |
import collections
def interpolate(vertices, target_vertices, target_triangles):
""" Interpolate missing data.
Parameters
----------
vertices: array (n_samples, n_dim)
points of data set.
target_vertices: array (n_query, n_dim)
points to find interpolated texture for.
target_t... | d1e3c1cf396f719ac8f68ada2cf4d672fc80f136 | 33,940 |
def parse_phot_table(table, rows):
"""
Retrieve filter information from the photometric file
Parameters
----------
path : str
path to LSST light curve file
rows : slice
range of rows for this SN
Returns
-------
dict
dictionary of filter data for the light cu... | 8029a981a8670dc475ee2e29b4fa410e0255ad6d | 33,941 |
def XOR(a: bool, b: bool) -> bool:
"""XOR logical gate
Args:
a (bool): First input signal
b (bool): Second input signal
Returns:
bool: Output signal
"""
return OR(AND(NOT(a), b), AND(a, NOT(b))) | 4b9bfed5454008970e3f3c50b2a16b5224082103 | 33,942 |
def create_list_from_dict(mydict):
"""
Converts entities dictionary to flat list.
Args:
mydict (dict): Input entities dictionary
Returns:
list
"""
outputs = []
for k, v in mydict.items():
if len(v) > 0:
for i in v:
outputs.append(i)
... | 50fba98b7590bd7d243464cf45be24c4405f2cef | 33,943 |
from typing import Iterable
from typing import Any
import numpy
def recode(
_x: Iterable,
*args: Any,
_default: Any = None,
_missing: Any = None,
**kwargs: Any,
) -> Iterable[Any]:
"""Recode a vector, replacing elements in it
Args:
x: A vector to modify
*args: and
... | b06b1467b55ad8c6c510088c7cd65777f384c415 | 33,944 |
from typing import List
from typing import Dict
from typing import Any
def get_details_for_all_categories(categories: List[str]) -> List[Dict[str, Any]]:
"""Get all api details for categories
:param categories List of all categories returned from server
:returns List of api details
"""
api_detail... | f712d2aa0843b33fdeec7f8d46f2f3e00b3caf17 | 33,945 |
def update_one(collection_name, _id, **kwargs):
"""
Update document in mongo
"""
collection = getattr(database, collection_name)
return collection.update_one({'_id': ObjectId(_id)}, {'$set': kwargs}) | 1ecd6b8113caa65179da6141b596d7f8f7093eef | 33,948 |
def AAPIEnterVehicle(idveh, idsection):
"""Execute command once a vehicle enters the Aimsun instance."""
global entered_vehicles
entered_vehicles.append(idveh)
return 0 | bfc93be891b104f1a8a3dd0de01265eaba04645c | 33,949 |
import time
import socket
import torch
import pickle
def get_predictionnet(args, model, unlabeled_dataloader):
"""Get predictions using a server client setup with POW on the server side."""
initialized = False
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by t... | a95c6dc14eb3ccbe804b60f1cbed720c93f6a1f1 | 33,950 |
async def get_history_care_plan(
api_key: str, doctor: Doctor = Depends(get_current_doctor)
):
"""Get all care plan for client"""
service = TestService()
return service.get_history_care_plan(api_key, doctor) | 9d7e1c56d93214b22f5018e739e1894ed03cf56b | 33,951 |
def bode(sys_list,w=None,x_lim=None,y_lim=None,dB=True,Hz=False,deg=True,log_x=True):
"""
Returns the impulse response of the continuous or discrete-time systems `sys_list`.
Parameters
----------
sys_list : system or list of systems
A single system or a list of systems to analyse
w ... | 4a11e8f7595ec6efeaac2a9a812f2620a5b5f737 | 33,952 |
def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
textcolors=["white", "black"],
threshold=None, **textkw):
"""
A function to annotate a heatmap.
Parameters
----------
im
The AxesImage to be labeled.
data
Data used to annotate. If N... | 6b2f49ecc91ca4af9e7b93cfa05a2fc8348b362f | 33,953 |
def _extract_body(payload, embedded_newlines):
"""
Extract HTTP headers and body
"""
headers_str, body = payload.split('\r\n\r\n',1)
headers = {}
for line in headers_str.splitlines():
line = line.rstrip()
if line.find(':') > -1:
key, value = line.split(':',1)
... | 7ac74fe4454fd00e1ec718dc1c5bb1fe93e1dc37 | 33,954 |
def connect(db_url, *, external=False):
"""Connect to the database using an environment variable.
"""
logger.info("Connecting to SQL database %r", db_url)
kwargs = {}
if db_url.startswith('sqlite:'):
kwargs['connect_args'] = {'check_same_thread': False}
engine = create_engine(db_url, **k... | b62c5a22eeaf63e4989dbde4e685341f37e2a7a1 | 33,955 |
from typing import List
def containsDuplicate(nums: List[int]) -> bool:
"""
Time: O(n)
Space: O(n)
"""
visited = set()
for n in nums:
if n in visited:
return True
else:
visited.add(n)
return False | 673544bcd10d31d185b65cb7c4b4330a0a7199a4 | 33,956 |
def getROC(detector = 0, methods = ['BDT']):
"""Get the ROC curve for a dectector given a set of methods testes
Keyword arguments:
detector -- detector used (default 0)
methods -- list of methods used (default ['BDT'])
"""
# retrive root tree as datafram
df= read_root('resultsDet{0}.root'... | 18e86eedfefd0fd079210a59a16f4537f311efbf | 33,958 |
def classify_dtypes_using_TF2_in_test(data_sample, idcols, verbose=0):
"""
If you send in a batch of Ttf.data.dataset with the name of target variable(s), you will get back
all the features classified by type such as cats, ints, floats and nlps. This is all done using TF2.
"""
print_features = False... | da6c9a82def789f5bb22c806b3cde294cd8d3631 | 33,959 |
def cs2coords(start, qstart, length, strand, cs, offset=1,
splice_donor=['gt', 'at'], splice_acceptor=['ag', 'ac']):
"""
# From minimap2 manual this is the cs flag definitions
Op Regex Description
= [ACGTN]+ Identical sequence (long form)
: [0-9]+ Identical sequence length
* [acgtn... | fa9b283ff58e494914e13aca552ca0bf71e8853a | 33,960 |
def get_learner_goals_from_model(learner_goals_model):
"""Returns the learner goals domain object given the learner goals
model loaded from the datastore.
Args:
learner_goals_model: LearnerGoalsModel. The
learner goals model from the datastore.
Returns:
LearnerGoals. The le... | 9216cc711f24ffbb0554a9dad4af8571c51429a3 | 33,962 |
def prepare_metadata_for_build_wheel(
metadata_directory, config_settings, _allow_fallback):
"""Invoke optional prepare_metadata_for_build_wheel
Implements a fallback by building a wheel if the hook isn't defined,
unless _allow_fallback is False in which case HookMissing is raised.
"""
... | 24826b1f18a83c97ec516dec2e67110d920725a9 | 33,963 |
from datetime import datetime
def get_modtime(ftp, filename):
"""
Get the modtime of a file.
:rtype : datetime
"""
resp = ftp.sendcmd('MDTM ' + filename)
if resp[:3] == '213':
s = resp[3:].strip()
mod_time = datetime.strptime(s,'%Y%m%d%H%M%S')
return mod_time
retur... | 2a69d0448c093319392afafcfff96dc04ec225d0 | 33,964 |
def rotor_between_objects_root(X1, X2):
"""
Lasenby and Hadfield AGACSE2018
For any two conformal objects X1 and X2 this returns a rotor that takes X1 to X2
Uses the square root of rotors for efficiency and numerical stability
"""
X21 = (X2 * X1)
X12 = (X1 * X2)
gamma = (X1 * X1).value[0... | 9b4818aa149b5b8ea1cda3791f88c0650fb7a0bf | 33,965 |
def propose_time_step(
dt: float, scaled_error: float, error_order: int, limits: LimitsType
):
"""
Propose an updated dt based on the scheme suggested in Numerical Recipes, 3rd ed.
"""
SAFETY_FACTOR = 0.95
err_exponent = -1.0 / (1 + error_order)
return jnp.clip(
dt * SAFETY_FACTOR * ... | fa587b612433605ad002cb89a9ba5a46caa90679 | 33,966 |
def cross_column(columns, hash_backet_size=1e4):
"""
generate cross column feature from `columns` with hash bucket.
:param columns: columns to use to generate cross column, Type must be ndarray
:param hash_backet_size: hash bucket size to bucketize cross columns to fixed hash bucket
:return: cross ... | c4dfbf9083686c083e753ec90f9dbb00b06d515c | 33,967 |
def conform_json_response(api, json_response):
"""Get the right data from the json response. Expects a list, either like [[],...], or like [{},..]"""
if api=='cryptowatch':
return list(json_response['result'].values())[0]
elif api=='coincap':
return json_response['data']
elif api in {'po... | a9a2ec51edc13843d0b8b7ce5458bb44f4efd242 | 33,968 |
import re
def parse_content(content):
"""
解析网页
:param content:
:return:
"""
movie = {}
html = etree.HTML(content)
try:
info = html.xpath("//div[@id='info']")[0]
movie['director'] = info.xpath("./span[1]/span[2]/a/text()")[0]
movie['screenwriter'] = info.xpath(".... | 3e1bab821268abe99e088f331e317ddf74bb36e8 | 33,971 |
def model_save(self, commit=True):
"""
Creates and returns model instance according to self.clean_data.
This method is created for any form_for_model Form.
"""
if self.errors:
raise ValueError("The %s could not be created because the data didn't validate." % self._model._meta.object_name)
... | 47192e57a91961fcd08ea7091ab8a3a7448e2c97 | 33,972 |
def count_items(item_list: list) -> (list, list):
"""
Essa função lista as categorias de itens e as suas respetivas quantidades.
:param item_list: lista de itens
:return: uma tupla contendo lista de tipos e lista com a contagem de elementos dos tipos
"""
item_types = set(item_list)
count_ite... | 07144327c72fb1c54a1adbd5cadbf8b78324a0df | 33,973 |
def find_adjacent_citations(adfix, uuid_ctd_mid_map, backwards=False):
""" Given text after or before a citation, find all directly adjacent
citations.
"""
if backwards:
perimeter = adfix[-50:]
else:
perimeter = adfix[:50]
match = CITE_PATT.search(perimeter)
if not match... | 3630c524a55c09c3b44e6aec3f5706e6a6253c07 | 33,974 |
def defineTrendingObjects(subsystem):
""" Defines trending histograms and the histograms from which they should be extracted.
Args:
subsystem (subsystemContainer): Current subsystem container
subsystem (str): The current subsystem by three letter, all capital name (ex. ``EMC``).
"""
fun... | f0bd25476c7b9e2db245e4fd07fa03cc521d6c3c | 33,975 |
def staff_beers():
"""
This method is used to return 3 beer
"""
return Beer.query.limit(3) | f4f0d8dbb1b2a0550889ee7d00674e7c939f9eef | 33,976 |
def gen_curves(gen_data, file_path="", plot=True):
"""
Generates all parameters/values needed to produce an IV surface. No actual computations done
except to compute relevant values for the drift.
"""
num_gen_days = len(gen_data)
tau = DEFAULT_TAU
pis, mus, sigs, As, lams = construct_p... | 07f509588bb1c6e21de14189b34c979306e2cc1b | 33,977 |
import math
def mm2phi(mm):
"""Convert a mm float to phi-scale.
Attributes:
mm <float64>: A float value for conversion"""
return(-math.log2(mm)) | b40a9125be92dcdcc2be5b888c971f36f17c1c38 | 33,978 |
def IV_action(arr, iv=None, action="extract"):
"""Extract or store IV at the end of the arr."""
if action == "store" and iv != None:
arr.append(iv)
elif action == "extract" and iv == None:
iv = arr.pop()
return iv
else:
return "Error: No action assigned." | 0844cbb8eb3fb07ff49fb63d035fc7d4b7201700 | 33,979 |
def get_tty_width():
"""
:return: Terminal width as a string
"""
return str(get_terminal_size()[0]) | 2c09599d13417e0243af142b7c79da2cf9802825 | 33,980 |
def set_train_val_test_sequence(df, dt_dset, rcpower_dset, test_cut_off,val_cut_off, f = None ):
"""
:param df: DataFrame object
:param dt_dset: - date/time header name, i.e. "Date Time"
:param rcpower_dset: - actual characteristic header name, i.e. "Imbalance"
:param test_cut_off: - value to pass... | 88145303e494578116e74d713f0e2333a1bd7798 | 33,981 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.