content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def find_global_peaks_integral(
cms: tf.Tensor, crop_size: int = 5, threshold: float = 0.2
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Find local peaks with integral refinement.
Integral regression refinement will be computed by taking the weighted average of
the local neighborhood around each rough peak.
... | 45,700 |
def test_data(test_data_info, pytestconfig):
"""Fixture provides test data loaded from files automatically."""
data_pattern = pytestconfig.getoption(constants.OPT_DATA_PATTERN)
if test_data_info.subdirs:
return list(
list(loader.each_data_under_dir(
test_data_info.datadi... | 45,701 |
def load_maggic_data():
"""Load MAGGIC data.
Returns:
orig_data: Original data in pandas dataframe
"""
# Read csv files
file_name = 'data/Maggic.csv'
orig_data = pd.read_csv(file_name, sep=',')
# Remove NA
orig_data = orig_data.dropna(axis=0, how='any')
# Remove labels
orig_data = o... | 45,702 |
def test_RandLaNet_test_right_after_training(
isolated_toy_dataset_tmpdir, one_epoch_trained_RandLaNet_checkpoint, tmpdir
):
"""Run test using the model that was just trained for one epoch.
Args:
isolated_toy_dataset_tmpdir (fixture -> str): directory to toy dataset
one_epoch_trained_RandLa... | 45,703 |
def create_res_hessian_computing_tf_graph(input_shape, layer_kernel, layer_stride):
"""
This function create the TensorFlow graph for computing hessian matrix for res layer.
Step 1: It first extract image patches using tf.extract_image_patches.
Step 2: Then calculate the hessian matrix by outer product... | 45,704 |
def load_profile_win_x64_win_x64_vs2015_settings(conf):
"""
Setup all compiler and linker settings shared over all win_x64_win_x64_v140 configurations for
the 'profile' configuration
"""
conf.load_win_x64_win_x64_vs2015_common_settings()
# Load additional shared settings
conf.load_profile_c... | 45,705 |
def loadUiType(uiFile):
"""
Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first
and then execute it in a special frame to retrieve the form_class.
http://tech-artists.org/forum/showthread.php?3035-PySide-in-Maya-2013
"""
parsed = xml.pa... | 45,706 |
def ldns_native2rdf_int8(*args):
"""LDNS buffer."""
return _ldns.ldns_native2rdf_int8(*args) | 45,707 |
def delete_vqe_runner(provider, program_id):
"""Delete the desired program on the IBMQ platform.
Args:
provider (object): IBMQ provider.
program_id (str): Id of the Qiskit runtime to be deleted.
"""
provider.runtime.delete_program(program_id) | 45,708 |
def _ListProcesses(args, req_vars): # pylint: disable=W0613
"""Lists processes and their CPU / mem stats.
The response is formatted according to the Google Charts DataTable format.
"""
device = _GetDevice(args)
if not device:
return _HTTP_GONE, [], 'Device not found'
resp = {
'cols': [
... | 45,709 |
def _runForRunnerUser(resourceDB: ResourceDB, user: User) -> TaskRun:
"""Returns the task run accessible to the given user.
Raises AccessDenied if the user does not represent a Task Runner
or the Task Runner is not running any task.
"""
# Get Task Runner.
if not isinstance(user, TokenUser):
... | 45,710 |
def test_example_1a():
"""Example A from figure 1 in the paper"""
gt = Tracks()
for i in range(20):
gt.add_frame(i, [0], np.array([[0, 0, 1, 1]]))
hyp = Tracks()
for i in range(10):
hyp.add_frame(i, [0], np.array([[0, 0, 1, 1]]))
metrics = calculate_hota_metrics(gt, hyp)
as... | 45,711 |
def main():
"""
main function
"""
print "Building multiprocesses engine"
pool = Pool(processes=len(sns))
print "Starting pool with ", len(sns), ' processes'
pool.map(multi_process, sns) | 45,712 |
def narrow(lon='auto',lat='auto',ax=None,lfactor=1,**kwargs):
"""
Plot north arrow.
Parameters:
lon: Starting longitude (decimal degrees) for arrow
lat: Starting latitude (ecimal degrees) for arrow
ax: Axes on which to plot arrow
lfactor: Length factor to increase/decrea... | 45,713 |
def test__MolecStruct_resonance_averaged_bond_order():
""" test pyx2z.MolecStruct.resonance_averaged_bond_order()
"""
asymbs = ['O', 'H', 'H']
coords = [(-1.2516025626, 2.3683550357, 0.0000000000),
(-0.2816025626, 2.3683550357, 0.0000000000),
(-1.5749323743, 3.2380324089, -0.... | 45,714 |
def dump_content_descriptor(artifact_manager: ArtifactsManager) -> ArtifactsReport:
""" Dumping content/content_descriptor.json into:
1. content_test
2. content_new
3. content_all
Args:
artifact_manager: Artifacts manager object.
Returns:
ArtifactsReport... | 45,715 |
def describe_continuous_backups(TableName=None):
"""
Checks the status of continuous backups and point in time recovery on the specified table. Continuous backups are ENABLED on all tables at table creation. If point in time recovery is enabled, PointInTimeRecoveryStatus will be set to ENABLED.
After contin... | 45,716 |
def sym_axis(input_file, axis, verbose):
"""
\b
calculates the distance of each amino acid from the symmetry axis.
homomer symmetric axis distance
"""
_caller = "atoms_pairs command"
cliutils = cu(click, is_verbose=verbose)
_axis = validate_trimer_options(cliutils, input_file, ... | 45,717 |
def parse_movie(line, sep='::'):
"""
Parses a movie line
Returns: tuple of (movie_id, title)
"""
fields = line.strip().split(sep)
movie_id = int(fields[0]) # convert movie_id to int
title = fields[1]
return movie_id, title | 45,718 |
def make_plot(dataset, plot_label, xlabel, ylabel, legend):
"""
Generates a MatPlotLib plot from the specified dataset and with the specified labeling features.
make_plot(dataset, plot_label, xlabel, ylabel, legend) -> plt
@type dataset: list of list
@param dataset: formatted dataset.
... | 45,719 |
def read_site_to_cmt():
""" Yields clock sources and which CMT they route within. """
fuzdir = os.getenv('FUZDIR')
part = os.getenv('XRAY_PART')
with open(os.path.join(fuzdir, 'build_{}'.format(part),
'cmt_regions.csv')) as f:
for l in f:
site, cmt = l.str... | 45,720 |
def flatten_list(in_list: typ.List) -> typ.List:
"""Flattens list"""
result = []
for item in in_list:
if isinstance(item, list):
result.extend(flatten_list(item))
else:
result.append(item)
return result | 45,721 |
def formatMessage(data):
"""
Format incoming message before passing to Discord
"""
logging.info("Formatting message payload...")
time = (data.occurredAt).split("T")
message = [":alarm_clock: __**Meraki Alert**__ :alarm_clock: "]
message.append(f"**Device:** {data.deviceName}")
message.ap... | 45,722 |
def test_initiation_from_wrong_type(value: Any) -> None:
"""
Test whether the string initializer correctly identifies wrong input
:param value: wrongly formatted string
"""
with pytest.raises(TypeError):
_ = fxp(value) | 45,723 |
def _convert_nearest_neighbors(operator, container, k=None, radius=None):
"""
Common parts to regressor and classifier. Let's denote
*N* as the number of observations, *k*
the number of neighbours. It returns
the following intermediate results:
top_indices: [N, k] (int64), best indices for
... | 45,724 |
def interface_alias_to_name(config_db, interface_alias):
"""Return default interface name if alias name is given as argument
"""
vlan_id = ""
sub_intf_sep_idx = -1
if interface_alias is not None:
sub_intf_sep_idx = interface_alias.find(VLAN_SUB_INTERFACE_SEPARATOR)
if sub_intf_sep_id... | 45,725 |
def twait(phrase, tn, tout=-1, logging='off', rcontent=False, screenprint=False):
""" telnetlib wait with optional timeout and optional logging"""
# Adding code to allow lists for phrase
finalcontent = ' '
#This is the time of the epoch
startTime = int(time.time())
while True:
# This i... | 45,726 |
def process_ob(obs : dict) -> dict:
""" Processes an individual post
:param obs: video observation metadata
:returns: processed post metadata based on tags in posts_titles
"""
metadata = {tag: obs[tag] for tag in obs_tags}
metadata.update(process_obs(obs["children"], obs["history"]))
metad... | 45,727 |
def calc_detectable_frac(gen, model, args, gen2=None, swap_h0_and_h1=False, verbose=0):
"""
:param gen: sample generator
:param model: NN model
:param args: parameters object (should contain alpha and beta attributes)
:param gen2: if gen2 is not None gen output is used for 0-hypothesis and gen2 for... | 45,728 |
def merge_json_folders(folders_in: t.List[pathlib.Path], folder_out: pathlib.Path, sub_process_count: int) -> None:
"""
Merges _several_ folders of `JSON` files into a _single_ folder of `JSON` files based on their file name.
Parameters
----------
folders_in : List[pathlib.Path]
Folders con... | 45,729 |
def similarity_std(
buffer: NumpyNDArray, wav_file: WavFile, rate: int, threshold: float
) -> Tuple[bool, float, float]:
"""Check the similarity of a recorded sound buffer and a given wav_file.
Use a correlation check using the standard deviation."""
import numpy as np
_, _, current_fft = perfor... | 45,730 |
def grdtrack(points, grid, newcolname=None, outfile=None, **kwargs):
"""
Sample grids at specified (x,y) locations.
Grdtrack reads one or more grid files and a table with (x,y) [or (lon,lat)]
positions in the first two columns (more columns may be present). It
interpolates the grid(s) at the positi... | 45,731 |
def add(x, y):
"""add two number"""
return x+y | 45,732 |
def is_exponential(character: str) -> bool:
"""
Whether an IPA character is written above the base line
and to the right of the previous character,
like how exponents of a power are written
in mathematical notation.
"""
return character in exponentials | 45,733 |
def _union_items(baselist, comparelist):
"""Combine two lists, removing duplicates."""
return list(set(baselist) | set(comparelist)) | 45,734 |
def setLanguage(languageName):
""" setLanguage(languageName)
Set the language for the app. Loads qt and pyzo translations.
Returns the QLocale instance to pass to the main widget.
"""
# Get locale
locale = getLocale(languageName)
# Get paths were language files are
qtTransPat... | 45,735 |
def get_data_from_ssh_server(rev_msg, tcp_socket, flag):
"""
:param rev_msg: a queue buffer of message need to be send to SSH client
:param tcp_socket: instance of socket used for sending data
:param flag: control this function
:return: null
"""
while running_flag[flag]:
data = tcp_s... | 45,736 |
def broadcast_state(state=current_state, ip=ip_osc, port=port_client):
"""
Broadcasts state
"""
print("Called Broadcast State Function")
#client = udp_client.UDPClient(ip, port,1)
#builder = osc_message_builder.OscMessageBuilder(address='/status')
#for k,v in state.items():
# builde... | 45,737 |
def check_element(actual, expected):
"""Verify that the actual element that came from the
periodic_table contains the same values as the expected element.
Parameters
actual: a list that came from the periodic_table.
expected: a list that contains the expected values.
Return: nothing
... | 45,738 |
async def test_bridge_import_already_configured(hass):
"""Test if a import flow aborts if host is already configured."""
MockConfigEntry(
domain="hue", unique_id="aabbccddeeff", data={"host": "0.0.0.0"}
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
const.DOMAIN... | 45,739 |
def make_gaussian(shape, var):
"""returns 2d gaussian of given shape and variance"""
h,w = shape
x = np.arange(w, dtype=float)
y = np.arange(h, dtype=float)[:,np.newaxis]
x0 = w // 2
y0 = h // 2
mat = np.exp(-0.5 * (pow(x-x0, 2) + pow(y-y0, 2)) / var)
normalized_img = np.zeros((h, w))
... | 45,740 |
def add_button(_editor: Editor, /, *,
# Keyword-only arguments
icon: Optional[str] = None,
cmd: Optional[str] = None, # Defaults to calling get_unique_cmd
func: Callable[[Editor], None],
tip: Optional[str] = "",
label: Optional[s... | 45,741 |
def analysis_iou_on_miyazakidata(result_path, pattern="GT_o"):
"""对最终4张图片统合的结果进行测试"""
ious = []
pattern1, pattern2 = pattern.strip().split("_")
pattern1 = pattern_dict[pattern1]
pattern2 = pattern_dict[pattern2]
for i in range(1, 21):
image1 = get_image(result_path, i, pattern1)
... | 45,742 |
def min_max_rdist(node_data, x: FloatArray):
"""Compute the minimum and maximum distance between a point and a node"""
lower_bounds = node_data[0]
upper_bounds = node_data[1]
min_dist = 0.0
max_dist = 0.0
for j in range(x.size):
d_lo = lower_bounds[j] - x[j]
d_hi = x[j] - upper_... | 45,743 |
def set_attitude(roll_angle = 0.0, pitch_angle = 0.0, yaw_rate = 0.0, thrust = 0.5, duration = 0):
"""
Note that from AC3.3 the message should be re-sent every second (after about 3 seconds
with no message the velocity will drop back to zero). In AC3.2.1 and earlier the specified
velocity persists until... | 45,744 |
def test_apply_qdm(tmpdir):
"""Test to apply a trained QDM to input data and read the output.
This is an integration test between train_qdm, apply_qdm.
"""
# Setup input data.
target_variable = "fakevariable"
variable_kind = "additive"
n_histdays = 10 * 365 # 10 years of daily historical.
... | 45,745 |
def strip_newlines(s, nleading=0, ntrailing=0):
"""strip at most nleading and ntrailing newlines from s"""
for _ in range(nleading):
if s.lstrip(' \t')[0] == '\n':
s = s.lstrip(' \t')[1:]
elif s.lstrip(' \t')[0] == '\r\n':
s = s.lstrip(' \t')[2:]
for _ in range(ntrai... | 45,746 |
def xyz_to_lab(x_val, y_val, z_val):
"""
Convert XYZ color to CIE-Lab color.
:arg float x_val: XYZ value of X.
:arg float y_val: XYZ value of Y.
:arg float z_val: XYZ value of Z.
:returns: Tuple (L, a, b) representing CIE-Lab color
:rtype: tuple
D65/2° standard illuminant
"""
x... | 45,747 |
def get_core_v1_api():
"""
:return: api client
"""
config.load_kube_config()
core_api = client.CoreV1Api()
return core_api | 45,748 |
def ssbm(n: int, k: int, p: float, q: float, directed=False):
"""
Generate a graph from the symmetric stochastic block model.
Generates a graph with n vertices and k clusters. Every cluster will have floor(n/k) vertices. The probability of
each edge inside a cluster is given by p. The probability of an... | 45,749 |
def get_norm(norm, out_channels):
"""
Args:
norm (str or callable): either one of BN, SyncBN, FrozenBN, GN;
or a callable that takes a channel number and returns
the normalization layer as a nn.Module.
Returns:
nn.Module or None: the normalization layer
"""
if out_channels == 32:
N = ... | 45,750 |
def std_normal_dist_cumulative(lower, upper):
"""
Find the area under the standard normal distribution between
the lower and upper bounds.
Bounds that aren't specified are taken at infinity.
"""
return find_distribution_area(stats.norm, lower, upper) | 45,751 |
def _write_dict_as_json(json_file, rules):
"""Write dictionary as a JSON file."""
with open(json_file, 'w') as f:
json.dump(rules, f, indent=2, sort_keys=True) | 45,752 |
def install_compute_service_scripts():
""" Install slurmd service file """
# slurmd.service
slurmd_service = Path('/usr/lib/systemd/system/slurmd.service')
slurmd_service.write_text(f"""
[Unit]
Description=Slurm node daemon
After=network.target munge.service
Requires=munge.service
ConditionPathExists={... | 45,753 |
def ann_pharm_variant(dataframe, genome, knowledgebase, variant_type):
"""query with chr, start, stop, ref, alt, genome assembly version. Returns all the drugs
targeting the observed variant. """
all_direct_targets = {}
rows = get_variant_list(dataframe)
for r in rows:
direct_target_list = ... | 45,754 |
def test_item(testapp):
"""Markdown processor has to work."""
stream = markdown.process(
testapp,
[
holocron.Item(
{
"content": textwrap.dedent(
"""\
# some title
text with *... | 45,755 |
async def test_locator_do_work_transfer_request_fc_yes_results(config, mocker):
"""Test that _do_work_transfer_request processes each file it gets back from the File Catalog."""
logger_mock = mocker.MagicMock()
lta_rc_mock = mocker.MagicMock()
lta_rc_mock.request = AsyncMock()
lta_rc_mock.request.re... | 45,756 |
def to_pier_settlement(
config: Config,
points: List[Point],
responses_array: List[List[float]],
response_type: ResponseType,
pier_settlement: List[Tuple[PierSettlement, PierSettlement]],
) -> List[List[float]]:
"""Time series of responses to pier settlement.
Args:
config: simulatio... | 45,757 |
def test_setup_polynomial_vandermonde(small_data, vander_enum):
"""Ensures that the Vandermonde matrix and the pseudo-inverse matrix are correct."""
if vander_enum == 0:
# no weights specified
weights = None
poly_order = 2
elif vander_enum == 1:
# uniform 1 weighting
... | 45,758 |
def subtract_something(a, b):
"""
Substracts something from something else.
a: add-able
First thing
b: add-able
Second thing.
Returns:
--------
Result of adding the two.
"""
return a - b | 45,759 |
def last_rådata(datafil, track=None):
"""Last inn rådata fra en gpx-fil eller en GPSLogger csv-fil.
"""
datafil = Path(datafil)
if datafil.suffix == '.gpx':
sjekk_at_gpxpy_er_installert()
return last_rådata_gpx(datafil, track=track)
elif datafil.suffix == '.csv':
if track is ... | 45,760 |
def getAverageStay(date1, date2, hop):
"""
The average number of days a patient stays at a hospital (from admission to discharge)
if hop is None it calculates the stat system wide
"""
count = 0
num = 0
for visit in Appointment.objects.all():
doc = Doctor.objects.get(id=visit.doctorID... | 45,761 |
def classify(inputTree,featLabels,testVec):
"""
决策树分类函数
"""
firstSides = list(myTree.keys())
firstStr = firstSides[0]
secondDict = inputTree[firstStr]
featIndex = featLabels.index(firstStr)
for key in secondDict.keys():
if testVec[featIndex]==key:
if type(secondDict[k... | 45,762 |
def update(sql, *args):
"""
执行update语句,返回update的行数
:param sql:
:param args:
:return:
"""
return _update(sql, *args) | 45,763 |
def videoSize():
"""
videoSize() -> (width, height)
Get the camera resolution.
Returns: A map with two integer values, i.e. width and height.
Parameters: This method does not have any parameter.
Usage: width, heigh = SIGBTools.videoSize()
size = SIGBTools.videoSize()
"""
ret... | 45,764 |
def get_req_from_pdf(fileNameIn, regExp, fileNameOut):
""" transform pdf file fileNameIn in requirements
in json file fileNameOut via reg exp regExp
:arg fileNameIn: pdf file containing requirements
:type fileNameIn: string
:arg regExp: regular expression
:type regExp: string
:ar... | 45,765 |
def generate_md5_token_from_dict(input_params):
""" Generate distinct md5 token from a dictionary.
初衷是为了将输入一个函数的输入参数内容编码为独一无二的md5编码, 方便在其变动的时候进行检测.
Parameters
----------
input_params : dict
Dictionary to be encoded.
Returns
-------
str
Encoded md5 token from input_param... | 45,766 |
def create_range(range_, arrayTest, headers_suppresed = True):
"""
Creates a range string from a start and end value
'A1','A4' becomes 'A1,A2,A3,A4'
"""
result_string = []
first_cell = range_.split(':')[0]
last_cell = range_.split(':')[1]
column_start = re.search(r'[a-zA-Z]+', first_cell... | 45,767 |
def find_largest_helper(n, maximum):
"""
:param n: int, the number to find the largest digit
:param maximum: int, the largest digit
:return: int, the largest digit
"""
if n % 10 > maximum:
maximum = n % 10
if n / 10 == 0:
return maximum
else:
return find_largest_helper(n // 10, maximum) | 45,768 |
def global_align(seq1_1hot, seq2_1hot):
"""Align two 1-hot encoded sequences."""
align_opts = {'gap_open_penalty':10, 'gap_extend_penalty':1, 'match_score':5, 'mismatch_score':-4}
seq1_dna = DNA(dna_io.hot1_dna(seq1_1hot))
seq2_dna = DNA(dna_io.hot1_dna(seq2_1hot))
# seq_align = global_pairwise_align_nucleo... | 45,769 |
def get_points_dist(pt1, pt2):
"""
Returns the distance between a pair of points.
get_points_dist(Point, Point) -> number
Parameters
----------
pt1 : a point
pt2 : the other point
Attributes
----------
Examples
--------
>>> get_points_dist(Point((4, 4)), Point((4, 8))... | 45,770 |
def get_source_type(*, db_session: Session = Depends(get_db), source_type_id: PrimaryKey):
"""Given its unique ID, retrieve details about a single source type."""
source_type = get(db_session=db_session, source_type_id=source_type_id)
if not source_type:
raise HTTPException(
status_code=... | 45,771 |
def get_namefiles(pth, exclude=None):
"""Search through a path (pth) for all .nam files.
Parameters
----------
pth : str
path to model files
exclude : str or lst
File or list of files to exclude from the search (default is None)
Returns
-------
namefiles : lst
L... | 45,772 |
def load_data(messages_filepath, categories_filepath):
""" Get the messages and categories from CSV files. """
messages = pd.read_csv(messages_filepath)
categories = pd.read_csv(categories_filepath)
return messages.merge(categories, on='id', how='left') | 45,773 |
def apply_meth(dna, meth):
"""Transforms DNA sequence to methylated DNA sequence
Input:
dna (np.array): array of DNA sequence
meth (np.array): Methylation labels (len == len(dna))
Output:
dna_meth (np.array): array of methylated DNA sequence
"""
dna_meth = dna.copy()
img ... | 45,774 |
def apply_affine_3D(coords_3d, affine_matrix):
"""
Apply an affine transformation to all coordinates.
Parameters
----------
coords_3d: numpy 2D array
The source coordinates, given as a 2D numpy array with shape (n, 3). Each of the n rows represents a point in space, given by its x, y and z ... | 45,775 |
def pa():
"""Report (all) the diffractometer settings."""
_check_geom_selected()
_geom_.pa() | 45,776 |
def weighted_degree_kernel_pos_inv(x1, x2, K=4, var=8, beacon=None, bin=None):
"""
Weighted degree kernel with positional invariance
:param x1:
Sequence of characters.
:param x2:
Sequence of characters.
:param K:
K-mers to be scanned.
:param beacon:
Beacon sequen... | 45,777 |
def is_valid_block_variable_definition(node: _VarDefinition) -> bool:
"""Is used to check either block variables are correctly defined."""
if isinstance(node, ast.Tuple):
return all(
_is_valid_single(var_definition)
for var_definition in node.elts
)
return _is_valid_s... | 45,778 |
def remove_test_repositories(base_folder: str):
""" Recursively remove a directory subtree. """
# The test_base_folder should not already exist.
if os.path.exists(base_folder):
rmtree(base_folder) | 45,779 |
def julian_day_to_gregorian(julian_day):
"""Converts a Julian Day number to its (proleptic) Gregorian calendar equivalent
Adapted from: https://en.wikipedia.org/wiki/Julian_day#Julian_or_Gregorian_calendar_from_Julian_day_number
Note that the algorithm is only valid for Julian Day numbers greater than or
... | 45,780 |
def muro_19():
"""muro_19"""
check50.run("python3 costear.py").stdin("VP-PV----------------PVPVPVV", prompt=False).stdout("160", regex=False).exit(0) | 45,781 |
def isnotebook():
"""Identify shell environment."""
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
if shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
... | 45,782 |
def erratic_leveling(target_level: int) -> int:
"""
Non-trivial calculation of experience to next level for an erratic leveling curve.
Args:
target_level (int): the level to reach.
Returns:
The amount of experience to reach this level from the ground up (from experience 0),
acc... | 45,783 |
def test_run_failure_switches(tmp_path, sample_catalog_minimal):
"""Test failure of _run on bad switches for RemoveCmd."""
# 1. Missing --file argument.
testargs = ['trestle', 'remove', '-e', 'catalog.metadata.roles']
with patch.object(sys, 'argv', testargs):
with pytest.raises(SystemExit) as e:... | 45,784 |
def get_puppetfile_tags(puppetfile):
"""
obtain tags from Puppetfile
:return: tuple(list, list)
"""
regex_vcs = re.compile(r"^:(git|svn)\s+=>\s+['\"](.+)['\"]\,", re.I)
regex_tag = re.compile(r"^:(ref|tag|commit|branch)\s+=>\s+['\"](.+)['\"]\,?", re.I)
vcss = []
tags = []
with open(... | 45,785 |
def test_init_skip_connect_on_init_false(proxy_minion_config):
"""
check netmiko_proxy init method
"""
proxy_minion_config["skip_connect_on_init"] = False
mock_make_con = MagicMock()
with patch.object(netmiko_proxy, "make_con", mock_make_con):
assert netmiko_proxy.init(proxy_minion_con... | 45,786 |
def inf_is_wide_high_byte_first(*args):
"""
inf_is_wide_high_byte_first() -> bool
"""
return _ida_ida.inf_is_wide_high_byte_first(*args) | 45,787 |
def rewrite_and_sanitize_link(link_header):
"""Sanitize and then rewrite a link header."""
return rewrite_links(sanitize_link(link_header)) | 45,788 |
def trans_slug_save(obj, slug_len=DEFAULT_SLUG_LENGTH, allowed_chars="0123456789"):
""" A function to generate a slug_len character slug and see if it has been used and contains naughty words."""
if not obj.transaction_hash: # if there isn't a slug
obj.transaction_hash = get_random_string(slug_len, allo... | 45,789 |
def reload_mapper(metadata, now):
"""<comment-ja>
Option(Model)のマッパーをリロードします。
@param metadata: リロードしたいMetaData
@type metadata: sqlalchemy.schema.MetaData
@param now: now
@type now: Datatime
</comment-ja>
<comment-en>
TODO: English Comment
</comment-en>
"""
t_option = get_... | 45,790 |
def listen_keyboard(
on_press: Optional[Callable[[str], Any]] = None,
on_release: Optional[Callable[[str], Any]] = None,
until: Optional[str] = "esc",
sequential: bool = False,
delay_second_char: float = 0.75,
delay_other_chars: float = 0.05,
lower: bool = True,
debug: bool = False,
... | 45,791 |
def user_info():
"""
用户个人中心页面显示
:return:
"""
user = g.user
if not user:
return redirect("/")
data = {
"user": user.to_dict()
}
return render_template("news/user.html", data=data) | 45,792 |
def compare_var(varname, array1, array2, rounding_error, idarray):
"""
Summarize differences between array1 and array2.
"""
rawdiff = array1 - array2
diff = rawdiff.round(2)
absdiff = np.abs(diff)
max_absdiff = np.amax(absdiff)
if max_absdiff <= rounding_error:
return # array1 a... | 45,793 |
def cartesian2polar(state: CartesianState, state_goal : CartesianState) -> PolarState:
"""
rho is the distance between the robot and the goal position
: \sqrt((x*-x)^2 + (y*-y)^2)
alpha is the heading of the robot relative the angle to the goal
: theta - atan2((y*-y),(x*-x))
beta is the goal pos... | 45,794 |
def _run_qmake(target_config, verbose, pro_name, module_config):
""" Run qmake against a .pro file. target_config is the target
configuration. verbose is set if the output is to be displayed. pro_name
is the name of the .pro file. module_config is the module configuration.
"""
inform("Creating ... | 45,795 |
def test_atomic_hex_binary_pattern_2_nistxml_sv_iv_atomic_hex_binary_pattern_3_2(mode, save_output, output_format):
"""
Type atomic/hexBinary is restricted by facet pattern with value
[0-9A-F]{18}.
"""
assert_bindings(
schema="nistData/atomic/hexBinary/Schema+Instance/NISTSchema-SV-IV-atomic... | 45,796 |
def set_verbosity(verbosity: int = 0):
"""Sets the verbosity level of the console output"""
global __verbosity
assert isinstance(
verbosity,
int), f"verbosity should be <class \'int\'> and not {str(type(verbosity))}"
assert verbosity >= 0, f"verbosity should be >= 0 and not {verbosity}"
__verbosity ... | 45,797 |
def organize_array_by_rows(unformatted_array, num_cols):
"""Take unformatted array and make grid array"""
num_rows = int(len(unformatted_array) / num_cols)
array = []
for row in range(num_rows):
array.append(unformatted_array[row * num_cols:(row + 1) * num_cols])
return array | 45,798 |
def group_abundance(
adata: AnnData,
groupby: str,
target_col: str = "has_ir",
*,
fraction: Union[None, str, bool] = None,
sort: Union[Literal["count", "alphabetical"], Sequence[str]] = "count",
) -> pd.DataFrame:
"""Summarizes the number/fraction of cells of a certain category by a certain ... | 45,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.