content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
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 - Patches from ... | 5,315,100 |
def test_raise_exception_BadRequest():
"""_raise_exception should raise the correct exceptions based on status."""
sc = steelconnection.SConnect("sc", connection_attempts=0)
sc.response = fake_requests.Fake_Response("", 400, {})
with pytest.raises(steelconnection.exceptions.BadRequest):
sc._rais... | 5,315,101 |
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", []) | 5,315,102 |
def barplot(df, x_label, y_label, title):
"""Creates bar plot of a given dataframe.
Args:
df: Pandas Dataframe that should have columns with columnnames specified in other arguments.
x_label: str, column name of x axis categories
y_label: str, column name of y axis values
title:... | 5,315,103 |
def p_declaracao_funcao(production):
"""declaracao_funcao : tipo cabecalho
| cabecalho
"""
node = DeclaracaoDeFuncao()
production_length = len(production)
index = 1
if production_length == 2:
tipo = Tipo()
tipo.rtype = 'vazio'
node.insert_nod... | 5,315,104 |
def main(check_type: str, path: str, version: str):
"""
Use this tool to verify that all expected packages are present in Apache Airflow svn.
In case of providers, it will generate Dockerfile.pmc that you can use
to verify that all packages are installable.
In case of providers, you should update `... | 5,315,105 |
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} | 5,315,106 |
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.
... | 5,315,107 |
def check_args(args):
"""Check arg validity."""
assert args.delay[0] <= args.delay[1]
assert args.bandwidth[0] <= args.bandwidth[1]
assert args.loss[0] <= args.loss[1]
assert args.queue[0] <= args.queue[1]
assert args.pretrained_model_path is None or args.pretrained_model_path.endswith(
... | 5,315,108 |
def _from_yaml(stream):
"""Load data form a YAML file or string."""
from yaml import load
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
data = load(stream, Loader=Loader)
return data | 5,315,109 |
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... | 5,315,110 |
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,
... | 5,315,111 |
def create_mixed_use_type(locator, internal_loads_df, indoor_comfort_df,
use_type_name, use_type_metadata, use_type_ratios_dict):
"""
Takes a list of use-types and their respective ratios to aggregate and create a new use-type
with schedules, internal loads and indoor comfort data
... | 5,315,112 |
def main():
"""
Start of execution; set up argument parser and get the arguments,
and start operations.
"""
parser = args_parse()
parser = set_args(parser)
pm = PluginMgr(parser)
parser = pm.call_add_args(parser)
(args, remaining) = parser.parse_known_args()
args.NAMES = NAMES
... | 5,315,113 |
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 [] | 5,315,114 |
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... | 5,315,115 |
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... | 5,315,116 |
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', ... | 5,315,117 |
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:
... | 5,315,118 |
def verifyScoringMethods(seriesclasslist):
"""Flashes a message if events comprising a series class use
more than one scoring methond (and probably shouldn't be combined)
"""
for scid, scinfo in seriesclasslist:
methods = []
for eid, ec in scinfo.items():
if eid == 'name' or ... | 5,315,119 |
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
... | 5,315,120 |
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) | 5,315,121 |
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... | 5,315,122 |
def clean_all_xydata():
"""Delete all xyData in current Session """
for xydata_key, xydata in session.xyDataObjects.items():
del xydata
return | 5,315,123 |
def test_get_candidate_fragments():
"""Test extraction of maximal longform candidate from text
"""
# Test with no excluded words
for text, result in zip([text1, text2, text3, text4, text5],
[result1, result2, result3, result4, result5]):
fragments = get_candidate_frag... | 5,315,124 |
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(fipath)
fi_nam... | 5,315,125 |
def convert_reshape(g, op, block):
"""Operator converter for reshape."""
input_shape = op.input("Shape")
input_shape_tensor = op.input("ShapeTensor")
data = g.get_node(op.input("X")[0])
if input_shape:
new_shape = g.get_node(input_shape[0])
new_shape = _infer_value(new_shape, g.get_... | 5,315,126 |
def ruby_spec_extra_config_files(current_api_version, path):
"""
Extra changes in ruby spec files for each release are done by this method
Files covered - spec/unit/oneview_sdk_spec.rb, spec/unit/resource_spec.rb, spec/unit/client_spec.rb,
spec/cli/version_spec.rb and spec/spec_helper.rb
"""
... | 5,315,127 |
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 | 5,315,128 |
def test_slackP_send_status_201(get_slackP, capsys, mocker):
"""
GIVEN a valid SlackPost object
WHEN send() is called
THEN assert the proper send sequence occurs
"""
con_mock = mocker.patch.object(SlackPost, '_construct_message')
req_mock = mocker.patch.object(requests, 'post')
req_mock.... | 5,315,129 |
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):
if isinsta... | 5,315,130 |
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_path)})
... | 5,315,131 |
def set_log_level(log_level=None):
"""set or reset the log level
Parameters
----------
log_level : str
Log level to set
"""
# check set log level against self defined log level array
if not log_level.upper() in valid_log_levels:
do_error_exit('Invalid log level: %s' % log_... | 5,315,132 |
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... | 5,315,133 |
def execute_drop_strategy(dataframe, arg_drop_count):
"""
Drop the first elements of dataframe
Args:
dataframe (pandas.Dataframe): Dataframe
arg_drop_count (int): rows to be dropped
"""
logging.debug('>>>>>>>>> Using drop rows strategy <<<<<<<<<<<<')
selected_drop_rows = MAX_... | 5,315,134 |
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) | 5,315,135 |
def community_per_member_optimised():
"""
Django pulls all objects including ForeignKey relation data
in single SQL join query:
>>> SELECT member.id, member.name, member.community_id, community.id,
community.name FROM member LEFT OUTER JOIN community ON
(member.community_id = community.... | 5,315,136 |
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(... | 5,315,137 |
def create_pdf_tickets_for_holder(order):
"""
Create tickets and invoices for the holders of an order.
:param order: The order for which to create tickets for.
"""
if order.status == 'completed' or order.status == 'placed':
pdf = create_save_pdf(render_template('pdf/ticket_purchaser.html', o... | 5,315,138 |
def test_first_run():
"""[summary]
Generate setup for first run and check if the directory and files are
created.
"""
setup_first_run(".", True, extra_context={"number_of_iterations": 2,
"project_name": "first_run_test",
... | 5,315,139 |
def random_transform():
"""
Transforms current selection randomnly as defined by scale and rotation limits in user values
"""
if APPLY_SCALE:
if UNIFORM_SCALE:
scale_u = random.uniform(SCALE_LIMITS_U[0], SCALE_LIMITS_U[1])
lx.eval("transform.channel scl.X {0}".format(sc... | 5,315,140 |
async def initialize_settings(user=Depends(login_required)):
"""
### 세팅값 초기화
- force: True일 경우 기존 값 초기화
"""
SettingModel.initialize(first=False)
return Response('Success', status_code=status.HTTP_200_OK) | 5,315,141 |
def run_method_tests(test):
"""Run all tests that exercise a method of a string object"""
test('capitalize', ' hello ', ' hello ')
test('capitalize', 'hello ', 'Hello ')
test('capitalize', 'aaaa', 'Aaaa')
test('capitalize', 'AaAa', 'Aaaa')
test('count', 'aaa', 3, 'a')
test('count', 'aaa', ... | 5,315,142 |
def main():
"""Main procedure"""
opt = get_options()
config_parameters, config_defauts = get_parameters(opt)
print("Create Jinja2 environment...")
env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=os.path.dirname(opt.template)),
trim_blocks=True,
... | 5,315,143 |
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... | 5,315,144 |
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_user.id, proj... | 5,315,145 |
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}) | 5,315,146 |
def test_doublewords():
"""tests doublewords"""
stdchecker = checks.StandardChecker()
assert passes(stdchecker.doublewords, "Save the rhino", "Save the rhino")
assert fails(stdchecker.doublewords, "Save the rhino", "Save the the rhino")
# Double variables are not an error
stdchecker = checks.Sta... | 5,315,147 |
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... | 5,315,148 |
def test_event_repr():
"""Base event should be reconstructible using it's repr for easy development."""
event = Event()
# The use of eval here is relevant to the repr convention
# pylint: disable=eval-used
assert eval(repr(event)).__dict__ == event.__dict__ | 5,315,149 |
def assert_array_almost_equal(x: numpy.float128, y: numpy.float128):
"""
usage.scipy: 6
"""
... | 5,315,150 |
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]) | 5,315,151 |
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... | 5,315,152 |
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 = pytd.NamedType("NoneType")
e... | 5,315,153 |
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 | 5,315,154 |
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 the operator. If
... | 5,315,155 |
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 extraneous HTML, such as presentational tags that open and
... | 5,315,156 |
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:
... | 5,315,157 |
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_... | 5,315,158 |
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) | 5,315,159 |
def grab_tweets():
"""
Searches for the list of tweets since the last job execution.
Yields relevant ones.
"""
max_id = r.get('max_id')
tweets = twitter_client.search(my_handle, since_id=max_id)
if tweets:
r.set('max_id', str(tweets[0].id))
else:
print("No one is tweeting... | 5,315,160 |
def pobj_len(this):
"""
returns length (of String, List or Dict)
"""
return _new_pobj(Number, len(this.getvalue())) | 5,315,161 |
def chat(message, arg):
"""
Arg: string amount
Does not return anything, but sets the variable "_endaga_ret" to the value
of the formatted currency string.
"""
resp = humanize_credits(int(arg))
consoleLog('info', "endaga_currency Chat %s -> %s" % (arg, resp))
message.chat_execute('set',... | 5,315,162 |
def add_MIDPOINT(self, timeperiod=14, type="line", color="secondary", **kwargs):
"""Midpoint Price over Period."""
if not self.has_close:
raise Exception()
utils.kwargs_check(kwargs, VALID_TA_KWARGS)
if "kind" in kwargs:
type = kwargs["kind"]
name = "MIDPOINT({})".format(str(timep... | 5,315,163 |
def check_git_installed() -> None:
"""Check if git is installed."""
with subprocess.Popen(
[GIT_PATH, "--help"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
) as process:
if process.wait():
raise click.ClickException("Git is not installed.") | 5,315,164 |
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... | 5,315,165 |
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')) | 5,315,166 |
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 th... | 5,315,167 |
def split_paragraphs(revision_text_dict, text):
""" Splits paragraphs into subparagraphs, if possible.
Any text belonging directly to the paragraph doesn't have
to be split any further.
"""
paragraph_id = 1
r = r"^[\s\S]*?(?=^1 |\Z)"
res = re.match(r, text, re.M)
revision_text_di... | 5,315,168 |
def test_add_tfds_id(dummy_builder: dataset_builder.DatasetBuilder): # pylint: disable=redefined-outer-name
"""Tests `add_tfds_id=True`."""
read_config = read_config_lib.ReadConfig(add_tfds_id=True)
ds = dummy_builder.as_dataset(split='train', read_config=read_config)
assert ds.element_spec == {
'id': tf... | 5,315,169 |
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... | 5,315,170 |
def enable_only( serial_numbers ):
"""
:param serial_numbers: A collection of serial-numbers to enable - all others' ports are
disabled and will no longer be usable!
"""
ports = [ get_port( sn ) for sn in serial_numbers ]
acroname.enable_ports( ports ) | 5,315,171 |
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... | 5,315,172 |
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) | 5,315,173 |
def CycleTarget_to_c(self):
"""Syntax for a target of a cycle."""
return f"cycle_{self.targetID}: continue;" | 5,315,174 |
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)
) | 5,315,175 |
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 <path> into ... | 5,315,176 |
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:
"""Adds expected header to sw... | 5,315,177 |
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... | 5,315,178 |
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'... | 5,315,179 |
def logger_callback(val):
""" Basic callback for multiprocessing just to log status of each job
- val is an integer returned by multiprocessing, describing the run
status
"""
logger.info("Multiprocessing run completed with status: %s" % val) | 5,315,180 |
def main(**kwargs):
"""Train a GAN using the techniques described in the paper
"Alias-Free Generative Adversarial Networks".
Examples:
\b
# Train StyleGAN3-T for AFHQv2 using 8 GPUs.
python train.py --outdir=~/training-runs --cfg=stylegan3-t --data=~/datasets/afhqv2-512x512.zip \\
--gp... | 5,315,181 |
def ensure_folder(*arg):
"""
Ensures the existence of a folder. If the folder does not exist it is created, otherwise nothing happens.
:param str | Path arg: Any number of strings of Path-objects which can be combined to a path.
"""
if len(arg) == 0:
raise Exception("No input to ensure_folde... | 5,315,182 |
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 | 5,315,183 |
def test_dataset_profile_property_tiled(data):
"""An tiled dataset's profile has block sizes"""
with rasterio.open('tests/data/shade.tif') as src:
assert src.profile['blockxsize'] == 256
assert src.profile['blockysize'] == 256
assert src.profile['tiled'] == True | 5,315,184 |
def add_logger(wf):
"""
Add logger to ``Workflow3.log`` attribute.
:type wf: Workflow3
"""
if not hasattr(wf, "log"):
logger = FileRotatingLogger(
name="aws_tools",
path=PATH_LOG.abspath,
max_bytes=1000000, # 1MB
backup_count=5,
)
... | 5,315,185 |
def test_byte_array():
"""Test byte arrays."""
ob = Test.ByteArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
max_ = 255
min_ = 0
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-... | 5,315,186 |
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) | 5,315,187 |
def main():
"""Read from the config file and get the Google maps info optionally"""
conf = configparser.ConfigParser()
config_file = os.path.join(os.path.dirname(__file__), "config.ini")
conf.read(config_file)
# get the apartments.com search URL(s)
apartments_url_config = conf.get('all', 'apar... | 5,315,188 |
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") | 5,315,189 |
def set_verbose(op):
"""Set verbosity status."""
global g_verbose
g_verbose = op | 5,315,190 |
def main():
"""Console script for gpx_converter."""
parser = argparse.ArgumentParser(
description="Convert from gpx to different formats or the other way around"
)
parser.add_argument(
"--function",
"-func",
help="conversion function to use",
type=str,
def... | 5,315,191 |
def Write(input_):
"""
Reads a WriteRequest from a file (text format) and sends it to the server.
It rewrites the device id and election id appropriately.
"""
req = p4runtime_pb2.WriteRequest()
if os.path.isfile(input_):
with open(input_, 'r') as f:
google.protobuf.text_forma... | 5,315,192 |
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 ... | 5,315,193 |
def test_docs_with_text(add_text, add_doc, add_citation):
"""
Citation_Index.docs_with_text() should return a set of ids for documents
that assign a given text.
"""
t1 = add_text()
t2 = add_text()
d1 = add_doc()
d2 = add_doc()
d3 = add_doc()
d4 = add_doc()
add_citation(te... | 5,315,194 |
def main():
"""Indicate sell signals."""
args = parse_args()
stocks = XueQiu.list_stocks(args.ebk)
stocks = check_sell(stocks, args)
common.show_result(stocks, '卖', args) | 5,315,195 |
def get_batch_prediction(BatchPredictionId=None):
"""
Returns a BatchPrediction that includes detailed metadata, status, and data file information for a Batch Prediction request.
See also: AWS API Documentation
:example: response = client.get_batch_prediction(
BatchPredictionId='string... | 5,315,196 |
def engine_queue_loop(port_dict):
"""
Specialized queue loop
"""
# Flow of information tags:
# NAME: engine_queue
update_proctitle('engine_queue_loop')
iface1, iface2 = port_dict['engine_url1'], port_dict['engine_url2']
name = 'engine'
queue_name = name + '_queue'
loop_name = qu... | 5,315,197 |
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 =... | 5,315,198 |
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(others):
... | 5,315,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.