content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def DownloadData(output_folder, latlim, lonlim, dataset, level = None):
"""
This function downloads SoilGrids data from SoilGrids.org
Keyword arguments:
output_folder -- directory of the result
latlim -- [ymin, ymax] (values must be between -50 and 50)
lonlim -- [xmin, xmax] (values must be betwe... | 5,287,400 |
def send_prediction(ui: UtopiaDataInterface, Ptgt, used_idx=None, timestamp:int=-1):
"""Send the current prediction information to the utopia-hub
Args:
ui (UtopiaDataInterface): the interface to the data-hub
Ptgt (np.ndarray (outputs,)): the current distribution of target probabilities over out... | 5,287,401 |
def run_codeml_for_sicos(codeml_dir, genome_ids_a, genome_ids_b, sico_files):
"""Run codeml for representatives of clades A and B in each of the SICO files, to calculate dN/dS."""
logging.info('Running codeml for %s aligned and trimmed SICOs', len(sico_files))
codeml_files = []
for sico_file in sico_fi... | 5,287,402 |
def serial_transmit_message(msg):
"""Frame up and send a message to the badge
The message should contain only printable characters.
"""
crc = '{0:04x}'.format(crc16.crc16xmodem(msg)).encode('ascii')
uart.send(frame_flag + msg + crc + frame_flag) | 5,287,403 |
def import_data(object_name):
"""Extract data from data dir."""
with open(f"data/{object_name}.pkl","rb") as my_file:
return pickle.load(my_file) | 5,287,404 |
def verify_tables(tablenames, columns, io1, io2):
"""Verify files contain tables and tables have same columns."""
for table in tablenames:
if not table in io1['data']:
print('File "{}" does not have table "{}".'.format(
args.fns_in[0], table), file=sys.stderr)
sys... | 5,287,405 |
def convert_to_nullable(input_val, cast_function):
"""For non-null input_val, apply cast_function and return result if successful; for null input_val, return None.
Args:
input_val (Any): The value to attempt to convert to either a None or the type specified by cast_function.
The recognized ... | 5,287,406 |
def maxSubArray(nums: List[int]) -> int:
"""
Time: O(n)
Space: O(1)
"""
local_max = 0
global_max = float('-inf')
for n in nums:
local_max = max(n, n + local_max)
if local_max > global_max:
global_max = local_max
return global_max | 5,287,407 |
def Nu_waste(Re_outtube_waste, Pr_coolwater_waste):
"""
Calculates the Nusselt criterion of coolwater.
Parameters
----------
Re_outtube_waste : float
The Reynold criterion, [dimensionless]
Pr_coolwater_waste : float
The Prandtl criterion, [dimensionless]
Returns
-------
... | 5,287,408 |
def fig_fire_assessment(assessment: SituationAssessment.WildfireCurrentAssessment,
original_ignition: ty.Sequence[TimedPoint],
max_time: float = np.inf) -> display.GeoDataDisplay:
"""Assessed wildfire map"""
gdd = display.GeoDataDisplay.pyplot_figure(assessment.ge... | 5,287,409 |
def calc_pi():
"""A crude (even for python) implentation of monte pi
"""
Nsample=100000000
x = np.random.rand(Nsample)
y = np.random.rand(Nsample)
count = np.sum(np.sqrt(x**2+y**2)<1)
return 4*count/Nsample | 5,287,410 |
def split_group(nsubj, ngroups):
"""Split the proposed group into random disjoint subgroups
Parameters
----------
nsubj (int) the number of subjects to be split
ngroups(int) Number of subbgroups to be drawn
Returns
-------
samples: a list of ngroups arrays containing
the i... | 5,287,411 |
def monkey_patch(**on):
"""Globally patches certain system modules to be greenthread-friendly.
The keyword arguments afford some control over which modules are patched.
If no keyword arguments are supplied, all possible modules are patched.
If keywords are set to True, only the specified modules are pa... | 5,287,412 |
def reduce_table(table, params, exclude_any=None, exclude_all=None):
"""Returns the subset of a table that satisfy the specified variables
table : pd.DataFrame
table to reduce (pandas table)
params : dict
params that must all be satisfied (each value must be scalar)
exclude : dict
... | 5,287,413 |
def get_maya_main_window():
"""return the main window of maya
:rtype: QtWidgets.QMainWindow
"""
ptr = mui.MQtUtil.mainWindow()
return shiboken2.wrapInstance(long(ptr), qtgui.QMainWindow) | 5,287,414 |
def test_init_invalid_sequence(sequence):
"""Exception must be raised with invalid input"""
with pytest.raises((ValueError, AttributeError)):
Lattice2DEnv(sequence) | 5,287,415 |
def get_rank1(x, dict_y):
"""
Computes rank-1 distance between one vector given a set of other vectors. The higher the better.
:param x: vector of appearances of the query object
:param dict_y: dictionnary of appearances of the candidates objects
"""
# We create a 2D-array with all the feature... | 5,287,416 |
def _align_column(strings, alignment, minwidth=0, has_invisible=True):
"""
[string] -> [padded_string]
>>> list(map(str,_align_column( \
["12.345", "-1234.5", "1.23", "1234.5", \
"1e+234", "1.0e234"], "decimal")))
[' 12.345 ', '-1234.5 ', ' 1.23 ', \
' 1234.5 ', ' ... | 5,287,417 |
def status(ctx):
"""Show status.
Guest mode: show the summary of OptHub status.
Owner mode: show the status of the current user.
Player mode: show the status of the current player.
:param ctx: Click context
"""
_logger.debug('status()')
execute(
ctx,
'''
query s... | 5,287,418 |
def atan2(y, x) -> Expression[float]:
"""
Calculates the arc tangent of a given coordinate.
"""
return _binary_op("atan2", y, x) | 5,287,419 |
def test_saturation_specific_humidity():
"""Test saturation_specific_humdiity."""
actual = saturation_specific_humidity(
[1000, 500]*units.mbar, [20, -20]*units.celsius)
truth = [0.01466435884730134, 0.001565585489192481]*units.dimensionless
assert_almost_equal(actual, truth, 6) | 5,287,420 |
def parse_header(header):
"""Read header information from 2 bytes:
- 1 byte for model id
- 4 bits for metric
- 4 bits for quality param
"""
model_id, code = header
quality = (code & 0x0F) + 1
metric = code >> 4
return (
"YUV",
inverse_dict(metric_ids)[metric],
... | 5,287,421 |
def test_auxiliary_power_lock_data_for_reading_copy_data_free_data(
channel, power_type, verbose):
"""test_auxiliary_power_lock_data_for_reading_copy_data_free_data.
DGILibAuxiliary.auxiliary_power_lock_data_for_reading
DGILibAuxiliary.auxiliary_power_copy_data
DGILibAuxiliary.auxiliary_power_f... | 5,287,422 |
def upload_generate_report():
"""Upload a txt file and display a query report"""
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('Pl... | 5,287,423 |
def test_convert_0():
"""Convert 0."""
assert utils.write_time(0) == '00s' | 5,287,424 |
def piece_size(file_size):
"""
Based on the size of the file, we decide the size of the pieces.
:param file_size: represents size of the file in MB.
"""
# print 'Size {0} MB'.format(file_size)
if file_size >= 1000: # more than 1 gb
return 2 ** 19
elif file_size >= 500 and file_size ... | 5,287,425 |
def provider_parser(subparser):
"""Configure provider parser"""
gransy_provider_parser(subparser)
subparser.description = "Compatibility proxy for Gransy site subreg.cz. The Subreg " \
"provider is deprecated, use Gransy provider instead." | 5,287,426 |
def execute(command):
"""
Run local image in a container
Arguments
---------
command: string of command to execute
"""
command = f'"{command}"'
process = subprocess.run(
f"docker exec --workdir $maple_target $maple_container bash -c {command}",
shell=True,
check=... | 5,287,427 |
def create_mock_datapath(num_ports):
"""Mock a datapath by creating mocked datapath ports."""
dp_id = random.randint(1, 5000)
dp_name = mock.PropertyMock(return_value='datapath')
def table_by_id(i):
table = mock.Mock()
table_name = mock.PropertyMock(return_value='table' + str(i))
... | 5,287,428 |
def get_gold():
"""
Return the gilded symbol.
"""
symbol = u'\u272A' if config.unicode else '*'
attr = curses.A_BOLD | Color.YELLOW
return symbol, attr | 5,287,429 |
def test_send_request_wrong_url():
"""Successful requests are tested by other tests in this file.
This test will trigger errors instead.
"""
not_an_url = "foo"
client = ensembl_api.EnsemblRestApiClient()
data = client.send_request(not_an_url)
assert type(data) == MissingSchema
url = f"h... | 5,287,430 |
def _CharTraits_get_hdf5_memory_type():
"""_CharTraits_get_hdf5_memory_type() -> hid_t"""
return _RMF_HDF5._CharTraits_get_hdf5_memory_type() | 5,287,431 |
def operator_unassigned_ticket(request, structure_slug,
structure, office_employee):
"""
Returns all unassigned tickets managed by operator
:type structure_slug: String
:type structure: OrganizationalStructure (from @is_operator)
:type office_employee: OrganizationalS... | 5,287,432 |
def raw_resolution(splitter=False):
"""
Round a (width, height) tuple up to the nearest multiple of 32 horizontally
and 16 vertically (as this is what the Pi's camera module does for
unencoded output).
Originally Written by Dave Jones as part of PiCamera
"""
width, height = RESOLUTION
i... | 5,287,433 |
def check_keys(dct):
"""Recursively check against '.' and '$' at start position in dictionary keys."""
if not isinstance(dct, dict):
raise TypeError('dict-like argument expected')
dot_err_str = 'MongoDB does not allow . in field names. "%s"'
dollar_err_str = 'MongoDB does not allow fields starti... | 5,287,434 |
def odd_improvement(lst):
"""Calculates the improvement of odds compared to their base values. The higher above 0, the more the odds
improved from base-value. The lower under 0, the more the odds deteriorated. Used
https://en.wikipedia.org/wiki/Logit as a source for this formula. """
base_probability =... | 5,287,435 |
def megabeast_wrapper(
megabeast_input_file, run_megabeast=False, diagnostic_plots=False, verbose=True
):
"""
Wrapper to run the MegaBEAST. This will eventually include making the diagnostic plots, too.
Parameters
----------
megabeast_input_file : string
Name of the file that contains ... | 5,287,436 |
def next_named_type(*args):
"""
next_named_type(ti, name, ntf_flags) -> char const *
Enumerate types. Returns mangled names. Never returns anonymous types.
To include it, enumerate types by ordinals.
@param ti (C++: const til_t *)
@param name (C++: const char *)
@param ntf_flags (C++: int)
"""
... | 5,287,437 |
async def read_role_by_id(
role_id: UUID,
*,
uow: IUnitOfWork = Depends(get_uow),
current_user: models.User = Depends(get_current_active_admin),
) -> models.Role:
"""Gets a specific role by their unique ID."""
role = uow.role.get(role_id)
if not role:
raise HTTPException(
... | 5,287,438 |
def my_name():
"""Returns the name of this BiBli"""
# start with the database
name = get_kv("name")
# fall back to the hostname
if not name:
name = socket.gethostname()
if "." in name:
name = name[:name.index(".")]
return name | 5,287,439 |
def balanced_bst(sorted_list):
"""Return balanced BST constructed from sorted list."""
return balanced_bst_rec(sorted_list, 0, len(sorted_list)) | 5,287,440 |
def send(buf, dest, tag, comm=lib.MPI_COMM_WORLD, datatype=lib.MPI_BYTE):
"""Perform a blocking send.
Parameters
----------
buf : bytes or any object supporting buffer interface
The send buffer
dest : int
Rank of destination
tag : int
Message tag
comm : MPI_Comm
... | 5,287,441 |
def silent_stderr():
""" Shush stderr for receiving unnecessary errors during setup. """
devnull = open(os.devnull, "w")
old = os.dup(sys.stderr.fileno())
os.dup2(devnull.fileno(), sys.stderr.fileno())
try:
yield devnull
finally:
os.dup2(old, sys.stderr.fileno()) | 5,287,442 |
def sql_query_tbr_create_table_dummy() -> TableDummySQL:
"""
returns table tbr create statement, dummy data insertion, and dummy data.
The dummy data is not constructed correctly, all are equal to -1 for
clarity. Message_id = -1 also ensures that first message_id will be set to 0.
Example where the... | 5,287,443 |
def enmap_from_healpix(hp_map, shape, wcs, ncomp=1, unit=1, lmax=0,
rot="gal,equ", first=0, is_alm=False, return_alm=False, f_ell=None):
"""Convert a healpix map to an ndmap using harmonic space reprojection.
The resulting map will be band-limited. Bright sources and sharp edges
could cause ringing. Use enma... | 5,287,444 |
def nearest(items, pivot):
"""Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Valu... | 5,287,445 |
def exclusively(f):
"""
Decorate a function to make it thread-safe by serializing invocations
using a per-instance lock.
"""
@wraps(f)
def exclusively_f(self, *a, **kw):
with self._lock:
return f(self, *a, **kw)
return exclusively_f | 5,287,446 |
def _read_header(file_object):
"""Get the entire header from a file, and return as dictionary"""
file_object.seek(0)
if _header_read_one_parameter(file_object) != "HEADER_START":
file_object.seek(0)
raise ValueError("Missing HEADER_START")
expecting = None
header = {}
while True:... | 5,287,447 |
def _create_data_table(
source: ColumnDataSource, schema: ProcSchema, legend_col: str = None
):
"""Return DataTable widget for source."""
column_names = [
schema.user_name,
schema.user_id,
schema.logon_id,
schema.process_id,
schema.process_name,
schema.cmd_lin... | 5,287,448 |
def x_integral(a, b, c, x):
"""
function involved in computing the a_matrix (Rayleigh Ritz approx of the spectrum)
@param a:
@param b:
@param c:
@param x:
@return: x_integral
"""
a_conj = np.conj(a)
# helper variables to tidy up function
k_0 = a * a_conj
k_1 = np.sqrt((k... | 5,287,449 |
def test() -> int:
"""
Testing that connection can be established
:return: int
"""
try:
connection = setup_connection()
setup.test()
cursor = connection.cursor()
# Print PostgreSQL Connection properties
print(connection.get_dsn_parameters(), "\n")
# P... | 5,287,450 |
def activate_virtualenv_in_precommit_hooks(session: Session) -> None:
"""Activate virtualenv in hooks installed by pre-commit.
Args:
session: The Session object.
This function patches git hooks installed by pre-commit to activate the
session's virtual environment. This allows pre-commit to loc... | 5,287,451 |
def next_line_same_block(line, *args):
""":type line: FrekiLine"""
next_line = line.doc.get_line(line.lineno+1)
return same_block(line, next_line) | 5,287,452 |
async def remove_orphaned_services(
registry: RedisResourceRegistry, app: web.Application
) -> None:
"""Removes services which are no longer tracked in the database
Multiple deployments can be active at the same time on the same cluster.
This will also check the current SWARM_STACK_NAME label of the se... | 5,287,453 |
def inspur_driver_debug_trace(f):
"""Log the method entrance and exit including active backend name.
This should only be used on Share_Driver class methods. It depends on
having a 'self' argument that is a AS13000_Driver.
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
driver = ar... | 5,287,454 |
def make_hash(hash_type="hashids") -> Hashids:
"""Factory function, can make different encoders in the future if needed"""
def make_hashid() -> Hashids:
"""Build a Hashid instance based on Django's settings.py configuration"""
try:
config = settings.PROXYID["hashids"]
sa... | 5,287,455 |
def iter_scss_deps(src_path):
"""Yields first-level dependencies from the given source path, which
should be a Sass file. Dependencies will either be more
Sass files or static image resources.
"""
assert os.path.isfile(src_path), src_path
root = os.path.dirname(src_path)
src = open(src_path)... | 5,287,456 |
def graph_from_polygon(polygon, network_type='all_private', simplify=True,
retain_all=False, truncate_by_edge=False, name='unnamed',
timeout=180, memory=None, date="",
max_query_area_size=50*1000*50*1000,
clean_periphery=True, infrastructure='way["highway"]'):
"""
Create a networkx gra... | 5,287,457 |
def subprocess(command, input_iterator):
"""Run a subprocess, yield its stdout.
Feeds bytes from input_iterator to the process in a separate thread.
Writes stderr of the process to our own stderr."""
def feeder(proc, input_iterator):
try:
for chunk in input_iterator:
... | 5,287,458 |
def cast_op(x, dtype):
"""The operation takes input tensor `x` and casts it to the output with `dtype`
Args:
x (oneflow.Tensor): A Tensor
dtype (flow.dtype): Data type of the output tensor
Returns:
oneflow.Tensor: A Tensor with specific dtype.
For example:
.. code-block::... | 5,287,459 |
def decode(model_output: np.ndarray, labels: dict) -> str:
"""Decodes the integer encoded results from inference into a string.
Args:
model_output: Results from running inference.
labels: Dictionary of labels keyed on the classification index.
Returns:
Decoded string.
"""
t... | 5,287,460 |
async def change_activity(*, atype=False, name=False, url=False, status=False, client):
"""Changes the bots activity
Note: atype stands for activity type since 'type' seems to be used by python itself
"""
with open('settings/config.json', 'r+') as f:
config = json.load(f)
# uppercase i... | 5,287,461 |
def CODE(string):
"""
Returns the numeric Unicode map value of the first character in the string provided.
Same as `ord(string[0])`.
>>> CODE("A")
65
>>> CODE("!")
33
>>> CODE("!A")
33
"""
return ord(string[0]) | 5,287,462 |
def usage(file_name):
""" This is usage for how to use this tool """
common.usage(file_name) | 5,287,463 |
def lookupExeFolder():
"""Returns executable folder path"""
if frozen:
exeFolder = (
# targetdir/Bitmessage.app/Contents/MacOS/Bitmessage
os.path.dirname(sys.executable).split(os.path.sep)[0] + os.path.sep
if frozen == "macosx_app" else
os.path.dirname(sys... | 5,287,464 |
def expected_weighted(da, weights, dim, skipna, operation):
"""
Generate expected result using ``*`` and ``sum``. This is checked against
the result of da.weighted which uses ``dot``
"""
weighted_sum = (da * weights).sum(dim=dim, skipna=skipna)
if operation == "sum":
return weighted_su... | 5,287,465 |
def matching(strategies):
"""Returns the number of strategy1's result.
Parameters
----------
strategies : list of str
Names of used strategies.
matching_number : int
Number of matches.
Returns
----------
count_win, count_lose, count_draw : int
result of matches... | 5,287,466 |
def set_logger_dir(dirname, action=None):
"""
Set the directory for global logging.
Args:
dirname(str): log directory
action(str): an action of ["k","d","q"] to be performed
when the directory exists. Will ask user by default.
"d": delete the directory. Note tha... | 5,287,467 |
def is_ec2_linux():
"""Detect if we are running on an EC2 Linux Instance
See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html
"""
if os.path.isfile("/sys/hypervisor/uuid"):
with open("/sys/hypervisor/uuid") as f:
uuid = f.read()
return uu... | 5,287,468 |
def flask_apis():
""" List of Flask RESTful APIs """
apilist = ["Geolocate by IP Address", "Geolocate by Lat/Long", "Phone Number Location", "Street Address Validation",
"Email Address Deliverablity", "IP Address to Consumer Profile"]
return render_template(
"flask.html",
c... | 5,287,469 |
def train_model(
X, y, df, model, num_epochs, skip_epochs, learning_rate,
plot_frames_dir, predictions_plot_mesh_size):
"""
Train the model by iterating `num_epochs` number of times and updating
the model weights through backpropagation.
Parameters
----------
model: Pytorch model
... | 5,287,470 |
def filter_get_project_samples_response(response, json_response):
"""Filter list project samples sensitive data from response."""
if "results" in json_response:
for result in json_response["results"]:
if "id" in result:
result["id"] = MOCK_UUID
if "client_id" in r... | 5,287,471 |
def extract_dictionary(dataframe, column, key_list=None, prefix=None, separator='.'):
"""
Extract values of keys in ``key_list`` into separate columns.
.. code-block:: python
>>> df = DataFrame({
... 'trial_num': [1, 2, 1, 2],
... 'subject': [1, 1,... | 5,287,472 |
def BetaPrime(alpha, beta, tag=None):
"""
A BetaPrime random variate
Parameters
----------
alpha : scalar
The first shape parameter
beta : scalar
The second shape parameter
"""
assert (
alpha > 0 and beta > 0
), 'BetaPrime "alpha" and "beta" paramete... | 5,287,473 |
def get_sweep_parameters(parameters, env_config, index):
"""
Gets the parameters for the hyperparameter sweep defined by the index.
Each hyperparameter setting has a specific index number, and this function
will get the appropriate parameters for the argument index. In addition,
this the indices wi... | 5,287,474 |
def cli(ctx, pipe, opt_dir_out, opt_ext, opt_frame_type, opt_prefix, opt_data_key):
"""Save to images"""
from os.path import join
import cv2 as cv
from vframe.settings import app_cfg
from vframe.utils import file_utils, im_utils
# --------------------------------------------------------------------... | 5,287,475 |
def test_Remove_All_Disks_At__FreePositions(score,max_score):
"""Function remove_all_disks_at: free positions."""
max_score.value += 3
try:
set_up()
Board.remove_all_disks_at(test_board_6,set([(1,2),(4,2),(5,3)]))
assert not Board.has_disk_at(test_board_6,(1,2))
assert Board.... | 5,287,476 |
def load_values(files):
"""
Loads the sasa values from the files in the files dictionary. Returns the maximum and minimum values.
Values are loaded into the "files" structure.
"""
min_val = float("inf")
max_val = 0.0
for filename in files:
files[filename]["values"] = numpy.loadtxt(f... | 5,287,477 |
def install(path, restart=False):
"""
Install a KB from a .msu file.
Args:
path (str):
The full path to the msu file to install
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.... | 5,287,478 |
def reproject_helper(args, raster_tuple, procnum, return_dict, resolution):
"""
Helper function for reprojection
"""
(pre_post, src_crs, raster_file) = raster_tuple
basename = raster_file.stem
dest_file = args.staging_directory.joinpath('pre').joinpath(f'{basename}.tif')
try:
return_... | 5,287,479 |
def create_board(user, **params):
"""Helper function to create a new board"""
defaults = {
'title': 'Test Board',
'code': 'tb'
}
defaults.update(**params)
return Board.objects.create(
user=user, **defaults
) | 5,287,480 |
def transform(resp_type):
"""A decorator to take a RundeckResponse and pass it through one of the is_transform marked
functions above
"""
def inner(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
results = func(self, *args, **kwargs)
try:
... | 5,287,481 |
def create_attributes_filter_rules_list(raw_attributes_filter_rules_list):
"""Validate and parse a list of attributes filter rules
:param raw_attributes_filter_rules_list: A list of filter rules of type
`attribute`, formatted as strings.
:return The list of filter rules that matches the provided... | 5,287,482 |
def glue_example_to_feature(
task,
examples,
tokenizer,
max_seq_len,
label_list,
pad_token=0,
pad_token_segment_id=0,
):
"""
task: the name of one of the glue tasks, e.g., mrpc.
examples: raw examples, e.g., common.SentenceExamples.
tokenizer: BERT/ROBERTA tokenizer.
max_... | 5,287,483 |
def mount(
storage=None, name="", storage_parameters=None, unsecure=None, extra_root=None
):
"""
Mount a new storage.
.. versionadded:: 1.0.0
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified, it will be infered from this
name.
... | 5,287,484 |
def rename_character(character, name) -> None:
"""Change the name of the character to the given name"""
... | 5,287,485 |
def labeled_comprehension(input,
labels,
index,
func,
out_dtype,
default,
pass_positions=False):
"""
Compute a function over an image at specified subregion... | 5,287,486 |
def get_resub(db: Session, *, name: str) -> Optional[Resub]:
"""Get the resub with the given name."""
return db.query(Resub).filter(Resub.name == name).first() | 5,287,487 |
def smooth_control_inputs_gaussian(log, sigma):
"""
Bind smoothed control inputs to the driving log using a Gaussian filter.
This more closely preserves the mean than the exponential smoothing (but
the outputs have so far been not that different).
"""
for control_column in CONTROL_COLUMNS:
... | 5,287,488 |
def load_batcher(dictionary: dict, args: argparse.Namespace) -> Batcher:
"""Loads batcher into CACHE and on subsequent calls, retrieves batcher
from cache.
Arguments:
dictionary {dict} -- Batcher dictionary
args {argparse.Namespace} -- Parsed commandline options
Returns:
Batche... | 5,287,489 |
def add_tags_to_certificate(CertificateArn=None, Tags=None):
"""
Adds one or more tags to an ACM certificate. Tags are labels that you can use to identify and organize your AWS resources. Each tag consists of a key and an optional value . You specify the certificate on input by its Amazon Resource Name (ARN). Y... | 5,287,490 |
def get_scaled_sum_aggregations(field_to_sum: str, pagination: Optional[Pagination] = None) -> Dict[str, A]:
"""
Creates a sum and bucket_sort aggregation that can be used for many different aggregations.
The sum aggregation scaled the values by 100 so that the scaled_floats are handled as integers to avoid... | 5,287,491 |
def create_vocabs(filepath: Text, src_vocab: Text, tar_vocab: Text) -> None:
"""
Create vocabularies from `NMTDataset`.
Args:
filepath: Path to txt file containing Translation. Used to initialise `NMTDataset`.
src_vocab: Path where to save source language vocabulary
tar_vocab: Path ... | 5,287,492 |
def _get_versions(client, bucket, key):
"""
Returns all the version IDs for a key ordered by last modified timestamp.
"""
resp_iterator = client.get_paginator("list_object_versions").paginate(
Bucket=bucket, Prefix=key
)
try:
versions = [version for page in resp_iterator for vers... | 5,287,493 |
def test_buildout(project_id):
"""Run the test command in the buildout project's base directory.
Tries to do some intelligent guessing about how tests should be run."""
project = Project.objects.get(id=project_id)
print("running tests for %s" % project.name)
test_binaries = []
# FIXME: HOLY NE... | 5,287,494 |
def associate_new_data(dataframe, df_studies_by_funder):
"""Merge two dataframes based on Case Study ID.
Takes a dataframe with the case study information and merges it with another
dataframe that contains case study IDs and some other data (e.g. funders, disciplines)
:params: a dataframe with case st... | 5,287,495 |
def print_v(text: str):
"""
Print a message preceded by modelspec always
"""
print_(text, True) | 5,287,496 |
def infer_feature_schema(features, graph, session=None):
"""Given a dict of tensors, creates a `Schema`.
Infers a schema, in the format of a tf.Transform `Schema`, for the given
dictionary of tensors.
If there is an override specified, we override the inferred schema for the
given feature's tensor. An over... | 5,287,497 |
def _parse_timestamp(exit_or_boot_timestamp):
"""
Parse boot_timestamp or exit_timestamp and return datetime object or None.
"""
timestamp = exit_or_boot_timestamp.strip(':')
if timestamp:
return datetime_parse(timestamp).replace(tzinfo=utc)
else:
return None | 5,287,498 |
def sig_handler(signum, stack):
"""
A function to handle OS signals to be able to gracefully shutdown
the program.
"""
print('Exiting...')
streamer.shutdown()
sys.exit(signum) | 5,287,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.