content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def correct_name(name):
"""
Ensures that the name of object used to create paths in file system do not
contain characters that would be handled erroneously (e.g. \ or / that
normally separate file directories).
Parameters
----------
name : str
Name of object (course, file, folder, e... | 34,900 |
def getLivePosSnap(*args, **kwargs):
""" Get live pos snap """
pass | 34,901 |
def runner(parallel, config):
"""Run functions, provided by string name, on multiple cores on the current machine.
"""
def run_parallel(fn_name, items):
items = [x for x in items if x is not None]
if len(items) == 0:
return []
items = diagnostics.track_parallel(items, fn_... | 34,902 |
def get_ifc2x3_element_type(element: int) -> ifc_2x3_element_type:
"""Get IFC element type.
Args:
element (int): element ID
Returns:
ifc_2x3_element_type: ifc type
""" | 34,903 |
def containers_start(
port=8080, rmq='docker', mongo='docker', memcached='docker',
provision=False, **kwargs):
"""
Start all appropriate containers. This is, at least, worker and girder.
Optionally, mongodb and rabbitmq are included.
:param port: default port to expose.
:param rmq:... | 34,904 |
def test_calibrate_new_mlflow_run():
"""Assert that a new mlflow run is created."""
atom = ATOMClassifier(X_bin, y_bin, experiment="test", random_state=1)
atom.run("GNB")
run = atom.gnb._run
atom.gnb.calibrate()
assert atom.gnb._run is not run | 34,905 |
def hsv_to_hsl(hsv):
"""
HSV to HSL.
https://en.wikipedia.org/wiki/HSL_and_HSV#Interconversion
"""
h, s, v = hsv
s /= 100.0
v /= 100.0
l = v * (1.0 - s / 2.0)
return [
HSV._constrain_hue(h),
0.0 if (l == 0.0 or l == 1.0) else ((v - l) / min(l, 1.0 - l)) * 100,
... | 34,906 |
def is_ci() -> bool:
"""Returns if current execution is running on CI
Returns:
`True` if current executions is on CI
"""
return os.getenv('CI', 'false') == 'true' | 34,907 |
def reindex_faces(mesh, ordering):
"""
Reorder the faces of the given mesh, returning a new mesh.
Args:
mesh (lacecore.Mesh): The mesh on which to operate.
ordering (np.arraylike): An array specifying the order in which
the original faces should be arranged.
Returns:
... | 34,908 |
def check_exact_match(line, expected_line):
"""
Uses regular expressions to find an exact (not partial) match for 'expected_line' in 'line', i.e.
in the example below it matches 'foo' and succeeds:
line value: '66118.999958 - INFO - [MainThread] - ly_test_tools.o3de.asset_processor - foo'
ex... | 34,909 |
def rounding_filters(filters, w_multiplier):
""" Calculate and round number of filters based on width multiplier. """
if not w_multiplier:
return filters
divisor = 8
filters *= w_multiplier
new_filters = max(divisor, int(filters + divisor / 2) // divisor * divisor)
if new_filters < 0.9 *... | 34,910 |
def process(request, service, identifier):
"""
View that displays a detailed description for a WPS process.
"""
wps = get_wps_service_engine(service)
wps_process = wps.describeprocess(identifier)
context = {'process': wps_process,
'service': service,
'is_link': abs... | 34,911 |
def update(pipeline_id, name, description):
"""Submits a request to CARROT's pipelines update mapping"""
# Create parameter list
params = [
("name", name),
("description", description),
]
return request_handler.update("pipelines", pipeline_id, params) | 34,912 |
def test_failed_split_line_line_algo_png() -> None:
"""Failed to compute line for split line with line detection alog."""
MockDisableSeparatePage(MAX_VAL, FUZZING).treat_file(
get_absolute_from_current_path(
__file__, "failed_split_line_line_algo.png"
),
{
ConstSt... | 34,913 |
def symmetric_poly(n, *gens, **args):
"""Generates symmetric polynomial of order `n`. """
gens = _analyze_gens(gens)
if n < 0 or n > len(gens) or not gens:
raise ValueError("can't generate symmetric polynomial of order %s for %s" % (n, gens))
elif not n:
poly = S.One
else:
p... | 34,914 |
def load(name: str, *args, **kwargs) -> Any:
"""
Loads the unit specified by `name`, initialized with the given arguments
and keyword arguments.
"""
entry = get_entry_point(name)
return entry.assemble(*args, **kwargs) | 34,915 |
def get_gate_names_2qubit() -> List[str]:
"""Return the list of valid gate names of 2-qubit gates."""
names = []
names.append("cx")
names.append("cz")
names.append("swap")
names.append("zx90")
names.append("zz90")
return names | 34,916 |
def test_insert(connection: Connection) -> None:
"""Insert and delete queries are handled properly."""
def test_empty_query(c: Cursor, query: str) -> None:
assert c.execute(query) == -1, "Invalid row count returned"
assert c.rowcount == -1, "Invalid rowcount value"
assert c.description ... | 34,917 |
def positive_leading_quat(quat):
"""Returns the positive leading version of the quaternion.
This function supports inputs with or without leading batch dimensions.
Args:
quat: A quaternion [w, i, j, k].
Returns:
The equivalent quaternion [w, i, j, k] with w > 0.
"""
# Ensure quat is an np.array ... | 34,918 |
def test_aperture_photometry_with_error_units():
"""Test aperture_photometry when error has units (see #176)."""
data1 = np.ones((40, 40), dtype=float)
data2 = u.Quantity(data1, unit=u.adu)
error = u.Quantity(data1, unit=u.adu)
radius = 3
true_flux = np.pi * radius * radius
unit = u.adu
... | 34,919 |
def comp_avg_silh_metric(data_input, cluster_indices, silh_max_samples, silh_distance):
"""
Given a input data matrix and an array of cluster indices, returns the
average silhouette metric for that clustering result (computed across all clusters).
Parameters
----------
data_input : ndarray
... | 34,920 |
def convert_lgg_data_tromso_reseksjon(path):
"""convert_lgg_data"""
convert_table = get_convert_table()
conn = sqlite3.connect(util.DB_PATH)
cursor = conn.cursor()
for volume in glob.glob(path + "*.nii"):
if "label" in volume:
continue
case_id = re.findall(r'\d+\b', volu... | 34,921 |
def _validate_args(func, args, keywords):
"""Signal error if an alias is of the wrong type."""
for indx in list(range(len(args))) + list(keywords.keys()):
if indx not in func.ALIAS_ARGS:
continue
# Get argument type and translate
arg = _getarg(indx, args, keywords)
... | 34,922 |
async def test_entity_debug_info_message(hass, mqtt_mock):
"""Test MQTT debug info."""
await help_test_entity_debug_info_message(
hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG
) | 34,923 |
def test_precommit_install(
check_dir_mock: Mock,
cli_fs_runner: CliRunner,
):
"""
GIVEN None
WHEN the command is run
THEN it should create a pre-commit git hook script
"""
result = cli_fs_runner.invoke(
cli,
["install", "-m", "local"],
)
hook = open(".git/hooks/... | 34,924 |
def prepare_url(base_url, path, url_params=None):
"""Prepare url from path and params"""
if url_params is None:
url_params = {}
url = '{0}{1}'.format(base_url, path)
if not url.endswith('/'):
url += '/'
url_params_str = urlencode(url_params)
if url_params_str:
url += '?'... | 34,925 |
def extract_at_interval(da: xr.DataArray, interval) -> xr.DataArray:
"""Reduce size of an Error Grid by selecting data at a fixed interval along
both the number of high- and low-fidelity samples.
"""
return da.where(
da.n_high.isin(da.n_high[slice(None, None, interval)]) *
da.n_low.isin(... | 34,926 |
def compute_log_zT_var(log_rho_var, log_seebeck_sqr_var, log_kappa_var):
"""Compute the variance of the logarithmic thermoelectric figure
of merit zT.
"""
return log_rho_var + log_seebeck_sqr_var + log_kappa_var | 34,927 |
def main(global_config, **settings):
""" Very basic pyramid app """
config = Configurator(settings=settings)
config.include('pyramid_swagger')
config.add_route(
'sample_nonstring',
'/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}',
)
config.add_route('standard', '/sample/... | 34,928 |
def main(args):
"""
Function analyze the `Red Sequence` using by cross-matching catalogues
from `RedMapper` (http://risa.stanford.edu/redmapper/) and NOAO Data-Lab
catalogue.
"""
## Reading all elements and converting to python dictionary
param_dict = vars(args)
## Checking for correct i... | 34,929 |
def plot_decision_boundaries(model, X, y,
probability=False, show_input=False,
feature_names=None, class_names=None, alpha=0.5, size=30):
"""Plots the decision boundaries for a classifier with 2 features.
This is good way to visualize the decision boundaries of various classifiers
to build intution... | 34,930 |
async def cardMovedUp(cardName, destination, channel, author):
"""
Discord embed send function using a specific embed style
Args:
cardName (STR): Name of a given card
destination (STR): Name of a given distentation
channel (OBJ): Discord channel object
author (str, optional)... | 34,931 |
def get_name():
"""MUST HAVE FUNCTION! Returns plugin name."""
return "ASP.NET MVC" | 34,932 |
def tag_images(
x_test,
test_case_images,
tag_list_file,
image_source,
clean=False
):
"""
Performs the tagging of abnormal images using RTEX@R
:param test_case_ids:
:param x_test:
:param x_test:
:param tag_list_file:
:param clean: if True the predictio... | 34,933 |
def close_debug_windows():
"""
Close all debugging related views in active window.
"""
window = sublime.active_window()
# Remember current active view
current_active_view = window.active_view()
for view in window.views():
if is_debug_view(view):
window.focus_view(view)
... | 34,934 |
def test_consensus_cluster_membership():
"""Tests reading cluster membership from a consensus cluster."""
with create_cluster('consensus', nodes=3) as cluster:
node = cluster.node(1)
assert len(node.client.cluster.nodes()) == 3, "number of nodes is not equal to 3"
assert node.client.clus... | 34,935 |
def load_CIFAR(model_mode):
"""
Loads CIFAR-100 or CIFAR-10 dataset and maps it to Target Model and Shadow Model.
:param model_mode: one of "TargetModel" and "ShadowModel".
:param num_classes: one of 10 and 100 and the default value is 100
:return: Tuple of numpy arrays:'(x_train, y_train), (x_... | 34,936 |
def _jbackslashreplace_error_handler(err):
"""
Encoding error handler which replaces invalid characters with Java-compliant Unicode escape sequences.
:param err: An `:exc:UnicodeEncodeError` instance.
:return: See https://docs.python.org/2/library/codecs.html?highlight=codecs#codecs.register_error
... | 34,937 |
def calculate_spark_settings(instance_type, num_slaves, max_executor=192,
memory_overhead_coefficient=0.15,
num_partitions_factor=3):
"""
More info:
http://c2fo.io/c2fo/spark/aws/emr/2016/07/06/apache-spark-config-cheatsheet/
"""
all_instanc... | 34,938 |
def run_on_host(con_info, command):
"""
Runs a command on a target pool of host defined in a hosts.yaml file.
"""
# Paramiko client configuration
paramiko.util.log_to_file(base + "prt_paramiko.log")
UseGSSAPI = (paramiko.GSS_AUTH_AVAILABLE)
DoGSSAPIKeyExchange = (paramiko.GSS_AUTH_AVAILABLE)... | 34,939 |
def main(argv=None):
"""
"""
print("starting GUI...")
input_shapefile, info_file, output_shapefile = gui_inputs()
print("Start renaming fields...")
batch_rename_field_shapefile(input_shapefile, info_file, output_shapefile)
print("... renaming completed!") | 34,940 |
def split(reader, line_count, suffix="%05d.pickle", dumper=pickle.dump):
"""
you can call the function as:
split(paddle.dataset.cifar.train10(), line_count=1000,
suffix="imikolov-train-%05d.pickle")
the output files as:
|-imikolov-train-00000.pickle
|-imikolov-train-00001.pickle
|... | 34,941 |
def extract(root_data_folder, dry=False):
"""
Extracts behaviour only
"""
extract_session.bulk(root_data_folder, dry=dry, glob_flag='**/extract_me.flag') | 34,942 |
def uniqueColor(string):
"""
Returns a color from the string.
Same strings will return same colors, different strings will return different colors ('randomly' different)
Internal: string =md5(x)=> hex =x/maxhex=> float [0-1] =hsv_to_rgb(x,1,1)=> rgb =rgb_to_int=> int
:param string: input string
... | 34,943 |
def _quoteattr(data, entities={}):
""" Escape and quote an attribute value.
Escape &, <, and > in a string of data, then quote it for use as
an attribute value. The \" character will be escaped as well, if
necessary.
You can escape other strings of data by passing a dictionary as
... | 34,944 |
def external_login_confirm_email_get(auth, uid, token):
"""
View for email confirmation links when user first login through external identity provider.
HTTP Method: GET
When users click the confirm link, they are expected not to be logged in. If not, they will be logged out first and
redirected bac... | 34,945 |
def date_since_epoch(date, unit='day'):
""" Get the date for the specified date in unit
:param date: the date in the specified unit
:type date: int
:param unit: one of 'year', 'month' 'week', 'day', 'hour', 'minute',
or 'second'
:return: the corresponding date
:rtype: ee.Date
"""
... | 34,946 |
def main():
"""
This program should implement a console program
that asks 3 inputs (a, b, and c)
from users to compute the roots of equation
ax^2 + bx + c = 0
Output format should match with 3 conditions, which have different number of root .
"""
print('stanCode Quadratic Solver')
a = int(input('Enter a:'))
b... | 34,947 |
def eval_assoc(param_list, meta):
"""
Evaluate the assoication score between a given text and
a list of categories or statements.
Param 1 - string, the text in question
Param 2 - list of strings, the list of categories to associate Param 1 to
"""
data = {
'op': 'eval_assoc',
... | 34,948 |
def quiver3d(*args, **kwargs):
"""Wraps `mayavi.mlab.quiver3d`
Args:
*args: passed to `mayavi.mlab.quiver3d`
**kwargs: Other Arguments are popped, then kwargs is passed to
`mayavi.mlab.quiver3d`
Keyword Arguments:
cmap (str, None, False): see :py:func:`apply_cmap`
... | 34,949 |
def get_instance_types(self):
"""
Documentation:
---
Description:
Generate SSH pub
"""
instance_types = sorted([instance_type["InstanceType"] for instance_type in self.ec2_client.describe_instance_types()["InstanceTypes"]])
return instance_types | 34,950 |
def analysis_result():
"""
use the model predict the test data , then analysis the y_predict and y_ture
"""
train_x, train_y, test_x, test_y = eunite_data.load_eunite_train_data()
model = keras.models.load_model("./model/load_model")
# test_x.shape = 229 * 13
y_predict = model.predict(trai... | 34,951 |
def import_zip(wiki, file):
"""
Import a zip into a wiki
Zip should contain two directories:
pages
page.txt # path: page
page
subpage.txt # path: page/subpage
assets
internal_id.jpg
Page extensions must be .txt or .md - ... | 34,952 |
def ret_digraph_points(sed, digraph):
"""Finds the digraph points of the subject extracted data.
Parameters
----------
`sed` (object) "_subject","_track_code", "data": [{"digraph","points"}]
Returns
---------
(list) The points of the particular digraph found
"""
ret = [d['points'] fo... | 34,953 |
async def test_async_setup_entry_host_unavailable(hass):
"""Test async_setup_entry when host is unavailable."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: HOST, CONF_PORT: PORT},
unique_id=f"{HOST}:{PORT}",
)
with patch(
"homeassistant.components.cert_expir... | 34,954 |
def _sizeof_fmt(num):
"""Format byte size to human-readable format.
https://web.archive.org/web/20111010015624/http://blogmag.net/blog/read/38/Print_human_readable_file_size
Args:
num (float): Number of bytes
"""
for x in ["bytes", "KB", "MB", "GB", "TB", "PB"]:
if num < 1024.0:
... | 34,955 |
def gatherData(gatherLFP = True):
"""
Function for/to <short description of `netpyne.sim.gather.gatherData`>
Parameters
----------
gatherLFP : bool
<Short description of gatherLFP>
**Default:** ``True``
**Options:** ``<option>`` <description of option>
"""
from ... | 34,956 |
def stations_by_distance(stations, p):
"""For a list of stations (MonitoringStation object) and
coordinate p (latitude, longitude), returns list of tuples
(station, distance) sorted by the distance from the given
coordinate p"""
# Create the list of (stations, distance) tuples
station_dist = []... | 34,957 |
def process(fh: TextIO, headers: Optional[Dict[str, str]],
writer: csv.DictWriter, args: Args) -> int:
"""
Process the file into Mongo (client)
First 5 columns are: STREAM, DATE, STATION, REP, #GRIDS
Columns after that are the measurements
"""
reader = csv.DictReader(fh, delimiter=... | 34,958 |
def dipole_moment_programs():
""" Constructs a list of program modules implementing
static dipole moment output readers.
"""
return pm.program_modules_with_function(pm.Job.DIP_MOM) | 34,959 |
def generate_api_v2(model_output_dir, output, level, state, fips):
"""The entry function for invocation"""
# Load all API Regions
selected_dataset = combined_datasets.load_us_timeseries_dataset().get_subset(
aggregation_level=level, exclude_county_999=True, state=state, fips=fips,
)
_logger... | 34,960 |
def _SafeTcSetPgrp(fd, pgrp):
"""Set |pgrp| as the controller of the tty |fd|."""
try:
curr_pgrp = os.tcgetpgrp(fd)
except OSError as e:
# This can come up when the fd is not connected to a terminal.
if e.errno == errno.ENOTTY:
return
raise
# We can change the owner only if currently own ... | 34,961 |
def test_review_submission_list_query_bootcamp_run_id(admin_drf_client):
"""
The review submission list view should return a list of submissions filtered by bootcamp run id
"""
submission = ApplicationStepSubmissionFactory.create(is_review_ready=True)
bootcamp_run = submission.bootcamp_application.b... | 34,962 |
def scan(self, s, pfits=True):
"""
Returns
-------
namedtuple('spectrum', 'w f berv bjd blaze drift timeid sn55 ')
w - wavelength
f - flux
berv - Barycentric Earth Radial Velocity
bjd - Barycentric Julian Day
blaze - Blaze filename
dri... | 34,963 |
def run_experiment(params: Dict[str, Dict]):
"""
This function runs the experiments for the given parameters and stores the results at the end.
:param params: a dictionary containing all different parameters for all different modules.
"""
# Create the action space; initialize the environment; initi... | 34,964 |
def kappa(a, b, c, d):
""" GO term 2
| yes | no |
-------------------------------
GO | yes | a | b |
term1 | no | c | d |
kapa(GO_1, GO_2) = 1 - (1 - po) / (1 - pe)
po = (a + d) / (a + b + c + d)
marginal_a = ( (a + b) * ( a + c )) / (a + b + ... | 34,965 |
def test_8():
"""
Test outputs of compute_direction_XY(), with n=16, m=100,
no_vars=m.
"""
np.random.seed(91)
n = 16
m = 100
no_vars = m
f = est_dir.quad_f_noise
minimizer = np.ones((m,))
centre_point = np.random.uniform(-2, 2, (m,))
matrix = est_dir.quad_func... | 34,966 |
def test_CreativeProject_integration_ask_tell_ask_works(covars, model_type, train_X, train_Y,
covars_proposed_iter, covars_sampled_iter,
response_sampled_iter, monkeypatch):
"""
te... | 34,967 |
def plot_sources(azimuth, elevation, distance=1.6):
"""Display sources in a 3D plot
Arguments:
azimuth (np.ndarray): azimuth of the sources in degree. Must be same length as elevation
elevation (np.ndarray): elevation of the sources in degree. Must be same length as azimuth
distance (flo... | 34,968 |
def ferret_init(id):
"""
Initialization for the stats_chisquare Ferret PyEF
"""
axes_values = [ pyferret.AXIS_DOES_NOT_EXIST ] * pyferret.MAX_FERRET_NDIM
axes_values[0] = pyferret.AXIS_CUSTOM
false_influences = [ False ] * pyferret.MAX_FERRET_NDIM
retdict = { "numargs": 3,
"d... | 34,969 |
def has(key):
"""Checks if the current context contains the given key."""
return not not (key in Context.currentContext.values) | 34,970 |
def pilot_realignement():
"""
Realignement
============
"""
# Pilot imports
import os
from caps.toy_datasets import get_sample_data
from capsul.study_config import StudyConfig
from pclinfmri.preproc.pipeline import SpmRealignement
"""
Study configuration
---------------... | 34,971 |
def VGG_16(weights_path=None):
"""
Creates a convolutional keras neural network, training it with data from ct scans from both datasets.
Using the VGG-16 architecture.
----
Returns the model
"""
X_train, Y_train = loadfromh5(1, 2, 19)
X_train1, Y_train1 = loadfromh5(2, 2, 19)
X_tr... | 34,972 |
def test_io_stc_h5(tmpdir, is_complex, vector):
"""Test IO for STC files using HDF5."""
if vector:
stc = _fake_vec_stc(is_complex=is_complex)
else:
stc = _fake_stc(is_complex=is_complex)
pytest.raises(ValueError, stc.save, tmpdir.join('tmp'),
ftype='foo')
out_name =... | 34,973 |
def test_cross_correlate_masked_over_axes():
"""Masked normalized cross-correlation over axes should be
equivalent to a loop over non-transform axes."""
# See random number generator for reproducible results
np.random.seed(23)
arr1 = np.random.random((8, 8, 5))
arr2 = np.random.random((8, 8, 5)... | 34,974 |
def nested_dict_itervalue(nested):
"""
http://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values
:param nested:
Nested dictionary.
:return:
Iteratoer of values.
>>> list(nested_dict_iter({'a': {'b': {'c': 1, 'd': 2},
... | 34,975 |
def inv_fap_davies(p, fmax, t, y, dy, normalization='standard'):
"""Inverse of the davies upper-bound"""
from scipy import optimize
args = (fmax, t, y, dy, normalization)
z0 = inv_fap_naive(p, *args)
func = lambda z, *args: fap_davies(z, *args) - p
res = optimize.root(func, z0, args=args, method... | 34,976 |
def test_direct_evaluation(infix, values, expected):
"""Test direct evaluation of an infix against some values"""
assert evaluate(infix, values) == expected | 34,977 |
def public(request):
"""browse public repos. Login not required"""
username = request.user.get_username()
public_repos = DataHubManager.list_public_repos()
# This should really go through the api... like everything else
# in this file.
public_repos = serializers.serialize('json', public_repos)
... | 34,978 |
def get_boundaries_old(im,su=5,sl=5,valley=5,cutoff_max=1.,plt_val=False):
"""Bintu et al 2018 candidate boundary calling"""
im_=np.array(im)
ratio,ration,center,centern=[],[],[],[]
for i in range(len(im)):
x_im_l,y_im_l = [],[]
x_im_r,y_im_r = [],[]
xn_im_l,yn_im_l = [],[]
... | 34,979 |
def zfsr32(val, n):
"""zero fill shift right for 32 bit integers"""
return (val >> n) if val >= 0 else ((val + 4294967296) >> n) | 34,980 |
def n_optimize_fn(step: int) -> int:
"""`n_optimize` scheduling function."""
if step <= FLAGS.change_n_optimize_at:
return FLAGS.n_optimize_1
else:
return FLAGS.n_optimize_2 | 34,981 |
def compute_receptive_field(model, img_size=(1, 3, 3)):
"""Computes the receptive field for a model.
The receptive field is computed using the magnitude of the gradient of the
model's output with respect to the input.
Args:
model: Model for hich to compute the receptive field. Assumes NCHW inp... | 34,982 |
def bound_free_emission(r_packet, time_explosion, numba_plasma, continuum, continuum_id):
"""
Bound-Free emission - set the frequency from photo-ionization
Parameters
----------
r_packet : tardis.montecarlo.montecarlo_numba.r_packet.RPacket
time_explosion : float
numba_plasma : tardis.monte... | 34,983 |
def flippv(pv, n):
"""Flips the meaning of an index partition vector.
Parameters
----------
pv : ndarray
The index partition to flip.
n : integer
The length of the dimension to partition.
Returns
-------
notpv : ndarray
The complement of pv.
Example:
>>... | 34,984 |
def test_create_api_message_defaults(hass):
"""Create a API message response of a request with defaults."""
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#xy")
directive_header = request["directive"]["header"]
directive = messages.AlexaDirective(request)
msg = directive.respon... | 34,985 |
def PseAAC(fn, pt):
"""
creating PseAAC matirx under user dir
"""
cmd = 'python ' + root_path + 'tool/BioSeq-Analysis2/pse.py ' + fn + '/test.fasta Protein -method PC-PseAAC-General ' + \
'-f csv -out ' + fn + '/' + pt + '_PseAAC.txt -lamada 2 -w 0.3 -labels -1'
os.system(cmd) | 34,986 |
def is_dir(path: Union[str, Path]) -> bool:
"""Check if the given path is a directory
:param path: path to be checked
"""
if isinstance(path, str):
path = Path(path)
if path.exists():
return path.is_dir()
else:
return str(path).endswith("/") | 34,987 |
def log_binlog_upload(instance, binlog):
""" Log to the master that a binlog has been uploaded
Args:
instance - a hostAddr object
binlog - the full path to the binlog file
"""
zk = MysqlZookeeper()
binlog_creation = datetime.datetime.fromtimestamp(os.stat(binlog).st_atime)
replica_set =... | 34,988 |
def work(out_dir: str, in_coord: str, in_imd_path: str, in_topo_path: str, in_perttopo_path: str, in_disres_path: str,
nmpi: int = 1, nomp: int = 1, out_trg: bool = False,
gromos_bin: str = None, work_dir: str = None):
"""
Executed by repex_EDS_long_production_run as worker_scripts
... | 34,989 |
def test_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev):
"""sigma_dut DPP/QR (mutual) initiator as Enrollee (extra check)"""
run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev,
extra="DPPAuthDirection,Mutual,") | 34,990 |
def _replace_dendro_colours(
colours,
above_threshold_colour="C0",
non_cluster_colour="black",
colorscale=None
):
""" Returns colorscale used for dendrogram tree clusters.
Keyword arguments:
colorscale -- Colors to use for the plot in rgb format.
Should have 8 colours.
"""
f... | 34,991 |
def document_to_vector(lemmatized_document, uniques):
"""
Converts a lemmatized document to a bow vector
representation.
1/0 for word exists/doesn't exist
"""
#print(uniques)
# tokenize
words = re.findall(r'\w+', lemmatized_document.lower())
# vector = {}
vector = [0]*len(uniq... | 34,992 |
def ubcOcTree(FileName_Mesh, FileName_Model, pdo=None):
"""
Description
-----------
Wrapper to Read UBC GIF OcTree mesh and model file pairs. UBC OcTree models are defined using a 2-file format. The "mesh" file describes how the data is descritized. The "model" file lists the physical property values fo... | 34,993 |
def main(featsFolder, jsonPath, modelPath, maxDur, normalised, cuda):
"""
Adding wav2vec2 features to a given dataset and writting its reference to a json file
Example
----------
python wav2vec2.py -f "xlsr_53_56k_cut30" -d 29.99 -n True -j "/mnt/HD-Storage/Datasets/Recola_46/data.json" -m "/mnt/... | 34,994 |
def invert_and_write_to_disk(term2doc, results_path, block_num):
"""
Takes as an input a list of term-doc_id pairs, creates an inverted index out of them,
sorts alphabetically by terms to allow merge and saves to a block file.
Each line represents a term and postings list, e.g. abolish 256 1 278 2 2... | 34,995 |
def load_colormaps():
"""Return the provided colormaps."""
return load_builtin_data('colormaps') | 34,996 |
def discriminator(hr_images, scope, dim):
"""
Discriminator
"""
conv_lrelu = partial(conv, activation_fn=lrelu)
def _combine(x, newdim, name, z=None):
x = conv_lrelu(x, newdim, 1, 1, name)
y = x if z is None else tf.concat([x, z], axis=-1)
return minibatch_stddev_layer(y)
... | 34,997 |
def addchallenges(request) :
"""
管理员添加新的题目
"""
if request.user.is_superuser :
if request.method == 'POST' :
success = 0
form = forms.AddChallengeForm(request.POST, request.FILES)
if form.is_valid() :
success = 1
print(request.FILES)
if request.FILES :
i = models.Challenges(file=request.F... | 34,998 |
def _decompose_ridge(Xtrain, alphas, n_alphas_batch=None, method="svd",
negative_eigenvalues="zeros"):
"""Precompute resolution matrices for ridge predictions.
To compute the prediction::
Ytest_hat = Xtest @ (XTX + alphas * Id)^-1 @ Xtrain^T @ Ytrain
where XTX = Xtrain^T ... | 34,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.