content string | sha1 string | id int64 |
|---|---|---|
from typing import Union
from typing import Tuple
from typing import Dict
from typing import Any
import io
def format_result(result: Union[Pose, PackedPose]) -> Tuple[str, Dict[Any, Any]]:
"""
:param: result: Pose or PackedPose object.
:return: tuple of (pdb_string, metadata)
Given a `Pose` or `Packed... | 15b3c6ce32a3a5ab860d045ba8679e0299f122f6 | 3,126 |
def str_array( listString):
"""
Becase the way tha Python prints an array is different from CPLEX,
this function goes the proper CPLEX writing of Arrays
:param listString: A list of values
:type listString: List[]
:returns: The String printing of the array, in CPLEX format
:rtype: String
"""
... | 46737bb05f310387d69be6516ebd90afd3d91b08 | 3,127 |
def read_gene_annos(phenoFile):
"""Read in gene-based metadata from an HDF5 file
Args:
phenoFile (str): filename for the relevant HDF5 file
Returns:
dictionary with feature annotations
"""
fpheno = h5py.File(phenoFile,'r')
# Feature annotations:
geneAnn = {}
for key... | 86e1b26a5600e1d52a3beb127ef8e7c3ac41721a | 3,128 |
from typing import Optional
import binascii
def hex_xformat_decode(s: str) -> Optional[bytes]:
"""
Reverse :func:`hex_xformat_encode`.
The parameter is a hex-encoded BLOB like
.. code-block:: none
"X'CDE7A24B1A9DBA3148BCB7A0B9DA5BB6A424486C'"
Original purpose and notes:
- SPECIAL ... | 8f868d4bbd5b6843632f9d3420fe239f688ffe15 | 3,129 |
def threshold(data, direction):
"""
Find a suitable threshold value which maximizes explained variance of the data projected onto direction.
NOTE: the chosen hyperplane would be described mathematically as $ x \dot direction = threshold $.
"""
projected_data = np.inner(data, direction)
sorted_x ... | 7fdab7f87c3c2e6d937da146ce5a27074ea92f52 | 3,130 |
def StrType_any(*x):
""" Ignores all parameters to return a StrType """
return StrType() | d1faac14a91cd6149811a553113b25f34d5d4a54 | 3,131 |
def height(tree):
"""Return the height of tree."""
if tree.is_empty():
return 0
else:
return 1+ max(height(tree.left_child()),\
height(tree.right_child())) | a469216fc13ed99acfb1bab8db7e031acc759f90 | 3,133 |
def applyTelluric(model, tell_alpha=1.0, airmass=1.5, pwv=0.5):
"""
Apply the telluric model on the science model.
Parameters
----------
model : model object
BT Settl model
alpha : float
telluric scaling factor (the power on the flux)
Returns
-------
model : model object
BT Settl model times... | 7eaf7cafe1f8b5f4c273858f289d2c1c3865680b | 3,134 |
def max_power_rule(mod, g, tmp):
"""
**Constraint Name**: DAC_Max_Power_Constraint
**Enforced Over**: DAC_OPR_TMPS
Power consumption cannot exceed capacity.
"""
return (
mod.DAC_Consume_Power_MW[g, tmp]
<= mod.Capacity_MW[g, mod.period[tmp]] * mod.Availability_Derate[g, tmp]
... | 2c1845253524a8383f2256a7d67a8231c2a69485 | 3,135 |
def check_archs(
copied_libs, # type: Mapping[Text, Mapping[Text, Text]]
require_archs=(), # type: Union[Text, Iterable[Text]]
stop_fast=False, # type: bool
):
# type: (...) -> Set[Union[Tuple[Text, FrozenSet[Text]], Tuple[Text, Text, FrozenSet[Text]]]] # noqa: E501
"""Check compatibility of ar... | d500e0b89ca3edd4e76630a628d9e4d970fadbf1 | 3,137 |
def create_data_table(headers, columns, match_tol=20) -> pd.DataFrame:
"""Based on headers and column data, create the data table."""
# Store the bottom y values of all of the row headers
header_tops = np.array([h.top for h in headers])
# Set up the grid: nrows by ncols
nrows = len(headers)
nc... | 56b1cb21afa7813138d03b56849b594e18664348 | 3,138 |
def interp2d_vis(model, model_lsts, model_freqs, data_lsts, data_freqs, flags=None,
kind='cubic', flag_extrapolate=True, medfilt_flagged=True, medfilt_window=(3, 7),
fill_value=None):
"""
Interpolate complex visibility model onto the time & frequency basis of
a data visibil... | 6ac4fad738691f470e36252fc7544e857c8fdca0 | 3,139 |
def eps_divide(n, d, eps=K.epsilon()):
""" perform division using eps """
return (n + eps) / (d + eps) | 2457e5fc4458521b4098cfb144b7ff07e163ba9c | 3,140 |
import requests
def get_mc_uuid(username):
"""Gets the Minecraft UUID for a username"""
url = f"https://api.mojang.com/users/profiles/minecraft/{username}"
res = requests.get(url)
if res.status_code == 204:
raise ValueError("Users must have a valid MC username")
else:
return res.js... | fceeb1d9eb096cd3e29f74d389c7c851422ec022 | 3,141 |
def api(default=None, api=None, **kwargs):
"""Returns the api instance in which this API function is being ran"""
return api or default | 3d636408914e2888f4dc512aff3f729512849ddf | 3,143 |
def parse_json(data):
"""Parses the PupleAir JSON file, returning a Sensors protobuf."""
channel_a = []
channel_b = {}
for result in data["results"]:
if "ParentID" in result:
channel_b[result["ParentID"]] = result
else:
channel_a.append(result)
sensors = list(... | 11ded094b71d6557cc7c1c7ed489cdcbfe881e0b | 3,144 |
import logging
import traceback
def asynchronize_tornado_handler(handler_class):
"""
A helper function to turn a blocking handler into an async call
:param handler_class: a tornado RequestHandler which should be made asynchronus
:return: a class which does the same work on a threadpool
"""
cl... | 0e7d3b46b199cdf1aa1a31a19ed3d54f0abbce16 | 3,145 |
def convert_single_example(ex_index, example: InputExample,
tokenizer, label_map, dict_builder=None):
"""Converts a single `InputExample` into a single `InputFeatures`."""
# label_map = {"B": 0, "M": 1, "E": 2, "S": 3}
# tokens_raw = tokenizer.tokenize(example.text)
tokens_ra... | 3dca77aa191f821c9785c8431c4637e47582a588 | 3,146 |
async def converter_self_interaction_target(client, interaction_event):
"""
Internal converter for returning the received interaction event's target. Applicable for context application
commands.
This function is a coroutine.
Parameters
----------
client : ``Client``
The cli... | 66975897b9f8a7d0b224f80d1827af3ea07eb51d | 3,148 |
from typing import List
def publication_pages(publication_index_page) -> List[PublicationPage]:
"""Fixture providing 10 PublicationPage objects attached to publication_index_page"""
rv = []
for _ in range(0, 10):
p = _create_publication_page(
f"Test Publication Page {_}", publication_i... | 5d9b75bcbdc5c9485cc83ddc2befeb946f447227 | 3,149 |
from typing import List
def rp_completion(
rp2_metnet,
sink,
rp2paths_compounds,
rp2paths_pathways,
cache: rrCache = None,
upper_flux_bound: float = default_upper_flux_bound,
lower_flux_bound: float = default_lower_flux_bound,
max_subpaths_filter: int = default_max_subpaths_filter,
... | ac7539d1d8f0f9388c9d6bef570362d62ec90414 | 3,150 |
import torch
def wrap(func, *args, unsqueeze=False):
"""
Wrap a torch function so it can be called with NumPy arrays.
Input and return types are seamlessly converted.
"""
args = list(args)
for i, arg in enumerate(args):
if type(arg) == np.ndarray:
args[i] = torch.from_nump... | 5a5491e2b911235d7bf858b19d0d32a9e8da20e6 | 3,151 |
def STOCHF(data, fastk_period=5, fastd_period=3, fastd_ma_type=0):
"""
Stochastic %F
:param pd.DataFrame data: pandas DataFrame with open, high, low, close data
:param int fastk_period: period used for K fast indicator calculation
:param int fastd_period: period used for D fast indicator calculatio... | 3412a6832f54b2dfbaff7eb25de0f6644d914934 | 3,152 |
def playerid_reverse_lookup(player_ids, key_type=None):
"""Retrieve a table of player information given a list of player ids
:param player_ids: list of player ids
:type player_ids: list
:param key_type: name of the key type being looked up (one of "mlbam", "retro", "bbref", or "fangraphs")
:type ke... | e5bbe46567d1c8e517020d9cb9f551249ea8f515 | 3,153 |
def get_delta_z(z, rest_ghz, ghz=None):
"""
Take a measured GHz value, and calculates the restframe GHz value based on the given z of the matched galaxy
:param z:
:param ghz:
:return:
"""
# First step is to convert to nm rom rest frame GHz
set_zs = []
for key, values in transitions.... | acb0069c56fb34aeaba302368131400f3c35d643 | 3,154 |
def hist_orientation(qval, dt):
"""
provided with quats, and time spent* in the direction defined by quat
produces grouped by ra, dec and roll quaternions and corresponding time, spent in quats
params: qval a set of quats stored in scipy.spatial.transfrom.Rotation class
params: dt corresponding to... | bbdecc58a9a3dc248d68b73018cd5f1d803ddbfd | 3,155 |
def proclamadelcaucacom_story(soup):
"""
Function to pull the information we want from Proclamadelcauca.com stories
:param soup: BeautifulSoup object, ready to parse
"""
hold_dict = {}
#text
try:
article_body = soup.find('div', attrs={"class": "single-entradaContent"})
mainte... | e8bcf0faaa7731b71e7b9db33e454b422b3285bc | 3,157 |
def asarray_fft(x, inverse):
"""Recursive implementation of the 1D Cooley-Tukey FFT using np asarray
to prevent copying.
Parameters:
x (array): the discrete amplitudes to transform.
inverse (bool): perform the inverse fft if true.
Returns:
x (array): the amplitudes of the origin... | 87f86f8529f5c54535d9a188c454f762f96a7a58 | 3,158 |
import jinja2
def wrap_locale_context(func):
"""Wraps the func with the current locale."""
@jinja2.contextfilter
def _locale_filter(ctx, value, *args, **kwargs):
doc = ctx['doc']
if not kwargs.get('locale', None):
kwargs['locale'] = str(doc.locale)
return func(value, *... | a2f720e9ed38eb2bf0f546ab392f295d969f7ab7 | 3,160 |
from numpy import loadtxt
from scipy.interpolate import UnivariateSpline
def mu_Xe(keV=12):
"""Returns inverse 1/e penetration depth [mm-1 atm-1] of Xe given the
x-ray energy in keV. The transmission through a 3-mm thick slab of Xe at
6.17 atm (76 psi) was calculated every 100 eV over an energy range
... | 5f106871e7517ef910739b74a13d2139e03ed480 | 3,161 |
import hashlib
def file_md5(input_file):
"""
:param input_file: Path to input file.
:type input_file: str
:return: Returns the encoded data in the inputted file in hexadecimal format.
"""
with open(input_file, 'rb') as f:
data = f.read()
return hashlib.md5(data).hexdigest() | 4a7ea12e3b5e0429787eb65e651852e49b40ecf7 | 3,162 |
from typing import Dict
def message_args() -> Dict[str, str]:
"""A formatted message."""
return {"subject": "Test message", "message": "This is a test message"} | 4d25d5c9f54aa0997f2e619f90eb6632717cf0d3 | 3,164 |
def to_drive_type(value):
"""Convert value to DriveType enum."""
if isinstance(value, DriveType):
return value.value
sanitized = str(value).upper().strip().replace(" ", "_")
try:
return DriveType[sanitized].value
except KeyError as err:
raise ValueError(f"Unknown drive type:... | 10183ac3ad15c2e01d9abf262f097dc6b366e7ab | 3,165 |
def upload_authorized_key(host, port, filepath):
"""UPLOAD (key) upload_authorized_key"""
params = {'method': 'upload_authorized_key'}
files = [('key', filepath, file_get_contents(filepath))]
return _check(https.client.https_post(host, port, '/', params, files=files)) | 68ada5d834ff77c4ee1b09815a6b094c30a42c1b | 3,166 |
def thermalize_cutoff(localEnergies, smoothing_window, tol):
"""Return position where system is thermalized
according to some tolerance tol, based on the derivative
of the smoothed local energies
"""
mean = np.mean(localEnergies)
smoothLocalEnergies = smoothing(localEnergies, smoothing_window)
... | d72904596ab88298232e9c2ed0fac151e3e66a71 | 3,167 |
def annualize_metric(metric: float, holding_periods: int = 1) -> float:
"""
Annualize metric of arbitrary periodicity
:param metric: Metric to analyze
:param holding_periods:
:return: Annualized metric
"""
days_per_year = 365
trans_ratio = days_per_year / holding_periods
return (1... | 0c84816f29255d49e0f2420b17abba66e2387c99 | 3,168 |
def get_latest_tag():
"""
Find the value of the latest tag for the Adafruit CircuitPython library
bundle.
:return: The most recent tag value for the project.
"""
global LATEST_BUNDLE_VERSION # pylint: disable=global-statement
if LATEST_BUNDLE_VERSION == "":
LATEST_BUNDLE_VERSION = g... | 2195d2cde7e2ff67a110b1a1af2aa8cebad52294 | 3,170 |
def read_gold_conll2003(gold_file):
"""
Reads in the gold annotation from a file in CoNLL 2003 format.
Returns:
- gold: a String list containing one sequence tag per token.
E.g. [B-Kochschritt, L-Kochschritt, U-Zutat, O]
- lines: a list list containing the original line spli... | 1e11513c85428d20e83d54cc2fa2d42ddd903341 | 3,172 |
import functools
def translate_nova_exception(method):
"""Transforms a cinder exception but keeps its traceback intact."""
@functools.wraps(method)
def wrapper(self, ctx, *args, **kwargs):
try:
res = method(self, ctx, *args, **kwargs)
except (nova_exceptions.ConnectionRefused,
... | 186b7f944b03073c758b4af5f4ccfcaa80e8f5e8 | 3,173 |
def _update_form(form):
""" """
if not form.text():
return form.setStyleSheet(error_css)
return form.setStyleSheet(success_css) | 94e241a98aa6c8305965d4149f4d60e28843aea7 | 3,174 |
import torch
from torch_adapter import TorchAdapter
from openvino.inference_engine import IEPlugin
from openvino_adapter import OpenvinoAdapter
from torch_adapter import TorchAdapter
import importlib
def create_adapter(openvino, cpu_only, force_torch, use_myriad):
"""Create the best adapter based on constraints p... | 4fd0fc51c7758d32a1eac4d86d1b5dc6b90d20b7 | 3,175 |
def _make_ecg(inst, start, stop, reject_by_annotation=False, verbose=None):
"""Create ECG signal from cross channel average."""
if not any(c in inst for c in ['mag', 'grad']):
raise ValueError('Unable to generate artificial ECG channel')
for ch in ['mag', 'grad']:
if ch in inst:
... | 27d1ef6da9c9d491de4b9806c85528f1226b2c3d | 3,176 |
def lorentzian(freq, freq0, area, hwhm, phase, offset, drift):
"""
Lorentzian line-shape function
Parameters
----------
freq : float or float array
The frequencies for which the function is evaluated
freq0 : float
The center frequency of the function
area : float
hwhm: float
... | 2f9b2ede75773c2100941e16fd14210b1a85a453 | 3,177 |
def findTilt(root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return findTilt_helper(root)[1] | 1338a704f754678f88dedaf5a968aa3bfe4ff17f | 3,178 |
def generate_report():
"""
Get pylint analization report and write it to file
"""
files = get_files_to_check()
dir_path = create_report_dir()
file_path = create_report_file(dir_path)
config_opts = get_config_opts()
pylint_opts = '--load-plugins pylint_flask' + config_opts
pylint_stdo... | 655345a128847285712f683274637201ee264010 | 3,179 |
def make_trampoline(func_name):
""" Create a main function that calls another function """
mod = ir.Module('main')
main = ir.Procedure('main')
mod.add_function(main)
entry = ir.Block('entry')
main.add_block(entry)
main.entry = entry
entry.add_instruction(ir.ProcedureCall(func_name, []))
... | 1dcaf61cbadde4fdd8e94958658ce8b1b69612f1 | 3,181 |
def model_fields(dbo, baseuri=None):
"""Extract known fields from a BQ object, while removing any known
from C{excluded_fields}
@rtype: dict
@return fields to be rendered in XML
"""
attrs = {}
try:
dbo_fields = dbo.xmlfields
except AttributeError:
# This occurs when the ... | 59a07057dccb116cc4753a4973a3128ccc79c558 | 3,183 |
def get_bsj(seq, bsj):
"""Return transformed sequence of given BSJ"""
return seq[bsj:] + seq[:bsj] | d1320e5e3257ae22ca982ae4dcafbd4c6def9777 | 3,184 |
from typing import Dict
import warnings
import math
def sample(problem: Dict, N: int, calc_second_order: bool = True,
skip_values: int = 0):
"""Generates model inputs using Saltelli's extension of the Sobol' sequence.
Returns a NumPy matrix containing the model inputs using Saltelli's sampling
... | a3a356fd037b879c71cb6dc2e4751350857302e8 | 3,185 |
def standardize(table, option):
"""
standardize
Z = (X - mean) / (standard deviation)
"""
if option == 'table':
mean = np.mean(table)
std = np.std(table)
t = []
for row in table:
t_row = []
if option != 'table':
mean = np.mean(row)
std ... | 337ec0d22340ca74e54236e1cb39829eab8ad89b | 3,186 |
def raw_input_nonblock():
"""
return result of raw_input if has keyboard input, otherwise return None
"""
if _IS_OS_WIN32:
return _raw_input_nonblock_win32()
else:
raise NotImplementedError('Unsupported os.') | 90cc9febcaa4866334b69b19809565795a07de49 | 3,187 |
def get_batch_hard(draw_batch_size,hard_batchs_size,semihard_batchs_size,easy_batchs_size,norm_batchs_size,network,dataset,nb_classes, margin):
"""
Create batch of APN "hard" triplets
Arguments:
draw_batch_size -- integer : number of initial randomly taken samples
hard_batchs_size -- interger : sel... | da6dc7f69354b0b74b59717140c6c46826925050 | 3,188 |
import math
def sine(
start, end, freq, amp: Numeric = 1, n_periods: Numeric = 1
) -> TimeSerie:
"""
Generate a sine TimeSerie.
"""
index = pd.date_range(start=start, end=end, freq=freq)
return TimeSerie(
index=index,
y_values=np.sin(
np.linspace(0, 2 * math.pi * n_... | df4254f9fafcb61f0bcf492edf1847d89f4debb0 | 3,189 |
def get_from_address(sending_profile, template_from_address):
"""Get campaign from address."""
# Get template display name
if "<" in template_from_address:
template_display = template_from_address.split("<")[0].strip()
else:
template_display = None
# Get template sender
template... | 8617d2b793b76456cb7d1a17168f27fd1d548e6d | 3,190 |
import ctypes
def is_dwm_compositing_enabled():
"""Is Desktop Window Manager compositing (Aero) enabled.
"""
enabled = ctypes.c_bool()
try:
DwmIsCompositionEnabled = ctypes.windll.dwmapi.DwmIsCompositionEnabled
except (AttributeError, WindowsError):
# dwmapi or DwmIsCompositionEna... | 9b31b3ef62d626008d2b6c6ef59446be79da89f6 | 3,191 |
def fgsm(x, y_true, y_hat, epsilon=0.075):
"""Calculates the fast gradient sign method adversarial attack
Following the FGSM algorithm, determines the gradient of the cost function
wrt the input, then perturbs all the input in the direction that will cause
the greatest error, with small magnitude.
... | a71d2042ea1f5efa0a3f6409836da52bf323aa5c | 3,192 |
def tour_delete(request,id):
""" delete tour depending on id """
success_message, error_message = None, None
form = TourForm()
tour = get_object_or_404(Tour, id=id)
tours = Tour.objects.all()
if request.method=="POST":
tour.delete()
success_message = "deleted tour"
... | c42e355734444d858555ad627f202f73161cbedf | 3,193 |
import random
def d3():
"""Simulate the roll of a 3 sided die"""
return random.randint(1, 3) | c2eac44bb36b7e35c66894bce3467f568a735ca1 | 3,194 |
def _search_qr(model, identifier, session):
"""Search the database using a Query/Retrieve *Identifier* query.
Parameters
----------
model : pydicom.uid.UID
Either *Patient Root Query Retrieve Information Model* or *Study Root
Query Retrieve Information Model* for C-FIND, C-GET or C-MOVE... | 29fe8831b1e44a381202b48212ff7c40c4c8d7fd | 3,197 |
def find_max_value(binary_tree):
"""This function takes a binary tree and returns the largest value of all the nodes in that tree
with O(N) space and O(1) time using breadth first traversal while keeping track of the largest value thus far
in the traversal
"""
root_node = []
rootnode.push(binar... | a797ea1598195cfcfe1abf00d73562c59617ad9b | 3,199 |
def failed_jobs(username, root_wf_id, wf_id):
"""
Get a list of all failed jobs of the latest instance for a given workflow.
"""
dashboard = Dashboard(g.master_db_url, root_wf_id, wf_id)
args = __get_datatables_args()
total_count, filtered_count, failed_jobs_list = dashboard.get_failed_jobs(
... | 5d755f6e84f7c406174fb1a7bdb8de64a6e0c049 | 3,200 |
def get_vm_types(resources):
"""
Get all vm_types for a list of heat resources, do note that
some of the values retrieved may be invalid
"""
vm_types = []
for v in resources.values():
vm_types.extend(list(get_vm_types_for_resource(v)))
return set(vm_types) | f13e8860d5b25cd03360e859527d61a06d103f53 | 3,201 |
def interface_names(obj):
"""
Return: a list of interface names to which `obj' is conformant.
The list begins with `obj' itself if it is an interface.
Names are returned in depth-first order, left to right.
"""
return [o.__name__ for o in interfaces(obj)] | 99aad05e14daeb13ed7f19599684acc8b324df84 | 3,203 |
import six
def add_basic(token):
"""For use with Authorization headers, add "Basic "."""
if token:
return (u"Basic " if isinstance(token, six.text_type) else b"Basic ") + token
else:
return token | cd579e77e243fdfba0853a87087e45cf58bcc6f2 | 3,204 |
import json
import requests
def updateUser(token, leaderboard=None, showUsername=None, username=None):
"""
Update user account information.
Parameters-
token: Authentication token.
leaderboard: True to show user's profit on leaderboard.
showUsername: True to show the username on LN Marktes pu... | 9b953256b85327411445729b574cf9b79750e735 | 3,205 |
def init_validator(required, cls, *additional_validators):
"""
Create an attrs validator based on the cls provided and required setting.
:param bool required: whether the field is required in a given model.
:param cls: the expected class type of object value.
:return: attrs validator chained correct... | 924b5ff6e77d38c989eef187498f774a2322ed48 | 3,206 |
def ShiftRight(x, **unused_kwargs):
"""Layer to shift the tensor to the right by padding on axis 1."""
if not isinstance(x, (list, tuple)): # non-chunked inputs
pad_widths = [(0, 0)] * len(x.shape)
pad_widths[1] = (1, 0) # Padding on axis=1
padded = np.pad(x, pad_widths, mode='constant')
return pa... | ec5265b5937e3e90e2c3267b6501b008ac7090e5 | 3,208 |
def empty_record():
"""Create an empty record."""
record = dump_empty(Marc21RecordSchema)
record["metadata"] = "<record> <leader>00000nam a2200000zca4500</leader></record>"
record["is_published"] = False
record["files"] = {"enabled": True}
return record | 7797e1bf0ade98a2400daff1f7937b7af2da280d | 3,210 |
def illuminanceToPhotonPixelRate(illuminance,
objective_numerical_aperture=1.0,
illumination_wavelength=0.55e-6,
camera_pixel_size=6.5e-6,
objective_magnification=1,
... | cbbb2f6bdce7592f997b7ab3784c15beb2b846b1 | 3,211 |
def stop_tuning(step):
""" stop tuning the current step method """
if hasattr(step, 'tune'):
step.tune = False
elif hasattr(step, 'methods'):
step.methods = [stop_tuning(s) for s in step.methods]
return step | 45e02b8d3ec86ceda97de69bbc730aa62affb06d | 3,212 |
import json
def assemble_english():
"""Assemble each statement into """
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
stmts = stmts_from_json(stmts_json)
sentences = {}
fo... | 24c267e2763198056e275feda1e81ef1bf280bdb | 3,213 |
def schema_class(classname, schema, schemarepr=None, basename='SchemaBase'):
"""Generate code for a schema class
Parameters
----------
classname : string
The name of the class to generate
schema : dict
The dictionary defining the schema class
basename : string (default: "SchemaB... | 2f497de54205e5c180805d77638c9ffe342f76c8 | 3,214 |
import requests
def orthology_events(ids='R-HSA-6799198,R-HSA-168256,R-HSA-168249', species='49633'):
"""
Reactome uses the set of manually curated human reactions to computationally infer reactions in
twenty evolutionarily divergent eukaryotic species for which high-quality whole-genome sequence
data... | 8a75e2bc9af34358164492d1d2b2d8154d4e696e | 3,215 |
def judge(name):
"""
Return some sort of score for automatically ranking names based on all the
features we can extract so far.
I guess we'll just add the scores * weights up for now.
"""
score = 0
for scoreID, scorer, weight in weights:
subscore = scorer(name)
score += subs... | 34811f49fc8fe6c88ef31978702cacddbacd5314 | 3,216 |
import re
def parse_year(inp, option='raise'):
"""
Attempt to parse a year out of a string.
Parameters
----------
inp : str
String from which year is to be parsed
option : str
Return option:
- "bool" will return True if year is found, else False.
- Return yea... | a91efb0614e7d0ad6753118f9b4efe8c3b40b4e2 | 3,217 |
def retry_import(e, **kwargs):
"""
When an exception occurs during channel/content import, if
* there is an Internet connection error or timeout error,
or HTTPError where the error code is one of the RETRY_STATUS_CODE,
return return True to retry the file transfer
* the file ... | b125841dff7154352b2031013ffa7058242e4974 | 3,218 |
def cvCloneMat(*args):
"""cvCloneMat(CvMat mat) -> CvMat"""
return _cv.cvCloneMat(*args) | 84dc4f59d29580477b7ded41f26d95011b2804b3 | 3,219 |
from typing import Callable
import time
def run_episode(kwargs) -> [Trajectory]:
"""
Runs a single episode and collects the trajectories of each agent
"""
total_controller_time = 0
env_dict: Callable = kwargs.get("env_dict")
obs_builder = kwargs.get("obs_builder")
controller_creator: Calla... | 91b64a8df57e1fc47ffecc184b0473d633b545c4 | 3,220 |
def get_data(request: Request):
"""
Get the data page.
Parameters
----------
request : Request
The request object.
Returns
-------
HTMLResponse
The data page.
"""
return templates.TemplateResponse("data.html", {"request": request}) | 4a44df5122f9db9009a769d4d9bec99d924fb0f7 | 3,222 |
def remove_last_measurements(dag_circuit, perform_remove=True):
"""Removes all measurements that occur as the last operation
on a given qubit for a DAG circuit. Measurements that are followed by
additional gates are untouched.
This operation is done in-place on the input DAG circuit if perform_pop=Tru... | 858a16c33de67f835cf32535f2e69f9c144d6e25 | 3,223 |
def J(*args, **kwargs):
"""Wrapper around jsonify that sets the Content-Type of the response to
application/vnd.api+json.
"""
response = jsonify(*args, **kwargs)
response.mimetype = "application/vnd.api+json"
return response | 714537b180cab60b7ad614018fa551020aeee292 | 3,225 |
def is_gzipped(filename):
""" Returns True if the target filename looks like a GZIP'd file.
"""
with open(filename, 'rb') as fh:
return fh.read(2) == b'\x1f\x8b' | b1afb5b9cddc91fbc304392171f04f4b018fa929 | 3,227 |
def tag_helper(tag, items, locked=True, remove=False):
""" Simple tag helper for editing a object. """
if not isinstance(items, list):
items = [items]
data = {}
if not remove:
for i, item in enumerate(items):
tagname = '%s[%s].tag.tag' % (tag, i)
data[tagname] = i... | 27500df099824fff1d93afbe7649d42141ffa9c1 | 3,229 |
def get_keys_from_file(csv):
"""Extract the credentials from a csv file."""
lines = tuple(open(csv, 'r'))
creds = lines[1]
access = creds.split(',')[2]
secret = creds.split(',')[3]
return access, secret | eccf56c52dd82656bf85fef618133f86fd9276e6 | 3,230 |
import pkg_resources
import json
def fix_model(project, models, invert=False):
"""Fix model name where file attribute is different from values accepted by facets
>>> fix_model('CMIP5', ['CESM1(BGC)', 'CESM1-BGC'])
['CESM1(BGC)', 'CESM1(BGC)']
>>> fix_model('CMIP5', ['CESM1(BGC)', 'CESM1-BGC'], inver... | b1e91ba7305a75ed376948d92607b1ab97bc93f2 | 3,231 |
from typing import Union
from typing import List
from typing import Tuple
def _get_choices(choices: Union[str, List]) -> List[Tuple[str, str]]:
"""Returns list of choices, used for the ChoiceFields"""
result = [('', '')]
if isinstance(choices, str):
result.append((choices, choices))
else:
... | 249a068571b0ddca858cd8dcc4f2f7af25689b9d | 3,235 |
def invalid_file():
"""Create an invalid filename string."""
return "/tmp/INVALID.FILE" | 9a249f3ef9445cb78bc962e46ef524360bb44bdb | 3,236 |
def get_model(app_label, model_name):
"""
Fetches a Django model using the app registery.
All other methods to acces models might raise an exception about
registery not being ready yet.
This doesn't require that an app with the given app label exists,
which makes it safe to call when the regis... | dd3ba70f2220ba09d256ae58b418cd3401f129e6 | 3,237 |
def affaires_view(request):
"""
Return all affaires
"""
# Check connected
if not check_connected(request):
raise exc.HTTPForbidden()
query = request.dbsession.query(VAffaire).order_by(VAffaire.id.desc()).all()
return Utils.serialize_many(query) | c44e703680034230121c426e7496746355b8ee4b | 3,238 |
from typing import Union
def metric_try_to_float(s: str) -> Union[float, str]:
"""
Try to convert input string to float value.
Return float value on success or input value on failure.
"""
v = s
try:
if "%" in v:
v = v[:-1]
return float(v)
except ValueError:
... | 6b0121469d35bc6af04d4808721c3ee06955d02e | 3,239 |
def _table_difference(left: TableExpr, right: TableExpr):
"""
Form the table set difference of two table expressions having identical
schemas. A set difference returns only the rows present in the left table
that are not present in the right table
Parameters
----------
left : TableExpr
... | aae66ddb29d30a0bc95750d62ce87c16773d3d63 | 3,241 |
def parse_args():
"""
It parses the command-line arguments.
Parameters
----------
args : list[str]
List of command-line arguments to parse
Returns
-------
parsed_args : argparse.Namespace
It contains the command-line arguments that are supplied by the user
"""
par... | 7849b9a1422e959be9e5b2504dc7d42c2475572d | 3,243 |
def parse_row(row, entity_dict, span_capture_list, previous_entity):
""" updates the entity dict and span capture list based on row contents """
bio_tag, entity = parse_tag(row.tag)
if bio_tag == 'B':
# update with previous entity, if applicable
entity_dict, span_capture_list, pre... | a7d49b6e4dbe747c65688c01652f1d413314b407 | 3,244 |
def _is_fn_init(
tokens: list[Token] | Token,
errors_handler: ErrorsHandler,
path: str,
namehandler: NameHandler,
i: int = 0
):
""" "fn" <fn-name> "("<arg>*")" (":" <returned-type>)? <code-body>"""
tokens = extract_tokens_with_code_body(tokens, i)
if tokens is None ... | 2e65dbe9e7976f7e13215fbf04bd40f08da7e16e | 3,245 |
import asyncio
from typing import cast
async def http_connect(address: str, port: int) -> HttpConnection:
"""Open connection to a remote host."""
loop = asyncio.get_event_loop()
_, connection = await loop.create_connection(HttpConnection, address, port)
return cast(HttpConnection, connection) | 2d98815b17f6d0e03763b643a052737f6931a33f | 3,246 |
def make_parallel_transformer_config() -> t5_architecture.EncoderDecoder:
"""Returns an EncoderDecoder with parallel=True."""
dtype = jnp.bfloat16
num_attn_heads = 8
make_dropout = lambda: nn.Dropout(rate=0.1, broadcast_dims=(-2,))
make_layer_norm = layer_norm.T5LayerNorm
def _make_encoder_layer(shared_rel... | f61c02d66075fb71fbecd58e8c369a6ba406c15f | 3,247 |
def get_device_mapping(embedding_sizes, num_gpus, data_parallel_bottom_mlp,
experimental_columnwise_split, num_numerical_features):
"""Get device mappings for hybrid parallelism
Bottom MLP running on device 0. Embeddings will be distributed across among all the devices.
Optimal solu... | 2265831d87d8f48c4b87ca020c7f56293cb62647 | 3,248 |
def _generate_relative_positions_embeddings(length, depth,
max_relative_position, name):
"""Generates tensor of size [length, length, depth]."""
with tf.variable_scope(name):
relative_positions_matrix = _generate_relative_positions_matrix(
length, max_relative... | 7c69705cf5cc161144181b09a377f66d863b12ae | 3,249 |
def continTapDetector(
fs: int, x=[], y=[], z=[], side='right',
):
"""
Detect the moments of finger-raising and -lowering
during a fingertapping task.
Function detects the axis with most variation and then
first detects several large/small pos/neg peaks, then
the function determines sample-w... | 742a7f5590e8ad76e521efe5d1c293c43d71de0b | 3,250 |
def parallelize(df, func):
""" Split data into max core partitions and execute func in parallel.
https://www.machinelearningplus.com/python/parallel-processing-python/
Parameters
----------
df : pandas Dataframe
func : any functions
Returns
-------
data : pandas Dataframe
R... | dc9c085ada6ffa26675bd9c4a218cc06807f9511 | 3,251 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.