content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def validateFilename(value):
"""
Validate filename.
"""
if 0 == len(value):
raise ValueError("Name of SimpleGridDB file must be specified.")
return value | 5,349,900 |
def readPNM(fd):
"""Reads the PNM file from the filehandle"""
t = noncomment(fd)
s = noncomment(fd)
m = noncomment(fd) if not (t.startswith('P1') or t.startswith('P4')) else '1'
data = fd.read()
ls = len(s.split())
if ls != 2 :
name = "<pipe>" if fd.name=="<fdopen>" else "Filename = {0}".format(fd.nam... | 5,349,901 |
def test_atomic_decimal_enumeration_4_nistxml_sv_iv_atomic_decimal_enumeration_5_5(mode, save_output, output_format):
"""
Type atomic/decimal is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/decimal/Schema+Instance/NISTSchema-SV-IV-atomic-decimal-enumeration-5.xsd... | 5,349,902 |
def run(argv=None):
"""
Pipeline entry point, runs the all the necessary processes
"""
# Initialize runtime parameters as object
pipeline_options = PipelineOptions()
# Save main session state so pickled functions and classes
# defined in __main__ can be unpickled
pipeline_options.view_as... | 5,349,903 |
def gdxfile(rawgdx):
"""A gdx.File fixture."""
return gdx.File(rawgdx) | 5,349,904 |
def generate_sample( # pylint: disable=too-many-arguments
samp: Sample,
set_type: str,
handler: typing.Callable,
input_path: Path,
output_path: Path,
pre_proc: ProcType,
post_proc: ProcType):
"""Generate JSON for a sample
Arguments:
samp {Sample}... | 5,349,905 |
def test_children():
"""test ExternalLink.__children__()"""
node1 = ExternalLink(wraptext("http://example.com/"), brackets=False)
node2 = ExternalLink(wraptext("http://example.com/"),
wrap([Text("Example"), Text("Page")]))
gen1 = node1.__children__()
gen2 = node2.__children_... | 5,349,906 |
def AppBar(
absolute: bool = None,
app: bool = None,
attributes: dict = {},
bottom: bool = None,
children: list = [],
class_: str = None,
clipped_left: bool = None,
clipped_right: bool = None,
collapse: bool = None,
collapse_on_scroll: bool = None,
color: str = None,
dark... | 5,349,907 |
def check_file(filename):
"""Check if "filename" exists and is a file.
Returns:
True if file exists and is a file.
False if filename==None or is not a file.
"""
file_ok = True
error_mssg = ""
if(filename == None):
error_mssg = "Error: file is missing."
f... | 5,349,908 |
def conjoin(*funcs):
"""
Creates a function that composes multiple predicate functions into a single predicate that tests
whether **all** elements of an object pass each predicate.
Args:
*funcs (callable): Function(s) to conjoin.
Returns:
Conjoin: Function(s) wrapped in a :class:`C... | 5,349,909 |
def main():
"""
Entry-point for the function.
"""
conn_obj = connect_to_database_server(DATABASE)
if conn_obj == -1:
print("Connection to PostgreSQL Database: {} failed.".format(DATABASE))
sys.exit(0)
else:
conn = conn_obj[0]
cur = conn_obj[1]
n_... | 5,349,910 |
def calculate_file_sha256(file_path):
"""calculate file sha256 hash code."""
with open(file_path, 'rb') as fp:
sha256_cal = hashlib.sha256()
sha256_cal.update(fp.read())
return sha256_cal.hexdigest() | 5,349,911 |
def select_columns_by_feature_type(df, unique_value_to_total_value_ratio_threshold=.05, text_unique_threshold=.9,
exclude_strings = True, return_dict = False, return_type='categoric'):
""" Determine if a column fits into one of the following types: numeric, categoric, datetime, text.
set r... | 5,349,912 |
def _Counter_random(self, filter=None):
"""Return a single random elements from the Counter collection, weighted by count."""
return _Counter_randoms(self, 1, filter=filter)[0] | 5,349,913 |
def EnsureAndroidSdkPackagesInstalled(abi):
"""Return true if at least one package was not already installed."""
abiPackageList = SdkPackagesForAbi(abi)
installedSomething = False
packages = AndroidListSdk()
for package in abiPackageList:
installedSomething |= EnsureSdkPackageInstalled(packa... | 5,349,914 |
def dataframe_like(value, name, optional=False, strict=False):
"""
Convert to dataframe or raise if not dataframe_like
Parameters
----------
value : object
Value to verify
name : str
Variable name for exceptions
optional : bool
Flag indicating whether None is allowed
... | 5,349,915 |
def pcaFunc(z, n_components=100):
"""
PCA
"""
pca = PCA(n_components=100)
pca_result = pca.fit_transform(z)
re = pd.DataFrame()
re['pca-one'] = pca_result[:, 0]
re['pca-two'] = pca_result[:, 1]
re['pca-three'] = pca_result[:, 2]
# Not print Now
# print('Explained variation pe... | 5,349,916 |
def choose_optimizer(discriminator, generator, netD, netG, lr_d=2e-4, lr_g=2e-3):
"""
Set optimizers for discriminator and generator
:param discriminator: str, name
:param generator: str, name
:param netD:
:param netG:
:param lr_d:
:param lr_g:
:return: optimizerD, optimizerG
"""... | 5,349,917 |
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the giv... | 5,349,918 |
def prod(*args: int) -> int:
"""
This function is wrapped and documented in `_polymorphic.prod()`.
"""
prod_ = 1
for arg in args:
prod_ *= arg
return prod_ | 5,349,919 |
def field_value(field):
"""
Returns the value for this BoundField, as rendered in widgets.
"""
if field.form.is_bound:
if isinstance(field.field, FileField) and field.data is None:
val = field.form.initial.get(field.name, field.field.initial)
else:
val = field.dat... | 5,349,920 |
def distances(p):
"""Compute lengths of shortest paths between all nodes in Pharmacophore.
Args:
p (Pharmacophore): model to analyse
Returns:
dist (numpy array): array with distances between all nodes
"""
if not isinstance(p, Pharmacophore):
raise TypeError("Expected Pharmac... | 5,349,921 |
def initial_data(logged_on_user, users_fixture, streams_fixture):
"""
Response from /register API request.
"""
return {
'full_name': logged_on_user['full_name'],
'email': logged_on_user['email'],
'user_id': logged_on_user['user_id'],
'realm_name': 'Test Organization Name'... | 5,349,922 |
def affine_relu_backward(dout, cache):
"""
Backward pass for the affine-relu convenience layer
"""
fc_cache, relu_cache = cache
da = relu_backward(dout, relu_cache)
dx, dw, db = affine_backward(da, fc_cache)
return dx, dw, db | 5,349,923 |
def total_equalities_generator(block):
"""
Generator which returns all equality Constraint components in a model.
Args:
block : model to be studied
Returns:
A generator which returns all equality Constraint components block
"""
for c in activated_block_component_generator(block... | 5,349,924 |
def create_initial_population() -> List[Image]:
"""
Create population at step 0
"""
return [random_image() for _ in range(POP_SIZE)] | 5,349,925 |
def adapt(value: Any, pg_type: str) -> Any:
"""
Coerces a value with a PG type into its Python equivalent.
:param value: Value
:param pg_type: Postgres datatype
:return: Coerced value.
"""
if value is None:
return None
if pg_type in _TYPE_MAP:
return _TYPE_MAP[pg_type](v... | 5,349,926 |
def createPREMISEventXML(eventType, agentIdentifier, eventDetail, eventOutcome,
outcomeDetail=None, eventIdentifier=None,
linkObjectList=[], eventDate=None):
"""
Actually create our PREMIS Event XML
"""
eventXML = etree.Element(PREMIS + "event", nsmap=P... | 5,349,927 |
def get_primary_key(conn, table, columns):
""" attempts to reverse lookup the primary key by querying the table using the first column
and iteratively adding the columns that comes after it until the query returns a
unique row in the table.
:param
conn: an SQLite connection object
... | 5,349,928 |
def redirect_to_docs():
"""Redirect to API docs when at site root"""
return RedirectResponse('/redoc') | 5,349,929 |
def pytest_generate_tests(metafunc):
""" Dynamic test case generation and parameterization for this module. """
if "delimiter" in metafunc.fixturenames:
metafunc.parametrize("delimiter", ["\t", ","]) | 5,349,930 |
def init_neighbours(key):
"""
Sets then neighbouring nodes and initializes the edge count to the neighbours to 1
:param key: str - key of node to which we are searching the neighbours
:return: dictionary of neighbours with corresponding edge count
"""
neighbours = {}
neighbouring_nodes = gra... | 5,349,931 |
def computeNumericalGradient(J, theta):
""" Compute numgrad = computeNumericalGradient(J, theta)
theta: a matrix of parameters
J: a function that outputs a real-number and the gradient.
Calling y = J(theta)[0] will return the function value at theta.
"""
# Initialize numgrad with zeros
numgrad = np.zer... | 5,349,932 |
def get_error_msg(handle):
"""
Get the latest and greatest DTrace error.
"""
txt = LIBRARY.dtrace_errmsg(handle, LIBRARY.dtrace_errno(handle))
return c_char_p(txt).value | 5,349,933 |
def sigma_hat(frequency, sigma, epsilon=epsilon_0, quasistatic=False):
"""
conductivity with displacement current contribution
.. math::
\hat{\sigma} = \sigma + i \omega \\varepsilon
**Required**
:param (float, numpy.array) frequency: frequency (Hz)
:param float sigma: electrical con... | 5,349,934 |
def encode_list(key, list_):
# type: (str, Iterable) -> Dict[str, str]
"""
Converts a list into a space-separated string and puts it in a dictionary
:param key: Dictionary key to store the list
:param list_: A list of objects
:return: A dictionary key->string or an empty dictionary
"""
... | 5,349,935 |
async def delete_relationship(request: web.Request):
"""
Remove relationships of resource.
Uses the :meth:`~aiohttp_json_api.schema.BaseSchema.delete_relationship`
method of the schema to update the relationship.
:seealso: http://jsonapi.org/format/#crud-updating-relationships
"""
relation... | 5,349,936 |
def save_obj(obj, saved_name ):
"""
===============================================================
save_obj(obj, saved_name )
===============================================================
this function is used to save any python object to your hard desk
Inputs:
----------
... | 5,349,937 |
def cost_efficiency(radius, height, cost):
"""Compute and return the cost efficiency of a steel can size.
The cost efficiency is the volume of the can divided by its cost.
Parameters
radius: the radius of the steel can
height: the height of the steel can
cost: the cost of the steel ... | 5,349,938 |
def process_response():
"""
Outer scope for processing the response to a request via the '/response' endpoint. Ensure all data is present,
request exists in Pending table and then change case status and notify app about the response via webhook.
:return: status code, message
TODO set up
TOD... | 5,349,939 |
def test_point_within_dimensions_border():
"""Make sure a point on the non-zero border is rejected as out of bounds"""
point = np.array([100, 20])
image_dimensions = np.array([100, 100])
assert not point_within_dimensions(point, image_dimensions) | 5,349,940 |
def cb_xmlrpc_register(args):
"""
Register as a pyblosxom XML-RPC plugin
"""
args['methods'].update({'pingback.ping': pingback})
return args | 5,349,941 |
def try_except(method):
"""
A decorator method to catch Exceptions
:param:
- `func`: A function to call
"""
def wrapped(self, *args, **kwargs):
try:
return method(self, *args, **kwargs)
except self.error as error:
log_error(error, self.logger, self.erro... | 5,349,942 |
def sosfilter_double_c(signal, sos, states=None):
"""Second order section filter function using cffi, double precision.
signal_out, states = sosfilter_c(signal_in, sos, states=None)
Parameters
----------
signal : ndarray
Signal array of shape (N x 0).
sos : ndarray
Second order... | 5,349,943 |
def log_to_csv(queries_info):
"""
Write to CSV.
"""
with open('file_name.csv', 'a') as f:
writer = csv.writer(f)
for line in queries_info:
writer.writerow(line) | 5,349,944 |
def setup_logging(name, default_path='graphy/logging.yaml', default_level=logging.INFO):
""" Setup logging configuration """
path = files.get_absolute_path(default_path, from_project=True)
try:
with open(path, 'r') as f:
config = yaml.safe_load(f.read())
logging.config.dictCo... | 5,349,945 |
def test_STMM_fit():
"""Test Fit of STMB"""
clf = STMB(typemulticlassifier='ovr',C1=1.0, C2=1.0, maxIter=30, tolSTM=1e-4, penalty = 'l2', dual = True, tol=1e-4,loss = 'squared_hinge', maxIterSVM=100000) | 5,349,946 |
def node_exporter_check():
"""
Checks existence & health of node exporter pods
"""
kube = kube_api()
namespaces = kube.list_namespace()
ns_names = []
for nspace in namespaces.items:
ns_names.append(nspace.metadata.name)
result = {'category': 'observability',
'case... | 5,349,947 |
def create(cmd, resource_group_name=None, workspace_name=None, location=None, storage_account=None, skip_role_assignment=False, provider_sku_list=None):
"""
Create a new Azure Quantum workspace.
"""
client = cf_workspaces(cmd.cli_ctx)
if not workspace_name:
raise RequiredArgumentMissingError... | 5,349,948 |
def functional_domain_min(braf_gene_descr_min,
location_descriptor_braf_domain):
"""Create functional domain test fixture."""
params = {
"status": "preserved",
"name": "Serine-threonine/tyrosine-protein kinase, catalytic domain",
"id": "interpro:IPR001245",
... | 5,349,949 |
def rsa_encrypt(rsa_key, data):
"""
rsa_key: 密钥
登录密码加密
"""
data = bytes(data, encoding="utf8")
encrypt = PKCS1_v1_5.new(RSA.importKey(rsa_key))
Sencrypt = b64encode(encrypt.encrypt(data))
return Sencrypt.decode("utf-8") | 5,349,950 |
def shuffle_and_split_data(data_frame):
"""
Shuffle and split the data into 2 sets: training and validation.
Args:
data_frame (pandas.DataFrame): the data to shuffle and split
Returns:
2 numpy.ndarray objects -> (train_indices, validation_indices)
Each hold the inde... | 5,349,951 |
def test_disable_agent_zero_slots() -> None:
"""
Start a command, disable the agent it's running on. The command should
then be terminated promptly.
"""
slots = _fetch_slots()
assert len(slots) == 1
agent_id = slots[0]["agent_id"]
command_id = run_zero_slot_command(sleep=60)
# Wait ... | 5,349,952 |
def parse_array_from_string(list_str, dtype=int):
""" Create a 1D array from text in string.
Args:
list_str: input string holding the array elements.
Array elements should be contained in brackets [] and seperated
by comma.
dtype: data type of the array elements. Default ... | 5,349,953 |
def download_api_coinslists_handler(bot, job):
"""
the function to download API from the agregators sites to local file
:param bot: a telegram bot main object
:type bot: Bot
:param job: job.context is a name of the site-agregator, which has been send from job_queue.run_repeating... method
... | 5,349,954 |
def Maj(x, y, z):
""" Majority function: False when majority are False
Maj(x, y, z) = (x ∧ y) ⊕ (x ∧ z) ⊕ (y ∧ z)
"""
return (x & y) ^ (x & z) ^ (y & z) | 5,349,955 |
def get_package_data():
"""Load services and conn_states data into memory"""
with open(DATA_PKL_FILE, "rb") as f:
services, conn_states = pickle.load(f)
return services, conn_states | 5,349,956 |
def is_module(module):
"""Check if a given string is an existing module contained in the
``MODULES_FOLDER`` constant."""
if (os.path.isdir(os.path.join(MODULES_FOLDER, module)) and
not module.startswith('_')):
return True
return False | 5,349,957 |
def _finalize_sv(solution_file, data):
"""Add output files from TitanCNA calling optional solution.
"""
out = {"variantcaller": "titancna"}
with open(solution_file) as in_handle:
solution = dict(zip(in_handle.readline().strip("\r\n").split("\t"),
in_handle.readline().... | 5,349,958 |
def list_dumps(dump_list, **kwargs):
"""Function: list_dumps
Description: Lists the dumps under the current repository.
Arguments:
(input) dump_list -> List of database dumps
(input) kwargs:
raw -> True|False - Print raw data in JSON format
"""
dump_list = list(dum... | 5,349,959 |
def test_create_jobs_returns_the_job(client):
"""Return the created job"""
response = client.post(
'%s/jobs' % BASE_URL, data=json.dumps(DATA), headers=HEADERS)
answer = DATA.copy()
del answer['type']
assert response.get_json() == answer | 5,349,960 |
def test_parse_args_and_kwargs():
"""Parse args and kwargs."""
docstring = """
Arguments:
a (str): an argument.
*args (str): args arguments.
**kwargs (str): kwargs arguments.
"""
sections, warnings = parse(docstring)
assert len(sections) == 1
expected... | 5,349,961 |
def compare_collision_diagram(
path_data,
gt_data,
sim_data,
begin=0,
end=0,
time_step_sim=0.0005,
time_step_gt=0.01):
""" Plots collision/gait diagrams.
Parameters
----------
path_data: <str>
Path to simulation results.
sim_data: <str... | 5,349,962 |
def reload_county():
""" Return bird species, totals, location to map """
# receive data from drop-down menu ajax request
bird = request.args.get("bird")
county = request.args.get("county")
# get the zoom level of the new chosen county
zoomLevel = get_zoom(county)
# reset session data fr... | 5,349,963 |
def test_train_pass_3(example_timeseries, example_results, modify_config):
""" Correctly run training script with plots
"""
mod_cfg = {'dataset': {'output': example_results['results_dir']}}
with modify_config(example_timeseries['config'], mod_cfg) as cfg:
runner = CliRunner()
result = ru... | 5,349,964 |
def get_conv2d_out_channels(kernel_shape, kernel_layout):
"""Get conv2d output channels"""
kernel_shape = get_const_tuple(kernel_shape)
if len(kernel_shape) == 4:
idx = kernel_layout.find("O")
assert idx >= 0, "Invalid conv2d kernel layout {}".format(kernel_layout)
return kernel_shap... | 5,349,965 |
def bindparam(key, value=None, type_=None, unique=False, required=False, callable_=None):
"""Create a bind parameter clause with the given key.
:param key:
the key for this bind param. Will be used in the generated
SQL statement for dialects that use named parameters. This
v... | 5,349,966 |
def set_membership_to_true(apps, schema_editor):
"""Set membership_is_managed to true"""
Channel = apps.get_model("channels", "Channel")
# At the point the migration runs
Channel.objects.all().update(membership_is_managed=True) | 5,349,967 |
def create_dictionary(timestamp, original_sentence, sequence_switched, err_message, suggestion_list):
"""Create Dictionary Function
Generates and exports a dictionary object with relevant data for website interaction to take place.
"""
if len(suggestion_list) != 0:
err_message_str = "Possible e... | 5,349,968 |
def test_cannot_execute_shell():
"""The credential should raise CredentialUnavailableError when the subprocess doesn't start"""
with patch(POPEN, Mock(side_effect=OSError)):
with pytest.raises(CredentialUnavailableError):
AzurePowerShellCredential().get_token("scope") | 5,349,969 |
def benefits(path):
"""Unemployment of Blue Collar Workers
a cross-section from 1972
*number of observations* : 4877
*observation* : individuals
*country* : United States
A time serie containing :
stateur
state unemployment rate (in %)
statemb
state maximum benefit level
state
... | 5,349,970 |
def get_L_BB_b2_d_t(L_BB_b2_d, L_dashdash_b2_d_t):
"""
Args:
L_BB_b2_d: param L_dashdash_b2_d_t:
L_dashdash_b2_d_t:
Returns:
"""
L_BB_b2_d_t = np.zeros(24 * 365)
L_BB_b2_d = np.repeat(L_BB_b2_d, 24)
L_dashdash_b2_d = np.repeat(get_L_dashdash_b2_d(L_dashdash_b2_d_t), 24)
... | 5,349,971 |
def _get_tab_counts(business_id_filter, conversation_tab, ru_ref_filter, survey_id):
"""gets the thread count for either the current conversation tab, or, if the ru_ref_filter is active it returns
the current conversation tab and all other tabs. i.e the value for the 'current' tab is always populated.
Calls... | 5,349,972 |
def IsInverseTime(*args):
"""Time delay is inversely adjsuted, proportinal to the amount of voltage outside the regulating band."""
# Getter
if len(args) == 0:
return lib.RegControls_Get_IsInverseTime() != 0
# Setter
Value, = args
lib.RegControls_Set_IsInverseTime(Value) | 5,349,973 |
def create_userinfo(fname, lname, keypass):
"""
function to create new user
"""
new_userinfo = Userinfo(fname, lname, keypass)
return new_userinfo | 5,349,974 |
def get_networks() -> Dict[str, SpikingNetwork]:
"""Get a set of spiking networks to train."""
somatic_spike_fn = get_spike_fn(threshold=15)
dendritic_nl_fn = get_default_dendritic_fn(
threshold=2, sensitivity=10, gain=1
)
neuron_params = RecurrentNeuronParameters(
tau_mem=10e-3,
... | 5,349,975 |
def _load_jupyter_server_extension(server_app):
"""Registers the API handler to receive HTTP requests from the frontend extension.
Parameters
----------
lab_app: jupyterlab.labapp.LabApp
JupyterLab application instance
"""
... | 5,349,976 |
def test_custom_entity_marshaler():
"""Test that json marshaler use custom marshaler to marshal an entity.
1. Create a sub-class of JSONMarshaler with redefined create_entity_marshaler factory.
2. Create json marshaler from the sub-class.
3. Marshal an entity.
4. Check that custom marshaler is used... | 5,349,977 |
def plot_gain_offsets(dio_cross,dio_chan_per_coarse=8,feedtype='l',ax1=None,ax2=None,legend=True,**kwargs):
"""
Plots the calculated gain offsets of each coarse channel along with
the time averaged power spectra of the X and Y feeds
"""
#Get ON-OFF ND spectra
Idiff,Qdiff,Udiff,Vdiff,freqs = get_... | 5,349,978 |
def process_files(pair_path):
"""
Process all protein (pdb) and ligand (sdf) files in input directory.
Args
pair_path dir (str): directory containing PDBBind data
Returns
structure_dict (dict): dictionary containing each structure, keyed by PDB code. Each PDB is a dict containing protein... | 5,349,979 |
def metric_group_max(df, metric_names=None):
"""Find the step which achieves the highest mean value for a group of metrics."""
# Use METRIC_NAMES defined at the top as default
metric_names = metric_names or METRIC_NAMES
group_to_metrics = collections.defaultdict(set)
for metric in metric_names.values():
g... | 5,349,980 |
def save_output(issues, filename):
"""Save output to file."""
with open(filename, 'a') as output:
for issue in issues:
output.write(issue) | 5,349,981 |
def get_settings_value(definitions: Definitions, setting_name: str):
"""Get a Mathics Settings` value with name "setting_name" from definitions. If setting_name is not defined return None"""
settings_value = definitions.get_ownvalue(setting_name)
if settings_value is None:
return None
return set... | 5,349,982 |
def show_clusterhost(clusterhost_id):
"""Get clusterhost."""
data = _get_request_args()
return utils.make_json_response(
200,
_reformat_host(cluster_api.get_clusterhost(
clusterhost_id, user=current_user, **data
))
) | 5,349,983 |
def resize3d_cubic(data_in, scale, coordinate_transformation_mode):
"""Tricubic 3d scaling using python"""
dtype = data_in.dtype
d, h, w = data_in.shape
new_d, new_h, new_w = [int(round(i * s)) for i, s in zip(data_in.shape, scale)]
data_out = np.ones((new_d, new_h, new_w))
def _cubic_spline_we... | 5,349,984 |
def seasurface_skintemp_correct(*args):
"""
Description:
Wrapper function which by OOI default applies both of the METBK seasurface
skin temperature correction algorithms (warmlayer, coolskin in coare35vn).
This behavior is set by the global switches JWARMFL=1 and JCOOLFL=1. The
... | 5,349,985 |
def run_experiment_here(
experiment_function,
variant=None,
exp_id=0,
seed=0,
use_gpu=True,
gpu_id=0,
# Logger params:
exp_name="default",
snapshot_mode='last',
snapshot_gap=1,
git_infos=None,
script_name=None,
trial... | 5,349,986 |
def extract_character_pairs(letter_case, reverse_letter_case):
"""
Extract character pairs. Check that two unicode value are also a mapping value of each other.
:param letter_case: case mappings dictionary which contains the conversions.
:param reverse_letter_case: Comparable case mapping table which c... | 5,349,987 |
def test_to_graph_should_return_link_to_spatial_coverage_with_location_triple() -> None:
"""It returns a spatial coverage graph isomorphic to spec."""
dataset = Dataset()
dataset.identifier = "http://example.com/datasets/1"
# Create location:
location = Location()
location.identifier = "http://e... | 5,349,988 |
def after_timestep(simulation, is_steady, force_steady=False):
"""
Move u -> up, up -> upp and prepare for the next time step
"""
# Stopping criteria for steady state simulations
vel_diff = None
if is_steady:
vel_diff = 0
for d in range(simulation.ndim):
u_new = simul... | 5,349,989 |
def get_summary_indices(df, on='NOSC'):
""" Get the summary stats for the indices: median, mean, std, weighted mean and weighted std """
samples = get_list_samples(df)
samples.append(on)
t = df[samples]
t = t.melt(id_vars=[on], var_name='SampleID', value_name='NormIntensity')
t = t[t['NormI... | 5,349,990 |
def view_evidence(evidence_id: int):
"""View a single Evidence model."""
evidence = manager.get_evidence_by_id_or_404(evidence_id)
return render_template(
'evidence/evidence.html',
evidence=evidence,
manager=manager,
) | 5,349,991 |
def get_filenames(split, mode, data_dir):
"""Returns a list of filenames."""
if not split:
data_dir = os.path.join(data_dir, 'cifar-10-batches-bin')
assert os.path.exists(data_dir), (
'Run cifar10_download_and_extract.py first to download and extract the '
'CIFAR-10 data.')
if split:
if mo... | 5,349,992 |
def rigidBlades(blds, hub=None, r_O=[0,0,0]):
""" return a rigid body for the three blades
All bodies should be in a similar frame
"""
blades = blds[0].toRigidBody()
for B in blds[1:]:
B_rigid = B.toRigidBody()
blades = blades.combine(B_rigid, r_O=r_O)
blades.name='blades'
re... | 5,349,993 |
def mea_slow(posterior_matrix, shortest_ref_per_event, return_all=False):
"""Computes the maximum expected accuracy alignment along a reference with given events and probabilities.
Computes a very slow but thorough search through the matrix
:param posterior_matrix: matrix of posterior probabilities with r... | 5,349,994 |
def predict(cart_tree, feature_set, data_set):
"""Predict the quality."""
feature_dict = {}
for index, feature in enumerate(feature_set):
feature_dict[feature] = index
results = []
for element in data_set:
# Append a tuple.
results.append((trace(cart_tree, feature_dict, eleme... | 5,349,995 |
def _generate_residue_name(residue, smiles):
"""Generates residue name for a particular residue which
corresponds to a particular smiles pattern.
Where possible (i.e for amino acids and ions) a standard residue
name will be returned, otherwise a random name will be used.
Parameters
----------
... | 5,349,996 |
def test_incorporate_getitem_through_switch(tag):
""" test_incorporate_getitem_through_switch """
fns = FnDict()
scalar_gt = Primitive('scalar_gt')
@fns
def before(x, y):
def f1(x, y):
return x, y
def f2(x, y):
return y, x
return tuple_getitem(
... | 5,349,997 |
def response_json(status, message, response):
"""
Helper method that converts the given data in json format
:param success: status of the APIs either true or false
:param data: data returned by the APIs
:param message: user-friendly message
:return: json response
"""
data = {
"status": status,
"message": me... | 5,349,998 |
def settings(request):
"""
"""
from . import conf
conf = dict(vars(conf))
# conf.update(ThemeSite.objects.get_theme_conf(request=request, fail=False))
data = request.session.get('cms_bs3_theme_conf', {})
conf.update(data)
return {'bs3_conf': conf} | 5,349,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.