content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def get_seconds_from_duration(time_str: str) -> int:
"""
This function will convert the TM1 time to seconds
:param time_str: P0DT00H01M43S
:return: int
"""
pattern = re.compile('\w(\d+)\w\w(\d+)\w(\d+)\w(\d+)\w')
matches = pattern.search(time_str)
d, h, m, s = matches.groups(... | a8614c0ed6e41c7216ae461ef1fd57319a5995e1 | 3,649,280 |
def get_protecteds(object: Object) -> Dictionary:
"""Gets the protected namespaces of an object."""
return object.__protecteds__ | 479f6ee0a9334107f67517fd6bb2ad55a915d0ac | 3,649,281 |
def pah2area(_position, angle, height, shape):
"""Calculates area from position, angle, height depending on shape."""
if shape == "PseudoVoigt":
fwhm = np.tan(angle) * height
area = (height * (fwhm * np.sqrt(np.pi / ln2))
/ (1 + np.sqrt(1 / (np.pi * ln2))))
return area
... | 79e239de4ee8b356152717f7a9a301f062cc6c71 | 3,649,282 |
def config(key, values, axis=None):
"""Class decorator to parameterize the Chainer configuration.
This is a specialized form of `parameterize` decorator to parameterize
the Chainer configuration. For all `time_*` functions and `setup` function
in the class, this decorator wraps the function to be calle... | a2ab11ca245647c6a5267b2f1c62a55b9aa1b96b | 3,649,284 |
def dot2states(dot):
"""Translate a dot-bracket string in a sequence of numerical states"""
dot = dot.replace(".", "0") # Unpaired
dot = dot.replace("(", "1") # Paired
dot = dot.replace(")", "1") # Paired
return np.array(list(dot), dtype=int) | 655b57749a39d04f62aae20ac16ffb1f31b0bc71 | 3,649,286 |
def mel_to_hz(mels, htk=False):
"""Convert mel bin numbers to frequencies
Examples
--------
>>> librosa.mel_to_hz(3)
200.
>>> librosa.mel_to_hz([1,2,3,4,5])
array([ 66.667, 133.333, 200. , 266.667, 333.333])
Parameters
----------
mels : np.ndarray [shape=(n,)],... | 93e9d115d9ef0a58420c796737b96f4460f44ceb | 3,649,287 |
import numpy as np
def load_images(images):
"""
Decodes batch of image bytes and returns a 4-D numpy array.
"""
batch = []
for image in images:
img_np = readImage(image)
batch.append(img_np)
batch_images = np.concatenate(batch)
logger.info('batch_images.shape:%s'%(str(bat... | ae4f18488cdfa4980f849f2f7110f9963381e6e7 | 3,649,288 |
def stats_hook():
"""
decorator to register a stats hook.
:raises InvalidStatsHookTypeError: invalid stats hook type error.
:returns: stats hook class.
:rtype: type
"""
def decorator(cls):
"""
decorates the given class and registers an instance
of it into available... | de386a9bff39c4060833f11100ec538b6d2b8d68 | 3,649,290 |
def safe_infer(node, context=None):
"""Return the inferred value for the given node.
Return None if inference failed or if there is some ambiguity (more than
one node has been inferred).
"""
try:
inferit = node.infer(context=context)
value = next(inferit)
except exceptions.Infer... | 928c1d2e3c2813cc389085ea6bd3ccd50709effe | 3,649,291 |
import functools
def catch_exception(func):
"""
Returns:
object:
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
worker = kwargs['error_catcher']
try:
return func(*args, **kwargs)
except Exception as e:
print('stdout:', worker.stdou... | be579d9b6723e5025b7b70f38c83bcedc30196a5 | 3,649,292 |
def RandomCrop(parent, new_shape, name=""):
"""\
Crop an image layer at a random location with size ``[height, width]``.
:param parent: parent layer
:param new_shape: [height, width] size
:param name: name of the output layer
:return: CropRandom layer
"""
return _eddl.RandomCrop(parent,... | 6078cf9f6daf73876d3503a1e77523df079c41d1 | 3,649,293 |
import time
def get_linear_sys(eqns, params):
"""Gets the linear system corresponding to the symbolic equations
Note that this function only work for models where the left-hand side of
the equations all contain only linear terms with respect to the given model
parameters. For these linear cases, this... | e3ef88c695bcbcd6e7ab1dfbe8ee45ad552e3be7 | 3,649,295 |
def slightly(membership: npt.ArrayLike) -> npt.ArrayLike:
"""
Applies the element-wise function fn(u) = u^(1/2).
:param membership: Membership function to be modified.
>>> from fuzzy_expert.operators import slightly
>>> slightly([0, 0.25, 0.5, 0.75, 1])
array([0. , 0.16326531, 0.9969618... | eb0e71462c5e3959584970e9e9b84a3dff876d54 | 3,649,296 |
def int_max(int_a, int_b):
"""
max(a, b)
"""
if int_a > int_b:
return int_a
else:
return int_b | 5ae0df8ff7bdc5539d127fad4df03b6215d9380f | 3,649,297 |
def extract_depth_map(frame):
"""
Extract front-view lidar camera projection for ground-truth depth maps
"""
(range_images, camera_projections, range_image_top_pose) = frame_utils.parse_range_image_and_camera_projection(frame)
for c in frame.context.camera_calibrations:
if dataset_pb2.CameraName.Name.Nam... | 2568d8563e256bde6c5df5c3bb34038b57993a1b | 3,649,298 |
from .functions import express
def cross(vect1, vect2):
"""
Returns cross product of two vectors.
Examples
========
>>> from sympy.vector import CoordSys3D
>>> from sympy.vector.vector import cross
>>> R = CoordSys3D('R')
>>> v1 = R.i + R.j + R.k
>>> v2 = R.x * R.i + R.y * R.j + ... | 8857f53a3db4066b2be6cd0fc3443b89a9c97022 | 3,649,299 |
def get_cognates(wordlist, ref):
"""
Retrieve cognate sets from a wordlist.
"""
etd = wordlist.get_etymdict(ref=ref)
cognates = {}
if ref == "cogids":
for cogid, idxs_ in etd.items():
idxs, count = {}, 0
for idx, language in zip(idxs_, wordlist.cols):
... | bf64ecb8f2182dba06f0b28b384c0e66ba78d49e | 3,649,300 |
def get_actress_string(_movie, s):
"""Return the string of the actress names as per the naming convention specified
Takes in the html contents to filter out the actress names"""
a_list = get_actress_from_html(_movie, s)
actress_string = ''
# if javlibrary returns no actresses then we'll just say wh... | bf9bd07bfc6c3e5bac87c52f4c6cba113a607b2d | 3,649,301 |
def get_lessons_of_day(day):
"""
Returns the lessons as a string for the given day webelement
:param day: day webelement
:return: dictionary with day as key and list with lessons as value
"""
day_lessons = []
to_iterate = day.find_elements_by_class_name('event-content')
to_iterate.reve... | 47b3ba18fd530ac8e724eb91e4b4d2886a008ac5 | 3,649,302 |
def ising_hamiltonian(n_qubits, g, h):
""" Construct the hamiltonian matrix of Ising model.
Args:
n_qubits: int, Number of qubits
g: float, Transverse magnetic field
h: float, Longitudinal magnetic field
"""
ham_matrix = 0
# Nearest-neighbor interaction
spin_coupling = ... | f485ac686001c0d9790276f19f5ba79b6de8db9c | 3,649,305 |
import shutil
def test_main(
mock_building_parser,
mock_return_logger,
config_dict,
db_connection,
monkeypatch,
test_dir,
):
"""Test main()"""
def mock_parser(*args, **kwargs):
parser = Namespace(
cache_dir=(test_dir / "test_outputs" / "test_outputs_uniprot"),
... | 5155b914d1f0320abc7991b7cc86e30664e75b53 | 3,649,306 |
def _slots_from_params(func):
"""List out slot names based on the names of parameters of func
Usage: __slots__ = _slots_from_signature(__init__)
"""
funcsig = signature(func)
slots = list(funcsig.parameters)
slots.remove('self')
return slots | fc55665a2bfa0ee27545734699f8527af5d57e6d | 3,649,307 |
import time
import requests
import re
def gnd_to_wd_id(gnd_id):
"""
Searches for a Wikidata entry which contains
the provided GND ID. Outputs the Wikidata ID (if found).
---------
gnd_id : str
GND ID of entity.
Returns
-----------
str.
"""
url = 'https://query.... | acf482aa05eac7c5307529643f30b7ef6880c55b | 3,649,308 |
from typing import Optional
def get_instance_category(entry) -> Optional[str]:
"""Determines the instance category for which the entry was submitted.
If it does not match the config of any instance category, returns None.
"""
instance_categories = RidehailEnv.DIMACS_CONFIGS.ALL_CONFIGS
... | ad1208f1bbc93b3579eb1e82f0752671d856f501 | 3,649,309 |
def extendheader(table, fields):
"""
Extend header row in the given table. E.g.::
>>> import petl as etl
>>> table1 = [['foo'],
... ['a', 1, True],
... ['b', 2, False]]
>>> table2 = etl.extendheader(table1, ['bar', 'baz'])
>>> table2
+... | 352fc187e5778f415221b73c179cff496da9b8a5 | 3,649,310 |
def get_teamcount():
"""Get a count of teams."""
#FINISHED FOR SASO
teamlist = get_list_of_teams()
return len(teamlist) | 512dd11ff27600d91a8e6ee461b3f1e761604734 | 3,649,311 |
def make_adjacencyW(I, D, sigma):
"""Create adjacency matrix with a Gaussian kernel.
Args:
I (numpy array): for each vertex the ids to its nnn linked vertices
+ first column of identity.
D (numpy array): for each data the l2 distances to its nnn linked vertices
... | 4e310c5677d66b7fef66db5f96eda1c9bf8efdc7 | 3,649,312 |
def blackbody2d(wavelengths, temperature):
"""
Planck function evaluated for a vector of wavelengths in units of meters
and temperature in units of Kelvin
Parameters
----------
wavelengths : `~numpy.ndarray`
Wavelength array in units of meters
temperature : `~numpy.ndarray`
... | 168c9e951350e3c93ef36cf95ec3e7a335d06102 | 3,649,313 |
def bookShop():
"""
Este programa resuelve el siguiente ejercicio: Book Shop
Link: https://cses.fi/problemset/task/1158
Este programa retorna el máximo número de páginas que se pueden conseguir
comprando libros dados el precio y páginas de los libros disponibles y la
cantidad de dinero disponible.
"""
... | 52f2b3ca84c7d6db529f51e2c05ad4767d4466c7 | 3,649,314 |
import mpmath
def pdf(x, nu, sigma):
"""
PDF for the Rice distribution.
"""
if x <= 0:
return mpmath.mp.zero
with mpmath.extradps(5):
x = mpmath.mpf(x)
nu = mpmath.mpf(nu)
sigma = mpmath.mpf(sigma)
sigma2 = sigma**2
p = ((x / sigma2) * mpmath.exp(-(x... | b2d96bc19fb61e5aaf542b916d06c11a0e3dea46 | 3,649,315 |
import typing
def get_310_prob(score_prob_dct: dict) -> typing.Dict[str, float]:
"""get home win, draw, away win prob"""
prob = {}
result_dct = get_score_pairs(0)
type_dict = ['home_win', 'draw', 'away_win']
for i in type_dict:
prob[i] = get_one_prob(score_prob_dct, result_dct, i)
s... | c003e75796b6f3e67d6558f59492a9db065c6a51 | 3,649,316 |
def load_project_data(storage):
"""Load project data using provided open_func and project directory."""
# Load items and extractors from project
schemas = storage.open('items.json')
extractors = storage.open('extractors.json')
# Load spiders and templates
spider_loader = SpiderLoader(storage)
... | c0f8e2b339a21bf4f73dcba098e992e550005098 | 3,649,317 |
import json
def home():
"""
Route to display home page and form to receive text from user for speech synthesis.
"""
form = TextToSpeechForm()
# Instantiates a client
client = texttospeech.TextToSpeechClient()
# Get the language list
voices = client.list_voices()
voice_codes_list ... | 626dc2cde1dc326034772acb8b87cb35621c3e3f | 3,649,318 |
def load_c6_file(filename, is_radar):
"""
Loads ice scattering LUTs from a file (based on Yang et al., JAS, 2013).
Parameters
----------
filename: str
The name of the file storing the Mie scattering parameters
is_radar: bool
If True, the first LUT column is treated as the freque... | c07256fde7ab5eac577caae2289a5d3d0dff583e | 3,649,319 |
import typing
import click
import copy
def gwrite(document: vp.Document, output: typing.TextIO, profile: str):
"""
Write gcode or other ascii files for the vpype pipeline.
The output format can be customized by the user heavily to an extent that you can also output most known
non-gcode ascii text fil... | d5a28fa7542db297d97c6252021bc4f103dea05d | 3,649,320 |
def user_int(arg):
"""
Convert a :class:`~int` to a `USER` instruction.
:param arg: Int that represents instruction arguments.
:return: Fully-qualified `USER` instruction.
"""
return str(arg) | df3f72eac3de12b4c8cbb1ccee5305dc43837bc3 | 3,649,322 |
def timezoneAdjuster(context, dt):
"""Convinience: new datetime with given timezone."""
newtz = ITimezoneFactory(context)
return dt.astimezone(newtz) | ba75bad6b8edfbc3198aad0adc0b1250626b9ce7 | 3,649,323 |
def make_adder(n):
"""Return a function that takes one argument k and returns k + n.
>>> add_three = make_adder(3)
>>> add_three(4)
7
"""
def adder(k):
return k + n
return adder | 64808cb857f7bd17c8c81bfd749ed96efcc88a9f | 3,649,324 |
def IsWritable(Feature):
"""IsWritable(Feature) -> Writable
Parameters:
Feature: str
Return value:
Writable: ctypes.c_int"""
if _at_camera_handle is not None:
return _at_core_lib.AT_IsWritable(_at_camera_handle, Feature) != AT_FALSE
else:
raise AndorError('Andor libr... | bfe4ff1b93595e8b8df11193e04e13b8bd6c39d9 | 3,649,325 |
import torch
from typing import Union
from typing import Tuple
def groupby_apply(
keys: torch.Tensor, values: torch.Tensor, bins: int = 95, reduction: str = "mean", return_histogram: bool = False
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""
Groupby apply for torch tensors
Args:
... | 711acc0cf2eb30e978f7f30686dbf67644d51fb0 | 3,649,326 |
def cube(x):
"""return x^3"""
return x*x*x | df9aa4330b7cfb1946b3c403935c864a2e7fae7a | 3,649,327 |
def get_candidados(vetor):
"""Retorna o dado dos candidatos"""
lista_retorno = []
for i in vetor:
lista_retorno.append(candidatos[int(i)])
return lista_retorno | 259b921db5d3840ea220b9690f4eca1b84c2d98d | 3,649,328 |
import copy
def get_fmin_tree(f_df, tree):
"""
"""
f = f_df[f_df['F4ratio']>=0].reset_index()
t = copy.deepcopy(tree)
i=0
for node in t.traverse():
if node.children:
l = node.children[0]
r = node.children[1]
lleaves = l.get_leaf_names()
... | 78da92675edfa2d8b9fd75591d104fbdb6adb369 | 3,649,329 |
def primes(n):
""" Returns a list of primes < n """
n = int(n)
sieve = [True] * n
for i in np.arange(3, n ** 0.5 + 1, 2, dtype=int):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
return [2] + [i for i in np.arange(3,n,2) if sieve[i]] | 91af8e025c688e3b09638c8f00ca67a358e7137d | 3,649,330 |
def H_TP(Z, T, P):
"""
Enthalpy defined by temperature and pressure (reference state at 300 K and 1 bar)
Z - array of molar composition
T, P - temperature and pressure
Units are specified above
"""
H = RP.ABFLSHdll('TP', T, P*100, Z, 2).h - RP.ABFLSHdll('TP', 300, 100, Z, 2).... | 36078f63478f7582e462f92d991a9941f07308c9 | 3,649,331 |
def test_fallback_round_with_input_n_not_int():
"""
Feature: JIT Fallback
Description: Test round() in graph mode with input x is not int.
Expectation: TypeError.
"""
@ms_function
def foo():
x = round(10.123, 1.0)
return x
with pytest.raises(TypeError) as ex:
foo(... | 3acef5aeaf1fdc40b66e0eede3f6df9d76bb5b9b | 3,649,333 |
def validate_netmask(s):
"""Validate that a dotted-quad ip address is a valid netmask.
>>> validate_netmask('0.0.0.0')
True
>>> validate_netmask('128.0.0.0')
True
>>> validate_netmask('255.0.0.0')
True
>>> validate_netmask('255.255.255.255')
True
>>> validate_netmask(BROADCAST)... | 9462f27dc53ad907c8b6ef99db7a09631ca7157b | 3,649,334 |
def translate():
"""
A handler for translating given english word which about digit to chinese
character
Return:
- `JSON`
.. code-block
# message = isError ? reason : "OK"
# output = isError ? '' : <TRANSLATION>
{
message: string,
output: str... | 5e40a724e6d183151f155ec3e951ec6098a92016 | 3,649,335 |
def create_matrix_sars_overlap_between_networks(networks_summary_df, networks_dict):
""" Creates matrix where element (i,j) quantifies the number of common SARS-Cov-2 partners in networks i and j
divided by the total number of SARS-Cov-2 partners in both networks
Args:
networks_summary_df: data... | 4b1d7c36e0781e7875f99cb7ac366ca3063cb77f | 3,649,336 |
from typing import Tuple
def load_forcings_gauge_metadata(path: str) -> Tuple[float, float, float]:
"""
Loads gauge metadata from the header of a CAMELS-USE forcings file.
Parameters
----------
path: str
Path to the forcings file.
Returns
-------
tuple
(gauge latitude... | c91c3bafb83709967d6dd480afd8e53ac9f94445 | 3,649,337 |
def transition(measure, N, **measure_args):
""" A, B transition matrices for different measures
measure: the type of measure
legt - Legendre (translated)
legs - Legendre (scaled)
glagt - generalized Laguerre (translated)
lagt, tlagt - previous versions of (tilted) Laguerre with slightly... | 8a701ace9b0d73e8f27062084dbf78711b8b4185 | 3,649,338 |
import numpy
import pandas
def interpolate_coord(df, xcol, ycol, step, distcol='d'):
"""
Interpolates x/y coordinates along a line at a fixed distance.
Parameters
----------
df : pandas.DataFrame
xcol, ycol : str
Labels of the columns in ``df`` containing the x- and y-coords,
... | 6ac736a4f82ffd7c0b3b45027bf7ab17b5d7d71c | 3,649,339 |
def oven_cook_setting_to_str(cook_setting: OvenCookSetting, units: str) -> str:
"""Format OvenCookSetting values nicely."""
cook_mode = cook_setting.cook_mode
cook_state = cook_mode.oven_state
temperature = cook_setting.temperature
modifiers = []
if cook_mode.timed:
modifiers.append(STA... | 02d339b82c8dbfb34f4bb6cc968fee83496df04e | 3,649,340 |
def print_location(location: Location) -> str:
"""Render a helpful description of the location in the GraphQL Source document."""
return print_source_location(
location.source, get_location(location.source, location.start)
) | 2c6f0f5e475fdbb14060b55f5698a2548720cc01 | 3,649,341 |
def run_metrics(ground_truth, simulation, measurement_name,users=None,repos=None):
"""
Run all of the assigned metrics for a given measurement.
Inputs:
ground_truth - DataFrame of ground truth data
simulation - DataFrame of simulated data
measurement_name - Name of measurement corresponding to... | 733a04165853cb76f84bd15ff8f38585224ec039 | 3,649,342 |
def checkTrue(comment,res,update=True):
"""
This method is a pass-through for consistency and updating
@ In, comment, string, a comment printed out if it fails
@ In, res, bool, the tested value
@ In, update, bool, optional, if False then don't update results counter
@ Out, res, bool, True if test
... | 4f8c0cf99921477e7187178d5576f2df03881417 | 3,649,343 |
def compute_votes(
candidates,
voters,
voter_id,
node_degree_normalization,
):
"""Comptue neighbor voting for a given set of candidates and voters
Arguments:
candidates {np.ndarray} -- genes x cells normalized expression for candidates
voters {np.ndarray} -- genes x cells norma... | a04e4030b01d1188830a1ad2f55419d732afa432 | 3,649,344 |
def _precompute_cache(x, y, num_classes):
"""Cache quantities to speed-up the computation of L2-regularized least-sq."""
# Whiten
mean = jnp.mean(x, axis=0, keepdims=True)
std = jnp.std(x, axis=0, keepdims=True) + 1e-5
x = (x - mean) / std
# Add a constant feature for the bias, large so it's almost unregul... | b357620b7f2883182a33f040b2f7d82e0205bcaa | 3,649,346 |
def show_user():
"""Return page showing details: walks, landmarks rated, scores."""
user = User.query.filter_by(user_id=session.get('user_id')).first()
ratings = user.ratings
# import pdb; pdb.set_trace()
walks = user.walks
# for walk in walks:
# origin = Landmark.query.filter(La... | ddcfed7ac98576cd6273bef5937f1ffbc4e3ecb9 | 3,649,347 |
def DesignCustomSineWave(family_list, how_many_gen, amp, per, shift_h, shift_v,
show=False, print_phase_mse=False, return_phases=False):
""" "Grid Search" Approach:
Create sine waves with unknown amp, per, shift_h and shift_v in combinatorial manner
and align famili... | 5905a25b5be585303f5dbeaf42174a2a7be4879e | 3,649,348 |
def get_environment_names():
"""Return a list of defined environment names, with user preference first."""
envlist = [r[0] for r in _session.query(models.Environment.name).order_by(models.Environment.name).all()]
# move user preference to top of list
userenvname = _config.userconfig.get("environmentnam... | 0348738aa0bf3ea2df3783e2308b185e95292215 | 3,649,350 |
def plot(direction, speed, **kwargs):
"""Create a WindrosePlot, add bars and other standard things.
Args:
direction (pint.Quantity): wind direction from North.
speed (pint.Quantity): wind speeds with units attached.
**bins (pint.Quantity): wind speed bins to produce the histogram for.
... | f5020da6946b0242bea826d166bb32b83547bc40 | 3,649,351 |
def convert_floor(node, **kwargs):
"""Map MXNet's floor operator attributes to onnx's Floor operator
and return the created node.
"""
return create_basic_op_node('Floor', node, kwargs) | 476ff140cde55db2d489b745a08a7257576e3209 | 3,649,352 |
async def get_qrcode_login_info():
"""获取二维码登录信息"""
url = f"{BASE_URL}qrcode/auth_code"
return await post(url, reqtype="app") | 93f131cdfcf6cd7b18d126cd32c7836e10a67870 | 3,649,353 |
def get_global_free_state(self):
"""
Recurse get_global_free_state on all child parameters, and hstack them.
Return: Stacked np-array for all Param except for LocalParam
"""
# check if the child has 'get_local_free_state' method
for p in self.sorted_params:
if isinstance(p, (param.Param,... | 29c2a397261dddb92b718a57ba4ec3747d1ce661 | 3,649,354 |
def case_activity_update_type():
""" Case Activity Update Types: RESTful CRUD Controller """
return crud_controller() | 4722001b25857bd56d1470334551c8bbe085f18e | 3,649,355 |
def dftregistration(buf1ft,buf2ft,usfac=100):
"""
# function [output Greg] = dftregistration(buf1ft,buf2ft,usfac);
# Efficient subpixel image registration by crosscorrelation. This code
# gives the same precision as the FFT upsampled cross correlation in a
# small fraction of the computat... | 1cd8cd37efebea29da1086b998e98a334697e2d4 | 3,649,356 |
def parametrize_simulations(args):
"""Parametrize simulations"""
if args.type == INSTANCE_COUNTS:
return instance_count_sims(args)
if args.type == FEATURE_COUNTS:
return feature_count_sims(args)
if args.type == NOISE_LEVELS:
return noise_level_sims(args)
if args.type == SHUFF... | ad592e64cbf7fa8ae79ccb753a1fd87db85e1f11 | 3,649,357 |
from typing import Union
def connect(base_url: Union[str, URL], database_id: int = DJ_DATABASE_ID) -> Connection:
"""
Create a connection to the database.
"""
if not isinstance(base_url, URL):
base_url = URL(base_url)
return Connection(base_url, database_id) | aac724326f0f6e487caf8d614265c8028bae4e79 | 3,649,358 |
def micore_tf_deps():
"""Dependencies for Tensorflow builds.
Returns:
list of dependencies which must be used by each cc_library
which refers to Tensorflow. Enables the library to compile both for
Android and for Linux. Use this macro instead of directly
declaring dependencies on Tensor... | b4c8786df978a536f1adf1384209f0a0b663c100 | 3,649,359 |
def de_bruijn(k, n):
"""
de Bruijn sequence for alphabet k
and subsequences of length n.
"""
try:
# let's see if k can be cast to an integer;
# if so, make our alphabet a list
_ = int(k)
alphabet = list(map(str, range(k)))
except (ValueError, TypeError):
... | 7e39d51bccbbb42bdda0594fa8c7077d4f2af1a1 | 3,649,360 |
def append_artist(songs, artist):
"""
When the songs gathered from the description just contains the
titles of the songs usually means it's an artist's album.
If an artist was provided appends the song title to the artist
using a hyphen (artist - song)
:param list songs: List of song titles (onl... | b3fbda311849f68ab01c2069f44ea0f694365270 | 3,649,361 |
def pose2pandas(pose: pyrosetta.Pose, scorefxn: pyrosetta.ScoreFunction) -> pd.DataFrame:
"""
Return a pandas dataframe from the scores of the pose
:param pose:
:return:
"""
pose.energies().clear_energies()
scorefxn.weights() # neccessary?
emopts = pyrosetta.rosetta.core.scoring.methods... | 71c3342f86138f28411302da271ca0fb252727d2 | 3,649,362 |
def rantest(seed,N=100):
"""get some random numbers"""
buff = np.zeros(N,dtype=np.double)
ct_buff = buff.ctypes.data_as(ct.POINTER(ct.c_double))
sim.rantest(seed,N,ct_buff)
return buff | 4764968f8b0c46ab58b0b2710f4a0764a417f51c | 3,649,363 |
def tf_efficientnet_b0_ap(pretrained=False, **kwargs):
""" EfficientNet-B0 AdvProp. Tensorflow compatible variant """
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet(
'tf_efficientnet_b0_ap', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pre... | 4cbd2d791301c4001f9bd07da0357550ea93f585 | 3,649,364 |
import torch
def pi_del(
shape,
y_tgt_star,
pad_symbol=0,
plh_symbol=0,
bos_symbol=0,
eos_symbol=0,
Kmax=100,
device="cpu",
):
"""Operations and states to edit a partially deleted version of y_star back to y_star."""
# shape = B x N x M
# y_tgt_star : B x M
shape = list... | edbd9c40de5b8d5639bfa382d90071e7405aa062 | 3,649,365 |
from typing import Dict
from typing import Any
import logging
def create_service_account(project_id: str, service_account_name: str,
role_name: str, file_name: str) -> Dict[str, Any]:
"""Create a new service account.
Args:
project_id: GCP project id.
service_account_name: The s... | 48bcd081cef0eb76be5412febb76e05266a12968 | 3,649,366 |
def test_ode_FE():
"""Test that a linear u(t)=a*t+b is exactly reproduced."""
def exact_solution(t):
return a*t + b
def f(u, t): # ODE
return a + (u - exact_solution(t))**m
a = 4
b = -1
m = 6
dt = 0.5
T = 20.0
u, t = ode_FE(f, exact_solution(0), dt, T)
diff ... | 992aaf22b89a235b7ab5505225a8f3ff4f34ae10 | 3,649,367 |
def file_finder():
"""
This function allows to the user
to select a file using the dialog with tkinter.
:return path_name
:rtype str
the string of the path_name file.
"""
root = Tk()
root.title("File Finder")
root.geometry("500x400")
root.attributes("-topmost", ... | 2da5df55010e8edbd5975fe527ad4780ce6e69e9 | 3,649,368 |
def htm_search_cone(IndexFile_data,Long,Lat,Radius,Ind=None,Son_index=np.arange(2,6),PolesLong_index=np.arange(6,11,2),PolesLat_index=np.arange(7,12,2)):
#print('I am running htm_search_cone')
"""Description: Search for all HTM leafs intersecting a small circles
Input :-Either a table of HTM data or an... | 2b202f943264cc979c4271c41fca2386a3b2b14f | 3,649,369 |
def get_missing_columns(missing_data):
"""
Returns columns names as list that containes missing data
:param
missing_data : return of missing_data(df)
:return
list: list containing columns with missing data
"""
missing_data = missing_data[missing_data['percent'] > 0]
missing_... | 80feccec6148a417b89fb84f4c412d9ea4d0dd37 | 3,649,372 |
def read(request):
"""Render the page for a group."""
pubid = request.matchdict["pubid"]
slug = request.matchdict.get("slug")
group = models.Group.get_by_pubid(pubid)
if group is None:
raise exc.HTTPNotFound()
if slug is None or slug != group.slug:
url = request.route_url('grou... | 8376c94a4ffe6569cd7531d18427fbfd57629031 | 3,649,373 |
import time
import copy
import tqdm
import torch
from typing import OrderedDict
def train_model(
model,
device,
train_data_loader,
valid_data_loader,
criterion, optimizer, scheduler, num_epochs=5):
"""
training
Parameters
--------------
model : DogClassificationModel
... | c12929a8aec02031f8d293f5347beaeb5dc6d759 | 3,649,374 |
from src.dialogue_system.agent.agent_with_goal_3 import AgentWithGoal as AgentWithGoal3
import json
import time
import pickle
def run(parameter):
"""
The entry function of this code.
Args:
parameter: the super-parameter
"""
print(json.dumps(parameter, indent=2))
time.sleep(2)
slo... | 75e9fd2204e2e3e0aa7101e9656c23617fb56099 | 3,649,375 |
from typing import Iterable
def convert(
value: str,
conversion_recipes: Iterable[ConversionRecipe[ConvertResultType]]) -> ConvertResultType:
"""
Given a string value and a series of conversion recipes, attempt to convert the value using the
recipes.
If none of the recipes declare the... | a6f1162f4069a3846636ad95cecde0b3ba3601a8 | 3,649,376 |
def get_function_name(fcn):
"""Returns the fully-qualified function name for the given function.
Args:
fcn: a function
Returns:
the fully-qualified function name string, such as
"eta.core.utils.function_name"
"""
return fcn.__module__ + "." + fcn.__name__ | ae186415225bd5420de7f7b3aef98480d30d59f8 | 3,649,377 |
def clean_cases(text):
"""
Makes text all lowercase.
:param text: the text to be converted to all lowercase.
:type: str
:return: lowercase text
:type: str
"""
return text.lower() | 9b0c931336dbf762e5e3a18d103706ddf1e7c14f | 3,649,378 |
def root():
"""Refreshes data in database"""
db.drop_all()
db.create_all()
# Get data from api, make objects with it, and add to db
for row in df.index:
db_comment = Comment(user=df.User[row],text=df.Text[row]) # rating = df.Rating[row]
db.session.add(db_comment)
db.sessi... | 0731926301cd981cc9278964cb313a35bcfb4f43 | 3,649,379 |
def bond_value_to_description(value):
"""bond_value_to_description(value) -> string
Convert from a bond type string into its text description,
separated by "|"s. The result are compatible with
OEGetFPBontType and are in canonical order.
"""
return _get_type_description("bond", _btype_flags, val... | 2eeb333334740ed9cdad28b43742c7a2274885bc | 3,649,381 |
def read_set_from_file(filename):
"""
Extract a de-duped collection (set) of text from a file.
Expected file format is one item per line.
"""
collection = set()
with open(filename, 'r', encoding='utf-8') as file_:
for line in file_:
collection.add(line.rstrip())
return c... | ba71ed4fb6e85cf5156d35a85245058bb3711f9b | 3,649,382 |
def filter_0_alleles(allele_df, allele_num=2):
"""Drop alleles that do not appear in any of the strains.
"""
drop_cols = []
for col in allele_df.columns:
if allele_df[col].sum()<allele_num:
drop_cols.append(col)
allele_df.drop(drop_cols, inplace=True, axis=1)
return allele_df | 9b76152d6e6fc200c2d80d4721122d3958642286 | 3,649,383 |
def gradient_of_rmse(y_hat, y, Xn):
"""
Returns the gradient of the Root Mean Square error with respect to the
parameters of the linear model that generated the prediction `y_hat'.
Hence, y_hat should have been generated by a linear process of the form
Xn.T.dot(theta)
Args:
y... | 73a46197f90cf1b9c0a90a8ce2d2eae006c6d002 | 3,649,384 |
def is_commit_in_public_upstream(revision: str, public_upstream_branch: str, source_dir: str):
"""
Determine if the public upstream branch includes the specified commit.
:param revision: Git commit hash or reference
:param public_upstream_branch: Git branch of the public upstream source
:param sour... | 6f7259f8e3a1893a7fbd41914df37e42fed73c7b | 3,649,385 |
def align_down(x: int, align: int) -> int:
"""
Align integer down.
:return:
``y`` such that ``y % align == 0`` and ``y <= x`` and ``(x - y) < align``
"""
return x - (x % align) | 8144309badf601999f4c291ee3af5cfbd18397ea | 3,649,386 |
def null():
"""return an empty bit buffer"""
return bits() | 53b7e87648c33ab1072651ee6ef6bfb3fe92da8d | 3,649,388 |
def find_coherent_patch(correlations, window=11):
"""Looks through 3d stack of correlation layers and finds strongest correlation patch
Also accepts a 2D array of the pre-compute means of the 3D stack.
Uses a window of size (window x window), finds the largest average patch
Args:
correlations ... | 27bc06ec5e73d854c094f909fdf507fad38168f3 | 3,649,389 |
def test():
"""HI :)"""
return 'Hi!' | 626b2ffcfc3f60dcd5456efa2d61a3ed18d428d8 | 3,649,390 |
def get_vdfdx(stuff_for_time_loop, vdfdx_implementation="exponential"):
"""
This function enables VlaPy to choose the implementation of the vdfdx stepper
to use in the lower level sections of the simulation
:param stuff_for_time_loop: (dictionary) contains the derived parameters for the simulation
... | 538548a2d2d39b83ad74ac052c3c1a51895357d2 | 3,649,392 |
def worker(args):
"""
1. Create the envelope request object
2. Send the envelope
"""
envelope_args = args["envelope_args"]
# 1. Create the envelope request object
envelope_definition = make_envelope(envelope_args)
# 2. call Envelopes::create API method
# Exceptions will be caught by... | 79891142b34da8d9d5aacc4d55ab7f65198a4116 | 3,649,393 |
import glob
import csv
def write_colocated_data_time_avg(coloc_data, fname):
"""
Writes the time averaged data of gates colocated with two radars
Parameters
----------
coloc_data : dict
dictionary containing the colocated data parameters
fname : str
file name where to store th... | 2e786c6df8a617f187a7b50467111785342310c5 | 3,649,394 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.