content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from torchvision.models.vgg import vgg11_bn
from torchvision.models.vgg import vgg11
def vgg_11(batch_norm=True, pretrained=False, fixed_feature=True):
""" VGG 11-layer model from torchvision's vgg model.
:param batch_norm: train model with batch normalization
:param pretrained: if true, return a model pretrained... | 645b79fa96e3bce65e6f0191a78c9cff88c99fb9 | 3,629,700 |
import logging
import sys
def main():
""" Main
"""
parser = ctg_parseargs()
args = parser.parse_args()
# set up logger
level = logging.WARNING
if args.quiet:
level = logging.ERROR
if args.verbose:
level = logging.INFO
if args.debug:
level = logging.DEBU... | 5013fe612664c0201480d73a092c13b56ca5bce6 | 3,629,701 |
def Wavelet_hardSoft(s, jN, wname, alpha=0.5):
"""
小波折中阈值滤波
:param s:
:param jN:
:param wname:
:param alpha:
:return:
"""
ca, cd = wavedec(s, jN, wname)
for i in range(len(ca)):
thr = np.median(cd[i] * np.sqrt(2 * np.log((i + 2) / (i + 1)))) / 0.6745
di = np.array... | f1f348345151e6dcb3dd347a6e51612341ee4bd3 | 3,629,702 |
def compute_vad(log_energy, energy_mean_scale=0.5, energy_threshold=0.5, frames_context=0, proportion_threshold=0.6):
""" Apply voice activity detection
:param log_energy: Log mel energy.
:param energy_mean_scale: If this is set to s, to get the actual threshold we let m be the mean log-energy of the file,... | 1b9370494892e18447014cc6850ad528b8786304 | 3,629,703 |
def current_velocity(x_new, x_prev, h):
""" returns current velocity of a particle from next
position at timestep. """
"""
parameters
----------
x_new : array
new x-position of particle
x_prev : array
previous x-position of particle
h : float
simulation timestep
... | 33d47f901be44fed20613957459aca1eecd5ea2c | 3,629,704 |
import csv
def csvReadCallback(inputFile, **kw):
"""Read callback for CSV data"""
inputFile.readline() # skip header
reader = csv.reader(inputFile, lineterminator='\n', **kw)
return [row for row in reader] | e36c92e5792e905da22438a58c8ce810c2a22e2a | 3,629,705 |
def get_interface_config_commands(interface, intf, existing):
"""Generates list of commands to configure on device
Args:
interface (str): k/v pairs in the form of a set that should
be configured on the device
intf (str): full name of interface, i.e. Ethernet1/1
Returns:
lis... | 745dd81a3a45de14d8dd9c58a4e64b78b310136e | 3,629,706 |
def load_word():
""" return the sql and values of the insert queuery."""
sql = """
INSERT INTO Spanglish_Test.Word
(
`word`, `language_id`, `category_id`
)
VALUES (%s, %s, %s)
"""
values = [
(
'Ir', 2, 1
),
... | f0d836f5ca912865f9d75a5e6c10c13cf554674b | 3,629,707 |
def AttenLogitsRPE(query, key, abs_pos_emb, is_causal):
"""Attention logits from ...
https://arxiv.org/pdf/1803.02155.pdf with trainable rel position emb.
Notice padding is supposed to be masked by the caller of this function.
B: batch size
T: sequence length
N: num of attention heads.
H: per-head atte... | d7d99c4ad07089e61516dd65b5765568542887a2 | 3,629,708 |
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re_art.sub(' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
return re_punc.sub(' ', text) # convert punctu... | 80e30ee45d665fca1c2ebdd20226da249028064e | 3,629,709 |
def qso_template_uv(wa, z):
""" Return a composite UV QSO spectrum at redshift z.
Wavelengths must be in Angstroms.
This is a smoothed version of the HST/COS EUV+FUV AGN composite
spectrum shown in Figure 5 of Shull, Stevans, and Danforth 2012.
Only good between 550 and 1730 Angstroms (rest frame... | 9c70e2f9c88b3d851951cd3e1b77638c21b99227 | 3,629,710 |
def encode_multipart_formdata(fields, files):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (headers, body) ready for httplib.HTTP instance
based on http://code.activest... | 7948d8ff0a2785b84c2e9a7e85182fa5db772692 | 3,629,711 |
def lanefinder_pipeline(img, video=False, debug=False):
"""
The pipeline for laneline finding based on all the techniques used so far
:param img: The image to find lanelines on
:return: An image with laneline boundaries drawn on
"""
# Undistort
undst = cv2.undistort(img, mtx, dist, None, mtx... | dfed7941b81197584c61f6f89aa45c69418a0768 | 3,629,712 |
from datetime import datetime
def get_ppl_experience(log_entries: QuerySet) -> dict:
"""
https://www.easa.europa.eu/sites/default/files/dfu/Part-FCL.pdf
(a) Applicants for a PPL(A) shall have completed at least 45 hours of flight instruction in aeroplanes or TMGs,
5 of which may have been complet... | 1fb2421352954c837b27fa46a47f36029a560ed8 | 3,629,713 |
import torch
def reconstruct_from_patches_2d(patches, img_shape, step=[1.0,1.0], batch_first=False):
"""Given patches generated from extract_patches_2d function, creates the original unpatched image. We keep track of the
overlapped regions and average them in the end.
Parameters:
patches ... | 35b03ee61dd5a2749601e839d7ade75d1b686383 | 3,629,714 |
def get_debug_queries():
"""
Return an array of queries executed within the context of a
:class:`DebugTracer` under the current application context and thread.
"""
return getattr(_app_ctx_stack.top, "storm_debug_queries", []) | a00f5b231e9b17c49da78815408850fcf2b7c122 | 3,629,715 |
def _LJ_rminepsilon_to_ab(coeffs):
"""
Convert rmin/epsilon representation to AB representation of the LJ
potential
"""
A = coeffs['epsilon'] * coeffs['Rmin']**12.0
B = 2 * coeffs['epsilon'] * coeffs['Rmin']**6.0
return {"A": A, "B": B} | 0963c0e8b949d35842660a499ce80a388485773f | 3,629,716 |
def get_offset_stars_ps1(df, target_name_column, target_ra_column,
target_dec_column, radius, data_release='dr2',
catalog='mean', quality_query=None, n=3, verbosity=0):
"""Get offset stars for all targets in the input DataFrame for PanSTARRS
using the MAST website.
... | f86390ba3a114934f682169ae82b830002e8a647 | 3,629,717 |
from yaml import load
from yaml import CLoader as Loader
from yaml import Loader
def _from_yaml(stream):
"""Load data form a YAML file or string."""
try:
except ImportError:
data = load(stream, Loader=Loader)
return data | 5fb82419c2705cb14077164b954aac530b5ddefb | 3,629,718 |
def is_unit_by_ten_thousand(text: str) -> bool:
"""
是否是以万为计量单位
@param: text 薪资描述字符串
@rtype: bool
"""
log.info(f'invoke method -> is_unit_by_ten_thousand(), salary unit text: {text}')
try:
unit = NumericUnit(text.strip())
except ValueError as e:
log.error(str(e))
r... | aeeac44391f5d06a181fd22246a510d16b500c9b | 3,629,719 |
def had_cells_north_edge(strmfunc, frac_thresh=0.1, lat_str=LAT_STR,
lev_str=LEV_STR):
"""Latitude of northern edge of northern Hadley cell."""
return had_cell_edge(
strmfunc,
cell="north",
edge="north",
frac_thresh=frac_thresh,
lat_str=lat_str,
... | f764801ef8047169b9138b696e52d24ef340369d | 3,629,720 |
def get_referrers(*objs): # real signature unknown; restored from __doc__
"""
get_referrers(*objs) -> list
Return the list of objects that directly refer to any of objs.
"""
return [] | a16f99e392b66b0b03d3dd298334b0af4d7d1246 | 3,629,721 |
def margAccRepay(asset, amount, isIsolated="", symbol="", recvWindow=""):
"""# Margin Account Repay (MARGIN)
#### `POST /sapi/v1/margin/repay (HMAC SHA256)`
Repay loan for margin account.
### Weight:
1
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------|--------
asset |STRING |YES |
isIso... | 639c9f33889ee97e1db95dccdb814a1becb79ba5 | 3,629,722 |
def clean_formula(formula: str) -> str:
"""
Translate mongo's syntax to hande columns names containing spaces to pandas syntax.
Example:
>>> clean_formula('colA * `col B` * [col C] * `[col D]`')
'colA * `col B` * `col C` * `[col D]`'
"""
formula_splitted = COLUMN_PATTERN.split(formu... | 522cfe6f5481e665e7cf0df136f6a2f384607eab | 3,629,723 |
def calculate_SI(aggregated_df):
""" calculates suspicion of infection as per Sepsis-3 on aggregated hourly dataframe and saves it under the column `suspicion_of_infection`.
Note:
aggregated_df must contain `antibiotics` and `microbio-sample` columns.
"""
df = aggregated_df[['hadm_id', 'hour', ... | 88f0fb6285c3fc2826168f01416e1e825b2ed4cc | 3,629,724 |
def _get_reduce_batch_axis(axis, x_dim, x_ndim):
"""get batch_axis for reduce* operation."""
if not isinstance(axis, tuple):
axis = (axis,)
batch_axis = ()
if axis:
for index in axis:
if index < x_dim:
batch_axis = batch_axis + (index,)
else:
... | b2a41f5e03c0388c70d2690793329d922f2d3248 | 3,629,725 |
def no_game_no_life(seed, rules, iterations, print_list):
"""
>>> rules = {3 : 1, 4 : 1, 8 : 1, 10 : 1, 11 : 1, 12 : 1, 15 : 1, 21 : 1,
... 23 : 1, 26 : 1, 27 : 1, 28 : 1, 29 : 1, 30 : 1}
>>> current_plants = no_game_no_life('1001010011000000111000111', rules, 20, True)
1000100001000001001001001
... | f8f8ab138a331cd413f3b730afd443c4a3de0e8c | 3,629,726 |
def evalrawexp(context, mapping, arg):
"""Evaluate given argument as a bare template object which may require
further processing (such as folding generator of strings)"""
func, data = arg
return func(context, mapping, data) | dc443da540bef0fe1198b12c0205921f0de66b2e | 3,629,727 |
def _execute_single_config_query(query_name, np1_list, peer_container, output_config):
"""
Runs a query on single set of policies
:param str query_name: the name of the arg.query
:param str np1_list: set of policies
:param PeerContainer peer_container: set of peers
:param OutputConfiguration out... | f49cbe947c952535ea72e0959ab35d9af724c854 | 3,629,728 |
import os
import re
def _ordernii_butterfly(niis):
"""Order a the provided list of nifti1 (.nii) files as appropriate
for the Ploran 2007 dataset (a.k.a butterfly).
"""
scanmap = {}
## Keyed on scode, values are a list of scans
for fipath in niis:
fi = os.path.basename(... | 549aebd5708cabd0d1386fb43ee4464bb04cf72c | 3,629,729 |
from typing import Tuple
def shape(A: Matrix) -> Tuple[int, int]:
"""returns the shape of a given matrix"""
num_rows = len(A)
num_cols = len(A[0]) if A else 0
return num_rows, num_cols | d0a76a63444d3b5e541d738eca591ff0a868da40 | 3,629,730 |
import functools
def integrity(integrity_func, retry_errors=(ResponseNotValid,)):
"""
Args:
:param integrity_func: couldb callable or string contains name of
method to call
"""
def build_decorator(func):
@functools.wraps(func)
def func_wrapper(self, grab, task):
... | de5ec2e8039919620bb448d8faedd6fe1fcc12fc | 3,629,731 |
import os
def get_file_list(path):
"""
获取文件夹下的所有文件,返回list
:param path:
:return:
"""
file_paths = []
get_dir = os.listdir(path)
for dir in get_dir:
tmp_path = os.path.join(path,dir)
if os.path.isdir(tmp_path):
file_paths.append({str(dir):get_file_list(tmp_pat... | 47f183479fb9304d33677fc811509f1801fa0130 | 3,629,732 |
def _convert_evaluation_data_to_frame(steps, evals):
"""Convert evaluation data to (tidy) data frame.
Args:
steps (namedtuple): Namedtuple with field names pos and neg. Is generated by
:func:`~estimagic.differentiation.generate_steps.generate_steps`.
evals (namedtuple): Namedtuple w... | 5ac049ed1b2e213e328b883905cf703ab9edde52 | 3,629,733 |
def unsharp_mask(rgb: np.ndarray, sigma: float, alpha=2.0) -> np.ndarray:
"""シャープ化。sigmaは0~1程度、alphaは1~2程度がよい?"""
rgb = ensure_channel_dim(rgb)
blured = blur(rgb, sigma)
rgb = rgb.astype(np.float32)
rgb = rgb + (rgb - blured) * alpha
return to_uint8(rgb) | 5c74995d7e322c1ff432320d8f18232bfcfdf4fb | 3,629,734 |
async def async_get_actions(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device actions for RFXCOM RFXtrx devices."""
try:
device = async_get_device_object(hass, device_id)
except ValueError:
return []
actions = []
for action_type in ACTION_TYPES:
if hasattr(... | d821c4e17dc4944b9cfe126e6cd959725d0a7b27 | 3,629,735 |
async def initialize_settings(user=Depends(login_required)):
"""
### 세팅값 초기화
- force: True일 경우 기존 값 초기화
"""
SettingModel.initialize(first=False)
return Response('Success', status_code=status.HTTP_200_OK) | 4e95029db3dcad14c7e08400d358b5fd098ad0b9 | 3,629,736 |
def build_generator(z_input: Input, label_input: Input):
"""
Build generator CNN
:param z_input: latent input
:param label_input: conditional label input
"""
model = Sequential([
Dense(128, input_dim=latent_dim),
LeakyReLU(alpha=0.2), BatchNormalization(momentum=0.8),
De... | e809026b7f4e326d8bd7190fa667b14888948688 | 3,629,737 |
import json
def annotate(project_id, document_id):
"""Annotate document with provided ID.
:param project_id: project id
:param document_id: document id
:return: rendered template
"""
current_user = auth.current_user
document_id = str(document_id)
project = services.get_project(current... | dc215edaf0e5d9829451b0e3c0adfe485db24231 | 3,629,738 |
def send_query_search_request(query, page):
"""Send a request to get one page of results for a query."""
logger.info(f'Sending a request for query {query}, page {page}')
return send_request(
query_url,
{'query': query, 'inclusive': True, 'page': page, 'api_key': api_key}) | 1ecfd2af4c61a1ccd811c506d25d6e9648ec9788 | 3,629,739 |
def find_stab(state, xs, zs):
"""
Find a stabilizer in the stabilizer group.
Args:
state:
logical_circuit:
delogical_circuit:
Returns:
"""
stabs = state.stabs
destabs = state.destabs
# Find the destabilizer generators that anticommute with the stabilizer indi... | 07987377192cb4a4fa8cc35bd13d7566a838778c | 3,629,740 |
def get_darwin_memory():
""" Use system-call to extract total memory on macOS """
system_output = sabnzbd.newsunpack.run_simple(['sysctl', 'hw.memsize'])
return float(system_output.split()[1]) | 16329528b4f9ea1ced90446e717f750276026f38 | 3,629,741 |
def normalise_release(release, area):
"""Try to normalise the release name.
None is a valid argument.
Note that the current policy to is accept any release name if an existing
tag is to be used, and only perform the normalisation on tags to be created
by this script.
Arguments:
releas... | 83fe9c7277aacc54b8679ab1f5cc7c5a1d3cebf6 | 3,629,742 |
from typing import Optional
def _pytd_return_type(
name: str,
return_type: Optional[pytd_node.Node],
is_async: bool
) -> pytd_node.Node:
"""Convert function return type to pytd."""
if name == "__init__":
if (return_type is None or
isinstance(return_type, pytd.AnythingType)):
ret = py... | 9e960570fd4064aaf0168b62214b9c0b53288236 | 3,629,743 |
def getvpidx(rate, bdepth):
"""Get the token numbers for indices of value and policy vectors."""
qpm = getqpm(rate, bdepth)
vidx = np.arange(qpm[0], qpm[2]+1, dtype=np.float64)/qpm[1]
pidx = np.arange(qpm[1], qpm[2]+1, dtype=np.float64)/qpm[1]
return vidx, pidx | 93783c23dff9f3122b994be41a084fdc9d63e2d4 | 3,629,744 |
import functools
def apply_on_axis(op, inputs, axis, *args, **kwargs):
"""Applies a differentiable operator on a given axis of the input.
Args:
op: a differentiable operator (can be ranks, quantile, etc.)
inputs: jnp.ndarray<float> of any shape.
axis: the axis (int) or tuple of ints on which to apply... | 2ef84e164acb1f018a5f4e7e7ef3a289f99886d4 | 3,629,745 |
from django.utils.text import normalize_newlines
import re
def clean_html(text):
"""
Clean the given HTML. Specifically, do the following:
* Convert <b> and <i> to <strong> and <em>.
* Encode all ampersands correctly.
* Remove all "target" attributes from <a> tags.
* Remove ex... | 7598a8c18e3cf3fc9bc256c33aed52a11c4bfa88 | 3,629,746 |
def get_report_importer_cls(library_name):
""" Return a ReportImporter class to handle importing a specific library's report information. """
lib_module = find_library_module(library_name)
if lib_module:
try:
return lib_module.REPORT_IMPORTER_CLASS
except AttributeError:
... | 964137420816bfbeb0eb7d22c861633dfd9efb67 | 3,629,747 |
def read_reddened_stars(filename):
"""
Read reddened stars from a text file.
Parameters
----------
filename : str
The name (with a path if neccessary) of the file which
has 5 five columns. The first one with integers, the rest
with floats. Each column represents: star_id, x_... | e9c50f90d9499cfa8544f41c808992ba10899ded | 3,629,748 |
def rotate_pil(image, angle, center=None, scale=1.0):
"""PIL旋转图像
效果比Image.rotate效果要好,调用rotate进行实现
"""
image = np.asarray(image)
rotated = rotate(image, angle)
return Image.fromarray(rotated) | 1ae75ddba68540b3b7b02cdeb11d62b7b9152fe0 | 3,629,749 |
def pobj_len(this):
"""
returns length (of String, List or Dict)
"""
return _new_pobj(Number, len(this.getvalue())) | 071abd1446e6e1d2394b41ccbf3063c6881f3505 | 3,629,750 |
def _compressed_sparse_stack(blocks, axis):
"""Fast path for stacking CSR/CSC matrices
(i) vstack for CSR, (ii) hstack for CSC.
"""
other_axis = 1 if axis == 0 else 0
data = cupy.concatenate([b.data for b in blocks])
constant_dim = blocks[0].shape[other_axis]
idx_dtype = sputils.get_index_dt... | 934ad0b1d1a26da3496b78e4a4c549c32a7923e5 | 3,629,751 |
def _parse_wall_max_height(response: HtmlResponse):
"""Parse max height of wall.
Returns 0 if not available.
"""
return _parse_length(response.css('th:contains("Höhe") + td ::text')) | b38ddbd8b9a6938fc57cf7cbfbb4feb1531b4525 | 3,629,752 |
def mandelbrot_square(z_min: complex, z_max: complex, n: int = 500,
n_max: int = 100, show_plot: bool = False,
axis: Axes = None, overall_extent: list[float] = None) -> AxesImage:
"""Visualise the mandelbrot set in a square matrix
Colours correspond to the num... | fcfcfdb036bde6c423abaed3884f7d22c86da735 | 3,629,753 |
def compatible(s1: Shape, s2: Shape):
"""Assert that two shapes are compatible shapes.
Args:
s1 (:class:`lab.shape.Shape`): First shape.
s2 (:class:`lab.shape.Shape`): Second shape.
Returns:
bool: Boolean indicating whether the two shapes are compatible.
"""
try:
ex... | 174b32f048fef109bc9383bdd8393f56fb3235b0 | 3,629,754 |
def get_job_service(request_type: RequestType) -> JobServiceInterface:
"""
This is a factory to get a corretly wired job service. Use that function to get any JobServiceInterface instance.
:param request_type: The request type. The JobServiceInterface is chosen and wired based on this type.
:return: Co... | 3ed998fc3ba19822100f7333bf69aa1ad4c6461e | 3,629,755 |
def get_index(repository_path, pkl_fname=PKL_FNAME):
"""
Return the index information for the EMTF repository located at
*repository_path*.
"""
pkl_fname, _ = initialize(repository_path, pkl_fname=pkl_fname)
with open(pkl_fname) as fid:
return cPickle.load(fid) | 1c3e3c333c0925ceeb167a8bfd32b4487c994454 | 3,629,756 |
def CycleTarget_to_c(self):
"""Syntax for a target of a cycle."""
return f"cycle_{self.targetID}: continue;" | 12cc7a57e5a24a62aba43ac99879d5a5d364ee29 | 3,629,757 |
def _run_ic(dataset):
"""Run iterative compression on a dataset."""
# Run
return solve_ic(
str(HUFFNER_DATA_DIR / (dataset + HUFFNER_DATA_EXT)),
timeout=EXACT_TIMEOUT,
preprocessing=2,
htime=min(0.3 * EXACT_TIMEOUT, 1)
) | a2e4bfd12d41720fe40a97f67294cd7234551525 | 3,629,758 |
import os
def _expand_target_patterns(blade, target_ids, excluded_trees):
"""Expand target patterns from command line."""
# Parse command line target_ids. For those in the form of <path>:<target>,
# record (<path>,<target>) in direct_targets; for the rest (with <path>
# but without <target>), record ... | abdea59b76865fedb90882dcdbf25d7eb6f7031c | 3,629,759 |
from typing import Callable
def expect_jwt(
api: Api,
message: str = "JWT token is required and has the format: 'Bearer <token>'",
) -> Callable:
"""
Adds expected header to swagger,
validates JWT token is present,
adds token to g
"""
def decorator(func: Callable) -> Callable:
... | 414fd3339414ddd190b1a7457c14a2791e848353 | 3,629,760 |
def get_pythia_definitions(parsed_file):
"""
Return a dictionary of all Pythia definitions in the input parsed file,
of the form
"PythiaBothParam <NAME>=<LABEL>"
or
"PythiaBothParam <NAME>=<NUMBER>",
as {'NAME1': 'LABEL1', 'NAME2': VALUE2, ...}.
Parameters
----------
parsed_file... | 4363ee6180847e0991b6b4a9ed3a8636ce70725c | 3,629,761 |
def disable_layer_logging():
"""
Disable the shape logging for all layers from this moment on. Can be
useful when creating multiple towers.
"""
class ContainEverything:
def __contains__(self, x):
return True
# can use nonlocal in python3, but how
globals()['_LAYER_LOGGED'... | e05785f1ade46903c2e66efc35d4fc5f0e9d4fbd | 3,629,762 |
def remove_punct(word: Text) -> Text:
"""Removes punctuation from the word. Returns String."""
result = ''.join([char.lower() for char in word if char.isalpha()])
if len(result) > 0 and result != None:
return result | 7ea8282488a6ddb6f01ecf303b5353dbf2848b24 | 3,629,763 |
def onCapability(name, value):
"""
Run test only if capability with `name` equals `value`.
"""
capability = getattr(process_capabilities, name)
def check_capability():
return capability != value
return skipOnCondition(
check_capability, 'Capability "%s" not present.' % name) | 22ec305df57ee8b2c39d82789b2a5badbbb46225 | 3,629,764 |
from re import U
def WGS84ReferenceSystem():
"""
returns the `GeodeticReferenceSystem` for the WGS84 Ellipsoid
"""
return GeodeticReferenceSystem(a=6378137.0 *U.m, f=1/298.257223563, angular_unit=1*U.DEG, height_unit=100.*U.km, name="WGS84") | 05e1ba83b451eebab752bfe018cd2a0d09f434e3 | 3,629,765 |
def _remap_keypoints(keypoints, padded_w, padded_h, expand, data_shape, ratio):
"""
Remap bboxes in (x0, y0, x1, y1) format into the input image space
Parameters
----------
bboxes
padded_w
padded_h
expand
Returns
-------
"""
keypoints[:, 0::2] *= padded_w / (data_shape ... | 1b8d2520f0df1847967e8db9c565598d6b5ee2b6 | 3,629,766 |
def viz_mask(mask):
"""Given a (batch, w, h, 10) array, returns a visualization"""
rgb_palette = np.array([(248, 183, 205), (246, 210, 224), (200, 231, 245), (103, 163, 217), (6, 113, 183),
(249, 200, 14), (248, 102, 36), (234, 53, 70), (102, 46, 155), (67, 188, 205)])
mask =... | e889f7aa630ed6b98074eb26279ab8bd1b157faf | 3,629,767 |
import click
def varg_command(cli, name, *others):
"""Create positional argument that are of variable length.
The token ``^`` can be used to mark the end of the argument list.
"""
def decorator(func):
r = click.argument(CommandAfterArgs.split_arg, nargs=-1)(func)
for o in reversed(ot... | a6d6d5e828d427e8d0534c36510640f0aa21632e | 3,629,768 |
def get_pipeline_lines(input_pipeline):
"""Returns a list with the lines in the .cppipe file"""
with open(input_pipeline) as f:
lines = f.readlines()
return lines | 403e7531b1cadfe25f519d2b176b97ac344cde6b | 3,629,769 |
def _f3_int_x_ ( self , *args ) :
""" Integrate 3D-function over x
>>> f = ...
>>> g = f.integrate_x ( 'x-range' )
- see ROOT.RooAbsReal.createIntegral
"""
##
vset = ROOT.RooArgSet ( self.xvar )
i = self.fun.createIntegral ( vset , *args )
##
return Fun2D ( i , self.yvar , s... | 2e70642a24f7882a0009e9be54ae903c4bf593cd | 3,629,770 |
def eotvos_number(L, lambda_c):
"""Returns the Eötvös/Bond number for the given liquid and gravity.
Parameters
----------
L : scalar (m) or Quantity
Characteristic length, ie. the radius of curvature at the top of the droplet.
lambda_c : scalar (m) or Quantity
The capillary length o... | e2fe6c435a47b62b29ebef7fc25895aafe4af62a | 3,629,771 |
def simple_update_property(attr_name, can_change=False,
type_cast_method=_string_type_cast):
"""Creates a simple @property corresponding to an attribute.
If can_change is True, also protects updating the value of this attribute.
Args:
attr_name: String; the name of a hid... | 24d91e3548c5c5b04402a2a904fe4c625e832ebf | 3,629,772 |
def _hyphenate_word(word):
""" Memoized hyphenate_word() function. """
cache = _hyphenate_word_cache
if word not in cache:
cache[word] = hyphenate_word(word)
return cache[word][:] | 660c419e5a512cad856b34117075dd984f1caacf | 3,629,773 |
def _rmse(y, y_bin, probs):
"""return 1-rmse since we're maximizing the score for hillclimbing"""
return 1.0 - sqrt(mean_squared_error(y_bin, probs)) | 2d6409ad829ba15fd9ff926708805cadd89c65d9 | 3,629,774 |
def skip_movie():
"""
The judge didn't like the movie they were presented with, so give them a new one.
Returns:
str: response string
"""
room = _get_room(request.args.get('code'))
movie = Movie.get_random()
room.current_round.movie = movie
# Send title & plot to host
sock... | a69e09b390aff269947cf6feeb8c5117bd7fc8ed | 3,629,775 |
import re
import os
import mimetypes
def static(req, resp):
"""Serves files from static directory"""
resp.content_type = const.TEXT_HTML
static = g.app.config.get('application', 'static').strip('/')
static_path_re = re.compile("^\/%s\/%s" %
(req.app.strip('/'), static,)... | 26f341cb2c092dfb4142bbec846507e28451b1a8 | 3,629,776 |
def argmin_2d(X):
"""Take the arg minimum of a 2D array."""
assert X.size > 0, "argmin of empty array not defined"
ii, jj = np.unravel_index(X.argmin(), X.shape)
return ii, jj | 1058c5bdce085b1bb953eb9e0d0a62bdc6a357af | 3,629,777 |
def get_cf():
"""
Get an authenticated cloudflare API instance. Authentication resolved in
order from:
1. `.cloudflare.cfg`
2. Environment variables
@see
https://github.com/cloudflare/python-cloudflare#providing-cloudflare-username-and-api-key
"""
return CloudFlare.CloudFlare() | 9eb6e31642254fae0d2a776fa3de7ce4ad85f429 | 3,629,778 |
def remove_user_past_events(user_id):
"""
:Route: DELETE /<user_id>/past?past_event=event_id&past_event=event_id
:Description: Remove past events for a single user with id `user_id`. If no past events are specified, all of the user's past events are removed.
:param user_id: The unique ID of a specific... | 80c83e5953144030ec1780c7127d9b2d5132e1f3 | 3,629,779 |
import requests
from bs4 import BeautifulSoup
def futures_index_dict():
"""
name and code map
:return: name to code
:rtype: dict
index_code
商品期货指数 CCFI
农产品期货指数 CAFI
油脂油料期货指数 OOFI
谷物期货指数 CRFI
油脂期货指数 OIFI
粮食期货指数 GRFI
... | bbe9558346e67473d9be317d14ce3b8aafb617bf | 3,629,780 |
def int_like(value, name, optional=False, strict=False):
"""
Convert to int or raise if not int_like
Parameters
----------
value : object
Value to verify
name : str
Variable name for exceptions
optional : bool
Flag indicating whether None is allowed
strict : bool... | cb70054688bbd08c8ca4ee6f5573e8918d3510aa | 3,629,781 |
def maxmin(*args):
"""
Returns timed ((t,max),(t,min)) values from a (t,v) dataset
When used to filter an array the winndow will have to be doubled to
allocate both values (or just keep the one with max absdiff from previous).
"""
data = args[0]
t = sorted((v,t) for t,v in data)
mn,mx... | 8f76ee029d04a4a35688054512d0a0212adbfede | 3,629,782 |
def from_none(exc):
"""raise from_none(ValueError('a')) == raise ValueError('a') from None"""
exc.__cause__ = None
exc.__suppress_context__ = True
return exc | 86e45ba2df0020c85f13b85d8a98ee693422e922 | 3,629,783 |
def create_1D_velocity_magnitude_array_RHS(number_of_flowrates_analyzed, lower_flowrate_design_value, upper_flowrate_design_value, D_fd):
"""Goal is to create an array of velocity magnitudes. Will be used to create the velocity components in accordance with the angle arrays previously determined.
Args:
... | 24bf026fa97e42e86e68ddbe99422575f2dff80d | 3,629,784 |
def get_interface_type(interface):
"""Gets the type of interface
"""
if interface.upper().startswith("ET"):
return "ethernet"
elif interface.upper().startswith("VL"):
return "svi"
elif interface.upper().startswith("LO"):
return "loopback"
elif interface.upper().startswith... | f770a3ef1c43574d22630a5c4fff2f25d4975279 | 3,629,785 |
from swingers.sauth.models import ApplicationLink
def retrieve_access_token(request, service):
"""
Returns url, access_token for a service and request.
Service should be a string representing a service to connect to.
System will introspect settings.SITE_NAME to find service.
Probably issues if mor... | aa4bdf6610aa63c739d66553868ee30cd0d78bc8 | 3,629,786 |
from typing import Union
from pathlib import Path
from typing import Any
import pickle
def load_pickle(path: Union[Path, str]) -> Any:
"""
Loads a pickle from the path
:param path:
:return:
"""
assert check_file_exists(path), f'"{path}" does not exist'
return pickle.load(open(path, 'rb')) | 33ec2c16e09141fda2faeb4ac20aa80cebf4d1cf | 3,629,787 |
def convolutional_encode2(layers, batch_norm, stim_in,
is_training, reuse_variables=False):
"""Embed stimulus using multiple layers of convolutions.
Each convolutional layer has convolution, batch normalization and soft-plus.
Args :
layers : string description of multiple layers.
... | fa1f8a7ea2ac1a8fdb19afaa3512959350b49195 | 3,629,788 |
import logging
import sys
def get_headers_and_fields(fileobject) -> list[str]:
"""
Add processed event fieldnames to fields.
"""
try:
headers = fileobject.readline().strip().split(",")
except Exception as e:
logging.exception("Error in reading mongoexport header")
sys.exit(... | 83e5c7e28ce70eaa93feb7aee84159c9d53bac94 | 3,629,789 |
def getUniqueExposures(conn, candidateList, limit = 0, mostRecent = True, nonDets = False, discoveryLimit = 10, lastDetectionLimit=20, requestType = REQUESTTYPES['incremental'], ddc = False):
"""getUniqueExposures.
Args:
conn:
candidateList:
limit:
mostRecent:
nonDets:
... | 4101909d59d481509ce90d738b5234574fdf5aba | 3,629,790 |
def rgb2gray(image):
"""Convert 3-channel RGB image into grayscale"""
if image.ndim == 3:
return (0.299 * image[:, :, 0] + 0.587 * image[:, :, 1] +
0.114 * image[:, :, 2])
elif image.ndim == 4:
return (0.299 * image[:, :, :, 0] + 0.587 * image[:, :, :, 1] +
0.... | f87ed301dfd9c13ebfbabf99ad4b56c959a91e46 | 3,629,791 |
def create_variable(workflow_stat):
"""
Generates the javascript variables used to generate the chart.
@param workflow_stat the WorkflowInfo object reference
"""
number_of_jobs = workflow_stat.total_job_instances
# Adding variables
var_str = "<script type='text/javascript'>\nvar initMaxX = " + str(workflow_sta... | d0b55b00952f28242775a297fedab6cf1a69169e | 3,629,792 |
def group_fnames_by_pair_param2_param3_and_param1(directory: str,
param1: str,
param2: str,
param3: str):
"""
:param directory: directory do folder, which contai... | 7598cebac63a26477545935acf51405d037d8edd | 3,629,793 |
def drought_add_facecolor(drought: pd.DataFrame) -> pd.DataFrame:
"""Add facecolor column before drought plot."""
bar_colors = np.array(['blue', 'cyan', 'green', 'orange', 'red'])
drought_index_band = pd.cut(drought.drought_index, [-1.0, -0.99, -0.5, +0.5, +0.99, +1.001], right=False)
drought['facecolor... | a69471c1d8fc8e2b7aa80ef22a5c3274fa0e211d | 3,629,794 |
def aten_le(mapper, graph, node):
""" 构造对比大小的PaddleLayer。
TorchScript示例:
%80 : bool = aten::le(%78, %79)
参数含义:
%80 (bool): 输出,第一个元素是否小于等于第二个元素。
%78 (-): 需对比的输入1。
%79 (-): 需对比的输入2。
"""
scope_name = mapper.normalize_scope_name(node)
output_name = mapper._get_ou... | 45797abf1ec5a97619578dd734c1d9d7fb448aec | 3,629,795 |
def fstr(*args, **kwargs):
"""fstr(format) is f-string format like. Uses locals and globlallas. Useful in Py2."""
if not args:
raise TypeError('missing format in fstr(format, *args, **kwargs)')
fmt, args = args[0], args[1:]
return vfstr(fmt, args, kwargs) | 61843ed4b35c9cb89b3855801097a4961e1f174e | 3,629,796 |
import logging
def race_store(cfg):
"""
Creates a proper race store based on the current configuration.
:param cfg: Config object. Mandatory.
:return: A race store implementation.
"""
if cfg.opts("reporting", "datastore.type") == "elasticsearch":
logging.getLogger(__name__).info("Creat... | 78b1b56d103a47e1ef941674ddd9c9b3debf16de | 3,629,797 |
def getframeinfo(frame, context=1):
"""Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line within that list.
Th... | 2d554d9db43fcc5a697e9b5db2486ba91fb59503 | 3,629,798 |
def Adjoint(T):
"""Computes the adjoint representation of a homogeneous transformation
matrix
:param T: A homogeneous transformation matrix
:return: The 6x6 adjoint representation [AdT] of T
Example Input:
T = np.array([[1, 0, 0, 0],
[0, 0, -1, 0],
... | 3894ecec8c4e1de01b550307c7df47fdc959d46e | 3,629,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.