content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def cost_aggregation(c_v, max_d):
"""
the formula
Lr(p,d) = C(p,d)
+ min[Lr(p-r, d),Lr(p-r, d-1)+p1,Lr(p-r,d+1)+p1,miniLr(p-r, i)+p2]
- minkLr(p-r,k)
:param c_v:
:param max_d:
:return: sum of all the Lr
"""
(H, W, D) = c_v.shape
p1 = 10
p2 = 120
Lr1 = ... | 46,600 |
def send_approved_resource_email(user, request, reason):
"""
Notify the user the that their request has been approved.
"""
email_template = get_email_template()
template = "core/email/resource_request_approved.html"
subject = "Your Resource Request has been approved"
context = {
"sup... | 46,601 |
def is_in_section_title(node: Element) -> bool:
"""Determine whether the node is in a section title"""
from sphinx.util.nodes import traverse_parent
warnings.warn('is_in_section_title() is deprecated.',
RemovedInSphinx30Warning, stacklevel=2)
for ancestor in traverse_parent(node):
... | 46,602 |
def create_number_type(lang):
""" Creates a sort corresponding to the PDDL "number" """
parent = lang.get_sort("Real")
lower = parent.lower_bound
upper = parent.upper_bound
lang.interval("number", parent, lower, upper) | 46,603 |
def _set_data_location(elec_meters, building):
"""Goes through each ElecMeter in elec_meters and sets `data_location`.
Modifies `elec_meters` in place.
Parameters
----------
elec_meters : dict of dicts
building : string e.g. 'building1'
"""
for meter_instance in elec_meters:
dat... | 46,604 |
def convert(im_fd: str, pc_fd: str, out_fd: str):
"""Converts 2D bbox in image to 3D bbox in pointcloud"""
model = ObjectDetctor()
im_fd_prefix = im_fd + IM_PREFIX
pc_fd_prefix = pc_fd + PC_PREFIX
frame_list = get_frame_ids(im_fd, pc_fd)
i = 0
total_frames = len(frame_list)
# down sampl... | 46,605 |
def common_mgr():
"""
Create a base topology.
This uses the ExtendedNMLManager for it's helpers.
"""
# Create base topology
mgr = ExtendedNMLManager(name='Graphviz Namespace')
sw1 = mgr.create_node(identifier='sw1', name='My Switch 1')
sw2 = mgr.create_node(identifier='sw2', name='My S... | 46,606 |
def reshape_array_h5pyfile(array,number_of_gatesequences,datapoints_per_seq):
"""reshaping function"""
new_array = np.reshape(array,(number_of_gatesequences,datapoints_per_seq),order='F') #order is important, for data as column,
#use order F, this will give an number_of_gatesequences x datapoints_per_seq ma... | 46,607 |
def step060() -> None:
"""
Update the tsa of documents in elasticsearch
"""
logger.logMessage('Begin: elasticsearch bulk update')
client = es.Elasticsearch(hostlist)
def generate():
with open(renumFile,'r') as f:
line = f.readline().rstrip()
while line != '':
... | 46,608 |
def write_png_from_xr(png_path, dataset, bands, png_filled_path=None, fill_color='red', scale=None, low_res=False,
no_data=-9999, crs="EPSG:4326"):
"""Write a rgb png from an xarray dataset.
Note that using `low_res==True` currently causes the file(s)
for `png_path` and `png_filled_pat... | 46,609 |
def build_value_counts_query(table: str,
categorical_column: str,
limit: int):
"""
Examples:
SELECT
{column_name},
COUNT (*) as frequency
FROM
`{table}`
WHERE
{not_null_str... | 46,610 |
def get_model_benchmarks_data(benchmark_runlogs_filepath: Path):
"""
Return Python dict with summary of model performance for one choice of
training set size.
"""
benchmark_genlog = read_json(benchmark_runlogs_filepath)
benchmark_runlog = read_json(benchmark_runlogs_filepath.parent / "runlog.jso... | 46,611 |
def make_labels(module_path, *names, **names_labels):
"""Make a namespace of labels."""
return collections.Namespace(
*((name, Label(module_path, name)) for name in names),
*((n, l if isinstance(l, Label) else Label(module_path, l))
for n, l in names_labels.items()),
) | 46,612 |
def check_port_occupied(port, address="127.0.0.1"):
"""Check if a port is occupied by attempting to bind the socket and returning any resulting error.
:return: socket.error if the port is in use, otherwise False
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((address,... | 46,613 |
def test_heterogeneous_multiagent_env(
common_config,
pf_config,
multicomponent_building_config,
pv_array_config,
ev_charging_config
):
"""Test multiagent env with three heterogeneous agents."""
building_agent ={
"name": "building",
"bus": "675c",
"cls": MultiCompone... | 46,614 |
def find_sublinks(artist_link):
"""Some artists have that many songs so we have multiple pages for them. This functions finds all subpages for given artist
e.g if we have page freemidi/queen_1 script go on that page and seek for all specific hyperlinks.
as a return we could get [freemidi/queen_1, fre... | 46,615 |
def class_mock(request, q_class_name, autospec=True, **kwargs):
"""Return mock patching class with qualified name *q_class_name*.
The mock is autospec'ed based on the patched class unless the optional
argument *autospec* is set to False. Any other keyword arguments are
passed through to Mock(). Patch i... | 46,616 |
async def test_reclaim_pending_messages(redis_client, redis_pool, error_queue):
"""Test that unacked messages belonging to this consumer get reclaimed on startup"""
# Add a message
await redis_client.xadd(
"my.dummy.my_event:stream",
fields={
b"api_name": b"my.dummy",
... | 46,617 |
def kwargs_only(fn):
"""Wraps function so that callers must call it using keyword-arguments only.
Args:
fn: fn to wrap.
Returns:
Wrapped function that may only be called using keyword-arguments.
"""
if hasattr(inspect, 'getfullargspec'):
# For Python 3
args = inspect.getfullargspec(fn)
... | 46,618 |
def _labeling_complete(labeling, G):
"""Determines whether or not LPA is done.
Label propagation is complete when all nodes have a label that is
in the set of highest frequency labels amongst its neighbors.
Nodes with no neighbors are considered complete.
"""
return all(labeling[v] in... | 46,619 |
def get_random_id_str(alphabet=None):
""" Get random integer and encode it to URL-safe string. """
if not alphabet:
alphabet = BASE62
n = _random(RANDOM_ID_SOURCE_BYTES)
return int2str(n, len(alphabet), alphabet) | 46,620 |
def multivariate_normal_pdf(x, mean, cov):
"""Unnormalized multivariate normal probability density function."""
# Convert to ndarray
x = np.asanyarray(x)
mean = np.asanyarray(mean)
cov = np.asarray(cov)
# Deviation from mean
dev = x - mean
if isinstance(dev, np.ma.MaskedArray):
... | 46,621 |
def remove_below(G, attribute, value):
""" Remove attribute below certain value
Parameters
----------
G : nx.graph
Graph
attribute : str
Attribute
value : float
Value
Returns
-------
G : nx.graph
Graph
"""
... | 46,622 |
def format_header(header_values):
"""
Formats a row of data with bolded values.
:param header_values: a list of values to be used as headers
:return: a string corresponding to a row in enjin table format
"""
header = '[tr][td][b]{0}[/b][/td][/tr]'
header_sep = '[/b][/td][td][b]'
return ... | 46,623 |
def plot_confusion_matrix(cm: ndarray,
classes: List[str],
savefolder: str,
filename: str = utils.timestamp() + '.png',
figsize: Tuple[int, int] = (30,20)) -> str:
"""
Creates an image of a confusion ma... | 46,624 |
def getRandomWalk(initial_position: int, current_path: np.ndarray, adjacency_matrix: np.ndarray,
heuristic: np.ndarray, pheromone: np.ndarray, alpha: float, max_lim: int,
Q: float or None, R: float or None) -> np.ndarray:
"""
Function that given an array indicating the nodes ... | 46,625 |
def sample_circle(plane="xy", N=100):
"""Define all angles in a certain plane."""
phi = np.linspace(0, 2 * np.pi, N)
if plane == "xy":
return np.array([np.cos(phi), np.sin(phi), np.ones_like(phi)])
elif plane == "xz":
return np.array([np.cos(phi), np.ones_like(phi), np.sin(phi)])
eli... | 46,626 |
def generate_today_word_cloud(path='images/'):
"""
generate today word cloud
Args:
path (str, optional): [description]. Defaults to 'images/'.
"""
terms_counts = get_term_count()
if terms_counts:
word_cloud = generate_word_cloud(terms_counts, drc_flag_color_map)
word_clo... | 46,627 |
def load_attr(str_full_module):
"""
Args:
- str_full_module: (str) correspond to {module_name}.{attr}
Return: the loaded attribute from a module.
"""
if type(str_full_module) == str:
split_full = str_full_module.split(".")
str_module = ".".join(split_full[:-1])
str_at... | 46,628 |
def define_and_run_dnn_classifier(num_steps, logdir, lr=.1, batch_size=100):
"""Run a DNN classifier."""
feature_columns = [tf.contrib.layers.real_valued_column("pixels", dimension=784)]
dnn_classifier = tf.estimator.DNNClassifier(
feature_columns=feature_columns,
n_classes=10,
hidd... | 46,629 |
def conv(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]) -> List[XLayer]:
"""ONNX Conv to XLayer Conv conversion function"""
logger.info("ONNX Conv -> XLayer Conv (+ BiasAdd)")
assert len(node.get_outputs()) == 1
name = node.get_outputs()[0]
bottoms = no... | 46,630 |
def plot_3D(
Xdata,
Ydata,
Zdata,
colormap="RdBu_r",
color_list=None,
x_min=None,
x_max=None,
y_min=None,
y_max=None,
z_min=None,
z_max=None,
title="",
xlabel="",
ylabel="",
zlabel="",
xticks=None,
yticks=None,
xticklabels=None,
yticklabels=Non... | 46,631 |
def yices_bvconst_int32(n, x):
"""Conversion of an integer to a bitvector constant, returns NULL_TERM (-1) if there's an error.
bvconst_int32(n, x):
- n = number of bits
- x = value
The low-order bit of x is bit 0 of the constant.
- if n is less than 32, then the value of x is truncated to
... | 46,632 |
def combination(n, k):
"""
组合数 n!/k!(n-k)!
:param n:
:param k:
:return:
"""
from scipy.special import comb
return comb(n, k, exact=True) | 46,633 |
def save_report(report, output_dir, participant_id):
"""Saves HTML report."""
# Create output directory
makedirs(output_dir, exist_ok=True)
# Save
fname = f'{output_dir}/{participant_id}_report.html'
print(f'Saving HTML report to {fname}')
_ = report.save(fname, open_browser=False, overwri... | 46,634 |
def insert_prize(conn, number, prize):
""" Insert de premios """
try:
cur = conn.cursor()
logger.debug('INSERT PRIZE - "%s" / "%s"', number, prize)
cur.execute(INSERT_PRIZE_QUERY, (number, prize, prize))
conn.commit()
cur.close()
return True
except mysql.conn... | 46,635 |
def register_cors(app: FastAPI):
"""
支持跨域
:param app:
:return:
"""
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.BACKEND_CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
a... | 46,636 |
def merge_original_and_extra_vocab(
tokenizer_name,
dest_tokenizer_name=uuid.uuid4().hex[:6].upper(),
src_wordpiece_vocab="wordpiece.vocab",
mode="a",
):
"""
Merge original BERT model vocabulary with our extra vocabulary.
Arguments
tokenizer_name: str
Valid model id on h... | 46,637 |
def create_carray(h5file_uri, type, shape):
"""Creates an empty chunked array given a file type and size.
h5file_uri - a uri to store the carray
type - an h5file type
shape - a tuple indicating rows/columns"""
h5file = tables.openFile(h5file_uri, mode='w')
root ... | 46,638 |
def sort_dictionary_by_keys(input_dict):
"""
Sort the dictionary by keys in alphabetical order
"""
sorted_dict = {}
for key in sorted(input_dict.keys()):
sorted_dict[key] = input_dict[key]
return sorted_dict | 46,639 |
def sorted_instructions(binview):
"""
Return a sorted list of the instructions in the current viewport.
"""
addrs = []
instructions = []
for ii in binview.instructions:
if ii[1] not in addrs:
instructions.append(instr(ii))
addrs.append(ii[1])
del addrs
in... | 46,640 |
def setup_transfer_service(project_name: str, source_bucket: str,
sink_bucket: str, start_date: datetime.date) -> None:
"""Set up a data transfer job between two buckets.
Args:
project_name: string like 'firehook-censoredplanet'
source_bucket: GCS bucket to read from like 'censor... | 46,641 |
def log_rate_limits(hass, device_name, resp, level=logging.INFO):
"""Output rate limit log line at given level."""
if ATTR_PUSH_RATE_LIMITS not in resp:
return
rate_limits = resp[ATTR_PUSH_RATE_LIMITS]
resetsAt = rate_limits[ATTR_PUSH_RATE_LIMITS_RESETS_AT]
resetsAtTime = dt_util.parse_date... | 46,642 |
def quick_sort(seq):
"""
Реализация быстрой сортировки. Рекурсивный вариант.
:param seq: любая изменяемая коллекция с гетерогенными элементами,
которые можно сравнивать.
:return: коллекция с элементами, расположенными по возрастанию.
Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3,... | 46,643 |
def _geocode(address):
"""
Like :func:`geocode` except returns the raw data instead.
:param str address: A location (e.g., "Newark, DE") somewhere in the United States
:returns: str
"""
key = _geocode_request(address)
result = _get(key) if _CONNECTED else _lookup(key)
if _CONNECTED ... | 46,644 |
def main():
"""Entrypoint function."""
prog_desc = 'Simple network socket client with customized \
workload support.'
parser = ParameterParser(description=prog_desc)
start_parser = parser.prepare(socket.socket)
__populate_start_parser(start_parser)
parser.parse_args() | 46,645 |
def easeOutBack(n, s=1.70158):
"""A tween function that overshoots the destination a little and then backs into the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to... | 46,646 |
def clean_db(database, exp_config):
"""Clean insert example experiment entries to collections."""
database['experiments'].drop()
database['experiments'].insert_many(exp_config[0])
database['trials'].drop()
database['trials'].insert_many(exp_config[1])
database['workers'].drop()
database['wor... | 46,647 |
def apply_corrections(chain):
""" Apply phase0 and freq shift correction to individual FID data """
ds = chain._dataset
set = chain.set
time = chain.raw_combined.copy()
xx = np.arange(time.shape[3]) / ds.sw
_, ncoil, nfids, npts = chain.raw.shape
if chain.do_freq_raw:
chain.... | 46,648 |
def test_11_log_file(capsys):
"""Verify that we can open a log file."""
with capsys.disabled():
config = {'log_file_name': 'tmp.log',
'logger_name': 'f',
'version': 'r1.0.0',
'migration_action': 'info'}
pydbvolve.setup_file_logger(config)
... | 46,649 |
def print_multipage(path: Path, tick: int, rgb_image: np.ndarray, heatmaps: np.ndarray):
"""
Prints a multi-page PDF.
"""
with PdfPages(path) as pdf:
height, width, _channels = rgb_image.shape
figsize = width / float(DPI), height / float(DPI)
fig = plt.figure(figsize=figsize)
... | 46,650 |
def multi_count_word(args, process_no=None):
"""
:param args: 参数字典
:param process_no: 进程数量,默认为 None, 即 CPU核数
:return:
"""
if process_no is None:
process_no = cpu_count()
logger.info('- ' * 30)
logger.info(' {:d} 进程 n_gram 词组统计程序开始。。。。'.format(process_no))
# 词组长度 n_gram 窗... | 46,651 |
def normalize_query_result(result, sort=True):
"""
Post-process query result to generate a simple, nested list.
:param result: A QueryResult object.
:param sort: if True (default) rows will be sorted.
:return: A list of lists of RDF values.
"""
normalized = [[row[i] for i in range(len(row))... | 46,652 |
def count_jobpairs(buildpairs: List) -> int:
"""
:param buildpairs: A list of build pairs.
:return: The number of job pairs in `buildpairs`.
"""
counts = [len(bp['jobpairs']) for bp in buildpairs]
return sum(counts) | 46,653 |
def unravel_params(nn_params, input_layer_size, hidden_layer_size,
num_labels, n_hidden_layers=1):
"""Unravels flattened array into list of weight matrices
:param nn_params: Row vector of model's parameters.
:type nn_params: numpy.array
:param input_layer_size: Number of units in th... | 46,654 |
def is_op_stack_var(ea, index):
""" check if operand is a stack variable """
return idaapi.is_stkvar(idaapi.get_flags(ea), index) | 46,655 |
def test_beams():
"""Beams with axial force"""
# Analytic problem
nodes = np.array([
[0, 0.0, 0.0],
[1, 0.0, 6.0],
[2, 4.0, 6.0]])
cons = np.array([
[-1, -1, -1],
[0, 0, 0],
[-1, -1, -1]])
mats = np.array([[200e9, 1.33e-4, 0.04]])
... | 46,656 |
def get_circles():
"""
Create 3 images each containing a circle at a different position.
Returns:
List([numpy array,]) of 3 circle images
"""
circles = []
x, y = np.meshgrid(range(256), range(256))
for d in range(30, 390, 120):
img = np.zeros((256, 256), dtype=np.uint8... | 46,657 |
def load_sequences( fasta_file ):
"""! @brief load candidate gene IDs from file """
sequences = {}
assembly_seq_order = []
with open( fasta_file ) as f:
header = f.readline()[1:].strip()
if " " in header:
header = header.split(' ')[0]
seq = []
line = f.readline()
while line:
if line[0] == '>':
... | 46,658 |
def test_action_not_configured(client, fake_identity):
"""Tests a non configured action call."""
# NOTE: recid can be dummy since it won't reach pass the resource view
response = client.post(
"/records/1234-abcd/draft/actions/non-configured", headers=HEADERS
)
assert response.status_code ==... | 46,659 |
def compute_distance_fields(params, canvas_size, df=distance_to_cuboids):
"""Compute distance fields of size (canvas_size+2)^3 to specified primitives.
params -- [b, *]
canvas_size
df -- distance_to_*
"""
grid_pts = th.stack(th.meshgrid([th.linspace(-1/(canvas_size-1),
... | 46,660 |
def restart_router():
"""Restart the Traefik docker container. You can run this after
updating the config (~/_mypaas/traefik.toml or staticroutes.toml)
or to update Traefik after updating MyPaas. Your PAAS will be
offline for a few seconds.
"""
image_name = "traefik:" + __traefik_version__
... | 46,661 |
def url_retrieve(url: str, outfile: Path, overwrite: bool = False):
"""
Adapted from https://www.scivision.dev/python-switch-urlretrieve-requests-timeout/
"""
outfile = Path(outfile).expanduser().resolve()
if outfile.is_dir():
raise ValueError("Please specify full filepath, including filenam... | 46,662 |
def view_user_posts(request, pk=None):
"""View your own posts or others posts"""
if pk is None:
pk = request.user.pk
user = get_object_or_404(User, pk=pk)
return render(request, 'home/view_user_posts.html',
{"pk": user.username, "user": user}) | 46,663 |
def find_all_strobogrammatic_numbers(n: int):
""" Returns all strobogrammatic numbers for a given number of digits.
Args:
int: number of digits
Returns:
A list of string with strobogrammatic numbers.
"""
result = numdef(n, n)
return result | 46,664 |
def write_htmls(grouped_details, grouped_task, start_date, end_date, output_folder):
"""Write detailed dataframe and main page's task dataframe to html files
Because of that Linux file name cannot contain slash,
html file name of a task contains different characters(-_-) which are replaced with slash.
... | 46,665 |
def get_deploy_size_bytes(deploy: Deploy) -> int:
"""Returns size of a deploy in bytes.
:deploy: Deploy to be written in JSON format.
:returns: Size of deploy in bytes.
"""
size: int = len(deploy.hash)
for approval in deploy.approvals:
size += len(approval.signature)
size += le... | 46,666 |
def find_coordinates(
hass: HomeAssistantType, entity_id: str, recursion_history: Optional[list] = None
) -> Optional[str]:
"""Find the gps coordinates of the entity in the form of '90.000,180.000'."""
entity_state = hass.states.get(entity_id)
if entity_state is None:
_LOGGER.error("Unable to f... | 46,667 |
def make_hetero_tuple_unstructure_fn(cl: Any, converter, unstructure_to=None):
"""Generate a specialized unstructure function for a heterogenous tuple."""
fn_name = "unstructure_tuple"
type_args = get_args(cl)
# We can do the dispatch here and now.
handlers = [
converter._unstructure_func.... | 46,668 |
def get_dps(name: Optional[str] = None,
resource_group_name: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDpsResult:
"""
Use this data source to access information about an existing IotHub Device P... | 46,669 |
def install(ctx):
"""Install platform firmware"""
ctx.obj[COMPONENT_PATH_CTX_KEY] = [ ] | 46,670 |
def obtener_id_modulo_por_nombre(modulo: Union[str, None]) -> Union[str, None]:
"""Devuelve el UUID de un modulo por su nombre."""
if modulo:
from cacao_accounting.database import Modulos
MODULO = Modulos.query.filter_by(modulo=modulo).first()
return MODULO.id
else:
return N... | 46,671 |
def qg8_graph_get_chunk(graph: qg8_graph, idx: int):
"""
Get a chunk from the graph according to its index provided the second argument `idx`
"""
if not isinstance(graph, qg8_graph):
raise TypeError("Argument is not a qg8_graph")
if idx > len(graph.chunks) - 1:
raise ValueError("Inde... | 46,672 |
def InterruptStartForwardForVector(builder, numElems):
"""This method is deprecated. Please switch to Start."""
return StartForwardForVector(builder, numElems) | 46,673 |
def build_network(
operations,
cwd=None,
rescheduled=None,
endured=None,
parallel=None,
marshalled=None,
node_props=None,
renamer=None,
excludes=None,
):
"""
The :term:`network` factory that does :term:`operation merging` before constructing it.
:param nest:
see ... | 46,674 |
def convert(source, target):
"""
Performs actuall conversion.
Currently, 'source' has to be UnitFile and 'target' RCFile.
"""
if isinstance(source, UnitFile) and isinstance(target, RCFile):
_unit2openrc(source, target)
else:
raise TypeError("Unsupported conversion") | 46,675 |
def test_addExt_imageFiles_mustExist_shouldPass():
"""Tests the addExt function where the path exists, and the inputs
are valid.
"""
groups = fslimage.FILE_GROUPS
allowedExts = fslimage.ALLOWED_EXTENSIONS
# (files_to_create, path, expected)
tests = [
# Single files
... | 46,676 |
def merge_contents(cset, offset=None, callback=None):
"""
merge a :class:`pkgcore.fs.contents.contentsSet` instance to the livefs
:param cset: :class:`pkgcore.fs.contents.contentsSet` instance
:param offset: if not None, offset to prefix all locations with.
Think of it as target dir.
:para... | 46,677 |
def test_get_user(staff_client, user):
"""
Get a user
"""
profile = user.profile
url = reverse("user_api-detail", kwargs={"username": user.username})
resp = staff_client.get(url)
assert resp.status_code == 200
assert resp.json() == {
"id": user.id,
"username": user.userna... | 46,678 |
def main():
"""Register subcommands and run taurus_cmd"""
# set the log level to WARNING avoid spamming the CLI while loading
# subcommands
# it will be restored to the desired one first thing in taurus_cmd()
taurus.setLogLevel(taurus.Warning)
#register the subcommands
register_subcommands... | 46,679 |
def write_dat(ds, file_name):
"""
This writes the .dat files that generate the intermediate parameters used
by the Igor processing.
Parameters
----------
ds: xarray Dataset
The dataset containing the processed signal data.
file_name: str
The name of the file to save to.
... | 46,680 |
def test_four_who_likes_it_code_wars():
"""Function that emulates test.assert_equals
(likes(['Max', 'John', 'Mark'])."""
from who_likes_it import likes
assert likes(['Max', 'John', 'Mark']) == 'Max, John and Mark like this' | 46,681 |
def docker_volume_exist(volume):
"""Check if the docker-volume exists."""
cmd = "docker volume inspect {0}".format(volume)
status = execute_subprocess(cmd)
return status == 0 | 46,682 |
def test_set_and_unset_launch_configuration_execute():
"""Test the execute() of the SetLaunchConfiguration and UnsetLaunchConfiguration classes."""
lc1 = LaunchContext()
assert len(lc1.launch_configurations) == 0
SetLaunchConfiguration('name', 'value').visit(lc1)
assert len(lc1.launch_configuration... | 46,683 |
def get_embed_similarity(embed1, embed2, sim_measure="euclidean", num_top=None):
"""
Score alignments based on embeddings of two graphs
"""
if embed2 is None:
embed2 = embed1
if num_top is not None and num_top != 0: # KD tree with only top similarities computed
kd_sim = kd_... | 46,684 |
def test_onchain_middleman_their_unilateral_in(node_factory, bitcoind):
""" This is the same as test_onchain_middleman, except that
node l1 drops to chain, not l2, reversing the unilateral
handling logic """
# We track channel balances, to verify that accounting is ok.
coin_mvt_plugin = os.p... | 46,685 |
def get_ingredientes():
"""
Devuelve una lista de todos los ingredientes.
"""
logger.info("IP: %s\n" % request.environ['REMOTE_ADDR'] +
"Devuelve lista completa de los ingredientes")
try:
cx = db.connect()
ings = bocadillos.get_ings_all(cx)
cx.close()
... | 46,686 |
def pathmatch(path, patterns):
"""
Test whether the ``path`` string matches any of the strings in ``patterns``.
``path`` can be a relative file path, with both its basename and absolute
path also tested against ``patterns``.
:param path: The file path to test.
:param patterns: An iterable o... | 46,687 |
def preprocess_meta_data():
""" preprocess the config for specific run:
1. reads command line arguments
2. updates the config file and set gpu config
3. configure gpu settings
4. define logger.
"""
args = get_args()
config = read_config(args)
gpu_in... | 46,688 |
def calc_water(scenario, years, days_in_year):
"""Calculate Water costs Function
Args:
scenario (object): The farm scenario
years (int): The no. of years the simulation will analyse
days_in_year (float): The number of days in a year
Returns:
cogs_water (list): Cost of Goods So... | 46,689 |
def vit_large_patch32_224_in21k(pretrained=False, **kwargs):
""" ViT-Large model (ViT-L/32) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(
patch_size=32,
embed_... | 46,690 |
def test_md027_bad_block_quote_setext_heading_multiples_last_misaligned():
"""
Test to make sure we get the expected behavior after scanning a good file from the
test/resources/rules/MD026 directory that has atx headings that do not end with
punctuation.
"""
# Arrange
scanner = MarkdownScan... | 46,691 |
def _check_template(hass, value_template):
""" Checks if result of template is true """
try:
value = template.render(hass, value_template, {})
except TemplateError:
_LOGGER.exception('Error parsing template')
return False
return value.lower() == 'true' | 46,692 |
def test_load_startup_script_3(tmp_path, reset_sys_modules): # noqa: F811
"""
Test for ``load_startup_script`` function.
Verifies if variables defined in global and local scope in the script are handled correctly.
"""
# Load first script
script_dir = os.path.join(tmp_path, "script_dir1")
sc... | 46,693 |
def test_octree_partition_accept():
"""
if the population of a NestedOctree search space _within the buffered bounds of the region of
interest_ is acceptable, then it should create only one partition.
if it has only one partition, then why call it an octree?
"""
# build a query set and two sea... | 46,694 |
def _snr_single_region(spectrum, region=None):
"""
Calculate the mean S/N of the spectrum based on the flux and uncertainty
in the spectrum.
Parameters
----------
spectrum : `~specutils.spectra.spectrum1d.Spectrum1D`
The spectrum object overwhich the equivalent width will be calculated.... | 46,695 |
def getFusedSimilarity(filename, sr, hop_length, win_fac, wins_per_block, K, reg_diag, reg_neighbs, niters, do_animation, plot_result, do_crema=True):
"""
Load in filename, compute features, average/stack delay, and do similarity
network fusion (SNF) on all feature types
Parameters
----------
fi... | 46,696 |
def plot_results():
"""Creates a stacked bar chart of the results"""
plot_array = Nuts3_Area.loc[:,Nuts3_Area.columns.str.startswith('perc_')].to_numpy()
plot_array_T = plot_array.T # invert columns and rows
label_array = Nuts3_Area['NUTS_NAME_left'] #to get NUTS3 units to label x-axis
colors... | 46,697 |
def squared_error(
prediction: chex.Array,
targets: chex.Array,
weight: float = 1.0,
# register_loss: bool = True,
) -> chex.Array:
"""Squared error loss."""
if prediction.shape != targets.shape:
raise ValueError("prediction and targets should have the same shape.")
# if register_loss:
kfac_... | 46,698 |
def add_vqe_exact(params):
"""Add the ground states to the dict"""
ex = run_exact(params["operator"])
vq = run_vqe(params["operator"])
return {**params, **vq, **ex} | 46,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.