content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gen_csrv_msome(shape, n_parts, mic_rad, min_ip_dst):
"""
Generates a list of 3D coordinates and rotations a CSRV pattern
:param shape: tomogram shape
:param n_parts: number of particles to try to generate
:param mic_rad: microsome radius
:param min_ip_dst: minimum interparticle distance
... | 5,341,000 |
def electra_model(request):
"""Exposes the command-line option to a test case."""
electra_model_path = request.config.getoption("--electra_model")
if not electra_model_path:
pytest.skip("No --electra_model given")
else:
return electra_model_path | 5,341,001 |
def By_2d_approximation(x, w, d, j):
"""Approximation of By_surface valid except near edges of slab."""
mu0_over_4pi = 1e-7
return 2e-7 * j * d * np.log((w/2 + x) / (w/2 - x)) | 5,341,002 |
def read_lists(paths: Dict[str, Path]) -> Dict[str, List[str]]:
"""Return a dictionary of song lists read from file.
Arguments:
paths {Dict[str, Path]} -- A dictionary of type returned by find_paths.
Returns:
Dict[str, List[str]] -- The keys are a string song list id ('1' to '6' or 'F'),
... | 5,341,003 |
def learningCurve(theta, X_train, y_train, X_cv, y_cv, lambda_param):
"""
:param X_train:
:param y_train:
:param X_cv:
:param y_cv:
:param lambda_param:
:return:
"""
number_examples = y_train.shape[0]
J_train, J_cv = [], []
for i in range(1, number_examples + 1):
th... | 5,341,004 |
def reduce_labels(y):
"""Reduziert die Themen und Disziplinen auf die höchste Hierarchiestufe"""
labels = [] # new y
themes = []
disciplines = []
for i, elements in enumerate(y):
tmp_all_labels = []
tmp_themes = []
tmp_disciplines = []
#print("... | 5,341,005 |
def api_get_categories(self):
"""
Gets a list of all the categories.
"""
response = TestCategory.objects.all()
s = ""
for cat in response:
s += b64(cat.name) + "," + b64(cat.description) + ","
return HttpResponse(s.rstrip(',')) | 5,341,006 |
def histtab(items, headers=None, item="item", count="count", percent="percent",
cols=None):
"""Make a histogram table."""
if cols is not None:
# items is a Table.
items = items.as_tuples(cols=cols)
if headers is None:
headers = cols + [count, percent]
if head... | 5,341,007 |
def read_sdf_to_mol(sdf_file, sanitize=False, add_hs=False, remove_hs=False):
"""Reads a list of molecules from an SDF file.
:param add_hs: Specifies whether to add hydrogens. Defaults to False
:type add_hs: bool
:param remove_hs: Specifies whether to remove hydrogens. Defaults to False
:type remov... | 5,341,008 |
def harmonize_ocean(ocean, elevation, ocean_level):
"""
The goal of this function is to make the ocean floor less noisy.
The underwater erosion should cause the ocean floor to be more uniform
"""
shallow_sea = ocean_level * 0.85
midpoint = shallow_sea / 2.0
ocean_points = numpy.logical_and... | 5,341,009 |
def gen_fulltest_buildfile_windows() -> None:
"""Generate fulltest command list for jenkins.
(so we see nice pretty split-up build trees)
"""
import batools.build
batools.build.gen_fulltest_buildfile_windows() | 5,341,010 |
def search_and_score(milvus_collection_name, mongo_name, field_name, vectors,
topk, nprobe, inner_score_mode: str):
"""
search vectors from milvus and score by inner field score mode
:param milvus_collection_name: collection name will be search
:param mongo_name: mongo collecti... | 5,341,011 |
def fix_simulation():
""" Create instance of Simulation class."""
return Simulation() | 5,341,012 |
def build_tree(vectors, algorithm='kd_tree', metric='minkowski', **kwargs):
"""Build NearestNeighbors tree."""
kwargs.pop('algorithm', None)
kwargs.pop('metric', None)
return NearestNeighbors(algorithm=algorithm, metric=metric,
**kwargs).fit(vectors) | 5,341,013 |
def _expectedValues():
"""
These values are expected for well exposed spot data. The dictionary has a tuple for each wavelength.
Note that for example focus is data set dependent and should be used only as an indicator of a possible value.
keys: l600, l700, l800, l890
tuple = [radius, focus, width... | 5,341,014 |
def storyOne(player):
"""First Story Event"""
player.story += 1
clear()
print("The dust gathers around, swirling, shaking, taking some sort of shape.")
time.sleep(2)
print("Its the bloody hermit again!")
time.sleep(2)
clear()
print("Hermit: Greetings, " + str(player.name) + ". It is ... | 5,341,015 |
def test_compute_c_max_D():
"""Runs compute_c_max with isotope T and checks that the correct value is
produced
"""
# build
T = np.array([600, 500])
E_ion = np.array([20, 10])
E_atom = np.array([30, 40])
angles_ion = np.array([60, 60])
angles_atom = np.array([60, 60])
ion_flux = n... | 5,341,016 |
def restart():
"""Restart beobench. This will stop any remaining running beobench containers."""
beobench.utils.restart() | 5,341,017 |
def mcat(i):
"""Concatenate a list of matrices into a single matrix using separators
',' and ';'. The ',' means horizontal concatenation and the ';' means
vertical concatenation.
"""
if i is None:
return marray()
# calculate the shape
rows = [[]]
final_rows = 0
fin... | 5,341,018 |
def get_optional_info() -> Dict[str, Union[str, bool]]:
"""Get optional package info (tensorflow, pytorch, hdf5_bloscfilter, etc.)
Returns
-------
Dict[str, Union[str, False]]
package name, package version (if installed, otherwise False)
"""
res = {}
try:
import h5py
... | 5,341,019 |
def epsilon_experiment(dataset, n: int, eps_values: list):
"""
Function for the experiment explained in part (g).
eps_values is a list, such as: [0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 1.0]
Returns the errors as a list: [9786.5, 1234.5, ...] such that 9786.5 is the error when eps = 0.0001,
... | 5,341,020 |
def infer_scaletype(scales):
"""Infer whether `scales` is linearly or exponentially distributed (if latter,
also infers `nv`). Used internally on `scales` and `ssq_freqs`.
Returns one of: 'linear', 'log', 'log-piecewise'
"""
scales = asnumpy(scales).reshape(-1, 1)
if not isinstance(scales, np.n... | 5,341,021 |
def authorized_http(credentials):
"""Returns an http client that is authorized with the given credentials.
Args:
credentials (Union[
google.auth.credentials.Credentials,
oauth2client.client.Credentials]): The credentials to use.
Returns:
Union[httplib2.Http, google_... | 5,341,022 |
def add_grating_couplers_with_loopback_fiber_array(
component: Component,
grating_coupler: ComponentSpec = grating_coupler_te,
excluded_ports: Optional[List[str]] = None,
grating_separation: float = 127.0,
bend_radius_loopback: Optional[float] = None,
gc_port_name: str = "o1",
gc_rotation: i... | 5,341,023 |
def enable_x64():
"""Use double (x64) precision for jax arrays"""
jax.config.update("jax_enable_x64", True) | 5,341,024 |
def FEBA_Save_Tables(gene_fit_d, genes_df, organism_name_str,
op_dir, exps_df,
cfg=None,
writeImage=False, debug=False):
"""
Args:
gene_fit_d (python dict): Documentation above function
genes_df (pandas DataFrame): table genes.GC
... | 5,341,025 |
def auto_update_function(cities):
"""Auto-update weather function
The function takes a list of the cities to update.
If the error connecting to sources - an error with
a status of 500 and JSON with the cause of the error and URL.
If the connection is successful, it enters the
... | 5,341,026 |
def absolute_sum_of_changes(x):
"""
Returns the sum over the absolute value of consecutive changes in the series x
.. math::
\\sum_{i=1, \ldots, n-1} \\mid x_{i+1}- x_i \\mid
:param x: the time series to calculate the feature of
:type x: pandas.Series
:return: the value of this featur... | 5,341,027 |
def handle_program_options():
"""
Uses the built-in argparse module to handle command-line options for the
program.
:return: The gathered command-line options specified by the user
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(description="Convert Sanger-sequencing \
... | 5,341,028 |
def start_v_imp(model, lval: str, rval: str):
"""
Calculate starting value for parameter in data given data in model.
For Imputer -- just copies values from original data.
Parameters
----------
model : Model
Model instance.
lval : str
L-value name.
rval : str
R-v... | 5,341,029 |
async def websocket_network_status(
hass: HomeAssistant,
connection: ActiveConnection,
msg: dict,
entry: ConfigEntry,
client: Client,
) -> None:
"""Get the status of the Z-Wave JS network."""
data = {
"client": {
"ws_server_url": client.ws_server_url,
"state":... | 5,341,030 |
def get_image_features(X, y, appearance_dim=32):
"""Return features for every object in the array.
Args:
X (np.array): a 3D numpy array of raw data of shape (x, y, c).
y (np.array): a 3D numpy array of integer labels of shape (x, y, 1).
appearance_dim (int): The resized shape of the app... | 5,341,031 |
def findlinestarts(code):
"""Find the offsets in a byte code which are start of lines in the source.
Generate pairs (offset, lineno) as described in Python/compile.c.
CTB -- swiped from Python 2.5, module 'dis', so that earlier versions
of Python could use the function, too.
"""
byte_increment... | 5,341,032 |
def test_broken_yaml_header(testdata_dir: pathlib.Path) -> None:
"""Test for a bad markdown header."""
bad_file = testdata_dir / 'author' / 'bad_md_header.md'
with pytest.raises(TrestleError):
ControlIOReader._load_control_lines_and_header(bad_file) | 5,341,033 |
def deactivate_text(shell: dict, env_vars: dict) -> str:
"""Returns the formatted text to write to the deactivation script
based on the passed dictionaries."""
lines = [shell["shebang"]]
for k in env_vars.keys():
lines.append(shell["deactivate"].format(k))
return "\n".join(lines) | 5,341,034 |
def is_dict(etype) -> bool:
""" Determine whether etype is a Dict """
return get_origin(etype) is dict or etype is dict | 5,341,035 |
def t_plot_parameters(thickness_curve, section, loading, molar_mass, liquid_density):
"""Calculates the parameters from a linear section of the t-plot."""
slope, intercept, corr_coef, p, stderr = scipy.stats.linregress(
thickness_curve[section],
loading[section])
# Check if slope is good
... | 5,341,036 |
def main():
"""主函数
"""
temp_str = input("1. 测试\n2. raw data\n3. json文件绝对路径\n")
if temp_str == '1':
test_file = open('./resources/test.json', mode='r')
raw_data = test_file.read()
print_json(raw_data)
test_file.close()
elif temp_str == '2':
raw_data = input("给定... | 5,341,037 |
def get_data(stock, start_date):
"""Fetch a maximum of the 100 most recent records for a given
stock starting at the start_date.
Args:
stock (string): Stock Ticker
start_date (int): UNIX date time
"""
# Build the query string
request_url = f"https://api.pushshift.io/reddit/sea... | 5,341,038 |
def depart_people(state, goal):
"""Departs all passengers that can depart on this floor"""
departures = []
for departure in state.destin.items():
passenger = departure[0]
if passenger in goal.served and goal.served[passenger]:
floor = departure[1]
if state.lift_at == ... | 5,341,039 |
def get_topic_for_subscribe():
"""
return the topic string used to subscribe for receiving future responses from DPS
"""
return _get_topic_base() + "res/#" | 5,341,040 |
def generate_AES_key(bytes = 32):
"""Generates a new AES key
Parameters
----------
bytes : int
number of bytes in key
Returns
-------
key : bytes
"""
try:
from Crypto import Random
return Random.get_random_bytes(bytes)
except ImportError:
print('... | 5,341,041 |
def remove_deploy_networkIPv6_configuration(user, networkipv6, equipment_list):
"""Loads template for removing Network IPv6 equipment configuration, creates file and
apply config.
Args: NetworkIPv6 object
Equipamento objects list
Returns: List with status of equipments output
"""
data = d... | 5,341,042 |
def extant_file(x):
"""
'Type' for argparse - checks that file exists but does not open.
Parameters
----------
x : str
Candidate file path
Returns
-------
str
Validated path
"""
if not os.path.isfile(x):
# ArgumentTypeError gives a rejection message of... | 5,341,043 |
def can_pay_with_two_coins(denoms, amount):
""" (list of int, int) -> bool
Return True if and only if it is possible to form amount, which is a
number of cents, using exactly two coins, which can be of any of the
denominations in denoms.
>>> can_pay_with_two_coins([1, 5, 10, 25], 35)
True
... | 5,341,044 |
def make_column_kernelizer(*transformers, **kwargs):
"""Construct a ColumnKernelizer from the given transformers.
This is a shorthand for the ColumnKernelizer constructor; it does not
require, and does not permit, naming the transformers. Instead, they will
be given names automatically based on their t... | 5,341,045 |
def plugin_info():
""" Returns information about the plugin.
Args:
Returns:
dict: plugin information
Raises:
"""
return {
'name': 'PT100 Poll Plugin',
'version': '1.9.2',
'mode': 'poll',
'type': 'south',
'interface': '1.0',
'config': _DEF... | 5,341,046 |
def test_no_celery_task():
"""
If the 'CELERY_TASK_NAME' env var is not set, not tasks are sent to the
Celery queue.
"""
(
flexmock(os)
.should_receive("getenv")
.with_args("CELERY_TASK_NAME")
.and_return(None)
.once()
)
flexmock(celery_app).should_rec... | 5,341,047 |
def get_engine(isolation_level=None):
"""
Creates an engine with the given isolation level.
"""
# creates a shallow copy with the given isolation level
if not isolation_level:
return _get_base_engine()
else:
return _get_base_engine().execution_options(isolation_level=isolation_le... | 5,341,048 |
def phantomjs_driver(capabilities, driver_path, port):
"""
Overrides default `phantomjs_driver` driver from pytest-selenium.
Default implementation uses ephemeral ports just as our tests but
it doesn't provide any way to configure them, for this reason we basically
recreate the driver fixture using... | 5,341,049 |
def to_TH1x(
fName,
fTitle,
data,
fEntries,
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fSumw2,
fXaxis,
fYaxis=None,
fZaxis=None,
fNcells=None,
fBarOffset=0,
fBarWidth=1000,
fMaximum=-1111.0,
fMinimum=-1111.0,
fNormFactor=0.0,
fContour=None,
fOptio... | 5,341,050 |
def parse_args():
"""
Parse and validate the command line arguments, and set the defaults.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
description='Utility commands for handle.net EPIC persistent identifiers')
parser.add_argument('command',
... | 5,341,051 |
def parse(address, addr_spec_only=False, strict=False, metrics=False):
"""
Given a string, returns a scalar object representing a single full
mailbox (display name and addr-spec), addr-spec, or a url.
If parsing the entire string fails and strict is not set to True, fall back
to trying to parse the... | 5,341,052 |
def infer(
args: Namespace,
model: BaseModel
) -> None:
"""Perform the inference.
Parameters
----------
model : BaseModel
The model to be used for inference.
args : Namespace
Arguments to configure the model and the inference.
See Also
--------
ptlflow.models.ba... | 5,341,053 |
def test_wb_has_agm():
"""test_wb_has_agm"""
query = """
MATCH (a:AffectedGenomicModel)
WHERE a.primaryKey = 'WB:WBStrain00023353'
RETURN count(a) as counter """
result = execute_transaction(query)
for record in result:
assert record["counter"] == 1 | 5,341,054 |
def unfreeze_file(user, data):
""" unfreeze a file.
:return: status code, response data
"""
r = requests.post('%s/unfreeze' % URL, json=data, auth=(user, PASS), verify=False)
return r.status_code, r.json() | 5,341,055 |
def p_ir_metadata_debug_attribute_bool(p):
# type: (YaccProduction) -> None
"""
ir-metadata-debug-attribute : TRUE
| FALSE
""" | 5,341,056 |
def test_mg_l004_mg_l004_v(mode, save_output, output_format):
"""
TEST :model groups (ALL) : choice: with 1 elements, 1 element is in
the instant XML doc
"""
assert_bindings(
schema="msData/modelGroups/mgL004.xsd",
instance="msData/modelGroups/mgL004.xml",
class_name="Doc",
... | 5,341,057 |
def prompt_url(q):
"""
:param q: The prompt to display to the user
:return: The user's normalized input. We ensure there is an URL scheme, a domain, a "/" path,
and no trailing elements.
:rtype: str
"""
return prompt(q, _url_coerce_fn) | 5,341,058 |
def eval_mnl_logsums(choosers, spec, locals_d, trace_label=None):
"""
like eval_nl except return logsums instead of making choices
Returns
-------
logsums : pandas.Series
Index will be that of `choosers`, values will be
logsum across spec column values
"""
trace_label = tra... | 5,341,059 |
def find_zeroed_indices(adjusted, original):
"""Find the indices of the values present in ``original`` but missing in ``adjusted``.
Parameters
----------
adjusted: np.array
original: array_like
Returns
-------
Tuple[np.ndarray]
Indices of the values present in ``original`` but ... | 5,341,060 |
def inventory_update(arr1, arr2):
"""Add the inventory from arr2 to arr1.
If an item exists in both arr1 and arr2, then
the quantity of the item is updated in arr1.
If an item exists in only arr2, then the item
is added to arr1. If an item only exists in
arr1, then that item remains unaffected.... | 5,341,061 |
def racaty(url: str) -> str:
""" Racaty direct link generator
based on https://github.com/SlamDevs/slam-mirrorbot"""
dl_url = ''
try:
link = re.findall(r'\bhttps?://.*racaty\.net\S+', url)[0]
except IndexError:
raise DirectDownloadLinkException("No Racaty links found\n")
scraper ... | 5,341,062 |
def test_copyto(func_interface):
"""Tests for numpoly.copyto."""
poly = numpoly.polynomial([1, X, Y])
poly_ref = numpoly.polynomial([1, X, Y])
with raises(ValueError):
func_interface.copyto(poly.values, poly_ref, casting="safe")
with raises(ValueError):
numpoly.copyto(poly.values, [1... | 5,341,063 |
def addDBToConf(conf_name, db_name, db_username, db_password, db_location = 'local', host_ip = None, host_port = None):
"""
Method for adding a database configuration to the your own database configuration.
:param str username: the username given by user
"""
db_settings = settings.database_settings... | 5,341,064 |
def get_logger(
name='mltk',
level='INFO',
console=False,
log_file=None,
log_file_mode='w',
parent:logging.Logger=None
):
"""Get or create a logger, optionally adding a console and/or file handler"""
logger = logging.getLogger(name)
if len(logger.handlers) == 0:
if parent... | 5,341,065 |
def _remove_old_snapshots(connection, volume, max_snapshots):
""" Remove old snapshots
:type connection: boto.ec2.connection.EC2Connection
:param connection: EC2 connection object
:type volume: boto.ec2.volume.Volume
:param volume: Volume to check
:returns: None
"""
logging.info(kayvee.... | 5,341,066 |
def main():
"""pull the region sets as bed files to visualize results
"""
# input files
mpra_file = sys.argv[1]
rule_dir = sys.argv[2]
dir_url = "http://mitra.stanford.edu/kundaje/dskim89/ggr/paper"
# for rule in rule dir, pull the BED file from it
rules = pd.read_csv(mpra_file, sep... | 5,341,067 |
def _parse_cli_args() -> Tuple[str, List[str]]:
"""Parses CLI args to return device name and args for unittest runner."""
parser = argparse.ArgumentParser(
description="Runs a GDM + unittest reboot test on a device. All "
"arguments other than the device name are passed through to "
... | 5,341,068 |
def build_tree(tree, parent, counts, ordered_ids):
"""
Recursively splits the data, which contained in the tree object itself
and is indexed by ordered_ids.
Parameters
----------
tree: Tree object
parent: TreeNode object
The last node added to the tree, w... | 5,341,069 |
def get_perf_measure_by_group(aif_metric, metric_name):
"""Get performance measures by group."""
perf_measures = ['TPR', 'TNR', 'FPR', 'FNR', 'PPV', 'NPV', 'FDR', 'FOR', 'ACC']
func_dict = {
'selection_rate': lambda x: aif_metric.selection_rate(privileged=x),
'precision': lambda x: aif_metr... | 5,341,070 |
def test_skew_single_return_type():
"""This function tests the return type for the skew method for a 1d array."""
numpy_array = np.random.random(size=(30,))
dask_array = da.from_array(numpy_array, 3)
result = dask.array.stats.skew(dask_array).compute()
assert isinstance(result, np.float64) | 5,341,071 |
def _strxor_direct(term1, term2, result):
"""Very fast XOR - check conditions!"""
_raw_strxor.strxor(term1, term2, result, c_size_t(len(term1))) | 5,341,072 |
def hello_world(request):
"""Return a greeting."""
return HttpResponse('Hello, world!{now}'.format(
now=datetime.now().strftime('%b %dth, %Y : %M HttpResponses')
)) | 5,341,073 |
def getfile(id, name):
"""
Retorna um arquivo em anexo.
"""
mime = mimetypes.guess_type(name)[0]
if mime is None:
mime = "application/octet-stream"
c = get_cursor()
c.execute(
"""
select files.ticket_id as ticket_id,
files.size as size,
files.c... | 5,341,074 |
def get_default_wavelet():
"""Sets the default wavelet to be used for scaleograms"""
global DEFAULT_WAVELET
return DEFAULT_WAVELET | 5,341,075 |
def check_output(file_path: str) -> bool:
"""
This function checks an output file, either from geomeTRIC or
from Psi4, for a successful completion keyword. Returns
True if the calculation finished successfully, otherwise
False.
"""
with open(file_path, "r") as read_file:
text = read_... | 5,341,076 |
def _check_func_signature_supported(func: Callable) -> None:
"""
Checks if a given function has a supported type.
If function signature includes parameters that are
of kind POSTIONAL_ONLY, VAR_KEYWORD or VAR_POSITIONAL
an FunctionSignatureNotSupportedException is raised.
"""
sig = signature(... | 5,341,077 |
def dumps(value):
"""
Dumps a data structure to TOML source code.
The given value must be either a dict of dict values, a dict,
or a TOML file constructed by this module.
"""
if not isinstance(value, TOMLFile):
raise RuntimeError(
'Can only dump a TOMLFile instance loaded by... | 5,341,078 |
def calc_graph(dict_graph):
"""
creates scatter of comfort and curves of constant relative humidity
:param dict_graph: contains comfort conditions to plot, output of comfort_chart.calc_data()
:type dict_graph: dict
:return: traces of scatter plot of 4 comfort conditions
:rtype: list of plotly.g... | 5,341,079 |
def index():
"""Display a user's account information."""
if not current_user.is_authenticated:
return redirect(url_for("account.login"))
cancel_reservation_form = CancelReservationForm()
if cancel_reservation_form.validate_on_submit():
cancel_id = int(cancel_reservation_form.id.data)
... | 5,341,080 |
def report_raw_stats(
sect,
stats: LinterStats,
old_stats: Optional[LinterStats],
) -> None:
"""calculate percentage of code / doc / comment / empty"""
total_lines = stats.code_type_count["total"]
sect.description = f"{total_lines} lines have been analyzed"
lines = ["type", "number", "%", "p... | 5,341,081 |
def add_property(inst, name_to_method: Dict[str, Callable]):
"""Dynamically add new properties to an instance by creating a new class
for the instance that has the additional properties"""
cls = type(inst)
# Avoid creating a new class for the inst if it was already done before
if not hasattr(cls, "_... | 5,341,082 |
def centrality(raw_centrality: List[Hist], centralities: Dict[params.EventActivity, Hist],
output_info: analysis_objects.PlottingOutputWrapper) -> None:
""" Plot the centrality distribution for a list of centralities
Args:
raw_centrality: Raw centrality. Each entry should have the same c... | 5,341,083 |
def generate_arrays(df, resize=True, img_height=50, img_width=200):
""" Generates image array and labels array from a dataframe """
num_items = len(df)
images = np.zeros((num_items, img_height, img_width), dtype=np.float32)
labels = [0] * num_items
for i in range(num_items):
input_... | 5,341,084 |
def printWifiNames():
"""print all cells from interface wlan0"""
res= wifi.Cell.all('wlan0')
for r in res:
print r | 5,341,085 |
def compute_cosine_distance(Q, feats, names):
"""
feats and Q: L2-normalize, n*d
"""
dists = np.dot(Q, feats.T)
# print("dists:",dists)
# exit(1)
idxs = np.argsort(dists)[::-1]
rank_dists = dists[idxs]
rank_names = [names[k] for k in idxs]
return (idxs, rank_dists, rank_n... | 5,341,086 |
def test_fuss_pretty(fixed):
"""Test Fuss' pretty formatting."""
examples = [
(Fuss(fixed, "abc.txt", 2, "message"), "abc.txt:1: NIP002 message"),
(Fuss(fixed, "abc.txt", 2, "message", "", 15), "abc.txt:15: NIP002 message"),
(
Fuss(fixed, "abc.txt", 1, "message", "\tsuggestio... | 5,341,087 |
def phase(ifc, inc_pt, d_in, normal, z_dir, wvl, n_in, n_out):
""" apply phase shift to incoming direction, d_in, about normal """
try:
d_out, dW = ifc.phase(inc_pt, d_in, normal, z_dir, wvl, n_in, n_out)
return d_out, dW
except ValueError:
raise TraceEvanescentRayError(ifc, inc_pt, ... | 5,341,088 |
def generate_udf(spec: "rikai.spark.sql.codegen.base.ModelSpec"):
"""Construct a UDF to run sklearn model.
Parameters
----------
spec : ModelSpec
the model specifications object
Returns
-------
A Spark Pandas UDF.
"""
def predict(model, X):
if hasattr(model, "predi... | 5,341,089 |
def test_list_hex_binary_max_length_nistxml_sv_iv_list_hex_binary_max_length_1_3(mode, save_output, output_format):
"""
Type list/hexBinary is restricted by facet maxLength with value 5.
"""
assert_bindings(
schema="nistData/list/hexBinary/Schema+Instance/NISTSchema-SV-IV-list-hexBinary-maxLengt... | 5,341,090 |
def ssl_loss_mean_teacher(labels_x, logits_x, logits_teacher, logits_student):
"""
Computes two cross entropy losses based on the labeled and unlabeled data.
loss_x is referring to the labeled CE loss and loss_u to the unlabeled CE loss.
Args:
labels_x: tensor, contains labels correspondi... | 5,341,091 |
def _sch_el(self, *wert, **kwargs):
"""Element einer Schar; für einen Parameter"""
if kwargs.get('h'):
print("\nElement einer Schar von Matrizen\n")
print("Aufruf matrix . sch_el( wert )\n")
print(" matrix Matrix")
print(" wer... | 5,341,092 |
def check_directory(path, read=False, write=False, execute=False):
"""Does that path exist and can the current user rwx."""
if os.path.isdir(path) and check_mode(path, read=read, write=write, execute=execute):
return True
else:
return False | 5,341,093 |
def test_parse_from_yaml(petstore_expanded):
"""
Tests that we can parse a valid yaml file
"""
spec = OpenAPI(petstore_expanded) | 5,341,094 |
def scsilun_to_int(lun):
"""
There are two style lun number, one's decimal value is <256 and the other
is full as 16 hex digit. According to T10 SAM, the full 16 hex digit
should be swapped and converted into decimal.
For example, SC got zlinux lun number from DS8K API, '40294018'. And it
should... | 5,341,095 |
def consolidate_control_snp(data_containers, filename_or_fileobj):
"""saves a pickled dataframe with non-CpG probe values.
NOTE: no longer called in pipeline. Kept for legacy purposes, but because it uses all of SampleDataContainer objects, this happens inline with each sample to save memory.
Returns:
Control:... | 5,341,096 |
def ordered_indices(src_sizes,tgt_sizes,common_seed,shuffle=True,buckets=None):
"""Return an ordered list of indices. Batches will be constructed based
on this order."""
if shuffle:
indices = np.random.RandomState(common_seed).permutation(len(src_sizes)).astype(np.int64)
else:
indi... | 5,341,097 |
def run_ppxf(specs, templates_file, outdir, velscale=None, redo=False, V0=None):
""" Running pPXF. """
velscale = context.velscale if velscale is None else velscale
V0 = context.V if V0 is None else V0
# Reading templates
ssp_templates = fits.getdata(templates_file, extname="SSPS").T
param... | 5,341,098 |
def test_mix_up_single():
"""
Test single batch mix up op
"""
logger.info("Test single batch mix up op")
resize_height = 224
resize_width = 224
# Create dataset and define map operations
ds1 = ds.ImageFolderDatasetV2(DATA_DIR_2)
num_classes = 10
decode_op = c_vision.Decode()
... | 5,341,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.