content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def Sparsity_lower(*args):
"""
lower(int n) -> Sparsity
"""
return _casadi.Sparsity_lower(*args) | 7ab8e5ec46ff56c1f821918ab132d1ee03c36e08 | 80,632 |
def set_content(content: str):
""" Creates the CSS rule for setting content.
:param content: The content to be set.
:return: CSS rule for applying the content.
note:: Author(s): Mitch """
return CSS_Rule('content', content) | fa1ababc773a8a1c8342a11e70ca8694c95ea00b | 80,633 |
def calculate_engagement_index(data, config):
"""Calculate engagement_index using different features.
Parameters
----------
data : dataframe
Dataframe containing band powers.
config : yaml
Configuration file.
Returns
-------
dataframe
Dataframe of calculated eng... | c20bc1a135ba2d8d44e5f7f36d1bc42d51e73153 | 80,634 |
def part2(lines):
"""
>>> part2(load_example(__file__, '11'))
26
"""
d = list(map(str.strip, lines))
changed = True
while changed:
changed, d = step_part2(d)
return count_seats(d) | 833b9a56ff69b8835288fb62633a3b79683d7456 | 80,635 |
def get_score(cards):
"""
:param cards: (list of ints) the cards to evaluate
:return: score (int) the best possible score of the set of cards. 22 is blackjack and 0 means that the
player burst.
"""
max_score = 0
min_score = 30
for v in get_values(cards):
if 22 > v > max_score:
... | 0107506663198f0707a07bb6135ed7de62cbc15e | 80,636 |
import torch
def interpolate(ae, gg, z1, z2, vocab,
steps=5, sample=None, maxlen=None):
"""
Interpolating in z space
Assumes that type(z1) == type(z2)
"""
if type(z1) == Variable:
noise1 = z1
noise2 = z2
elif type(z1) == torch.FloatTensor or type(z1) == torch.cu... | 28163ab05c0f2293e76d091622b082123b91f893 | 80,637 |
from pathlib import Path
def rename_bad_elf_gpx(gpx_file, dest_folder_path = None):
"""Renames a GPX file to match the configured timestamp format."""
# Get the timestamp for the earliest waypoint in the GPX file.
with open(gpx_file, 'r') as gf:
gpx = gpxpy.parse(gf)
first_point_time = mi... | 6a64df5423df5ec3a6069ca9803fdca6e747d475 | 80,638 |
def create_room_get(user):
"""
Renders the login page for the user
:return: The login page to be rendered
"""
return render_template('settings.html') | ca97f1703660b3fdd541eb90a50ed84412e0b2b3 | 80,641 |
def get_current_application(request):
"""Get current application."""
try:
app_name = request.resolver_match.namespace
if not app_name:
app_name = "home"
except Exception as e:
app_name = "home"
return app_name | 310004714da3129cafb2bc635837920a7457fbe7 | 80,642 |
def upload(data, path, **kwargs):
"""Given a concrete data object, store it at given location return Source
Use this function to publicly share data which you have created in your
python session. Intake will try each of the container types, to see if
one of them can handle the input data, and write the... | d2f30a5d80ddb39479700fc35a71bac843f540b9 | 80,643 |
def pwned_passwords_check(password):
"""Uses pwned passwords api"""
pw_hash = sha1(password.encode()).hexdigest()
hash_prefix = pw_hash[:5]
hash_suffix = pw_hash[5:].upper()
response = Request(url=PWNED_PASSWORD_API + hash_prefix, headers={
'User-Agent': 'Competition Manager'})
for line ... | 68803ea213bf80515076bd7e5f4462766a7c273b | 80,644 |
def xyz_to_rgb(x, y, z, *, reference="D65", clip=True):
"""
Converts CIE-XYZ to Linear-RGB (0-1)
Note: This function is still in beta-testing. Do not use in your
production code.
:param x: CIE-X
:param y: CIE-Y
:param z: CIE-Z
:param reference: White reference (default: D65)
:param... | cd43b4ec3a48a3e962916eeab7a7b93044fdabd1 | 80,645 |
def hermite(n,x):
"""
Returns the Hermite polynomial for integers `n > -1`.
REFERENCE:
- AS 22.5.40 and 22.5.41, page 779.
EXAMPLES::
sage: x = PolynomialRing(QQ, 'x').gen()
sage: hermite(2,x)
4*x^2 - 2
sage: hermite(3,x)
8*x^3 - 12*x
sage: hermite... | 1982a6f24406262b611bbf4473927d095533029f | 80,646 |
def histogram_him_collocated_double(dataframe, top_feature, base_feature):
"""
Produces a figure containing histograms of Himawari band data
from the given dataframe where the top_feture type is above the
base_feature type (double only).
NB// All cloud types are reduced into a single cloud category.... | 6d32a8df8803df1a78038e4e621c0c8562d77737 | 80,647 |
def get_reference_link(html_string):
"""Returns reference links in the given html_string.
Returns:
a tuple of two URL lists, (matches, mismatches).
"""
parser = ExtractReferenceLinkParser()
parser.feed(html_string)
parser.close()
return parser.matches, parser.mismatches | 809177e77e6175b57da36efe263e4e1172cb4c3e | 80,648 |
def normalization(arr):
"""normalize the array
Args:
arr: array
Return:
(array): normalization of the array
"""
return (arr - np.min(arr)) / (np.max(arr) - np.min(arr)) | 13dcbea88871f48d2ebd609a6d88c5522236e33c | 80,649 |
def make_network(num_rows, num_columns):
""" Build the network."""
# Make an array of nodes.
nodes = [[None for c in range(num_columns)] for r in range(num_rows)]
for r in range(num_rows):
for c in range(num_columns):
nodes[r][c] = Node(r, c)
# Make horizontal links.
for r i... | a889363da9d70096d0ea99ad55419ddf5d82b773 | 80,650 |
def _average(matrix, iters):
"""
Assigns mean of all non-zero/non-NaN values to each gridcell given
that the blocks are smaller than the maximum allowable block height.
Args:
matrix: NumPy 2D depth matrix
iters: Divides matrix into 4^iters equally-sized blocks
by subdividing mat... | 24eb6d1a0464a85daae4f4b50c691d4aa72b6b30 | 80,652 |
import sympy
def _lift_matrix_sympy(matrix, qubits, num_qubits):
"""A version of _lift_matrix working on Sympy matrices."""
return _lift_matrix(
matrix,
qubits,
num_qubits,
# sympy has different signature of `zeros` than numpy, hence the below adapter.
lambda size: symp... | 43052d4b112d3c418d2e73d5f1355788715d9d39 | 80,653 |
from pathlib import Path
def to_hmrc(instance: "Upload", filename: str):
"""Generate the filepath to upload to HMRC."""
return str(Path(settings.HMRC_STORAGE_DIRECTORY) / filename) | 7f72c0d87243207e5e34465cd229f4a1fb60a15a | 80,655 |
def calcular_ponto_de_fuga(img, equacoes):
"""
Recebe os coenficientes das retas e retornar o ponto de encontro entre elas. E desenha esse ponto na imagem.
"""
equation_1, equation_2, equation_3 = equacoes
m1, h1 = equation_1
m2, h2 = equation_2
m3, h3 = equation_3
y1 = int((h2 - h1)... | d810fb56d8044cb7ba18065ac1ed2b27bb50a1fb | 80,657 |
def variance(dat, timeaxis=-2):
"""Compute the variance along the ``timeaxis`` of ``dat``.
This method reduces the dimensions of `dat.data` by one.
Parameters
----------
dat : Data
Returns
-------
dat : Data
copy of ``dat`` with with the variance along the ``timeaxis``
... | 8fe8f665373b4a390a589875c5693d6ca1a83067 | 80,658 |
def build_json(image_content):
"""Builds a json string containing response from vision api."""
json_data = {
'requests': [{
'image': {
'content': image_content
},
'features': [{
'type': 'FACE_DETECTION',
'maxResults': 1,
}]
... | bf6f45187d2e6b2c4a50ccf7ecfbeeb862f353ff | 80,659 |
def get_task_option_info(task_config, task_class):
"""Gets the the following info for each option in the task
usage: example usage statement (i.e. -o name VALUE)
required: True/False
default: If a default value is present
description: Description string provided on the task option
option_type: A... | fb0a19c82ac43f2b8b12d5f39e3246bce102081e | 80,660 |
def sum_of_squares_error(y, t):
"""
(function) sum_of_squares_error
-------------------------------
The sum of squares error
Parameter
---------
- y : output value(s)
- t : target value(s)
Return
------
- error value between value(s)
"""
return 0.5 * np.sum((y - t) ... | 5cb6f208052ae4c90d9e046d5a78e414d585e514 | 80,661 |
def get_channel_axis():
"""Gets the channel axis."""
if K.image_data_format() == 'channels_first':
return 1
else:
return -1 | 03ac8963173a849514d5c1b90e7fdb14e32e19e2 | 80,662 |
from typing import Any
def ensure_TP(tp: Any) -> TP:
"""Convert aiokafka ``TopicPartition`` to Faust ``TP``."""
return tp if isinstance(tp, TP) else TP(tp.topic, tp.partition) | d6c63f4cd1c2b14c8f02239f892991f0d19f7959 | 80,663 |
from typing import Dict
from typing import Any
import httpx
async def async_basic_auth_request(method: str,
url: str,
token: str = None,
payload: Dict[str, Any] = None,
params: D... | 2d3108e758e501f86a8974cbc8df09cc63ba0f3b | 80,664 |
import configparser
def parse_setup_cfg(fp, cythonize=False, pkg_config=None, base_dir=''):
"""
Parse the cython specific bits in a setup.cfg file.
*fp* must be a file-like object opened for reading.
*pkg_config* may be a callable taking a list of library names and returning
a ``pkg-config`` lik... | d4c7ee18b1674cc09656791a56cb6ce6af626b78 | 80,665 |
def rotors_complete(species_index):
"""Function to check whether all of the Gaussian rotor jobs have finished running.
Looks at the run.sh script to find the highest rotor index, then searches each .log file
for Normal termination
"""
if incomplete_rotors(species_index):
return False
ret... | e3b6b517cb62875e19aecb7eca6c0a7ad6d2afda | 80,666 |
def get_embeddings(tokenizer, embed_name, embed_size, max_features):
"""Returns: embedding matrix n_words x embed_size
"""
assert embed_name in GLOVE_SETS, embed_name
embeddings_index = get_embeddings_index(embed_name, embed_size)
# Use these vectors to create our embedding matrix, with random init... | e8bd3c21e3af7df18869c76e79cef63056d2c682 | 80,667 |
def missing_summary(df):
"""
Takes in a dataframe and
returns a summary of all
missing values.
Parameters:
-----------
df : dataframe
Dataframe to calculate the
missing summary from.
Returns:
--------
df_miss : dataframe
Missing values s... | 4c6bb35e9d01827667d7b5ecbbc0b1ebcc8231bb | 80,668 |
def composite_bayer(r, g1, g2, b, cfa='rggb', output=None):
"""Composite an interleaved image from densely sampled bayer color planes.
Parameters
----------
r : `numpy.ndarray`
ndarray of shape (m, n)
g1 : `numpy.ndarray`
ndarray of shape (m, n)
g2 : `numpy.ndarray`
ndar... | e82264353565353ba202ff6ca15c8d9f0ed10ada | 80,670 |
def docker(function):
"""Decorator to set the global container type to docker"""
def wrapper(*args, **kwargs):
hpccm.config.g_ctype = container_type.DOCKER
return function(*args, **kwargs)
return wrapper | 878c7e022af8cf653b787f01a3dc66642064270d | 80,671 |
def check_word(word):
"""Checks that a given word is accepted or rejected by the LNFA."""
# This set contains all the possible states in which we currently are
current_states = lambda_closure(initial_state)
# Go through each character in the word
for symbol in word:
new_states = set()
... | 27bd3fb6f78bdc278553bf1fae9530442f9ccb5a | 80,672 |
def is_valid_pdb(ext):
""" Checks if is a valid PDB file """
formats = ['pdb']
return ext in formats | a2181b3cba5ced496af8f5dc5f3d9194e050887c | 80,673 |
import hashlib
def checksum(file, method='sha1', chunk_size=4096):
"""Calculate the checksum of a file.
Args:
file: str, path-like, or file-like bytes object
"""
try:
fh = open(file, 'rb')
except TypeError:
fh = file
try:
h = hashlib.new(method)
while ... | 9638985bec0c95d2c9cd30a93bf48f93381f99de | 80,674 |
import torch
def getVectorizedParams(net,device):
"""
obtain vectors of the running means, running variances, and parameters
use built-in parameters_to_vector approach
:param net: the network
:param device: retired/unused
:return: vector of the running means, vector of the running varian... | f6cde87125817efe00ece03de71519ae8b6d541d | 80,675 |
import re
def _recognize_character_icon(url: str):
"""Recognizes a character's icon url and returns its name."""
exp = r'https://upload-os-bbs.mihoyo.com/game_record/genshin/character_(?:.*)_(\w+)(?:@\dx)?.png'
match = re.fullmatch(exp,url)
if match is None:
return None
character = match.g... | 0cc3c349a890722a3e17c325182c2f56222f752f | 80,676 |
def update(store_id):
"""Updates a store. Returns the updated store instance."""
form = UpdateStoreForm()
if form.validate_on_submit():
return _stores.update(_stores.get_or_404(store_id), **request.json)
raise _app_upper_name_FormError(form.errors) | 93ec76abb8c1f4d958cd43cbb86f3ab688b9d207 | 80,677 |
def _read_bdf_global(instream):
"""Read global section of BDF file."""
# read global section
bdf_props = {}
x_props = {}
comments = []
parsing_x = False
nchars = -1
for line in instream:
line = line.strip('\r\n')
if not line:
continue
elif line.startsw... | 18afd0447bf25c46a89e118dde256a7d9f8f94b3 | 80,678 |
def readArrow():
"""
The usage of readchar gave problems between platofrm, and it was more complicated
to read the directional arrows. The correct function to read a key pressing is
readchar.readkey(), the function that I'm now using
"""
try:
value = readkey()
value = value.upper... | d4282ac0b0ce04d2468d52bf91f987a53f48622c | 80,679 |
def _get_cxx_inc_directories_impl(repository_ctx, cc, lang_is_cpp):
"""Compute the list of default C or C++ include directories."""
if lang_is_cpp:
lang = "c++"
else:
lang = "c"
result = repository_ctx.execute([cc, "-E", "-x" + lang, "-", "-v"])
index1 = result.stderr.find(_INC_DIR_M... | 0896d36582738ee86fb833e6e38152cdf781cab6 | 80,680 |
def grayToRGB(frame):
"""
project gray into Green
"""
# cv2.cvtColor(result, cv2.COLOR_GRAY2BGR))
result = np.zeros((frame.shape[0], frame.shape[1], 3))
if len(frame.shape) == 2:
result[:, :, 1] = frame
else:
summary = np.zeros((frame.shape[0], frame.shape[1]))
for... | 7b25bae1deabdd4276c10ea8c3e60af62c623820 | 80,681 |
def get_A_dash_door_0():
"""主開口方向から時計回りに0°の方向に面したドアの面積 (m2)
Args:
Returns:
float: 主開口方向から時計回りに0°の方向に面したドアの面積 (m2)
"""
return get_table_3(7, None) | fe867a9f4897184bd0f3acadeefb4c19fdb59718 | 80,684 |
def week(make_week):
"""Fixture creating a week."""
return make_week() | 52dda51ed415d75f966e302c930cc54119005307 | 80,686 |
from typing import Concatenate
def braid_group_rep_net(R_op,R_op_inv,input_shape=1):
"""
Purpose
-------
This is an axiluray network that is trained to force the relations on the input generators.
The network returns the sides of the relations of this algebraic structure.
Pa... | 42a89e7b7ed333567a109923c199790105f7782a | 80,687 |
def pagerank(adj, d=0.85, max_iter=500, tol=1.0e-4, verbose=False):
"""
Return the PageRank of the nodes in a graph using power iteration.
This funciton takes the sparse matrix as input directly, avoiding the overheads
of converting the network to a networkx Graph object and back.
Input:
ad... | 2ff30c855894268d33867b4b7044d4386f8f1b45 | 80,688 |
def get_topics_for_song(topic_model: LatentDirichletAllocation, transformed_lyrics: list, song_index: int,
data: pd.DataFrame):
"""
For a given song's LDA transformed vector, returns the most relevant topic indexes
"""
topic_relevancy = transformed_lyrics[song_index]
sorted... | e69b37438835b0fbc92d73cb8c47b6161ccf0898 | 80,690 |
def randomWalkFromCSC(csc_matrix,
n_steps=10, starting_node=None, restart_rate=0):
"""
This method produces an index trajectory on a graph by random walk,
when the adjacency matrix is given in Compressed Sparse Column (CSC)
Matrix format as implemented by scipy.
The trajectory ... | 605e8226be7496da007656dab9279ab20ebcc781 | 80,691 |
def tf_score(word, sentence):
"""
Formula:
Number of times term w appears in a document) / (Total number of terms in the document).
"""
word_frequency_in_sentence = 0
len_sentence = len(sentence)
for word_in_sentence in sentence.split():
if word == word_in_sentence:
word_... | e93efbd52dfcdf05f771ab4d3f353e3f837dda96 | 80,693 |
def main():
"""Computational pathology toolbox by TIA Centre."""
return 0 | 7a0c5a83b018860f683407bd9517d4d28b1c2443 | 80,694 |
def est_cell_counts_IDOL(rgset,library):
"""Given RGSet object, estimate cell counts for 450k/850k using reference approach via IDOL library.
Parameters
----------
rgset
RGSet object stored in python via rpy2
library
What type of CpG library to use."""
robjects.r('library(FlowSo... | 1b2436a333e52ab6ca004c175d7f21e8587ed682 | 80,695 |
from typing import Union
def apply_calibration(visibilities: np.ndarray, station_name: str, rcu_mode: Union[str, int],
subband: int, caltable_dir: str = "CalTables"):
"""
Apply calibration to visibilities
Args:
visibilities (np.ndarray): Visibility cube
station_name ... | bd58f1d6ee5ed9e8a8d84321e548d41e5387b4ea | 80,696 |
def misc_item_list(fn):
"""
Decorator to set up misc items list
.. versionadded:: 0.10
"""
def misc_item_setup(*args, **kwargs):
"""
Setup misc items list
"""
context = args[0]
if not hasattr(context, 'misc_item_list'):
context.misc_item_list = {... | 368dc0f4c51e9665842c4bb3045a3180a64b4761 | 80,697 |
def overlay_class_names(image, predictions):
"""
Adds detected class names and scores in the positions defined by the
top-left corner of the predicted bounding box
Arguments:
image (np.ndarray): an image as returned by OpenCV
predictions (BoxList): the result of the computation by the m... | af837b0fee1a6894be28662c496de62ddc75e5f7 | 80,698 |
import html
def _pick_fields(form):
"""Return the most likely field names for username and password"""
userfield = passfield = emailfield = None
for x in form.inputs:
if not isinstance(x, html.InputElement):
continue
type_ = x.type
if type_ == 'password' and passfield ... | ce73b63d79887fb04b4790ba0b99658f0b751996 | 80,699 |
def concrete_dropout(incoming, mc, n_filters = None, temperature=0.02, epsilon=1e-7, use_expectation=True, name='concrete_dropout'):
""" Concrete Dropout.
Outputs the input element multiplied by a random variable sampled from a concrete distribution
Arguments:
incoming : A `Tensor`. The incoming ten... | 0bd0784fe0161529a5623d48744dbe257a92743c | 80,701 |
def generate_costs(scenario, treatment_options, option):
""" Generate costs graph """
data_traces = []
for treatment in treatment_options:
dt = pd.DataFrame()
hc = costs.loc[
(costs["treatment"] == treatment)
& (costs["scenario"] == scenario)
& (costs["mo... | 2adc9591ea86a18a827ec83a23044a7966a3aa21 | 80,702 |
def cors_allow_xblock_handler(sender, request, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
Sandboxed XBlocks need to be able to call XBlock handlers via POST,
from a different domain. See 'xblock_handler' method for details and how security is
enforced.
Per the corsheaders docs, ... | f12a2f10df6c541c9db200a82137bca45cced7c4 | 80,703 |
from datetime import datetime
def _add_years(d, years):
"""Return a date that's `years` years after the date (or datetime)
object `d`. Return the same calendar date (month and day) in the
destination year, if it exists, otherwise use the following day
(thus changing February 29 to March 1).
"""
... | 96ba913c54bfd052147ed2bd4378c8a42659e708 | 80,704 |
from typing import List
def apply(text_to_encrypt: str, cipher: str, alphabets: List[str]) -> str:
"""Encrypts text with the provided cipher.
Args:
text_to_encrypt (str): [description]
cipher (str): [description]
Returns:
str: [description]
"""
cipher_dict, _ = create_cip... | 9a95714e37efa2fa6fd0a77cf5b2678577ffdfaa | 80,705 |
def _get_capsule(capsule_ident):
"""Get capsule by name or UUID"""
capsule = api_utils.get_resource('Capsule', capsule_ident)
if not capsule:
pecan.abort(404, ('Not found; the capsule you requested '
'does not exist.'))
return capsule | 96c5875316aabfe11b8df06cad94451ada3f75c8 | 80,706 |
def get_primes_from_2_to(n_):
""" Input n>=6, Returns a array of primes, 2 <= p <= n """
n_ += 1
sieve = np.ones(n_//3 + (n_%6==2), dtype=np.bool)
for i in range(1,int(n_**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k//3 ::2*k] = False
sieve[k*(k-2*(... | 20c104f575ff9a1ac942f49f3d430b73edc19c6c | 80,707 |
import requests
def get_json(url, params):
"""获取网页中json数据"""
r = requests.get(url, params=params)
return r.json() | e0245871bb334cd83080c39f7d4c0c38db730205 | 80,708 |
def add_dimension():
"""
Adds a new named dimension to the data cube.
Returns
-------
data cube :
The data cube with a newly added dimension. The new dimension has exactly one dimension label.
All other dimensions remain unchanged.
"""
return AddDimension() | 460cb7f73e113414df89860acdc5a9f649f4b397 | 80,709 |
def redirect(to, permanent=False, anchor=None, **kwargs):
"""
Returns a redirect response by applying funfactory's locale-aware reverse
to the given string.
Pass in permanent=True to return a permanent redirect. All other keyword
arguments are passed to reverse.
"""
if permanent:
re... | c2ca3047b5a7f7d7a5fc2708d6375df999d85f00 | 80,710 |
def check_existance(account_type):
"""
Function for checking if an account exists using account tpe name.
"""
return Credentials.credentials_exists(account_type) | 8bec63b0cf9d656fcc17bc9c79a0822a840f2d00 | 80,711 |
def pad_batch(batch, pad_id, neox_args):
"""
pads context lengths in batch with pad_id to equal neox_args.seq_length,
and returns the padded batch and the new lengths.
batch: torch.Tensor of tokens
pad_id: int, integer to use as padding token
neox_args: neox_args
"""
context_lengths = ... | 4d2b4630c5a84e1eaa7e0e05a45b8cfcd0d9fae8 | 80,712 |
def __max_successive_series_len(arr, asc=True, eq=False):
"""
寻找最大连续子序列,子序列的下标必须是相连的
例如, 1,2,3 返回3
@param arr:
@param asc:
@param eq:
@return:
"""
max_area_len = 0
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if asc and (arr[j] > arr[j - 1]):
... | 3ddd09a663c493eea0eed367d5a7c98ca3963acc | 80,714 |
def _generate_type_config(configs, old_copyright_heads, new_copyright, update_template_file):
"""Generate complete configuration for easy use.
Args:
configs: `list of dict`, original type config
old_copyright_heads: `list of str`, old copyright first line
new_copyright: `str`, new copyr... | e55797d7ef0060d0eed4033794dbab6c62fb3107 | 80,715 |
def slugify(text, separator='_'):
"""Implements a stable slugify function over python-slugify, unicode-slugify, or awesome-slugify
"""
try:
# Preferred: python-slugify (https://github.com/un33k/python-slugify)
# [This usage also works for awesome-slugify (https://github.com/voronind/awesome-... | 3d5b2fefc91196ec2bcf447ce1282bfaa269c549 | 80,716 |
def color_txt(txt: str, color: BColors) -> str:
"""Color some text."""
return f"{color.value}{txt}{BColors.ENDC.value}" | 3231d87aa58f37dc1f2f6e5412a256268a618293 | 80,717 |
def get_loss_fn():
"""Returns loss function for BERT pretraining."""
def _bert_pretrain_loss_fn(unused_labels, losses, **unused_args):
return tf.reduce_mean(losses)
return _bert_pretrain_loss_fn | 50c54500832ca07eeb5649828d37596be67c571c | 80,719 |
def inference(bmodel_path, input_path, loops, tpu_id, compare_path):
""" Do inference of a model in a thread.
Args:
bmodel_path: Path to bmodel
input_path: Path to input image.
loops: Number of loops to run
compare_path: Path to correct result file
status: Status of comparison
Returns:
T... | f3ba222e5755b92576a36fa6b629c07616de847c | 80,720 |
def weibull_data(par_id, months, lon, lat):
"""Returns an array parameter season mean and their cumulative probability estimate."""
df = data_load_or_extract(par_id, lon, lat)
return df.groupby(by=lambda ts: ts.year).max()[1].values | 743bfab50682c72d9059353bce896a1e33ff8abe | 80,721 |
def grad_rms(grad):
"""
Compute the root-mean-square of the gradient.
Args:
grad (Gradient)
Returns:
rms (float)
"""
n = len(grad.layers) + len(grad.weights)
tensor_mean_square = compose(be.mean, be.square)
return sqrt(grad_accumulate(tensor_mean_square, grad) / n) | 835224b95bf4ca1f16438fd952823fe6315afcfd | 80,722 |
import logging
def twitter_auth():
""" 連携アプリ認証用URLにリダイレクト """
# tweepy でアプリのOAuth認証を行う
auth = tweepy.OAuthHandler(current_app.config["CONSUMER_KEY"], \
current_app.config["CONSUMER_SECRET"], current_app.config["CALLBACK_URL"])
try:
# 連携アプリ認証用の URL を取得
redirect_url = auth.get_a... | 2a5d0ee514bbb6b5621abb5215c76422576c0ad6 | 80,724 |
def is_bgp_import_path_selection(
device, vrf, selection_type, max_time=30, check_interval=10
):
""" Verifies that import path selection of type is in running
config
Args:
device('obj'): device to use
vrf('str'): vrf name
selection_type('str'): import path se... | 9c7e878ff0b422777e88904fe65f4dc0c9ca9ed3 | 80,725 |
import warnings
from typing import Pattern
def _data_checks_pivot_longer(
df, index, column_names, names_sep, names_pattern, names_to, values_to
):
"""
This function raises errors or warnings if the arguments have the wrong
python type, or if an unneeded argument is provided.
This function is exe... | 3a992396177aad338f0022d10065b25b90106212 | 80,726 |
def data_var_chunks(data_vars):
""" Returns a {dim: chunks} dictionary constructed from `data_vars` """
chunks = {}
for k, var in data_vars.items():
if not isinstance(var.data, da.Array):
continue
for d, c in zip(var.dims, var.chunks):
if d in chunks and c != chunks... | c3eeaaf46b1120395b02eee7f865c71196bce6fb | 80,727 |
def children_container_to_data(cc):
"""
returns the given children container as data
"""
return dict(
children_container_key=children_container_to_str(cc.__class__),
children_container_data=cc.to_data(),
) | d9b2aecceb189f2ccb95d2b36164b82779f248d1 | 80,728 |
def reverse_edges(edges):
"""Reverses direction of dependence dict.
Parameters
----------
edges : dict
Dict of the form {a: {b, c}, b: set(), c: set()} where b and c depend
on a.
Returns
-------
Dict of the form {a: set(), b: {a}, c: {a}} where b and c depend on a.
Exa... | d0de015c2b26f6ba211009b6d7bef4c9a9750baf | 80,729 |
def user_edit(request):
"""
Handles the post data for editing user's profile
and displays a form if get request is obtained
"""
if request.method == 'POST':
user_form = UserEditForm(instance=request.user, data=request.POST)
profile_form = UserProfileEditForm(instance=request.user.use... | 0fc06fc64371f62209fe4ea3a4f1384d8d377dea | 80,730 |
from pathlib import Path
def parse_ply(filepath: Path) -> PlyFile:
"""
Parse the provided PLY file into its relevant components (header, vertices, faces).
The PLY file is assumed to be of the form:
<header line(s)>
element vertex <n_vertices>
<header line(s)>
end_header
... | 789c87d0aa4d71e956612cccbba2172b2753df80 | 80,731 |
import random
import torch
def set_seed(seed):
"""
Set random seed for all relevant randomisation tools.
Parameters
----------
seed : int
Random seed value
Returns
-------
None
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.m... | a080c91e216d8440a60872554efb0b0c6e1e93cf | 80,732 |
def in_memory_mask(data):
"""
Creates an `ImageRef` object with that embeds an in memory
(i.e., not attached to a file) ``HDUList`` containing the supplied mask
data.
Parameters
----------
data: numpy.ndarray
Data to be used to create an in-memory FITS file. Data will be
wr... | 84edc619440ab53bf7c9be131d16e2f14fc694d3 | 80,733 |
def mock_resources_with_data(
minimal_labware_def: LabwareDefinition,
mock_resources: AsyncMock,
) -> AsyncMock:
"""Get a mock in the shape of the LabwareDataProvider primed with data."""
mock_resources.labware_data.get_labware_definition.return_value = (
minimal_labware_def
)
mock_resou... | 60b0b6fa2b73fa2760526a67e3eabe5f0c12d50e | 80,734 |
from typing import List
from typing import Mapping
def solve(proposition: str, mappings: List[Mapping] = None) -> List[Mapping]:
"""Find all solutions for given proposition.
Attempt to find solutions for the proposition after parsing and
simplification.
Args:
proposition: Propositional logic... | 28819b4e500ac8609e7c653ac3237999b5e474e2 | 80,736 |
def get_range(value):
"""
Filter - returns a list containing range made from given value.
Usage (in template):
<ul>{% for i in 3|get_range %}
<li>{{ i }}. Do something</li>
{% endfor %}</ul>
Results with the HTML:
<ul>
<li>0. Do something</li>
<li>1. Do something</... | 8f6b0a465ca98b425117aed2c2ae708032be1112 | 80,737 |
def _get_command_line_argument_type(
command: kfp_component_spec_pb2.StringOrPlaceholder
) -> placeholders.CommandlineArgumentType:
"""Converts a container command to the corresponding type.
Args:
command: StringOrPlaceholder which encodes a container command.
Returns:
command to be passed into crea... | ae9509ee1e8fa8deaf238185b98655f63ec859e7 | 80,738 |
def crop_faces(image):
"""
:param image: Картинка (cv2.imread())
:return: Лист со всеми лицами на фото(В том числе и перевернутые)
"""
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # конвертируем изображение в RGB
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # делаем изображение ЧБ
f... | d01ac95b3cd91b51c36d5630e756ca689f80ee51 | 80,739 |
from typing import Optional
def check_for_nans(event_series: EventSeries, start_step: int) -> Optional[int]:
"""Finds step >= start_step at which first NaN value occurs if there are any.
Args:
event_series: list of tuples (step, value).
start_step: After which step to check for NaNs.
Returns:
Step... | 11eb2b52f8169e4e416d60ffc3b9d8e761ddd7ee | 80,740 |
def get_gain_index(trend,seasonality,model,real_values):
"""This method takes as input the trend, seasonality the model type
as well as the real values of the time series and calculates the gain
index. The gain index expresses the contribution of the seasonality to the actual time series.
In order... | 692f6feedbb131958350790e270d2ccee5c1ce56 | 80,741 |
import random
def noise_seed():
"""
Generate a random seed for NoiseSource.block().
"""
return random.randint(0, 2**32 - 1) | caf4ed6117dd542c042be1499ee8d58af2662c9c | 80,742 |
def register_rigid(atlas, img, learning_rate=1e-2, iters=200, min_step=1e-10, shrink_factors=None, sigmas=None, use_mi=False, grad_tol=1e-6, verbose=False):
"""
Performs affine registration between an atlas an an image given that they have the same spacing.
"""
if shrink_factors == None: shrink_factors ... | 636a65c3cd3f05fe127ddea735861f9bf18ae960 | 80,743 |
from typing import Optional
from typing import Union
from pathlib import Path
def resolve_dir(trainer: pl.Trainer, dirpath: Optional[Union[str, Path]], suffix: str):
"""
Determines tensor save directory at runtime. References attributes from the
trainer's logger to determine where to save checkpoints.
... | 9adbb6e43cbe6c3881bdded5132bb0629646f328 | 80,744 |
def make_colorbar(im, ax, label=None, fontsize=14, *args, **kwargs):
"""
"""
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = plt.colorbar(im, cax=cax, *args, **kwargs)
if label:
cbar.set_label(label, fontsize=fontsize)
return ax, cbar | 9ff64a539ea66bb3063864f74469dcd250b73314 | 80,745 |
import typing
def render_error(
project: 'projects.Project',
error: Exception,
stack: typing.List[dict] = None
) -> dict:
"""
Renders an Exception to an error response that includes rendered text and
html error messages for display.
:param project:
Currently open proje... | 4a4f12617fd615c4d8c1c87b15f8c960f50b6094 | 80,746 |
def s3_bucket_and_key_from_url(s3_url):
"""
Raises:
ValueError
"""
parts = urlparse(s3_url)
# parts.path[1:] drops the leading slash that urlparse includes
return (parts.netloc, parts.path[1:]) | eefcb7a799b168ed9da09260b9233eda5bd44c03 | 80,747 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.