content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def and_(*validation_func # type: ValidationFuncs
):
# type: (...) -> Callable
"""
An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a
`AtLeastOneFailed` failure on the first `False` received or `Exception` caught.
Note that an implicit `and_... | 4541531cd46e7a5d1ce726b6f25232b016132ce9 | 45,123 |
def config_get_state_power_on(config):
"""Get command/result on."""
return config[CONF_STATE][STATE_ON] | d32a024ee1832d0788704b70d73c48c816321774 | 45,124 |
def addr_entry(key):
"""querries the user for address data, cleans it"""
# getting the input
rawline = input(
'please enter ' + key + ': '
)
# get rid of trailing whitespace
line = rawline.strip()
# replace tabs
line = line.replace('\t', ' ')
# remove forbidden strings
... | 3edf6a39a276f9abb63ee5930a907b75ba3c623a | 45,125 |
import torch
def extract_neighborhood_sets(
o1: torch.Tensor, o2: torch.Tensor, s1: torch.Tensor, s2: torch.Tensor,
dist1: torch.Tensor, im1seeds: torch.Tensor, im2seeds: torch.Tensor,
k1: torch.Tensor, k2: torch.Tensor, R1: float, R2: float,
fnn12: torch.Tensor, ORIENTATION_THR: float... | 485c505a350f1f1ef027088d8c44fea6fe53f8e3 | 45,127 |
def calculate_l2r_matrix(left_extrinsics: np.ndarray,
right_extrinsics: np.ndarray) -> np.ndarray:
"""
Return the left to right transformation matrix:
l2r = R * L^-1
"""
l2r = np.matmul(right_extrinsics, np.linalg.inv(left_extrinsics))
return l2r | 330f58362f47e7ebd29ee800da6a89bd8ea46a15 | 45,129 |
def load_data(messages_filepath, categories_filepath):
"""
Load messages and categories from dataset
Args:
message_filepath(string): the file path of messages.csv
categories_filepath(string): the file path of categories.csv
Return:
df(Dataframe): merged dataframe of message... | c72ee4f9b41cc5f31751551b4a48fa76dd05cdc1 | 45,130 |
def total_units_given(type_, value, start, end):
""" Find total units given for a dose """
if type_ in [DoseType.bolus, DoseType.suspend]:
return value
return value * hours(end, start) | 2caa0dc55c04c38697936b68f3bc5ceb7c32dc9c | 45,131 |
def process_season_matches(season_matches_df):
"""Processes raw season match data into parsable match and table data.
:param season_matches_df: Dataframe as returned by get_season_matches function
:return: 3 dataframes: expanded_df with match info, table_df with match outcome info, and grouped_table_df
... | 6bbbf1bc76870b75e429bdb8719e0af6d6fa888c | 45,132 |
import base64
def decode_argument_value(name, value):
"""
Decodes the value of an argument. The value is assumed to be Base64 encoded
:param name: The name of the argument that is being decoded
:param value: The encoded value of the argument. It is assumed to be Base64 encoded
:return: The decod... | b21687a6c41f5080ca0557a0d89479fce13497a0 | 45,133 |
def _lr(k, x, size):
"""Helper function to fit one gene"""
ashr = rpy2.robjects.packages.importr('ashr')
lam = x / size
if np.isclose(lam.min(), lam.max()):
return k, 0
else:
res0 = scmodes.ebpm.ebpm_unimodal(x, size)
res1 = scmodes.ebpm.ebpm_npmle(x, size)
return k, np.array(res1.rx2('loglik'... | d0712478585cc573e1fa63b4330e2b4ba9074e30 | 45,134 |
def get_text_from_image(input_file: str,
lang: str = "eng",
tessdata_prefix: str = "") -> str:
"""
Get text from image using Tesseract OCR.
Parameters
----------
input_file : str
lang : str
| Language which will Tesseract use for OCR. Avai... | ccfef30c90bad95a749fe97c031d9612211ccbf3 | 45,135 |
def create_msms_dataframe(df):
"""
create a dataframe organized into spectra from a raw dataframe of points
"""
#removed polarity and hdf5_file
if 'precursor_MZ' in df.columns:
grouped = df.groupby(['precursor_MZ','rt','precursor_intensity','collision_energy']).aggregate(lambda x: tuple(x))
... | 30b777dbac946d4e65f09ef80b160ee0b935dad2 | 45,136 |
def penn_to_wn(tag):
"""
Convert PENN to WordNet Format
Args:
tag (str): PENN Tag
Returns:
str: Wordent Representation
"""
try:
if tag.startswith('J'):
return wn.ADJ
elif tag.startswith('N'):
return wn.NOUN
elif tag.startswith('... | 4946a7e7491d0b7c27e32ec81d17cb091f92f91b | 45,137 |
def add_landingpage_on_nav_page(sender, request=None, **kwargs):
"""
Receive the 'nav_organizer' signal which triggers when controlling an organization.\n
If this signal occurs, the 'Landing Page' tab will be added to the menu bar on the left side.\n
With the added tab you'll have access to the Landi... | f33cad80d9018df3d3b3e7017bb7c0a57b79b489 | 45,138 |
def process_code_blocks(filestr, code_style, format):
"""Process a filestr with code blocks
Loop through a file and process the code it contains.
:param str filestr: text string
:param str code_style: optional typesetting of code blocks
:param str format: output formatting, one of ['html', 'latex',... | 4629df4da2acc4fcb8ca6d2bdf4b3a74a081aad8 | 45,139 |
def vgg_net():
"""
https://arxiv.org/pdf/1409.1556.pdf
"""
_log.info('Building the model')
model = Sequential()
_mult_conv_max(model, nb_conv=2, nb_filter=64)
_mult_conv_max(model, nb_conv=2, nb_filter=128)
_mult_conv_max(model, nb_conv=3, nb_filter=256)
_mult_conv_max(model, nb_conv... | c4f9374d10cfa8ed25a1dbbc0428a65d2ec4cadd | 45,140 |
def grayscale(im, amount=1):
"""Converts image to grayscale.
A grayscale operation is equivalent to the following matrix operation:
| R' | |0.2126+0.7874g 0.7152-0.7152g 0.0722-0.0722g 0 0 | | R |
| G' | |0.2126-0.2126g 0.7152+0.2848g 0.0722-0.0722g 0 0 | | G |
| B' | = |0.2126... | 1a84c62d535739e8f5a4a0f679a9c12575cc8094 | 45,141 |
def bar_chart(**kwargs):
"""
An example of a bar chart
Args
**kwargs lets you pass arguments into this function
"""
years = [str(year) for year in range(2010, 2021)]
visitors = [1241, 50927, 162242, 222093,
665004, 2071987, 2460407, 3799215,
5399000,... | b251669ae32e08b0bdf083d1360e29eb1593e598 | 45,142 |
def splitname(name, strict_mode=True):
"""
Break a name into its constituent parts: First, von, Last, and Jr.
:param string name: a string containing a single name
:param Boolean strict_mode: whether to use strict mode
:returns: dictionary of constituent parts
:raises `customization.InvalidName... | 29a24a26e7b644548f33de79f0e1dc07c4d4fc7c | 45,143 |
def _gen_image(num_per_item, _list, is_covers=True, _min=None, images_list=None):
"""
Generate n image for each item in _list or random between _min and num_per_item,
because url images are unique, it accepts list of image object (return from
SQLAlchemy query) to avoid duplicate with existed images
... | 5ba68dcf5471cf10460e56f0cc2c31c29709c17f | 45,144 |
def arikan_gen(n):
"""
The n-th kronecker product of [[1, 1], [0, 1]], commonly referred to as Arikan's kernel.
Parameters
----------
n: int
log2(N), where N is the block length
Returns
----------
ndarray<int>
polar code generator matrix
"""
F = np.array([[1, ... | f1f78d84b08da81bef942178fd37df9636fc595c | 45,146 |
import math
def check_user_answer(user_answer, calculated_answer):
"""
This method checks the user's answer with the calculated answer.
Args:
user_answer (Union[str, int, float, List[Union[int, float]]]): The user's answer.
calculated_answer (Union[str, int, float, List[Union[in... | 42d9c7b8ea5f5ce6cfc2bf67edb548ad809d44e9 | 45,147 |
def segment_sentence(bestprecodetree,roottree,bestsuffcodetree,bestpostcodetree,bestendcodetree,bestvocab,
sentence,marker1,marker2,mode=0,generateroots=False,optmode=1,extramode=0,nentnums=[],nentsegs=[],verbose=False):
""" Segment line of words (whitespace-tokenized string) with PRP encoding
... | 9e9ccb76292dd79b41cf2813bcddadb92e8fbc87 | 45,149 |
def feat_upsampling_nearest_neighbor(input_feat, up_shape, name='feat_upsampling'):
""" nearest neighborhood upsampling
Args:
up_shape (list of length 2): upsampled shape
"""
with tf.name_scope(name):
up_feat = tf.image.resize_nearest_neighbor(
input_feat, (up_shape... | 57ec83970382e47b4ef5cb895e387930c0721233 | 45,150 |
from io import StringIO
def open_url(url: str) -> StringIO:
"""Fetches a given URL synchronously.
The download of binary files is not supported. To download binary
files use :func:`pyodide.http.pyfetch` which is asynchronous.
Parameters
----------
url : str
URL to fetch
Returns
... | 03babf9a465ae3c29de0352aae328953837107e6 | 45,151 |
def get_replaced_all_jokers_hands(hand):
"""
Заменяем обоих джокеров и возвращаем общий список замен
:param hand: исходная рука
:return:
"""
replaced_joker_hands = []
replaced_black_joker_hands = get_replaced_joker_hands(
hand, LIST_BLACK_CARD, '?B'
)
for replaced_black_joke... | 31911c6accc1ab16009eb699f490946cd053e546 | 45,153 |
def step(t, n, initial, after, seed=1, dt=0.05):
"""Simulates for n generators for t ms. Step at t/2."""
nest.ResetKernel()
nest.SetStatus([0], [{"resolution": dt}])
nest.SetStatus([0], [{"grng_seed": 256 * seed + 1}])
nest.SetStatus([0], [{"rng_seeds": [256 * seed + 2]}])
g = nest.Create('sin... | 5ab1084f4d07e457f9b69d8a9b232d0fce6dc7e2 | 45,154 |
def harmonic_epmi_score(pdict, wlist1, wlist2):
""" Calculate harmonic mean of exponentiated PMI over all word pairs
in two word lists, given pre-computed PMI dictionary
- If harmonic ePMI is undefined, return -inf
"""
total_recip_epmi = None
# Number of pairs for which PMI exists
N... | 5aec36df72e22fecbb1dfdcbc6ec840944a40d8d | 45,155 |
def datafiles(request, tmpdir):
"""
pytest fixture to define a 'tmpdir' containing files or directories
specified with a 'datafiles' mark.
"""
entry_list = []
options = {
'keep_top_dir': False,
'on_duplicate': 'exception', # ignore, overwrite
}
for mark in request.no... | 456f13fde72609f7f65e5b50be38166ba16267e9 | 45,156 |
def get_paramvals_percentile(mcmc_table, pctl, chi2, randints_df=None):
"""
Isolates 68th percentile lowest chi^2 values and takes random 100 sample
Parameters
----------
mcmc_table: pandas.DataFrame
Mcmc chain dataframe
pctl: int
Percentile to use
chi2: array
Arra... | f29a00a68208987edefa62623e4b39ac6dcf6e88 | 45,157 |
def parse_origin(url):
"""
Return the origin of a URL or None if empty or invalid.
Per https://tools.ietf.org/html/rfc6454#section-7 :
Return ``<scheme> + '://' + <host> + <port>``
for a URL.
:param url: URL string
:rtype: str or None
"""
if url is None:
return None
pa... | c0efb2cc1c3910f56f634ad87a83a8fe1bab8a3f | 45,158 |
def optional_apply(f, value):
"""
If `value` is not None, return `f(value)`, otherwise return None.
>>> optional_apply(int, None) is None
True
>>> optional_apply(int, '123')
123
Args:
f: The function to apply on `value`.
value: The value, maybe None.
"""
if value is... | dfa5b6793d7226370a27d6a638c0a5bc975f78d4 | 45,159 |
from .plot_methods import multi_scatter_plot
from .bokeh_plots import bokeh_multi_scatter
def scatter(xdata, ydata, backend=None, data=None, **kwargs):
"""
Plot the provided data as a scatter plot. Varying size and color
are possible. Multiple data sets are possible
:param xdata: data for the x-axis
... | 6f3bfca1e11b2b07e3bac361b27209fb3d08bd65 | 45,160 |
def repl_func(m):
"""process regular expression match groups for word upper-casing problem"""
return m.group(1) + m.group(2).upper() | 72ae8d2cdcec98ce4ae661dbe020dc244d47c8af | 45,161 |
def make_email(to, cc=None, bcc=None, subject=None, body=None):
"""\
Encodes either a simple e-mail address or a complete message with
(blind) carbon copies and a subject and a body.
:param to: The email address (recipient). Multiple values are allowed.
:type to: str or iterable of strings
:par... | 9387bdba6968eb1cc3b948ba260a918af8554124 | 45,163 |
def invoke_gate(a, b):
"""Function modelling one input (a) invoking a second input (b).
If the invoking is at either -1,0,1 the output is also at that value.
The second input can only modify the output between those values.
Args:
a (float): invoking input
b (float): second input
... | 82be9c62cd6bc0897641ff25fb30a7e0fa8e8d7b | 45,164 |
def cosine_similarity(
X,
Y=None,
dense_output=True,
use_float=False,
approx_size=1.0,
compression_rate=1.0,
blas="default",
):
"""Compute cosine similarity between samples in X and Y.
Cosine similarity, or the cosine kernel, computes similarity as the
normalized dot product of X... | 1b8d8e780aa59bbf36c156ca0fb1cb88f5dba511 | 45,165 |
def cdlhikkakemod(opn, high, low, close):
"""Modified Hikkake Pattern:
The modified hikkake pattern is a less frequent variant of the basic hikkake pattern and is
viewed as a reversal pattern. The concept of the modified version is similar to the basic
version, except that a "context bar" is used prior... | fda33ad68affabb8d18481c8c4658eb2200ca998 | 45,166 |
def coffee():
"""About page."""
return render_template('public/coffee.html') | 03ce072cfc917f9a16894fd6da2015fc5a44e278 | 45,168 |
def after_request(response):
"""log details on the request and its served response"""
__log__.info('%s - "%s %s %s" %s -',
request.remote_addr, request.method, request.full_path,
request.environ.get('SERVER_PROTOCOL'), response.status_code)
return response | d26e3b6a9606da9f1684e320447c9bfb75683002 | 45,169 |
def average_infid_set(U_dict: dict, index, dims, eval, proj=True):
"""
Mean average fidelity over all gates in U_dict.
Parameters
----------
U_dict : dict
Contains unitary representations of the gates, identified by a key.
index : int
Index of the qubit(s) in the Hilbert space t... | 9cc07fcdd0989f1d7f3edf35043720d227c041af | 45,170 |
async def read(id: int, auth_data: dict = Depends(get_auth_data)):
"""
读取组织数据详情
:param id: 组织id
:return: 组织详情结构
"""
resp = OrgRespDetailSchema()
resp.detail = OrgService(auth_data).read(id)
return resp | 84bf2d3306548e09207d9bfa1318fc4ce8f5c33f | 45,171 |
def RAND(*args) -> Function:
"""
Returns a random number between 0 inclusive and 1 exclusive.
Learn more: https//support.google.com/docs/answer/3093438
"""
return Function("RAND", args) | 3759d35ef8233a18223d3f9d65d32c65fd694142 | 45,172 |
import json
def get_channel_status_bulk(request):
""" Create the channel node """
data = json.loads(request.body)
try:
statuses = {cid: get_status(cid) for cid in data['channel_ids']}
return HttpResponse(json.dumps({
"success": True,
'statuses': statuses,
}... | 6082cac06b4ef8d96da12c8c8ed1b226b44705fb | 45,173 |
def GetChainAloneResidueTypesStatus(FileIndex, ChainID):
"""Get status of residue types for chain alone object."""
Status = OptionsInfo["InfilesInfo"]["SpecifiedChainsAndLigandsInfo"][FileIndex]["ResidueTypesChain"][ChainID]
return Status | 4e26ef6556fc0fcd8466c0c8ab53095ea83578ef | 45,174 |
def run_3gpp_tests(
setup, key_filename=DEFAULT_KEY_FILENAME, test_files=NG40_TEST_FILES
):
"""
Run teravm s6a and gxgy test cases. Usage: 'fab run_3gpp_tests:' for
default key filename and default test files.
key_filename: path to where the private key is for authorized-key based
ssh. The ... | aab8faf5dd4701f2c294c4da59a03f969dba05d2 | 45,175 |
def gameOver(currentBoard,typeCurrentPlayer):
"""
Function that checks if the game is over in the current board
Parameters :
-currentBoard : the current board
-typeCurrentPlayer : type of the current player
Returns :
- [True, game over message] if the game is over
- [Fals... | a7b27235d31c348d260873cd7b57e16db02828b7 | 45,176 |
def task_table(request):
"""
ProductionTask table
:return: table page or data for it
"""
last_task_submit_time = ProductionTask.objects.order_by('-submit_time')[0].submit_time
return TemplateResponse(request, 'prodtask/_task_table.html', { 'title': 'Production Tasks Table',
... | 1388c14763e553aec77caa070dde0c26e04c28c3 | 45,177 |
import requests
import json
def user_files():
"""
This route renders a file-upload page for users.
Not logged-in users (anonymous):
> request that they login
logged-in users (anonymous):
> list files they own
> show file-upload box
The file-up... | c78b5891b1776feeb3c39678051efa9f45ac8ddc | 45,178 |
def update_meta_sheet_feeders(self, puzzle_id) -> None:
"""
Updates the input meta puzzle's spreadsheet with the
latest feeder puzzle info
"""
meta_puzzle = Puzzle.objects.get(pk=puzzle_id)
if not meta_puzzle.is_meta or not meta_puzzle.sheet:
return
logger.info(
"Starting up... | 3b174c8c3662020a52b3d31651b7ffd3435472f5 | 45,179 |
def prod(F, E):
"""Check that the factorization of P-1 is correct. F is the list of
factors of P-1, E lists the number of occurrences of each factor."""
x = 1
for y, z in zip(F, E):
x *= y**z
return x | 401a5596b42b1299a07b3f621c996226474735f5 | 45,180 |
def _parse_common(raw_object: RawObject) -> TiledObject:
"""Create an Object containing all the attributes common to all types of objects.
Args:
raw_object: Raw object to get common attributes from
Returns:
Object: The attributes in common of all types of objects
"""
common = Tile... | 7795a5bf462d03e46bf270276bcb8dd3cdaf6c5c | 45,181 |
def load_file(fname, force_reload=False, **kwargs):
"""Load a file
Parameters:
fnames (list): single file name, or list of files that are part
of the same time series. Glob patterns and slices are
accepted, see :doc:`/tips_and_tricks` for more info.
fname (str): a file n... | d274c0b4406f0c41f8fb239c3086ab64414a6170 | 45,182 |
def sort_data(data, cols):
"""Sort `data` rows and order columns"""
return data.sort_values(cols)[cols + ['value']].reset_index(drop=True) | 33acbfd9be36d187120564f1792147b644b6c394 | 45,183 |
def calc_2d_ellipse_properties(cov,nstd=2):
"""Calculate the properties for 2d ellipse given the covariance matrix."""
def eigsorted(cov):
vals, vecs = np.linalg.eigh(cov)
order = vals.argsort()[::-1]
return vals[order], vecs[:,order]
vals, vecs = eigsorted(cov)
width, height = ... | 6875e7f92287fe9a5c1ff772988e3be09a57388b | 45,184 |
from typing import Dict
from typing import Callable
from typing import Tuple
def _augment_grid(
policy: np.ndarray,
value: np.ndarray,
expected_value: np.ndarray,
min_wealth_grid: float,
params: pd.DataFrame,
options: Dict[str, int],
compute_utility: Callable,
) -> Tuple[np.ndarray, np.nda... | 5d1fe3bb18c841952546735bd32c825530c74258 | 45,185 |
import torch
def argval_subsample_idx(values, n, polarity="MAX"):
"""values is a list, n an int, polarity is MAX or MIN"""
assert n > 0
descending = {"MAX": True, "MIN": False}[polarity]
_, idxs = torch.sort(torch.Tensor(values), descending=descending)
return idxs.tolist()[:n] | dbf15c72554be1bc750b12ca47c98b0e654a3c2e | 45,187 |
def shortest_path_matrix(G):
"""
Return a matrix of pairwise shortest path lengths between nodes.
Parameters
----------
G (nx.Graph): the graph in question
Returns
-------
pmat (np.ndarray): a matrix of shortest paths between nodes in G
"""
N = G.number_of_nodes()
pmat = ... | 32c478efd2123041feff6d62a798dcc861dfecfc | 45,188 |
from typing import Any
def build_put201_creating_failed200_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest:
"""Long running put request, service returns a 201 to the initial request, with an entity that
contains ProvisioningState=’Created’. Polls return this value until the la... | fec506a6704aeb55a2e71d2375351520f31fe099 | 45,189 |
def safe_convert_list_to_sql_tuple(filter_list):
""" Safe version of convert_list_to_sql_tuple(), by first flattening the input list
and then casting all its elements to strings, before proceeding with the conversion.
"""
return convert_list_to_sql_tuple(cast_elements_to_string(flatten_list(filter_lis... | 39559b581752a1699c54935ba7adff6e09241cfc | 45,190 |
def depthAvgFlow(U, V, dz, depthRange=500):
"""
Depth averaged flow for flow from bottom up to depthrange.
"""
steps = int(np.ceil(depthRange/dz))
Umeans = np.empty(0)
Vmeans = np.empty(0)
for Ui, Vi in zip(U.T, V.T):
mask = np.where(np.isfinite(Ui))[0]
mask = mask[-1:np.max... | e69622eba490903937c9a5ab6936e8b89f0eaba7 | 45,191 |
import numpy
def get_array4d(json_data, microplate_names):
"""Return well values as numpy' 4d array.
(iteration x spreadsheet x microplate x well)
"""
if len(json_data[u'iterations']) > 0:
pad_missing_spreadsheets(json_data)
iterations = []
for iteration in json_data[u'i... | 93db6d54fcf8c40ed9348ee1385cac3629b87c0d | 45,192 |
import logging
def sanitise_graphite_url(current_skyline_app, graphite_url):
"""
Transform any targets in the URL that need modifications like double encoded
forward slash and return whether the URL was sanitised and the url.
:param current_skyline_app: the Skyline app calling the function
:param... | 8151a83861a3ff275694946f623f6beb42fc6bbd | 45,193 |
def convention(predictions, length):
"""
Function for implementimg the convention of Indian plates
"""
cls = np.argmax(predictions, axis = 1)
for i in [0,1]: # first 2 district code must represent letters
if cls[i]==0:
cls[i]= 24
# else:
# print(np.argmax(pred... | ba08164b998554e740ec47e2f4d5ca7df708396d | 45,194 |
def is_connected_dominating_set(G, nodes):
"""Return whether or not *nodes* is a connected dominating set of *G*.
A set *D* is a *connected dominating set* of *G* is *D* is a
dominating set in *G* and the subgraph of *G* induced by *D* is a
connected graph.
Parameters
----------
G : Networ... | 20081f33de032c515bc78dbd0b2ecab212278df6 | 45,195 |
import functools
import time
def _retry_on_deadlock(f):
"""Decorator to retry a DB API call if Deadlock was received."""
@functools.wraps(f)
def wrapped(*args, **kwargs):
while True:
try:
return f(*args, **kwargs)
except db_exc.DBDeadlock:
LO... | edc7e15826ad1d32569a1d9c8a514aa5020430a8 | 45,197 |
def command(server, cmd):
"""
Simple ssh remote command.
Args:
server (collection): Collection with server data
cmd (string): Command to run on remote server
Returns:
string: STDOUT for the remote command
"""
with setup_server_connection(server) as connection:
result = connection.run(cmd, ... | b73d17a68c1e4c37de315aea2aa72e7fe30a375b | 45,198 |
def _union_all(iterables):
"""Return a set representing the union of all the contents of an
iterable of iterables.
"""
out = set()
for iterable in iterables:
out.update(iterable)
return out | 673bc7493007c6cf781d84490023cea7139f1e93 | 45,199 |
def _valid_dimension_name(name):
"""Check if given dimension name is valid for PRMS.
:param str name: dimension name
:returns: True if dimension name is valid otherwise False
:rtype: bool
"""
return name in DIMENSION_NAMES | d80d044eccf9aa7fc525c96944c32325592d9b0b | 45,200 |
from typing import List
def construct_relative_positions(pos: int, max_length: int) -> List[int]:
"""Construct relative positions to a specified pos
Args:
pos: the pos that will be `0`
max_length: max sequence length
Returns:
a list of relative positions
Raises:
Valu... | 152c59d288f797ef87f9e0dbf1b415b71f1fe9e7 | 45,201 |
def get_jira_task(req_sheet, row_num):
""" Accessor for JIRA Key
Args:
req_sheet: A variable holding an Excel Workbook sheet in memory.
row_num: A variable holding the row # of the data being accessed.
Returns:
A string value of the Notes
"""
return (req_sheet['F' + str(r... | e96a2d7f09f6d723795f6d24df231c332a19d628 | 45,202 |
import time
def make_Palomar_pupil(N, apRad, sp_thickness=0.0127, write=False, plot=False, spiders=True, obscuration=True):
"""
Make Palomar pupil
:param N:
:param apRad:
:return:
"""
outer_diameter = 5.09
inner_diameter = 1.83
#sp_thickness = 0.0127
Rin = apRad*inner_diameter... | 6a394acc478da21b1dc545ab8c3cbfde72fbc57c | 45,203 |
def plot_grid(lon,lat,
title_string = 'N/A',
meridians_delta = 15,
parallels_delta = 15,
same_figure = False,
figsize = None,
file_name = None,
dpi = 80,
skip = 5,
return_map = False,
marker = '+'
):
"""Function to plot grids similar to those generated by WPS
Modified 27/01/08: Minor ... | ee06ac2804539a45d65114f72708ce3aa85ed4be | 45,204 |
import pathlib
def _match_path(p1, p2):
"""Compare two paths from right to left and return True if they could refer
to the same file.
As a special case, if the second argument is None, or empty, it is always
considered a match. This simplifies query logic when the target does not
have a path comp... | 7935e4312c444c9e2d0ee62611e1db5d6af210ad | 45,206 |
def submit(host, entity_class, body):
"""
Negotiate submitting the data for an entity to the target service.
:param host: host url
:type host: str
:param entity_class: which entity class is being sent
:type entity_class: class
:param body: map between entity keys and values
:type body: ... | b450a396df3354af288128538c94b8772181e7c1 | 45,208 |
import re
def note_name_to_number(note_name):
"""Converts a note name in the format
``'(note)(accidental)(octave number)'`` (e.g. ``'C#4'``) to MIDI note
number.
``'(note)'`` is required, and is case-insensitive.
``'(accidental)'`` should be ``''`` for natural, ``'#'`` for sharp and
``'!'`` or... | 22395fd81f4a66592d4292d87292f709fa34ef13 | 45,209 |
def determine_temps_for_date_range(start, end):
"""Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range."""
"""When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date."""
... | e44d339e58218e3c8d54c7e0bbb1a094dfc38177 | 45,210 |
def scan_coordinate(rxn, zma):
""" Obtain the scan coordinates
:param rxn: a hydrogen migration Reaction object
"""
return SCAN_COORD_DCT[rxn.class_](rxn, zma) | 81953983f49e7a5965bbc5bfe0918978c8e7ff40 | 45,212 |
def rescaleImage(image, output_size=128, scale=1 / 255.0):
"""Rescale the image in a sample to a given size.
Args:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping aspect ... | 4fedf92940daba680b88206b8271b2756c3a7ba9 | 45,214 |
import datasets
def generate_and_write_mol_dataset(task_type: tasks.Task):
"""Generate all variables and optionally files needed for a molecular task."""
task = tasks.get_task(task_type)
use_h = task_type == tasks.Task.crippen
use_data_aug = isinstance(
task.task_type,
tasks.BinaryClas... | aa88f0d2f2ff329fe3a0418e386841df2caea365 | 45,215 |
def test_run(ray_start_2_cpus):
"""Tests that Train can be run without any specific backends."""
num_workers = 2
key = "value"
value = 1
config = TestConfig()
def train_func():
checkpoint = train.load_checkpoint()
train.report(**checkpoint)
train.save_checkpoint(**checkp... | 61e52c62a71bd69945f3918375da1f9e857b0af7 | 45,216 |
def import_files(configuration):
"""
Import trades from configured files.
"""
return CsvOrderImporter(configuration).import_orders() | f20a29ea921a8747d33e2ffd1975c3a3d9362e86 | 45,217 |
def image_targets_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for target images."""
pixel_embedding_size = 64
inputs = x
with tf.variable_scope("image_modality"):
if not tf.executing_eagerly():
tf.summary.image(
"targets_bottom",
common_layers.tpu_safe_image_summ... | 80b824e17dbf96b0a91702a7bddf3a86e0ff9a98 | 45,218 |
def _GetEventTriggerEventParams(trigger_event, trigger_resource):
"""Get the args for creating an event trigger.
Args:
trigger_event: The trigger event
trigger_resource: The trigger resource
Returns:
A dictionary containing trigger_provider, trigger_event, and
trigger_resource.
"""
trigger_pr... | 4b961910e4d31107b128db97a680cd7e390e87ed | 45,219 |
def pie_chart(start_date, end_date):
# select date range
"""
Presents the day of the week proportion summary of the energy consumed by the appliances in the house.
Parameters
----------
df : pd.DataFrame(selected_data)
Groups the initial dataframe by day_of_week.
start_date : start... | 3cfc55936d0842f9a918fb52cd3729854c52f819 | 45,220 |
def _propose_rois_tpu(scores,
boxes,
anchor_boxes,
height,
width,
scale,
rpn_pre_nms_topn,
rpn_post_nms_topn,
rpn_nms_threshold,
... | a203f8ef6ae52b800632a363fa98f4b80b9476b0 | 45,221 |
import re
def has_text_an_image(text):
"""
:param text: String with base64 data
:return: true if text has base64 data otherwise false
"""
regex_to_extract = r'data:image.+\"'
return re.search(regex_to_extract, text) | c1d23738cc2f8f415a059a51b647d17157474655 | 45,222 |
def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):
"""Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary of POST data to send with the :class:`Request`.
:param headers: (optional... | 2cab2601f3a1321188b46c98e970b0989fc23ebd | 45,224 |
def _get_max(lhs, rhs):
"""Get max value"""
if lhs < 0:
return lhs
if rhs < 0:
return rhs
return max(lhs, rhs) | 244c9401a4f578a4cc4dbdf5d476bc15fdcf054a | 45,225 |
def csr_matmat(data, indices, indptr, B, *, shape, transpose=False):
"""Product of CSR sparse matrix and a dense matrix.
Args:
data : array of shape ``(nse,)``.
indices : array of shape ``(nse,)``
indptr : array of shape ``(shape[0] + 1,)`` and dtype ``indices.dtype``
B : array of shape ``(shape[0]... | 0c43f938cbcc532d728d1b23365f2301b54cf7b5 | 45,226 |
def simplify_elaspic_data(data) -> DataFrame:
"""
Given ELASPIC results data, simplify it into three columns: "UniProt_ID", "Mutation", "Interactor_UniProt_ID".
"""
data = data[["UniProt_ID", "Mutation", "Interactor_UniProt_ID"]].copy(deep=True)
return data | e9c6ba46d076f81faa2cfe84e146e3b06315a2a3 | 45,228 |
import io
def pickle_load(content, safe_to_import=None):
"""
**pickle_load**
Load the pickled content. content should be a bytes object.
**Parameters**
content : Bytes of pickled object. It needs to have Delta header in it that is
separated by a newline character from the rest of the pic... | 13c392a3489f60c8039a327107cdfa2607c973a5 | 45,229 |
def import_string(dotted_path: str):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit(".", 1)
except ValueError as err:
raise Impor... | d4c7f70111f2333d992bfdcc84f5624def0fae17 | 45,230 |
def get_new_ids(index, playlist_name, client):
"""
Gets a list of youtube videoIDs that are in the Elasticsearch index but not
in the Youtube playlist
"""
playlist_id = get_playlist_id(playlist_name, client)
# Force evaluation of scan here since it can throw an exception if done
# lazily (El... | f31c5567fb239e7720528d55fdecb062c01b7568 | 45,231 |
def process_articles(articles_list):
"""Function that processes the article results and transforms them to a list of Article Objects"""
articles_results = []
for article in articles_list:
author = article.get("author")
article_title = article.get("title")
article_description = articl... | ffa2c6094d281e21aabbb48b4b1b52d3488f4e91 | 45,232 |
def delete_vocabulary(word_id: int) -> str:
"""削除する"""
slack_msg = "該当する番号は見つからなかったっぽ!"
with VocabularyDatabase() as v_d:
result = v_d.get_word_list()
cnt = 1
for row in result:
row_id, _ = row
if cnt == word_id:
delete_id = row_id
... | 79f960cd85a1f0b09b6e94b341a88634364ea5ca | 45,233 |
def regnety160(**kwargs):
"""
RegNetY-16GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for... | db0c63e23ec12531f7824f97ab64e57459c93d57 | 45,234 |
import codecs
def unicode_open(filename, *args, **kwargs):
"""
Opens a file with UTF-8 encoding, in a Python 2- and 3-compatible way.
:param filename: Name of file to open.
:param *args: Optional args to be passed on to `open()`.
:param **kwargs: Optional kwargs to be passed on to `open()`.
"... | 49616adedd6dff5b04082de9e42ce54f8384ba86 | 45,235 |
def tupled_argmax(a):
"""
Argmax that returns an index tuple. Note that `numpy.argmax` will return a
scalar index as if you had flattened the array.
Parameters
----------
a : array_like
Input array.
Returns
-------
index : tuple
Tuple of index, even if `a` is one-di... | f84e60e8d8fddc0d114a170c74db667f9602926b | 45,236 |
def record_permission_factory(record=None, action=None):
"""Record permission factory."""
return RecordPermission.create(record, action) | 5b59c5f830e3908eefb5209224812ee765342d71 | 45,238 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.