content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _url(url, params):
"""
Returns long url with parameters
http://mydomain.com?param1=...¶m2=...
"""
if params is not None and len(params) > 0:
return url + "?" + urlencode(params)
else:
return url | 7b13652682db17f61546834965cb00d3804688da | 3,614,842 |
def UniProt_NCBI_TaxID_and_TaxName_for_autocomplete_UPS_FIN(fn_in, fn_out):
"""
e.g. of input file
UP000464341 1408252 None bacteria 270 0 270 Escherichia coli R178
UP000000558 83334 ECO57 bacteria 5060 4 9234 Escherichia coli O157:H7
priority t... | a5ba2dc54f427ddfd5d521c257dea1dd74e3db43 | 3,614,843 |
def get_port() -> str:
"""Looks for ngrok processID. If found, scans the PID in `netstat` for an `activeListener` to skim the port number.
Notes:
Alternate is to run `echo {root_password} | sudo -S lsof -PiTCP -sTCP:LISTEN | grep ngrok`
Returns:
str:
Local IP address and port numbe... | 2baf2f10fdd5446101020fa5e6a24f29f4d124ef | 3,614,844 |
from typing import Dict
from typing import Union
from typing import List
from typing import Any
from typing import Tuple
def dict_to_aiohttp_tuples(
d: Dict[str, Union[str, int, List[Any]]]
) -> List[Tuple[Any, Any]]:
"""aiohttp doesn't like dictionaries where the values are arrays.
In particular, passin... | dc2f4ad0bff961062d6001096ebb6716aef0864d | 3,614,845 |
def image_caption_correct(dataset, images_path):
"""Stream in images from a directory and pre-populate the text box with the
model's predicted caption. The original caption is stored as "orig_caption",
the potentially edited caption as "caption".
"""
encoder, decoder, vocab, transform = load_model()... | f93621d407ab4975754a765743a5bef561ff0df4 | 3,614,848 |
import logging
from typing import Optional
def init_stc(
api: ApiType,
logger: logging.Logger,
install_dir: Optional[str] = None,
rest_server: Optional[str] = None,
rest_port: Optional[int] = 80,
) -> StcApp:
"""Helper function to create STC object.
This helper supports only new sessions.... | a8172dd43ace0f2d57d89baa8ec0fbb1929c8725 | 3,614,849 |
import importlib
def _check_import(package_name):
"""Import a package, or give a useful error message if it's not there."""
try:
return importlib.import_module(package_name)
except ImportError:
err_msg = (
f"{package_name} is not installed. "
"It may be an optional ... | c4cb7c5a49071663d23e9530155bdee3304a5f72 | 3,614,850 |
from skimage.draw import polygon
from skimage.measure import regionprops
import numpy as np
import tqdm
def blobs_to_dict(blobs, img_shape, region_manager):
"""
outputs ground truth in a list of dicts like:
{'0_angle_deg': 196.81771700655054,
'0_major': 63.263008639602724,
'0_minor': 14.997692... | 8376ccfdf587ed3dec02775453d8e804a377773c | 3,614,851 |
import json
def get_tool_shed_repo_requirements(app, tool_shed_url, repositories=None, repo_info_dicts=None):
"""
Contact tool_shed_url for a list of requirements for a repository or a list of repositories.
Returns a list of requirements, where each requirement is a dictionary with name and version as key... | 5492703bf39bfb87c3217ddc1f87b9211566e2cd | 3,614,852 |
import string
def metadata(draw):
"""The "cu102" in "torch==1.8.1+cu102"."""
# https://www.python.org/dev/peps/pep-0440/#local-version-identifiers
alphabet = string.ascii_letters + string.digits + ".-_"
return draw(st.text(alphabet=alphabet, min_size=1)) | 82e33b2c391b08eb1e5f7b4dba55f2226edb0c39 | 3,614,853 |
def getListConfiguration(request, params, visibility, order):
"""Returns the list data for the specified params.
Args:
visibility: determines which list will be used
order: the order the data should be sorted in
"""
key_order, col_names = getKeyOrderAndColNames(params, visibility)
conf_extra = para... | 13bb030a37d37f1c80a7264db6ada39132aac06b | 3,614,854 |
def compute_outcome_stats(df):
"""Compute statistics regarding the relative quanties of arrests, warnings, and citations"""
n_total = len(df)
n_warnings = len(df[df['stop_outcome'] == 'Written Warning'])
n_citations = len(df[df['stop_outcome'] == 'Citation'])
n_arrests = len(df[df['stop_outcome'] ==... | 25dbdfbc15ddd5ac5b112d5fef0eec071bd573ad | 3,614,855 |
def augment_data_sq(x, a, y, Theta):
"""
Augment the dataset so that the x carries an additional feature of theta
Then also attach appropriate weights to each data point.
Theta: Assume uniform grid Theta
"""
n = np.shape(x)[0] # number of original data points
num_theta = len(Theta)
wid... | b7b4186801a5a0eea45c95b6961a49ab833aeedc | 3,614,856 |
def check_day_start(gtfs, desired_weekday):
"""
Assuming a weekly extract, gets the utc of the start of the desired weekday
:param gtfs:
:param day_start:
:param desired_weekday:
:return:
"""
day_start_add = 24 * 3600
day_start, _ = gtfs.get_day_start_ut_span()
tz = gtfs.get_time... | fcaa2969be134f2e17bfa6948eba9f8df47c0666 | 3,614,857 |
import time
def get_picasaweb_date(date_time):
"""Converts a date to PicasaWeb format (string). adjusted for 1/1/1970 or
later (PicasaWeb does not recognize dates before 1/1/1970).
Args:
date_time: the datetime.datetime to convert
Return: the date or 1/1/1970, in PicasaWeb format, whichever... | d6e101eb8729483cb181e626af81c015f8ade7cb | 3,614,858 |
from typing import Any
import click
def confirm(
cfg: Configuration,
msg: str,
force: bool,
default: bool = False,
abort: bool = False,
) -> Any:
"""Wrapped click.confirm function to print to stderr."""
assert cfg.logger is not None
if force:
return force
if cfg.output_fo... | c47ff7893d32614b06d0e1a5bef4fff789c33052 | 3,614,859 |
def dumps_bdd_as_code(
roots,
bdd,
lang='python',
renaming=None):
"""Return code that computes root values from bits.
@param roots: `dict` that maps each "output" bit to
a BDD that depends on "input" bits
@param bdd: BDD manager
@param renaming: `dict` that maps ... | b713cd91b72125e996812d51c363c466b64afd23 | 3,614,860 |
def get_standard_name(uid):
"""
return CF standard name
"""
return dq.inx.uid[uid.vid].sn | 20b59faded81c3975304f2f23e1b47ac7b6d117b | 3,614,861 |
def get_null_reference_cdf(
lowerlimit: np.float32,
upperlimit: np.float32,
numbins: int=1000,
)->ModifiedECDF:
"""
This function will return a CDF to be used as a null reference.
:param lowerlimit: lower bound for the CDF
:param upperlimit: upperbound for the CDF
:p... | 4be8f7305d80fc0f8c8d5f83c187f71f232a12e3 | 3,614,862 |
import getpass
def prompt(identifier) -> tuple:
"""Credential entry helper.
Returns:
Tuple of login_id, key
"""
login_id = input(f"API Login ID for {identifier}: ")
key = getpass.getpass(f"API Transaction Key for {identifier}: ")
return (login_id, key) | be0ed9be1a60c2c29753d6a9ca8b3f12294f183b | 3,614,863 |
def _load_navigation(dataset: xr.Dataset, navigation_files: str):
"""Load navigation data from nmea, gpx or netcdf files.
Returns the dataset with the added navigation data. Data from the navigation file
are interpolated on the dataset time vector.
Parameters
----------
dataset :
Datas... | d021270738b96bcbb0a2811cd48748ad72eb8c5b | 3,614,864 |
import torch
def rotation_3d_in_axis(points, angles, axis=0):
"""Rotate points by angles according to axis.
Args:
points (torch.Tensor): Points of shape (N, M, 3).
angles (torch.Tensor): Vector of angles in shape (N,)
axis (int, optional): The axis to be rotated. Defaults to 0.
R... | f9ae51e59e8531e25d376267b16746f5e88575e0 | 3,614,867 |
from typing import List
def load_cabins() -> List[Cabin]:
"""
Load cabins from yaml file
"""
cabins = []
cabin_data = utils.get_cabin_data()
for cabin in cabin_data:
cabins.append(Cabin(cabin["class"], cabin["quality"]))
return cabins | b75695ea66be77ad78e72f4d2ae17d29eda97942 | 3,614,868 |
def get_bod_class_start_quarter_after(term):
"""
Return the datetime object of the beginning of the first instruction
day in the term after the give year and quarter.
Only the summer full term is relevant.
"""
nterm = get_term_after(term)
if nterm is None:
return None
return nter... | c251da89833d3dff4f5f0826fce5ec3c2d5c2e0d | 3,614,869 |
import json
import traceback
def trigger_request():
""" Callback for IFTTT trigger bunq_request """
try:
data = request.get_json()
print("[trigger_request] input: {}".format(json.dumps(data)))
if "triggerFields" not in data or \
"account" not in data["triggerFields"]:
... | 1dc1c4ff88924f7d7af826016f9218a241164627 | 3,614,871 |
import pathlib
def get_managed_environment_log_path():
"""Path for charmcraft log when running in managed environment."""
return pathlib.Path("/tmp/charmcraft.log") | 1d8c66d480094a728820ea80bdf1ad65a8859fe7 | 3,614,872 |
def image_small_bokeh(an_image, a_title):
"""an_image is a skimage gray image"""
rgb = cv2.cvtColor(img_as_ubyte(an_image),cv2.COLOR_GRAY2RGB)
rgba = cv2.cvtColor(rgb, cv2.COLOR_RGB2RGBA)
rgba_flipped = rgba[::-1, :]
p = bokeh.plotting.figure(plot_width=256, plot_height=160, tools='box_zoom', title=a_title)
... | 0282d0a9600f0f70d0b9b670c1b58a27e4b71a15 | 3,614,874 |
def create_volume_type_settings(volume_type):
"""
Returns a VolumeTypeSettings object
:param volume_type: a SNAPS-OO VolumeType object
"""
control = None
if volume_type.encryption:
if (volume_type.encryption.control_location
== ControlLocation.front_end.value):
... | a87cb6c7d1f14faed9c8903a358d82fd95bff252 | 3,614,875 |
def plot_3d_surface(axes, image, xdata=None, ydata=None, samples=None, clim=None, axlim='auto', **kwargs):
"""
Plot 2D image data as 3d surface
:param axes: matplotlib figure or subplot axes, None uses current axe
:param image: 2d array image data
:param xdata: array data, 2d or 1d
:param ydata:... | b056bd6cbe38c76881c763abe8f08162ebeaffa2 | 3,614,877 |
def get_gpu_capability() -> tuple[float, ...]:
"""Gives CUDA capability for each GPU"""
with _nvml():
handles = _get_device_handles()
return *map(py3nvml.nvmlDeviceGetCudaComputeCapability, handles), | 9f8e3a9cfff4b6ec77945574ec8723d2ca2d33a7 | 3,614,879 |
from typing import Optional
from typing import Union
import pathlib
import socket
def reconnecting_sftp(hostname: str,
username: Optional[str] = None,
password: Optional[str] = None,
port: Optional[int] = None,
private_key_file: O... | b78e887892d91c8e0a5b5e95e57fa86be9973a27 | 3,614,880 |
def pp_2(node, indentation):
""""Lisp Style indentation, i.e. xxx yyy
zzz
"""
if isinstance(node, TreeText):
return node.unicode_
if len(node.children) <= 2:
return "(" + " ".join(pp_flat(c) for c in node.children) + ")"
my_arg_0 = "(" + pp_flat... | 6e5e2b124d1a821df7eb73ba7928afd9c9ffa769 | 3,614,881 |
from unittest.mock import Mock
from datetime import datetime
def player_model_fixture(db_mock=Mock(), **kwargs):
"""
Get a player model fixture which can be manipulated at will
All values passed will be set to the player fixture
param unittest.mock db_mock: The mock object to use for the database obj... | 67196bc8934428603e8a9297a1524187b3d4fd3c | 3,614,882 |
def to_romaji(w):
"""カタカナ・ひらがなをローマ字書きに変換する
一般的なローマ字ではなく、IMEでの単体文字入力となる形に変換して予測候補を出しやすくする
ref: http://developers.linecorp.com/blog/?p=367
"""
def ctoromaji(c):
c = c.group(0)
# if RE_HIRAGANA.search(c):
# c = chr(ord(c)+96)
if c in ROMAJI_DICT:
return ... | 9c915b0b00e3c15b6d50e5ac330dd9621c31acf4 | 3,614,883 |
def setup_faiss_index(embedding_dim: int) -> faiss.Index:
"""Returns a simple `IndexFlatIP` FAISS index with a vector dimension size of `embedding_dim`
and an ID map for cosine similarity searching.
"""
index = faiss.IndexFlatIP(embedding_dim)
index = faiss.IndexPreTransform(faiss.NormalizationTrans... | 05ca97680bed1468c99dcd28d89bfcad80e1279f | 3,614,884 |
def mm_init_guess(runprops):
"""This function will produce the initial guess used in multimoon.
Input:
runprops- All run properties for the code. Will include
the name of the init_guess dataframe csv file.
Returns:
params_df - A parameters dataframe with the same column n... | 60a65507d2a9f12cb43c0a6f651f3d4f3f39972b | 3,614,885 |
def add_ixn_decreases_phosphorylation(graph, ixn):
"""Adds an interaction that represents the chemical decreasing the phosphorylation of a protein
:param pybel.BELGraph graph: A BEL graph
:param pyctd.manager.models.ChemGeneIxn ixn: A chemical-gene interaction
:return: The hash of the added edge
:r... | 6c896e781a3eaa16db6aecb42a71653e1dbc77cb | 3,614,886 |
import struct
def set_wm_window_opacity(window, opacity):
"""
Sets the opacity of the current window.
N.B. If your window manager uses decorations, you'll typically want to pass
your client's *parent* window to this function.
:param window: A window identifier.
:param opacity: A float betwe... | 5fcfdfb3aecef2f78e9f6ced8602258749ea2527 | 3,614,887 |
def defer(fn, delay):
"""Defer a function call after a set period of time has elapsed (in seconds)
Parameters
----------
fn : a callable that takes no args
delay : int | float
the time delay in seconds to wait before calling fn
Returns
-------
DeferRef
a reference to th... | 8540abd637381c3a1b2c47c6a561f16e7d2033c6 | 3,614,889 |
def proactive(ARG_defaultname: str="file"):
"""Use this function *before* generating data.
Parameters
----------
ARG_defaultname : str, default is "file"
The filename to save the data under, assuming the user does not choose another name.
Returns
-------
savebool : bool
If ... | dc94f7f847842f644fafe26622ea4d8870d0b1ae | 3,614,890 |
def _is_authorized(vdc):
"""Check if the user is authorized through BasicAuth or API Keys.
"""
auth_header = request.headers.get("Authorization")
if auth_header:
# Get vdc name and password from request Authorization header with Basic type
name, password = parse_auth(auth_header)
... | 6bb0adcd76ded8c22e10c48cc816a38059b4ccc2 | 3,614,891 |
def _extract_graph_summary(graph_def):
"""Extracts useful information from the graph and returns them."""
name_to_input_name = {} # Keyed by the dest node name.
name_to_node = {} # Keyed by node name.
# Keeps track of node sequences. It is important to still output the
# operations in the original order.
... | 8984faf6f95c847cd7d4c43654f96ef1ae44f460 | 3,614,893 |
def _compute_rank_down(start_nodes):
"""
Compute the rank of the down stream nodes.
Args:
start_nodes (list[NodeGraphQt.BaseNode]):
(Optional) the start nodes of the graph.
Returns:
dict{NodeGraphQt.BaseNode: node_rank, ...}
"""
nodes_rank = {}
for node in start... | 0424b4b0e75af6e2710dfc139f70133c4587f164 | 3,614,894 |
import time
def generate_timestamp(expire_after: float = 30) -> int:
"""
:param expire_after: expires in seconds.
:return: timestamp in milliseconds
"""
return int(time.time() * 1000 + expire_after * 1000) | 16f2fcd77de9edb1e167f1288e37a10491469c22 | 3,614,895 |
from typing import Counter
import math
def radius_of_gyration(positions, user):
"""
Returns the radius of gyration, the *equivalent distance* of the mass from
the center of gravity, for all visited places. [GON2008]_
References
----------
.. [GON2008] Gonzalez, M. C., Hidalgo, C. A., & Baraba... | b71d82d30b28d16efa57943cb1a5b34578a8fd5a | 3,614,896 |
def evaluate_manufactured_solution_result_at_step(filename,dof,list_of_functions,step=-1,meshname='connect1',rtol=1e-5):
"""
=======================================================
| evaluate_manufactured_solution_result_at_step |
=======================================================
Evalua... | fb91cc2f6a84eebaec2d17796cfe9b68cfb2f9fd | 3,614,897 |
import base64
def b64e(s):
"""b64e(s) -> str
Base64 encodes a string
Example:
>>> b64e("test")
'dGVzdA=='
"""
return base64.b64encode(s) | 2562f5d18ac59bbe4e8a28ee4033eaa0f10fc641 | 3,614,899 |
def login(request):
"""登录视图"""
if request.session.get('is_login',None):
logger.info(request)
return redirect("/index/")
if request.method == "POST":
login_form = UserForm(request.POST)
message = "请检查填写的内容!"
if login_form.is_valid():
username = login_form.c... | b9ea5492bcc9f7224f75e2121a6e8e3e6a1d9827 | 3,614,900 |
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Set up the Visonic Alarm platform. """
hub.update()
visonic_alarm = VisonicAlarm(hass)
add_devices([visonic_alarm])
# Create an event listener to listen for changed arm state.
# We will only fetch the events from the API on... | cd345fec39db4388b06e7efed8cf392e2797fcdc | 3,614,901 |
def pipeline_send_op(node, destination, comm, stream=None, ctx=None):
"""Make a new instance of PipelineSendOp and call the instance.
Parameters:
----
node : Node
The Node to be send.
destination : scalar value
The gpu index for destination.
Returns:
----
A new Node ins... | 29db37670805705032cb293d8606d20bc4bc6bb1 | 3,614,902 |
import signal
import math
def synth(**kwargs):
"""return ricker wavelet synthetic data"""
# defaults
if 'pol' not in kwargs: kwargs['pol'] = 0.
if 'delta' not in kwargs: kwargs['delta'] = 1.
if 'split' not in kwargs: kwargs['split'] = []
if 'noise' not in kwargs: kwargs['noise'] = 0.0... | 8186c37add652e63ecdfe610866abc00d08eefe6 | 3,614,903 |
import yaml
import random
import string
def tmp_config_file(dict_: dict) -> str:
"""
Dumps dict into a yaml file that is saved in a randomly named file. Used to as config file to create
ObservatoryConfig instance.
:param dict_: config dict
:return: path of temporary file
"""
content = yaml... | d4ea42a8dc1824757df7f9823f44f7fc181b29aa | 3,614,904 |
import re
def get_bootstrap_assets(self, platform=None):
"""
:param self:
:param platform: optional, defaults to current build's platform
:return: Asset type requested for the supplied platform in bootstrap.cfg
"""
if platform is None:
platform = self.env['PLATFORM']
bootstrap_cfg ... | 55510ed1d15c3ec7323b257b5596cd601bad2316 | 3,614,905 |
def calc_checksum(packet):
"""
Calculates the checksum of a given packet.
This function is only for use in environments where 16-bit words are used.
:param packet: A list with 16-bit numbers as Integers.
:return: The checksum of the packet as Integer
"""
# validate the input
try:
... | 7fd61f9cd15bf7acc7e87255cd6813aa84216266 | 3,614,906 |
def interpolate_with_degree(nodes, values, deg, use_mp=False):
"""Compute a rational function which interpolates the given nodes/values
with given degree `m` of the numerator and `n` of the denominator.
Args:
nodes (array): the interpolation nodes
values (array): the values at the interpola... | 19f5ffa5ac4f1b18de4d489b68ba7726a4c8851a | 3,614,907 |
def preprocess_input(title, overview, vectorizer):
"""
Extract TF-IDF features from a single title and overview input.
:param title: Str. Movie title.
:param overview: Str. Movie plot.
:param vectorizer: Fitted sklearn.feature_extraction.text.TfidfVectorizer object.
:return: Tf-IDF features matr... | 0de37a8e7c870eef185baa3aa1a497ea8d353201 | 3,614,908 |
def _generate_image_info(im, params):
""""generate url and tokens for image"""
image = ee.Image(im)
if "sld_style" in params:
m = image.sldStyle(params.get("sld_style"))
del params["sld_style"]
elif "palette" in params:
m = image.visualize(
**{
"min":... | 13a6bc4a6ad9eb7dd549682d707b1dd7aabb65fe | 3,614,909 |
def _setup_fig(ncols, nrows, figsize_width, figsize_height):
"""
Parameters:
-----------
ncols
Number of columns in the figure.
type: int
nrows
Number of rows in the figure.
type: int
figsize_width
Scaler adjustment of figure width
default: 1
... | cf6c75101220620a8bf7c04d59ba9642ba339779 | 3,614,911 |
def unconfirmed():
"""Catch users with unconfirmed emails."""
if current_user.is_anonymous or current_user.confirmed:
return redirect(url_for('main.index'))
return render_template('account/unconfirmed.html') | 04c40e63a48da389fdec7897c8db049cde572228 | 3,614,912 |
def computeAlleleFrequency (f_C, f_T):
"""3
f_C = minor allele count
f_T = major allele count
minor_allele_frequency = f_C/ (f_C+f_T)
7"""
minor_allele_frequency = f_C/(f_C+f_T)
return minor_allele_frequency | 984a7364bfd3ff2c724c885dedd97f61f959b7e6 | 3,614,914 |
def update_m(obj, ia, rcut=9.0, pbc=None):
"""
retrieve local structure around atom `ia
for periodic systems (or very large system)
"""
zs, coords, c = obj
v1, v2, v3 = c
vs = ssd.norm(c, axis=0)
nns = []
for i,vi in enumerate(vs):
n1_doulbe = rcut/li
n1 = int(n1_dou... | 5ee6752f1c5cc1274557e523acb12394a9b33f56 | 3,614,915 |
def crext_TruncatedHMAC():
"""Create a Truncated HMAC extension."""
return ExtensionType.truncated_hmac.value + lenprefix(b"") | 4d9dbc4156e4bc1855e241bd493aa7b7149e800a | 3,614,916 |
def microcycle_days(weekly_training_days, weeks):
"""generates indexes of training days during the weeks"""
training_day_indexes = []
for w in range(weeks):
for d in weekly_training_days:
training_day_indexes.append(w * 7 + d.value)
return training_day_indexes | 5c0364b1dc58d2c0205d4e6442d590a23519e5f4 | 3,614,917 |
def reduced_supercell_vectors(ab, n):
"""
Returns all possible reduced in-plane lattice vectors and
transition matrices for the given starting unit cell lattice
vectors(ab) and the supercell size n
"""
uv_list = []
tm_list = []
for r_tm in get_trans_matrices(n):
uv = get_uv(ab, r... | 7c75258e19037ee8e09858793b3232690313add8 | 3,614,918 |
from typing import List
def make_polygon_from_coords(coords: List[float]):
"""
Creates a `Polygon` instance using the passed in coordinates:
`[x1 y1 x2 y2 ... xn yn]`.
It raises a `ValueError` if the coordinates list does't have
an even number of entries.
:param coords: list of the coordinat... | 7aa7c46d9f769f57a1bfdbe962bb2f942ab08e96 | 3,614,919 |
def fibonacciMemoization(n: int):
"""
:param n: range numbers to be visited in fibonacci series
:return: nth value in the fibonacci sequence
"""
global fibb_memo
if n in fibb_memo:
return fibb_memo[n]
if n <= 2:
return 1
fibb_memo[n] = fibonacciMemoization(n - 1) + fi... | affd30d81fc6a0564c4acddb2b676a26fcb9846a | 3,614,920 |
def scatter(data, **kwargs):
"""I dont like this. Viewing code should not reside in model logic."""
fig, ax = plt.subplots(1, 1, figsize=(6, 5))
ax.scatter(*data.cpu().numpy().T[:2], **kwargs)
plt.close()
return fig | b89416ded88c872585a3db75651b393d5d319b79 | 3,614,921 |
def build_training_model_component():
"""
Build training model component
Returns:
training_model_component: training model component
"""
model_training_stage = []
rfor = RandomForestClassifier(featuresCol=FEATURES, labelCol=TARGET, seed=RANDOM_SEED)
model_training_stage.append(rfor)
... | 7bbb6f830bb8f4719e95dd3b18121e3ba8ab23cc | 3,614,922 |
import torch
def cka(k_x: torch.Tensor, k_y: torch.Tensor, centered: bool = False, unbiased: bool = True) -> torch.Tensor:
"""Compute Centered Kernel Alignment (CKA).
:param k_x: n by n values of kernel applied to all pairs of x data
:param k_y: n by n values of kernel on y data
:param centered: whet... | a0abf43f33e79f67a2974d7524730f04ae86dd93 | 3,614,923 |
from typing import OrderedDict
def columns(table, missing=None):
"""
Construct a :class:`dict` mapping field names to lists of values. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]]
>>> cols = etl.columns(table)
>>> cols['foo']
... | 2938710112da2b8317fda65b8d873f48e1e2dc40 | 3,614,925 |
def _project_vertices(v, w, h, cam_r, cam_t):
"""projects vertices onto image plane"""
V = ch.array(v)
U = ProjectPoints(v=V, f=[w * 2, w * 2], c=[w / 2., h / 2.], # camera intrinsics
k=ch.zeros(5), t=cam_t, rt=cam_r)
return U | db7f664a531abb4949c66499ef9ef7bfd3cff047 | 3,614,927 |
import pprint
def check_overlapping(features):
"""Check for elements of `features` with overlapping ranges. In the
case of overlap, print an informative error message and return
names and positions of overlapping features.
"""
features = features[:]
overlapping = []
for i in range(len(fea... | 6a246aca29c01b32091d7890b6a55d66367e8e14 | 3,614,928 |
def predict(x, P, F=1, Q=0, u=0, B=1, alpha=1.):
""" Predict next position using the Kalman filter state propagation
equations.
Parameters
----------
x : numpy.array
State estimate vector
P : numpy.array
Covariance matrix
F : numpy.array()
State Transition matrix
... | fb6002c528489f5d595acd8137f1606416eb6678 | 3,614,929 |
def update_hosts(hosts_list=None, user='root'):
"""
@param_post{hosts_list}
@param_post{user} (optional, default: @val{root})
"""
if user is None:
missing_parameter('user')
if hosts_list is None:
missing_parameter('host_list')
try:
f = open("/etc/hosts", "r")
... | 2e95445363814befe67757d517590d2b112bf871 | 3,614,930 |
def get_file_to_load():
"""Open a popup window to select a file to load"""
return sg.popup_get_file(
'Select a file to open',
EVENT_OPEN,
initial_folder=USER_HOME,
no_window=True,
default_extension=EDITOR_EXTENSION,
) | 3ab90ed642d460dd0db0fbdf63d09dc900d19715 | 3,614,931 |
def does_asyncio(func):
"""Simple decorator for running a test inside an asyncio event loop."""
def wrapper(*args, **kwargs):
get_event_loop().run_until_complete(func(*args, **kwargs))
return wrapper | 8f1d9a37400204cfa63ec5edaa25592558219b4d | 3,614,934 |
def correct_baseline(raw_data, mode, smoothing=True, transform=False,
**kwargs):
"""
Calculate baseline data for raw_data with generate_baseline(...).
Takes the same arguments like generate_baseline, for details see
docstring of generate_baseline.
"""
return raw_data - gene... | b9e3b278cfd1e33bb606a32866eea2be5cb75bef | 3,614,935 |
def article(*args, **kwargs):
"""
The HTML <article> element represents a self-contained composition
in a document, page, application, or site, which is intended to be
independently distributable or reusable (e.g., in
syndication). This could be a forum post, a magazine or newspaper
article, a b... | 79405862e88865296aa16ae477f2a6c5d2323ac9 | 3,614,936 |
from typing import Dict
def validate(business: Business, cod: Dict) -> Error:
"""Validate the Change of Directors filing."""
if not business or not cod:
return Error(HTTPStatus.BAD_REQUEST, [{'error': babel('A valid business and filing are required.')}])
msg = []
msg_directors_addresses = val... | 937b74506eb4e3a9d73bc135394f78b42a32e861 | 3,614,937 |
def index():
"""
Basic index view, listing online users.
"""
msg = 'Online: %s' % ', '.join(get_online_users())
return make_response(msg) | a74c95ec7d25f46c3a5c30203ec6ce34260d35ba | 3,614,938 |
def pixel2wave (pix, c, model='linear') :
"""
Inverse function for a given pixel(wave) model.
Converts a pixel position pix into a wavelength w using one of several invertable models:
'linear','quadratic','cubic' w(pix) = invert_polynomial(pix,c) because pix(w) = c[0]+c[1]*w+...
'exp' w(pix) = -ln[(pix-c2)... | e8722d739bcf7fa76a5b8dbda34edddc76915496 | 3,614,939 |
def compute_level(id, tree):
"""
compute the level of an id in a tree
"""
topic = tree[id]
level = 0
while (id != 0):
level += 1
id = topic['parent']
topic = tree[id]
return(level) | fb7fbc1c1f97e85c03abdd453a3deb3411960e45 | 3,614,940 |
import csv
def ReadDirectoryFromFile(file_name, hub_map):
"""directory_tools.ReadDirectory
INPUTS:
- file_name -- name of the file containing the MemberHub directory dump
- hub_map -- dictionary that maps hub names to hub IDs
OUTPUTS:
- directory -- list of families read from the MemberHub d... | 3ed042a2b26436f4061e8d0b628f4887a8982a10 | 3,614,942 |
from typing import Sequence
from typing import Any
from typing import Optional
from typing import Union
from typing import List
def flatten(sequence: Sequence[Any], depth: Optional[int] = -1, **kwargs) -> Union[List[Any], Any]:
"""
Receives values, whether arrays of values, regardless of their shape and flatn... | bfdd0ed66d3eaac5ec3b6c17e43f917bfbbadc69 | 3,614,943 |
def polyglot_1st_pronoun(s):
"""Get first pronoun from the sentence.
Parameters
----------
:param s: string
Sentence
Returns
-------
:returns: string
first pronoun
"""
pronouns = polyglot_pronouns(s)
return pronouns[0] | c0c27ae6bdb5be5b6317cf6751242759538de41c | 3,614,945 |
def filter_by_pvalue_strand_lag(ratios, pcutoff, pvalues, output, no_correction, name, singlestrand):
"""Filter DPs by strang lag and pvalue"""
if not singlestrand:
zscore_ratios = zscore(ratios)
ratios_pass = np.where(np.bitwise_and(zscore_ratios > -2, zscore_ratios < 2) == True, True, False)
... | 394b7b6561c869ba97bbb2ad1d015b2600b71b26 | 3,614,946 |
def write_user_playlist(username, text_file=None):
""" Write user playlists to text_file """
links = get_playlists(username=username)
playlist = internals.input_link(links)
return write_playlist(playlist, text_file) | 2ab684f2f7eec1484d76427fe179fe8620e60da8 | 3,614,947 |
def is_float(db_type):
"""Return True if the database type is a float supported type, False otherwise.
"""
return db_type in ACCEPTED_FLOAT_DB_TYPES | 114657762f76afce67739aac011539b6a0c081e6 | 3,614,948 |
import time
def generate_papernot():
"""
Train the second/distilled model using uncertaity array
:return: distilled model
"""
sigmas = np.load(PROJ_PATH + 'mnist_papernot/sigmas.npz')['sigmas']
start = time()
model_papernot = train_papernot(sigmas)
end = time()
print("Papernot trai... | d526855245b05fcc5f2107952082239e8121674c | 3,614,949 |
def inverse_stft_window_fn(frame_step,
forward_window_fn=window_ops.hann_window,
name=None):
"""Generates a window function that can be used in `inverse_stft`.
Constructs a window that is equal to the forward window with a further
pointwise amplitude cor... | 73a17762231915b35409c05119c1b39eace851b2 | 3,614,950 |
def Vegas(integrand, ndim, userdata=NULL,
epsrel=EPSREL, epsabs=EPSABS, flags=0, ncomp=1, seed=None,
mineval=MINEVAL, maxeval=MAXEVAL, nstart=NSTART,
nincrease=NINCREASE, nbatch=NBATCH,
gridno=GRIDNO, statefile=NULL, nvec=1):
"""
*nstart*: the number of integrand evaluations per iteration to start... | 0762180ec96902b045ff0a16e9f389a7917287ea | 3,614,951 |
def human_annotations(human_file):
"""
Generates JSON from TSV files
"""
zipped_rows = get_rows_from_file(human_file, '\r')
# Too many processes causes the http requests causes the remote to respond with error
pool = mp.Pool(processes=1)
annotations = pool.map(human_single_annotation, zipped... | 965b3f8d1ab557ae79e3f2fa2f0e8e635b568842 | 3,614,952 |
import torch
import math
def eval_gather_inds(len_, num_samples=7):
""" get the gather indices """
inds = torch.arange(0, num_samples, dtype=torch.long)
mul = math.ceil(len_ / num_samples)
output = inds.repeat(mul)[:len_]
return output | 516ca54ff5c3b442bc93becd15d1bdabd8c8025f | 3,614,953 |
def vap_lapserate(temp,pres,dvap=None,chkvals=False,chktol=_CHKTOL,
dvap0=None,chkbnd=False,mathargs=None):
"""Calculate water vapour adiabatic lapse rate.
Calculate the adiabatic lapse rate of water vapour at temperature
and pressure.
:arg float temp: Temperature in K.
:arg float pres... | 6597bd3d0faef483d7db9c46e0c01a4cb3fc9922 | 3,614,954 |
def none_or_valid_float_value_as_string(str_to_check):
"""
Unless a string is "none", tries to convert it to a float and back to check
that it represents a valid float value. Throws ValueError if type
conversion fails. This function is only needed because the MATLAB scripts
take some arguments eithe... | 54f3c63fab0752678cb5a69723aa7790ab11a624 | 3,614,955 |
def hunkify_lines(lines, context=3):
"""
Return a list of line hunks given a list of lines `lines`. The number of
context lines can be control with `context` which will return line hunks
surrounded with `context` lines before and after the code change.
"""
# Find contiguous line changes
rang... | c5acde8c6335b82173af724ba3c8c34058fa23b6 | 3,614,956 |
def init_policy(states, Q):
"""
Define initial target policy of off-policy MC method
Parameters
----------
states : list of tuples
States consist of positions and velocity of agent
Q : dict
Dictionary with q values of each action in each state
Returns
-------
pi : d... | 1c354291668c3489695cd5d25ea11bb3d00d5531 | 3,614,958 |
def gaussianFWHM(x, fwhm, norm = 'area'):
"""
Calculate a Gaussian function.
Parameters
----------
x : array_like
Input array
fwhm : scalar
The full-width at half-maximum value.
norm : {'area', 'amplitude'}
The normalization convention. The default is 'area'. See... | 3df6f2b531669862322bc34796d315c1e8d6f2e2 | 3,614,959 |
def S_moving_average_filter(_data_list, _smoothing=1):
"""
Returns moving average data without data lag.
Use the smoothing factor to get required overall smoothing where the smoothing factor is greater than zero.
"""
ma_data = []
ds = len(_data_list)
s = _smoothing
mas = int((ds... | 763bff294c6225260cb67e2e38440eb4d514c126 | 3,614,960 |
def StripKey(key):
"""Returns key with header, footer and all newlines removed."""
key = key.strip()
key_lines = key.split(b'\n')
if (not key_lines[0].startswith(b'-----')
or not key_lines[-1].startswith(b'-----')):
raise OpenSSLException(
'The following key does not appear to be in PEM format... | bed4f367759098fcb001c315791f3cf25328993e | 3,614,961 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.