content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def ft32m3(ft3):
"""ft^3 -> m^3"""
return 0.028316847*ft3 | 5,335,800 |
def get_audience(request):
"""
Uses Django settings to format the audience.
To figure out the audience to use, it does this:
1. If settings.DEBUG is True and settings.SITE_URL is not set or
empty, then the domain on the request will be used.
This is *not* secure!
2. Otherwise, sett... | 5,335,801 |
def visit(obj, visitor: BooleanExpressionVisitor[T]) -> T:
"""A generic function for applying a boolean expression visitor to any point within an expression
The function traverses the expression in post-order fashion
Args:
obj(BooleanExpression): An instance of a BooleanExpression
visitor(... | 5,335,802 |
def max_shading_elevation(total_collector_geometry, tracker_distance,
relative_slope):
"""Calculate the maximum elevation angle for which shading can occur.
Parameters
----------
total_collector_geometry: :py:class:`Shapely Polygon <Polygon>`
Polygon corresponding to t... | 5,335,803 |
def tensor_scatter_add(input_x, indices, updates):
"""
Creates a new tensor by adding the values from the positions in `input_x` indicated by
`indices`, with values from `updates`. When multiple values are given for the same
index, the updated result will be the sum of all values. This operation is almo... | 5,335,804 |
def test100():
"""
CIFAR-100 test set creator.
It returns a reader creator, each sample in the reader is image pixels in
[0, 1] and label in [0, 9].
:return: Test reader creator.
:rtype: callable
"""
return reader_creator(
paddle.v2.dataset.common.download(CIFAR100_URL, 'cifar'... | 5,335,805 |
def test_s3_16_2v03_s3_16_2v03i(mode, save_output, output_format):
"""
tests restriction facet in intervening union
"""
assert_bindings(
schema="ibmData/valid/S3_16_2/s3_16_2v03.xsd",
instance="ibmData/valid/S3_16_2/s3_16_2v03.xml",
class_name="Root",
version="1.1",
... | 5,335,806 |
def setupradiusserver(step):
""" This function is to setup radius server in the ops-host image
"""
h1 = hosts[0]
h2 = hosts[1]
switchip = get_switch_ip(step)
print("SwitchIP:" + switchip)
out = h2("sed -i \"76s/steve/steve/\" /etc/freeradius/users")
out = h2("sed -i \"76s/#steve/steve/\... | 5,335,807 |
def extract_mapped_read_records(fastq_fwd, fastq_rev, read_ids, paired_out, unpaired_out, unaligned_out):
"""
Split FASTQ files into a FASTQ with the aligned and one with the unaligned reads.
:param fastq_fwd: Forward FASTQ file used for creating the SAM file.
:param fastq_rev: Reverse FASTQ file used ... | 5,335,808 |
def clear():
"""Cleanup Moler's configuration"""
global loaded_config
loaded_config = ["NOT_LOADED_YET"]
conn_cfg.clear()
dev_cfg.clear() | 5,335,809 |
def _calculate_target_matrix_dimension(m, kernel, paddings, strides):
"""
Calculate the target matrix dimension.
Parameters
----------
m: ndarray
2d Matrix
k: ndarray
2d Convolution kernel
paddings: tuple
Number of padding in (row, height) on one side.
If you... | 5,335,810 |
def any_email():
"""
Return random email
>>> import re
>>> result = any_email()
>>> type(result)
<type 'str'>
>>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None
True
"""
return "%s@%s.%s" % (any_string(max_length=10),
... | 5,335,811 |
def transform_pts_base_to_stitched_im(pts):
"""Project 3D points in base frame to the stitched image
Args:
pts (np.array[3, N]): points (x, y, z)
Returns:
pts_im (np.array[2, N])
inbound_mask (np.array[N])
"""
im_size = (480, 3760)
# to image coordinate
pts_rect = ... | 5,335,812 |
def get_equal_static_values(*args):
"""get_equal_static_values(FileConstHandle input, FileConstHandle out) -> bool"""
return _RMF.get_equal_static_values(*args) | 5,335,813 |
def quaternion_to_rotation_matrix(quaternion):
"""
This converts a quaternion representation of on orientation to
a rotation matrix. The input is a 4-component numpy array in
the order [w, x, y, z], and the output is a 3x3 matrix stored
as a 2D numpy array. We follow the approach in
"3D Math P... | 5,335,814 |
def load_subject(filename: str,
mask_niimg):
"""
Load a subject saved in .mat format with
the version 7.3 flag. Return the subject
niimg, using a mask niimg as a template
for nifti headers.
Args:
filename <str> the .mat filename for the subject... | 5,335,815 |
def get_data_monash(directory):
"""
Get the monash data in a dictionary
"""
# Generate the wildcard for the models
wildcard = os.path.join(directory, "*")
model_files = glob.glob(wildcard)
all_models = {}
for model_file in model_files:
# First extract the filename
file_n... | 5,335,816 |
def pretty_duration(seconds):
"""Return a human-readable string for the specified duration"""
if seconds < 2:
return '%d second' % seconds
elif seconds < 120:
return '%d seconds' % seconds
elif seconds < 7200:
return '%d minutes' % (seconds // 60)
elif seconds < 48 * 360... | 5,335,817 |
def delete_bucket(zkclient, bucket_id):
"""Deletes bucket definition from Zoookeeper."""
zkutils.ensure_deleted(zkclient, z.path.bucket(bucket_id)) | 5,335,818 |
def plot_ecdf(tidy_data, cats, val, title, width=550, conf_int=False):
"""
Plots an ECDF of tidy data.
tidy_data: Set of tidy data.
cats: Categories to plot
val: The value to plot
title: Title of plot
width: width of plot
conf_int: Whether or not to bootstrap a CI.
"""
p = bokeh... | 5,335,819 |
def upsert(left, right, inclusion=None, exclusion=None):
"""Upserts the specified left collection with the specified right collection by overriding the
left values with the right values that have the same indices and concatenating the right values
to the left values that have different indices on the common keys tha... | 5,335,820 |
def train(training_data):
"""Trains the model on a given data set.
Parameters
----------
training_data
Returns
-------
"""
counts = Counter(training_data)
model = {}
# sort counts by lowest occurrences, up to most frequent.
# this allows higher frequencies to overwrite rel... | 5,335,821 |
def _exit():
"""Exit the program."""
exit() | 5,335,822 |
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['cache'] = 86400
desc['description'] = """This chart totals the number of distinct calendar
days per month that a given present weather condition is reported within
the MET... | 5,335,823 |
def check_cortex(ioc, ioc_type, object_id, is_mail=False, cortex_expiration_days=30):
"""Run all available analyzer for ioc.
arguments:
- ioc: value/path of item we need to check on cortex
- ioc_type: type of the ioc (generic_relation and cortex datatype)
- object_id: item to attach report to
-... | 5,335,824 |
def test_assert_callback_not_called_when_not_called(
callable_group: MockCallableGroup,
schedule_call: Callable,
) -> None:
"""
Test that assert_no_item succeeds when the item is produced too late.
:param callable_group: the callable group under test
:param schedule_call: a callable used to sch... | 5,335,825 |
def _env_corr_same(wxy, Xa, Ya, sign=-1, log=True, x_ind=None, y_ind=None):
"""
The cSPoC objective function with same filters for both data sets:
the correlation of amplitude envelopes
Additionally, it returns the gradients of the objective function
with respect to each of the filter coefficients.... | 5,335,826 |
def create_resource():
"""Hosts resource factory method"""
deserializer = HostDeserializer()
serializer = HostSerializer()
return wsgi.Resource(Controller(), deserializer, serializer) | 5,335,827 |
def test_write_two_regions_starting_from_position_that_is_bigger_than_file_length(chunk_size, local_file, mount_file):
"""TC-PIPE-FUSE-67"""
actual_size = os.path.getsize(local_file)
write_regions(local_file, {'offset': actual_size + 5, 'amount': 10}, {'offset': actual_size + 20, 'amount': 10})
write_re... | 5,335,828 |
def resolve_media_files(document, resource):
""" Embed media files into the response document.
:param document: the document eventually containing the media files.
:param resource: the resource being consumed by the request.
.. versionadded:: 0.4
"""
for field in resource_media_fields(document... | 5,335,829 |
def reformat(args):
"""Reformats a database to comply with diamond
diamond makedb has some requirements when adding taxonomic info
1. protein seqids cannot be longer than 14 characters
2. nodes.dmp and names.dmp must be supplied
3. a prot.accession2taxid.gz file mapping protein ids to taxonomy ids ... | 5,335,830 |
def get_ref_kmer(ref_seq, ref_name, k_len):
""" Load reference kmers. """
ref_mer = []
ref_set = set()
for i in range(len(ref_seq) - k_len + 1):
kmer = ref_seq[i:(i + k_len)]
if kmer in ref_set:
raise ValueError(
"%s found multiple times in reference %s, at p... | 5,335,831 |
def get_distutils_build_or_install_option(option):
""" Returns the value of the given distutils build or install option.
Parameters
----------
option : str
The name of the option
Returns
-------
val : str or None
The value of the given distutils build or install option. If ... | 5,335,832 |
def boot(num):
""" Show boot sequence on screen """
_boot(num) | 5,335,833 |
def test_hist_bbox(basic_image):
"""Test that the bbox dimensions are customizable."""
f, ax = ep.hist(basic_image, figsize=(50, 3))
bbox = str(f.__dict__.get("bbox_inches"))
assert bbox == "Bbox(x0=0.0, y0=0.0, x1=50.0, y1=3.0)" | 5,335,834 |
def CMDset_close(parser, args):
"""Closes the issue."""
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error('Unrecognized args: %s' % ' '.join(args))
cl = Changelist(auth_config=auth_config)
# Ensure t... | 5,335,835 |
def gchip(k_k, b_b, c_c):
"""gchip(k_k, b_b, c_c)"""
yout = b_b*c_c*nu_f(1, b_b, k_k)**((c_c+1)/2)*\
cos((c_c+1)*atan(b_b*k_k))
return yout | 5,335,836 |
def register(args: argparse.Namespace) -> None:
"""
Handler for `lambada register`, which registers a new lambada function against a simiotics
registry
Args:
args
`argparse.Namespace` object containing parameters to the `register` command
Returns: None, prints key of registered functio... | 5,335,837 |
def epochs_sim_agg_returns_cov_market_plot(agg_ret: pd.Series, epochs_len: int) -> None:
"""Plots the aggregated distribution of simulated returns for a market.
:param agg_ret: simulated rotated and aggregated returns from a simulated
market.
:type agg_ret: pd.Series
:param epochs_len: length of t... | 5,335,838 |
def create_component(ctx: NVPContext):
"""Create an instance of the component"""
return ProcessUtils(ctx) | 5,335,839 |
def is_valid_ip(ip: str) -> bool:
"""
Args:
ip: IP address
Returns: True if the string represents an IPv4 or an IPv6 address, false otherwise.
"""
try:
ipaddress.IPv4Address(ip)
return True
except ValueError:
try:
ipaddress.IPv6Address(ip)
... | 5,335,840 |
def complete_tree(leaves):
"""
Complete a tree defined by its leaves.
Parmeters:
----------
leaves : np.array(dtype=np.int64)
Returns:
--------
np.array(dtype=np.int64)
"""
tree_set = _complete_tree(leaves)
return np.fromiter(tree_set, dtype=np.int64) | 5,335,841 |
def pick_best_batch_size_for_gpu():
"""
Tries to pick a batch size that will fit in your GPU. These sizes aren't guaranteed to work, but they should give
you a good shot.
"""
free, available = torch.cuda.mem_get_info()
availableGb = available / (1024 ** 3)
if availableGb > 14:
return... | 5,335,842 |
def getTensorRelativError(tA, pA):
"""Get the relative error between two tensors."""
pA_shape = np.shape(pA)
tA_shape = np.shape(tA)
assert (pA_shape == tA_shape), "Arrays must be same shape"
err = np.max(np.abs(np.array(pA)-np.array(tA)))
return err | 5,335,843 |
def eliminations(rct_gras, prd_gras):
""" find eliminations consistent with these reactants and products
:param rct_gras: reactant graphs (must have non-overlapping keys)
:param prd_gras: product graphs (must have non-overlapping keys)
Eliminations are identified by forming a bond between an attacking... | 5,335,844 |
def ParseAndCreateModel(inputFilePath, jsonFilePath = None, outputFilePath = None, className = "SBMLmodel"):
"""
This function parses an SBML model file and generates a Python file implementing the model.
Parameters
----------
inputFilePath : str
Location of the SBML model to be pa... | 5,335,845 |
def sigmoid(*columns):
"""Fit a Sigmoid through the data of the last scan.
The return value is a pair of tuples::
((a, b, x0, c), (d_a, d_b, d_x0, d_c))
where the elemets of the second tuple the estimated standard errors of the
fit parameters. The fit parameters are:
* a - amplitude of ... | 5,335,846 |
def update_dictionary_count(dictionary: dict, key: str):
"""
Add 1 to the specified dictionary key or create a dictionary entry for that key.
@param dictionary: The dictionary to be updated
@param key: String holding the dictionary key
@return: None (Dictionary is updated)
"""
dictionary[ke... | 5,335,847 |
def _install(
bz2,
recipe_name,
debug=False,
meta_recipe=False,
env_var_dir="",
env_var_file="",
parent_name="",
commands_file="",
):
"""Method to install a local pre-built package to ensure package installs correctly
_install
========
This method is used to install a p... | 5,335,848 |
def MakeSamplesFromOutput(metadata, output):
"""Create samples containing metrics.
Args:
metadata: dict contains all the metadata that reports.
output: string, command output
Example output:
perfkitbenchmarker/tests/linux_benchmarks/nccl_benchmark_test.py
Returns:
Samples containing training m... | 5,335,849 |
def _write_bytes_to_temporary_file(local_path):
"""if `local_path` is a file-like object, write the contents to an *actual* file and
return a pair of new local filename and a function that removes the temporary file when called."""
if hasattr(local_path, "read"):
# `local_path` is a file-like object... | 5,335,850 |
def tree_to_newick_rec(cur_node):
""" This recursive function is a helper function to generate the Newick string of a tree. """
items = []
num_children = len(cur_node.descendants)
for child_idx in range(num_children):
s = ''
sub_tree = tree_to_newick_rec(cur_node.descendants[child_idx])... | 5,335,851 |
def clean(layers, skiplayers, db_url):
"""Clean and index the data after load
"""
db = fwa.util.connect(db_url)
# parse the input layers
in_layers = parse_layers(layers, skiplayers)
for layer in settings.source_tables:
table = fwa.tables[layer['table']]
if layer['table'] in in_la... | 5,335,852 |
def create_data_bucket():
"""
Creates the main GCS data bucket; enables logging and versioning for the bucket
and sets/overwrites access rights according to best practices.
:return: None
"""
run_command('gsutil mb -p {} -c {} -l {} gs://{}'
.format(PROJECT_ID, DATA_STORAGE_CLAS... | 5,335,853 |
def stop_at_chimera_removal(inFolder, outFolder, rdb, trimq, joining_method,
qcq, maxloose, fastq_p):
"""
"""
global PR
trimmed = asfolder(outFolder + PR['Ftrimmed'])
merged = asfolder(outFolder + PR['Fmerged'])
qc = asfolder(outFolder + PR['Fqc'])
chi = asfold... | 5,335,854 |
def mdetr_efficientnetB3(pretrained=False, return_postprocessor=False):
"""
MDETR ENB3 with 6 encoder and 6 decoder layers.
Pretrained on our combined aligned dataset of 1.3 million images paired with text.
"""
model = _make_detr("timm_tf_efficientnet_b3_ns")
if pretrained:
checkpoint =... | 5,335,855 |
def goods_insert():
"""Goods Insert"""
products = (
('์ ํ1', 30000, 'wenyang-x700.jpg', 10, 3, '์ ํ1์ ๋ํ ์ค๋ช
์ด ์ฌ๊ธฐ์ ๋ค์ด์ต๋๋ค'),
('์ ํ2', 33000, 'tamara-bellis-x700.jpg', 10, 5, '์ ํ2์ ๋ํ ์ค๋ช
์ด ์ฌ๊ธฐ์ ๋ค์ด์ต๋๋ค'),
('์ ํ3', 35000, 'roland-denes-x700.jpg', 10, 1, '์ ํ3์ ๋ํ ์ค๋ช
์ด ์ฌ๊ธฐ์ ๋ค์ด์ต๋๋ค'),
('์ ํ4', 3300... | 5,335,856 |
def _check_EJR_brute_force(profile, committee):
"""
Test using brute-force whether a committee satisfies EJR.
Parameters
----------
profile : abcvoting.preferences.Profile
A profile.
committee : iterable of int
A committee.
Returns
-------
bool
"""
# should... | 5,335,857 |
def read_stanford_labels():
"""Read stanford hardi data and label map"""
# First get the hardi data
fetch_stanford_hardi()
hard_img, gtab = read_stanford_hardi()
# Fetch and load
files, folder = fetch_stanford_labels()
labels_file = pjoin(folder, "aparc-reduced.nii.gz")
labels_img = nib... | 5,335,858 |
def generate_generators(n_vals, replicas, output_directory):
""" Generate generators and save them in `output_directory`. Will read an
array of n values from `n_vals`, generating `replicas` generators for each
n value. Creates with deterministic state machine generators. """
filename_format = os.path.abspath(ou... | 5,335,859 |
def _WrapRequestForUserAgentAndTracing(http_client, trace_token,
trace_email,
trace_log,
gcloud_ua):
"""Wrap request with user-agent, and trace reporting.
Args:
http_client: The original http ob... | 5,335,860 |
def indexData_x(x, ukn_words):
"""
Map each word in the given data to a unique integer. A special index will be kept for "out-of-vocabulary" words.
:param x: The data
:return: Two dictionaries: one where words are keys and indexes values, another one "reversed" (keys->index, values->words)
... | 5,335,861 |
def BFS_TreeSearch(problem):
"""
Tree Search BFS
Args->problem: OpenAI Gym environment
Returns->(path, time_cost, space_cost): solution as a path and stats.
"""
node = Node(problem.startstate, None)
time_cost = 0
space_cost = 1
if node.state == problem.goalstate:
return buil... | 5,335,862 |
def remove_metaRotation(gA_rot: GeoArray, rspAlg='cubic') -> GeoArray:
"""Remove any metadata rotation (a rotation that only exists in the map info)."""
gA = GeoArray(*warp_ndarray(gA_rot[:], gA_rot.gt, gA_rot.prj,
rspAlg=rspAlg,
# out_gsd=(gA_rot.... | 5,335,863 |
def _objective_function(extra_features: jnp.ndarray,
media_mix_model: lightweight_mmm.LightweightMMM,
media_input_shape: Tuple[int,
int], media_gap: Optional[int],
target_scaler: Optional[preprocessi... | 5,335,864 |
def decode_block(block: np.ndarray) -> Union[np.ndarray, bool]:
"""
Decode a data block with hamming parity bits.
:param block: The data block to be decoded
:return the decoded data bits, False if the block is invalid
"""
if not block.size & block.size - 1 and block.size & 0x5555_5555:
... | 5,335,865 |
def clone():
"""
Clone the student repositories for the assignment and (optionall) copies
notebook files into the course_materials 'submitted' directory. Clones into
the clone_dir directory, as specified in config.yml.
Requires that you have filename of student roster
defined in config.yml and ... | 5,335,866 |
def kt_android_library(name, exports = [], visibility = None, **kwargs):
"""Creates an Android sandwich library.
`srcs`, `deps`, `plugins` are routed to `kt_jvm_library` the other android
related attributes are handled by the native `android_library` rule.
"""
# TODO(bazelbuild/rules_kotlin/issues... | 5,335,867 |
def occupancy(meta, ax=None):
""" Show channel occupancy over time.
"""
if ax is None:
f, ax = plt.subplots()
f.set_figwidth(14)
f.suptitle("Occupancy over time")
start_time = meta.read_start_time.min() / 10000 / 60
end_time = meta.read_end_time.max() / 10000 / 60
to... | 5,335,868 |
def reg1_r_characteristic(r, s, alpha, beta, c, h):
"""
evaluate x - ((4/3)r - (2/3)s)t in region 1, equation 19
"""
# when s < 0 the expression can be factored and you avoid the
# difference of nearly equal numbers and dividing by a small number
# equation 74
rr = r/c
ss = s/c
pol... | 5,335,869 |
def olf_gd_offline_in_z(X: np.ndarray, k: int, rtol: float = 1e-6,
max_iter: int = 100000,
rectY: bool = False, rectZ: bool = False,
init: str = 'random', Y0=None, Z0=None,
verbose: bool = False, alpha=1,
cycle=500, rho=1, be... | 5,335,870 |
def get_features(model_description_features: List[Dict[str, Any]]):
"""Get features from a list of dictionaries
Parameters
----------
model_description_features : List[Dict[str, Any]]
Examples
--------
>>> l = [{'StrokeCount': None}, \
{'ConstantPointCoordinates': \
... | 5,335,871 |
def get_cluster_codes(cluster: pd.Categorical) -> pd.Series:
"""Get the X location for plotting p-value string."""
categories = cluster.cat.categories.rename("cluster")
return pd.Series(range(len(categories)), index=categories, name="x") | 5,335,872 |
def _expand_configurations_from_chain(chain, *, pragma: str = 'pytmc',
allow_no_pragma=False):
"""
Wrapped by ``expand_configurations_from_chain``, usable for callers that
don't want the full product of all configurations.
"""
def handle_scalar(item, pvname, co... | 5,335,873 |
def encrypt(data=None, key=None):
"""
Encrypts data
:param data: Data to encrypt
:param key: Encryption key (salt)
"""
k = _get_padded_key(key)
e = AES.new(k, AES.MODE_CFB, k[::-1])
enc = e.encrypt(data)
return base64.b64encode(enc) | 5,335,874 |
def get_logger(logdir_path=None):
"""logging.Logger
Args
----
logdir_path: str
path of the directory where the log files will be output
Returns
-------
logger (logging.Logger): instance of logging.Logger
"""
log_format = (
'%(levelname)-8s - %(asctime)s - '
... | 5,335,875 |
def set_is_dirty_for_all_views(is_dirty: bool) -> None:
"""
@brief Set is_dirty for all views.
@param is_dirty Indicate if views are dirty
"""
for w in sublime.windows():
for v in w.views():
if is_view_normal_ready(v):
view_is_dirty_val(v, is_dirty) | 5,335,876 |
def combine_results (input_files, output_files):
"""
Combine all
"""
(output_filename, success_flag_filename) = output_files
with open(output_filename, "w") as out:
for inp, flag in input_files:
with open(inp) as ii:
out.write(ii.read())
with open(success_flag... | 5,335,877 |
def add_ROCR100(self, timeperiod=10, type="line", color="tertiary", **kwargs):
"""Rate of Change (Ratio * 100)."""
if not self.has_close:
raise Exception()
utils.kwargs_check(kwargs, VALID_TA_KWARGS)
if "kind" in kwargs:
type = kwargs["kind"]
name = "ROCR100({})".format(str(timepe... | 5,335,878 |
def box_in_k_largest(boxes, box, k):
"""Returns True if `box` is one of `k` largest boxes in `boxes`. If there are ties that
extend beyond k, they are included."""
if len(boxes) == 0:
return False
boxes = sorted(boxes, reverse=True, key=box_volume)
n = len(boxes)
prev = box_volume(boxes[... | 5,335,879 |
def _config_cron_workflow(
schedule,
concurrency_policy='"Allow"', # Default to "Allow"
successful_jobs_history_limit=3, # Default 3
failed_jobs_history_limit=1, # Default 1
starting_deadline_seconds=10,
suspend="false",
timezone="Asia/Shanghai", # Default to Beijing time
):
"""
... | 5,335,880 |
def print_report_row(col1, col2, col3, col4):
"""Prints memory usage report row"""
print("{: >20} {: >10} {: >10} {: >10}".format(col1, col2, col3, col4)) | 5,335,881 |
def diagonal(a, offset=0, axis1=0, axis2=1):
"""
Returns specified diagonals.
If `a` is 2-D, returns the diagonal of a with the given offset, i.e., the
collection of elements of the form a[i, i+offset]. If `a` has more than two
dimensions, then the axes specified by axis1 and axis2 are used to dete... | 5,335,882 |
def available_number_of_windows_in_array(n_samples_array, n_samples_window, n_advance):
"""
Parameters
----------
n_samples_array
n_samples_window
n_advance
Returns
-------
"""
stridable_samples = n_samples_array - n_samples_window
if stridable_samples < 0:
print("... | 5,335,883 |
def tensor_to_image(tensor: torch.tensor) -> ndarray:
"""
Convert a torch tensor to a numpy array
:param tensor: torch tensor
:return: numpy array
"""
image = TENSOR_TO_PIL(tensor.cpu().clone().squeeze(0))
return image | 5,335,884 |
def translate_fields(translations, proto_set, fields):
"""In-place replace text with translations for one proto_set."""
for item in proto_set.data_array:
for field in fields:
val = getattr(item, field)
if val:
setattr(item, field, translations[val]) | 5,335,885 |
def shimizu_mirioka(XYZ, t, a=0.75, b=0.45):
"""
The Shinizu-Mirioka Attractor.
x0 = (0.1,0,0)
"""
x, y, z = XYZ
x_dt = y
y_dt = (1 - z) * x - a * y
z_dt = x**2 - b * z
return x_dt, y_dt, z_dt | 5,335,886 |
def mock_client_fixture():
"""Prevent setup."""
with patch("custom_components.porscheconnect.Client") as mock:
instance = mock.return_value
instance.getVehicles.return_value = async_return([])
instance.getAllTokens.return_value = async_return([])
instance.isTokenRefreshed.return_... | 5,335,887 |
def draw_cap_peaks_rh_coord(img_bgr, rafts_loc, rafts_ori, raft_sym, cap_offset, rafts_radii, num_of_rafts):
"""
draw lines to indicate the capillary peak positions
in right-handed coordinate
:param numpy array img_bgr: the image in bgr format
:param numpy array rafts_loc: the locations of rafts
... | 5,335,888 |
def plot_calibration_results(
run_dict_list,
fig_scale=1,
aggregation="median",
legend=True,
legend_kwargs=None,
ax=None,
):
"""
Plot calibration results
Parameters
----------
run_dict_list : list[dict]
List of dicts, each with keys
id: Run id
... | 5,335,889 |
def invoke(command):
"""Invoke sub-process."""
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT)
status = 0
except subprocess.CalledProcessError as error: # pragma: no cover
output = error.output
status = error.returncode
return status, output | 5,335,890 |
def pack_bidirectional_lstm_state(state, num_layers):
"""
Pack the hidden state of a BiLSTM s.t. the first dimension equals to the number of layers.
"""
assert (len(state) == 2 * num_layers)
_, batch_size, hidden_dim = state.size()
layers = state.view(num_layers, 2, batch_size, hidden_dim).trans... | 5,335,891 |
def _create_record_from_template(template, start, end, fasta_reader):
"""Returns a copy of the template variant with the new start and end.
Updates to the start position cause a different reference base to be set.
Args:
template: third_party.nucleus.protos.Variant. The template variant whose
non-locat... | 5,335,892 |
def run_W_E(cfg=None, eta_path=None, pris_path=None, etrm_daily_path=None, output_folder=None, is_ssebop=False, is_jpl=False, shape=None,
start_date=None, end_date=None, time_step='monthly', eta_output=None, precip_output=None, ratiomod=True):
"""
:return:
"""
# over 15 years we normalize e... | 5,335,893 |
def create_outputfile(prxdoc,inputfiles_element,inputfilehref,nominal_outputfilehref,outputfilehref,outputdict,ignore_locking):
"""Create the output XML file from the raw input by running any filters, etc.
It will be presumed that the output XML file will eventually be referred to by nominal_outputfilehref,
... | 5,335,894 |
def test_resolver():
"""Simple test of the DNS resolver
"""
hosts = ['www', 'mail', 'maps']
dns_servers = ['8.8.8.8', '4.2.2.2']
r = resolver.Resolver(
hostnames=hosts,
domain='google.com',
nameservers=dns_servers,
tries=1
)
cache = r.resolve()
assert le... | 5,335,895 |
def section3():
"""
## Convert Mask Annotations to Polygon
More about from_segmentation() function on <a href="https://console.dataloop.ai/sdk-docs/dtlpy.entities.annotation_definitions.html#dtlpy.entities.annotation_definitions.polygon.Polygon.from_segmentation" target="_blank">here</a>.
""" | 5,335,896 |
def get_example_data(filepath: str, is_gzip: bool = True, make_bytes: bool = False) -> BytesIO:
"""
่ทๅ็คบไพๆฐๆฎ๏ผไธ่ฝฝๆๅผๆไปถ๏ผ่ฟ่ก่งฃๅ็ผฉใ
:param filepath: ๆไปถ่ทฏๅพใ
:param is_gzip: ๆฏๅฆๅ็ผฉ็ใ
:param make_bytes: ๅญ่ๆฐๆฎใ
:return:
"""
# ๅฆๆๆฌๅฐๅญๅจๅไปๆฌๅฐๅ ่ฝฝ
local_path = os.path.join(EXAMPLES_FOLDER, "data", filepath)
... | 5,335,897 |
def test_get_InSar_flight_comment(data_name, expected):
"""
Test we can formulate a usefule comment for the uavsar annotation file
and a dataname
"""
blank = '{} time of acquisition for pass {}'
desc = {blank.format('start', '1'): {'value': pd.to_datetime('2020-01-01 10:00:00 UTC')},
... | 5,335,898 |
def convert_time(time_string):
"""
Input a time in HH:MM:SS form and output
a time object representing that
"""
return time.strptime(time_string, "%H:%M") | 5,335,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.