content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def encode(data):
""" Encodes a string to the 'cstring' encoding supported by the replay DTD.
Args:
data: string value to be encoded
Returns:
String containing the encoded value
Raises:
None
"""
chars = string.letters + string.digits + " ?!:."
return ''.join([x if ... | 5,320,500 |
def gen_frame_symbol(
data: types.PulseInstruction, formatter: Dict[str, Any], device: device_info.DrawerBackendInfo
) -> List[drawings.TextData]:
"""Generate a frame change symbol with instruction meta data from provided frame instruction.
Stylesheets:
- The `frame_change` style is applied.
... | 5,320,501 |
def leanlauncher_download_version(version=LATEST_VERSION, path=DEFAULT_INSTALL_PATH):
"""
Installs the specified version of Minecraft to the specified path
Parameters:
version (str): the version of Minecraft to be installed, by default the latest
path (str): the path to install Minecraft to, by default ~... | 5,320,502 |
def Weierstrass_Enneper(f, g, z, imag_unit=1j):
"""
Compute the Weierstrass Enneper parametrization for given 'Weierstrass data'.
:param sympy expression f: h'/g, with h the height function
:param sympy expression g: Gauss map.
:param sympy variable z: Complex variable.
:param imag_unit: Represe... | 5,320,503 |
def build_lstm(seq_length):
"""Builds an LSTM in Keras."""
model = tf.keras.Sequential([
tf.keras.layers.Bidirectional(
tf.keras.layers.LSTM(22),
input_shape=(seq_length, 3)), # output_shape=(batch, 44)
tf.keras.layers.Dense(4, activation="sigmoid") # (batch, 4)
])
model_path =... | 5,320,504 |
def human_size(size_bytes):
"""
format a size in bytes into a 'human' file size, e.g. B, KB, MB, GB, TB, PB
Note that bytes will be reported in whole numbers but KB and above will have
greater precision. e.g. 43 B, 443 KB, 4.3 MB, 4.43 GB, etc
"""
suffixes_table = [('B', 0), ('KB', 1), ('MB', ... | 5,320,505 |
def plot_restraint_profile(system_id, ax, restraint_cutoff):
"""Plot the free energy as a function of the restraint cutoff."""
# Load the free energy profile for this system.
restraint_profile_file_path = os.path.join(RESTRAINT_DATA_DIR_PATH,
system_id.replace(... | 5,320,506 |
def list_resource_definitions(MaxResults=None, NextToken=None):
"""
Retrieves a list of resource definitions.
See also: AWS API Documentation
:example: response = client.list_resource_definitions(
MaxResults='string',
NextToken='string'
)
:type MaxResults: str... | 5,320,507 |
def configure(self):
"""Check that booc is available """
self.check_booc() | 5,320,508 |
def RigidSupport(NodeID: int):
"""
Function that fixes the x, y movements and the rotation of one node.
@param NodeID (int): ID of the node to be fixed
@exception NegativeValue: The ID of NodeID needs to be a positive integer.
"""
if NodeID < 1: raise NegativeValue()
fix(NodeID, 1, 1, 1) | 5,320,509 |
def html_color_to_rgba(html_colour, alpha):
"""
:param html_colour: Colour string like FF0088
:param alpha: Alpha value (opacity)
:return: RGBA semitransparent version of colour for use in css
"""
html_colour = html_colour.upper()
if html_colour[0] == '#':
html_colour = html_colour[1... | 5,320,510 |
def select_speedup(speedup):
"""speedup is used by the mock api"""
global _speedup
_speedup = speedup | 5,320,511 |
def _assign_category_colors(uses, cmap, use_colors=None, assigned_colors=None):
"""Set a dictionary of nice colors for the use blocks.
Options allow specifing pre-defined elements for some categories."""
use_colors = OrderedDict() if use_colors is None else use_colors
assigned_colors = (
Ordere... | 5,320,512 |
def GetClientContext(client_id, token):
"""Get context for the given client id.
Get platform, os release, and arch contexts for the client.
Args:
client_id: The client_id of the host to use.
token: Token to use for access.
Returns:
array of client_context strings
"""
client_context = []
clie... | 5,320,513 |
def calculate_slope_intercept(line):
"""
Calculating slope nd intercept for a line
"""
for x1, y1, x2, y2 in line:
if x2-x1 == 0:
return math.inf, 0
slope = (y2-y1)/(x2-x1)
intercept = y1 - slope * x1
return slope, intercept | 5,320,514 |
def get_welcome_response():
""" If we wanted to initialize the session to have some attributes we could
add those here
"""
session_attributes = {}
card_title = "Welcome"
speech_output = "I'm the Magic Conch Shell. Ask me a question"
# If the user either does not reply to the welcome messag... | 5,320,515 |
def rmcgs(A: np.ndarray, m: Optional[int] = None, r: Optional[int] = None) -> np.ndarray:
"""
Compute the product: B <- G * S * A where G has size m * r and elements from the standard
normal distribution, rescaled by 1/sqrt(m), and S is a CountSketch of size r * n. The matrix
G is not explicitly formed,... | 5,320,516 |
def test_many_columns_non_unischema_dataset(carbon_many_columns_non_unischema_dataset, reader_factory):
"""Check if we can read a dataset with huge number of columns (1000 in this case)"""
with reader_factory(carbon_many_columns_non_unischema_dataset.url) as reader:
sample = next(reader)
assert set(sample._... | 5,320,517 |
def get_messages():
""" Gets messages """
for msg in db.messages:
can_messages.append(msg) | 5,320,518 |
def start_multi_svf():
"""
This is function for satrt multi SVF GUI
:return: result, details
"""
app.logger.info("Try to start multi SVF GUI for test")
cli_rest_port_list = []
svf_num = int(request.form.get("svf_num"))
try:
cli_rest_port_list = StartMultiSvf(svf_num=svf_num, log... | 5,320,519 |
def get_files_by_pattern(root, pattern='a/b/*.ext', strip_root=False):
"""Optionally to only return matched sub paths."""
# Get the abspath of each directory images.
ret = glob.glob(osp.join(root, pattern))
# exclude the root str, so the ret is spec['patterns']. such as ['images/train/*.jpg]
if stri... | 5,320,520 |
def test_value_check_search_pattern():
"""Test value checks with the search_pattern() function."""
field_names = ('foo', 'bar')
validator = CSVValidator(field_names)
validator.add_value_check('bar', search_pattern('\d{4}-\d{2}-\d{2}'))
data = (
('foo', 'bar'),
('1', '1999-0... | 5,320,521 |
def gumbel_softmax(logits, temperature=1, hard=False):
"""
ST-gumple-softmax
input: [*, n_class]
return: flatten --> [*, n_class] an one-hot vector
"""
y = gumbel_softmax_sample(logits, temperature)
if not hard:
return y
shape = y.size()
_, ind = y.max(dim=-1)
y_hard = ... | 5,320,522 |
def _load_augmentation_aug_all():
""" Load image augmentation model """
def sometimes(aug):
return iaa.Sometimes(0.5, aug)
return iaa.Sequential(
[
# apply the following augmenters to most images
iaa.Fliplr(0.5), # horizontally flip 50% of all images
ia... | 5,320,523 |
def zk_get_mq_servers(zookeeper_servers, logger = logging.getLogger(__name__)):
"""
Get list of mq servers from zookeeper
:param zookeeper_servers: list of zookeeper servers
:param logger: logger to use
:return: list of mq servers or None
"""
mq_servers = None
# connect to zookeeper
... | 5,320,524 |
def create_list_of_file_lists(possible_storage_locations, dir_path_to_files, dir_name_appendix):
"""This function creates a list of the files within each of the file storage locations so the user can inspect them to look for comparison options."""
# Output list of files
files_to_compare = []
for locat... | 5,320,525 |
def _make_todays_date() -> str:
""" build today's date as a standard format """
return datetime.now().strftime("%a %d-%b") | 5,320,526 |
def add_review_suggestion_flags(df,
text_col,
result_col='result_binary'):
"""
attempt to add on some logical "manual review suggested" flags onto cases to reduce false positive/negative classifications. currently
flags cases with "flora" ... | 5,320,527 |
def create3DMatrix(data, trialTable, events, trialList, trialDur, fs, normalize, baselineDur=0.1):
"""
"""
trials = trialTable.copy()
trials = trials[trials['trialNum'].isin(trialList)]
totalTrialNum = np.max(trials['trialNum'])
m = trials.shape[0]
print m, totalTrialNum
electrodeNumber... | 5,320,528 |
def roundrobin(*iterables):
"""Yields an item from each iterable, alternating between them.
>>> list(roundrobin('ABC', 'D', 'EF'))
['A', 'D', 'E', 'B', 'F', 'C']
This function produces the same output as :func:`interleave_longest`, but
may perform better for some inputs (in particular when... | 5,320,529 |
def followed_list(username):
"""关注列表
"""
current_user = models.get_current_user()
user = models.get_user(username=username)
page = request.args.get('page', 1, type=int)
followed_list = user.followed.paginate(page, error_out=False)
user_list = [i.followed for i in followed_list.items]
ret... | 5,320,530 |
def add_edge_degree(graph, k=3):
"""
Add k edges to defend based on top edge degree centrality entries :cite:`tong2012gelling`.
:param graph: an undirected NetworkX graph
:param k: number of edges to add
:return: a list of edges to add
"""
info = defaultdict(list)
info['added'] = get_c... | 5,320,531 |
def number_of_fishers():
""" Prompt the user for the number of fishermen entering the draw."""
try:
number = int(input("How many fishermen will enter the competition: "))
return number
except ValueError:
print("Please enter an integer for the number of competing fishermen") | 5,320,532 |
def validate_module_specific_inputs(scenario_id, subscenarios, subproblem, stage, conn):
"""
Get inputs from database and validate the inputs
:param subscenarios: SubScenarios object with all subscenario info
:param subproblem:
:param stage:
:param conn: database connection
:return:
"""
... | 5,320,533 |
def plot_histogram(df, x, bins, xlabel=None, ylabel=None, title=None, figsize=(8, 5)):
"""
"""
fig = plt.figure(figsize=figsize)
ax = fig.gca()
ax.hist(df[x], bins=bins, color='#8d1a93')
ax.set_xlabel(xlabel, fontsize=16)
ax.set_ylabel(ylabel, fontsize=16)
ax.set_title(title, fontsize ... | 5,320,534 |
def pygmo_gaco(
criterion,
x,
lower_bounds,
upper_bounds,
*,
population_size=None,
batch_evaluator=None,
n_cores=1,
seed=None,
discard_start_params=False,
#
stopping_max_iterations=STOPPING_MAX_ITERATIONS_GENETIC,
kernel_size=63,
speed_parameter_q=1.0,
oracle=... | 5,320,535 |
def get_project_by_id(project_id: str) -> Project:
"""
Get a project by its project_id, with project model and project data joined.
:param project_id: project id of the project
:return: Project with the project id
"""
query = (
Project.select(Project, ProjectModel, ProjectData)
... | 5,320,536 |
def hist_similarity(image_1, image_2):
"""color hist based image similarity
@param image_1: np.array(the first input image)
@param image_2: np.array(the second input image)
@return similarity: float(range from [0,1], the bigger the more similar)
"""
if image_1.ndim == 2 and image_2.ndim == ... | 5,320,537 |
def slotter_obj():
""" Return basic slotter object """
return Slotter() | 5,320,538 |
def test_template_smoothing():
"""
Test template smoothing:
- `eazy.templates.Template.smooth_velocity`
- `eazy.templates.Template.to_observed_frame`
"""
from astropy.stats import gaussian_sigma_to_fwhm
#### Template with delta function line
xtest = np.lins... | 5,320,539 |
def get_ncbi_enrichment_domains():
""" Find all domains matched to given node id, then return dictionary with all domains as
result. All domains should have matching indices e.g. regulon[1] should be data from
matching same node as uniprot[1].
"""
# TODO: Validate incoming data using webargs... | 5,320,540 |
def gaussian(wavelength, w, sigma, amp=1., norm=True):
"""
Computes a gaussian for a given central wavelength, sigma and amp
.. math::
G = \\frac{A}{\sigma \sqrt{2 \pi}} \exp{\left( \\frac{ (w - w_0)^2 }{2 \sigma^2 } \\right) }
Args:
wavelength (np.ndarray): wavelength array to cal... | 5,320,541 |
def set_max_tick_env():
"""shares an environment with different
instances of the same test
"""
global SHARED_MAX_TICK_ENV
if SHARED_MAX_TICK_ENV is None:
binary_path = holodeck.packagemanager.get_binary_path_for_package(
"DefaultWorlds"
)
SHARED_MAX_TICK_ENV =... | 5,320,542 |
def summarize_samples(samples, run_parallel):
"""Back compatibility for existing pipelines. Should be replaced with summary when ready.
"""
return samples | 5,320,543 |
def test_deploy_log_messages_invoke(deploy_result: Result, namespace: str) -> None:
"""Test deploy log messages."""
assert f"{namespace}-dockerizepip returned 200" in deploy_result.stdout
assert f"{namespace}-nondockerizepip returned 200" in deploy_result.stdout | 5,320,544 |
def get_keywords(string):
"""Get keywords for a given string.
Args:
string (str): A string to get keywords for.
Returns:
(list): A list of keywords.
"""
keywords = string.lower().split(' ')
keywords = [x.strip() for x in keywords if x]
keywords = list(set(keywords))
retur... | 5,320,545 |
def calc_mass_loading_factor(OIII_results, OIII_error, hbeta_results, hbeta_error, hbeta_no_outflow_results, hbeta_no_outflow_error, statistical_results, z, header):
"""
Calculates the mass loading factor
eta = M_out/SFR
Using the calc_sfr.calc_sfr_koffee and the calc_mass_outflow_rate functions
... | 5,320,546 |
def _write_calccache(calc_cache, key_fn, val_fn, json_too=False, comm=None):
"""
Write `caclcache`, a dictionary of compact polys, to disk in two files,
one for the keys and one for the values.
This function can be called by multiple ranks and passed `comm` to
synchronize collecting and writing a s... | 5,320,547 |
def truecircle(radius, rho):
"""Create a "true" circular mask with anti-aliasing.
Parameters
----------
samples : `int`, optional
number of samples in the square output array
radius : `float`, optional
radius of the shape in the square output array. radius=1 will fill the
rho :... | 5,320,548 |
def distancia(ponto1, ponto2):
"""
Calcula a distância entre dois pontos
"""
xdif = ponto2.getx() - ponto1.getx()
ydif = ponto2.gety() - ponto1.gety()
dif = (xdif**2 + ydif**2)**0.5
return dif | 5,320,549 |
def foo(x, sleep_time):
"""Dummy function for the tests"""
time.sleep(sleep_time)
return [{"type": "objective", "name": "objective", "value": x}] | 5,320,550 |
def aug_ims(ims, fliplr=0, flipud=0, T=0):
"""Augment images with flips and transposition."""
ims_aug = np.array(ims, copy=True)
for i in range(len(ims_aug)):
if fliplr: # flip left right
ims_aug[i] = np.fliplr(ims_aug[i])
if flipud: # flip up down
ims_aug[i] = np.f... | 5,320,551 |
def bt_search(btree, key):
"""基于二叉树查询操作"""
bt = btree
while bt is not None:
entry = bt.data
if key < entry.key:
bt = bt.left
elif key > entry.key:
bt = bt.right
else:
return entry.values
return None | 5,320,552 |
def make_reply(msgname, types, arguments, major):
"""Helper method for constructing a reply message from a list or tuple
Parameters
----------
msgname : str
Name of the reply message.
types : list of kattypes
The types of the reply message parameters (in order).
arguments : list... | 5,320,553 |
def empty_coord():
"""Return an empty coordinate tensor representing 1 residue-level pad character."""
coord_padding = np.zeros((NUM_COORDS_PER_RES, 3))
coord_padding[:] = GLOBAL_PAD_CHAR
return coord_padding | 5,320,554 |
def grib_clone(msgid_src):
"""
@brief Create a copy of a message.
Create a copy of a given message (\em msgid_src) resulting in a new
message in memory (\em msgid_dest) identical to the original one.
\b Examples: \ref grib_clone.py "grib_clone.py"
@param msgid_src id of message to be cloned... | 5,320,555 |
def layernorm(x, epsilon=1e-5, name='lnconv'):
"""Layer Normalization for conv. x must be [NCHW]"""
shape = x.get_shape().as_list()
with tf.variable_scope(name):
beta = tf.get_variable("beta", [1, shape[1], 1, 1], initializer=tf.constant_initializer(0.))
gamma = tf.get_variable("gamma", [1, ... | 5,320,556 |
def create_graph_from_edges(edges):
"""
Create a graph from the `edges`
"""
G = nx.Graph()
for e in edges:
p1 = e[0]
p2 = e[1]
dist = LA.norm(np.array(p2) - np.array(p1))
G.add_edge(p1, p2, weight=dist)
return G | 5,320,557 |
def far_field(frequency, radius, current, r, theta):
"""
Calculate the electric and magnetic far fields for a small circular loop.
:param r: The range to the field point (m).
:param theta: The angle to the field point (rad).
:param frequency: The operating frequency (Hz).
:param radius: The radi... | 5,320,558 |
def rng_laplace(lambd=1, trunc=None):
"""
Generate random numbers from a Laplace distribution
Parameters
----------
lambd: float
The scale of the distribution
trunc: None, tuple
Specifies whether the distribution is truncated. If it's
not None then it must be a 2-tuple i... | 5,320,559 |
def test_update_success(mocker):
"""dataid存在"""
_clean_success_parpare(mocker)
PARAMS = {
"raw_data_id": 42,
"json_config": JSON_CONF,
"pe_config": "",
"bk_biz_id": 2,
"clean_config_name": "output",
"result_table_name": "output",
"result_table_name_ali... | 5,320,560 |
def PrintCategorised(DataDirectory,fname_prefix, Drape_prefix,
show_colourbar = False,
cmap = "jet", cbar_loc = "right", cbar_label = "drape colourbar", size_format = "ESURF",
fig_format = "png", dpi = 250, out_fname_prefix = ""):
"""
This function... | 5,320,561 |
def settings_to_connections(
settings: amicus.options.Configuration,
suffixes: Sequence[str]) -> Dict[str, List[str]]:
"""[summary]
Args:
settings (amicus.options.Configuration): [description]
suffixes (Sequence[str]): [description]
Returns:
Dict[str, List[str]]: [descripti... | 5,320,562 |
def radec_from_pointing_object(pointing,
# default output in degrees
as_radians=False,
as_string=False):
"""Astropy object to ICRS format as strings"""
pnt_radec = pointing.transform_to(ICRS())
if as_string:
... | 5,320,563 |
def get_potentially_supported_ops():
"""Gets potentially supported ops.
Returns:
list of str for op names.
"""
supported_ops = _get_potentially_supported_ops()
op_names = [s.op for s in supported_ops]
return op_names | 5,320,564 |
def hard_sigmoid_me(input_, inplace: bool = False):
"""jit-scripted hard_sigmoid_me function"""
return HardSigmoidJitAutoFn.apply(input_) | 5,320,565 |
def demoji(tokens):
"""
This function describes each emoji with a text that can be later used for vectorization and ML predictions
:param tokens:
:return:
"""
emoji_description = []
for token in tokens:
detect = emoji.demojize(token)
emoji_description.append(detect)
retur... | 5,320,566 |
async def get_journal_entries_by_permalink_handler(
journal_permalink: str = Path(...),
entry_permalink: str = Path(...),
db_session: Session = Depends(db.yield_connection_from_env),
) -> RedirectResponse:
"""
Get specific journal entry by short link.
"""
try:
journal_id, journal_pub... | 5,320,567 |
def ignore_pre_big_bang(run):
"""
Remove metrics before timestamp 0.
"""
return [m for m in run if m[TS] >= 0]
#return [m for m in run if m[TS] >= 0 and m[TS] < MAX_TIME] | 5,320,568 |
def signUp():
"""Sign up a new user.
:field phone [int]: user phone number
:field name [str]: user name
:field password [str]: user password (will be encrypted)
:returns [dict]: newly created user's info with auth token
"""
phone = handler.parse('phone', int)
name = handler.parse('name'... | 5,320,569 |
def next_player(player,list_player_names,player_index,open_card,given_card):
""" returns the next player
>>> list_player_names=['Mark','John','Harry','Henry']
>>> player_index=0
>>> player='Mark'
>>> next_player(player,list_player_names,player_index,('A', '♥', 11))
'John'
>>> player_i... | 5,320,570 |
def loss_function(image, idx, c, omega):
"""
:param last_image: the previous generated frame
:param outputs: Generated image
:return: The sum of the style and content loss
"""
outputs = extractor(image)
style_outputs = outputs["style"]
content_outputs = outputs["content"]
style_loss... | 5,320,571 |
def bra(seq, dim=2):
"""
Produces a multiparticle bra state for a list or string,
where each element stands for state of the respective particle.
Parameters
----------
seq : str / list of ints or characters
Each element defines state of the respective particle.
(e.g. [1,1,0,1] o... | 5,320,572 |
def file_exists(filepath):
"""Check whether a file exists by given file path."""
return os.path.isfile(filepath) | 5,320,573 |
def rmse_diff(model_data, subj_data):
"""this rmse only consider diff"""
R = np.array(model_data)
D = np.array(subj_data)
r_DIFF = np.round([np.mean(R[0:2])-np.mean(R[2:4]),
R[0]-R[1], R[2]-R[3]], 4)
d_DIFF = np.round([np.mean(D[0:2]) - np.mean(D[2:4]),
D[0] - D[1... | 5,320,574 |
def preparation_time_in_minutes(number_of_layers: int) -> int:
"""Calculate the preparation time per layer.
.:param number_of_layers: int number of layers.
.:return: int time in minutes derived from 'PREPARATION_TIME'.
Function that takes the actual number of layer of the lasagna and
return how muc... | 5,320,575 |
def eliminate(board, i, j):
"""
Propagates the effects of fixing a cell to the affected neighbors
within the same square and vertical and horizontal lines
"""
value = board[i][j][0]
# Horizontal propagation
for k in range(n):
if j!=k and value in board[i][k]:
board[i][k].... | 5,320,576 |
def prep_tweet_body(tweet_obj, args, processed_text):
""" Format the incoming tweet
Args:
tweet_obj (dict): Tweet to preprocess.
args (list): Various datafields to append to the object.
0: subj_sent_check (bool): Check for subjectivity and sentiment.
1: subjectivity (num... | 5,320,577 |
def send_mfg_inspector_data(inspector_proto, credentials, destination_url,
payload_type):
"""Upload MfgEvent to steam_engine."""
envelope = guzzle_pb2.TestRunEnvelope()
envelope.payload = zlib.compress(inspector_proto.SerializeToString())
envelope.payload_type = payload_type
envelo... | 5,320,578 |
def cache_lookup_only(key):
"""Turns a function into a fallback for a cache lookup.
Like the `cache` decorator, but never actually writes to the cache.
This is good for when a function already caches its return value
somewhere in its body, or for providing a default value for a value
that is suppos... | 5,320,579 |
def social_distancing_policy():
"""
Real Name: b'social distancing policy'
Original Eqn: b'1-PULSE(social distancing start, FINAL TIME-social distancing start+1)*social distancing effectiveness'
Units: b'dmnl'
Limits: (None, None)
Type: component
b''
"""
return 1 - functions.pulse(
... | 5,320,580 |
def text2lm(in_filename, out_filename):
"""Wrapper around the language model compilation tools"""
def text2idngram(in_filename, out_filename):
cmd = "text2idngram -vocab %s < %s -idngram temp.idngram" % (out_filename,
in_filename)
... | 5,320,581 |
def mersenne_prime(n_max):
""" This is the description of the function 4 ~ Loves it + 3
Parameters
----------
n_max : int
for p up to n_max
Returns
-------
list
list of q
"""
primes = []
for a in range(0,n_max):
b = 2**a... | 5,320,582 |
def orderbook(chart, limit, show_date, width, height, ascii):
"""Obtain orderbook of the internal market"""
stm = shared_steem_instance()
if stm.rpc is not None:
stm.rpc.rpcconnect()
market = Market(steem_instance=stm)
orderbook = market.orderbook(limit=limit, raw_data=False)
if not show... | 5,320,583 |
def import_locus_intervals(path,
reference_genome='default',
skip_invalid_intervals=False,
contig_recoding=None,
**kwargs) -> Table:
"""Import a locus interval list as a :class:`.Table`.
Examples
---... | 5,320,584 |
def speech_tagging(test_data, model, tags):
"""
Inputs:
- test_data: (1*num_sentence) a list of sentences, each sentence is an object of line class
- model: an object of HMM class
Returns:
- tagging: (num_sentence*num_tagging) a 2D list of output tagging for each sentences on test_data
"""
tagging = []
######... | 5,320,585 |
def evaluate_if(hook_dict: dict, context: 'Context', append_hook_value: bool) -> bool:
"""Evaluate the when condition and return bool."""
if hook_dict.get('for', None) is not None and not append_hook_value:
# We qualify `if` conditions within for loop logic
return True
if hook_dict.get('if',... | 5,320,586 |
def create_install_repo_without_openstack_and_compute(*tgzs, **kwargs):
"""Creates contrail install repo in all nodes excluding openstack and compute nodes."""
if len(tgzs) == 0:
cmd = 'create_install_repo_node'
else:
cmd = 'create_install_repo_from_tgz_node'
for host_string in env.role... | 5,320,587 |
def startRhevmDbRelatedServices(etlService, notificationService):
"""
bring back any service we stopped
we won't start services that are down
but weren't stopped by us
"""
(output, rc) = etlService.conditionalStart()
if rc != 0:
logging.warn("Failed to start rhevm-etl")
messa... | 5,320,588 |
def find_vgg_layer(arch, target_layer_name):
"""Find vgg layer to calculate GradCAM and GradCAM++
Args:
arch: default torchvision densenet models
target_layer_name (str): the name of layer with its hierarchical information. please refer to usages below.
target_layer_name = 'features... | 5,320,589 |
def plain_bst():
"""Returns a plain binary search tree and a tuple of its nodes. The tree has the same structure as ref_bst."""
t = Tree.tree()
n1 = Tree.tree().treeNode(1)
n3 = Tree.tree().treeNode(3)
n4 = Tree.tree().treeNode(4)
n6 = Tree.tree().treeNode(6)
n7 = Tree.tree().treeNode(7)
... | 5,320,590 |
def test_confirm_name(monkeypatch, single_with_trials):
"""Test name must be confirmed for update"""
def incorrect_name(*args):
return "oops"
monkeypatch.setattr("builtins.input", incorrect_name)
execute("db set test_single_exp status=broken status=interrupted", assert_code=1)
def correc... | 5,320,591 |
def get_one_hot_reprs(batch_stds):
""" Get one-hot representation of batch ground-truth labels """
batch_size = batch_stds.size(0)
hist_size = batch_stds.size(1)
int_batch_stds = batch_stds.type(torch.cuda.LongTensor) if gpu else batch_stds.type(torch.LongTensor)
hot_batch_stds = torch.cuda.FloatTe... | 5,320,592 |
def ursula(config,
action,
rest_port,
rest_host,
db_name,
checksum_address,
debug,
teacher_uri,
min_stake
) -> None:
"""
Manage and run an Ursula node
Here is the procedure to "spin-up" an Ursula node.
... | 5,320,593 |
def absolute_confusion_from_incidence(true_incidence, predicted_incidence) -> Tuple[float, float, float, float]:
"""Return the absolute number of true positives, true negatives, false positives and false negatives.
Parameters
----------
true_incidence: numpy.ndarray
the true target incidence ma... | 5,320,594 |
def test_every_iteration_model_updater_with_cost():
"""
Tests that the model updater can use a different attribute from loop_state as the training targets
"""
class MockModel(IModel):
def optimize(self):
pass
def set_data(self, X: np.ndarray, Y: np.ndarray):
sel... | 5,320,595 |
def run_setup_error_group():
"""Run the phase group example where an error occurs in a setup phase.
The terminal setup phase shortcuts the test. The main phases are
skipped. The PhaseGroup is not entered, so the teardown phases are also
skipped.
"""
test = htf.Test(
htf.PhaseGroup(
setup=... | 5,320,596 |
def correlating_weight2_data(shots_discr, idx_qubit_ro, correlations, num_segments):
"""
"""
correlations_idx = [
[idx_qubit_ro.index(c[0]), idx_qubit_ro.index(c[1])] for c in correlations]
correl_discr = np.zeros((shots_discr.shape[0], len(correlations_idx)))
correl_avg = np.zeros((num_seg... | 5,320,597 |
def create_test_network_6():
"""Aligned network with dropout for test.
The graph is similar to create_test_network_1(), except that the right branch
has dropout normalization.
Returns:
g: Tensorflow graph object (Graph proto).
"""
g = tf.Graph()
with g.as_default():
# An input test ima... | 5,320,598 |
def timedcall(fn, *args):
"""
Run a function and measure execution time.
Arguments:
fn : function to be executed
args : arguments to function fn
Return:
dt : execution time
result : result of function
Usage example:
You want to time the function call "C = foo(A,B)".
-... | 5,320,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.