content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calc(diff, pool, torment=5, charmed=1):
"""
api call to get the probabilities of a dice pool.
"""
root = wodDice.PoolCalc(pool, diff, torment, charmed)
s = root.summary()
result = {
'pool': pool,
'diff': diff,
'torment': torment,
'charmed': charmed,
'F... | 61,700 |
def update_xml_for_new_img(current_ome_xml_str, new_xyzct, bf_dtype, is_rgb, pixel_physical_size_xyu=None, channel_names=None, perceputally_uniform_channel_colors=False):
"""Update dimensions ome-xml metadata
Used to create a new ome-xml that reflects changes in an image, such as its shape
If `current_ome... | 61,701 |
def url_name(context):
""" Returns URL name of the current request.
Example::
{% url_name as current_url_name %}
{% if current_url_name != 'auth_login' %}
<li>
<a href="{% url 'auth_login_next' request.get_full_path|urlencode %}">
{% trans 'Signin' %}</a>
</... | 61,702 |
def lowest_common_ancestor(G, node1, node2, default=None):
"""Compute the lowest common ancestor of the given pair of nodes.
Parameters
----------
G : NetworkX directed graph
node1, node2 : nodes in the graph.
default : object
Returned if no common ancestor between `node1` and `node2`... | 61,703 |
def cross_entropy(prediction, target):
"""
prediction should be probabilities [N × C], target should be label index (0 ~ C-1)
:param prediction: size: [N, C]
:param target: size: [N]
:return:
"""
return F.cross_entropy(prediction, target) | 61,704 |
def resolve_class(classref):
"""Attempt to return a Python class for the input class reference.
If `classref` is a class or None, return it. If `classref` is a
python classpath (e.g., "foo.bar.MyClass") import the class and return
it.
Args:
classref: A fully-qualified Python path to class,... | 61,705 |
def test_xfailing():
""" example of an xfail test """
assert 2 == 3 | 61,706 |
def nms(bboxes, score_threshold, iou_threshold, sigma=0.3):
"""
:param bboxes:
假设有N个bbox的score大于score_threshold,那么bboxes的shape为(N, 6),存储格式为(xmin, ymin, xmax, ymax, score, class)
其中(xmin, ymin, xmax, ymax)的大小都是相对于输入原图的,score = conf * prob,class是bbox所属类别的索引号
:return: best_bboxes
假设NMS后剩下N个bb... | 61,707 |
def QCLog_Meta():
"""QCLog_Meta() -> MetaObject"""
return _DataModel.QCLog_Meta() | 61,708 |
def nice_Horizons(target, centre, epochs, id_type, refplane='earth'):
"""
Mike Alexandersen
Convenience function to reformat data returned by Horizons
Only require the inputs I actually want to vary.
Return in the format I actually want, not an astropy table.
"""
horizons_table = Horizons(t... | 61,709 |
def policy_iteration(mdp,verbose=0):
"""Solves an MDP by policy iteration"""
U = {s: 0 for s in mdp.states}
pi = {s: random.choice(mdp.actions(s)) for s in mdp.states}
if verbose:
print("Initial random choice:",pi)
iter_count=0
while True:
iter_count+=1
U = policy_ev... | 61,710 |
def test_analyze__analyze_storage__1(zodb_storage, zodb_root):
"""It parses storage and returns result of analysis."""
zodb_root['obj'] = Example(
binary_string=b'bär',
unicode_string=u'föö',
reference=Example(binary_string=b'bär', unicode_string=u'bümm'))
transaction.commit()
r... | 61,711 |
def calc_contact(scp,sigma_ext):
"""
return (du_da, # distributed stress concentration field along crack, in Pa/m, positive tensile
contact_stress, # physical positive-compression contact stress between crack faces, Pa
displacement) # Physical displacement between crack surfaces; posi... | 61,712 |
def _func_call_cache_key(func, arg_map_function, *args, **kwargs):
"""
Returns a cache key based on the function's module,
the function's name, a stringified list of arguments
and a stringified list of keyword arguments.
"""
arg_map_function = arg_map_function or force_text
converted_args =... | 61,713 |
def thermal_conductivity_carbon_steel(temperature):
"""
DESCRIPTION:
[BS EN 1993-1-2:2005, 3.4.1.3]
PARAMETERS:
OUTPUTS:
REMARKS:
"""
temperature += 273.15
if 20 <= temperature <= 800:
return 54 - 0.0333 * temperature
elif 800 <= temperature <= 120... | 61,714 |
def reshape_image(frame, model):
"""
reshape_image:
Reshaping the camera input frame to fit the model
"""
image = frame.copy()
image = tf.image.resize_with_pad( np.expand_dims(image, axis=0), model.input_dim[0], model.input_dim[1] )
input_image = tf.cast(image, dtype=tf.float32)
... | 61,715 |
def _get_func_signature(func):
"""
Given a function or method, return its signature.
For example:
1 function::
def func(a, b='a', *args):
xxxx
get_func_signature(func) # 'func(a, b='a', *args)'
2 method::
class Demo:
def __init__(self):
... | 61,716 |
def get_password():
"""
:return: the password of the user (needed for lid)
"""
global _password
return _password | 61,717 |
def _file(*args):
""" Wrapper around os.path.join and os.makedirs."""
filename = os.path.join(*args)
_makedirs_for_file(filename)
return filename | 61,718 |
def get_chosen_table_size(input_text: str, get: Callable[[str], QWidget]) -> Tuple[int, int]:
"""
Returns chosen table size from gui according to given input text
"""
if len(input_text) <= 0:
return (0, 0)
sizes, _ = get_potential_table_sizes(len(input_text))
return sizes[get('arraySi... | 61,719 |
def _list(apis):
"""List configured apps."""
response = restclient.get(apis, _APP_REST_PATH)
cli.out(_FORMATTER(response.json())) | 61,720 |
def get_scheme(url):
"""
Get the scheme from a URL, if the URL is valid.
Parameters:
url: A :term:`native string`.
Returns:
The scheme of the url as a :term:`native string`, or ``None`` if the
URL was invalid.
"""
try:
return urlparse(url).scheme
except Valu... | 61,721 |
def fast_inverse_hadamard_transform(k, dist):
"""Performs inverse Hadamard transform."""
if k == 1:
return dist
dist1 = dist[0:k // 2]
dist2 = dist[k // 2:k]
trans1 = fast_inverse_hadamard_transform(k // 2, dist1)
trans2 = fast_inverse_hadamard_transform(k // 2, dist2)
trans = np.concatenate((trans1 +... | 61,722 |
def update_maturity_index (db, cl, nodeid, old_values, is_new = False) :
""" Reactor to update maturity index for all predecessors. We walk
the predecessor chain, if the maturity_index is undefined, we
compute it via all the children, otherwise we do a simple update
with the changed maturity... | 61,723 |
def get_chaincode(org1_gw):
""" Gets chaincode in default gw """
yield org1_gw.chaincode | 61,724 |
def putListIntoInt(inList, base = 2):
"""takes a list of values and converts it into an int"""
string = "".join(str(i) for i in inList)
return int(string, base) | 61,725 |
def parse_money(s: str, *, unit="円") -> int:
"""Parse amount of money en JPY.
The unit of string ("円" or "万円") can be chosen the to apply
the appropriate conversion to JPY units.
"""
if s == "-":
return 0
multipliers_by_unit = {"円": 1, "万円": 10000}
pattern = rf"(\d*[.]?\d+){unit}"
... | 61,726 |
def false_pred():
"""Returns a predicate that always returns ``False``."""
def new_pred(*args):
return False
return new_pred | 61,727 |
def image( session ) -> None :
""" Build image.
"""
if ( os.path.exists( 'dockerfile' ) ) :
dist( session )
try :
session.run( 'az', 'acr', 'login', '--name', 'ecaregistry' )
except Exception :
pass
session.run( 'docker', 'build', '--tag', repository... | 61,728 |
def DeferredLightResolveAddShadowManager(builder, shadowManager):
"""This method is deprecated. Please switch to AddShadowManager."""
return AddShadowManager(builder, shadowManager) | 61,729 |
def calculate_speech_ratio(vad):
"""Calculate percentage of time when each speaker is active"""
speaker1 = np.sum(vad[:, 0]) / vad.shape[0]
speaker2 = np.sum(vad[:, 1]) / vad.shape[0]
speakers = speaker1 + speaker2
return np.array([[speaker1 / speakers, speaker2 / speakers], [speaker1, speaker2]]) | 61,730 |
def get_leaves(conn, category, attached_db="", tbl=""):
"""returns a list of 'category' objects in attached_db
[objectCode, objectLabel, Definition, 'sub-level']
"""
# create formatting shortcuts
def f(t):
return ('"%s"' % t.replace('"', '""')) if t != "" else t
def d(t):
return... | 61,731 |
def start_session(file_name='appdata.db', echo=False):
""" 既存のデータベースを使ってセッション開始 """
db_engine = create_engine('sqlite:///' + file_name, echo=echo)
metadata = Base.metadata
Session = sessionmaker(bind=db_engine)
return Session() | 61,732 |
def txs_to_fasta(txs, filename, truncate=0):
"""
Write reads to file in FASTQ format, with names indexed by UTR.
:param txs: list of strings representing transcripts with alternative 3' UTRs
:param filename: FASTA file
:param truncate: size of output transcripts, measured from 3' end
:return: N... | 61,733 |
def process_NNC(chrom, positions, strand, edge_IDs, vertex_IDs, transcript_dict,
gene_starts, gene_ends, edge_dict, locations, vertex_2_gene, run_info):
""" Novel not in catalog case """
novelty = []
start_end_info = {}
gene_ID = find_gene_match_on_vertex_basis(
vertex_IDs, str... | 61,734 |
def density_angle(rho0: Density, rho1: Density) -> float:
"""The Fubini-Study angle between density matrices"""
rho1 = rho1.permute(rho0.qubits)
return fubini_study_angle(rho0.tensor, rho1.tensor) | 61,735 |
def fake_run_vasp(
ref_path: Union[str, Path],
incar_settings: Sequence[str] = tuple(),
check_inputs: Sequence[Literal["incar", "kpoints", "poscar", "potcar"]] = vfiles,
clear_inputs: bool = True,
):
"""
Emulate running VASP and validate VASP input files.
Parameters
----------
ref_p... | 61,736 |
def forward_solve(eqns, knowns, branching=False):
"""Returns a dict of unknowns:solutions from a simple backward solve.
Does a simple backward solver for a list of eqn given a list of unknowns.
Each equation should be an expression that equals zero. If an unknown is
not solved for, then its entr... | 61,737 |
def test_is_binary_array(input_array: np.ndarray, expected: bool) -> None:
"""
Test is_binary_array function
"""
assert image_util.is_binary_array(input_array) == expected | 61,738 |
def test_struct_comparison(source):
"""
(struct glass (width height) #:transparent #:mutable)
(struct lead (width height))
(define slab (lead 1 2))
(let* ([glass_test (equal? (glass 1 2) (glass 1 2))]
[slab (lead 1 2)]
[lead_test1 (equal? slab slab)]
[lead_test2 (eq... | 61,739 |
def test_auto_download_after_task_completed(rayvision_download, task_id_list,
max_speed, sleep_time,
expected_result, mocker):
"""Test auto_download_after_task_completed, we can get a expected result."""
mocker_task_id = moc... | 61,740 |
def _covariance_diag(matrix, dof, mem_threshold=(10**9)/8):
"""
computes the sample covariance matrix from a 2d-array.
matrix should be demeaned before!
Computes an optimal shrinkage estimate of a sample covariance matrix
as described by the following publication:
Schäfer, J., & Strimmer, K. (... | 61,741 |
def _testMetadataPadding(data, reporter):
"""
- The padding must be null.
"""
header = unpackHeader(data)
if not header["metaOffset"] or not header["privOffset"]:
return
paddingLength = calcPaddingLength(header["metaLength"])
if not paddingLength:
return
paddingOffset = h... | 61,742 |
def test_compute_Sv_ek80_CW_complex(ek80_path):
"""Test calibrate CW mode data encoded as complex samples."""
ek80_raw_path = str(
ek80_path.joinpath('ar2.0-D20201210-T000409.raw')
) # CW complex
echodata = ep.open_raw(ek80_raw_path, sonar_model='EK80')
ds_Sv = ep.calibrate.compute_Sv(
... | 61,743 |
def get_index_of_quantile(dist_mat: np.ndarray, quantile: float):
"""Returns index of `quantile` in `dist_mat`.
Args:
dist_mat (np.ndarray): square distance matrix
quantile (float): quantile
Returns:
index (int): index of quantile
"""
flat_dist_mat = dist_mat.flatten()
... | 61,744 |
def RefineBlock(high_inputs=None,low_inputs=None):
"""
A RefineNet Block which combines together the ResidualConvUnits,
fuses the feature maps using MultiResolutionFusion, and then gets
large-scale context with the ResidualConvUnit.
Arguments:
high_inputs: The input tensors that have the high... | 61,745 |
def process_get_account_transactions(
status: int,
json: list,
network_type: models.NetworkType,
) -> typing.Sequence[models.Transaction]:
"""
Process the "/account/{public_key}/transactions" HTTP response.
:param status: Status code for HTTP response.
:param json: JSON data for response me... | 61,746 |
def psi4(input_data):
"""
Runs Psi4 in API mode
"""
# Insert API path if needed
psiapi = config.get_config("psi_path")
if (psiapi is not None) and (psiapi not in sys.path):
sys.path.insert(1, psiapi)
try:
import psi4
except ImportError:
raise ImportError("Could ... | 61,747 |
def in_struct(ln,FO,nesting=0):
"""Copy a top level structure over to the #define output, keeping track of
nested structures."""
if nesting == 0:
if re.match(r"(}.*);",ln):
FO.write(ln[:-1] + "\n\n");
return find_struct;
FO.write(ln + " \\\n");
if ln == "struct {" o... | 61,748 |
def __random_positions(max_position):
"""Generates two random different list positions given a max position.
The max position is exclusive.
...
Args:
max_position(integer): The maximum position
"""
[lhs, rhs] = random.sample(range(0, max_position - 1), 2)
return (lhs, rhs) | 61,749 |
def errorEllipse(fit, p1, p2, n=100):
"""
fit is a result from leastsqFit (dict)
p1, p2 are parameters name (str)
n number of point in ellipse (int, default 100)
returns ellipse of errors (x1, x2), computed from the covariance. The n values are centered
around fit['best']['p1'] and fit['best'][... | 61,750 |
def run_scheduled_instances(DryRun=None, ClientToken=None, InstanceCount=None, ScheduledInstanceId=None, LaunchSpecification=None):
"""
Launches the specified Scheduled Instances.
Before you can launch a Scheduled Instance, you must purchase it and obtain an identifier using PurchaseScheduledInstances .
... | 61,751 |
def get_config_directory():
"""Return the directory the config file is located in.
This enables us to use relative paths in config values.
"""
# avoid circular import
from ...commands.stacker import Stacker
command = Stacker()
namespace = command.parse_args()
return os.path.dirname(nam... | 61,752 |
def app_info(app_name):
"""gets app info"""
app_path = app_installed(app_name)
try:
return readPlist(app_path + "/Contents/Info.plist")
except ExpatError:
return | 61,753 |
def upper_case(values: dict, data: StepData):
"""Jedes Wort in der Liste wird komplett in Großbuchstaben geschrieben.
:param values: Werte aus der JSON-Datei
:param data: Daten aus der API
:return:
"""
for idx, key in data.loop_key(values["keys"], values):
value = data.get_data(key, val... | 61,754 |
def create_deployment(inputs,
labels,
blueprint_id,
deployment_id,
rest_client):
"""Create a deployment.
:param inputs: a list of dicts of deployment inputs.
:type inputs: list
:param labels: a list of dicts of depl... | 61,755 |
def _refine_projectlist(response: Dict, Translator=DataFields) -> ProjectList:
"""Parse the project list response.
Args:
response: Ganttic API response
Translator: Description of fields
Returns: project List Pydantic.
"""
return ProjectList(**response) | 61,756 |
def parse(
in_data: Union[str, PathLike, IO],
encoding: str = "utf-8",
results_fname: str = _RESULTS_FNAME,
max_size: int = _MAX_SIZE,
) -> dict:
"""Parses FastQC results into a dictionary.
:param in_data: File handle of a fastqc_data.txt file, or path to a
fastqc_data.txt file, or path... | 61,757 |
def load_dataset(args):
"""
Load UKBB or CIFAR10 datasets
Image centering statistics
/lfs/1/heartmri/coral32/flow_250_tp_AoV_bh_ePAT@c/
max: 192
mean: 27.4613475359
std: 15.8350095314
/lfs/1/heartmri/coral32/flow_250_tp_AoV_bh_ePAT@c_P/
max: 4095
mean: 2... | 61,758 |
def frb_191001():
"""
Bhandari+2020b https://ui.adsabs.harvard.edu/abs/2020arXiv200812488B/abstract
"""
# Taken from Bhandari, Table 1
FRB_191001_coord = SkyCoord("21h33m24.373s -54d44m51.86s", frame='icrs')
frb191001 = frb.FRB('FRB191001', FRB_191001_coord,
507.90 * un... | 61,759 |
def split_sentences(text, delimiter="\n"):
""" Split a text into sentences with a delimiter"""
return re.sub(r"(( /?[.!?])+ )", rf"\1{delimiter}", text) | 61,760 |
def SimpleJobExample(configuration_item_name, userid, userpw=None):
""" Dummy workflow to test the install
Parameters
----------
configuration_item_name: str
the name of the configuration item (ex. "Gabriel")
userid: str
user name on the server side
userpw: str (optional)
... | 61,761 |
def getFPSA3(ChargeSA):
"""The calculation of fractional charged partial negative surface areas
-->FPSA3
"""
temp=0.0
for i in ChargeSA:
temp=temp+i[2]
if temp == 0.0:
return 0.0
else:
return getPPSA3(ChargeSA)/temp | 61,762 |
def setUpModule(): # pylint: disable=invalid-name
"""Initialize a Home Assistant server."""
global hass
hass = get_test_home_assistant()
hass.bus.listen('test_event', lambda _: _)
hass.states.set('test.test', 'a_state')
bootstrap.setup_component(
hass, http.DOMAIN,
{http.DOM... | 61,763 |
def load_FF(data_files, parm_dict, h5_path, verbose=False, loadverbose=True,
average=True, mirror=False):
"""
Generates the HDF5 file given path to data_files and parameters dictionary
Creates a Datagroup FFtrEFM_Group with a single dataset in chunks
Parameters
----------
data_files : list
List of the \*.i... | 61,764 |
def DoG1filter(a, sigma):
"""
Creates 2 1-D gaussian filters.
Parameters
----------
a : half-support of the filter.
sigma: standard deviation.
Notes
-----
2-D DoG filters can be contructed by combining 2 1-D DoG filters separably, in x and y directions
Refere... | 61,765 |
def items_iterator(dictionary):
"""Add support for python2 or 3 dictionary iterators."""
try:
gen = dictionary.iteritems() # python 2
except:
gen = dictionary.items() # python 3
return gen | 61,766 |
def do_permutation(df_reference: pd.DataFrame,
df_future: pd.DataFrame,
seed: int) -> pd.DataFrame:
"""
Conducts a permutation test with the given reference classifications,
future classifications, and seed.
"""
# Permute the reference and future data.
np.... | 61,767 |
def control_game(cmd):
"""
returns state based on command
"""
if cmd.lower() in ("y", "yes"):
action = "pictures"
else:
action = "game"
return action | 61,768 |
def evaluate_metric(logger, pred_labels_list, gt_labels_list, label2class_list, test_classes):
"""
:param pred_labels_list: a list of np array, each entry with shape (n_queries*n_way, num_points).
:param gt_labels_list: a list of np array, each entry with shape (n_queries*n_way, num_points).
:param test... | 61,769 |
def answer_problem(problem):
""" 回答问题 """
problem_context = re.findall(r'(\d+)(\w+)(\d+)', problem)[0]
expression = '%s%s%s' % (problem_context[0], _operators[problem_context[1]], problem_context[2])
return int(eval(expression)) | 61,770 |
def cleaning_history(dev):
"""Query the cleaning history."""
res = dev.clean_history()
click.echo("Total clean count: %s" % res.count)
click.echo("Cleaned for: %s (area: %s m²)" % (res.total_duration,
res.total_area))
click.echo()
for idx, id_ in... | 61,771 |
def Extrema_Curve2dTool_Parabola(*args):
"""
:param C:
:type C: Adaptor2d_Curve2d &
:rtype: gp_Parab2d
"""
return _Extrema.Extrema_Curve2dTool_Parabola(*args) | 61,772 |
def _get_argnames_argvalues(argnames=None, argvalues=None, **args):
"""
:param argnames:
:param argvalues:
:param args:
:return: argnames, argvalues - both guaranteed to be lists
"""
# handle **args - a dict of {argnames: argvalues}
if len(args) > 0:
kw_argnames, kw_argvalues = ... | 61,773 |
def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
"""
Parses an OSM IM vnfd_catalog and insert at DB
:param mydb:
:param tenant_id:
:param vnf_descriptor:
:return: The list of cretated vnf ids
"""
try:
myvnfd = vnfd_catalog.vnfd()
try:
pybindJSONDecoder.load_i... | 61,774 |
def clip(x, a_min, a_max):
"""Clip (limit) the values in an array. Given an interval, values
outside the interval are clipped to the interval edges.
Parameters
----------
x : tvm.Tensor
Input argument.
a_min : int or float
Minimum value.
a_max : int or float
Maximum ... | 61,775 |
def sprints_needed(data):
""" sprints needed """
clus = StackCluster()
for j in range(data[1]):
clus.add_stack(True)
init = int(data[2] / max(data[0]) / data[1])
for j in range(data[1]):
sim = np.random.choice(data[0], init, replace=True)
for k in range(init):
... | 61,776 |
def get_ipo_calendar(from_date: str, to_date: str) -> pd.DataFrame:
"""Get IPO calendar
Parameters
----------
from_date : str
from date (%Y-%m-%d) to get IPO calendar
to_date : str
to date (%Y-%m-%d) to get IPO calendar
Returns
-------
pd.DataFrame
Get dataframe... | 61,777 |
def query_history_k_data_plus(
taskEnum,
frequency,
adjustflag,
load_data_func,
load_data_func_params: dict = None,
):
"""
按照任务表获取历史A股K线数据
"""
fields = _get_fields(frequency)
# ### 登陆系统 ####
lg = bs.login() # noqa
with concurrent.futures.ThreadPoolExecutor() as execut... | 61,778 |
def wait_until_finish(self,interval='30s',timeout=u'30m',verbose=False):
""" Waits until the test finished or timeout
*Notes*: This is a blocking keyword
"""
step = DateTime.convert_time(interval)
BuiltIn().log("Wait (max=%s) until the test finished" % timeout)
if not self._test_id:
Bui... | 61,779 |
def run_trial(rep, num):
"""Sleep for 100 milliseconds, 'num' times; repeat for 'rep' attempts."""
sleep = 'sleep(0.1)'
return min(timeit.repeat(stmt=sleep, setup = 'from time import sleep', repeat=rep, number=num)) | 61,780 |
def cholesky(A):
"""
# A is positive definite mxm
"""
assert A.shape[0] == A.shape[1]
# assert all(A.eigenvals() > 0)
m = A.shape[0]
N = deepcopy(A)
D = ones(*A.shape)
for i in range(m - 1):
for j in range(i + 1, m):
N[j, i] = N[i, j]
D[j, i] = D[i, j]... | 61,781 |
def apply_sprite(image, sprite,w,x,y, angle, ontop = True):
"""
image: array or image like object
sprite: array or image like object
w:int
x:int
y:int
"""
sprite = rotate_image(img = sprite, angle = angle, scale = 1.0)
sprite, y_final = adjust_sprite2head( sprite , w, ... | 61,782 |
def load_embeddings(xlm_path = "data/xlm-embeddings/", save=False):
""" Load data from all tensors into single dataframe"""
# embeddings = pd.concat([
# pd.DataFrame(torch.load(xlm_path+"xlm-embeddings-0_499.pt").data.numpy(), index=range(0,500)),
# pd.DataFrame(torch.load(xlm_path+"xlm-embeddings-500_... | 61,783 |
def test_get_link_by_id_failed(client):
"""
NO ID EXISTS NOW BECAUSE OF PREVIOUS CALL
"""
headers = {
'Authorization': f"Bearer {TOKEN}"
}
res = client.get(
f'{LINKS_MAIN_ROUTE}/{NEW_CREATED_LINK_ID}',
headers=headers
)
assert res.status_code == 404 | 61,784 |
def mock_smile_error(aioclient_mock: AiohttpClientMocker) -> None:
"""Mock the Plugwise Smile server failure for Home Assistant."""
aioclient_mock.get(re.compile(".*"), status=500)
aioclient_mock.put(re.compile(".*"), status=500) | 61,785 |
def create_policy(Content=None, Description=None, Name=None, Type=None):
"""
Creates a policy of a specified type that you can attach to a root, an organizational unit (OU), or an individual AWS account.
For more information about policies and their use, see Managing Organization Policies .
This operati... | 61,786 |
def basic_style(color=None, size=None, opacity=None, stroke_color=None, stroke_width=None):
"""Helper function for quickly creating a basic style.
Args:
color (str, optional): hex, rgb or named color value.
Defaults is '#FFB927' for point geometries and '#4CC8A3' for lines.
size (in... | 61,787 |
def git_errors_message(git_info):
"""Format a list of any git errors to send as slack message"""
git_msg = [
{
"color": "#f2c744", "blocks": [
{
"type": "divider"
},
{
"type": "section", "text": {"type": ... | 61,788 |
def test_atomic_base64_binary_min_length_4_nistxml_sv_iv_atomic_base64_binary_min_length_5_5(mode, save_output, output_format):
"""
Type atomic/base64Binary is restricted by facet minLength with value
74.
"""
assert_bindings(
schema="nistData/atomic/base64Binary/Schema+Instance/NISTSchema-SV... | 61,789 |
def show_settings(window: MainWindow) -> None:
"""Shows the settings dialog and allows the user the change deck specific
settings. Settings are not saved until OK is clicked."""
ui = window.ui
deck_id = _deck_id(ui)
settings = SettingsDialog(window)
api.stop_dimmer(deck_id)
for label, value... | 61,790 |
def get_avg_score(num_moves=None, num_trials=None):
"""Get the average score for a specified configuration of num_moves and num_trials
Args:
num_moves (int, optional): The value for num_moves which printed trials must match. Defaults to None.
num_trials (int, optional): The value for num_trials... | 61,791 |
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words=break_words(sentence)
return sort_words(words) | 61,792 |
def download_cifar10(filepath=cifar10_raw):
"""
Args:
filepath (str, optional): Directory containing CIFAR-10. Path is created if nonexistant. CIFAR-10 is downloaded if missing.
Returns None.
"""
url = 'https://www.cs.toronto.edu/~kriz/'
tar_filename = 'cifar-10-binary.tar.gz'
if fi... | 61,793 |
def get_pdb_file(file_name, print_out=True):
""" (file_name) -> file_path
This function will check if a pdb file_name exist.
If it is not, it will either fetch it from the RCSB website
or find it on LBLs pdb mirror folder
:param file_name (str): a pdb file name
:return file_name (str): the location, path, ... | 61,794 |
def get_instance_state(instanceName=None):
"""
Returns the state of a specific instance. Works on one instance at a time.
See also: AWS API Documentation
:example: response = client.get_instance_state(
instanceName='string'
)
:type instanceName: string
:param inst... | 61,795 |
def change_edge_appliance(edge_id):
"""Update the appliances data of an edge
Update the edge appliances data according to its current availability zone
and the nsx.ini config, including the resource pool, edge_ha, datastore &
ha_datastore.
The availability zone of the edge will not be changed.
... | 61,796 |
def export_scorekeepers_table(output_directory: Path):
"""Export ww_scorekeepers table and write the generated JSON out to
a text file.
:param output_directory: Path object containing the output directory
path.
"""
scorekeepers = Scorekeepers(connect_dict=config_dict)
scorekeepers_json ... | 61,797 |
def create_knx_exposure(
hass: HomeAssistant, xknx: XKNX, config: ConfigType
) -> KNXExposeSensor | KNXExposeTime:
"""Create exposures from config."""
address = config[KNX_ADDRESS]
expose_type = config[ExposeSchema.CONF_KNX_EXPOSE_TYPE]
attribute = config.get(ExposeSchema.CONF_KNX_EXPOSE_ATTRIBUTE)
... | 61,798 |
async def test_or_condition_with_template(hass):
"""Test the 'or' condition."""
test = await condition.async_from_config(
hass,
{
"condition": "or",
"conditions": [
{'{{ states.sensor.temperature.state == "100" }}'},
{
"... | 61,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.