content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_border_mask(input_data, target, max_dist, background_label,axis=0):
"""
Overlay a border mask with background_label onto input data.
A pixel is part of a border if one of its 4-neighbors has different label.
Parameters
----------
input_data : h5py.Dataset or numpy.ndarray - Input... | 25,000 |
def femda_estimator(X, labels, eps = 1e-5, max_iter = 20):
""" Estimates the matrix of means and the tensor of scatter matrix of the dataset using MLE estimator.
To tackle singular matrix issues, we use regularization.
Parameters
----------
X : 2-d array of size n*m
... | 25,001 |
def get_collections():
"""read .db file, return raw collection"""
col = {}
f = open(collection_db, "rb")
version = nextint(f)
ncol = nextint(f)
for i in range(ncol):
colname = nextstr(f)
col[colname] = []
for j in range(nextint(f)):
f.read(2)
... | 25,002 |
def ot_has_small_bandgap(cp2k_input, cp2k_output, bandgap_thr_ev):
""" Returns True if the calculation used OT and had a smaller bandgap then the guess needed for the OT.
(NOTE: It has been observed also negative bandgap with OT in CP2K!)
cp2k_input: dict
cp2k_output: dict
bandgap_thr_ev: float [eV]... | 25,003 |
def _run(top_narr_dir_name, top_front_line_dir_name, top_wpc_bulletin_dir_name,
first_time_string, last_time_string, pressure_level_mb,
thermal_field_name, thermal_colour_map_name,
max_thermal_prctile_for_colours, first_letter_label, letter_interval,
output_dir_name):
"""Plots pr... | 25,004 |
def fuzz_and_reduce_bug(
active_device: str,
seed: int,
check_result: Callable[[], None],
settings: Optional[Settings] = None,
ignored_signatures: Optional[List[str]] = None,
) -> None:
"""
Fuzz, find a bug, reduce it.
Linux only.
"""
# Test only works on Linux.
if util.get_... | 25,005 |
def test_generate_ticket(user):
"""Test a ticket from a valid user and a spam bot."""
ticket = generate_ticket(user)
assert ticket == user.expected_output | 25,006 |
def profile():
"""Checking if user is already logged_in"""
if 'logged_in' in session:
'''getting all the account info for the user for displaying it on the profile page'''
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE usern... | 25,007 |
def gather_metrics(config, worker_output, endpoint_output, container_names):
"""Process the raw output to lists of dicts
Args:
config (dict): Parsed configuration
worker_output (list(list(str))): Output of each container ran on the edge
endpoint_output (list(list(str))): Output of each ... | 25,008 |
async def ping(ws):
"""Send a ping request on an established websocket connection.
:param ws: an established websocket connection
:return: the ping response
"""
ping_request = {
'emit': "ping",
'payload': {
'timestamp': int(time.time())
}
}
await ws.se... | 25,009 |
def split_files_each_proc(file_arr,nprocs):
""" Returns array that distributes samples across all processors. """
ntot = len(file_arr)
post_proc_file_arr = []
for i in range(0,nprocs):
each_proc_arr = []
ib,ie = split_array_old(ntot,nprocs,i)
if i... | 25,010 |
def get_data_generators_for_output(output):
""" Get the data generators involved in an output
Args:
output (:obj:`Output`): report or plot
Returns:
:obj:`set` of :obj:`DataGenerator`: data generators involved in the output
"""
data_generators = set()
if isinstance(output, Repo... | 25,011 |
def MarkovChainFunction(data, bins):
""" Data should be numpy array; bins is an integer """
#Normalize data
datMin = min(data)
datMax = max(data)
datNorm = (data - datMin)/(datMax - datMin)
# Create Markov Transition Table:
mesh = np.linspace(0, 1, bins)
meshReal = (mesh*(datMa... | 25,012 |
def clustering_report(y_true, y_pred) -> pd.DataFrame:
"""
Generate cluster evaluation metrics.
Args:
y_true: Array of actual labels
y_pred: Array of predicted clusters
Returns:
Pandas DataFrame with metrics.
"""
return pd.DataFrame(
{
"Homogeneity"... | 25,013 |
def _create_sampler_data(
datastores: List[Datastore], variables: Sequence[Variable],
preconditions: Set[LiftedAtom], add_effects: Set[LiftedAtom],
delete_effects: Set[LiftedAtom], param_option: ParameterizedOption,
datastore_idx: int
) -> Tuple[List[SamplerDatapoint], List[SamplerDatapoint]]:
"""Ge... | 25,014 |
def call_assign_job(job_id, mex_id):
""" Function to send an update to the MEx Sentinel to assign a Job to an MEx. """
try:
rospy.wait_for_service('/mex_sentinel/assign_job_to_mex', rospy.Duration(1))
try:
assign_job = rospy.ServiceProxy('mex_sentinel/assign_job_to_mex', AssignJobToM... | 25,015 |
def full(
coords, nodata=np.nan, dtype=np.float32, name=None, attrs={}, crs=None, lazy=False
):
"""Return a full DataArray based on a geospatial coords dictionary.
Arguments
---------
coords: sequence or dict of array_like, optional
Coordinates (tick labels) to use for indexing along each d... | 25,016 |
def calculate_alignment(
sequences, mode, matrix, gapopen, gapextend, hash=uuid4().hex):
"""
1 - remove modifications
2 - convert sequence
3 - muscle - msa
4 - revert sequences
5 - add original modifications
"""
new_file_lines = []
for i, element in enumerate(sequences):
... | 25,017 |
def add_weight_decay(
model: nn.Module, weight_decay: float = 1e-5, skip_list: Union[List, Tuple] = ()
) -> List[Dict]:
"""Helper function to not decay weights in BatchNorm layers
Source: https://discuss.pytorch.org/t/weight-decay-in-the-optimizers-is-a-bad-idea-especially-with-batchnorm/16994/3
"""
... | 25,018 |
def find_bands_hdu(hdu_list, hdu):
"""Discover the extension name of the BANDS HDU.
Parameters
----------
hdu_list : `~astropy.io.fits.HDUList`
hdu : `~astropy.io.fits.BinTableHDU` or `~astropy.io.fits.ImageHDU`
Returns
-------
hduname : str
Extension name of the BANDS HDU. N... | 25,019 |
def read_raw_binary_file(file_path):
"""can actually be any file"""
with open(file_path, 'rb') as f:
return f.read() | 25,020 |
def encode_cl_value(entity: CLValue) -> dict:
"""Encodes a CL value.
"""
def _encode_parsed(type_info: CLType) -> str:
if type_info.typeof in TYPES_NUMERIC:
return str(int(entity.parsed))
elif type_info.typeof == CLTypeKey.BYTE_ARRAY:
return entity.parsed.hex()
... | 25,021 |
def escape(string):
""" Escape a passed string so that we can send it to the
regular expressions engine.
"""
ret = None
def replfunc(m):
if ( m[0] == "\\" ):
return("\\\\\\\\")
else:
return("\\\\" + m[0])
# @note - I had an issue getting replfunc to be ca... | 25,022 |
def batch_apply(fn, inputs):
"""Folds time into the batch dimension, runs fn() and unfolds the result.
Args:
fn: Function that takes as input the n tensors of the tf.nest structure,
with shape [time*batch, <remaining shape>], and returns a tf.nest
structure of batched tensors.
inputs: tf.nest s... | 25,023 |
def grab_haul_list(creep: Creep, roomName, totalStructures, add_storage=False):
"""
μμ νμΈλ¬κ° μλμ§λ₯Ό μ±μΈ λͺ©λ‘ νμΈ.
:param creep:
:param roomName: λ°©μ΄λ¦.
:param totalStructures: λ³Έλ¬Έ all_structures μ λμΌ
:param add_storage: μ€ν 리μ§λ₯Ό ν¬ν¨ν κ²μΈκ°? priority == 0 μΈ μν© μλλ©΄ ν¬ν¨ν μΌμ΄ μμ.
:return: νμΈλ¬μ μλμ§ μ±μΈ λμλͺ©λ‘
"""... | 25,024 |
def data_static(filename):
"""
Get files
:param filename:
:return:
"""
_p, _f = os.path.split(filename)
# print(_p, _f)
return flask.send_from_directory(os.path.join(config['path']['path_data'], _p), _f) | 25,025 |
def target(x, seed, instance):
"""A target function for dummy testing of TA
perform x^2 for easy result calculations in checks.
"""
# Return x[i] (with brackets) so we pass the value, not the
# np array element
return x[0] ** 2, {'key': seed, 'instance': instance} | 25,026 |
def generate(fspec, count, _fuel=None):
"""Generate <count> number of random passwords/passphrases.
The passphrases are formated according to <fspec>.
Returned value is (list, json_data),
where list is a <count>-element sequence of
pair of (password, reading hint for password).
json_da... | 25,027 |
def convert_to_valid_einsum_chars(einsum_str):
"""Convert the str ``einsum_str`` to contain only the alphabetic characters
valid for numpy einsum.
"""
# partition into valid and invalid sets
valid, invalid = set(), set()
for x in einsum_str:
(valid if is_valid_einsum_char(x) else invalid... | 25,028 |
def prop_GAC(csp, newVar=None):
"""
Do GAC propagation. If newVar is None we do initial GAC enforce
processing all constraints. Otherwise we do GAC enforce with
constraints containing newVar on GAC Queue
"""
constraints = csp.get_cons_with_var(newVar) if newVar else csp.get_all_cons()
pruned... | 25,029 |
def clone( # pylint: disable=R0913,R0912,R0914
source, target, branch="main", depth=None, delete_git_dir=False,
username=None, password=None, key_filename=None, key_data=None,
track_branch_upstream=True,
):
""" Clone repository """
# Prepare auth args
auth_args = dict()
if usern... | 25,030 |
def submit_only_kwargs(kwargs):
"""Strip out kwargs that are not used in submit"""
kwargs = kwargs.copy()
for key in ['patience', 'min_freq', 'max_freq', 'validation',
"max_epochs", "epoch_boost", "train_size", "valid_size"]:
_ = kwargs.pop(key, None)
return kwargs | 25,031 |
def make_simple_boundary(outline_edge_group: UniqueEdgeList, all_edges: UniqueEdgeList):
"""
Step 3 recursive
:param outline_edge_group: A list of edges, grouped by connectivity between edges.
:param all_edges:
:return: ???
"""
while len(all_edges.edge_list) > 0:
current_edge = all_e... | 25,032 |
def convert_rscape_svg_to_one_line(rscape_svg, destination):
"""
Convert R-scape SVG into SVG with 1 line per element.
"""
output = os.path.join(destination, 'rscape-one-line.svg')
cmd = (r"perl -0777 -pe 's/\n +fill/ fill/g' {rscape_svg} | "
r"perl -0777 -pe 's/\n d=/ d=/g' | "
... | 25,033 |
def getDSSImage(ra,dec,radius=1.0,xsize=800,**kwargs):
"""
Download Digitized Sky Survey images
https://archive.stsci.edu/cgi-bin/dss_form
https://archive.stsci.edu/cgi-bin/dss_search
Image is in celestial orientation (RA increases to the right)
https://archive.stsci.edu/dss/script_usage.h... | 25,034 |
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
job = HassJob(action)
if config[CONF_TYPE] == "turn_on":
entity_id = config[CONF_ENTITY_ID]
@callback
... | 25,035 |
def imread(image_path, as_uint8=True):
"""Read an image as numpy array.
Args:
image_path (str or pathlib.Path):
File path (including extension) to read image.
as_uint8 (bool):
Read an image in uint8 format.
Returns:
:class:`numpy.ndarray`:
Image ... | 25,036 |
async def _update_listener(opp: OpenPeerPower, entry: ConfigEntry):
"""Handle options update."""
await opp.config_entries.async_reload(entry.entry_id) | 25,037 |
def pk(obj):
"""
A helper that gets the primary key of a model instance if one is passed in.
If not, this returns the parameter itself.
This allows functions to have parameters that accept either a primary key
or model instance. For example:
``` python
def get_translations(target_locale):
... | 25,038 |
def auto_link(elements: Iterable[Gst.Element]):
"""
Automatically link a *linear* Iterable of elements together (no tees or
other branching).
note: Won't link sometimes/request pads (for now), but link() could be
patched to so. If you want to submit a PR, this would be a welcome
add... | 25,039 |
def get_dataset(id):
"""Query for existence of dataset by ID."""
uu = UrlUtils()
es_url = uu.rest_url
#es_index = "{}_{}_s1-ifg".format(uu.grq_index_prefix, version)
es_index = "grq"
# query
query = {
"query": {
"wildcard": {
"_id": id
}
}
}
l... | 25,040 |
def bags_with_gold( parents_of, _ ):
"""
Starting from leaf = 'gold', find recursively its parents upto the root and add them to a set
Number of bags that could contain gold = length of the set
"""
contains_gold = set()
def find_roots( bag ):
for outer_bag in parents_of[ bag ]:
... | 25,041 |
def buildCon(filter, testhost):
"""Load the config file and build the connections, then check connecting to the testHost if defined """
global adc
adc.setFilter(filter)
adc.collectInstanceData()
adc.loadConfig()
adc.buildConnections(debug=True)
if ( testhost is not None):
found = Fal... | 25,042 |
def send_mail(sending_email, sending_password, list_emails, subject, html_file):
"""
Send a mail to a list of emails. The body is an html
formated file template.
"""
# Creating the server, and handling all connections steps
server = smtplib.SMTP('smtp.gmail.com', 587)
serv... | 25,043 |
def test_director_exception():
"""Test handling of an exception raised in a director.
"""
db = setup_database()
query = xapian.Query('it')
enq = xapian.Enquire(db)
enq.set_query(query)
class TestException(Exception):
def __init__(self, a, b):
Exception.__init__(self, a +... | 25,044 |
def create(project, schema, roles):
"""Create system DB schema, if not exists."""
engine, _ = project_engine(project)
DB.ensure_schema_exists(engine, schema, grant_roles=roles) | 25,045 |
def process_file(file_path):
"""
This function processes the submitted file
:return: A dictionary of errors found in the file. If there are no errors,
then only the error report headers will in the results.
"""
enc = detect_bom_encoding(file_path)
if enc is None:
with open(file_path... | 25,046 |
def setup_package():
"""Setup the environment for testing diff_local."""
global TEST_WORKSPACE
TEST_WORKSPACE = env.get_workspace('diff_local')
# Set the TEST_WORKSPACE used by the tests.
os.environ['TEST_WORKSPACE'] = TEST_WORKSPACE
test_config = {}
test_project = 'cpp'
project_inf... | 25,047 |
def get_request_body(text, api_key, *args):
"""
send a request and return the response body parsed as dictionary
@param text: target text that you want to detect its language
@type text: str
@type api_key: str
@param api_key: your private API key
"""
if not api_key:
raise Excep... | 25,048 |
def generate_sample_task(project):
""" Generate task example for upload and check it with serializer validation
:param project: project with label config
:return: task dict
"""
task = generate_sample_task_without_check(project.label_config)
# check generated task
'''if project:
try... | 25,049 |
def entry_point():
"""Basic entrypoint for cortex subcommands"""
pass | 25,050 |
async def test_sensor_registry(
hass, mqtt_client_mock, mqtt_mock, mock_phoniebox, config
):
"""Test that a new sensor is created"""
entity_registry = er.async_get(hass)
er_items_before = er.async_entries_for_config_entry(
entity_registry, mock_phoniebox.entry_id
)
async_fire_mqtt_messa... | 25,051 |
def serializable_value(self, field_name):
"""
Returns the value of the field name for this instance. If the field is
a foreign key, returns the id value, instead of the object. If there's
no Field object with this name on the model, the model attribute's
value is returned directly.
Used to seri... | 25,052 |
def fetch_fi2010(normalization=None) -> pandas.DataFrame:
"""
Load the FI2010 dataset with no auction.
Benchmark Dataset for Mid-Price Forecasting of Limit Order Book Data with Machine
Learning Methods. A Ntakaris, M Magris, J Kanniainen, M Gabbouj, A Iosifidis.
arXiv:1705.03233 [cs.CE]. https://a... | 25,053 |
def get_netcdf_filename(batch_idx: int) -> str:
"""Generate full filename, excluding path."""
assert 0 <= batch_idx < 1e6
return f"{batch_idx:06d}.nc" | 25,054 |
def CreateBoardConfigs(site_config, boards_dict, ge_build_config):
"""Create mixin templates for each board."""
# Extract the full list of board names from GE data.
separate_board_names = set(config_lib.GeBuildConfigAllBoards(ge_build_config))
unified_builds = config_lib.GetUnifiedBuildConfigAllBuilds(ge_build_... | 25,055 |
def area_calc(radius, point_in, total_points):
"""Calculates the partial area of ball
:param radius: radius of ball
:param point_in: points of the total points to include
:param total_points: number of sampled points
:return: area
"""
return (4 * pi * radius ** 2) * (point_in / total_... | 25,056 |
def results_framework_export(request, program):
"""Returns .XLSX containing program's results framework"""
program = Program.rf_aware_objects.get(pk=program)
wb = openpyxl.Workbook()
wb.remove(wb.active)
ws = wb.create_sheet(gettext("Results Framework"))
get_font = lambda attrs: styles.Font(**{*... | 25,057 |
def generate_subwindow(pc, sample_bb, scale, offset=2, oriented=True):
"""
generating the search area using the sample_bb
:param pc:
:param sample_bb:
:param scale:
:param offset:
:param oriented: use oriented or axis-aligned cropping
:return:
"""
rot_mat = np.transpose(sample_b... | 25,058 |
def save_agent(agent, algorithm, policy, run_name):
""" Saves the state dict of an agent to file """
if algorithm in ["mcts", "lfd", "lfd-mcts"] and policy == "nn" and agent is not None:
filename = f"./data/runs/{run_name}/model.pty"
logger.info(f"Saving model at {filename}")
torch.save... | 25,059 |
def augmented_print(text, file, flush=False):
"""Print to both the standard output and the given file."""
assert isinstance(text, str)
print(text)
file.write(text + "\n")
if flush:
sys.stdout.flush()
file.flush() | 25,060 |
def close_swift_conn(src):
"""
Force close the http connection to the backend.
:param src: the response from the backend
"""
try:
# Since the backends set "Connection: close" in their response
# headers, the response object (src) is solely responsible for the
# socket. The c... | 25,061 |
def tsfigure(num=None, figsize=None, dpi=None, facecolor=None,
edgecolor=None, frameon=True, subplotpars=None,
FigureClass=TSFigure):
"""
Creates a new :class:`TimeSeriesFigure` object.
Parameters
----------
num : {None, int}, optional
Number of the figure.
... | 25,062 |
def load_predict_result(predict_filename):
"""Loads the file to be predicted"""
predict_result = {}
ret_code = SUCCESS
try:
predict_file_zip = zipfile.ZipFile(predict_filename)
except:
ret_code = FILE_ERROR
return predict_result, ret_code
for predict_file in predict_file_... | 25,063 |
def localize_all(roi, ignore_exception=True, **kwargs):
""" localize all variable local sources in the roi, make TSmaps and associations if requested
ignore if extended -- has 'spatial_model'
kwargs can have prefix to select subset with name starting with the prefix, e.g. 'SEED'
"""
tsmin =... | 25,064 |
def test_map_lambda_as_element():
"""Test that a map lambda is held as a single element"""
stack = run_vyxal("β½Ζ1+;M", inputs=[[[1, 2], [3, 4]]])
assert stack[-1] == [[2, 3], [4, 5]] | 25,065 |
def convert_post_to_VERB(request, verb):
"""
Force Django to process the VERB.
"""
if request.method == verb:
if hasattr(request, '_post'):
del(request._post)
del(request._files)
try:
request.method = "POST"
request._load_post_and_files()
... | 25,066 |
def close(x, y, rtol, atol):
"""Returns True if x and y are sufficiently close.
Parameters
----------
rtol
The relative tolerance.
atol
The absolute tolerance.
"""
# assumes finite weights
return abs(x-y) <= atol + rtol * abs(y) | 25,067 |
def add_unknown_words(word_vecs, vocab, min_df=1, k=300):
"""
For words that occur in at least min_df sentences, create a separate word vector.
0.25 is chosen so the unknown vectors have (approximately) same variance as pre-trained ones
"""
for word in vocab:
if word not in word_vecs and... | 25,068 |
def plot_precip_field(
precip,
ptype="intensity",
ax=None,
geodata=None,
units="mm/h",
bbox=None,
colorscale="pysteps",
probthr=None,
title=None,
colorbar=True,
axis="on",
cax=None,
map_kwargs=None,
**kwargs,
):
"""
Function to plot a precipitation intensi... | 25,069 |
def get_for_repo(repo, name, default=None):
"""Gets a configuration setting for a particular repository. Looks for a
setting specific to the repository, then falls back to a global setting."""
NOT_FOUND = [] # a unique sentinel distinct from None
value = get(name, NOT_FOUND, repo)
if value is NOT_... | 25,070 |
def new_user(tenant: AnyStr, password: AnyStr) -> bool:
"""Return a boolean containing weither a new tenant is created or no."""
if not query.get_tenant_id(tenant):
return True
return False | 25,071 |
def home():
"""
Home page control code
:return Rendered page:
"""
error = request.args.get("error", None)
state, code = request.args.get("state", None), request.args.get("code", None)
if code and not has_user() and 'state' in session and session['state'] == state:
tok = reddit_get_access_t... | 25,072 |
def build_and_save_df():
"""Assembles all data together into a pandas DataFrame
and saves as csv.
Saves
----------------
elem_dict:
dict
Dictionary of mapping stoich vector to elements
magpie_embed:
dict
Dictionary mapping precursors to magpie embeddings (for use ... | 25,073 |
def get_date_list(num_days):
"""
For an integer number of days (num_days), get an ordered list of
DateTime objects to report on.
"""
local_tz = tzlocal.get_localzone()
local_start_date = local_tz.localize(datetime.datetime.now()).replace(hour=0, minute=0, second=0, microsecond=0) - datetime.time... | 25,074 |
def is_even(val):
"""
Confirms if a value if even.
:param val: Value to be tested.
:type val: int, float
:return: True if the number is even, otherwise false.
:rtype: bool
Examples:
--------------------------
.. code-block:: python
>>> even_numbers = list(filter(is_even, ran... | 25,075 |
def get_fremont_data(filename = "Fremont.csv", url = URL, force_download = False):
""" Download and cache the fremont data
Parameters
----------
csv file Fremont.csv
url URL
force download
Returns
-------
data : pandas dataframe
"""
if force_dow... | 25,076 |
def min_spacing(mylist):
"""
Find the minimum spacing in the list.
Args:
mylist (list): A list of integer/float.
Returns:
int/float: Minimum spacing within the list.
"""
# Set the maximum of the minimum spacing.
min_space = max(mylist) - min(mylist)
# Iteratively find ... | 25,077 |
def extract_dawn_compiler_options() -> list:
"""Generate options_info for the Dawn compiler options struct."""
options_info = []
regex = re.compile(r"OPT\(([^,]+), ?(\w+)")
DAWN_CPP_SRC_ROOT = os.path.join(
os.path.dirname(__file__), os.pardir, os.pardir, "src", "dawn"
)
# Extract info... | 25,078 |
def sign(x):
"""Return the mathematical sign of the particle."""
if x.imag:
return x / sqrt(x.imag ** 2 + x.real ** 2)
return 0 if x == 0 else -1 if x < 0 else 1 | 25,079 |
def wrap_strings(lines: [str], line_width: int):
"""Return a list of strings, wrapped to the specified length."""
i = 0
while i < len(lines):
# if a line is over the limit
if len(lines[i]) > line_width:
# (try to) find the rightmost occurrence of a space in the first 80 chars
... | 25,080 |
def test_deprecated_section():
"""Parse deprecated section."""
docstring = """
Deprecated
----------
1.23.4
Deprecated.
Sorry.
"""
sections, _ = parse(docstring)
assert len(sections) == 1
assert sections[0].value.version == "1.23.4"
assert sec... | 25,081 |
def has_even_parity(message: int) -> bool:
""" Return true if message has even parity."""
parity_is_even: bool = True
while message:
parity_is_even = not parity_is_even
message = message & (message - 1)
return parity_is_even | 25,082 |
def is_primitive(structure):
"""
Checks if a structure is primitive or not,
:param structure: AiiDA StructureData
:return: True if the structure can not be anymore refined.
prints False if the structure can be futher refined.
"""
refined_cell = find_primitive_cell(structure)
prim = Fals... | 25,083 |
def mock_mkdir(monkeypatch):
"""Mock the mkdir function."""
def mocked_mkdir(path, mode=0o755):
return True
monkeypatch.setattr("charms.layer.git_deploy.os.mkdir", mocked_mkdir) | 25,084 |
def validate_run_items(run_items):
"""
Check the validity of classical addresses / qubits for the payload.
:param list|range run_items: List of classical addresses or qubits to be validated.
"""
if not isinstance(run_items, (list, range)):
raise TypeError("run_items must be a list")
if ... | 25,085 |
def test_jsd1():
""" Test the JSD of a distribution with itself """
d1 = Distribution("AB", [0.5, 0.5])
jsd = JSD([d1, d1])
assert_almost_equal(jsd, 0) | 25,086 |
def add_worker():
"""Increase the number of your Gunicorn workers"""
set_env_defaults()
if not gunicorn_running():
puts(colors.red("Gunicorn isn't running!"))
return
puts(colors.green('Increasing number of workers...'))
run('kill -TTIN `cat %s`' % (env.gunicorn_pidpath))
puts(co... | 25,087 |
async def setup(mass) -> None:
"""Perform async setup of this Plugin/Provider."""
prov = FanartTvProvider(mass)
await mass.register_provider(prov) | 25,088 |
def zip_dir_recursively(base_dir, zip_file):
"""Zip compresses a base_dir recursively."""
zip_file = zipfile.ZipFile(zip_file, 'w', compression=zipfile.ZIP_DEFLATED)
root_len = len(os.path.abspath(base_dir))
for root, _, files in os.walk(base_dir):
archive_root = os.path.abspath(root)[root_... | 25,089 |
def saferepr(obj, maxsize=240):
"""return a size-limited safe repr-string for the given object.
Failing __repr__ functions of user instances will be represented
with a short exception info and 'saferepr' generally takes
care to never raise exceptions itself. This function is a wrapper
around the Re... | 25,090 |
def figsize(x=9, y=4):
"""Temporarily set the figure size using 'with figsize(a,b):'"""
size = pylab.rcParams['figure.figsize']
set_figsize(x, y)
yield
pylab.rcParams['figure.figsize'] = size | 25,091 |
def filter(pred : Callable[[A], bool], stream : Stream[A]) -> Stream[A]:
"""Filter a stream of type `A`.
:param pred: A predicate on type `A`.
:type pred: `A -> bool`
:param stream: A stream of type `A` to be filtered.
:type stream: `Stream[A]`
:return: A stream of type `A`.
:rtype: `Strea... | 25,092 |
def _get_kernel_size_numel(kernel_size):
"""Determine number of pixels/voxels. ``kernel_size`` must be an ``N``-tuple."""
if not isinstance(kernel_size, tuple):
raise ValueError(f"kernel_size must be a tuple. Got {kernel_size}.")
return _get_numel_from_shape(kernel_size) | 25,093 |
def random():
"""Get a random UUID."""
return str(uuid.uuid4()) | 25,094 |
def printe(s: str, end="\n"):
"""
Print to stderr
"""
sys.stderr.write(s + end) | 25,095 |
def reautorank(reaumur):
""" This function converts Reaumur to rankine, with Reaumur as parameter."""
rankine = (reaumur * 2.25) + 491.67
return rankine | 25,096 |
def list_pets():
"""Shows list of all pets in db"""
pets = Pet.query.all()
return render_template('list.html', pets=pets) | 25,097 |
def test_make_gameshow():
"""Test gameshow factory."""
app = make_gameshow()
assert isinstance(app, GameShow) | 25,098 |
def BundleFpmcuUnittests(chroot, sysroot, output_directory):
"""Create artifact tarball for fingerprint MCU on-device unittests.
Args:
chroot (chroot_lib.Chroot): The chroot containing the sysroot.
sysroot (sysroot_lib.Sysroot): The sysroot whose artifacts are being
archived.
output_directory (st... | 25,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.