content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def guess(key, values):
"""
Returns guess values for the parameters of this function class based on the input. Used for fitting using this
class.
:param key:
:param values:
:return:
"""
return [min(values)-max(values), (max(key)-min(key))/3, min(values)] | 5,329,100 |
def add_metadata_values_to_record(record_message, schema_message):
"""Populate metadata _sdc columns from incoming record message
The location of the required attributes are fixed in the stream
"""
extended_record = record_message['record']
extended_record['_sdc_batched_at'] = datetime.now().isoform... | 5,329,101 |
def manipulate_reservation_action(request: HttpRequest, default_foreward_url: str):
"""
This function is used to alter the reservation beeing build inside
a cookie. This function automatically crafts the required response.
"""
js_string: str = ""
r: GroupReservation = None
u: Profile = get_c... | 5,329,102 |
def get_Y_feed(X, datapath=None, upsample=False):
"""
Generator for getting each Y vector (label vector) that corresponds to each X vector.
X is a list of: [(reversed, fv), (reversed, fv), ...]
A Y vector is a numpy array that looks like this:
[A_betrays_B_in_one_season, A_betrays_B_in_two_seasons,... | 5,329,103 |
def _decompose(number):
"""Generate digits from `number` in base alphabet, least significants
bits first.
Since A is 1 rather than 0 in base alphabet, we are dealing with
`number - 1` at each iteration to be able to extract the proper digits.
"""
while number:
number, remainder ... | 5,329,104 |
def _dense_to_sparse(data):
"""Convert a numpy array to a tf.SparseTensor."""
indices = np.where(data)
return tf.SparseTensor(
np.stack(indices, axis=-1), data[indices], dense_shape=data.shape) | 5,329,105 |
def wait_for_block(network: vegaNetwork, height: int = 1) -> None:
"""Wait for block at specific height"""
for validator_id in range(network.validators_count()):
host, public_port, private_port = network.api_address(validator_id)
client = vegaClient(host, public_port, private_port)
for _... | 5,329,106 |
def update_migration_index(db: typing.Any, index: int) -> None:
"""
Set the database's migration index to the given index.
This function also ensures that the migration index can only ever be
increased and fails with an assertion error otherwise.
:param db: the database
:param index: the new m... | 5,329,107 |
def subcommand2(args):
"""
Subcommand2
"""
print("This is subcommand2") | 5,329,108 |
def getflookup(facetid):
"""
find out if a facet with this id has been saved to the facet_files table
"""
found = FacetLookup.objects.all().values_list('graphdb', flat=True).get(id=facetid)
if found:
return True
else:
return False | 5,329,109 |
def numeric_to_string(year):
"""
Convert numeric year to string
"""
if year < 0 :
yearstring = "{}BC".format(year*-1)
elif year >= 0:
yearstring = "{}AD".format(year)
else:
raise
return yearstring | 5,329,110 |
def code_server(HandlerClass, ServerClass=ThreadingHTTPServer, protocol="HTTP/1.0", port=8000, bind="", ssl=False):
"""
This runs an HTTP server on port 8000 (or the port argument).
"""
server_address = (bind, port)
HandlerClass.protocol_version = protocol
with ServerClass(server_address, Han... | 5,329,111 |
def validate_arguments(
expected_types: Mapping[str, QueryArgumentGraphQLType], arguments: Mapping[str, Any]
) -> None:
"""Ensure that all arguments are provided and that they are of the expected type.
Backends are the database languages we have the ability to compile to, like OrientDB MATCH,
Gremlin, ... | 5,329,112 |
def _get_num_ve_sve_and_max_num_cells(cell_fracs):
"""
Calculate the num_ve, num_sve and max_num_cells
Parameters
----------
cell_fracs : structured array, optional
A sorted, one dimensional array,
each entry containing the following fields:
:idx: int
Th... | 5,329,113 |
def is_void(at):
"""Returns True if the given object is an ``adatetime`` with all of its
attributes equal to None.
"""
if isinstance(at, datetime):
return False
return all((getattr(at, attr) is None) for attr in adatetime.units) | 5,329,114 |
def _get_metric_fn(params):
"""Get the metrix fn used by model compile."""
batch_size = params["batch_size"]
def metric_fn(y_true, y_pred):
"""Returns the in_top_k metric."""
softmax_logits = y_pred
logits = tf.slice(softmax_logits, [0, 1], [batch_size, 1])
# The dup mask should be obtained from... | 5,329,115 |
def test_subclass_nt_to_phenotypic_feature(rosetta,eg):
"""named_thing -> Phenotype """
node = KNode('HP:0001874', type=node_types.NAMED_THING)
rosetta.synonymizer.synonymize(node)
assert eg.get_leaf_type(node,node_types.NAMED_THING)[0]== node_types.PHENOTYPIC_FEATURE | 5,329,116 |
def mark_contention_and_waiters(all_lock_periods):
"""
thread 1 -> ------ lock ------ locked ------ unlocked ------
thread 2 -> ------------- lock ---------------------- locked
thread 3 -> lock ------------------------------------ ...... locked
=> contention means A thread <locked> after B thread <... | 5,329,117 |
def check():
"""Check if all required modules are present.
Returns 0 on success, non-zero on error.
"""
flag = 0
for package in import_list:
try:
exec( "import " + package )
except Exception:
log.error( "Missing module: %s", package )
flag = True
... | 5,329,118 |
def flip_nums(text):
""" flips numbers on string to the end (so 2019_est --> est_2019)"""
if not text:
return ''
i = 0
s = text + '_'
while text[i].isnumeric():
s += text[i]
i += 1
if text[i] == '_':
i += 1
return s[i:] | 5,329,119 |
def nnls(A, b, k=None, maxiter=None):
"""
Compute the least-squares solution to the equation ``A @ x = b`` subject to
the nonnegativity constraints ``x[:k] >= 0``.
Parameters
----------
A : array_like, shape (m, n)
Matrix `A` as shown above.
b : array_like, shape (m,)
Right-... | 5,329,120 |
def send_new_submission_message(submission):
"""
Sends an embed to the specified Discord webhook with details of the Reddit submission.
"""
# Escape any formatting characters in the title since it'll apply them in the embed.
title = discord.escape_formatting(submission.title)
embed_json = {
... | 5,329,121 |
def test_question_correct_index_set():
"""Test set correct answer index
"""
q = exam2pdf.Question("Who are you?")
a1 = exam2pdf.Answer()
a2 = exam2pdf.Answer()
q.add_answer(a1)
q.add_answer(a2)
q.correct_index = 1
assert q.correct_answer == a2
assert q.correct_index == 1 | 5,329,122 |
def read_inputs(filename, height, padding, num_quant_levels, p_norm,
predict_semantics):
"""Reads inputs for scan completion.
Reads input_sdf, target_df/sem (if any), previous predicted df/sem (if any).
Args:
filename: TFRecord containing input_sdf.
height: height in voxels to be processe... | 5,329,123 |
def f_elas_linear_tsswlc(x, t3, t2, e_b, gam, e_par, e_perp, eta):
"""Compute spring forces and torques on each bead of dsswlc."""
N, _ = x.shape
f = np.zeros(x.shape)
t = np.zeros(x.shape)
for i in range(0, N - 1):
dx = x[i+1] - x[i]
dx_par = dx @ t3[i]
dx_perp = dx - dx_par... | 5,329,124 |
def extent2(texture):
""" Returns the extent of the image data (0.0-1.0, 0.0-1.0) inside its texture owner.
Textures have a size power of 2 (512, 1024, ...), but the actual image can be smaller.
For example: a 400x250 image will be loaded in a 512x256 texture.
Its extent is (0.78, 0.98), the... | 5,329,125 |
def clean_all_annotations_in_directory(
input_directory,
output_directory=None,
check_misnomers=True,
verbose=True):
"""
Cleans every annotation file in a directory and saves the invalid
annotations to their own file so that they can be checked and fixed.
Invalid annotat... | 5,329,126 |
def calculate_handlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
# Store the total length of the hand
hand_len = 0
# For every letter in the hand
for key in hand.keys():
# Add th... | 5,329,127 |
def add_fieldmap(fieldmap: BIDSFile, layout: BIDSLayout) -> dict:
"""
Locates fieldmap-related json file and adds them in an appropriate dictionary with keys that describe their directionality
Parameters
----------
fieldmap : BIDSFile
Fieldmap's NIfTI
layout : BIDSLayout
BIDSLay... | 5,329,128 |
def fit_plane_lstsq(XYZ):
"""
Fits a plane to a point cloud.
Where z=a.x+b.y+c; Rearranging: a.x+b.y-z+c=0
@type XYZ: list
@param XYZ: list of points
@rtype: np.array
@return: normalized normal vector of the plane in the form C{(a,b,-1)}
"""
[rows, cols] = XYZ.shape
G = np.ones(... | 5,329,129 |
def setup_logging(default_path='logging.json',
default_level=logging.INFO, env_key='LOG_CFG'):
"""Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
... | 5,329,130 |
def clean_name(name: str) -> str:
"""Clean a string by capitalizing and removing extra spaces.
Args:
name: the name to be cleaned
Returns:
str: the cleaned name
"""
name = " ".join(name.strip().split())
return str(titlecase.titlecase(name)) | 5,329,131 |
def pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]:
"""
Pull a list of items.
"""
items = []
with pull_block(buf, capacity) as length:
end = buf.tell() + length
while buf.tell() < end:
items.append(func())
return items | 5,329,132 |
def ResNet(
stack_fn, preact, use_bias, model_name='resnet', include_top=True, weights='imagenet',
input_tensor=None, input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', bottomright_maxpool_test=False,
use_group_norm=False, **kwargs):
"""Instantiates the Re... | 5,329,133 |
def read_yaml(yaml_path):
"""
Read yaml file from the path
:param yaml_path:
:return:
"""
stream = open(yaml_path, "r")
docs = yaml.load_all(stream)
result = dict()
for doc in docs:
for k, v in doc.items():
result[k] = v
return result | 5,329,134 |
def _server_allow_run_on_save() -> bool:
"""Allows users to automatically rerun when app is updated.
Default: true
"""
return True | 5,329,135 |
def _strip_schema(url):
"""Returns the url without the s3:// part"""
result = urlparse(url)
return result.netloc + result.path | 5,329,136 |
def simple_word_tokenize(text, _split=GROUPING_SPACE_REGEX.split):
"""
Split text into tokens. Don't split by a hyphen.
Preserve punctuation, but not whitespaces.
"""
return [t for t in _split(text) if t and not t.isspace()] | 5,329,137 |
def merge_strategy(media_identifier, target_site, sdc_data, strategy):
"""
Check if the file already holds Structured Data, if so resolve what to do.
@param media_identifier: Mid of the file
@param target_site: pywikibot.Site object to which file should be uploaded
@param sdc_data: internally forma... | 5,329,138 |
def convert_translations_to_dict(js_translations):
"""Convert a GNUTranslations object into a dict for jsonifying.
Args:
js_translations: GNUTranslations object to be converted.
Returns:
A dictionary representing the GNUTranslations object.
"""
plural, n_plural = _get_plur... | 5,329,139 |
def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None):
"""
Apply function of two arguments cumulatively to the items of sequence,
from left to right, so as to reduce the sequence to a single value.
Reduction will be executed sequentially without concurrency,
so passed values... | 5,329,140 |
def validate_JSON_dict(value):
""" validates if value JSON decodes to a Python dict """
try:
d = json.loads(value)
if type(d) is not dict:
raise ValidationError('%(value)s is not a JSON dictionary', params={'value': value})
except json.decoder.JSONDecodeError as e:
raise ... | 5,329,141 |
def sigm_temp(base_sim_param, assumptions, t_base_type):
"""Calculate base temperature depending on sigmoid diff and location
Parameters
----------
base_sim_param : dict
Base simulation assumptions
assumptions : dict
Dictionary with assumptions
Return
------
t_base_cy :... | 5,329,142 |
def test_slc25a6(ncbi, slc25a6):
"""Test that SLC25A6 normalizes to correct gene concept."""
# Concept ID
normalizer_response = ncbi.search('NCBIgene:293')
assertion_checks(normalizer_response, slc25a6, 1, MatchType.CONCEPT_ID)
# Symbol
normalizer_response = ncbi.search('SLC25A6')
assertion... | 5,329,143 |
def _test_get_cell(vertex, cell):
"""
Test :meth:`.Vertex.get_cell`.
Parameters
----------
vertex : :class:`.Vertex`
The vertex to test.
cell : :class:`numpy.ndarray`
The correct cell.
Returns
-------
None : :class:`NoneType`
"""
assert np.all(np.equal(ve... | 5,329,144 |
def is_socket_closed(sock):
"""Check if socket ``sock`` is closed."""
if not sock:
return True
try:
if not poll: # pragma nocover
if not select:
return False
try:
return bool(select([sock], [], [], 0.0)[0])
except socket.... | 5,329,145 |
def _fit_ovo_binary(estimator, X, y, i, j):
"""Fit a single binary estimator (one-vs-one)."""
cond = np.logical_or(y == i, y == j)
y = y[cond]
y_binary = np.empty(y.shape, np.int)
y_binary[y == i] = 0
y_binary[y == j] = 1
ind = np.arange(X.shape[0])
return _fit_binary(estimator, X[ind[co... | 5,329,146 |
def get_implicit_permissions_for_user(user: str, domain=None):
"""
GetImplicitPermissionsForUser gets implicit permissions for a user or role.
Compared to GetPermissionsForUser(), this function retrieves permissions for inherited roles.
For example:
p, admin, data1, read
p, alice, data2, re... | 5,329,147 |
def Law_f(text):
"""
:param text: The "text" of this Law
"""
return '\\begin{block}{Law}\n' + text + '\n\\end{block}\n' | 5,329,148 |
def ordered_dict_intersection(first_dict, second_dict, compat=operator.eq):
"""Return the intersection of two dictionaries as a new OrderedDict.
Items are retained if their keys are found in both dictionaries and the
values are compatible.
Parameters
----------
first_dict, second_dict : dict-l... | 5,329,149 |
def init_db():
"""Clear existing data and create new tables."""
db = get_db()
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print("Database version : %s " % data)
with current_app.open_resource('schema.sql') as f:
sql... | 5,329,150 |
def get_cl2cf_matrices(theta_bin_edges, lmin, lmax):
"""
Returns the set of matrices to go from one entire power spectrum to one binned correlation function.
Args:
theta_bin_edges (1D numpy array): Angular bin edges in radians.
lmin (int): Minimum l.
lmax (int): Maximum l.
Retu... | 5,329,151 |
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
"""
Frame a time series as a supervised learning dataset.
Arguments:
data: Sequence of observations as a list or NumPy array.
n_in: Number of lag observations as input (X).
n_out: Number of observations as output (y).
... | 5,329,152 |
def valid_from_done(done):
"""Returns a float mask which is zero for all time-steps after a
`done=True` is signaled. This function operates on the leading dimension
of `done`, assumed to correspond to time [T,...], other dimensions are
preserved."""
done = done.type(torch.float)
valid = torch.o... | 5,329,153 |
def rollout_script(arg_def_fn=None,
env_factory=None,
policy_factory=None,
add_policy_arg: bool = False):
"""Performs a rollout script.
Args:
arg_def_fn: A function that takes an ArgumentParser. Use this to add
arguments to the script... | 5,329,154 |
def get_transfer_options(transfer_kind='upload', transfer_method=None):
"""Returns hostnames that the current host can upload or download to.
transfer_kind: 'upload' or 'download'
transfer_method: is specified and not None, return only hosts with which
we can work using this method (e.g... | 5,329,155 |
def calc_utility_np(game, iter):
"""Calc utility of current position
Parameters
----------
game : camel up game
Camel up game class
iter : int
Iterations to run the monte carlo simulations
Returns
-------
np.array
Numpy structured array with expected utilities
... | 5,329,156 |
def add_masses(line, mass_light, mass_heavy):
"""
Add m/z information in the output lines
"""
new_line = "{} {} {}\n".format(round_masses(mass_light), round_masses(mass_heavy), line)
return new_line | 5,329,157 |
def load_r_ind_sent_bars():
"""
Loads the random index-barcodes of the actual networks
"""
bars = []
for text in texts:
bars.append(np.load('Textbooks/{}/r_ind_sent_bars.npy'.format(text)))
return bars | 5,329,158 |
def load_pickle(indices, image_data):
""""
0: Empty
1: Active
2: Inactive
"""
size = 13
# image_data = "./data/images.pkl"
with open(image_data, "rb") as f:
images = pickle.load(f)
x = []
y = []
n = []
cds = []
for idx in indices:
D_dict = images[i... | 5,329,159 |
def summarize_vref_locs(locs:TList[BaseObjLocation]) -> pd.DataFrame:
"""
Return a table with cols (partition, num vrefs)
"""
vrefs_by_partition = group_like(objs=locs, labels=[loc.partition for loc in locs])
partition_sort = sorted(vrefs_by_partition)
return pd.DataFrame({
'Partition': ... | 5,329,160 |
def rescale_list_to_range(original, limits):
"""
Linearly rescale values in original list to limits (minimum and maximum).
:example:
>>> rescale_list_to_range([1, 2, 3], (0, 10))
[0.0, 5.0, 10.0]
>>> rescale_list_to_range([1, 2, 3], (-10, 0))
[-10.0, -5.0, 0.0]
>>> rescale_list_to_rang... | 5,329,161 |
def test_simulation(overwrite: bool = False) -> None:
"""export sim in JSON, and then load it again"""
component = gf.components.straight(length=3)
sim = gt.get_simulation(component=component)
if overwrite:
sim.to_file("sim_ref.yaml") # uncomment to overwrite material
sim.to_file("sim_run... | 5,329,162 |
def build_list_request(
filters: Optional[dict[str, str]] = None
) -> Union[IssueListInvalidRequest, IssueListValidRequest]:
"""Create request from filters."""
accepted_filters = ["obj__eq", "state__eq", "title__contains"]
invalid_req = IssueListInvalidRequest()
if filters is not None:
if n... | 5,329,163 |
def get_ratings(labeled_df):
"""Returns list of possible ratings."""
return labeled_df.RATING.unique() | 5,329,164 |
def split_edge_cost(
edge_cost: EdgeFunction, to_split: LookupToSplit
) -> Dict[Edge, float]:
"""Assign half the cost of the original edge to each of the split edges.
Args:
edge_cost: Lookup from edges to cost.
to_split: Lookup from original edges to pairs of split edges
(see [l... | 5,329,165 |
def get_ants_brain(filepath, metadata, channel=0):
"""Load .nii brain file as ANTs image."""
nib_brain = np.asanyarray(nib.load(filepath).dataobj).astype('uint32')
spacing = [float(metadata.get('micronsPerPixel_XAxis', 0)),
float(metadata.get('micronsPerPixel_YAxis', 0)),
float... | 5,329,166 |
def numpy_max(x):
"""
Returns the maximum of an array.
Deals with text as well.
"""
return numpy_min_max(x, lambda x: x.max(), minmax=True) | 5,329,167 |
def clip_gradient(model, clip_norm):
"""Computes a gradient clipping coefficient based on gradient norm."""
totalnorm = 0
for p in model.parameters():
if p.requires_grad:
modulenorm = p.grad.data.norm()
totalnorm += modulenorm ** 2
totalnorm = np.sqrt(totalnorm)
norm... | 5,329,168 |
def online_training(exp_folder: pathlib.Path, filename: pathlib.Path,
freeze: bool):
"""Continue running an experiment.
Args:
exp_folder (pathlib.Path): Experiments folders.
filename (pathlib.Path): Input path for new data set.
freeze (bool): Freeze non conditional l... | 5,329,169 |
def get_train_val_test_splits(X, y, max_points, seed, confusion, seed_batch,
split=(2./3, 1./6, 1./6)):
"""Return training, validation, and test splits for X and y.
Args:
X: features
y: targets
max_points: # of points to use when creating splits.
seed: seed for shuffli... | 5,329,170 |
def require_apikey(key):
"""
Decorator for view functions and API requests. Requires
that the user pass in the API key for the application.
"""
def _wrapped_func(view_func):
def _decorated_func(*args, **kwargs):
passed_key = request.args.get('key', None)
if passed_ke... | 5,329,171 |
def apply_actions(local_files, deployed_files, visitor):
"""Get actions to do "Update, Delete, Create"
- LocalFiles is a list of tuple (KuduPath, openable path)
- DeployedFiles is dict KuduPath as key, meta as value
return a list of tuple (action, KuduPath, openable path)
"""
deployed_files_cop... | 5,329,172 |
def gauss_legendre(ordergl,tol=10e-14):
"""
Returns nodal abscissas {x} and weights {A} of
Gauss-Legendre m-point quadrature.
"""
m = ordergl + 1
from math import cos,pi
from numpy import zeros
def legendre(t,m):
p0 = 1.0; p1 = t
for k in range(1,m):
p = ((2.... | 5,329,173 |
def test_hyperparameters_called(mock):
"""Checks that __call__ function of regularizers is executed."""
x, y = get_data()
ma = get_test_member()
ma.step_on_batch(x, y)
calls = [call('Called {}'.format(h)) for h in ma.hyperparameters
if isinstance(h, L1L2Mutable)]
mock.assert_has_cal... | 5,329,174 |
def _remove_variable_declaration_statements(parse_tree):
"""
Modify the parse tree by removing all variable declaration statements.
This is an in-place modification: the given tree's list of children is
modified.
:param parse_tree: The whole parse tree (a subtree won't work)
"""
indices_to... | 5,329,175 |
def write(notes):
"""Writes a Lilypond file containing the given notes in Lilypond notation"""
out = open("out.ly", "w")
out.write(template.replace("XXX", notes))
out.close() | 5,329,176 |
def simple_message(msg, parent=None, title=None):
"""
create a simple message dialog with string msg. Optionally set
the parent widget and dialog title
"""
dialog = gtk.MessageDialog(
parent = None,
type = gtk.MESSAGE_INFO,
buttons = gtk.BUTTONS_OK,
... | 5,329,177 |
def accept(value):
"""Accept header class and method decorator."""
def accept_decorator(t):
set_decor(t, 'header', CaseInsensitiveDict({'Accept': value}))
return t
return accept_decorator | 5,329,178 |
def create_meg_data():
"""Creates MEG data for testing."""
make_fake_meg_map_data()
make_fake_exponent_map_data() | 5,329,179 |
def screenshot(widget, path=None, dir=None):
"""Save a screenshot of a Qt widget to a PNG file.
By default, the screenshots are saved in `~/.phy/screenshots/`.
Parameters
----------
widget : Qt widget
Any widget to capture (including OpenGL widgets).
path : str or Path
Path to... | 5,329,180 |
def xyz_to_rtp(x, y, z):
"""
Convert 1-D Cartesian (x, y, z) coords. to 3-D spherical coords.
(r, theta, phi).
The z-coord. is assumed to be anti-parallel to the r-coord. when
theta = 0.
"""
# First establish 3-D versions of x, y, z
xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')
... | 5,329,181 |
def irccat_targets(bot, targets):
"""
Go through our potential targets and place them in an array so we can
easily loop through them when sending messages.
"""
result = []
for s in targets.split(','):
if re.search('^@', s):
result.append(re.sub('^@', '', s))
elif re... | 5,329,182 |
async def test_loading_with_no_config(hass, mock_config_entry):
"""Test component loading failure when it has not configuration."""
mock_config_entry.add_to_hass(hass)
await setup.async_setup_component(hass, DOMAIN, {})
# Component setup fails because the oauth2 implementation could not be registered
... | 5,329,183 |
def do_analyze(directory, config):
"""
Analyze directory for keywords.
"""
analyze(directory, config) | 5,329,184 |
def _watchos_stub_partial_impl(
*,
ctx,
actions,
binary_artifact,
label_name,
watch_application):
"""Implementation for the watchOS stub processing partial."""
bundle_files = []
providers = []
if binary_artifact:
# Create intermediate file with pr... | 5,329,185 |
def contour_area_filter(image, kernel=(9,9), resize=1.0, uint_mode="scale",
min_area=100, min_area_factor=3, factor=3, **kwargs):
"""
Checks that a contour can be returned for two thresholds of the image, a
mean threshold and an otsu threshold.
Parameters
----------
imag... | 5,329,186 |
def catMullRomFit(p, nPoints=100):
"""
Return as smoothed path from a list of QPointF objects p, interpolating points if needed.
This function takes a set of points and fits a CatMullRom Spline to the data. It then
interpolates the set of points and outputs a smoothed path with the desired ... | 5,329,187 |
def pdf_from_ppf(quantiles, ppfs, edges):
"""
Reconstruct pdf from ppf and evaluate at desired points.
Parameters
----------
quantiles: numpy.ndarray, shape=(L)
L quantiles for which the ppf_values are known
ppfs: numpy.ndarray, shape=(1,...,L)
Corresponding ppf-values for all ... | 5,329,188 |
def get_arg_text(ob):
"""Get a string describing the arguments for the given object"""
arg_text = ""
if ob is not None:
arg_offset = 0
if type(ob) in (types.ClassType, types.TypeType):
# Look for the highest __init__ in the class chain.
fob = _find_constructor(ob)
... | 5,329,189 |
def create_ses_weights(d, ses_col, covs, p_high_ses, use_propensity_scores):
"""
Used for training preferentially on high or low SES people. If use_propensity_scores is True, uses propensity score matching on covs.
Note: this samples from individual images, not from individual people. I think this is okay ... | 5,329,190 |
def vectors_intersect(vector_1_uri, vector_2_uri):
"""Take in two OGR vectors (we're assuming that they're in the same
projection) and test to see if their geometries intersect. Return True of
so, False if not.
vector_1_uri - a URI to an OGR vector
vector_2_uri - a URI to an OGR vector
Return... | 5,329,191 |
def decoder_g(zxs):
"""Define decoder."""
with tf.variable_scope('decoder', reuse=tf.AUTO_REUSE):
hidden_layer = zxs
for i, n_hidden_units in enumerate(FLAGS.n_hidden_units_g):
hidden_layer = tf.layers.dense(
hidden_layer,
n_hidden_units,
activation=tf.nn.relu,
... | 5,329,192 |
def make_evinfo_str(json_str):
"""
[メソッド概要]
DB登録用にイベント情報を文字列に整形
"""
evinfo_str = ''
for v in json_str[EventsRequestCommon.KEY_EVENTINFO]:
if evinfo_str:
evinfo_str += ','
if not isinstance(v, list):
evinfo_str += '"%s"' % (v)
else:
... | 5,329,193 |
def parse_cisa_data(parse_file: str) -> object:
"""Parse the CISA Known Exploited Vulnerabilities file and create a new dataframe."""
inform("Parsing results")
# Now parse CSV using pandas, GUID is CVE-ID
new_dataframe = pd.read_csv(parse_file, parse_dates=['dueDate', 'dateAdded'])
# extend datafra... | 5,329,194 |
def camera():
"""Video streaming home page."""
return render_template('index.html') | 5,329,195 |
def new_doc():
"""Creating a new document."""
if request.method == 'GET' or request.form.get('act') != 'create':
return render_template('new.html', title='New document', permalink=url_for('.new_doc'))
else:
slug = request.form['slug'].strip()
src = os.path.join(app.config['DOCPATH'],... | 5,329,196 |
def fit_alternative(model, dataloader, optimizer, train_data, labelled=True):
"""
fit method using alternative loss, executes one epoch
:param model: VAE model to train
:param dataloader: input dataloader to fatch batches
:param optimizer: which optimizer to utilize
:param train_data: useful for... | 5,329,197 |
def FlagOverrider(**flag_kwargs):
"""A Helpful decorator which can switch the flag values temporarily."""
return flagsaver.flagsaver(**flag_kwargs) | 5,329,198 |
def test_transcode_j2k_dicom_wsi_to_zarr(samples_path, tmp_path):
"""Test that we can transcode a J2K compressed DICOM WSI to a Zarr."""
reader = readers.Reader.from_file(samples_path / "CMU-1-Small-Region-J2K")
writer = writers.ZarrReaderWriter(
path=tmp_path / "CMU-1.zarr",
tile_size=reade... | 5,329,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.