content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import requests
def list_with_one_dict(sort_type, url_param=None):
"""
Search by parameter that returns a list with one dictionary.
Used for full country name and capital city.
"""
extra_param = ""
if sort_type == 2:
url_endpoint = "/name/"
user_msg = "full country name"
... | 79f96ab76c123bfa3c3faee57e9af6c1900c3cd7 | 17,800 |
def get_form(case, action_filter=lambda a: True, form_filter=lambda f: True, reverse=False):
"""
returns the first form that passes through both filter functions
"""
gf = get_forms(case, action_filter=action_filter, form_filter=form_filter, reverse=reverse)
try:
return gf.next()
except S... | b0e8caeb6fae1f56407aaf14475c5f06c9b4a3d0 | 17,801 |
from datetime import datetime
def csv_to_json_generator(df, field_map: dict, id_column: str, category_column: str):
"""
Creates a dictionary/json structure for a `single id dataframe` extracting content using the
`extract_features_by_category` function.
"""
id_list = find_ids(df=df, id_column=id_c... | 40bf0657d8ca7d141af919f03b9b6e7cc6887749 | 17,802 |
import argparse
import os
def parse_args():
"""Get command line arguments."""
parser = argparse.ArgumentParser(prog='metrics',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=desc_str)
parser.add_argument('-v', '--... | a15df38667bd95f87c7ce5fa7c150589a1082bae | 17,803 |
def sunset_hour_angle(sinLat, cosLat, sinDec, cosDec):
"""
Calculate local sunset hour angle (radians) given sines and cosines
of latitude and declination.
"""
return np.arccos(np.clip(-sinDec / cosDec * sinLat / cosLat, -1, 1)) | 43e9e6d5026ea16f348f6704a8226763f0d08786 | 17,804 |
def handle_enable(options):
"""Enable a Sopel plugin.
:param options: parsed arguments
:type options: :class:`argparse.Namespace`
:return: 0 if everything went fine;
1 if the plugin doesn't exist
"""
plugin_names = options.names
allow_only = options.allow_only
settings = ut... | e3b931fcd8f90e7570f80604d7690cf8c8485cd9 | 17,805 |
def compare_img_hist(img_path_1, img_path_2):
"""
Get the comparison result of the similarity by the histogram of the
two images. This is suitable for checking whether the image is close
in color. Conversely, it is not suitable for checking whether shapes
are similar.
Parameters
----------
... | 4fa34b3186b69464be15052a9427bb274f95d28f | 17,806 |
import json
def recombinant_example(resource_name, doc_type, indent=2, lang='json'):
"""
Return example data formatted for use in API documentation
"""
chromo = recombinant_get_chromo(resource_name)
if chromo and doc_type in chromo.get('examples', {}):
data = chromo['examples'][doc_type]
... | 1a6cfe474425ba4d62472f571ca0eae0d3cfbff0 | 17,807 |
def _integral_diff(x, pdf, a, q):
"""Return difference between q and the integral of the function `pdf`
between a and x. This is used for solving for the ppf."""
return integrate.quad(pdf, a, x)[0] - q | 616cfba7361c92f7cbdf8bac55f9a65a60c2c32f | 17,808 |
def Fcomplete(t,y,k0m,k1,k2m,k2p,k3,k4,k5m,k6m,k7,Kr0,Kr1,Kr2,Kr2p,Km5,Km6,Km7,Gt,Rt,Mt,k_Gp,Gpt,n):
"""
Right hand side of ODE y'(t) = f(t,y,...)
It receives parameters as f_args, as given py param_array (see param.py)
3 components: G, R, M
"""
k0=k0m*Kr0 # kmi =ki/Kri or ki/Kmi
k2=k2m*Kr2... | a6b614a34fb0c2dcaf29107c05eb397312825568 | 17,809 |
def lu_solve(l: np.ndarray, u: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Решение СЛАУ, прошедшей через LU-разложение.
Требуется предварительно умножить вектор правых частей на матрицу перестановки.
:param l: нижняя треугольная матрица
:param u: верхняя треугольная матрица
:param b: вектор правых... | 5429fe91dfb15a5cf306871d07f0204f8f23a405 | 17,810 |
def datetime_to_httpdate(input_date):
# type: (datetime) -> Optional[str]
"""Converts datetime to http date string"""
if input_date is None:
return None
try:
return input_date.strftime(HTTP_DATE_FORMAT)
except (ValueError, TypeError) as e:
logger.debug(e)
return None | bf4cb68bb156a3abb214867e4e366497d091a17b | 17,811 |
def zr_bfr_tj():
"""
Real Name: b'Zr bfr Tj'
Original Eqn: b'Zr aftr Dam-Wr sup aftr Zr Dam+(Wr sup aftr Zr Dam*0.2)'
Units: b''
Limits: (None, None)
Type: component
b''
"""
return zr_aftr_dam() - wr_sup_aftr_zr_dam() + (wr_sup_aftr_zr_dam() * 0.2) | aae58ac349a7039afd0f3f3f12166a39de8afe31 | 17,812 |
def simplify(n):
"""Remove decimal places."""
return int(round(n)) | 9856c8f5c0448634956d1d05e44027da2f4ebe6a | 17,813 |
def resnet_qc_18(**kwargs):
"""Constructs a ResNet-18 model."""
model = ResNetQC(BasicBlock, [2, 2, 2, 2], **kwargs)
return model | a1554e044dd69e96474602c88e8e73d4d697c861 | 17,814 |
import scipy.sparse
def sparse_from_npz(file, **_kw):
"""
Possible dispatch function for ``from_path_impl``'s ``from_npz``.
Reads a scipy sparse matrix.
"""
return scipy.sparse.load_npz(file) | 9909975ff0309cde98117e64718fe292de574987 | 17,815 |
import copy
def get_config():
"""
Read the configuration
:returns: current configuration
"""
global config
return copy.deepcopy(config) | 3e9b064123ed9165c04cbc7e1c2b0d646703cb7a | 17,816 |
def resnext20_2x64d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (2x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
p... | 147b9ff5565fdbbcaab68d66fbfa3e8a5a4b6062 | 17,817 |
def test_target(target):
"""Returns the label for the corresponding target in the test tree."""
label = to_label(target)
test_package = label.package.replace("src/main/", "src/test/", 1)
return Label("@{workspace}//{package}:{target_name}".format(
workspace = label.workspace_name,
packag... | 8b4391a5acdea7b851ef6606ad3dfa0b21132ae1 | 17,818 |
def pred_fwd_rc(model, input_npy, output_fwd, output_rc, replicates=1, batch_size=512):
"""Predict pathogenic potentials from a preprocessed numpy array and its reverse-complement."""
y_fwd, _ = predict_npy(model, input_npy, output_fwd, rc=False, replicates=replicates, batch_size=batch_size)
y_rc, _ = predi... | 90ed6c3a29dd3e24cef45415ec51381bf32a8b37 | 17,819 |
import os
def get_ids(viva_path, dataset):
"""Get image identifiers for corresponding list of dataset identifies.
Parameters
----------
viva_path : str
Path to VIVA directory.
datasets : list of str tuples
List of dataset identifiers in the form of (year, dataset) pairs.
Retu... | 526c094323af2be7611c3bf9261c703106442b24 | 17,820 |
def get_api_version(version_string):
"""Returns checked APIVersion object"""
version_string = str(version_string)
api_version = APIVersion(version_string)
check_major_version(api_version)
return api_version | 9bbc88c3aee2139dc39367d4788d6c382f711903 | 17,821 |
def evaluate_g9( tau7, tau8, tau9, tau10, tau11, s9 ):
"""
Evaluate the ninth constraint equation and also return the Jacobian
:param float tau7: The seventh tau parameter
:param float tau8: The eighth tau parameter
:param float tau9: The ninth tau parameter
:param float tau10: The tenth tau pa... | 9f8181e4d6abac9207eec721d6b347a560778ecf | 17,822 |
from functools import reduce
import operator
def qmul(*q, qaxis=-1):
""" Quaternion multiplication.
Parameters
----------
q: iterable of array_like
Arrays containing quaternions to multiply. Their dtype can be
quaternion, otherwise `qaxis` specifies the axis representing
the q... | d745fc94a66ec20e5c673252fb3d289201025473 | 17,823 |
def iterable(value,
allow_empty = False,
forbid_literals = (str, bytes),
minimum_length = None,
maximum_length = None,
**kwargs):
"""Validate that ``value`` is a valid iterable.
.. hint::
This validator checks to ensure that ``value`` supp... | 57de6a43243d9c611725f1e9987e881cf1485b63 | 17,824 |
from typing import List
def settings_notification(color: bool, messages: List[ExitMessage]) -> Form:
"""Generate a warning notification for settings errors.
:param messages: List of messages to display
:param color: Bool to reflect if color is transferred or not
:returns: The form to display
"""
... | a1ff085c76e84e01ba293f17b662626a39fda26f | 17,825 |
def message_type(ctx: 'Context', *types):
"""Filters massage_type with one of selected types.
Assumes update_type one of message, edited_message, channel_post, edited_channel_post.
:param ctx:
:param types:
:return: True or False
"""
m = None
if ctx.update.update_type is UpdateType.me... | 231bbb3b802d6f6dcf4a22af7704fae3ce24e783 | 17,826 |
import math
def VSphere(R):
"""
Volume of a sphere or radius R.
"""
return 4. * math.pi * R * R * R / 3. | 9e99d19683d9e86c2db79189809d24badccc197b | 17,827 |
from typing import Optional
from typing import Any
def resolve_variable(
var_name: str,
var_def: BlueprintVariableTypeDef,
provided_variable: Optional[Variable],
blueprint_name: str,
) -> Any:
"""Resolve a provided variable value against the variable definition.
Args:
var_name: The na... | 1df7d4804f104c8f746999aaaad5f91ca96b5f78 | 17,828 |
import os
def generate_navbar(structure, pathprefix):
"""
Returns 2D list containing the nested navigational structure of the website
"""
navbar = []
for section in structure['sections']:
navbar_section = []
section_data = structure['sections'][section]
section_url = os.pat... | daed8a1a74887406700fc2ca380e22165fa300f6 | 17,829 |
def additional_args(**kwargs):
"""
Additional command-line arguments.
Provides additional command-line arguments that are unique to the extraction process.
Returns
-------
additional_args : dict
Dictionary of tuples in the form (fixed,keyword) that can be passed to an argument... | 1b0f10f7f9c60077de9c580163b5e3893da63a83 | 17,830 |
import html
def extract_images_url(url, source):
"""
Extract image url for a chapter
"""
r = s.get(url)
tree = html.fromstring(r.text)
if source == 'blogtruyen':
return tree.xpath('//*[@id="content"]/img/@src')
elif source == 'nettruyen':
return tree.xpath('//*[@class="read... | f2299d3e1dde38fc7ac2d3789e8145f5a71a1299 | 17,831 |
from typing import Dict
from typing import Any
from typing import Optional
from typing import Literal
from typing import List
import pathlib
def _ntuple_paths(
general_path: str,
region: Dict[str, Any],
sample: Dict[str, Any],
systematic: Dict[str, Any],
template: Optional[Literal["Up", "Down"]],
... | efb96f1b977c30c83890c2030f312c0066eed4d8 | 17,832 |
def svn_ra_do_diff2(*args):
"""
svn_ra_do_diff2(svn_ra_session_t session, svn_revnum_t revision, char diff_target,
svn_boolean_t recurse, svn_boolean_t ignore_ancestry,
svn_boolean_t text_deltas,
char versus_url, svn_delta_editor_t diff_editor,
void diff_baton, apr_pool_t pool)... | 8964a6304582daf5631e8e26c8cf7ff9167837dd | 17,833 |
def ntuple_dict_length(ntuple_dict):
"""Returns a dictionary from track types to the number of tracks of
that type. Raises an exception of any value lists within one of its
track properties dicts are different lengths."""
return dict(map(lambda track_type, track_prop_dict:
(track_type, track_pr... | e5f7805dfb4a641268792e4e8982e21a05298f9e | 17,834 |
def range_ngram_distrib(text, n, top_most=-1):
"""
List n-grams with theis probabilities from the most popular to the smaller ones
:param text: text
:param n: n of n-gram
:param top_most: count of most popular n-grams to be returned, or -1 to return all
:return: list of ngrams, list of probs
... | 0822b2e7824aee6cc28e2a734dea5d9aff0df1ac | 17,835 |
import os
def extract_group_ids(caps_directory):
"""Extract list of group IDs (e.g. ['group-AD', 'group-HC']) based on `caps_directory`/groups folder."""
try:
group_ids = os.listdir(os.path.join(caps_directory, "groups"))
except FileNotFoundError:
group_ids = [""]
return group_ids | 908ac1c3c06028f526b1d474618fca05d76f8792 | 17,836 |
import functools
def require_methods(*methods):
"""Returns a decorator which produces an error unless request.method is one
of |methods|.
"""
def decorator(func):
@functools.wraps(func)
def wrapped(request, *args, **kwds):
if request.method not in methods:
allowed = ', '.join(methods)
... | 6c02675836c95f9ee7bab124cc1287bc6d3dfb95 | 17,837 |
def getUnit3d(prompt, default=None):
"""
Read a Unit3d for the termial with checking. This will accapt and
directon in any format accepted by Unit3d().parseAngle()
Allowed formats
* x,y,z or [x,y,z] three floats
* theta,psi or [theta,psi], in radians (quoted in "" for degrees)
* theta in... | dd39a706114c72ce9059686e342e8a1db1e3464b | 17,838 |
def checkOverlap(ra, rb):
"""
check the overlap of two anchors,ra=[chr,left_start,left_end,chr,right_start,right_end]
"""
if checkOneEndOverlap(ra[1], ra[2], rb[1], rb[2]) and checkOneEndOverlap(
ra[4], ra[5], rb[4], rb[5]):
return True
return False | 9644ed7e2de9d9091e21a64c7c4cd43a0e0e1210 | 17,839 |
import typing
def saveable(item: praw.models.reddit.base.RedditBase) -> dict[str, typing.Any]:
"""Generate a saveable dict from an instance"""
result = {k: legalize(v) for k, v in item.__dict__.items() if not k.startswith("_")}
return _parent_ids_interpreted(result) | 6e9e7092045e321de2beeba7debbd6dc2a2b2e61 | 17,840 |
import re
def decode_Tex_accents(in_str):
"""Converts a string containing LaTex accents (i.e. "{\\`{O}}") to ASCII
(i.e. "O"). Useful for correcting author names when bib entries were
queried from web via doi
:param in_str: input str to decode
:type in_str: str
:return: corrected string
:... | 2a4bd71b53cdab047a1ddd1e0e6fd6e9c81b0e0a | 17,841 |
from typing import Mapping
def tensor_dict_eq(dict1: Mapping, dict2: Mapping) -> bool:
"""Checks the equivalence between 2 dictionaries, that can contain torch Tensors as value. The dictionary can be
nested with other dictionaries or lists, they will be checked recursively.
:param dict1: Dictionary to co... | db3d7d23e633f5a240d0d0d13f6836494dc44e20 | 17,842 |
def calculate_stability(derivatives):
"""
Calculate the stability-axis derivatives with the body-axis derivatives.
"""
d = derivatives
if 'stability' not in d:
d['stability'] = {}
slat = calculate_stability_lateral(d['body'], np.deg2rad(d['alpha0']))
slong = calculate_stability_longi... | 888f63454265b3811751ae91654a9de083f25fec | 17,843 |
import os
def apply_config(keys, options, path=None):
# type: (Any, optparse.Values, Optional[str]) -> Dict[str, str]
"""
Read setup.cfg from path or current working directory and apply it to the
parsed options
Parameters
----------
keys
options : optparse.Values
parsed option... | b1a8bbb411fca106579fc543751b6f9336205d66 | 17,844 |
from os import linesep as ls
def convert_v1_to_v2(v1, max, asm, v2=None, first=0):
"""Converts a given v1 timecodes file to v2 timecodes.
Original idea from tritical's tcConv.
"""
ts = fn1 = fn2 = last = 0
asm = correct_to_ntsc(asm, True)
o = []
ap = o.append
en = str.encode
... | 350ed163977d06632297dd460e42a0ea8b70bd05 | 17,845 |
from datetime import datetime
def read_malmipsdetect(file_detect):
"""
This function is used to read the MALMI detection file which contains detection
information, that is for each detected event how many stations are triggered,
how many phases are triggered. Those information can be used for quality ... | cf42172e9f286254f31b2e57361c25360ed73d10 | 17,846 |
def GeneratePermissionUrl(client_id, scope='https://mail.google.com/'):
"""Generates the URL for authorizing access.
This uses the "OAuth2 for Installed Applications" flow described at
https://developers.google.com/accounts/docs/OAuth2InstalledApp
Args:
client_id: Client ID obtained by registe... | b4471e78eab772a57be8d3073451050fd78d904c | 17,847 |
import os
import shutil
import time
def download(request):
"""Download images as .zip file. """
def make_archive(source, destination):
print(source, destination)
base = os.path.basename(destination)
name = base.split('.')[0]
format = base.split('.')[1]
archive_fro... | 39fd231c96581f366f3a26f31bfc7bb17f977eb6 | 17,848 |
def get_scorekeeper_details():
"""Retrieve a list of scorekeeper and their corresponding
appearances"""
return scorekeepers.get_scorekeeper_details(database_connection) | 78092d0ae6bcb21ee86a1fddfc678472c81eb55f | 17,849 |
def layer_norm(input_tensor, axis):
"""Run layer normalization on the axis dimension of the tensor."""
layer_norma = tf.keras.layers.LayerNormalization(axis = axis)
return layer_norma(input_tensor) | 9687dedf8c3a624013c5188401e86d7ef6d73969 | 17,850 |
def compute_depth(disparity, focal_length, distance_between_cameras):
"""
Computes depth in meters
Input:
-Disparity in pixels
-Focal Length in pixels
-Distance between cameras in meters
Output:
-Depth in meters
"""
with np.errstate(divide='ignore'): #ignore division by 0
... | 5ea475dae1d4aa0c429a7f6766293a39d403904d | 17,851 |
def lecture(source=None,target=None,fseed=100,fpercent=100):
"""
Create conversion of the source file and the target file
Shuffle method is used, base on the seed (default 100)
"""
seed(fseed)
try:
copysource = []
copytarget = []
if(source!=None and target!=None)... | b0878ab2b3d888db984aa0644080578a85e9e554 | 17,852 |
def getScale(im, scale, max_scale=None):
"""
获得图片的放缩比例
:param im:
:param scale:
:param max_scale:
:return:
"""
f = float(scale) / min(im.shape[0], im.shape[1])
if max_scale != None and f * max(im.shape[0], im.shape[1]) > max_scale:
f = float(max_scale) / max(im.shape[0], im.s... | 52ae195714c1d39bccec553797bf6dbf2c6c2795 | 17,853 |
def load_swc(path):
"""Load swc morphology from file
Used for sKCSD
Parameters
----------
path : str
Returns
-------
morphology : np.array
"""
morphology = np.loadtxt(path)
return morphology | 0b0a4f82344b6c16180b4a52b1077a0f28966fde | 17,854 |
import os
def getFileName(in_path, with_extension=False):
"""Return the file name with the file extension appended.
Args:
in_path (str): the file path to extract the filename from.
with_extension=False (Bool): flag denoting whether to return
the filename with or without the extens... | 56972e397a2b5961656175962ab799bb95761e7c | 17,855 |
def quintic_extrap((y1,y2,y3,y4,y5,y6), (x1,x2,x3,x4,x5,x6)):
"""
Quintic extrapolate from three x,y pairs to x = 0.
y1,y2...: y values from x,y pairs. Note that these can be arrays of values.
x1,x2...: x values from x,y pairs. These should be scalars.
Returns extrapolated y at x=0.
"""
# ... | 41090e09f2b7f58e98fa9fc91ea6000d70594046 | 17,856 |
def answer_question_interactively(question):
"""Returns True or False for t yes/no question to the user"""
while True:
answer = input(question + '? [Y or N]: ')
if answer.lower() == 'y':
return True
elif answer.lower() == 'n':
return False | 52a123cc2237441de3b0243da268e53b7cc0d807 | 17,857 |
def connect(
instance_id,
database_id,
project=None,
credentials=None,
pool=None,
user_agent=None,
):
"""Creates a connection to a Google Cloud Spanner database.
:type instance_id: str
:param instance_id: The ID of the instance to connect to.
:type database_id: str
:param d... | 7cff910615df346a5a503dec5e1938476cb701e6 | 17,858 |
from typing import List
def intersect(linked_list_1: List, linked_list_2: List):
"""Intersection point of two linked list."""
length_diff = len(linked_list_1) - len(linked_list_2)
enum1 = list(enumerate(linked_list_1))
enum2 = list(enumerate(linked_list_2))
if length_diff < 0:
enum2 = _he... | dea64a6618ab3bda421250036e4eea8fa316a6ec | 17,859 |
import fnmatch
def recognize_package_manifests(location):
"""
Return a list of Package objects if any package_manifests were recognized for this
`location`, or None if there were no Packages found. Raises Exceptions on errors.
"""
if not filetype.is_file(location):
return
T = content... | 4e90726be78ec73b3d68dc52e1aa32b7bad420ab | 17,860 |
import torch
def content_loss(sharp_images, deblur_images, cont_net):
"""
Computes the Content Loss to compare the
reconstructed (deblurred) and the original(sharp) images
Takes the output feature maps of the relu4_3 layer of pretrained VGG19 to compare the content between
images as proposed in... | f55b4c22391d6e562afb927251fb6af267f9da08 | 17,861 |
def generate_cashflow_diagram(
cashflows, d=None, net=False, scale=None, color=None, title=None, **kwargs):
""" Generates a barplot showing cashflows over time
Given a set of cashflows, produces a stacked barplot with bars at each
period. The height of each bar is set by the amount of cash produced... | 88afbd975a20041dccd24b8dc25899347a0b44ae | 17,862 |
import collections
def is_iterable(obj):
# type: (Any) -> bool
"""
Returns True if obj is a non-string iterable
"""
if is_str(obj) is True or isinstance(obj, collections.Iterable) is False:
return False
else:
return True | 92db9be57250a53cf27118c9a4c91344a9d14fcb | 17,863 |
def other_players(me, r):
"""Return a list of all players but me, in turn order starting after me"""
return list(range(me+1, r.nPlayers)) + list(range(0, me)) | 5c2d2b03bfb3b99eb4c347319ccaaa3fc495b6c4 | 17,864 |
def mock_dd_slo_history(*args, **kwargs):
"""Mock Datadog response for datadog.api.ServiceLevelObjective.history."""
return load_fixture('dd_slo_history.json') | 963fbbe20373e4e207852be82b88e33ca2c24e9a | 17,865 |
import torch
def check_joints2d_visibility_torch(joints2d, img_wh):
"""
Checks if 2D joints are within the image dimensions.
"""
vis = torch.ones(joints2d.shape[:2], device=joints2d.device, dtype=torch.bool)
vis[joints2d[:, :, 0] > img_wh] = 0
vis[joints2d[:, :, 1] > img_wh] = 0
vis[joints... | a276d93a66dfd5bca15a684f652a0eede3094868 | 17,866 |
def getIntervalIntersectionLength(aa, bb, wrapAt=360):
"""Returns the length of the intersection between two intervals."""
intersection = getIntervalIntersection(aa, bb, wrapAt=wrapAt)
if intersection is False:
return 0.0
else:
if wrapAt is None:
return (intersection[1] - i... | 46924c149e8b5b802fc83e489417850f3a8dbd18 | 17,867 |
def test_jvp_construct_single_input_single_output_default_v_graph():
"""
Features: Function jvp
Description: Test jvp with Cell construct, single input, single output and default v in graph mode.
Expectation: No exception.
"""
x = Tensor(np.array([[1, 2], [3, 4]]).astype(np.float32))
v = Ten... | edd6b1c93dc880310fc0af2012d3fbfca328b64c | 17,868 |
def get_environment() -> Environment:
"""
Parses environment variables and sets their defaults if they do not exist.
"""
return Environment(
permission_url=get_endpoint("PERMISSION"),
media_url=get_endpoint("MEDIA"),
datastore_reader_url=get_endpoint("DATASTORE_READER"),
... | 2ce9b56c76fadcd19a861f00e8d880a181b676ed | 17,869 |
from typing import Optional
def get_kubernetes_cluster(name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKubernetesClusterResult:
"""
Use this data source to access informatio... | 38beb9a7a96e51364f35c658d85428991e0686a8 | 17,870 |
def gene_expression_conv_base():
"""Hparams for GeneExpressionConv model."""
hparams = common_hparams.basic_params1()
batch_size = 10
output_length = 2048
inputs_per_output = 128
chunk_size = 4
input_length = output_length * inputs_per_output // chunk_size
hparams.batch_size = input_length * batch_size... | 7bd239fb511a7f72837a139f236557278f0c1dab | 17,871 |
import typing
from typing import _GenericAlias
import collections
def is_callable(type_def, allow_callable_class: bool = False) -> bool:
"""
Checks whether the ``type_def`` is a callable according to the following rules:
1. Functions are callable.
2. ``typing.Callable`` types are callable.
3. Gen... | 68c51cfc4da4891c90c376e8ff1b26dc630a96de | 17,872 |
def vgg19(pretrained=False, **kwargs):
"""VGG 19-layer model (configuration "E")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = VGG(make_layers(cfg['E']), **kwargs)
if pretrained:
model.load_pretrained_model(model_zoo.load_url(model_urls['vgg19... | 7c7e43eb46ffeb20fd5901d5761e11f701650727 | 17,873 |
def get_formats(input_f, input_case="cased", is_default=True):
"""
Adds various abbreviation format options to the list of acceptable input forms
"""
multiple_formats = load_labels(input_f)
additional_options = []
for x, y in multiple_formats:
if input_case == "lower_cased":
... | a20a02a7e85c1711d8b9d779e5804ed8e1dec83a | 17,874 |
def db_select_entry(c, bibkey):
""" Select entry from database
:argument
c: sqlite3 cursor
:returns
entry_dict: dict
"""
fields = ['bibkey', 'author', 'genre', 'thesis', 'hypothesis',
'method', 'finding', 'comment', 'img_linkstr']
sql = "SELECT {:s} FROM note WHERE ... | a93425aa2487f28bc3215a65ad1f963ea1173fcd | 17,875 |
def to_bytes(obj, encoding='utf-8', errors='strict'):
"""Makes sure that a string is a byte string.
Args:
obj: An object to make sure is a byte string.
encoding: The encoding to use to transform from a text string to
a byte string. Defaults to using 'utf-8'.
errors: The error handler to use if ... | 4f8a0dcfdcfd3e2a77b5cbeedea4cb2a11acd4c1 | 17,876 |
def login() -> Response:
"""
Login to Afterglow
GET|POST /auth/login
- login to Afterglow; authentication required using any of the methods
defined in USER_AUTH
:return: empty response with "afterglow_core_access_token" cookie
if successfully logged in
"""
# TODO Ensu... | 691540d0652b9909fa0f05af0dcc434d400be5a4 | 17,877 |
def compact(number, strip_check_digit=True):
"""Convert the MEID number to the minimal (hexadecimal) representation.
This strips grouping information, removes surrounding whitespace and
converts to hexadecimal if needed. If the check digit is to be preserved
and conversion is done a new check digit is r... | ced106ed8c97d432a8059d8654cfb437620deb64 | 17,878 |
from typing import List
def hashtag_getter(doc: Doc) -> List[str]:
"""
Extract hashtags from text
Args:
doc (Doc): A SpaCy document
Returns:
List[str]: A list of hashtags
Example:
>>> from spacy.tokens import Doc
>>> Doc.set_extension("hashtag", getter=dacy.utili... | a85c5cf9bd2fec2ec74e70bf2dadfb1df688c128 | 17,879 |
def options():
"""Stub version of the parsed command line options."""
class StubOptions(object):
profile = None
return StubOptions() | dea85d2956eb6cbf97f870a74b122896915c8c19 | 17,880 |
import logging
def get_surface(shifts, orig_text, item, text, unit_shortening=0):
"""
Extract surface from regex hit.
"""
# handle cut end
span = (item.start(), item.end() - unit_shortening)
logging.debug('\tInitial span: %s ("%s")', span, text[span[0]:span[1]])
real_span = (span[0] - s... | dde9a59ed50a71ab21a2fcd8b3468f5414adc94a | 17,881 |
def plot_bootstrap_delta_grp(dfboot, df, grp, force_xlim=None, title_add=''):
"""Plot delta between boostrap results, grouped"""
count_txt_h_kws, mean_txt_kws, pest_mean_point_kws, mean_point_kws = _get_kws_styling()
if dfboot[grp].dtypes != 'object':
dfboot = dfboot.copy()
dfboot[... | 1d9d25604392433bc9cc10d645f0a8f2122a2a38 | 17,882 |
from typing import Tuple
from typing import Optional
from typing import Dict
from typing import Any
def inception_inspired_reservoir_model(
input_shape: Tuple[int, int, int],
reservoir_weight: np.ndarray,
num_output_channels: int,
seed: Optional[int] = None,
num_filters: int = 32,
reservoir_ba... | 221c0c17035d44178ca460c011c92d37f26b4ed4 | 17,883 |
def midnight(date):
"""Returns a copy of a date with the hour, minute, second, and
millisecond fields set to zero.
Args:
date (Date): The starting date.
Returns:
Date: A new date, set to midnight of the day provided.
"""
return date.replace(hour=0, minute=0, second=0, microseco... | b92086dd9d99a4cea6657d37f40e68696ad41f7c | 17,884 |
import aiohttp
import os
async def api_call(method, data=None):
"""Slack API call."""
with aiohttp.ClientSession() as session:
token = os.environ.get('TOKEN')
if not token.startswith('xoxb-'):
return 'Define the token please'
form = aiohttp.FormData(data or {})
form... | 1b7809c4138fc31bead83e6e94a23904fbaf87d7 | 17,885 |
from typing import Callable
from typing import Any
from typing import Sequence
def foldr(fun: Callable[[Any, Any], Any], acc: Any, seq: Sequence[Any]) -> Any:
"""Implementation of foldr in Python3.
This is an implementation of the right-handed
fold function from functional programming.
If the list i... | 5648d8ce8a2807270163ebcddad3f523f527986e | 17,886 |
def tj_dom_dem(x):
"""
Real Name: b'Tj Dom Dem'
Original Eqn: b'( [(1,0.08)-(365,0.09)],(1,0.08333),(2,0.08333),(3,0.08333),(4,0.08333),(5,0.08333),(6\\\\ ,0.08333),(7,0.08333),(8,0.08333),(9,0.08333),(10,0.08333),(11,0.08333),(12,0.08333\\\\ ),(13,0.08333),(14,0.08333),(15,0.08333),(16,0.08333),(17,0.08333... | df670af98362fd67bece677aa85bf37d31a75389 | 17,887 |
def filter_chants_without_volpiano(chants, logger=None):
"""Exclude all chants with an empty volpiano field"""
has_volpiano = chants.volpiano.isnull() == False
return chants[has_volpiano] | 3f03bbf3f247afd3a115442e8121a773aa90fb56 | 17,888 |
def split_trainer_ops_pass(program, config, default_device="cpu"):
"""
split cpu-trainer program from origin-program
1. find heter op (located on different device)
2. find input&output of every heter-block
3. create cpu-trainer program, add send&recv op
"""
# Todo: support user define defau... | 254c4d8e8ea610bf69a8611eff5a471ba57b0f88 | 17,889 |
import pathlib
import os
def get_builtin_templates_path() -> pathlib.Path:
"""Return the pathlib.Path to the package's builtin templates
:return: template pathlib.Path
"""
return pathlib.Path(
os.path.dirname(os.path.realpath(__file__))
) / 'templates' | 4b6bfeb826aa2badb000267e12a9bb6cf19f6a28 | 17,890 |
def sample_input():
"""Return the puzzle input and expected result for the part 1
example problem.
"""
lines = split_nonblank_lines("""
position=< 9, 1> velocity=< 0, 2>
position=< 7, 0> velocity=<-1, 0>
position=< 3, -2> velocity=<-1, 1>
position=< 6, 10> velocity=<-2, -1>
position=< 2, -4> veloci... | e027d2831ef5d16776b5c5f7bb8e759042056e2f | 17,891 |
def vector_angle(v):
"""Angle between v and the positive x axis.
Only works with 2-D vectors.
returns: angle in radians
"""
assert len(v) == 2
x, y = v
return np.arctan2(y, x) | 4402795a27ca20269dbfa5a5823c4e2768681ed0 | 17,892 |
def get_user_record_tuple(param) -> ():
"""
Internal method for retrieving the user registration record from the DB.
:return:
"""
conn = mariadb.connect(host=DB_URI, user=DB_USERNAME, password=DB_PASSWORD, database=DB_NAME)
db = conn.cursor()
# discord_id provided
if isinstance(param, ... | d35468b7b2141f6c19f0c5669f80c103a7499221 | 17,893 |
def A_weighting(x, Fs):
"""A-weighting filter represented as polynomial transfer function.
:returns: Tuple of `num` and `den`.
See equation E.6 of the standard.
"""
f1 = _POLE_FREQUENCIES[1]
f2 = _POLE_FREQUENCIES[2]
f3 = _POLE_FREQUENCIES[3]
f4 = _POLE_FREQUENCIES[4]
offset = _NO... | a4592939d3809da292c4f05f47ca69e41ad9d27a | 17,894 |
import inspect
def register(class_=None, **kwargs):
"""Registers a dataset with segment specific hyperparameters.
When passing keyword arguments to `register`, they are checked to be valid
keyword arguments for the registered Dataset class constructor and are
saved in the registry. Registered keyword... | f1ce9a7abc8224fcd4bd80cddbf0d46e11ee997a | 17,895 |
import random
def random_population(pop_size, tune_params, tuning_options, max_threads):
"""create a random population of pop_size unique members"""
population = []
option_space = np.prod([len(v) for v in tune_params.values()])
assert pop_size < option_space
while len(population) < pop_size:
... | b5f2fa518e29bdd6ccb5d10213080f9c594f01b0 | 17,896 |
def check_genome(genome):
"""Check if genome is a valid FASTA file or genomepy genome genome.
Parameters
----------
genome : str
Genome name or file to check.
Returns
-------
is_genome : bool
"""
try:
Genome(genome)
return True
except Exception:
... | 5f51d74203b77f39b0c8054d36fa6b68399540dd | 17,897 |
def extract_row_loaded():
"""extract_row as it should appear in memory"""
result = {}
result['classification_id'] = '91178981'
result['user_name'] = 'MikeWalmsley'
result['user_id'] = '290475'
result['user_ip'] = '2c61707e96c97a759840'
result['workflow_id'] = '6122'
result['workflow_name... | c5fd87149ab7dff6e9980a898013053ce309c259 | 17,898 |
def getb_reginsn(*args):
"""
getb_reginsn(ins) -> minsn_t
Skip assertions backward.
@param ins (C++: const minsn_t *)
"""
return _ida_hexrays.getb_reginsn(*args) | 04f0141c0053e74981264b90b3bb0be1fbea8c08 | 17,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.