content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main():
"""
This is a docstring that lets 3rd party tools to generate
documentation for "main" function
"""
print("This is a literal string")
print('Single quote works exactly the same')
print('It ' 'join ' 'using space between them')
print('If placed into a parenthesis, '
... | 5,321,200 |
def create_predict_function(
route, predict_service, decorator_list_name):
"""Creates a predict function and registers it to
the Flask app using the route decorator.
:param str route:
Path of the entry point.
:param expose.interfaces.PredictService predict_service:
The predict serv... | 5,321,201 |
def batch_pix_accuracy(output, target):
"""PixAcc"""
# inputs are NDarray, output 4D, target 3D
# the category -1 is ignored class, typically for background / boundary
predict = np.argmax(output.asnumpy(), 1).astype('int64') + 1
target = target.asnumpy().astype('int64') + 1
pixel_labeled = np.... | 5,321,202 |
def insert_data(con, data_file, table_name):
"""
CSVデータファイルを読み込み、全てのデータをinsertする
"""
print('InsertInto : {} -> {}'.format(data_file, table_name))
if os.path.splitext(data_file)[1] == '.tsv':
data = pd.read_csv(data_file, encoding="utf-8", sep='\t')
else:
data = pd.read_csv(data_f... | 5,321,203 |
def puma560() -> np.ndarray: # pragma: no cover
"""Get PUMA560 MDH model."""
return np.array(
[
[0, 0, 0, 0],
[-np.pi / 2, 0, 0, 0],
[0, 612.7, 0, 0],
[0, 571.6, 0, 163.9],
[-np.pi / 2, 0, 0, 115.7],
[np.pi / 2, 0, np.pi, 92.2],
... | 5,321,204 |
def get_scaling_factor(window: "Window" = None) -> float:
"""
Gets the scaling factor of the given Window.
This is the ratio between the window and framebuffer size.
If no window is supplied the currently active window will be used.
:param Window window: Handle to window we want to get scaling fact... | 5,321,205 |
def fetch_addresses(xml_tree):
"""Pull out address information (addresses + instructions). Final
notices do not have addresses (as we no longer accept comments)."""
address_nodes = xml_tree.xpath('//ADD/P')
addresses = {}
for p in address_nodes:
p = cleanup_address_p(p)
if ':' in p:
... | 5,321,206 |
def df_to_table(conn, table_name, df):
"""
Paste Values from a DataFrame into a DataBase table.
Parameters
----------
conn : SQLite3 Connection
The connection to the DataBase.
table_name : String
Name of the DataBase's table where the DataFrame will be pasted.
df : pandas Da... | 5,321,207 |
def css_tricks(data):
"""Handle data from css-tricks.com"""
articles = data["results"]
article = random.choice(articles)
title = article["highlight"]["title"][0]
description = article["highlight"]["content"][0]
if not description:
description = "No description found for this article"
... | 5,321,208 |
def choose_(all_service_nodes, service_node,node, accepted_method_verbs=('get', 'describe', 'list', 'search')):
# def choose_(service_node, node, method_verbs=('describe', 'list', 'search')):
"""Choose between method verbs.
Priorities:
"""
# filter the node's methods with accepted method verbs
accep... | 5,321,209 |
def rank(x, small_rank_is_high_num=True, rank_from_1=True):
"""
Rank items in an array. Using the 'first' method, which ranks ties using
the order of appearance. For rank functionality similar to R, see scipy's
rankdata function (which is imported from this module for convenience).'
Parameters
... | 5,321,210 |
def unauthorized():
"""For basic_auth. Return 403 instead of 401 to prevent browsers from displaying the default auth dialog."""
return make_response(jsonify({'error': 'Unauthorized access'}), 403) | 5,321,211 |
def cma_ajax_get_table_iso(request):
"""
Ajax view for fetching ISO images list.
"""
if request.method == 'GET':
iso = prep_data('admin_cm/iso_image/get_list/', request.session)
for item in iso:
item['size'] = filesizeformatmb(item['size'])
return messages_ajax.succ... | 5,321,212 |
def get_config_filepath():
"""Return the filepath of the configuration file."""
default_config_root = os.path.join(os.path.expanduser('~'), '.config')
config_root = os.getenv('XDG_CONFIG_HOME', default=default_config_root)
return os.path.join(config_root, 'zoia/config.yaml') | 5,321,213 |
def prefs(func: callable):
"""This decorator will pass the result of the given func to PREFS.convert_to_prefs,
to print a dictionary using PREFS format.
Example:
# Without prefs decorator
def dictionary():
return {'keybindings': {'Ctrl+C': 'Copy', 'Ctrl+V': 'Paste'}}
print(dicti... | 5,321,214 |
def write_genes(names, file_type, filename, header):
""" (list of str, str, str, str) -> NoneType
Write each line of the species name and genes to an output_file.
"""
output_file = open_file(file_type, filename)
output_file.write(header)
for name in names:
output_file.write(name)
if file_type == 'nexus':
... | 5,321,215 |
def main():
""" main function """
clear_old_vim_undo() | 5,321,216 |
def friction_fnc(normal_force,friction_coefficient):
"""Usage: Find force of friction using normal force and friction coefficent"""
return normal_force * friction_coefficient | 5,321,217 |
def clear_history(mac):
"""Clear the sensor history."""
poller = MiFloraPoller(mac, backend)
poller.clear_history() | 5,321,218 |
def parse_line(line):
"""
Parse a line of assembly code to create machine code byte templates.
If a line is not identifiably a JUMP_IF_OVERFLOW_FLAG assembly line,
return an empty list instead.
Args:
line (str): Assembly line to be parsed.
Returns:
list(dict): List of machine c... | 5,321,219 |
def unpack_asn1_general_string(value): # type (Union[bytes, ASN1Value]) -> bytes
""" Unpacks an ASN.1 GeneralString value. """
return extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.general_string) | 5,321,220 |
def test_internal_note():
"""Test internal note schema."""
valid_full = {
"user": "inveniouser",
"note": "RDM record",
"timestamp": "2020-02-01"
}
data = InternalNoteSchemaV1().load(valid_full)
assert data == valid_full
invalid_no_user = {
"note": "RDM record",
... | 5,321,221 |
def opti_loc_poly_traj(data_traj, t, minh, maxh, nb_h):
"""
Find the optimal parameter h to estimate the derivatives with local polynomial regression
...
"""
HH = np.linspace(minh,maxh,nb_h)
err_h = np.zeros(len(HH))
kf = KFold(n_splits=10, shuffle=False)
for j in range(len(HH)):
... | 5,321,222 |
def pickup_icec_job(pickle_filename, ccs_fofn, flnc_filename, fasta_files_to_add, root_dir):
"""
Reconstruct an ICE object from a pickle file and restart this ICE job.
"""
log.info("Reading ICE pickle %s ....", pickle_filename)
icec_obj, icec_pickle_filename = ensure_pickle_goodness(
pickle_... | 5,321,223 |
def _trimmed_mean(arr, n=2, axis=None, maskval=0):
"""
Return the trimmed mean of an input array.
Parameters
----------
arr: ndarray
Data to trim
n: integer
Number of points to trim at each end
axis: int
The axis along which to compute the trimmed mean.
... | 5,321,224 |
def validate_kind_name(value):
"""Validate the value of the kind_name."""
if value is not None and not isinstance(value, str):
raise ValidationError('kind_name must be a string')
return value | 5,321,225 |
def setup_directories(env, saving_dir, replay_filename, expert_replay_file_path, agent_replay_file_path, pretrain_model_save_path, create_dirs=True):
""" Setup directories where information will be saved
env: Pass in current environment to have access to getting environment variables for recording purposes
... | 5,321,226 |
def keyInfoCtxCopyUserPref(dst, src):
"""
Copies user preferences from src context to dst context.
dst : the destination context object.
src : the source context object.
Returns : 0 on success and a negative value if an error occurs.
"""
return xmlsecmod.keyInfoCtxCopyUserPref(dst, s... | 5,321,227 |
def _test_nested_change(case, outer_factory, inner_factory):
"""
Assert that ``IChangeState`` providers wrapped inside ``inner_factory``
wrapped inside ``outer_factory`` are run with the same deployer argument as
is passed to ``run_state_change``.
:param TestCase case: A running test.
:param ou... | 5,321,228 |
def kernel_classifier_distance_and_std_from_activations(real_activations,
generated_activations,
max_block_size=500,
dtype=None):
"""Kernel "cla... | 5,321,229 |
def yolo_eval(yolo_outputs,
anchors,
num_classes,
image_shape,
max_boxes=20,
score_threshold=.6, # max_boxes=20, score_threshold=.6,iou_threshold=.5
iou_threshold=.5):
"""Evaluate YOLO model on given input and return filtered boxes."""
num_layers = len(yolo_outputs)
anchor_mask = [[6,7... | 5,321,230 |
def tile_images(images: List[np.ndarray]) -> np.ndarray:
"""Tile multiple images into single image
Args:
images: list of images where each image has dimension
(height x width x channels)
Returns:
tiled image (new_height x width x channels)
"""
assert len(images) > 0, "e... | 5,321,231 |
def network(images1, images2, weight_decay):
"""
Siamese neural network for training person re-identification. Based on:
https://www.cv-foundation.org/openaccess/content_cvpr_2015/papers/Ahmed_An_Improved_Deep_2015_CVPR_paper.pdf
:param images1, images2: image pairs (positive and negative examples)
... | 5,321,232 |
def prepQuestAppliedNotification(shipper, questr, questdetails):
"""Prepare the details for notification emails for new quests"""
template_name="Quest_Accepted_Notification_Questr"
subject="Questr - Your shipment has been processed"
quest_support_email="support@questr.co"
email_details = {
... | 5,321,233 |
def commit_ref_db_val_from_raw_val(db_kvs: Iterable[Tuple[bytes, bytes]]) -> DigestAndBytes:
"""serialize and compress a list of db_key/db_value pairs for commit storage
Parameters
----------
db_kvs : Iterable[Tuple[bytes, bytes]]
Iterable collection binary encoded db_key/db_val pairs.
Ret... | 5,321,234 |
def measure_text(text, r, ax):
"""Measure size of text string on canvas."""
t = plt.text(0.5, 0.5, text, **font_opts)
res = measure_text_obj(t, r, ax)
t.remove()
return res | 5,321,235 |
def add_sto_plants(net: pypsa.Network, topology_type: str = "countries",
extendable: bool = False, cyclic_sof: bool = True) -> pypsa.Network:
"""
Add run-of-river generators to a Network instance
Parameters
----------
net: pypsa.Network
A Network instance.
topology_ty... | 5,321,236 |
def flow_to_image(flow):
"""
Convert flow into middlebury color code image
:param flow: optical flow map
:return: optical flow image in middlebury color
"""
print('flow to image shape', flow.shape)
u = flow[:, :, 0]
v = flow[:, :, 1]
maxu = -999.
maxv = -999.
minu = 999.
... | 5,321,237 |
def contract_edges(graph, edge_weight='weight'):
"""
Given a graph, contract edges into a list of contracted edges. Nodes with degree 2 are collapsed into an edge
stretching from a dead-end node (degree 1) or intersection (degree >= 3) to another like node.
Args:
graph (networkx graph):
... | 5,321,238 |
def lagval3d(x, y, z, c):
"""
Evaluate a 3-D Laguerre series at points (x, y, z).
This function returns the values:
.. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * L_i(x) * L_j(y) * L_k(z)
The parameters `x`, `y`, and `z` are converted to arrays only if
they are tuples or a lists, otherwise th... | 5,321,239 |
async def get_file_path(project_id: str, file_id: str) -> str:
"""
获取文件id
:param project_id:
:param file_id:
:return:
"""
file_path = PROJECT_FILE_DICT[project_id].pop(file_id)
return file_path | 5,321,240 |
async def regrade_request(ctx):
"""
Function: regrade_request
Description: Help for command regrade_request
Inputs:
- ctx: Context of the function activation
Outputs: Result of !help regrade_request
"""
embed = Embed(title='regrade-request',
de... | 5,321,241 |
def makeTopRegister(board, jigFrameSize, jigThickness, pcbThickness,
outerBorder=fromMm(3), innerBorder=fromMm(1),
tolerance=fromMm(0.05)):
"""
Create a SolidPython representation of the top register
"""
print("Top")
return makeRegister(board, jigFrameSize, ji... | 5,321,242 |
def pvxpv(a, b):
""" Outer product of two pv-vectors.
:param a: first pv-vector.
:type a: array-like of shape (2,3)
:param b: second pv-vector.
:type b: array-like of shape (2,3)
:returns: a x b as a numpy.matrix of shape 2x3.
.. seealso:: |MANUAL| page 191
"""
axb = _np.asmatrix... | 5,321,243 |
def rm_test_db() -> None:
"""
Removing temporary test database.
"""
CLIENT.delete(DB_NAME) | 5,321,244 |
def test_working_dir_argument_config(storage, monkeypatch):
"""Check that workning dir argument is handled properly"""
monkeypatch.chdir(os.path.dirname(os.path.abspath(__file__)))
dir_path = os.path.join("orion", "test")
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
orion.core.cli.m... | 5,321,245 |
def _encodeImage(image, encoding='JPEG', jpegQuality=95, jpegSubsampling=0,
format=(TILE_FORMAT_IMAGE, ), tiffCompression='raw',
**kwargs):
"""
Convert a PIL or numpy image into raw output bytes and a mime type.
:param image: a PIL image.
:param encoding: a valid PIL e... | 5,321,246 |
def get_local_gateway(filters: Optional[Sequence[pulumi.InputType['GetLocalGatewayFilterArgs']]] = None,
id: Optional[str] = None,
state: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOp... | 5,321,247 |
def last_char(text: str, begin: int, end: int, chars: str) -> int:
"""Returns the index of the last non-whitespace character in string
`text` within the bounds [begin, end].
"""
while end > begin and text[end - 1] in chars:
end -= 1
return end | 5,321,248 |
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a scene graph generation network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use',
default=0, type=int)
parser.add_argument('--weights', dest='model',
... | 5,321,249 |
def test_cache_memoize_async(cache):
"""Test that cache.memoize() can decorate async functions."""
loop = asyncio.get_event_loop()
marker = 1
@cache.memoize()
@asyncio.coroutine
def func(a):
return (a, marker)
assert asyncio.iscoroutinefunction(func)
assert len(cache) == 0
... | 5,321,250 |
def pathlib_convenience():
"""创建绝对路径文件系统"""
home = pathlib.Path.home()
# 当前文件所在路径
cwd = pathlib.Path.cwd()
print("home: ", home)
print("cwd: ", cwd)
r"""
home: C:\Users\Lcoderfit
cwd: E:\SocialProject\Learn-Tags\PythonStandardLibrary\file_system
""" | 5,321,251 |
def _gen_write_element(e: UxsdElement, parent: str) -> str:
"""Function to generate partial C++ code for writing out a struct generated
from an UxsdElement.
Currently, all values with non-zero default values are emitted.
Otherwise, we would have to check against the nonzero value, and the
check would create a cas... | 5,321,252 |
def compare_cols(fg_col, fg_cons, fg_size, fg_weights,
bg_col, bg_cons, bg_size, bg_weights,
aa_freqs, pseudo_size):
"""Compare amino acid frequencies between aligned columns via G-test."""
# Calculate the "expected" aa frequencies
bg_counts = count_col(bg_col, bg_weights, ... | 5,321,253 |
def test_run_checks():
"""Test the run_checks orchestator works."""
domains = ["asu.edu", "censys.io", "bannerhealth.com", "adobe.com"]
pot = findcdn.cdnEngine.DomainPot(domains)
chef = findcdn.cdnEngine.Chef(pot, THREADS, TIMEOUT, USER_AGENT)
chef.run_checks()
# Assertions
assert len(chef.... | 5,321,254 |
def test_Variable2():
"""
test Variable with set_value()
:return:
"""
os.environ["CUDA_VISIBLE_DEVICES"] = "6, 7"
with fluid.dygraph.guard():
new_variable = fluid.dygraph.to_variable(np.arange(10))
tools.compare(new_variable.numpy(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = ne... | 5,321,255 |
def quick_nph(mol, confId=0, step=2000, time_step=None, press=1.0, f_press=None, shake=False, idx=None, tmp_clear=False,
solver='lammps', solver_path=None, work_dir=None, omp=1, mpi=0, gpu=0, **kwargs):
"""
MD.quick_nph
MD simulation with NPH ensemble
Args:
mol: RDKit Mol o... | 5,321,256 |
def _set_operable_to_false(eq: EquipmentSinglePhase):
"""Helper which sets a given piece of equipment's 'operable'
parameter to False.
"""
eq.operable = False | 5,321,257 |
def parameter_converter(
possible_types: list,
default_return: t.Any,
cache_handler: t.Optional[t.Callable],
):
"""
parameter_converter is used for converting annotated parameters
of a function into the annotated types.
Conversion is attempted in the order that they are annotate... | 5,321,258 |
def send_data(log_data):
""" Sends parsed metric data to InsightFinder """
send_data_time = time.time()
# prepare data for metric streaming agent
to_send_data_dict = {"metricData": json.dumps(log_data),
"licenseKey": config_vars['license_key'],
"projectN... | 5,321,259 |
def next_tide_state(tide_info, current_time):
"""Compute next tide state"""
# Get next tide time
next_tide = tide_info.give_next_tide_in_epoch(current_time)
if next_tide.get("error") == None:
tidetime = time.strftime("%H:%M", time.localtime(next_tide.get("tide_time")))
tidetype = next_ti... | 5,321,260 |
def dct_2d_reverse(block):
"""
:reverse 2d Discrete Cosine Transformation
:param tensor:
:return:
"""
block = end_T(block)
block = idct(block, norm='ortho')
block = end_T(block)
block = idct(block, norm='ortho')
return block | 5,321,261 |
def convert_idx(text, tokens):
"""
Calculates the coordinates of each start
end spans of each token.
:param text: The text to extract spans from.
:param tokens: The tokens of that text.
:return: A list of spans.
"""
current = 0
spans = []
for token in tokens:
current = ... | 5,321,262 |
def _mgsort(comparables, auxiliary, lo, hi):
"""Merge sort helper function
Arguments:
comparables -- an array of which the elements can be compared
auxiliary -- an auxiliary array for sorted sub-arrays
lo -- lower bound of indices
hi -- higher bound of indices
"""
# merge sort too heavy f... | 5,321,263 |
def parse_zip(bufferstr):
"""
parse binary object as zip file
"""
z = zipfile.ZipFile(BytesIO(bufferstr))
filenames = z.namelist()
if not filenames:
print('No names found.')
with open('tmp.badzipfile.zip', 'wb') as f:
f.write(bufferstr)
exit()
if len(fil... | 5,321,264 |
def downsample(u_t, Fs, Fs_new, plotit=False):
"""
The proper way to downsample a signal.
First low-pass filter the signal
Interpolate / Decimate the signal down to the new sampling frequency
"""
tau = 2/Fs_new
nt = len(u_t)
tt = _np.arange(0, nt, 1)/Fs
# tt = tt.reshape(n... | 5,321,265 |
def convert_date_hours(times, start):
"""
This function converts model output time in hours to datetime objects.
:arg times: array of hours since the start date of a simulation.
From time_counter in model output.
:type times: int
:arg start: string containing the start date of the ... | 5,321,266 |
def feature(self, node="clickhouse1"):
"""Check the RBAC functionality of CREATE ROW POLICY."""
self.context.node = self.context.cluster.node(node)
self.context.node2 = self.context.cluster.node("clickhouse2")
Suite(run=privileges_granted_directly, setup=instrument_clickhouse_server_log)
Suite(run=... | 5,321,267 |
def idf_unit_test(app=UT, dut=IDFDUT, chip="ESP32", module="unit-test", execution_time=1,
level="unit", erase_nvs=True, **kwargs):
"""
decorator for testing idf unit tests (with default values for some keyword args).
:param app: test application class
:param dut: dut class
:param ... | 5,321,268 |
def get_materials():
"""return _materials dictionary, creating it if needed"""
mat = {}
fname = 'materials.dat'
if os.path.exists(fname):
fh = open(fname, 'r')
lines = fh.readlines()
fh.close()
for line in lines:
line = line.strip()
if len(line) >... | 5,321,269 |
def decoratebiom(biom_file, outdir, metadata, core=""):
"""inserts rows and column data
"""
out_biom = '.'.join(biom_file.split('.')[0:-1]) + '.meta.biom'
cmd_sample = f"biom add-metadata -i {biom_file} -o {out_biom} -m {metadata} --output-as-json"
res_add = subprocess.check_output(cmd_sample, shell... | 5,321,270 |
def index(request):
"""The home page for MMS Pair App"""
# If the client-side forgets to run the command manage.py checkdb,
# this check ensures that the data will be updated on the home page.
coins = Coin.objects.all().count()
# If database is empty, call the load_coin function
if coins == 0:... | 5,321,271 |
def cbdiag(size: int, blocks: Iterable[Tuple[int, ndarray]]) -> ndarray:
"""
Build a block matrix with (sub-)diagonal blocks and the given size.
Each block is specified with its offset from the diagonal and its data
(sub matrix). All blocks are expected to have the same shape. If not,
a `MatrixShap... | 5,321,272 |
def read_hca_metadata(metadata_file: Path) -> nx.DiGraph:
"""
:param metadata_file:
:return: A unique set of donor metadata
"""
donor_data = pd.read_table(metadata_file)
row_data = []
for i, row in donor_data.iterrows():
dotted_row_dict = dict(zip(row.index, value_adjust(row)))
... | 5,321,273 |
def search_results(rows):
"""
Display search results
"""
print()
print(to_table(rows))
print()
# Ask user input
input_ = menu.get_input(
message='Select a result # or type any key to go back to the main menu: ')
if input_:
try:
result = [row for row... | 5,321,274 |
def eval_js(expression_, **args):
"""Execute JavaScript expression in the user's browser and get the value of the expression
:param str expression_: JavaScript expression. The value of the expression need to be JSON-serializable.
:param args: Local variables passed to js code. Variables need to be JSON-ser... | 5,321,275 |
def quat2rot(q):
"""
Convert quaternion to 3x3 rotation matrix.
Source:
Blanco, Jose-Luis. "A tutorial on se (3) transformation parameterizations
and on-manifold optimization." University of Malaga, Tech. Rep 3 (2010): 6.
[Page 18, Equation (2.20)]
"""
assert len(q) == 4
qw, qx, qy, qz = q
qx2 = q... | 5,321,276 |
def test_tag_prefix_and_pattern_combination(runner, open_changelog):
"""Combination of prefix and pattern work in a way that first prefix tags are filtered,
then tag - (minus) prefix part is checked with the pattern.
JS test notes:
* includes also release-1.2.3
"""
result = runner.invoke(main, ... | 5,321,277 |
def insert_stroke(seq, stroke, offset=0):
"""Insert into seq positions from the stroke dict"""
frame = offset
for i, p in enumerate(stroke):
frame = p["frame"] + offset
if i == 0:
# Do not override a keyframe at the start of the insert position.
if launch_keyframe(seq... | 5,321,278 |
def get_dest_file(src_file):
"""
Takes a src file location
Returns the destination file location.
In the case of files with exif data, the destination file location is the
year/month/filename
In the case of files with exif data, but no Image DateTime, the destination
file location is... | 5,321,279 |
def Lazy(func=None, *, lazy=True):
""""Decorator that provides a function with a boolean parameter "lazy".
When set to true, the function will not be executed yet, sort of like a
coroutine (see examples). This can be nice for testing purposes. Also
opens the door to some interesting things (maybe sort o... | 5,321,280 |
def reduce(t: Any, options: Dict) -> Any:
"""recursively applies itself to a nested data structure. if given a list of dicts, will reduce those down to a
list of a single dict, whose values are ResultSets of the values from the dicts in the original list
Example:
[
{
'h... | 5,321,281 |
def test_nullable_deleting_field(app):
"""test delete a field
A field cannot be deleted if it is associated
"""
with app.app_context():
field1 = Field.query.filter_by(name="field1").one()
sa.session.delete(field1)
with pytest.raises(AssertionError):
sa.session.comm... | 5,321,282 |
def certificate_admin_list(request):
"""
Displays a list of :model:`rr.Certificate`
including old certificates and weak keys.
Only available for super users.
**Context**
``object_list``
List of :model:`rr.Certificate`.
**Template:**
:template:`rr/attribute_admin_list.html`
... | 5,321,283 |
def chaosmonkey_enabled(
base_url: str,
headers: Dict[str, Any] = None,
timeout: float = None,
verify_ssl: bool = True,
configuration: Configuration = None,
secrets: Secrets = None,
) -> bool:
"""
Enquire whether Chaos Monkey is enabled on the
specified service.
"""
response... | 5,321,284 |
def test_record_search_links(client, published_json, headers):
"""Tests the links for a search of published RDM records."""
response = client.get("/records", headers=headers)
search_record_links = response.json["links"]
expected_links = {
# NOTE: Variations are covered in records-resources
... | 5,321,285 |
def compute_norm(A, scale=None):
"""
Compute the norm of the *A* array, which contains spin directions in
Spherical or Cartesian coordinates, e.g.
A = [ A_theta0 A_phi0 A_theta1 A_phi1 ... A_thetaN A_phiN]
If necessary, scale the norm by the array size
"""
y = np.linalg.norm(A)
if ... | 5,321,286 |
def test_send_message():
"""
This sends a simple text message with a title and link button.
"""
teams_message = pymsteams.connectorcard(os.getenv("MS_TEAMS_WEBHOOK"))
teams_message.text("This is a simple text message.")
teams_message.title("Simple Message Title")
teams_message.addLinkBu... | 5,321,287 |
def _matrixify(mat):
"""If `mat` is a Matrix or is matrix-like,
return a Matrix or MatrixWrapper object. Otherwise
`mat` is passed through without modification."""
if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False):
return mat
if not(getattr(mat, 'is_Matrix', True... | 5,321,288 |
def format_value_list(value, tagname=None):
"""
convert osm tag value to nice html representation
:param value: osm tag value as ';' separated string
:return: html
"""
value = value.strip()
if not value:
return ''
parts = [part.strip() for part in value.split(';')]
make_bad... | 5,321,289 |
def get_arg_name(node):
"""
Args:
node:
Returns:
"""
name = node.id
if name is None:
return node.arg
else:
return name | 5,321,290 |
def tf_focal_loss(y_true, y_pred, alpha=.5, gamma=2.):
"""
Straightforward implementation of focal loss.
See https://arxiv.org/abs/1708.02002
# Arguments:
y_true: actual labels {0., 1.}
y_pred: predicted labels {0., 1.}
alpha: see paper
gamma: see paper
"""
assert... | 5,321,291 |
def two_armed_c3d(left_model, right_model):
"""
C3D architecture with two arms. One of the arms will focus in Doppler videos while the other will focus in
non-Doppler ones.
"""
left_model_input, left_model_output = left_model.layers[0].input, left_model.layers[-1].output
right_model_input, righ... | 5,321,292 |
def bbox_iou(box1, box2, x1y1x2y2=True):
"""
Returns the IoU of two bounding boxes
"""
if x1y1x2y2:
# Get the coordinates of bounding boxes
b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]
b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2],... | 5,321,293 |
def login():
"""
check user credentials
if next=... parameter is present redirect on success
"""
form = flask.request.form
if flask.request.method == "POST" and form.get("login", False):
password = form.get("password", None)
email = form.get("email", None)
... | 5,321,294 |
def load_module(url):
"""
Load module from url (simplest way)
https://python3-cookbook.readthedocs.io/zh_CN/latest/c10/p11_load_modules_from_remote_machine_by_hooks.html
"""
u = request.urlopen(url)
source = u.read().decode("utf-8")
mod = sys.modules.setdefault(url, types.ModuleType(url))
... | 5,321,295 |
def mlab_imshowColor(im, alpha = 255, **kwargs):
"""
Plot a color image with mayavi.mlab.imshow.
im is a ndarray with dim (n, m, 3) and scale (0->255]
alpha is a single number or a ndarray with dim (n*m) and scale (0->255]
**kwargs is passed onto mayavi.mlab.imshow(..., **kwargs)
"""
from tv... | 5,321,296 |
def get_remove_string(packages, cuda_version):
"""Creates pip remove string for given cuda version and package list"""
# Remove only these which version we want to change
ret = for_all_pckg(packages, lambda pckg: pckg.get_uninstall_names(cuda_version))
return " ".join(ret) | 5,321,297 |
def safe_file_name(name, posix=None):
"""
:param str name:
:param bool posix:
:rtype: str
"""
if posix is None:
posix = sys.platform != 'win32'
if posix:
return re.sub(r'[\x00/]', '', name)
else:
name = re.sub(r'[\x00-\x1f<>:"/\|?*]', '', name).rstrip('. ')[:255]... | 5,321,298 |
def h_bond_basic_result_collection(monkeypatch) -> BasicResultCollection:
"""Create a basic collection which can be filtered."""
# Create a molecule which contains internal h-bonds.
h_bond_molecule = Molecule.from_smiles(r"O\C=C/C=O")
h_bond_molecule.add_conformer(
np.array(
[
... | 5,321,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.