content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_point_callback(event, x, y, flags, param):
"""
cv2鼠标回调函数
"""
global points
if event == cv2.EVENT_MBUTTONDOWN:
points.append([x, y]) | 24,700 |
def make_optimiser_form(optimiser):
"""Make a child form for the optimisation settings.
:param optimiser: the Optimiser instance
:returns: a subclass of FlaskForm; NB not an instance!
"""
# This sets up the initial form with the optimiser's parameters
OptimiserForm = make_component_form(optimis... | 24,701 |
def prepare_for_evaluate(test_images, test_label):
"""
It will preprocess and return the images and labels for tesing.
:param original images for testing
:param original labels for testing
:return preprocessed images
:return preprocessed labels
"""
test_d = np.stack([preprocessing_for_te... | 24,702 |
def ab_group_to_dict(group):
"""Convert ABGroup to Python dict. Return None if group is empty."""
d = {'name': '', 'emails': [], 'is_group': True, 'is_company': False}
d['name'] = group.valueForProperty_(AB.kABGroupNameProperty)
for person in group.members():
identifier = group.distributionIden... | 24,703 |
async def async_setup(hass, config):
"""Set up the PEVC modbus component."""
hass.data[DOMAIN] = {}
return True | 24,704 |
def process_attribute_fields(sender, instance, created, **kwargs):
"""This function is attached to each :class:`Entity` subclass's post_save signal. Any :class:`Attribute`\ s managed by :class:`AttributeProxyField`\ s which have been removed will be deleted, and any new attributes will be created."""
if ATTRIBUTE_REG... | 24,705 |
def write_line_test_results(result_dict_outflows,
comp_dict_outflows,
result_dict_no_outflows,
comp_dict_no_outflows,
fit_mask,
run_dir,
... | 24,706 |
def deserialize_value(val: str) -> Any:
"""Deserialize a json encoded string in to its original value"""
return _unpack_value(
seven.json.loads(check.str_param(val, "val")),
whitelist_map=_WHITELIST_MAP,
descent_path="",
) | 24,707 |
def gen_signature(priv_path, pub_path, sign_path, passphrase=None):
"""
creates a signature for the given public-key with
the given private key and writes it to sign_path
"""
with salt.utils.files.fopen(pub_path) as fp_:
mpub_64 = fp_.read()
mpub_sig = sign_message(priv_path, mpub_64, ... | 24,708 |
def stringify(value):
"""
PHPCS uses a , separated strings in many places
because of how it handles options we have to do bad things
with string concatenation.
"""
if isinstance(value, six.string_types):
return value
if isinstance(value, collections.Iterable):
return ','.join... | 24,709 |
def _DISABLED_test_flash_obround():
"""Umaco example a simple obround flash with and without a hole"""
_test_render('resources/example_flash_obround.gbr', 'golden/example_flash_obround.png') | 24,710 |
def read_requirements_file(path):
""" reads requirements.txt file """
with open(path) as f:
requires = []
for line in f.readlines():
if not line:
continue
requires.append(line.strip())
return requires | 24,711 |
def vsa_get_all(context):
"""
Get all Virtual Storage Array records.
"""
session = get_session()
return session.query(models.VirtualStorageArray).\
options(joinedload('vsa_instance_type')).\
filter_by(deleted=can_read_deleted(context)).\
all() | 24,712 |
def scamp(filename, config, accuracy=0.5, itermax=10,
band=None, useweight=False, CheckPlot=False,
verbose="NORMAL"):
"""Compute astrometric solution of astronomical image using scamp"""
path = os.path.dirname(filename)
imagelist = np.atleast_1d(filename)
for ima in imagelist:
... | 24,713 |
def find_files_match_names_across_dirs(list_path_pattern, drop_none=True):
""" walk over dir with images and segmentation and pair those with the same
name and if the folder with centers exists also add to each par a center
.. note:: returns just paths
:param list(str) list_path_pattern: list of paths... | 24,714 |
def thread_it(obj, timeout = 10):
""" General function to handle threading for the physical components of the system. """
thread = threading.Thread(target = obj.run())
thread.start()
# Run the 'run' function in the obj
obj.ready.wait(timeout = timeout)
# Clean up
thread.join()... | 24,715 |
def _subsize_sub_pixel_align_cy_ims(pixel_aligned_cy_ims, subsize, n_samples):
"""
The inner loop of _sub_pixel_align_cy_ims() that executes on a "subsize"
region of the larger image.
Is subsize is None then it uses the entire image.
"""
n_max_failures = n_samples * 2
sub_pixel_offsets = np... | 24,716 |
def obj_setclass(this, klass):
"""
set Class for `this`!!
"""
return this.setclass(klass) | 24,717 |
def format(number, separator=' ', format=None, add_check_digit=False):
"""Reformat the number to the standard presentation format. The separator
used can be provided. If the format is specified (either 'hex' or 'dec')
the number is reformatted in that format, otherwise the current
representation is kept... | 24,718 |
def parse_equal_statement(line):
"""Parse super-sequence statements"""
seq_names = line.split()[1:]
return seq_names | 24,719 |
def rect(*args, **kwargs): # real signature unknown
""" Convert from polar coordinates to rectangular coordinates. """
pass | 24,720 |
def B5(n):
"""Factor Variables B5."""
return np.maximum(0, c4(n) - 3 * np.sqrt(1 - c4(n) ** 2)) | 24,721 |
def test_mnist_dataset():
"""Test case for MNIST Dataset.
"""
mnist_filename = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"test_mnist",
"mnist.npz")
with np.load(mnist_filename) as f:
(x_test, y_test) = f['x_test'], f['y_test']
image_filename = os.path.join(
os.path... | 24,722 |
def y_yhat_plots(y, yh, title="y and y_score", y_thresh=0.5):
"""Output plots showing how y and y_hat are related:
the "confusion dots" plot is analogous to the confusion table,
and the standard ROC plot with its AOC value.
The y=1 threshold can be changed with the y_thresh parameter.
"""
# The ... | 24,723 |
def _derive_scores(model, txt_file, base_words):
"""
Takes a model, a text file, and a list of base words.
Returns a dict of {base_word: score}, where score is an integer between 0
and 100 which represents the average similarity of the text to the given
word.
"""
with open(txt_file, 'r') as... | 24,724 |
def verifyRRD(fix_rrd=False):
"""
Go through all known monitoring rrds and verify that they
match existing schema (could be different if an upgrade happened)
If fix_rrd is true, then also attempt to add any missing attributes.
"""
global rrd_problems_found
global monitorAggregatorConfig
... | 24,725 |
def features_ids_argument_parser() -> ArgumentParser:
"""
Creates a parser suitable to parse the argument describing features ids in different subparsers
"""
parser = ArgumentParser(add_help=False, parents=[collection_option_parser()])
parser.add_argument(FEATURES_IDS_ARGNAME, nargs='+',
... | 24,726 |
def isolate_blue_blocks(image, area_min=10, side_ratio=0.5):
"""Return a sequence of masks on the original area showing significant blocks of blue."""
contours, _ = cv2.findContours(
blue(image).astype(np.uint8) * 255, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE
)
rects = []
for c in contours:
... | 24,727 |
def read_gtf(
filepath_or_buffer: Union[str, StringIO, Path],
expand_attribute_column: bool = True,
infer_biotype_column: bool = False,
column_converters: Optional[Dict[str, Callable[..., str]]] = None,
usecols: Optional[List[str]] = None,
features: Optional[Tuple[str]] = None,
chunksize: in... | 24,728 |
def version_in(dirname, indexname = None):
"""Returns a tuple of (release_version, format_version), where
release_version is the release version number of the Whoosh code that
created the index -- e.g. (0, 1, 24) -- and format_version is the
version number of the on-disk format used for the index --... | 24,729 |
def extract_pz(
ctable,
suffix="SAC_PZ",
outdir=".",
keep_sensitivity=False,
filter_by_chid=None,
filter_by_name=None,
filter_by_component=None,
):
"""Extract instrumental response in SAC PZ format from channel table.
.. warning::
Only works for instrumental responses of Hi-... | 24,730 |
def apply_pairs(fn, convert, *args):
"""non-public"""
if len(args) == 2:
fn([convert(args[0])], [args[1]])
else:
a1, a2 = unzip(args[0])
fn(convert(a1), list(a2)) | 24,731 |
def scrub_old_style_ceph():
"""Purge any legacy ceph configuration from install"""
# NOTE: purge old override file - no longer needed
if os.path.exists('/etc/init/cinder-volume.override'):
os.remove('/etc/init/cinder-volume.override')
# NOTE: purge any CEPH_ARGS data from /etc/environment
en... | 24,732 |
def trimAlphaNum(value):
"""
Trims alpha numeric characters from start and ending of a given value
>>> trimAlphaNum(u'AND 1>(2+3)-- foobar')
u' 1>(2+3)-- '
"""
while value and value[-1].isalnum():
value = value[:-1]
while value and value[0].isalnum():
value = value[1:]
... | 24,733 |
def hrm_job_title_represent(id, row=None):
""" FK representation """
if row:
return row.name
elif not id:
return current.messages.NONE
db = current.db
table = db.hrm_job_title
r = db(table.id == id).select(table.name,
limitby = (0, 1)).first()
... | 24,734 |
def test_update_exception_w_obj(client):
""" Verify the Client raises an exception if update is called with unsupporte type """
with pytest.raises(TypeError) as exc:
client.update(1)
assert "support updating objects of type" in str(exc) | 24,735 |
def is_empty_array_expr(ir: irast.Base) -> bool:
"""Return True if the given *ir* expression is an empty array expression.
"""
return (
isinstance(ir, irast.Array)
and not ir.elements
) | 24,736 |
def get_raw_entity_names_from_annotations(annotations):
"""
Args:
annotated_utterance: annotated utterance
Returns:
Wikidata entities we received from annotations
"""
raw_el_output = annotations.get("entity_linking", [{}])
entities = []
try:
if raw_el_output:
... | 24,737 |
def CheckFileStoragePathVsEnabledDiskTemplates(
logging_warn_fn, file_storage_dir, enabled_disk_templates):
"""Checks whether the given file storage directory is acceptable.
@see: C{CheckFileBasedStoragePathVsEnabledDiskTemplates}
"""
CheckFileBasedStoragePathVsEnabledDiskTemplates(
logging_warn_fn,... | 24,738 |
def nextPara(file, line):
"""Go forward one paragraph from the specified line and return the line
number of the first line of that paragraph.
Paragraphs are delimited by blank lines. It is assumed that the
current line is standalone (which is bogus).
- file is an array of strings
- line is the... | 24,739 |
def test_generate_all(pytester, file_creator):
"""Generated testfiles are saved and not collected, then collected and tested.
Note that tests/test_example.py is collected by pytest normally
since it is not a .md file.
When running pytest on generated test files, the pytest --doctest-modules
is need... | 24,740 |
def build_asignar_anexos_query(filters, request):
"""
Construye el query de búsqueda a partir de los filtros.
"""
return filters.buildQuery().filter(ambito__path__istartswith=request.get_perfil().ambito.path).order_by('nombre') | 24,741 |
def WriteResult(state, num):
"""保存结果"""
fileObject = open('results/result%04d.txt'%num, 'w')
for i in range(5,-1,-1):
for j in range(5-i):
for m in range(i):
fileObject.write(" ")
for k in range(5-i):
fileObject.write(str(state[i,j,k])+" ")
fileObject.write('\n')
fileObject.write('\n')
fileObje... | 24,742 |
def tang_save_features(data, labels, groundtruthfilename='100p'):
"""temp kludge
"""
[height, width, nbands] = data.shape
x = tf.placeholder(tf.float32, shape=(19,19,nbands+18))
feat = tang_net(x)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
padded_data = np.pad(... | 24,743 |
def validate_paths(paths_A, paths_B, strict=True, keys_ds=None):
""" Validate the constructed images path lists are consistent.
Can allow using B/HR and A/LR folders with different amount of images
Parameters:
paths_A (str): the path to domain A
paths_B (str): the path to domain B
k... | 24,744 |
def _median(data):
"""Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
>>> median([1, 3, 5])
3
>>> median... | 24,745 |
def num_translate(value: str) -> str:
"""переводит числительное с английского на русский """
str_out = NUM_DICT.get(value)
return str_out | 24,746 |
def test_code_fixture(db_test_app):
"""
Test the localhost fixture
"""
code_echo = db_test_app.code_echo
assert code_echo.uuid is not None
code_echo.get_remote_exec_path() | 24,747 |
def send_email(self, record_id):
# pylint: disable=no-member,too-many-arguments,too-many-statements
""" send out single email """
print(f"task:working on id - {record_id}")
print(f"attempt no: {self.request.retries}")
session = None
db_session = None
record = None
try:
session ... | 24,748 |
def get_patch_shape(corpus_file):
"""Gets the patch shape (height, width) from the corpus file.
Args:
corpus_file: Path to a TFRecords file.
Returns:
A tuple (height, width), extracted from the first record.
Raises:
ValueError: if the corpus_file is empty.
"""
example = tf.train.Example()
t... | 24,749 |
def _TopologicallySortedEnvVarKeys(env):
"""Takes a dict |env| whose values are strings that can refer to other keys,
for example env['foo'] = '$(bar) and $(baz)'. Returns a list L of all keys of
env such that key2 is after key1 in L if env[key2] refers to env[key1].
Throws an Exception in case of dependency c... | 24,750 |
def get_children_as_dict(parent):
"""For a given parent object, return all children as a dictionary with the childs tag as key"""
child_list = getChildElementsListWithSpecificXpath(parent, "*")
child_dict = {}
for child in child_list:
value = get_children_as_dict(child)
if child.tag not ... | 24,751 |
def markdown(build_reset, monkeypatch):
"""Create markdown and text widgets."""
app = App(__name__, sidebar=True)
app.add(mark)
app.add_sidebar(side)
app.add_sidebar(text)
app.subscribe(text.on_change)(write)
# pylint: disable=protected-access
app._build()
with server_check(app) as ... | 24,752 |
def test_create_vmis_proper_dpg(vmi_service, database, vnc_api_client, vm_model, vmi_model, vn_model_1, vn_model_2):
""" A new VMI is being created with proper DPG. """
vmi_model.vcenter_port.portgroup_key = 'dvportgroup-1'
database.vmis_to_update.append(vmi_model)
database.save(vn_model_1)
database... | 24,753 |
def load_ascii_font(font_name):
"""
Load ascii font from a txt file.
Parameter
---------
font_name: name of the font (str).
Return
------
font: font face from the file (dic).
Version
-------
Specification: Nicolas Van Bossuyt (v1. 27/02/17)
Notes
-----
Load fo... | 24,754 |
def get_multi_tower_fn(num_gpus, variable_strategy,
model_fn, device_setter_fn, lr_provider):
"""Returns a function that will build the resnet model.
Args:
num_gpus: number of GPUs to use (obviously)
variable_strategy: "GPU" or "CPU"
model_fn: The function providin... | 24,755 |
def _check_num_classes_binary(
num_classes: int, multiclass: tp.Optional[bool], implied_classes: tp.Optional[int]
) -> None:
"""This checks that the consistency of `num_classes` with the data and `multiclass` param for binary data."""
if implied_classes is not None and implied_classes != 2:
raise V... | 24,756 |
def extract_by_css(
content: str, selector: str, *, first: bool = True
) -> Union[str, list]:
"""Extract values from HTML content using CSS selector.
:param content: HTML content
:param selector: CSS selector
:param first: (optional) return first found element or all of them
:return: value of t... | 24,757 |
def generate_styles():
""" Create custom style rules """
# Set navbar so it's always at the top
css_string = "#navbar-top{background-color: white; z-index: 100;}"
# Set glossdef tip
css_string += "a.tip{text-decoration:none; font-weight:bold; cursor:pointer; color:#2196F3;}"
css_string += "a.ti... | 24,758 |
def get_config_file() -> Path:
"""
Get default config file.
"""
return get_project_root()/'data/config/config.yaml' | 24,759 |
def kilometers_to_miles(dist_km):
"""Converts km distance to miles
PARAMETERS
----------
dist_km : float
Scalar distance in kilometers
RETURNS
-------
dist_mi : float
Scalar distance in kilometers
"""
return dist_km / 1.609344 | 24,760 |
def test_Image_tmax_fallback(tmax_source, xy, expected, tol=0.001):
"""Test getting Tmax median value when daily doesn't exist
To test this, move the test date into the future
"""
input_img = ee.Image.constant([300, 0.8]).rename(['lst', 'ndvi']) \
.set({'system:index': SCENE_ID,
'... | 24,761 |
def test_get_bitinformation_dtype(rasm, dtype):
"""Test xb.get_bitinformation returns correct number of bits depending on dtype."""
ds = rasm.astype(dtype)
v = list(ds.data_vars)[0]
dtype_bits = dtype.replace("float", "")
assert len(xb.get_bitinformation(ds, dim="x")[v].coords["bit" + dtype_bits]) =... | 24,762 |
def test_atomic_any_uri_max_length_3_nistxml_sv_iv_atomic_any_uri_max_length_4_1(mode, save_output, output_format):
"""
Type atomic/anyURI is restricted by facet maxLength with value 31.
"""
assert_bindings(
schema="nistData/atomic/anyURI/Schema+Instance/NISTSchema-SV-IV-atomic-anyURI-maxLength-... | 24,763 |
def _objc_provider_framework_name(path):
"""Returns the name of the framework from an `objc` provider path.
Args:
path: A path that came from an `objc` provider.
Returns:
A string containing the name of the framework (e.g., `Foo` for `Foo.framework`).
"""
return path.rpartition("/"... | 24,764 |
def create(rosdistro_index_url, extend_path, dir, name, build_tool, verbose):
"""Creates a new workspace, saves it, and switches to it if it is the first
workspace.
:param rosdistro_index_url: The rosdistro to use
:param extend_path: Parent workspace to use.
:param dir: Where to create the workspac... | 24,765 |
def sample_publisher(name='EA'):
"""Create and return a sample publisher"""
return Publisher.objects.create(name=name) | 24,766 |
def AddGlobalFile(gfile):
"""
Add a global file to the cmd string.
@return string containing knob
"""
string = ''
if gfile:
string = ' --global_file ' + gfile
return string | 24,767 |
def get_scale_sequence(scale_0, v_init, a, n_frames):
""" simulates an object's size change from an initial velocity and an acceleration type
"""
scale = scale_0
sequence = [scale]
# TODO
# friction, sinusoidal
for i in range(n_frames-1):
scale = max(0.05, scale + v_init)
... | 24,768 |
def read_file(filename):
"""Opens the file with the given filename and creates the puzzle in it.
Returns a pair consisting of the puzzle grid and the list of clues. Assumes
that the first line gives the size. Afterwards, the rows and clues are given.
The description of the rows and clues may interleave ... | 24,769 |
def login_user(request):
"""View to login a new user"""
user = authenticate(username=request.POST['EMail'][:30], password=request.POST['Password'])
if user is not None:
if user.is_active:
login(request, user)
send_email("ROCK ON!!!", "User login - " + user.first_name + " " + ... | 24,770 |
def update_signature_approved(signature, value):
"""Helper function to update the signature approval status and send emails if necessary."""
previous = signature.get_signature_approved()
signature.set_signature_approved(value)
email_approval = cla.conf['EMAIL_ON_SIGNATURE_APPROVED']
if email_approva... | 24,771 |
def gdf_convex_hull(gdf):
"""
Creates a convex hull around the total extent of a GeoDataFrame.
Used to define a polygon for retrieving geometries within. When calculating
densities for urban blocks we need to retrieve the full extent of e.g.
buildings within the blocks, not crop them to an arbitrar... | 24,772 |
def room_operating_mode(mode: str) -> Dict[str, Any]:
"""Payload to set operating mode for
:class:`~pymultimatic.model.component.Room`.
"""
return {"operationMode": mode} | 24,773 |
def _validate_options(data: Dict[str, Any]) -> Dict[str, Any]:
"""
Looks up the exporter_type from the data, selects the correct export
options serializer based on the exporter_type and finally validates the data using
that serializer.
:param data: A dict of data to serialize using an exporter opti... | 24,774 |
def LodeCross(m=1.2, clr='black', ls='dashed', lw=1, zorder=0, **kwargs):
"""
Draw cross for Lode diagram
===========================
"""
xmin, xmax = gca().get_xlim()
ymin, ymax = gca().get_ylim()
if xmin > 0.0: xmin = 0.0
if xmax < 0.0: xmax = 0.0
if ymin > 0.0: ymin = 0.0
if y... | 24,775 |
def householder_name (name, rank):
"""Returns if the name conforms to Householder notation.
>>> householder_name('A_1', 2)
True
>>> householder_name('foobar', 1)
False
"""
base, _, _ = split_name(name)
if base in ['0', '1']:
return True
elif rank == 0:
if base in... | 24,776 |
def calculateDerivatives(x,t,id):
"""
dxdt, x0, id_, x_mean = calculateDerivatives(x,t,id)
Missing data is assumed to be encoded as np.nan
"""
nm = ~np.isnan(t) & ~np.isnan(x) # not missing
id_u = np.unique(id)
id_ = []
dxdt = []
x0 = []
x_mean = []
for k in range(0... | 24,777 |
def DeployConnectAgent(args,
service_account_key_data,
image_pull_secret_data,
membership_ref):
"""Deploys the GKE Connect agent to the cluster.
Args:
args: arguments of the command.
service_account_key_data: The contents of a Google IAM ... | 24,778 |
def SolveCaptcha(api_key, site_key, url):
"""
Uses the 2Captcha service to solve Captcha's for you.
Captcha's are held in iframes; to solve the captcha, you need a part of the url of the iframe. The iframe is usually
inside a div with id=gRecaptcha. The part of the url we need is the query parameter k,... | 24,779 |
def send_asset(asset_file_name):
"""Return an asset.
Args:
asset_file_name: The path of the asset file relative to the assets folder.
Returns:
The asset specified in the URL.
"""
asset_path = f"assets/{asset_file_name}"
asset_size = os.path.getsize(asset_path)
with open(ass... | 24,780 |
def clean_crn(crn, duplicates = True, trivial = True, inter = None):
"""Takes a crn and removes trivial / duplicate reactions. """
new = []
seen = set()
for [R, P] in crn:
lR = sorted(interpret(R, inter)) if inter else sorted(R)
lP = sorted(interpret(P, inter)) if inter else sorted(P)
... | 24,781 |
def to_libsvm(data, target, save_to=None):
"""
tranforms a dataset to libsvm format
"""
le = LabelEncoder()
target_t = le.fit_transform(data.data[target].to_ndarray())
groups = [group for group in data.groups if group != target]
with open(save_to, 'w') as f:
... | 24,782 |
def bwa_index(fasta):
""" Create a BWA index. """
shared.run_command(
[BIN['bwa'], 'index', fasta],
) | 24,783 |
def get_db_mapping(mesh_id):
"""Return mapping to another name space for a MeSH ID, if it exists.
Parameters
----------
mesh_id : str
The MeSH ID whose mappings is to be returned.
Returns
-------
tuple or None
A tuple consisting of a DB namespace and ID for the mapping or N... | 24,784 |
def MC_dBESQ_gateway(N = 10**6, t = 0, n0 = 0, test = 'laguerre', method = 'laguerre', args = [], num_decimal = 4):
"""
Monte Carlo estimator of expected dBESQ using birth-death simulation, exact BESQ solution, dLaguerre simulation
or PDE systems.
:param N: int, Number of simulations
:param T: posi... | 24,785 |
def locate_app(app_id):
"""Attempts to locate the application."""
if app_id is None:
return find_app_in_cwd()
if ':' in app_id:
module, app_obj = app_id.split(':', 1)
else:
module = app_id
app_obj = None
__import__(module)
mod = sys.modules[module]
if app_ob... | 24,786 |
def test_owe_transition_mode_multi_bss(dev, apdev):
"""Opportunistic Wireless Encryption transition mode (multi BSS)"""
try:
run_owe_transition_mode_multi_bss(dev, apdev)
finally:
dev[0].request("SCAN_INTERVAL 5") | 24,787 |
def resolve_image(image):
""" Resolve an informal image tag into a full Docker image tag. Any tag
available on Docker Hub for Neo4j can be used, and if no 'neo4j:' prefix
exists, this will be added automatically. The default edition is
Community, unless a cluster is being created in which case Enterpris... | 24,788 |
def _cifar_meanstd_normalize(image):
"""Mean + stddev whitening for CIFAR-10 used in ResNets.
Args:
image: Numpy array or TF Tensor, with values in [0, 255]
Returns:
image: Numpy array or TF Tensor, shifted and scaled by mean/stdev on
CIFAR-10 dataset.
"""
# Channel-wise means and std devs cal... | 24,789 |
def get_value_counts_and_frequencies(elem: Variable, data: pd.DataFrame) -> Categories:
"""Call function to generate frequencies depending on the variable type
Input:
elem: dict
data: pandas DataFrame
Output:
statistics: OrderedDict
"""
statistics: Categories = Categories()
_scale... | 24,790 |
def determineLinearRegions(data, minLength=.1, minR2=.96, maxSlopeInterceptDiff=.75):
"""
Determine regions of a plot that are approximately linear by performing
linear least-squares on a rolling window.
Parameters
----------
data : array_like
Data within which linear regions a... | 24,791 |
def compute_dispersion(aperture, beam, dispersion_type, dispersion_start,
mean_dispersion_delta, num_pixels, redshift, aperture_low, aperture_high,
weight=1, offset=0, function_type=None, order=None, Pmin=None, Pmax=None,
*coefficients):
"""
Compute a dispersion mapping from a IRAF multi-spec descri... | 24,792 |
async def websocket_remove_node(
hass: HomeAssistant,
connection: ActiveConnection,
msg: dict,
entry: ConfigEntry,
client: Client,
) -> None:
"""Remove a node from the Z-Wave network."""
controller = client.driver.controller
@callback
def async_cleanup() -> None:
"""Remove s... | 24,793 |
def _fix_google_module():
"""Reloads the google module to prefer our third_party copy.
When Python is not invoked with the -S option, it may preload the google module via .pth file.
This leads to the "site_packages" version being preferred over gsutil "third_party" version.
To force the "third_party" version, ... | 24,794 |
def _remove_edgetpu_model(data_dir):
"""Removes edgetpu models recursively from given folder.
Filenames with suffix `_edgetpu.tflite` will be removed.
Args:
data_dir: string, path to folder.
"""
print("Removing edgetpu models from ", data_dir)
edgetpu_model_list = glob.glob(
os.path.join(data_di... | 24,795 |
def test_shutil_ignore_function():
"""
>>> test_shutil_ignore_function()
"""
# Setup
path_test_dir = pathlib.Path(__file__).parent.resolve()
path_source_dir = path_test_dir / "example"
path_target_dir = path_test_dir / "target"
shutil.rmtree(path_target_dir, ignore_errors=True)
# ... | 24,796 |
def normalize_pcp_area(pcp):
"""
Normalizes a pcp so that the sum of its content is 1,
outputting a pcp with up to 3 decimal points.
"""
pcp = np.divide(pcp, np.sum(pcp))
new_format = []
for item in pcp:
new_format.append(item)
return np.array(new_format) | 24,797 |
def calc_line_flux(spec, ws, ivar, w0, w1, u_flux):
""" calculate the flux and flux error of the line within the range w0 and w1 using trapz rule"""
u_spec = spec.unit
u_ws = ws.unit
ivar = ivar.to(1./(u_spec**2))
spec_uless = np.array(spec)
ws_uless = np.array(ws)
ivar_uless = np.array(ivar)
if ivar.unit != ... | 24,798 |
def main():
"""
fonction principale
"""
if len(sys.argv) >= 2 and sys.argv[1] == 'find':
if len(sys.argv) > 2:
name = sys.argv[2]
else:
name = None
data = find_gce(name=name)
if len(data) > 0:
data = data[0]
print("{}:{}... | 24,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.