content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def theoritical_spectrum(peptide_sequence):
"""Returns the theoritical spectrum of a given amino acid sequence.
INPUT :
peptide_sequence: string. The peptide sequence to get its theoritical spectrum
OUTPUT:
.: List. The theoritical spectrum of the given peptide sequence.
"""
linear_... | 1808daed80b553fe3a5a2b38e178956e4a0d7de0 | 3,656,160 |
def is_amazon(source_code):
"""
Method checks whether a given book is a physical book or a ebook giveaway for a linked Amazon account.
:param source_code:
:return:
"""
for line in source_code:
if "Your Amazon Account" in line:
return True
return False | 31c50622b4bb97a05d8cabb94c58f6e0a8f58971 | 3,656,161 |
def data_dim(p):
""" Return the dimensionality of the dataset """
dataset_class = DATASETS[p.dataset]
return dataset_class(p).get_in_dim() | 25e32039733e8599c22d696f28bfffbf8b97cf02 | 3,656,163 |
import torch
def create_supervised_evaluator(model, metrics=None,
device=None, non_blocking=False,
prepare_batch=_prepare_batch,
output_transform=
lambda x, y, y_pred: (y_pred, y,)):
"""... | 2af4cc7b12a76c3c12940353a072d8b715fec8c1 | 3,656,164 |
import typing
def historical_earning_calendar(
apikey: str, symbol: str, limit: int = DEFAULT_LIMIT
) -> typing.Optional[typing.List[typing.Dict]]:
"""
Query FMP /historical/earning_calendar/ API.
Note: Between the "from" and "to" parameters the maximum time interval can be 3 months.
:param apike... | 7f231b253ef4f462ab89826d58546a3259bdd3d2 | 3,656,165 |
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_query_tor_network]
base_url = https://onionoo.torproject.org/details
#The Flag can be 'Running','Exit' for more information on flag sett... | 239436c9b2141e17f6158aab20d7951d79359fcd | 3,656,166 |
def show_object_id_by_date(
move_data,
create_features=True,
kind=None,
figsize=(21, 9),
return_fig=True,
save_fig=True,
name='shot_points_by_date.png',
):
"""
Generates four visualizations based on datetime feature:
- Bar chart trajectories by day periods
- Bar char... | 18bbd54adfba6ecfd0959904d99698cfaac4b198 | 3,656,167 |
def raw_escape(pattern, unix=None, raw_chars=True):
"""Apply raw character transform before applying escape."""
return _wcparse.escape(util.norm_pattern(pattern, False, raw_chars, True), unix=unix, pathname=True, raw=True) | e4df84b21b737f199a7314818cc7f892f93be1b8 | 3,656,168 |
def interpolate_effective_area_per_energy_and_fov(
effective_area,
grid_points,
target_point,
min_effective_area=1. * u.Unit('m2'),
method='linear',
):
"""
Takes a grid of effective areas for a bunch of different parameters
and interpolates (log) effective areas to given value of those p... | 58c32f49c96ed7ceb14e734f1386ef0015920204 | 3,656,169 |
def extract_edge(stats:np.ndarray, idxs_upper:np.ndarray, runner:int, max_index:int, maximum_offset:float, iso_charge_min:int = 1, iso_charge_max:int = 6, iso_mass_range:int=5)->list:
"""Extract edges.
Args:
stats (np.ndarray): Stats array that contains summary statistics of hills.
idxs_upper ... | 8101a024c20d169f470d4e6632272e0ad00c484b | 3,656,170 |
def _neq_attr(node, attr, gens, container):
"""
Calcs fitness based on the fact that node's target shall not have an attr
with a certain value.
"""
trg_nd = container.nodes[gens[node]]
if attr[0] in trg_nd and attr[1] == trg_nd[attr[0]]:
return 10.1
return 0.0 | adfa39aa60d0777b2b05f174a9cf61a847e55b1d | 3,656,171 |
def getItem( user, list, itempk ):
"""
Get a single item from a list.
:param user: user who owns list
:param list: list containing item
:param itempk: private key of item
:return: item or None
"""
itemType = list.itemType
item = None
if itemType == 'Item':
ite... | f0d2c3a6d1881e0e1288aae451a556ebe856242e | 3,656,172 |
def metric_divergence(neighborhood_vectors: np.ndarray, dL: float, polarity: int) -> float:
"""
Calculates the divergence of a sampling volume neighborhood.
Note: For JIT to work, this must be declared at the top level.
@param neighborhood_vectors: Sampling volume neighborhood vectors (six 3D vectors)... | 87dd2b19c654143ed54f3783059ece50eb32ec71 | 3,656,173 |
def tag(request):
"""
Add/Remove tag to email
"""
if request.is_ajax():
mail = request.POST.get("mail")
tag = request.POST.get("tag")
op = request.POST.get("op")
mail = get_object_or_404(Mail, pk=mail)
if op == "ADD":
mail.tags.add(tag)
elif op... | b1f5c2e65393be1d68a03b01c522214413e5b321 | 3,656,175 |
def sid_to_smiles(sid):
"""Takes an SID and prints the associated SMILES string."""
substance = pc.Substance.from_sid(sid)
cid = substance.standardized_cid
compound = pc.get_compounds(cid)[0]
return compound.isomeric_smiles | e243e201a8ac4e4ee63332454a8b8c64f0f43692 | 3,656,176 |
def view_static(request, **kwargs):
"""Outputs static page."""
template = kwargs.get('template', None)
if not template:
raise Http404
template = '.'.join([template, 'html'])
title = kwargs.get('title', 'static page')
img = kwargs.get('img', 'bgag.jpg')
return render_to_response(temp... | b6997e86175688f9b1293b0888faeb337bb5f3b6 | 3,656,177 |
def start_call(called_ident, skicall):
"""When a call is initially received this function is called.
Unless you want to divert to another page, this function should return called_ident which
would typically be the ident of a Responder or Template page dealing with the call.
If a ServeFile excep... | 0353d81273ea6638858bf18271f4480895ca1db1 | 3,656,178 |
def getmemory():
"""
Returns the memory limit for data arrays (in MB).
"""
return NX_MEMORY | f6850ac2ad5854f9798ef480e9ca105bf31644ed | 3,656,179 |
import this
def get_object_syncing_state():
""" Get a dictionary mapping which object trackers are active.
The dictionary contains name:bool pairs that can be fed back into
the func:`set_object_syncing_state()` function.
"""
states = {
"selection": bool(this._on_selection_changed_cb_id),
... | c6fa40e7945b8186db06cc00b461fc2fe6a16c36 | 3,656,180 |
def determine_nohit_score(cons, invert):
"""
Determine the value in the matrix assigned to nohit given SeqFindr options
:param cons: whether the Seqfindr run is using mapping consensus data
or not
:param invert: whether the Seqfindr run is inverting (missing hits to
... | d0539b5ac4dda8b4a15c6800fb4a821cb305b319 | 3,656,181 |
def library_get_monomer_desc(res_name):
"""Loads/caches/returns the monomer description objec MonomerDesc
for the given monomer residue name.
"""
assert isinstance(res_name, str)
try:
return MONOMER_RES_NAME_CACHE[res_name]
except KeyError:
pass
mon_desc = library_construct... | 98b4790995bd1d2eba96775e99826fae7b7cfc8a | 3,656,183 |
def _seqfix(ref_seq, seq, comp_len, rev):
""" Fill or trim a portion of the beginning of a sequence relative to a
reference sequence
Args:
ref_seq (str): reference sequence e.g. germline gene
seq (str): sequence to compare to reference
comp_len (int): length of s... | 222ba3a8e2c4bced8ebcde6662890c10a0b41cf8 | 3,656,187 |
import torch
from typing import Tuple
def get_dedup_tokens(logits_batch: torch.Tensor) \
-> Tuple[torch.Tensor, torch.Tensor]:
"""Converts a batch of logits into the batch most probable tokens and their probabilities.
Args:
logits_batch (Tensor): Batch of logits (N x T x V).
Returns:
... | 885048842e6d1b50cd5b98c5b455aeb71e49c191 | 3,656,188 |
def com(im):
"""
Compute the center of mass of im.
Expects that im is leveled (ie zero-centered). Ie, a pure noise image should have zero mean.
Sometimes this is improved if you square the im first com(im**2)
Returns:
y, x in array form.
"""
im = np.nan_to_num(im)
mass = np.sum(i... | 5e1a7c20075df3fe5804213e5fdddd4f46d276c6 | 3,656,189 |
def get_fitting_custom_pipeline():
"""
Pipeline looking like this
lagged -> custom -> ridge
"""
lagged_node = PrimaryNode('lagged')
lagged_node.custom_params = {'window_size': 50}
# For custom model params as initial approximation and model as function is necessary
custom_node =... | 3ed78dc2f83110b0ac7dd4622a76511d0316404f | 3,656,190 |
def get_regularizable_variables(scope):
"""
Get *all* regularizable variables in the scope.
:param scope: scope to filter variables by
:return:
"""
return tf.get_collection(REGULARIZABLE_VARS, scope) | 67a6673be12af47128a453e413778f18f4344eaa | 3,656,191 |
import glob
def load(midi_path: str, config: dict):
"""
returns a 3-tuple of `tf.Dataset` each returning `(input_seq, target_seq)`, representing train,
validation, and test portions of the overall dataset. `input_seq` represents the `inp_split`
portion of each midi sequence in `midi_path`.
"""
batch... | 38d890a78cf85ce43cbdb783246ef1a5e7e2cd06 | 3,656,192 |
import re
def _parse_docstring(doc):
"""Extract documentation from a function's docstring."""
if doc is None:
return _Doc('', '', {}, [])
# Convert Google- or Numpy-style docstrings to RST.
# (Should do nothing if not in either style.)
# use_ivar avoids generating an unhandled .. attribut... | ff4e3ce300748c32c2e65129c381f1e74912f4a1 | 3,656,193 |
def extract_remove_outward_edges_filter(exceptions_from_removal):
"""
This creates a closure that goes through the list of tuples to explicitly state which edges are leaving from the first argument of each tuple.
Each tuple that is passed in has two members. The first member is a string representing a sing... | 543e5823b8375cbdec200988ea5dd0c4f2d23d05 | 3,656,194 |
import torch
def ln_addTH(x : torch.Tensor, beta : torch.Tensor) -> torch.Tensor:
"""
out = x + beta[None, :, None]
"""
return x + beta[None, :, None] | 77e556c41a33a8c941826604b4b595ea7d456f9a | 3,656,195 |
def drude2(tags, e, p):
"""dielectric function according to Drude theory for fitting"""
return drude(e, p[0], p[1], p[2], p[3]) | 8032c61df099f6c1ac671f2b81c3bb93d1f81317 | 3,656,196 |
def ParseFile(path):
"""Parse function names and comments from a .h path.
Returns mapping from function name to comment.
"""
result = {}
with open(path, 'r') as fp:
lines = fp.readlines()
i = 0
n = len(lines)
while i < n:
line = lines[i]
m = MCRE.match(line)
if m and not m.g... | 6319137de084aaf366b28e76af52cc1911298d8b | 3,656,197 |
from typing import Dict
def get_records(data: Dict[_Expr, Dict], column_order):
"""Output data as a list of records"""
def cell_callback(expr, i, val, spreadsheet_data):
spreadsheet_data[-1].append(val)
return spreadsheet_data
def row_callback(spreadsheet_data):
spreadsheet_data[-1... | 8a8eb0e69c9dabe6dfc59c9b5637fdf4ee2d2dd1 | 3,656,198 |
import torch
def support_mask_to_label(support_masks, n_way, k_shot, num_points):
"""
Args:
support_masks: binary (foreground/background) masks with shape (n_way, k_shot, num_points)
"""
support_masks = support_masks.view(n_way, k_shot*num_points)
support_labels = []
for n in range(sup... | e6d73dc93e1e0b54d805d9c8b69785168dd2621e | 3,656,199 |
def cal_covered_users(positions, heat_map, radius):
"""
:param positions: $k$ positions array of !!!(y, x)!!!
:param heat_map: grid data with count
:param radius: 0(1 grid), 1(8 grids), 2(25 grids)
:return: coverage score
"""
row_num, col_num = heat_map.shape
mask = np.zeros(heat_map.sha... | 52e3fec6b7aa01c9882c15ca3331b3199fa554a2 | 3,656,200 |
from typing import Union
import pathlib
def certificate_from_file(
filename: Union[str, pathlib.Path],
format=OpenSSL.crypto.FILETYPE_PEM,
) -> TS.X509:
"""Load an X509 certificate from ``filename``.
:param filename: The path to the certificate on disk.
:param format: The format of the certificat... | 1cc3cb514454118ed6af9257b35aa39586bce31b | 3,656,201 |
def get_welcome_response(session):
"""
Welcome the user to my python skill
"""
card_title = "Welcome"
speech_output = "Welcome to my python skill. You can search for GitHub repositories. "
# If the user either does not reply to the welcome message or says something
# that is not understood... | d90bbd14bef29f1d7400042bbc593e4bb63b8713 | 3,656,202 |
import numpy as np
def rotate_quaternion ( angle, axis, old ):
"""Returns a quaternion rotated by angle about axis relative to old quaternion."""
# Note that the axis vector should be normalized and we test for this
# In general, the old quaternion need not be normalized, and the same goes for the resul... | ccc67dbcd2153b40a4e4c560d423d4c495912d8e | 3,656,203 |
def rochepot_dl(x, y, z, q):
"""
Dimensionless Roche potential (:math:`\\Phi_n`, synchronous rotation)
More massive component (:math:`m_1`) is centered at (x,y,z) = (0,0,0). Less massive
component (:math:`m_2`) is at (1,0,0). The unit of length is the distance between
the objects. Both objects ... | f3d15ea27e6b4c476d345fa8af254b2a14cbdfbc | 3,656,205 |
def health_check(config):
"""
Tests the API to ensure it is working.
"""
itglue = ITGlue(config['api_key'], config['itglue_host'])
try:
itglue._make_request('organizations', {})
return True
except:
return False | 02b9a582b506f590adcdcdbd661abbc7aec52d26 | 3,656,206 |
import io
import time
def capture_image(resolution=(1024, 768), size=(320, 240), sleep=2):
"""
Captures image from raspberry pi camera
resolution -- resolution of capture
size -- size of output
sleep -- sleep time in seconds
"""
stream = io.BytesIO()
with picamera.PiCamera() as camera:... | c8967d6bce5f953d11878fb31fa02dbffbe4e283 | 3,656,207 |
import numpy
def MLVR(XDATA,YDATA,xreference=0,residual=1,xlabel='',ylabel='',title='',alpha = 0.01,iters = 1000,plot=1):
"""Does Multivariant Linear Regression
properties:
XDATA = The Feature Dataframe
YDATA = The Target Dataframe
xreference = 1/0 -> The column index in XDATA for ploting graph
xlabel = La... | 84509c2e8ccc9b4f52b5d90432e74a18da226b0a | 3,656,208 |
def FilterAndTagWrapper(target, dontRemoveTag=False):
"""\
Returns a component that wraps a target component, tagging all traffic
going into its inbox; and filtering outany traffic coming out of its outbox
with the same unique id.
"""
if dontRemoveTag:
Filter = FilterButKeepTag
else:... | 045cdd4f0716ba187211fbb1a4536f1f4c863bc1 | 3,656,209 |
from typing import Union
def format_time(seconds: Union[int, float]) -> str:
"""Convert the seconds to human readable string with days, hours, minutes and seconds."""
s = int(np.rint(seconds))
if s < 60:
return "{0}s".format(s)
elif s < 60 * 60:
return "{0}m {1:02}s".format(s // 60, s... | f50b7d96a91e6e261169f0f0c9d71186e3c208fe | 3,656,210 |
def run_model(df, i, name, gscv, calibrate=True):
"""Given customercode values in dict_folds,
1. create balanced dataset
2. split into train, test sets
3. run grid search
4. get probability scores
5. calibrate as directed
6. find optimal cutoff from precision-recall
7. return predictions... | 0f5513b7e4117580dd297ee5e9b7a88afc691b3a | 3,656,211 |
import re
def extract_date(db):
"""Extract Release Date from metadata and convert it into YYYY MM format"""
date_pattern = 'releaseDate\":(\d{9,10})'
def format_date(x):
"""Takes epoch time as argument and returns date in YYYY MM format"""
date = re.search(date_pattern, x)
if dat... | 9d4d8c19846a49967f9e3deb3be8808df9d69812 | 3,656,213 |
def split_test_image(aa):
"""
Separate image created by mk_test_image into x,y components
"""
if aa.dtype.kind == 'f':
y = np.round((aa % 1)*1024)
x = np.floor(aa)
else:
nshift = (aa.dtype.itemsize*8)//2
mask = (1 << nshift) - 1
y = aa & mask
x = aa >>... | 4a06a0c0fb80dfcb8a58d9509971bfdc0b026d27 | 3,656,214 |
def sphdist(ra1, dec1, ra2, dec2):
"""measures the spherical distance between 2 points
Inputs:
(ra1, dec1) in degrees
(ra2, dec2) in degrees
Outputs:
returns a distance in degrees
"""
dec1_r = deg2rad(dec1)
dec2_r = deg2rad(dec2)
return 2. * rad2deg( arcsin( sqrt( ( sin((dec1_r - dec2_r) / 2)) ** 2 + cos(d... | 517f7c67370c6e065c8860b2be59470a2801567d | 3,656,215 |
def parse_kwargs(kwargs, a_list):
"""
extract values from kwargs or set default
"""
if a_list is not None:
num_colors = len(a_list)
default_colors = generate_colors(num_colors)
else:
num_colors = 1
default_colors = 'k'
logscale = kwargs.get('logscale', [False, Fa... | 3f1006a8f638b3304ec6aa975346be1a4b6e8189 | 3,656,216 |
def talib_WCLPRICE(DataFrame):
"""WCLPRICE - Weighted Close Price 加权收盘价"""
res = talib.WCLPRICE(DataFrame.high.values, DataFrame.low.values,
DataFrame.close.values)
return pd.DataFrame({'WCLPRICE': res}, index=DataFrame.index) | 6e2d4530fcb33d64b9fbe8a3f0a8a5d64c8f8107 | 3,656,217 |
def is_pi_parallel(ring1_center: np.ndarray,
ring1_normal: np.ndarray,
ring2_center: np.ndarray,
ring2_normal: np.ndarray,
dist_cutoff: float = 8.0,
angle_cutoff: float = 30.0) -> bool:
"""Check if two aromatic rings form a... | def4eaba9e25e9034fce7559041e5142f82fc3c8 | 3,656,218 |
def _fetch_alleninf_coords(*args, **kwargs):
"""
Gets updated MNI coordinates for AHBA samples, as shipped with `alleninf`
Returns
-------
coords : :class:`pandas.DataFrame`
Updated MNI coordinates for all AHBA samples
References
----------
Updated MNI coordinates taken from ht... | dae30a0f5404151a3e7d82f129ff36cfec14caa0 | 3,656,219 |
from typing import List
from typing import Union
from typing import DefaultDict
from typing import Dict
from typing import Tuple
def get_classes_for_mol_network(can: canopus.Canopus,
hierarchy: List[str],
npc_hierarchy: List[str],
... | 6808a751ed1873b7fb573bb3ecc55586d94590b1 | 3,656,220 |
def list_books(books):
"""Creates a string that, on each line, informs about a book."""
return '\n'.join([f'+ {book.name}: {book.renew_count}: {book.return_date}'
for book in books]) | fce770a39def7f40ed12820a578b4e327df7da43 | 3,656,221 |
def getHSPLNamespace():
"""
Retrieve the namespace of the HSPL XML.
@return: The namespace of the HSPL XML.
"""
return HSPL_NAMESPACE | 481db5781ff9d0b4a4e4702cccafb088379e38a4 | 3,656,222 |
def add_lead_zero(num,digit,IgnoreDataManipulation=False,RaiseDataManipulationError=False,DigitMustAtLeastTwo=False):
"""Add leading the letters '0' to inputted integer 'num' according to defined 'digit' and return as string.
Required keyword arguments:
- num (int) : Integer (can be positive, zero, or negative)
... | ae3cffa2470a2acf5900a41b342366fb7c6e92da | 3,656,223 |
def _attach_monitoring_policy_server(module, oneandone_conn, monitoring_policy_id, servers):
"""
Attaches servers to a monitoring policy.
"""
try:
attach_servers = []
for _server_id in servers:
server_id = get_server(oneandone_conn, _server_id)
attach_server = on... | bf096804ec6be47fa4e41c9f4e50d51313f8ef3f | 3,656,224 |
from typing import Union
def get_generator_contingency_fcas_availability_term_2(data, trader_id, trade_type, intervention) -> Union[float, None]:
"""Get generator contingency FCAS term 2"""
# Parameters
lower_slope_coefficient = get_lower_slope_coefficient(data, trader_id, trade_type)
if lower_slope... | 8ec9c76c1941713511f8b472c4649954fd725d58 | 3,656,225 |
def format_pvalue(p_value, alpha=0.05, include_equal=True):
"""
If p-value is lower than 0.05, change it to "<0.05", otherwise, round it to two decimals
:param p_val: input p-value as a float
:param alpha: significance level
:param include_equal: include equal sign ('=') to pvalue (e.g., '=0.06') or... | aa6506b14b68746f4fa58d951f246321e8b5a627 | 3,656,226 |
def _compute_y(x, ll):
"""Computes y."""
return np.sqrt(1 - ll ** 2 * (1 - x ** 2)) | 773a0695676e43984bb0ca8c1d8af2e0bc3bb4fd | 3,656,227 |
def create_axis(length=1.0, use_neg=True):
"""
Create axis.
:param length:
:param use_neg: If False, Only defined in Positive planes
:return: Axis object
"""
# Defining the location and colors of each vertex of the shape
vertices = [
# positions colors
-length... | fe9c9d49de786147a382e1fda1e6ab92d26a1fe9 | 3,656,228 |
def genmatrix(list, combinfunc, symmetric=False, diagonal=None):
"""
Takes a list and generates a 2D-matrix using the supplied combination
function to calculate the values.
PARAMETERS
list - the list of items
combinfunc - the function that is used to calculate teh value in a cell.
... | b7d8ebc916f57621a20c371139162cb0504470cd | 3,656,229 |
def get_all_raw_codes_by_area(area: EmisPermArea) -> list:
"""
Returns a list of code names for all permissions within a logical area,
for all possible modes.
"""
return get_raw_codes_by_area(
area, EmisPermMode.CREATE | EmisPermMode.UPDATE | EmisPermMode.VIEW
) | d5887af92ba5fb7c373078dca84a8f9e74a089dc | 3,656,230 |
def cartesian_pair(df1, df2, **kwargs):
"""
Make a cross join (cartesian product) between two dataframes by using a constant temporary key.
Also sets a MultiIndex which is the cartesian product of the indices of the input dataframes.
See: https://github.com/pydata/pandas/issues/5401
:param df1 dataf... | e4ec1526f7a7906c5349bff20f5d4f83244c8878 | 3,656,231 |
def get_cases_by_landkreise_3daysbefore():
"""
Return all Hospitals
"""
hospitals_aggregated = db.session.query(CasesPerLandkreis3DaysBefore).all()
return jsonify(__as_feature_collection(hospitals_aggregated)), 200 | 0442f66ff78549617dd582bc0d1529c0041e7edb | 3,656,232 |
def shape_list(x, out_type=tf.int32):
"""Deal with dynamic shape in tensorflow cleanly."""
static = x.shape.as_list()
dynamic = tf.shape(x, out_type=out_type)
return [dynamic[i] if s is None else s for i, s in enumerate(static)] | 80eea7ccdd4ebfa5a3318fb6070ec996df5b4972 | 3,656,233 |
import json
from typing import cast
def load_config(
config_file: str, print_warnings: bool = False
) -> InfestorConfiguration:
"""
Loads an infestor configuration from file and validates it.
"""
try:
with open(config_file, "r") as ifp:
raw_config = json.load(ifp)
except:
... | b1d4a1385bb8855530f7043ddff5cc8d2f48be79 | 3,656,235 |
def what_do_you_mean_response(ctx: Context) -> REPLY_TYPE:
"""Generate response when we are asked about subject of the dialog
Returns:
template phrase based on previous skill or intent or topic
confidence (can be 0.0, DONTKNOW_CONF, UNIVERSAL_RESPONSE_CONF, SUPER_CONF)
human attributes (... | 694b693d5ed1595781fdfe975f716cca4ff2dcd2 | 3,656,236 |
import warnings
def get_market_tops(symbols=None, **kwargs):
"""
MOVED to iexfinance.iexdata.get_tops
"""
warnings.warn(WNG_MSG % ("get_market_tops", "iexdata.get_tops"))
return TOPS(symbols, **kwargs).fetch() | 4c94e35f447762a3d3ed9c076708450f1d1f200b | 3,656,238 |
from pathlib import Path
def reduce_output_path(path=None, pdb_name=None):
"""Defines location of Reduce output files relative to input files."""
if not path:
if not pdb_name:
raise NameError(
"Cannot save an output for a temporary file without a PDB"
"code ... | 0add37e0d5b71998112045af34aba4c0a17310f9 | 3,656,240 |
def link_discord(request: HttpRequest):
"""Page to prompt user to link their discord account to their user account."""
skip_confirmation = request.GET.get("skip-confirm")
if skip_confirmation and skip_confirmation == "true":
return redirect("discord_register")
return render(request, "link_disco... | 05aba45b508e5a23cf62f5791a04e2525bbbbae0 | 3,656,242 |
import six
import functools
def rpc(f=None, **kwargs):
"""Marks a method as RPC."""
if f is not None:
if isinstance(f, six.string_types):
if 'name' in kwargs:
raise ValueError('name option duplicated')
kwargs['name'] = f
else:
return rpc(**kw... | 37ac21bd800bb202a78542636e9249ac3519c54e | 3,656,243 |
def fig_fits_h(fig, y):
"""Lista ut of figuren *fig* far plats pa hojden pa skarmen vid
position *x*, *y*
"""
_, h = _get_max_width()
win_h = fig.window.winfo_height()
result = (y + win_h) < h
return result | 4e3254d7a4fad2d8de816b36aacbfd069378c1fc | 3,656,244 |
def index():
"""
Handler for the root url. Loads all movies and renders the first page.
"""
if path_set():
load_movies()
return flask.render_template('main.html') | 8f5c3295175cfd45b3604d523ac6b7de086702e9 | 3,656,246 |
def __hitScore__(srcMZ, targetMZ, srcRT, targetRT, parameters):
# type: (float, float, float, float, LFParameters) -> float
"""Return the hit score of the target frame for the given source
frame.
Keyword Arguments:
srcMZ -- source m/z
targetMZ -- target m/z
srcRT -- ... | 1b35cfbb2f1e028ccbb53d4fed16459d5a469ac1 | 3,656,247 |
def compute_propeller_nonuniform_freestream(prop, upstream_wake,conditions):
""" Computes the inflow velocities in the frame of the rotating propeller
Inputs:
prop. SUAVE propeller
tip_radius - propeller radius [m... | c7dc48066356e4d79e512812976a3e1a80b16749 | 3,656,248 |
def _expect_const(obj):
"""Return a Constant, or raise TypeError."""
if obj in (0, "0"):
return ZERO
if obj in (1, "1"):
return ONE
if obj in ("x", "X"):
return LOGICAL
if obj == "?":
return ILLOGICAL
if isinstance(obj, Constant):
return obj
raise Type... | 33aff48ff285b89f36d28a99148afeea97302a05 | 3,656,249 |
def _eval_input_receiver_fn(tf_transform_output, schema, label_key):
"""Build everything needed for the tf-model-analysis to run the model.
Args:
tf_transform_output: A TFTransformOutput.
schema: the schema of the input data.
label_key: the name of the transformed label
Returns:
EvalInputReceiver ... | 60f0a6cf9a87894f7e37495b8b4e9f7bd9e85e22 | 3,656,250 |
def get_lpar_names(adp):
"""Get a list of the LPAR names.
:param adp: A pypowervm.adapter.Adapter instance for the PowerVM API.
:return: A list of string names of the PowerVM Logical Partitions.
"""
return [x.name for x in pvm_lpar.LPAR.search(adp, is_mgmt_partition=False)] | 4009ed95b23ba6a35cbe38e1354f109e29fb7fc7 | 3,656,251 |
def init_mlp(in_dim, out_dim, hidden_dim, num_layers, non_linearity=None, bias=True):
"""Initializes a MultilayerPerceptron.
Args:
in_dim: int
out_dim: int
hidden_dim: int
num_layers: int
non_linearity: differentiable function (tanh by default)
bias (bool)
R... | a2d5b8535af5d363df459cf0d2138b29b2356f30 | 3,656,252 |
def c_grad_curry_regularized(data, target):
"""A closure constructor with regularization term for functional."""
def loss(layerweight):
model = (lambda x: layerweight @ x.t())
reg = 1e-3 * (layerweight**2).sum()/2
return criterion(model(data).t(), target) + reg
return loss | 4571c8849bb1643b4d27bad7d2d0ed88ed23c2fa | 3,656,253 |
from typing import Counter
def convert_examples_to_features_yake(examples, label_list, max_seq_length,
tokenizer, output_mode,
cls_token_at_end=False, pad_on_left=False,
cls_token='[CLS]', sep_token='[SEP]', noi_token='... | 4af89357339a2a63ff765f9da8660ca3895ba8b5 | 3,656,254 |
def sq_to_hr(bins, rho, S_k, k, axis=1):
"""
Takes the structure factor s(q) and computes the real space
total correlation function h(r)
"""
# setup scales
dr = np.pi / (k[0] * bins)
radius = dr * np.arange(1, bins + 1, dtype=np.float)
# Rearrange to find total correlation function fr... | 870e535ee3cdec3b138da1c205b000292eaee8ba | 3,656,255 |
def scale17(data, factor):
"""Solution to exercise C-1.17.
Had we implemented the scale function (page 25) as follows, does it work
properly?
def scale(data, factor):
for val in data:
val *= factor
Explain why or why not.
--------------------------------------------------... | 84ac4012e0c839b78cb8617b6b9b7c2e8c54caa2 | 3,656,256 |
import sqlite3
def initialize_database() -> sqlite3.Connection:
"""Create a sqlite3 database stored in memory with two tables to hold
users, records and history. Returns the connection to the created database."""
with sqlite3.connect("bank_buds.db") as conn:
conn.execute("""CREATE TABLE IF NOT EXI... | c3e32534de39a53686672c5c537a2c277fa2d06d | 3,656,257 |
def stateless_multinomial(logits,
num_samples,
seed,
output_dtype=dtypes.int64,
name=None):
"""Draws deterministic pseudorandom samples from a multinomial distribution.
This is a stateless version of `tf.random.... | da750b8a33348b4f6ff0b47897b4421a8099f12e | 3,656,258 |
def calc_kss(tag,vj):
"""
calculate Kolmogorov-Smirnov statistics as in CMap; Lamb J, Science, 2006
Parameters
----------
tag: tuple
tuple of up-/down-gene lists; (up,down)
sorted with the values in the descending order
vj: dict
dictionary corresponding to V(j) in CMap;... | 8dbb6233fb82a65a3ffad347f8444d3c16f8f4a9 | 3,656,259 |
def encode(elem):
"""This is the general function to call when you wish to encode an
element and all its children and sub-children.
Encode in this context means to convert from pymm elements to
xml.etree.ElementTree elements.
Typically this is called by pymm.write()
"""
converter = Conversio... | 13578267efb0a6e21b61d86a6c60f5ecd9235b05 | 3,656,260 |
def register_blueprints(app: "Flask") -> "Flask":
"""A function to register flask blueprint.
To register blueprints add them like the example
Example usage:
from app.blueprints import blueprint
app.register_blueprint(blueprint)
Args:
app (Flask): Flask Application instance
R... | 13564aa6f95d995362a56e9be02a51e50475e446 | 3,656,261 |
def build_history_class(
cls: declarative.DeclarativeMeta,
prop: T_PROPS,
schema: str = None) -> nine.Type[TemporalProperty]:
"""build a sqlalchemy model for given prop"""
class_name = "%s%s_%s" % (cls.__name__, 'History', prop.key)
table = build_history_table(cls, prop, schema)
... | 696b379172c57145c215b64e3e3dc4648b42e535 | 3,656,262 |
def geo_distance(left, right):
"""
Compute distance between two geo spatial data
Parameters
----------
left : geometry or geography
right : geometry or geography
Returns
-------
distance : double scalar
"""
op = ops.GeoDistance(left, right)
return op.to_expr() | 8a7f1bc14eacf38cecda874d8b16d6c38d9d2049 | 3,656,263 |
def svn_dirent_local_style(*args):
"""svn_dirent_local_style(char dirent, apr_pool_t pool) -> char"""
return _core.svn_dirent_local_style(*args) | afe170a321713c9d0f671303fa71d86bc93d8167 | 3,656,264 |
def make_generator_model():
"""
The Generator
The generator uses `tf.keras.layers.Conv2DTranspose` (upsampling)
tf.keras.layers.to produce an image from a seed (random noise).
Start with a `Dense` layer that takes this seed as input,
then upsample several times until you reach the desired image ... | e02fa5487805a85aaa5830ce90a6cc26cb2f27a4 | 3,656,265 |
def find_simple_cycles(dg):
""" Find all simple cycles given a networkx graph.
Args:
dg (obj): a networkx directed graph
Returns:
simple_cycles (list of lists): a list of simple cycles ordered by number of segments.
"""
simple_cycles = [c for c in nx.simple_cycles(dg) if len(c) > 2]
... | 4ed18ec26df80631c415086b99e470567e2641ae | 3,656,266 |
from typing import Optional
def augment_edge(edge_index: np.ndarray, nodes: np.ndarray,
edge_weight: np.ndarray = None, *,
nbrs_to_link: Optional[np.ndarray] = None,
common_nbrs: Optional[np.ndarray] = None,
fill_weight: float = 1.0) -> tuple:
""... | 9b128dfd4bcefa7912af857de6998183ef4da3c2 | 3,656,267 |
def status(proc):
"""Check for processes status"""
if proc.is_alive==True:
return 'alive'
elif proc.is_alive==False:
return 'dead'
else:
return proc.is_alive() | e257385f06979643e19fd9facc2118f4ae07c909 | 3,656,269 |
def is_plumed_file(filename):
"""
Check if given file is in PLUMED format.
Parameters
----------
filename : string, optional
PLUMED output file
Returns
-------
bool
wheter is a plumed output file
"""
headers = pd.read_csv(filename, sep=" ", skipinitialspace=True... | b6fca7c82efb2b07779406f06c15bf195bb4b5e9 | 3,656,270 |
def detect_llj_xarray(da, inverse=False):
""" Identify local maxima in wind profiles.
args:
- da : xarray.DataArray with wind profile data
- inverse : to flip the array if the data is stored upside down
returns: : xarray.Dataset with vertical dimension removed containin... | 3fbe444e5eed6ff1ec4f525145276e2bc974050c | 3,656,271 |
def gen_blinds(depth, width, height, spacing, angle, curve, movedown):
"""Generate genblinds command for genBSDF."""
nslats = int(round(height / spacing, 0))
slat_cmd = "!genblinds blindmaterial blinds "
slat_cmd += "{} {} {} {} {} {}".format(
depth, width, height, nslats, angle, curve)
slat... | 2e8a2751f2bb2be0c2ffdff8218961b0b1c0191b | 3,656,272 |
def dev_Sonic(Mach, gamma=defg._gamma):
"""computes the deviation angle for a downstream SONIC Mach number
Args:
Mach: param gamma: (Default value = defg._gamma)
gamma: (Default value = defg._gamma)
Returns:
"""
return deflection_Mach_sigma(Mach, sigma_Sonic(Mach, gamma=gamma), gamm... | a29f90ec1de25a3b86c2dcc1a1a6becedbfbf696 | 3,656,273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.