content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def find_possible_words(word: str, dictionary: list) -> list:
"""Return all possible words from word."""
possible_words = []
first_character = word[0]
last_character = word[len(word) - 1]
for dictionary_entry in dictionary:
if (dictionary_entry.startswith(first_character) and
... | a3e63e6b6b9d8de3ca718cfc8e031bbc34630d50 | 3,637,267 |
def diag_multidim_gaussian_log_likelihood(z_u, mean_u, logvar_u, varmin):
"""Log-likelhood under a multidimensional Gaussian distribution with diagonal covariance.
Returns the log-likelihood for the multidim distribution.
"""
return np.sum(diag_gaussian_log_likelihood(z_u, mean_u, logvar_u, varmin), axis=0) | 010b1f510a74b2af29fe0cc94a2c36bc9c980778 | 3,637,268 |
def get_method(java_object, method_name):
"""Retrieves a reference to the method of an object.
This function is useful when `auto_field=true` and an instance field has
the same name as a method. The full signature of the method is not
required: it is determined when the method is called.
:param ja... | 9678cf38bfcf8dd34d6ccbad9b689709e9ab3dc5 | 3,637,270 |
def set_up_cube(
zero_point_indices=((0, 0, 7, 7),),
num_time_points=1,
num_grid_points=16,
num_realization_points=1,
):
"""Set up a cube with equal intervals along the x and y axis."""
zero_point_indices = list(zero_point_indices)
for index, indices in enumerate(zero_point_indices):
... | d19380e0cc7471178887ea006fa4f367461dac4d | 3,637,272 |
def messageBox(self, title, text, icon=QMessageBox.Information):
"""
Working on generic message box
"""
m = QMessageBox(self)
m.setWindowTitle(title)
m.setText(text)
m.setIcon(icon)
# yesButton = m.addButton('Yes', QMessageBox.ButtonRole.YesRole)
# noButton = m.addButton('No', QMess... | 7bec2d2f0ca1366382d5bfc800c23af424d9a3d3 | 3,637,273 |
def binary_seg_loss(loss):
"""
Chooses the binary segmentation loss to use depending on the loss name in parameter
:param loss: the type of loss to use
"""
if loss == 'focal':
return BinaryFocalLoss()
else:
return tf.keras.losses.BinaryCrossentropy() | 9d94a7e406a2fa1a12ba970731c7ce25b2408b21 | 3,637,274 |
def get_config_file():
""" Return the loaded config file if one exists. """
# config will be created here if we can't find one
new_config_path = os.path.expanduser('~/dagobahd.yml')
config_dirs = ['/etc',
os.path.expanduser('~/dagobah/dagobah/daemon/')]
config_filenames = ['dago... | 4a5009d5d6f5a4be6d953d7bc9150c033a56f187 | 3,637,275 |
def bostock_cat_colors(color_sets = ["set3"]):
"""
Get almost as many categorical colors as you please.
Get more than one of the color brewer sets with ['set1' , 'set2']
Parameters
----------
sets : list
list of color sets to return valid options are
(set1, set2, set3, paste... | d01a2c833c3ee4ab1a196184ec4aecdb6cfc97a0 | 3,637,276 |
def bbpssw_gates_and_measurement_bob(q1, q2):
"""
Performs the gates and measurements for Bob's side of the BBPSSW protocol
:param q1: Bob's qubit from the first entangled pair
:param q2: Bob's qubit from the second entangled pair
:return: Integer 0/1 indicating Bob's measurement outcome
"""
... | 71e981a99065ea2b0d76a2ebaacebdf04b53488a | 3,637,277 |
from typing import Tuple
def fiber_array(
n: int = 8,
pitch: float = 127.0,
core_diameter: float = 10,
cladding_diameter: float = 125,
layer_core: Tuple[int, int] = gf.LAYER.WG,
layer_cladding: Tuple[int, int] = gf.LAYER.WGCLAD,
) -> Component:
"""Returns a fiber array
.. code::
... | 88bf1536788313c99f6b3c56ce8633db8cc30b8b | 3,637,278 |
def delete(movie_id):
"""
deletes the movie from the database
:param movie_id: id to delete
:return: index file
"""
movie_to_delete_id = Movie.query.get(movie_id)
db_session.delete(movie_to_delete_id)
db_session.commit()
return redirect(url_for('home')) | cfaade7b63e4d4413b7593a667fe62d5de90eaad | 3,637,279 |
import torch
def one_vector_block_diagonal(num_blocks: int, vector_length: int) -> Tensor:
"""Computes a block diagonal matrix with column vectors of ones as blocks.
Associated with the mathematical symbol :math:`E`.
Example:
::
one_vector_block_diagonal(3, 2) == tensor([
... | babe3e8178f3d9cde9150909fbf890ae17830730 | 3,637,280 |
def get_cli_args():
"""
:return: argparse.Namespace with command-line arguments from user
"""
args = get_main_pipeline_arg_names().difference({
'output', 'ses', 'subject', 'task', WRAPPER_LOC[2:].replace('-', '_')
})
tasks = ('SST', 'MID', 'nback')
parser = get_pipeline_cli_argparser... | d728c1254ffcfdeb2ba883681dd997d578084e72 | 3,637,281 |
from google.cloud import securitycenter
def list_all_assets(organization_id):
"""Demonstrate listing and printing all assets."""
i = 0
# [START securitycenter_list_all_assets]
client = securitycenter.SecurityCenterClient()
# organization_id is the numeric ID of the organization.
# organizatio... | 882672c91e8a698730532e1e7801aba0d5ec7d05 | 3,637,282 |
def _0_to_empty_str(dataframe: pd.DataFrame, column_data_type: dict):
"""
데이터가 str인 column에 들어있는 0을 '' 로 바꾸어 준다.
column_data_type 에서 value가 'str' 인 column 만 바꾸어 준다.
"""
for column, datatype in column_data_type.items():
if datatype == "str":
dataframe[column].replace("0", "", inpl... | 2453b53c0e7a0067772f37d9d8c370b8accb933c | 3,637,283 |
def _predict(rel):
"""
Predicts the betrayal probabilities and returns them as an inference.Output object.
"""
return inference.predict(rel) | c3b0489bef0723012f1de336dad5f61c40d77c7e | 3,637,284 |
from datetime import datetime
def evaluate_exams(request, exam_id):
"""
Request-Methods :POST
Request-Headers : Authorization Token
Request-Body: Student-Solution -> JSON
Response: "student_name" -> str,
"teacher_name" -> str,
"batch" -> str,
"mark... | 688cf2cd43991c98475fb7921ad64fccd0ea2b36 | 3,637,285 |
def _accumulated_penalty_energy_fw(energy_to_track, penalty_matrix, parallel):
"""Calculates acummulated penalty in forward direction (t=0...end).
`energy_to_track`: squared abs time-frequency transform
`penalty_matrix`: pre-calculated penalty for all potential jumps between
two frequ... | cc05de06ab53a9dcf7937df8bc6c5613a649b01c | 3,637,286 |
def rot90(m, k=1, axis=2):
"""Rotate an array k*90 degrees in the counter-clockwise direction
around the given axis
This differs from np's rot90 because it's 3D
"""
m = np.swapaxes(m, 2, axis)
m = np.rot90(m, k)
m = np.swapaxes(m, 2, axis)
return m | 40bb5c4406e8f7a1f4f6019c56d1a734bee0eac6 | 3,637,287 |
def get_pads(onnx_node): # type: (NodeWrapper) -> Tuple[int, int, int]
"""
Get padding values for the operation described by an ONNX node.
If `auto_pad` attribute is specified as SAME_UPPER or SAME_LOWER, or VALID values are
calculated. Otherwise values are taken from the `pads` attribute.
`pads`... | 9199129f59c3f459dfbad209427f4dcb8b5863e7 | 3,637,288 |
def from_dict(transforms):
"""Deserializes the transformations stored in a dict.
Supports deserialization of Streams only.
Parameters
----------
transforms : dict
Transforms
Returns
-------
out : solt.core.Stream
An instance of solt.core.Stream.
"""
if not... | bf09deac48819306a7fef9b98cd68775f3d9bcbd | 3,637,290 |
def create_mp_pool(nproc=None):
"""Creates a multiprocessing pool of processes.
Arguments
---------
nproc : int, optional
number of processors to use. Defaults to number of available CPUs
minus 2.
"""
n_cpu = pathos.multiprocessing.cpu_count()
if nproc is None:
... | 37b750fb961535eada1924f524a4ec851ad7d613 | 3,637,291 |
def subpixel_edges(img, threshold, iters, order):
"""
Detects subpixel features for each pixel belonging to an edge in `img`.
The subpixel edge detection used the method published in the following paper:
"Accurate Subpixel Edge Location Based on Partial Area Effect"
http://www.sciencedirect.com/sci... | 546a8d1aedd1c53a329ce7a6e600307cf85b70a4 | 3,637,292 |
import numbers
import numpy
def arrays(hyperchunks, array_count):
"""Iterate over the arrays in a set of hyperchunks."""
class Attribute(object):
def __init__(self, expression, hyperslices):
self._expression = expression
self._hyperslices = hyperslices
@property
def expression(self):
... | 0b4e8833b1dd0f7cf90ed1fc97dbc77d76e29e17 | 3,637,293 |
from typing import Union
import torch
import types
def ne(x: Union[DNDarray, float, int], y: Union[DNDarray, float, int]) -> DNDarray:
"""
Returns a :class:`~heat.core.dndarray.DNDarray` containing the results of element-wise rich comparison of non-equality between values from two operands, commutative.
T... | f948f586781fb6c841a576b19defe2dff388469b | 3,637,294 |
def _quote_embedded_quotes(text):
"""
Replace any embedded quotes with two quotes.
:param text: the text to quote
:return: the quoted text
"""
result = text
if '\'' in text:
result = result.replace('\'', '\'\'')
if '"' in text:
result = result.replace('"', '""')
ret... | 71231e590e025c2ceb7b2dd4fde4465a9ff61a4c | 3,637,295 |
def exp2(x):
"""Calculate 2**x"""
return 2 ** x | d76d1e344e79ebb05d38a2e7e6ef36b6f367e85b | 3,637,296 |
import json
from typing import Generator
def play():
"""Play page."""
ticket_name = request.cookies.get('ticket_name')
ticket = None
game = get_game()
new_ticket = True
if ticket_name:
ticket = Ticket.get_by_name(ticket_name)
new_ticket = ticket and ticket.game != game.id
... | 75dd74a843c60d7eea2f1f2ffd08febbabbf5d41 | 3,637,297 |
def count_search_results(idx, typ, query, date_range, exclude_distributions,
exclude_article_types):
"""Count the number of results for a query
"""
q = create_query(query, date_range, exclude_distributions,
exclude_article_types)
#print q
return _es().... | b53742010645fc363abca8ddad5a15c7268ff49b | 3,637,298 |
def ifft(data: np.ndarray) -> np.ndarray:
"""
Perform inverse discrete Fast Fourier transform of data by conjugating signal.
Arguments:
data: frequency data to be transformed (np.array, shape=(n,), dtype='float64')
Return:
result: Inverse transformed data
"""
n = len(data)
result =... | 540ed47b2c7c4085609a9f94dba469c2b3a32d7a | 3,637,299 |
def archived_minute(dataSet, year, month, day, hour, minute):
"""
Input: a dataset and specific minute
Output: a list of ride details at that minute or -1 if no ride during that minute
"""
year = str(year)
month = str(month)
day = str(day)
#Converts hour and minute into 2 digit integers (that are strings)
ho... | e550cb8ae5fbcfcc2a0b718dc2e4f3372f100015 | 3,637,300 |
def Rq(theta, vect):
"""Returns a 3x3 matrix representing a rotation of angle theta about vect
axis.
Parameters
----------
theta: float, rotation angle in radian
vect: list of float or array, vector about which the rotation happens
"""
I = np.matrix(np.identity(3))
... | 069ef6568df170179a728b59dfb6a03dca0fbb75 | 3,637,301 |
def ExpsMaintPol():
"""Maintenance expense per policy"""
return asmp.ExpsMaintPol.match(prod, polt, gen).value | 778d77d860378deeceee33e20a996e667430f851 | 3,637,302 |
def inputRead(c, inps):
"""
Reads the tokens in the input channels (Queues) given by the list inps
using the token rates defined by the list c.
It outputs a list where each element is a list of the read tokens.
Parameters
----------
c : [int]
List of token consumption rates.
inp... | ea70548f7da4fae66fe5196734bbf39deb255537 | 3,637,303 |
def _split_schema_abstract(s):
"""
split the schema abstract into fields
>>> _split_schema_abstract("a b c")
['a', 'b', 'c']
>>> _split_schema_abstract("a(a b)")
['a(a b)']
>>> _split_schema_abstract("a b[] c{a b}")
['a', 'b[]', 'c{a b}']
>>> _split_schema_abstract(" ")
[]
... | ba1fba44979074b34adf87173a1277c212bd93e8 | 3,637,304 |
def myfn(n):
"""打印hello world
每隔一秒打印一个hello world,共n次
"""
if n == 1:
print("hello world!")
return
else:
print("hello world!")
return myfn(n - 1) | 4405e8b4c591c435d43156283c0d8e2aa9860055 | 3,637,305 |
def name(ea, **flags):
"""Return the name defined at the address specified by `ea`.
If `flags` is specified, then use the specified value as the flags.
"""
ea = interface.address.inside(ea)
# figure out what default flags to use
fn = idaapi.get_func(ea)
# figure out which name function to... | 7c0d938f5f4112f08749e1f412403d0da7ebf4d1 | 3,637,306 |
def estimate_distance(
row: pd.DataFrame,
agent_x: float,
agent_y: float
):
"""
Side function to estimate distance
from AGENT to the other vehicles
This function should be applied by row
Args:
row: (pd.DataFrame)
agent_x: (float) x coordinate of agent
... | c6d3dd9dbdcdde06baea95c8e0e56794d80aa0de | 3,637,307 |
from .plot_methods import plot_spinpol_bands
from .bokeh_plots import bokeh_spinpol_bands
def spinpol_bands(kpath, eigenvalues_up, eigenvalues_dn, backend=None, data=None, **kwargs):
"""
Plot the provided data for a bandstructure (spin-polarized)
Non-weighted, weighted, as a line plot or scatter plot,
... | 60df91e2a06b4ff2e943efebc4ff936fb55164dd | 3,637,308 |
def valid_config_and_get_dates():
"""
校验配置文件的参数,并返回配置文件的预约疫苗日期
:return:
"""
if config.global_config.getConfigSection("cookie") == "":
raise Exception("请先配置登陆后的 cookie,查看方式请查看 README.MD")
if config.global_config.getConfigSection("date") == "":
raise Exception("请先配置登陆后的 预约日期")
... | 42310c1fa60331e2ae238f4c6ab5ab23940536b3 | 3,637,309 |
import requests
def check_internet_connection():
"""Checks if there is a working internet connection."""
url = 'http://www.google.com/'
timeout = 5
try:
_ = requests.get(url, timeout=timeout)
return True
except requests.ConnectionError as e:
return False
return False | 5f587e6077377196d2c89b39f5be5d6a2747e093 | 3,637,310 |
def wall_filter(points, img):
"""
Filters away points that are inside walls. Works by checking where the refractive index is not 1.
"""
deletion_mask = img[points[:, 0], points[:, 1]] != 1
filtered_points = points[~deletion_mask]
return filtered_points | 05a34602e8a555eb1f1739f5de910a71514a92ae | 3,637,311 |
import requests
def navigateResults(results):
"""Navigate all links, returning a list contaning the ulrs and corresponding pages.
results:[String] - List with links to be visited
Return: {list}[{tuple}({String}url, {String}content)]"""
global BASE_ADDR
ret = []
for i in results:
... | 566da85528c7af46b29076c2b96eaf90f083becc | 3,637,312 |
def _get_matching_signature(oper, args):
""" Search the first operation signature matched by a list of arguments
Args:
oper: Operation where searching signature
args: Candidate list of argument expressions
Returns:
Matching signature, None if not found
"""
# Search correspon... | 21efb39c19f664ba0d79bcdbd1ab042bcaafffce | 3,637,313 |
def format_size(num: int) -> str:
"""Format byte-sizes.
:param num: Size given as number of bytes.
.. seealso:: http://stackoverflow.com/a/1094933
"""
for x in ['bytes', 'KB', 'MB', 'GB']:
if num < 1024.0 and num > -1024.0:
return "%3.1f%s" % (num, x)
num /= 1024.0
... | 349649fc1ee6069b2cfba1ac8aa3745aafc9c7fc | 3,637,314 |
def hub_payload(hub):
"""Create response payload for a hub."""
if hasattr(hub, "librarySectionID"):
media_content_id = f"{HUB_PREFIX}{hub.librarySectionID}:{hub.hubIdentifier}"
else:
media_content_id = f"{HUB_PREFIX}server:{hub.hubIdentifier}"
payload = {
"title": hub.title,
... | e446ea607db6a665c94fab774ef46db70e1ed76f | 3,637,315 |
def roq_transform(pressure, loading):
"""Rouquerol transform function."""
return loading * (1 - pressure) | b69d83579cdb904cc7e3625a371e1f6c0573e44b | 3,637,316 |
def _cms_inmem(file_names):
"""
Computes mean and image_classification deviation in an offline fashion. This is possible only when the dataset can
be allocated in memory.
Parameters
----------
file_names: List of String
List of file names of the dataset
Returns
-------
mean ... | 88f856bbe33ec0e819b81dc7f5ad5930db45beea | 3,637,317 |
def ddphi_spherical_zm (dd, ps_zm, r_e, lat, time_chunk=None ):
"""
This function calculates the gradient in meridional direction in a spherical system
It takes and returns xarray.DataArrays
inputs:
dd data xarray.DataArray with (latitude, time, level) or (latitude, time), or combinations... | 5cae237e3a1dc9646a0a288a6164880c482a82be | 3,637,318 |
def precompute_dgmatrix(set_gm_minmax,res=0.1,adopt=True):
"""Precomputing MODIT GRID MATRIX for normalized GammaL
Args:
set_gm_minmax: set of gm_minmax for different parameters [Nsample, Nlayers, 2], 2=min,max
res: grid resolution. res=0.1 (defaut) means a grid point per digit
adopt: i... | b007c4ec9f1aec9af364abc40ed903e9db66482c | 3,637,320 |
def get_image_urls(ids):
"""function to map ids to image URLS"""
return [f"http://127.0.0.1:8000/{id}" for id in ids] | a70cd4eea39ea277c82ccffac2e9b7d68dd7c801 | 3,637,321 |
def partition(n: int) -> int:
"""Pure Python partition function, ported to Python from SageMath.
A000041 implemented by Peter Luschny.
@CachedFunction
def A000041(n):
if n == 0: return 1
S = 0; J = n-1; k = 2
while 0 <= J:
T = A000041(J)
S = S+T if is_odd(k//2) else S-T
... | e30279029e8fd3ec012020fcf9e088822577e3d3 | 3,637,322 |
def port_to_host_int(port: int) -> int:
"""Function to convert a port from network byte order to little endian
Args:
port (int): the big endian port to be converted
Returns:
int: the little endian representation of the port
"""
return ntohs(port) | 69506efe702826ca55e013cfe7f064c61994beb9 | 3,637,323 |
def inv_median(a):
"""
Inverse of the median of array a.
This can be used as the `scale` argument of
ccdproc.combine when combining flat frames.
See CCD Data Reduction Guide Sect. 4.3.1
"""
return 1 / np.median(a) | 3612b6b334781c44677c3be91d876b69ec6cd6d3 | 3,637,324 |
def mpdisted(dask_client, T_A, T_B, m, percentage=0.05, k=None, normalize=True):
"""
Compute the z-normalized matrix profile distance (MPdist) measure between any two
time series with a distributed dask cluster
The MPdist distance measure considers two time series to be similar if they share
many s... | 5ba6455228901e528909a63764a5a9d4fbdef2b3 | 3,637,325 |
def naive_pipeline_2() -> Pipeline:
"""Generate pipeline with NaiveModel(2)."""
pipeline = Pipeline(model=NaiveModel(2), transforms=[], horizon=7)
return pipeline | a14cef26c6970260435ddd5a17762e8dfa98e51a | 3,637,326 |
import torch
def caption_image_batch(encoder, decoder, images, word_map, device, max_length):
"""
Reads an image and captions it with beam search.
:param encoder: encoder model
:param decoder: decoder model
:param image: image
:param word_map: word map
:param beam_size: number of sequences... | 192def399d6b05947df7bac06e90836771a22dda | 3,637,327 |
def wasserstein_distance(p, q, C):
"""Wasserstein距离计算方法,
p.shape=(m,)
q.shape=(n,)
C.shape=(m,n)
p q满足归一性概率化
"""
p = np.array(p)
q = np.array(q)
A_eq = []
for i in range(len(p)):
A = np.zeros_like(C)
A[i,:] = 1.0
A_eq.append(A.reshape((-1,)))
for i in ... | 3a1e1836f5ec9975b30dafff06d8a4eaee90e482 | 3,637,328 |
def median_cutoff_points(ventricular_rate, ponset, toffset):
"""Calculate the median cutoff start and end points"""
ponset = 0 if np.isnan(ponset) else int(ponset)
toffset = 600 if np.isnan(toffset) else int(toffset)
# limit the onset and offset to be in the range of 0-600
# take some margin of 10ms... | 28de4a6ec172a052cb3a819d21ae8371ba68a469 | 3,637,329 |
def make_colormap(color_palette, N=256, gamma=1.0):
"""
Create a linear colormap from a color palette.
Parameters
----------
color_palette : str, list, or dict
A color string, list of color strings, or color palette dict
Returns
-------
cmap : LinearSegmentedColormap
A... | 78fee496532616d3d4a8d7bee6ee5ec7637750f5 | 3,637,330 |
def frac_correct(t):
"""Compute fraction correct and confidence interval of trials t
"""
assert np.all(t.outcome.values<2)
frac = t.outcome.mean()
conf = confidence(frac, len(t))
return frac, conf | 82ed3ae7e6e9a34933ff7c07a2ca54faf563b235 | 3,637,331 |
def run_location(tokens, description):
"""Identifies the indices of matching text in the lines.
Arguments:
tokens (list): A list of strings, serialized from the GUI.
description (CourseDescription): The course to be matched against.
Returns:
list: List of list of index positions.
... | b2f7867319620f8a46c07727494cc8dbf85d5084 | 3,637,332 |
def domean(data, start, end, calculation_type):
"""
Gets average direction using Fisher or principal component analysis (line
or plane) methods
Parameters
----------
data : nest list of data: [[treatment,dec,inc,int,quality],...]
start : step being used as start of fit (often temperature mi... | 09e3539e4705995e8721976412977e13575add19 | 3,637,334 |
def download_data(dataset: str):
"""
Downloads a dataset as a .csv file.
:param dataset: The name of the dataset to download.
"""
return send_from_directory(app.config['DATA_FOLDER'], dataset, as_attachment=True) | cc4cd03f38ecfbfc3b602a2ed323482203ef319f | 3,637,335 |
def _split_features_target(feature_matrix, problem_name):
"""Split the features and labels.
Args:
feature_matrix (pd.DataFrame):
a dataframe consists of both feature values and target values.
problem_name (str):
the name of the problem.
Returns:
tuple:
... | 363dd1a9956f97c3c3520a074cca3c7c57f1517f | 3,637,336 |
def descope_queue_name(scoped_name):
"""Descope Queue name with '.'.
Returns the queue name from the scoped name
which is of the form project-id.queue-name
"""
return scoped_name.split('.')[1] | 24de78d12399e0894f495cd5c472b10c2315e4af | 3,637,337 |
from IPython.display import Image
def movie(function, movie_name="movie.gif", play_range=None,
loop=0, optimize=True, duration=100, embed=False, mp4=True):
"""
Make a movie from a function.
function has signature: function(index) and should return
a PIL.Image.
"""
frames = []
fo... | ac1705c4dae278a58af4f745d676c20570639567 | 3,637,339 |
def get_rounded_reward_2(duration: float) -> float:
""" Helper function to round reward.
:param duration: not rounded duration
:return: rounded duration, two decimal points
"""
return round(get_reward(duration), 2) | ad1e97788504e6b4173853dbd7e82e9b407f7d0b | 3,637,340 |
def fitness_order(order):
"""fitness function of a order of cities"""
score = 0
cacher = str(order)
if cacher in cache:
return cache[cacher]
for i in range(len(order) - 1):
score += distance_map[(order[i], order[i + 1])]
score += distance_map[(order[0], order[-1])]
cache[cach... | e2af48535bf2219ec4cb6ddf0972c7dcc7ef363a | 3,637,341 |
from ba import _lang
from typing import Optional
def get_human_readable_user_scripts_path() -> str:
"""Return a human readable location of user-scripts.
This is NOT a valid filesystem path; may be something like "(SD Card)".
"""
app = _ba.app
path: Optional[str] = app.python_directory_user
if... | f5d78fed6db03947f1bb4135391aeeb7a130031c | 3,637,342 |
def rotated_positive_orthogonal_basis(
angle_x=np.pi / 3, angle_y=np.pi / 4, angle_z=np.pi / 5
):
"""Get a rotated orthogonal basis.
If X,Y,Z are the rotation matrices of the passed angles, the resulting
basis is Z * Y * X.
Parameters
----------
angle_x :
Rotation angle around the ... | 8848d1d11f3e83727ed90957f012869f27991285 | 3,637,343 |
import array
def create_sequences(tokenizer, max_length, descriptions, photos_features, vocab_size):
"""
从输入的图片标题list和图片特征构造LSTM的一组输入
Args:
:param tokenizer: 英文单词和整数转换的工具keras.preprocessing.text.Tokenizer
:param max_length: 训练数据集中最长的标题的长度
:param descriptions: dict, key 为图像的名(不带.jpg后缀), value ... | 31cffba7fdce229bd264e87291e57ed386498f3f | 3,637,344 |
def avatar_uri(instance, filename):
"""
upload_to handler for Channel.avatar
"""
return generate_filepath(filename, instance.name, "_avatar", "channel") | f880f49055fbdc30f6a045f2f7916c077d22452c | 3,637,345 |
def readMoveBaseGoalsFromFile(poses_file):
"""Read and return MoveBaseGoals for the robot-station and patrol-poses.
If the contents of the file do not obey the syntax rules of
_readPosesFromFile(), or if no patrol-poses were found, an IOError
exception is raised.
"""
patrol_poses, station_pose =... | 09085a9bc569e78050f3f10552aa160e9a9324bb | 3,637,346 |
import configparser
def get_config(section = None):
"""Load local config file"""
run_config = configparser.ConfigParser()
run_config.read(get_repo_dir() + 'config.ini')
if len(run_config) == 1:
run_config = None
elif section is not None:
run_config = run_config[section]
return ... | 934dfad58fd674b58ccb4ddfeb9d62edbaba6e84 | 3,637,347 |
def get_parent(running_list, i, this_type, parent_type):
"""Get the description of an industry group's parent
OSHA industry decriptions are provided in ordered lists;
this function identifies the parent industry group based
on information provided by the groups preceeding it
"""
prior = running... | f307900a6220f4d6f14ed0c1924d8f03a40a8a1d | 3,637,349 |
import torch
def rebalance_binary_class(label, mask=None, base_w=1.0):
"""Binary-class rebalancing."""
weight_factor = label.float().sum() / torch.prod(torch.tensor(label.size()).float())
weight_factor = torch.clamp(weight_factor, min=1e-2)
alpha = 1.0
weight = alpha * label*(1-weight_factor)/weig... | 5adf3a21e4cc4b9e7bf129ecf31cfe37ab7a305a | 3,637,350 |
def from_base(num_base: int, dec: int) -> float:
"""Returns value in e.g. ETH (taking e.g. wei as input)."""
return float(num_base / (10 ** dec)) | 447a07b3e282e5104f8dcd50639c658f3013ec7a | 3,637,351 |
def make_auth_header(auth_token):
"""Make the authorization headers to communicate with endpoints which implement Auth0 authentication API.
Args:
auth_token (dict): a dict obtained from the Auth0 domain oauth endpoint, containing the signed JWT
(JSON Web Token), its expiry, the scopes grant... | e7c9b93cfbda876668068fb871d3abaf06157204 | 3,637,352 |
from typing import Tuple
def _drop_additional_columns(
pdf: PandasDataFrame,
column_names: Tuple,
additional_columns: Tuple,
) -> PandasDataFrame:
"""Removes additional columns from pandas DataFrame."""
# ! columns has to be a list
to_drop = list(compress(column_names, additional_columns))
... | 86a41647ae9bed9a18b428610f73af36105702b8 | 3,637,355 |
def get_cc3d(mask, top=1):
""" 26-connected neighbor
:param mask:
:param top: top K connected components
:return:
"""
msk = connected_components(mask.astype('uint8'))
indices, counts = np.unique(msk, return_counts=True)
indices = indices[1:]
counts = counts[1:]
if len(counts) >= ... | e91d5f2617ba526ebc27eaca93d8fed7e0145d0b | 3,637,356 |
def dscp_class(bits_0_2, bit_3, bit_4):
"""
Takes values of DSCP bits and computes dscp class
Bits 0-2 decide major class
Bit 3-4 decide drop precedence
:param bits_0_2: int: decimal value of bits 0-2
:param bit_3: int: value of bit 3
:param bit_4: int: value of bit 4
:return: DSCP cla... | 79e9881e413a5fcbbbaab110e7b3346a2dbcaa53 | 3,637,357 |
def load_data(impaths_all, test=False):
"""
Load data with corresponding masks and segmentations
:param impaths_all: Paths of images to be loaded
:param test: Boolean, part of test set?
:return: Numpy array of images, masks and segmentations
"""
# Save all images, masks and segmentations
... | b1d8f1b135eab0f122370aaa98f8cbbe6f2f1be7 | 3,637,358 |
def f_assert_seq0_gte_seq1(value_list):
"""检测列表中的第一个元素是否大于等于第二个元素"""
if not value_list[0] >= value_list[1]:
raise FeatureProcessError('%s f_assert_seq0_gte_seq1 Error' % value_list)
return value_list | 225e60a565ffa81ec373dea7f8097ee6619a8b01 | 3,637,359 |
from typing import List
def decorate_diff_with_color(contents: List[str]) -> str:
"""Inject the ANSI color codes to the diff."""
for i, line in enumerate(contents):
if line.startswith("+++") or line.startswith("---"):
line = f"\033[1;37m{line}\033[0m" # bold white, reset
elif line... | 55821622b1e7d7f545fa4ad34abebd108f27528d | 3,637,362 |
from typing import Dict
def _combine_multipliers(first: Dict[Text, float],
second: Dict[Text, float]) -> Dict[Text, float]:
"""Combines operation weight multiplier dicts. Modifies the first dict."""
for name in second:
first[name] = first.get(name, 1.0) * second[name]
return first | e9db49daad0463e42a9231a2459fac5b4d14e181 | 3,637,363 |
def scale_to_one(iterable):
"""
Scale an iterable of numbers proportionally such as the highest number
equals to 1
Example:
>> > scale_to_one([5, 4, 3, 2, 1])
[1, 0.8, 0.6, 0.4, 0.2]
"""
m = max(iterable)
return [v / m for v in iterable] | 92cfc7ef586ecfea4300aeedabe2410a247610f7 | 3,637,364 |
def insecure(path):
"""Find an insecure path, at or above this one"""
return first(search_parent_paths(path), insecure_inode) | 685e66392f2adf8c9447e5cacf883de68c3bbe2d | 3,637,366 |
import gc
def n_feature_influence(estimators, n_train, n_test, n_features, percentile):
"""
Estimate influence of the number of features on prediction time.
Parameters
----------
estimators : dict of (name (str), estimator) to benchmark
n_train : nber of training instances (int)
n_test :... | 16d386385f4fde04670e37e76abe13b8c22a487c | 3,637,367 |
def make_author_list(res):
"""Takes a list of author names and returns a cleaned list of author names."""
try:
r = [", ".join([clean_txt(x['family']).capitalize(), clean_txt(x['given']).capitalize()]) for x in res['author']]
except KeyError as e:
print("No 'author' key, using 'Unknown Author'. You should ... | e1459514928d87a3e688b6957437452d02e50987 | 3,637,368 |
def backproject_points_np(p, fx=None, fy=None, cx=None, cy=None, K=None):
"""
p.shape = (nr_points,xyz)
"""
if not K is None:
fx = K[0, 0]
fy = K[1, 1]
cx = K[0, 2]
cy = K[1, 2]
# true_divide
u = ((p[:, 0] / p[:, 2]) * fx) + cx
v = ((p[:, 1] / p[:, 2]) * fy) + cy
return np.stack([v, u]).... | a06031de2f03d6e80ae149024a5bb2bea96f6b76 | 3,637,369 |
def recover(D, gamma=None):
"""Recover low-rank and sparse part, using Alg. 4 of [2].
Note: gamma is lambda in Alg. 4.
Parameters
---------
D : numpy ndarray, shape (N, D)
Input data matrix.
gamma : float, default = None
Weight on sparse component. If 'None', then gamma = 1/s... | 83a269006a7cc6c48b1db520c813929886eedf7b | 3,637,371 |
def get_stylesheet():
"""Generate an html link to a stylesheet"""
return "{static_url}/code_pygments/css/{theme}.css".format(
static_url=core_config['ASSETS_URL'],
theme=module_config['PYGMENTS_THEME']) | e5f766a414d6fac32b361dfbb54da929bff4458d | 3,637,373 |
def create_volume(ctxt,
host='test_host',
display_name='test_volume',
display_description='this is a test volume',
status='available',
migration_status=None,
size=1,
availability_zone='fake_az',... | b638e98ab88f0e65c37503dee80bbec2250aab0e | 3,637,374 |
def duration_of_treatment_30():
"""
Real Name: b'duration of treatment 30'
Original Eqn: b'10'
Units: b'Day'
Limits: (None, None)
Type: constant
b''
"""
return 10 | 510b8e114007c9e64f866c98bfce9d2d86fa7bfe | 3,637,375 |
def input_pkgidx(g_dim):
"""
Specify the parking spots index by the user
return 1*pk_dim np.array 'pk_g_idx' where pk_dim is the number of spots
"""
#print('Please specify the num of parking spots:')
pk_dim = np.int(input('Please specify the num of parking spots:'))
while pk_dim >= g_dim:
... | acba8fdbeb1d0fdcb67d28b64fa313489fd597df | 3,637,376 |
def get_total_count(data):
"""
Retrieves the total count from a Salesforce SOQL query.
:param dict data: data from the Salesforce API
:rtype: int
"""
return data['totalSize'] | 7cb8696c36449425fbcfa944f1f057d063972888 | 3,637,377 |
def _check_hex(dummy_option, opt, value):
"""
Checks if a value is given in a decimal integer of hexadecimal reppresentation.
Returns the converted value or rises an exception on error.
"""
try:
if value.lower().startswith("0x"):
return int(value, 16)
else:
re... | 6acf63f42b79ba30a55fc1666bdd2c1f65124fd3 | 3,637,378 |
def get_challenge():
"""returns the ChallengeSetting object, from cache if cache is enabled"""
challenge = cache_mgr.get_cache('challenge')
if not challenge:
challenge, _ = ChallengeSetting.objects.get_or_create(pk=1)
# check the WattDepot URL to ensure it does't end with '/'
if cha... | f874b90624bbd9c4d4fc5e18efd6363d461fab0f | 3,637,379 |
async def get_user_from_event(event):
""" Get the user from argument or replied message. """
args = event.pattern_match.group(1).split(" ", 1)
extra = None
if event.reply_to_msg_id:
previous_message = await event.get_reply_message()
user_obj = await event.client.get_entity(previous_messa... | 4cd659637603e9910aa5fb00e855767ae8252c2e | 3,637,380 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.