content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_template_module(template_name_or_list, **context):
"""Return the python module of a template.
This allows you to call e.g. macros inside it from Python code."""
current_app.update_template_context(context)
tpl = current_app.jinja_env.get_or_select_template(template_name_or_list)
return tpl.... | 5,299,400 |
def test_tx_from_json():
"""test serialization and deserialization"""
sender = "abcd"
receivers = ["fe"]
amounts = [1]
fee = 100
t1 = Transaction(sender, receivers, amounts, fee)
t2 = transaction.from_json(t1.string())
assert t1.string() == t2.string()
assert t1.hash() == t2.hash()
... | 5,299,401 |
def get_user_agents(config):
"""Loads user-agent from data file to local memory"""
user_agent_file = config["USER_AGET_DATA_FILE"]
user_agents = config["USER_AGET_DATA"] if "USER_AGET_DATA" in config else None
if not user_agents:
logger.info("Processing user agent data from file %s", user_agent... | 5,299,402 |
def writeArk(filename, features, uttids, append=False):
"""
Takes a list of feature matrices and a list of utterance IDs,
and writes them to a Kaldi ark file.
Returns a list of strings in the format "filename:offset",
which can be used to write a Kaldi script file.
"""
pointers = []
... | 5,299,403 |
def callback_laser(msg):
"""Called when a message of the topic 'scan' is received."""
global _pub
ranges = msg.ranges
if len(msg.intensities) > 0:
ranges = [r for i, r in enumerate(msg.ranges) if msg.intensities[i] > 0]
dmin = min(ranges)
rospy.logdebug("received laser scan, dmin: %f", d... | 5,299,404 |
def graph_to_string(graph: nx.MultiDiGraph, starting_node, level=0):
"""
String representation of `graph` for debugging purposes.
A class name is wrapped in brackets []. A function name is wrapped in parens ().
For example, a graph 'g' representing Python module 'main.py' that defines
function func... | 5,299,405 |
def current_datetime_str(fmt="%Y%m%d_%H%M%S", ms=False, ms_prefix="_"):
"""Get the current datetime with second precision with default format ``YYYYMMDD_HHMMSS``"""
dt = datetime.datetime.now()
dt_str = dt.strftime(fmt)
if ms:
dt_str = dt_str + ms_prefix + str(datetime_ms(dt))
return dt_str | 5,299,406 |
def getRetiredPages(device, retiredType):
""" Return the retired pages for the specified type
Parameters:
device -- DRM device identifier
retiredType - Type of retired page to return (retired, pending, unreservable, all)
"""
returnPages = ''
pages = getSysfsValue(device, 'bad_pages')
if... | 5,299,407 |
def get_opening_sentences(season, day = None):
"""given a season (text), returns a dictionary with 'text' and 'verse"""
#TODO: special case for Ascension day: it should be using Easter opening sentences
if season in opening_sentences:
season_list = opening_sentences[season]
else:
# Error... | 5,299,408 |
def test_load_v3():
"""
Tests a pipeline that was produced with module revision 3.
The channel names are named according to the schema:
Channel(#new_imagenumber)_(#channel_number),
e.g. Channel3_2 would be the image number 3 that contains channel
number 2.
Thus it can be easily checked via t... | 5,299,409 |
def load_model_checkpoint(
load_checkpoint_dir: pathlib.Path,
model: torch.nn.Module,
optimizer: torch.optim.Optimizer,
) -> Tuple[int, torch.nn.Module, torch.optim.Optimizer]:
"""Loads the optimizer state dict and model state dict from the load_checkpoint_dir
into the passed model and optimizer. Se... | 5,299,410 |
def _genre(elem):
"""
Yield a C{list} of C{unicode} genre names.
"""
yield u'genres', [e.text
for e in elem.findall('a')
if e.get('class') is None] | 5,299,411 |
def get_rand_patches_rand_cond(img, mask, n_patches=16000, sz=160, nclasses=6,
nodata_ascloud=True, method='rand'
) -> np.array:
"""
Generate training data.
:param images: ndarray in the format (w,h,c).
:param mask: integer ndarray with shape... | 5,299,412 |
def decode_example(example):
"""Decode a serialized example."""
example = tf.io.parse_single_example(
example,
{
"image": tf.io.FixedLenFeature([], tf.string),
"mask": tf.io.FixedLenFeature([], tf.string),
},
)
image = tf.image.decode_png(example["image"])... | 5,299,413 |
def main():
"""
Main entry point for module execution
:returns: the result form module invocation
"""
module = AnsibleModule(
argument_spec=Lldp_interfacesArgs.argument_spec,
supports_check_mode=True,
)
result = Lldp_interfaces(module).execute_module()
module.exit_json(... | 5,299,414 |
def apply_dynamic_cleaning(image, signal_pixels, threshold, fraction):
"""
Application of the dynamic cleaning
Parameters
----------
image: `np.ndarray`
Pixel charges
signal_pixels
threshold: `float`
Minimum average charge in the 3 brightest pixels to apply
the dyn... | 5,299,415 |
def select(con, id):
""" 指定したキーのデータをSELECTする """
cur = con.execute(
'select id, title_en, title_ja, description_en, description_ja, author, created from suggestions where id=?',
(id,))
return cur.fetchone() | 5,299,416 |
def save_params(net, best_metric, current_metric, epoch, save_interval, prefix):
"""Logic for if/when to save/checkpoint model parameters"""
if current_metric < best_metric:
best_metric = current_metric
net.save_parameters('{:s}_best.params'.format(prefix, epoch, current_metric))
with op... | 5,299,417 |
def test_cray_hsm_service_values_class_list(cli_runner, rest_mock):
""" Test `cray hsm service values class list` with valid params """
runner, cli, config = cli_runner
url_template = '/apis/smd/hsm/v1/service/values/class'
result = runner.invoke(cli, ['hsm', 'service', 'values', 'class', 'list'])
... | 5,299,418 |
def resize(data, number_rows=None, number_columns=None, lower=None, upper=None, categories=None, weights=None, distribution=None, shift=None, scale=None, sample_proportion=None, minimum_rows=None, **kwargs):
"""
Resize Component
Resizes the data in question to be consistent with a provided sample size,... | 5,299,419 |
def svn_uri_dirname(*args):
"""svn_uri_dirname(char const * uri, apr_pool_t result_pool) -> char *"""
return _core.svn_uri_dirname(*args) | 5,299,420 |
def create_test_dl(df:pd.DataFrame, b:Optional[np.array]=None,
t_scaler:MaxAbsScaler=None, x_scaler:StandardScaler=None,
bs:int=128, only_x:bool=False) -> DataLoader:
"""
Take dataframe and return a pytorch dataloader.
parameters:
- df: pandas dataframe
- b: bre... | 5,299,421 |
def initialize_bot_settings(settings: Config) -> Config:
"""
Initialises the settings that are used within the bot to manage the contextual reminders
"""
settings.define_section("ctxreminders", ContextualRemindersSection)
settings.ctxreminders.configure_setting(
"persistence_dir",
... | 5,299,422 |
def update_votes_cubam(show_progress=False):
""" This function is automatically called by
mturk.tasks.mturk_update_votes_cubam_task """
from mturk.models import Experiment
from mturk.cubam import update_votes_cubam
# responses that we will consider
opacity_responses = IntrinsicPointOpacityResp... | 5,299,423 |
def from_pretrained(chkpt, model_dir=None, force_reload=False, **kwargs):
"""
Kwargs:
bucket(str): S3 bucket name
key(str): path in an S3 bucket
"""
stem, suffix = chkpt.split('.')
tag = kwargs.get('tag', 'v6.0')
s3 = kwargs.get('s3', None)
if s3 and s3.get('bucket', None) a... | 5,299,424 |
def generate_multilabel_ensemble_classification_outputs(classifiers, n_classes, n_samples, continuous_out=False,
parallelize=True):
"""
Generate random multilabel crisp classification outputs (assignments) for the given ensemble of classifiers with
th... | 5,299,425 |
def hermite_H_sequence(ns, x):
"""Physicist's Hermite polynomials H of orders ns at points x.
Parameters
----------
ns : iterable of int
rising polynomial orders, assumed to be sorted
x : numpy.ndarray
point(s) to evaluate at. Scalars and arrays both work.
Returns
-------
... | 5,299,426 |
def test_Stopwatch_timezone_change(alt_tz):
"""
The stopwatch should provide a consistent duration even
if the timezone changes.
"""
watch = timing.Stopwatch()
with alt_tz:
assert abs(watch.split().total_seconds()) < 0.1 | 5,299,427 |
def test_prepare_for_inference(monkeypatch):
"""
There are only 2 records in the input.manifest and they both are sent to batch transform.
"""
def mock_copy(*args, **kwargs):
source = args[0]
dest = args[1]
query = args[2]
transform = args[3]
mock_input = StringI... | 5,299,428 |
def nvisitsM5Maps(colmap=None, runName='opsim',
extraSql=None, extraMetadata=None,
nside=64, runLength=10.,
ditherStacker=None, ditherkwargs=None):
"""Generate number of visits and Coadded depth per RA/Dec point in all and per filters.
Parameters
------... | 5,299,429 |
def load_map(indexing_dir):
"""获得1.栏目id到内容视频的idx序列, 2.视频id到idx 的映射"""
res = []
file_list = ["cid2vidx.json", "vid2idx.json"]
for file in file_list:
file_path = os.path.join(indexing_dir, file)
with open(file_path, "r", encoding="utf8") as fp:
res.append(json.load(fp))
re... | 5,299,430 |
def test_53_http_transport():
"""
VEN/VTN
Shall implement the simple http transport. Including support for the
following mandatory http headers:
Host
Content-Length
Content-Type of application/xml
"""
assert False | 5,299,431 |
def create_3d_trap(radius, height, delta):
"""Creates a 3D surface plot showing the trap and the beach.
Args:
radius: the radius of the trap
height: the height of the trap
delta: how far along the beach the center of radius r circle the semicircular trap could be in
returns:
... | 5,299,432 |
def start_cli():
"""
Start the command line interface
"""
data = {}
settings = init_settings()
while True:
print("Have you already created key and data files? (Y/n)")
response = input("> ").lower()
if response.startswith("y") or response == "":
key = load_key... | 5,299,433 |
async def test_error_iter_ele(func: BufferAsyncCalls[int],
buffered: Set[int]) -> None:
"""Same as test_error_iter but with one element yielded."""
def error_gen() -> Yields[int]:
yield 1
raise ValueError
func.map(error_gen())
await aio.wait_for(func.wait(... | 5,299,434 |
def get_logger(name, log_file=None, log_level=logging.INFO):
"""Initialize and get a logger by name.
If the logger has not been initialized, this method will initialize the
logger by adding one or two handlers, otherwise the initialized logger will
be directly returned. During initialization, a StreamHa... | 5,299,435 |
def magmablas_dsymmetrize(uplo, n, A, lda):
"""
Symmetrize a triangular matrix.
"""
uplo = _uplo_conversion[uplo]
status = _libmagma.magmablas_dsymmetrize(uplo, n, int(A), lda)
magmaCheckStatus(status) | 5,299,436 |
def test_known_camera_names(camera_geometry):
""" Check that we can get a list of known camera names """
assert camera_geometry.camera_name in CameraDescription.get_known_camera_names() | 5,299,437 |
def convert_pyte_buffer_to_colormap(buffer, lines):
"""
Convert a pyte buffer to a simple colors
"""
color_map = {}
for line_index in lines:
# There may be lines outside the buffer after terminal was resized.
# These are considered blank.
if line_index > len(buffer) - 1:
... | 5,299,438 |
def find_offsets_local_direction(
centered_patches: tf.Tensor, delta: float
) -> tf.Tensor:
"""Computes subpixel offsets from the direction of the pixels around the peak.
This function finds the delta-offset from the center pixel of peak-centered patches
by finding the direction of the gradient around ... | 5,299,439 |
def to_device(data, device):
"""Move tensor (s) to chosen device"""
if isinstance(data, (list, tuple)):
return [to_device(x, device) for x in data]
return data.to(device, non_blocking=True) | 5,299,440 |
def evaluate_prediction(numbers, test_suite_path):
"""Run NIST tests to determine randomness of predicted numbers."""
results = [test_number(number, test_suite_path) for number in numbers]
success_measure = np.mean(results)
print(f'Evaluation: {success_measure * 100}%')
plt.plot(results)
plt.... | 5,299,441 |
def predict():
"""
预测过程
"""
with tf.Session() as sess:
encoder_inputs, decoder_inputs, target_weights, outputs, loss, update, saver, learning_rate_decay_op, learning_rate = get_model(
feed_previous=True)
saver.restore(sess, model_name)
sys.stdout.write("> ")
s... | 5,299,442 |
def push_branch_set_upstream(git_dir, branch_name):
""" Push new branch to remote.
"""
try:
# this will ask username/password
git('-C', git_dir, 'push', '--set-upstream', 'origin', branch_name)
except ErrorReturnCode as e:
return failed_util_call_results(e)
else:
retu... | 5,299,443 |
def delete_step_from_derivation(
deriv_id: str, step_to_delete: str, path_to_db: str
) -> None:
"""
Args:
deriv_id: numeric identifier of the derivation
step_to_delete:
path_to_db: filename of the SQL database containing
a JSON entry that returns a nested diction... | 5,299,444 |
def interpolate_g(xi,yi,zi,xx,yy,knots=10, error=False,mask=None):
"""Create a grid of zi values interpolating the values from xi,yi,zi
xi,yi,zi 1D Lists or arrays containing the values to use as base for the interpolation
xx,yy 1D vectors or lists containing the output coordinates
samples t... | 5,299,445 |
def knownTypes():
"""
Returns known types.
@ In, None
@ Out, __knownTypes, list, list of known types
"""
return __knownTypes | 5,299,446 |
def test_find_by_id_client(session):
"""Assert that find party by party ID for a client party contains all expected elements."""
party = Party.find_by_id(200000004)
assert party
assert party.party_type_cd == 'SP'
assert party.party_id == 200000004
assert party.registration_id
assert not part... | 5,299,447 |
def histogram_reads(bam_file, windowsize, chromosomes='all', exclude_chroms=['chrM', 'chrY', 'chrX'],
skip_qc_fail=True):
"""Histogram the counts along bam_file, resulting in a vector.
This will concatenate all chromosomes, together, so to get the
counts for a particular chromosome, pas... | 5,299,448 |
def test_merge_1():
"""
>>> a1 = [{u'items': [{u'name': u'A1', u'id': u'ID1'}, {u'name': u'A2', u'id': u'ID2'},
... {u'name': u'A4', u'id': u'ID4'}, {u'name': u'A8', u'id': u'ID8'}],
... u'name': u'Status'}]
>>> a2 = [{u'items': [{u'name': u'A5', u'id': u'ID1'},
... ... | 5,299,449 |
def pytask_parse_config(config):
"""Add the marker to the configuration."""
config["markers"]["persist"] = (
"Prevent execution of a task if all products exist and even if something has "
"changed (dependencies, source file, products). This decorator might be useful "
"for expensive task... | 5,299,450 |
def cron_monitor(ctx, max_age, bde):
"""
[Internal] Cron: Check and progress current imports
\b
Configure via:
*/15 * * * * /path/to/lds-bde-loader/bin/lds-bde-loader cron-monitor --max-age=7
"""
L.info("cron-monitor max-age=%s", max_age)
upload = bde.get_latest_upload()
if not... | 5,299,451 |
def test_HashCache_GetHash_non_existent_path(database_path, hash_fn):
"""Test that a non-existent path raises an error."""
c = hashcache.HashCache(database_path, hash_fn)
with tempfile.TemporaryDirectory() as d:
with test.Raises(FileNotFoundError) as e_info:
c.GetHash(pathlib.Path(d) / "a")
assert f... | 5,299,452 |
def single_load(input_, ac_parser=None, ac_template=False,
ac_context=None, **options):
"""
Load single configuration file.
.. note::
:func:`load` is a preferable alternative and this API should be used
only if there is a need to emphasize given input `input_` is single one.
... | 5,299,453 |
def read_abbrevs(abbrevs: IO[str]) -> List[Abbrev]:
"""Parse the XML from `abbrevs` into a list of `Abbrev` objects."""
root = ET.parse(abbrevs).getroot()
r = [] # type: List[Abbrev]
for node in root.findall('source'):
spellouts = [
normalize.fix_entities(x.text or '')
f... | 5,299,454 |
def test_index_route(test_client):
"""
TEST the main route
"""
res = test_client.get("/index", follow_redirects=False)
assert res.status_code == 200 | 5,299,455 |
def deleteTemplate(**kargs):
""" Delete Template (OS Image) of Your VM
* Args:
- zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2]
- id(String, Required) : Template ID
* Examples : print(server.deleteSnapshot(zone='KR-M', id='6a59215f-df8b-4633-9a55-c42ac41b3467'))
"""
... | 5,299,456 |
def create_session(checkpoint_path, target_device):
"""Create ONNX runtime session"""
if target_device == 'GPU':
providers = ['CUDAExecutionProvider']
elif target_device == 'CPU':
providers = ['CPUExecutionProvider']
else:
raise ValueError(
f'Unsupported target device... | 5,299,457 |
def test_load_function():
"""Test loading of the function"""
mixin = EmbedMixin("test", "test")
assert mixin.load_function("test", "test") == check | 5,299,458 |
def support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float:
"""
Third method: Support vector regressor
svr is quite the same with svm(support vector machine)
it uses the same principles as the SVM for classification,
with only a few minor differences and the only diffe... | 5,299,459 |
def _get_default_session():
"""
Get the default session, creating one if needed.
:rtype: :py:class:`~boto3.session.Session`
:return: The default session
"""
if DEFAULT_SESSION is None:
setup_default_session()
_warn_deprecated_python()
return DEFAULT_SESSION | 5,299,460 |
def read_meminfo():
"""
Mocks read_meminfo as this is a Linux-specific operation.
"""
return {
"MemTotal": random.randint(0, 999999999),
"MemFree": random.randint(0, 999999999),
"MemAvailable": random.randint(0, 999999999),
"HugePages_Total": random.randint(0, 999999999),... | 5,299,461 |
def irfft(x, axes):
"""
like np.fft.irfft
"""
return core.Result(core.IRFFT(axes),[x]) | 5,299,462 |
def hdf_sep2hdf_single_append(data_dir, filelist, export_dir,
out_name='database.h5'):
"""
Append to single large HDF5 file, all DF appended with single key.
"""
h5_file = pd.HDFStore(export_dir+out_name)#, complevel=5, complib='blosc')
counter = 1
for name in file... | 5,299,463 |
def set_tmin(ndvar, tmin=0.):
"""Change the time axis of an :class:`NDVar`
Parameters
----------
tmin : scalar
New ``tmin`` value (default 0).
Returns
-------
out_ndvar : NDVar
Shallow copy of ``ndvar`` with updated time axis.
"""
axis = ndvar.get_axis('time')
o... | 5,299,464 |
def place_by_name(place, key, FIND_PLACE=FIND_PLACE):
"""Finds a Google Place ID by searching with its name.
Args:
place (str): Name of the place. It can be a restaurant, bar, monument,
whatever you would normally search in Google Maps.
key (str): Key for the Google API.
FIN... | 5,299,465 |
def spearmanr(pred, target, eps=1e-6):
"""
Spearman correlation between target and prediction.
Implement in PyTorch, but non-diffierentiable. (validation metric only)
Parameters:
pred (Tensor): prediction of shape :math: `(N,)`
target (Tensor): target of shape :math: `(N,)`
"""
... | 5,299,466 |
def main():
""" Launcherfix and NVIDIA PhysX support.
"""
# Fixes the startup process.
util.replace_command('Launcher.exe', 'Borderlands2.exe')
util.append_argument('-NoSplash')
# Disables esync prevents crashes.
util.disable_esync()
# Enables NVIDIA PhysX in Borderlands 2.
util.p... | 5,299,467 |
def kappa_adj_err_fn(speed, a, b):
"""
:param a: the slope parameter of the adjustment function
:param b: the bias parameter of the adjustment function
"""
global good_a
global good_b
simulator = SingleCue(cue="wind")
rel_model = ReliabilityModel()
iterations = 100
r_averages =... | 5,299,468 |
def do_request(cur, method="GET"):
"""
GET API should provide a json with the following fields:
state: str - can be:
"idle" - before anything is done, or after camera is stopped (to be implemented with push button)
"ready" - camera is initialized
"capture" - camera is capturing
r... | 5,299,469 |
def reconnect_on_remote_close(f):
"""
lockdownd's _socket_select will close the connection after 60 seconds of "radio-silent" (no data has been
transmitted). When this happens, we'll attempt to reconnect.
"""
def _reconnect_on_remote_close(*args, **kwargs):
try:
return f(*args, ... | 5,299,470 |
def showstack(ui, repo, displayer):
"""current line of work"""
wdirctx = repo[b'.']
if wdirctx.rev() == nullrev:
raise error.Abort(
_(
b'stack view only available when there is a '
b'working directory'
)
)
if wdirctx.phase() == pha... | 5,299,471 |
def main():
"""
Instantiates the module and calls process_request.
:return: none
"""
module = AnsibleModule(
argument_spec=ApiGwBasePathMapping._define_module_argument_spec(),
supports_check_mode=True
)
base_path_mapping = ApiGwBasePathMapping(module)
base_path_mapping.p... | 5,299,472 |
def matchTimes(primary_dt,dt,tol_s=1,tol_us=4e5,fail_on_duplicates=True,allow_duplicates=False,warn_no_match=False):
"""
Finds a matching timestamp in primary_dt
within tolerance tol_us (given in microseconds)
for every value in dt.
Inputs:
-------
dt - numpy.array(dtype=object)
primary_dt - numpy.array(dtyp... | 5,299,473 |
def build_model():
"""
- Build model with GridSearch
Returns:
Trained model with GridSearch
"""
pipeline = Pipeline([
('features', FeatureUnion([
('text_pipeline', Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTran... | 5,299,474 |
def _get_field_default(field: attr.ib):
"""
Return a marshmallow default value given a dataclass default value
>>> @dataclass
... class A:
... x: int = attr.ib()
>>> _get_field_default(attr.fields(A).x)
<marshmallow.missing>
"""
if isinstance(field.default, attr.Factory):
... | 5,299,475 |
async def test_bad_core_config(hass):
"""Test a bad core config setup."""
files = {YAML_CONFIG_FILE: BAD_CORE_CONFIG}
with patch("os.path.isfile", return_value=True), patch_yaml_files(files):
res = await async_check_ha_config_file(hass)
log_ha_config(res)
assert isinstance(res.error... | 5,299,476 |
def str_to_vec(sequences):
"""converts nucleotide strings into vectors using a 2-bit encoding scheme."""
vecs = []
nuc2bit = {"A": (0, 0),
"C": (0, 1),
"T": (1, 0),
"G": (1, 1)}
for seq in sequences:
vec = []
for nuc in seq:
vec.ap... | 5,299,477 |
def windowbar_doorknob(alpha):
"""
This function draws the last lines for the program to fill the box
"""
#Windows
alpha.pencolor(184,134,11)
alpha.left(90)
alpha.setpos(35,25)
alpha.pensize(5)
alpha.pendown()
alpha.forward(22.5)
alpha.penup()
alpha.setpos(-35,25)
al... | 5,299,478 |
def vector_add(a, b):
"""Component-wise addition of two vectors.
>>> vector_add((0, 1), (8, 9))
(8, 10)
"""
return tuple(map(operator.add, a, b)) | 5,299,479 |
def gen_fill_suffix_row(row, name_to_suffix_dict,
street_name_col, street_suffix_col,
suggested_name_col=None, suggested_suffix_col=None):
""" Returns a callable that suggests suffix based on row information
Args:
row: a row in DataFrame
name_to_su... | 5,299,480 |
def _check_valid_time_values_length(time_timestamp: List[str]):
"""
Checks the length of passed params to adhere to standard.
For example hour has to be in HH format and will always be 2 characters.
:param time_timestamp: list of strings representing times going from hours -> minute -> second
... | 5,299,481 |
def classify_fragmentation_for_mitochondria(label_mask, skeletons):
"""
Performs mitochondria fragmentation based off the labels mask and skeletons mask
:param label_mask:
:param skeletons:
:return:
"""
# what if no mitochondria currently found?
# what if we want to compare the surface ... | 5,299,482 |
def test_api_challenge_delete_admin():
"""Can a user delete /api/v1/challenges/<challenge_id> if admin"""
app = create_ctfd()
with app.app_context():
gen_challenge(app.db)
with login_as_user(app, "admin") as client:
r = client.delete("/api/v1/challenges/1", json="")
a... | 5,299,483 |
def from_angle(theta: float) -> Vector2:
"""
Create a unit vector from an angle relative to the positive x-axis.
"""
return Vector2(cos(theta), sin(theta)) | 5,299,484 |
def test_fetching_url(aioclient_mock, hass, test_client):
"""Test that it fetches the given url."""
aioclient_mock.get('http://example.com', text='hello world')
def setup_platform():
"""Setup the platform."""
assert setup_component(hass, 'camera', {
'camera': {
'... | 5,299,485 |
def neg(left):
"""
Negative of a distribution.
Args:
dist (Dist) : distribution.
"""
if not isinstance(left, Dist):
return -left
return Neg(left) | 5,299,486 |
def initialize_from_tar(tar_path, is_full=False, clean_up=False):
"""Initialize from a remote TAR"""
# Step 1 is to unpack our TAR. Let's delete what was there first.
utils.delete_tree(dtfglobals.DTF_INCLUDED_DIR)
__unpack_included(tar_path)
# Next, we do the the auto config. If its not clean, sa... | 5,299,487 |
def get_aws_key_and_secret(aws_creds_file_path):
""" Given a filename containing AWS credentials (see README.md),
return a 2-tuple (access key, secret key).
"""
with open(aws_creds_file_path, 'r') as f:
creds_dict = json.load(f)
return creds_dict['accessKeyId'], creds_dict['secretAccessK... | 5,299,488 |
def check_existence(filename):
"""Check the existence of file or dir."""
if not os.path.exists(filename):
raise RuntimeError("%s not found. Are you under the TensorFlow source root"
" directory?") | 5,299,489 |
def config_file_init():
"""Read config file."""
try:
# print('Load ' + config_file)
cfg.read(config_file)
global _loaded
_loaded = True
except FileNotFoundError:
config_file_not_found_message() | 5,299,490 |
def group_service(app):
"""Group service."""
return current_groups_service | 5,299,491 |
def iterate(q, A_unrestrained, B, resp_a, resp_b, ihfree, symbols, toler, maxit, num_conformers):
"""Iterates the RESP fitting procedure
Parameters
----------
q : ndarray
array of initial charges
A_unrestrained : ndarray
array of unrestrained A matrix
B : ndarray
array o... | 5,299,492 |
def _AddTool(tool):
"""Adds a tool to the four dictionaries used to process settings.
This only defines the tool. Each setting also needs to be added.
Args:
tool: The _Tool object to be added.
"""
_msvs_validators[tool.msvs_name] = {}
_msbuild_validators[tool.msbuild_name] = {}
_msvs_to_m... | 5,299,493 |
def get_filename(part):
"""
Find the filename of a mail part. Many MUA send attachments with the
filename in the I{name} parameter of the I{Content-type} header instead
of in the I{filename} parameter of the I{Content-Disposition} header.
@type part: inherit from email.mime.base.MIMEBase
... | 5,299,494 |
def next_frame_stochastic_emily():
"""Emily's model."""
hparams = next_frame_stochastic()
hparams.latent_loss_multiplier = 1e-4
hparams.learning_rate_constant = 0.002
hparams.add_hparam("z_dim", 10)
hparams.add_hparam("g_dim", 128)
hparams.add_hparam("rnn_size", 256)
hparams.add_hparam("posterior_rnn_la... | 5,299,495 |
def test_get_vim_info(get_vim_info_keys):
"""Tests API call to get the information about individual vim"""
osm_admin = OSMClient.Admin(HOST_URL)
osm_auth = OSMClient.Auth(HOST_URL)
_token = json.loads(osm_auth.auth(username=USERNAME, password=PASSWORD))
_token = json.loads(_token["data"])
_v_li... | 5,299,496 |
def twix2DCMOrientation(mapVBVDHdr, force_svs=False, verbose=False):
""" Convert twix orientation information to DICOM equivalent.
Convert orientation to DICOM imageOrientationPatient, imagePositionPatient,
pixelSpacing and sliceThickness field values.
Args:
mapVBVDHdr (dict): Header info inte... | 5,299,497 |
def test_models_00(client):
"""
Test retrieving of available models with test credentials
"""
rest_value = client.get(
'/mug/api/3dcoord/resolutions?file_id=test',
headers=dict(Authorization='Authorization: Bearer teststring')
)
resolutions = json.loads(rest_value.data)
resol... | 5,299,498 |
def axial_mixture_unidir(x, config, is_training=True, causal=True):
"""Full attention matrix with axial pattern as local and mixture for global summary."""
del is_training
assert causal
bsize = x.shape[0]
query, key, value = attention.get_qkv(x, x, x, hidden_size=config.model_size,
... | 5,299,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.