content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_app_version_info(domain, build_id, xform_version, xform_metadata):
"""
there are a bunch of unreliable places to look for a build version
this abstracts that out
"""
appversion_text = get_meta_appversion_text(xform_metadata)
commcare_version = get_commcare_version_from_appversion_text(a... | 5,317,200 |
def plot_components_plotly(
m, fcst, uncertainty=True, plot_cap=True, figsize=(900, 200)):
"""Plot the Prophet forecast components using Plotly.
See plot_plotly() for Plotly setup instructions
Will plot whichever are available of: trend, holidays, weekly
seasonality, yearly seasonality, and add... | 5,317,201 |
def _format_as_geojson(results, geodata_model):
"""joins the results to the corresponding geojson via the Django model.
:param results: [description]
:type results: [type]
:param geodata_model: [description]
:type geodata_model: [type]
:return: [description]
:rtype: [type]
"""
# re... | 5,317,202 |
def ProduceNoiseTriggers(tray, name, gcd_file, nevents=1, run_id=None):
"""
ProduceNoiseTriggers: Create events containing only noise and no simulated particle interactions. These
are needed for low-energy DeepCore and PINGU simulation due to a lower detector threshold. There
are some nuances to this. A... | 5,317,203 |
def crosscorr(dfA, dfB, method='pearson', minN=0, adjMethod='fdr_bh'):
"""Pairwise correlations between A and B after a join,
when there are potential column name overlaps.
Parameters
----------
dfA,dfB : pd.DataFrame [samples, variables]
DataFrames for correlation assessment (Nans will be ... | 5,317,204 |
def county_transient(year, county_transient_controls, buildings, households, transient_pph):
"""
Allocate transient households and population using county-level controls.
"""
run_transient_in_hotels(
year, county_transient_controls, buildings, transient_pph)
run_transient_in_hh(
yea... | 5,317,205 |
def main(corpus_triplets_file, qa_graph_path, prediction_file, stem):
"""
1. Create Corpus Graph given its openie triplets in the stanford openIE format in the file "CORPUS_TRIPLETS_FILE".\n
2. Load the qa graph pickle dump located @PATH\n
3. Calculate Scores for each option for each graph.\n
4. Pre... | 5,317,206 |
def normalize_gradient(netC, x):
"""
f
f_hat = --------------------
|| grad_f || + | f |
x: real_data_v
f: C_real before mean
"""
x.requires_grad_(True)
f = netC(x)
grad = torch.autograd.grad(
f, [x], torch.ones_like(f), create_graph=True, re... | 5,317,207 |
def get_path_with_arch(platform, path):
"""
Distribute packages into folders according to the platform.
"""
# Change the platform name into correct formats
platform = platform.replace('_', '-')
platform = platform.replace('x86-64', 'x86_64')
platform = platform.replace('manylinux1', 'linux'... | 5,317,208 |
def _impl_ufunc_logical_and(x1, x2):
"""
Computes the logical AND for each element x1_i of the input array x1 with the respective
element x2_i of the input array x2.
"""
pass | 5,317,209 |
def compile_snippet(tmpl, **kwargs):
"""
Compiles selected snipped with jinja2
:param tmpl: snippet name
:param kwargs: arguments passed to context
:return: generated HTML
"""
def wrapper(val):
import numbers
if isinstance(val, numbers.Number):
return val
... | 5,317,210 |
def not_none(t: Optional[T], default: T):
"""
Returns `t` if not None, else `default`.
:param t: the value to return if not None
:param default: the default value to return
:return: t if not None, else default
"""
return t if t is not None else default | 5,317,211 |
def fallback_feature(func):
"""Decorator to fallback to `batch_feature` in FeatureModule
"""
def wrapper(self, *args, **kwargs):
if self.features is not None:
ids = args[0] if len(args) > 0 else kwargs['batch_ids']
return FeatureModule.batch_feature(self, batch_ids=ids)
... | 5,317,212 |
def extract_segment_features(y, sr):
"""
Extract audio features from a segment of audio using librosa.
Input: An array of a audiofile.
Output: Dictionary of segments with keys:
tempo, beats, chroma_stft, rms, spec_cent, spec_bw, rolloff, zcr,
and mfcc values from 1-12.
"""
tem... | 5,317,213 |
async def submit_mod_log(ctx: ChromeyContext, db_guild: Guild, user: Union[discord.Member, discord.User], log):
"""Submits a public log
Parameters
----------
ctx : ChromeyContext
"Bot context"
user : discord.Member
"User to notify"
db_user
"User DB"
db_guild
... | 5,317,214 |
def find_info_by_ep(ep):
""" 通过请求的endpoint寻找路由函数的meta信息"""
return manager.find_info_by_ep(ep) | 5,317,215 |
def setup_logger(outdir='.', label=None, log_level='INFO', print_version=False):
""" Setup logging output: call at the start of the script to use
Parameters
==========
outdir, label: str
If supplied, write the logging output to outdir/label.log
log_level: str, optional
['debug', 'in... | 5,317,216 |
def obtener_cantidad_total_turistas_entrantes_en_ciudad_anio(Ciudad, Anio):
"""
Dado una ciudad y un año obtiene la cantidad total de personas que llegan a esa ciudad de forma total
Dado una ciudad y un año obtiene la cantidad total de personas que llegan a esa ciudad de forma total
:param Ciudad: Ciuda... | 5,317,217 |
def update_from_file(params, par_file):
"""Update the config dictionary params from file.
Args:
params (dict):
Dictionary holding the to-be-updated values.
par_file (str):
Name of the parameter file with the update values.
Returns:
params (dict):
... | 5,317,218 |
def test_ip_command_invalid_ip_address(client):
"""
When user add invalid IP Address then it should raise ValueError with valid response
"""
from GoogleChronicleBackstory import ip_command
expected_message = 'Invalid IP - string'
with pytest.raises(ValueError) as error:
ip_command(clien... | 5,317,219 |
def accumulated_other_comprehensive_income(ticker, frequency):
"""
:param ticker: e.g., 'AAPL' or MULTIPLE SECURITIES
:param frequency: 'A' or 'Q' for annual or quarterly, respectively
:return: obvious..
"""
df = financials_download(ticker, 'bs', frequency)
return (df.loc['Accumulated other ... | 5,317,220 |
def sigint_handler(signum, frame):
"""Handels program exit with Ctrl+C"""
global EXIT
if EXIT:
sys.exit()
else:
print("\nPress CTRL+C again, to exit")
EXIT = True | 5,317,221 |
def PDifHist (inPixHistFDR):
""" Return the differential pixel histogram
returns differential pixel histogram
inPixHistFDR = Python PixHistFDR object
"""
################################################################
# Checks
if not PIsA(inPixHistFDR):
raise TypeError("inPixHist... | 5,317,222 |
def menu():
"""Функция, реализующая меню"""
print('Приветствую в программе, реализующей метод Ньютона!', '\n')
while True:
print('Меню:', '\n',
'Выберете цифру интересующего вас варианта.', '\n',
'1. Запуск программы', '\n',
'2. Тестовый запуск', '\n',
... | 5,317,223 |
def SendToRietveld(request_path, payload=None,
content_type="application/octet-stream", timeout=None):
"""Send a POST/GET to Rietveld. Returns the response body."""
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = upload.GetEmail()
password = getp... | 5,317,224 |
def setup_five_spotish(plot=False, sim_ws="fivespot", simple_pattern=False, eff1=0.75, eff2=0.95,
balance_inout=False, nlay=NLAY, simple_eff=False, ghb_source=False, simple_hk=True,
shared_inj=False):
"""create and run a separate flow and tranport sim with
multiple int... | 5,317,225 |
def _parse_args():
"""
For parsing args when run as __main__.
"""
parser = ArgumentParser(description='Simulates the action of a Turing Machine.')
parser.add_argument('path', help="Path of a file containing rule quintuples.")
parser.add_argument('input', help="Input string.")
parser.add_argument('--rules', ac... | 5,317,226 |
def join_2_steps(boundaries, arguments):
"""
Joins the tags for argument boundaries and classification accordingly.
"""
answer = []
for pred_boundaries, pred_arguments in zip(boundaries, arguments):
cur_arg = ''
pred_answer = []
for boundary_tag in pred_boundari... | 5,317,227 |
def qac_image(image, idict=None, merge=True):
""" save a QAC dictionary, optionally merge it with an old one
return the new dictionary.
This dictionary is stored in a casa sub-table called "QAC"
image: input image
idict: new or updated dictionary. If blank, it return QAC
... | 5,317,228 |
def get_random_useragent():
"""生成随机的UserAgent
:return: UserAgent字符串
"""
return random.choice(USER_AGENTS) | 5,317,229 |
def product_detail_view(request, pk='', **kwargs):
"""
Display a detailed view of a product, showing all specifications
"""
ctxt = {'pk': pk}
# Empty (thus invalid) pk
if pk == '':
return client_error_view(request, ERROR_MSG['wrong_prod_pk'].format(pk), 404)
matching_products = Product.objects.filter(pk=pk... | 5,317,230 |
def print_dict(dic, key=lambda x: x, val=lambda x: x,
num=None, cmp=cmp, order=None, reverse=False,
spacing=4, out=sys.stdout,
format=default_format,
justify=default_justify):
"""Print a dictionary in two columns."""
if num is None:
num = len(... | 5,317,231 |
def main():
"""
Main program
"""
args = init_args()
primers = import_bed_file(bed=args.file)
primer_dict = dict()
tempdir = tempfile.mkdtemp(dir='.', prefix='tmp')
for primer in primers:
add_primer(primers=primer_dict, primer=primer, idloc=args.idloc)
amplicons = list()
i... | 5,317,232 |
def _convert_velocities(
velocities: np.ndarray, lattice_matrix: np.ndarray
) -> np.ndarray:
"""Convert velocities from atomic units to cm/s.
Args:
velocities: The velocities in atomic units.
lattice_matrix: The lattice matrix in Angstrom.
Returns:
The velocities in cm/s.
"... | 5,317,233 |
def update_moderation_message(page, message):
"""This is bit special.. It updates last page state made from current user
for given page. Its called after page is saved - page state is created when
page gets saved (in signal), so this might have a concurrency issue, but
probably will work in 99,999%.
... | 5,317,234 |
def is_regular_file(element):
"""
Return True if the given element is a regular file.
It accepts input as :py:mod:`file`, :py:mod:`str` or :py:mod:`int`.
"""
if type(element) is file:
fstat = os.fstat(element.fileno())
elif type(element) is str:
fstat = os.stat(element)
elif... | 5,317,235 |
def unit_vector(vec1, vec2):
""" Return a unit vector pointing from vec1 to vec2 """
diff_vector = map(operator.sub, vec2, vec1)
scale_factor = math.sqrt( sum( map( lambda x: x**2, diff_vector ) ) )
if scale_factor == 0:
scale_factor = 1 # We don't have an actual vector, it has zero length
... | 5,317,236 |
def shuffle_list(gene_list, rand=np.random.RandomState(0)):
"""Returns a copy of a shuffled input gene_list.
:param gene_list: rank_metric['gene_name'].values
:param rand: random seed. Use random.Random(0) if you like.
:return: a ranodm shuffled list.
"""
l2 = gene_list.copy()
rand... | 5,317,237 |
def my_map(f, lst):
"""this does something to every object in a list"""
if(lst == []):
return []
return [f(lst[0])] + my_map(f, lst[1:]) | 5,317,238 |
def plot_avg_diff(colours, markers, fig_idx, fig_size, plotnames,
means, plot_title):
"""
Plot comparison between average difference in parameter estimates
across methods
Args:
colours: Line colours
markers: Line markers
fig_idx: Figure number
fig_size: Figure size
... | 5,317,239 |
def read_ipv6(d):
"""Read an IPv6 address from the given file descriptor."""
u, l = struct.unpack('>QQ', d)
return ipaddress.IPv6Address((u << 64) + l) | 5,317,240 |
def normalizeRounding(value):
"""
Normalizes rounding.
Python 2 and Python 3 handing the rounding of halves (0.5, 1.5, etc)
differently. This normalizes rounding to be the same (Python 3 style)
in both environments.
* **value** must be an :ref:`type-int-float`
* Returned value is a ``int``... | 5,317,241 |
def pin_light(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Combines lighten and darken blends.
:param a: The existing values. This is like the bottom layer in
a photo editing tool.
:param b: The values to blend. This is like the top layer in a
photo editing tool.
:param colorize: (Op... | 5,317,242 |
def sun():
"""Get Sun data source"""
filename = (
Path(nowcasting_dataset.__file__).parent.parent / "tests" / "data" / "sun" / "test.zarr"
)
return SunDataSource(
zarr_path=filename,
history_minutes=30,
forecast_minutes=60,
) | 5,317,243 |
def generate_level08():
"""Generate the bricks."""
bricks = bytearray(8 * 5 * 3)
colors = [2, 0, 1, 3, 4]
index = 0
col_x = 0
for x in range(6, 111, 26):
for y in range(27, 77, 7):
bricks[index] = x
bricks[index + 1] = y
bricks[index + 2] = colors[col_... | 5,317,244 |
def jwt_decode_token(token):
"""Register jwt decode handler
:param token:
"""
return jwt_lib.decode(token, current_app.config['JWT_SECRET_KEY'],
algorithms=current_app.config['JWT_ALGORITHMS']) | 5,317,245 |
def renormalize_vector(a, scalar):
"""This function is used to renormalise a 3-vector quantity.
Parameters
----------
a: np.ndarray
The 3-vector to renormalise.
scalar: Union[float, int]
The desired length of the renormalised 3-vector.
Returns
-------
a: np.ndarray
... | 5,317,246 |
def test_manager_get_queryset():
"""Test the get queryset method returns a query."""
GlobalPermission.objects.create(
name="Can View User Data", codename="view_user_data"
)
global_permissions = GlobalPermission.objects.first()
assert global_permissions.name == "Can View User Data" | 5,317,247 |
def load_data(path='affnist.npz'):
"""Loads the affnist dataset.
x_train: centered MNIST digits on a 40x40 black background
x_test: official affNIST test dataset (MNIST digits with random affine transformation)
# Arguments
path: path where to cache the dataset locally
(relative to ... | 5,317,248 |
def as_register_event_listener(
callback: EventCallback[RegisterEventEvent[T]]
) -> ListenerSetup[RegisterEventEvent[T]]:
"""A ListenerRegistraror type"""
return (EVENT_ID_REGISTER_EVENT, callback,) | 5,317,249 |
def MarkFlowAsFailed(client_id: str,
flow_id: str,
error_message: Optional[str] = None) -> None:
"""Marks the given flow as finished without executing it."""
flow_obj = data_store.REL_DB.ReadFlowObject(client_id, flow_id)
flow_obj.flow_state = flow_obj.FlowState.ERROR
i... | 5,317,250 |
def read_frame(frame_dir, model_name, scale_size=[480]):
"""
read a single frame & preprocess
"""
cv2_models = ['dino.vit', 'dino.conv', 'deit', 'mlp_mixer', 'resnet50', 'resnet152', 'resnet200', 'resnext', 'beit']
if model_name in cv2_models:
img = cv2.imread(frame_dir)
ori_h, ori_w, _ = img.shape
else:
... | 5,317,251 |
def gen_undirected_graph(nodes = 1000, edge_factor = 2, costs = (1,1)):
"""
generates an undicrected graph with `nodes` nodes and around `edge_factor` edges per node
@param nodes amount of nodes
@param edge_factor approximate edges per node, might happen that some nodes have more edges
@param ... | 5,317,252 |
def user_prompt(
question_str, response_set=None, ok_response_str="y", cancel_response_str="f"
):
"""``input()`` function that accesses the stdin and stdout file descriptors
directly.
For prompting for user input under ``pytest`` ``--capture=sys`` and
``--capture=no``. Does not work with ``--captur... | 5,317,253 |
def train_logistic_regression_clf(training_set, testing_set):
"""
accuracy: 74.59
"""
logistic_regression_classifier = SklearnClassifier(LogisticRegression())
logistic_regression_classifier.train(training_set)
print('Logistic Regression Classifier accuracy:',
(classify.accuracy(logisti... | 5,317,254 |
def compute_lpips(image1, image2, model):
"""Compute the LPIPS metric."""
# The LPIPS model expects a batch dimension.
return model(
tf.convert_to_tensor(image1[None, Ellipsis]),
tf.convert_to_tensor(image2[None, Ellipsis]))[0] | 5,317,255 |
def _recover(word: Word):
"""
recover wide char quotations
Args:
word: Word object
"""
word_quots = [_ for _ in word.raw if _ in _QUOT_NORM]
morph_quots = []
for idx, morph in enumerate(word.morphs):
if morph.tag != 'SS' or morph.lex not in _QUOT_NORM:
continue
... | 5,317,256 |
def int2bin(n, count=16):
"""
this method converts integer numbers to binary numbers
@param n: the number to be converted
@param count: the number of binary digits
"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) | 5,317,257 |
def _download_userconfig_file():
"""ユーザー名とメールアドレスをマッピングしたファイルを/tmpにダウンロード
Ref: https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/limits.html
"""
if not os.path.isdir("/tmp/config"):
os.makedirs("/tmp/config")
try:
s3 = boto3.resource("s3")
bucket = s3.Bucket(settings.S3_BUC... | 5,317,258 |
def conv1x1(in_planes, out_planes, stride=1, groups=1, bias=False):
"""2D 1x1 convolution.
Args:
in_planes (int): number of input channels.
out_planes (int): number of output channels.
stride (int): stride of the operation.
groups (int): number of groups in the operation.
bias (boo... | 5,317,259 |
def _get_preprocessing_functions(
train_client_spec: client_spec.ClientSpec,
eval_client_spec: client_spec.ClientSpec,
emnist_task: str) -> Tuple[_PreprocessFn, _PreprocessFn]:
"""Creates train and eval preprocessing functions for an EMNIST task."""
train_preprocess_fn = emnist_preprocessing.create_prep... | 5,317,260 |
def intstr(num, numplaces=4):
"""A simple function to map an input number into a string padded with
zeros (default 4). Syntax is: out = intstr(6, numplaces=4) -->
0006
2008-05-27 17:12 IJC: Created"""
formatstr = "%(#)0"+str(numplaces)+"d"
return formatstr % {"#":int(num)} | 5,317,261 |
def vehiclesHistoryDF(
token="", version="stable", filter="", format="json", **timeseries_kwargs
):
"""Economic data
https://iexcloud.io/docs/api/#economic-data
Args:
token (str): Access token
version (str): API version
filter (str): filters: https://iexcloud.io/docs/api/#filte... | 5,317,262 |
def fit(history, scale_start=None, decay_start=None, n_start=None,
scale_decay_fixed=False):
"""
Parameters
----------
history : np.array
1-dimensional array containing the event times in ascending order.
scale_start : float
Starting value for the likelihood optimization.
... | 5,317,263 |
def p_createopts_function_params(t):
"""
createOpts : R_FUNCTION ID S_PARIZQ typeParamsList S_PARDER R_RETURNS types R_AS S_DOBLEDOLAR codeBlock S_PUNTOCOMA S_DOBLEDOLAR R_LANGUAGE R_PLPGSQL
"""
t[0] = Function(t[2],t[7],t[4],t[10], t.slice[2].lineno, t.slice[2].lexpos)
t[0].execute(None)
global... | 5,317,264 |
def from_raw(raw_segment):
"""
Parse a new segment from a raw segment_changes response.
:param raw_segment: Segment parsed from segment changes response.
:type raw_segment: dict
:return: New segment model object
:rtype: splitio.models.segment.Segment
"""
keys = set(raw_segment['added']... | 5,317,265 |
def _max_mask_non_finite(x, axis=-1, keepdims=False, mask=0):
"""Returns `max` or `mask` if `max` is not finite."""
x = _convert_to_tensor(x)
m = np.max(x, axis=_astuple(axis), keepdims=keepdims)
needs_masking = ~np.isfinite(m)
if needs_masking.ndim > 0:
m = np.where(needs_masking, mask, m)
elif needs_m... | 5,317,266 |
def send_welcome_mail(request, user, activation):
"""
Sends welcome email to user with new account.
Making use of :class:`~django.core.mail.EmailMultiAlternatives` and
:class:`~email.mime.image.MIMEImage` to send a multipart email with plain text and html
version and also attach the integreat logo... | 5,317,267 |
def get_uniform_prototype(nlayer, opLibrary):
"""Creates a prototype over the uniform layer distribution (all
probabilities are equal).
Arguments
----------
nlayer: int
A number of layers in the prototype
opLibrary: list of layer classes
The layer library.
Returns
... | 5,317,268 |
def args_to_file(args_dict: dict) -> None:
"""Write the args to file."""
if args_dict["destination"].is_dir():
destination_file = args_dict["destination"] / ".preprocess_info.json"
else:
destination_file = (
args_dict["destination"].parent
/ f".{args_dict['destination... | 5,317,269 |
def make_batch_X(batch_X, n_steps_encode, dim_wordvec, word_vector):
"""Returns the world vector representation of the batch input by padding or truncating as may apply with a final dimension of [batch_size, n_steps_encode, word_vector] """
for i in range(len(batch_X)):
batch_X[i] = [word_vecto... | 5,317,270 |
def gap_fill(g, layer_qs, index, start_val, end_val, extrusion_rate, total_extruded, total_distance, n_fill_lines=None, gap=None):
"""Fill a polygon with a gap in between the lines that fill it.
The gap has a size of either `gap` or is evenly divided by `n_fill_lines`
"""
assert (n_fill_lines is not No... | 5,317,271 |
def weekend_christmas(start_date=None, end_date=None, observance=None):
"""
If christmas day is Saturday Monday 27th is a holiday
If christmas day is sunday the Tuesday 27th is a holiday
"""
return Holiday(
"Weekend Christmas",
month=12,
day=27,
days_of_week=(MONDAY, ... | 5,317,272 |
def force_set_all_well_sample_names(ds, sample_name):
"""
Set the WellSample name for all collections in the dataset metadata.
"""
for collection in ds.metadata.collections:
collection.wellSample.name = sample_name | 5,317,273 |
def lorentz(o, x, y, z, n=2000, dt=0.01):
"""Generate Lorentz attractor. Put graphic in a graphical object"""
o.grob = glGenLists(1)
glNewList(o.grob, GL_COMPILE)
try:
glDisable(GL_LIGHTING)
glBegin(GL_LINE_STRIP)
try:
glVertex3d(x, y, z)
frac = -1.0 * (8... | 5,317,274 |
def gen_markov():
"""Compile all the tweets and create a Markov chain."""
host_url = os.environ.get('REDIS_URL')
access_dict = {'sqlalchemy.url': os.environ.get('DATABASE_URL')}
engine = get_engine(access_dict)
SessionFactory = sessionmaker(bind=engine)
session = SessionFactory()
tweets = s... | 5,317,275 |
def get_interface_packages() -> List[str]:
"""Get all packages that generate interfaces."""
return get_resources('rosidl_interfaces') | 5,317,276 |
def rgb2str(r, g=None, b=None):
"""
Given r,g,b values, this function returns the closest 'name'.
:Example:
.. doctest:: genutil_colors_rgb2str
>>> print rgb2str([0,0,0])
'black'
:param r: Either a list of size 3 with r, g, and b values, or an integer representing r v... | 5,317,277 |
def count(args):
"""
%prog count fastafile jf.db
Run dump - jellyfish - bin - bincount in serial.
"""
from bitarray import bitarray
p = OptionParser(count.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, jfdb = args
K... | 5,317,278 |
def calc_uvw(phase_centre, timestamps, antlist, ant1, ant2, ant_descriptions, refant_ind=0):
"""
Calculate uvw coordinates
Parameters
----------
phase_centre
katpoint target for phase centre position
timestamps
times, array of floats, shape(nrows)
antlist
list of ant... | 5,317,279 |
def shrink_per_topic_to_per_meeting(input_file='predictions.txt', output_file='summaries.tgt.txt'):
"""
Concatenates the lines of a per-topic file to a per-meeting file.
"""
with open(output_file, 'w') as summaries_src_file:
with open(input_file, 'r') as predictions_file:
with open('... | 5,317,280 |
def rename_duplicate_name(dfs, name):
"""Remove duplicates of *name* from the columns in each of *dfs*.
Args:
dfs (list of pandas DataFrames)
Returns: list of pandas DataFrames. Columns renamed
such that there are no duplicates of *name*.
"""
locations = []
for i, df i... | 5,317,281 |
def test_accel_nb_1():
""" Use decorator """
accel.has_numba = True
@accel.try_jit
def fn():
return np.ones(100) * 5
assert isinstance(fn, jitd_class) | 5,317,282 |
async def m001_initial(db):
"""
Initial lnurlpos table.
"""
await db.execute(
f"""
CREATE TABLE lnurlpos.lnurlposs (
id TEXT NOT NULL PRIMARY KEY,
key TEXT NOT NULL,
title TEXT NOT NULL,
wallet TEXT NOT NULL,
currency TEXT NOT ... | 5,317,283 |
def payments(command):
"""Manage payments."""
if command == 'list':
list_payments(_get_connection())
elif command == 'add':
add_payment(_get_connection())
elif command == 'remove':
remove_payment(_get_connection())
elif command == 'update':
update_payment(_get_connect... | 5,317,284 |
def checkH(board, intX, intY, newX, newY):
"""Check if the horse move is legal, returns true if legal"""
tmp=False
if abs(intX-newX)+abs(intY-newY)==3:
if intX!=newX and intY!=newY:
tmp=True
return tmp | 5,317,285 |
def solarize_add(image, addition, threshold=None, name=None):
"""Adds `addition` intensity to each pixel and inverts the pixels
of an `image` above a certain `threshold`.
Args:
image: An int or float tensor of shape `[height, width, num_channels]`.
addition: A 0-D int / float tensor or int ... | 5,317,286 |
def do_tappy_tide_analysis(dates, val):
"""
"""
obs = pd.DataFrame(val, columns=['val'])
se = pd.Series(dates)
obs = obs.set_index (se)
obs.dropna()
obsh = obs.resample('H').mean()
dates = datetime64todatetime(obsh.index)
val = obsh.val
# ##
from tappy.tappy... | 5,317,287 |
def install_subpackage_dependencies(ctx, name=None, force=False):
"""Replaces top-level Pipfile dependencies with sub-package dependencies.
Use in CI to install only single sub-package dependencies.
Use without the ``name`` in local development to get dependencies from all sub-packages.
Args:
... | 5,317,288 |
def is_dirty2():
"""Function: is_dirty2
Description: Method stub holder for git.Repo.git.is_dirty().
Arguments:
"""
return False | 5,317,289 |
def getTranslation(tbl, all_names, tsv_output):
"""get name translation for contig files from prokka
Args:
tbl (string): Path to the tbl file
all_names (list of string): All the name in the fasta in order
tsv_output (string): Path of the output tsv table with the prokka and contig name
... | 5,317,290 |
def test_ucsc_link():
"""Test if ucsc link is correctly added"""
# GIVEN a minimal gene and a genome build
gene_obj = {"hgnc_id": 257, "ucsc_id": "uc001jwi.4"}
build = 37
# WHEN adding the gene links
add_gene_links(gene_obj, build)
# THEN assert some links are added
link = gene_obj.get("... | 5,317,291 |
def create(language, namespace, templatepath):
"""
Create a language by name.
"""
lang = None
if language == "Java":
lang = Java(namespace, templatepath)
elif language == "C++":
lang = CXX(namespace, templatepath)
else:
raise ModelProcessingError(
"Inval... | 5,317,292 |
def dq2segs(channel, gps_start):
"""
This function takes a DQ CHANNEL (as returned by loaddata or getstrain) and
the GPS_START time of the channel and returns a segment
list. The DQ Channel is assumed to be a 1 Hz channel.
Returns of a list of segment GPS start and stop times.
"""
#-- Che... | 5,317,293 |
def add_views_to_depth_estimator(original_data, udata, neighbors, de):
"""Add neighboring views to the DepthmapEstimator."""
num_neighbors = udata.config['depthmap_num_matching_views']
for shot in neighbors[:num_neighbors + 1]:
assert shot.camera.projection_type == 'perspective'
color_image ... | 5,317,294 |
def get_info(prefix, string):
"""
:param prefix: the regex to match the info you are trying to obtain
:param string: the string where the info is contained (can have new line character)
:return: the matches within the line
"""
info = None
# find and return the matches based on the prefix a... | 5,317,295 |
def to_unix(dt):
"""Converts a datetime object to unixtime"""
return calendar.timegm(dt.utctimetuple()) | 5,317,296 |
def test_paragraph_series_m_ha_ul_t_nl_ul_nl_ha_t():
"""
Test case: Unordered list text newline unordered list new line atx heading text
"""
# Arrange
source_markdown = """- abc
-
# foo
"""
expected_tokens = [
"[ulist(1,1):-::2:: ]",
"[setext(2,3):-:1::(1,3)]",
"[tex... | 5,317,297 |
def test_sp_hf_rhf(mtd, opts, h2o):
"""cfour/???/input.dat
#! single point HF/qz2p on water
"""
h2o = qcdb.set_molecule(h2o)
qcdb.set_options(opts)
g, jrec = qcdb.gradient(mtd, return_wfn=True, molecule=h2o)
print(g)
assert compare_arrays(rhf_scf, g, atol=1.0e-5)
# from cfour
... | 5,317,298 |
def count_circular_primes(ceiling):
"""
Counts the number of circular primes below ceiling.
A circular prime is a prime for which all rotations of the digits is also
prime.
"""
return len([
a for a in range(ceiling)
if is_prime(a) and all(is_prime(a) for a in gen_rotation_list(a)... | 5,317,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.