content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def read_loss_file(path):
"""Read the given loss csv file and process its data into lists that can be
plotted by matplotlib.
Args:
path (string): The path to the file to be read.
Returns: A list of lists, one list for each subnetwork containing the loss
values over time.
"""
... | 26,000 |
def number2human(n: Union[int, float]) -> str:
"""
Format large number into readable string for a human
Examples:
>>> number2human(1000)
'1.0K'
>>> number2human(1200000)
'1.2M'
"""
# http://code.activestate.com/recipes/578019
# >>> bytes2human(10000)
# '9.8... | 26,001 |
def binomial_confidence_interval(successes, trials, error_rate):
"""Computes a confidence interval on the true p of a binomial.
Assumes:
- The given `successes` count outcomes of an iid Bernoulli trial
with unknown probability p, that was repeated `trials` times.
Guarantees:
- The probability (over the ... | 26,002 |
def try_parse_func_decl(start, end):
"""Parse a function declarator between start and end.
Expects that tokens[end-1] is a close parenthesis. If a function
declarator is successfully parsed, returns the decl_node.Function
object. Otherwise, returns None.
"""
open_paren = find_pair_backward(end ... | 26,003 |
def eth_getBlockTransactionCountByNumber(block_number: int) -> int:
""" See EthereumAPI#get_block_transaction_count_by_number. """
with contextlib.closing(EthereumAPI()) as api:
return api.get_block_transaction_count_by_number(block_number) | 26,004 |
def day(db: Database, site: str = 'test', tag: str = '', search_body: str = '') -> List[Any]:
"""
戻り値 名前付きタプルのリスト # xxx List[DayCount] するにはclass DayCount(NamedTuple) 必要 pypy…
"""
tag_where = ''
body_where = ''
param = [site] # type: List[Union[str, int]]
if tag != '':
tag_where = "AND (tags like ? or tags li... | 26,005 |
def init_data(my_data, rp):
""" initialize the sod problem """
msg.bold("initializing the sod problem...")
# make sure that we are passed a valid patch object
if not isinstance(my_data, patch.CellCenterData2d):
print("ERROR: patch invalid in sod.py")
print(my_data.__class__)
sy... | 26,006 |
def xml_files_list(path):
"""
Return the XML files found in `path`
"""
return (f for f in os.listdir(path) if f.endswith(".xml")) | 26,007 |
def helloLoop(name_list):
"""assumes name_list is a list of strings, representing names
prints a greeting for each name in name_list"""
for name in name_list:
print("Hello!, " + name) | 26,008 |
def ppv2(
aim_stars=None, speed_stars=None, max_combo=None,
nsliders=None, ncircles=None, nobjects=None, base_ar=5.0,
base_od=5.0, mode=MODE_STD, mods=MODS_NOMOD, combo=None,
n300=None, n100=0, n50=0, nmiss=0, score_version=1, bmap=None
):
"""
calculates ppv2
returns (pp, aim_pp, speed_pp, ... | 26,009 |
def frame_shows_car(base_dir, frame, data_dir):
"""Return True if frame shows car. """
sem_seg = cv2.imread(os.path.join(base_dir, "semantic_segmentation/semantic_segmentation" + str(frame) + ".png"),
-1)
class_id_dict = pre_processing.get_dict_from_file(data_dir, "class_id_legend.t... | 26,010 |
def p_portail_home(request):
""" Portail d'accueil de CRUDY """
crudy = Crudy(request, "portail")
title = crudy.application["title"]
crudy.folder_id = None
crudy.layout = "portail"
return render(request, 'p_portail_home.html', locals()) | 26,011 |
def test_standardReceive():
"""Test StandardReceive."""
address = bytearray([0x11, 0x22, 0x33])
target = bytearray([0x44, 0x55, 0x66])
flags = 0x77
cmd1 = 0x88
cmd2 = 0x99
msg = StandardReceive(address, target, {'cmd1': cmd1, 'cmd2': cmd2},
flags=flags)
assert ... | 26,012 |
def check_eyr(eyr):
"""eyr (Expiration Year) - four digits; at least 2020 and at most 2030."""
year = int(eyr)
if year < 2020 or 2030 < year:
raise | 26,013 |
def generate_image_list(dir_path, max_dataset_size=float("inf")):
"""
Traverse the directory to generate a list of images path.
Args:
dir_path (str): image directory.
max_dataset_size (int): Maximum number of return image paths.
Returns:
Image path list.
"""
images = [... | 26,014 |
def A_norm(freqs,eta):
"""Calculates the constant scaling factor A_0
Parameters
----------
freqs : array
The frequencies in Natural units (Mf, G=c=1) of the waveform
eta : float
The reduced mass ratio
"""
const = np.sqrt(2*eta/3/np.pi**(1/3))
return const*freqs**-(7/6) | 26,015 |
def task1(input_io: IO) -> int:
"""
Solve task 1.
Parameters
----------
input_io: IO
Day10
stream of adapters joltage.
Return
------
int
number of differentes of 1 times number of diferences of 3.
"""
numbers = list(read_numbers(input_io))
numbers.appen... | 26,016 |
def get_logger(name, log_dir, config_dir):
"""
Creates a logger object
Parameters
----------
name: Name of the logger file
log_dir: Directory where logger file needs to be stored
config_dir: Directory from where log_config.json needs to be read
Returns
-------
A logger object which wri... | 26,017 |
def include(*sources: Union[FileSource, str], swim):
"""
include a source with its preprocessor directives
:param sources: the source objects or paths to cpp header files
"""
lines = []
for source in sources:
if isinstance(source, str):
if source.startswith('<') or source.sta... | 26,018 |
def test_varint__underflow():
"""Crash if VLQ gets a negative number."""
field = numeric.VariableLengthInteger(vli_format=varints.VarIntEncoding.VLQ)
with pytest.raises(errors.UnserializableValueError):
field.to_bytes(-1) | 26,019 |
def get_total_balance(view_currency='BTC') -> float:
"""
Shows total balance for account in chosen currency
:param view_currency: currency for total balance
:return: total balance amount for account
"""
result = pay.get_balance()
balance_dict = result.get('balance')
total = 0
for cur... | 26,020 |
def target_install():
"""Use the setup.py script to install."""
log.info("target: install")
_run("python setup.py install") | 26,021 |
def bin_hex(binary):
"""
Convert bytes32 to string
Parameters
----------
input: bytes object
Returns
-------
str
"""
return binascii.hexlify(binary).decode('utf-8') | 26,022 |
def get_component_observers(component: Dict[str, Any],
observer_type: str = 'qp',
**observer_kwargs):
"""Get component-based Observers."""
del component, observer_kwargs
raise NotImplementedError(observer_type) | 26,023 |
def build_format(name: str, pattern: str, label: bool) -> str:
"""Create snippet format.
:param name: Instruction name
:param pattern: Instruction regex pattern
"""
snip: str = f"{name:7s}" + pattern.format(**SNIPPET_REPLACEMENTS)
snip = snip.replace("(", "")
snip = snip.replace(")", "")
... | 26,024 |
def make_observation_mapper(claims):
"""Make a dictionary of observation.
Parameters
----------
claims: pd.DataFrame
Returns
-------
observation_mapper: dict
an dictionary that map rv to their observed value
"""
observation_mapper = dict()
for c in claims.index:
... | 26,025 |
def toCSV(
dataset, # type: BasicDataset
showHeaders=True, # type: Optional[bool]
forExport=False, # type: Optional[bool]
localized=False, # type: Optional[bool]
):
# type: (...) -> String
"""Formats the contents of a dataset as CSV (comma separated
values), returning the resulting CSV a... | 26,026 |
def test_driver_add_container_record(index_driver, database_conn):
"""
Tests creation of a record.
"""
index_driver.add('container')
count = database_conn.execute("""
SELECT COUNT(*) FROM index_record
""").fetchone()[0]
assert count == 1, 'driver did not create record'
record... | 26,027 |
def add_record(session, data):
"""
session -
data - dictionary {"site":"Warsaw"}
"""
skeleton = Skeleton()
skeleton.site = data["site"]
skeleton.location = data["location"]
skeleton.skeleton = data["skeleton"]
skeleton.observer = data["observer"]
skeleton.obs_date = dat... | 26,028 |
def pytest_tavern_beta_before_every_test_run(test_dict, variables):
"""Called:
- directly after fixtures are loaded for a test
- directly before verifying the schema of the file
- Before formatting is done on values
- After global configuration has been loaded
- After plugins have been loaded
... | 26,029 |
def insert_player_in_db(player):
"""Add player object in database."""
player = encode_class_to_dict(player)
db.player_table.insert(player) | 26,030 |
def hue_angle(C):
"""
Returns the *hue* angle :math:`h` in degrees from given colour difference
signals :math:`C`.
Parameters
----------
C : array_like
Colour difference signals :math:`C`.
Returns
-------
numeric or ndarray
*Hue* angle :math:`h` in degrees.
Exa... | 26,031 |
def get_submodel_list_copasi(model_name: str,
model_info: pd.DataFrame):
"""
This function loads a list of Copasi model files, which all belong to the
same benchmark model, if a string with the id of the benchmark model id is
provided.
It also extracts the respective sbm... | 26,032 |
def GetNextBmask(enum_id, value):
"""
Get next bitmask in the enum (bitfield)
@param enum_id: id of enum
@param value: value of the current bitmask
@return: value of a bitmask with value higher than the specified
value. -1 if no such bitmasks exist.
All bitmas... | 26,033 |
def nbshell(context):
"""Launch an interactive nbshell session."""
command = "nautobot-server nbshell"
run_command(context, command) | 26,034 |
def post_measurement(database) -> None:
"""Put the measurement in the database."""
measurement = dict(bottle.request.json)
latest = latest_measurement(measurement["metric_uuid"], database)
if latest:
for latest_source, new_source in zip(latest["sources"], measurement["sources"]):
if ... | 26,035 |
def annotate_link(domain):
"""This function is called by the url tag. Override to disable or change behaviour.
domain -- Domain parsed from url
"""
return u" [%s]"%_escape(domain) | 26,036 |
def kmeans(data, k, num_iterations, num_inits=10, verbose=False):
"""Execute the k-means algorithm for
determining the best k clusters of data
points in a dataset.
Parameters
----------
data : ndarray, (n,d)
n data points in R^d.
k : int
The number of clusters to separat... | 26,037 |
def main(es_host, es_index_1, es_index_2, es_type):
"""
The main function
:param es_host: elastic search host server
:param es_index_1: the index prefix 1
:param es_index_2: the index prefix 2
:param es_type: the type of records to be compared
:return:
"""
error_flag = False
if n... | 26,038 |
def add_figure(bbox=None, slide_no=None, keep_aspect=True, tight=True,
delete_placeholders=True, replace=False, **kwargs):
""" Add current figure to the active slide (or a slide with a given number).
Parameters:
bbox - Bounding box for the image in the format:
... | 26,039 |
def com_google_fonts_check_metadata_match_weight_postscript(font_metadata):
"""METADATA.pb weight matches postScriptName for static fonts."""
WEIGHTS = {
"Thin": 100,
"ThinItalic": 100,
"ExtraLight": 200,
"ExtraLightItalic": 200,
"Light": 300,
"LightItalic": 300,
... | 26,040 |
def point_on_bezier_curve(cpw, n, u):
"""
Compute point on Bezier curve.
:param ndarray cpw: Control points.
:param int n: Degree.
:param u: Parametric point (0 <= u <= 1).
:return: Point on Bezier curve.
:rtype: ndarray
*Reference:* Algorithm A1.4 from "The NURBS Book".
"""
b... | 26,041 |
def list_with_one_dict(sort_type, url_param=None):
"""
Search by parameter that returns a list with one dictionary.
Used for full country name and capital city.
"""
extra_param = ""
if sort_type == 2:
url_endpoint = "/name/"
user_msg = "full country name"
extra_param... | 26,042 |
def wait_then_open_async(url):
"""
Spawns a thread that waits for a bit then opens a URL.
"""
t = threading.Thread(target=wait_then_open, args=({url}))
t.daemon = True
t.start() | 26,043 |
def get_form(case, action_filter=lambda a: True, form_filter=lambda f: True, reverse=False):
"""
returns the first form that passes through both filter functions
"""
gf = get_forms(case, action_filter=action_filter, form_filter=form_filter, reverse=reverse)
try:
return gf.next()
except S... | 26,044 |
def csv_to_json_generator(df, field_map: dict, id_column: str, category_column: str):
"""
Creates a dictionary/json structure for a `single id dataframe` extracting content using the
`extract_features_by_category` function.
"""
id_list = find_ids(df=df, id_column=id_column)
logger.info('Found {}... | 26,045 |
def write_to_csv(filename, emb_paths, emb_array, exp_time, register_order_file=None):
"""Write to csv file in the format of: [name, features, threshold, path]
Args:
filename: The filename of output csv file
emb_paths: The image paths of the embeddings
emb_array: The embeddings generated ... | 26,046 |
def mark_battle_reported(database_key):
"""
Marks a battle from the reporting queue as reported, given a database_key retrieved from get_next_battle_to_report.
If this method isn't called, get_next_battle_to_report will start returning already-reported battles once it has
returned each battle once.
... | 26,047 |
def eval_args(egroup, show_supsup_task_inference=False):
"""This is a helper function of the function :func:`parse_cmd_arguments` to
add arguments to the evaluation argument group.
Args:
egroup: The argument group returned by function
:func:`utils.cli_args.eval_args`.
show_supsu... | 26,048 |
def write_flag_drawing(img, filename_out):
"""Write an image to a file in the flag_drawings directory"""
save_img(img, 'flag_drawings', filename_out) | 26,049 |
def parse_args():
"""Get command line arguments."""
parser = argparse.ArgumentParser(prog='metrics',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=desc_str)
parser.add_argument('-v', '--version', action='version', ... | 26,050 |
def sunset_hour_angle(sinLat, cosLat, sinDec, cosDec):
"""
Calculate local sunset hour angle (radians) given sines and cosines
of latitude and declination.
"""
return np.arccos(np.clip(-sinDec / cosDec * sinLat / cosLat, -1, 1)) | 26,051 |
def handle_enable(options):
"""Enable a Sopel plugin.
:param options: parsed arguments
:type options: :class:`argparse.Namespace`
:return: 0 if everything went fine;
1 if the plugin doesn't exist
"""
plugin_names = options.names
allow_only = options.allow_only
settings = ut... | 26,052 |
def compare_img_hist(img_path_1, img_path_2):
"""
Get the comparison result of the similarity by the histogram of the
two images. This is suitable for checking whether the image is close
in color. Conversely, it is not suitable for checking whether shapes
are similar.
Parameters
---... | 26,053 |
def test_get_queryset_duplicates(
api_rf, km_user_accessor_factory, km_user_factory, user_factory
):
"""
If the user has managed to create an accessor granting access to
their own account, there should not be a duplicate entry in the user
list.
Regression test for #352.
"""
user = user_... | 26,054 |
def recombinant_example(resource_name, doc_type, indent=2, lang='json'):
"""
Return example data formatted for use in API documentation
"""
chromo = recombinant_get_chromo(resource_name)
if chromo and doc_type in chromo.get('examples', {}):
data = chromo['examples'][doc_type]
elif doc_ty... | 26,055 |
def _integral_diff(x, pdf, a, q):
"""Return difference between q and the integral of the function `pdf`
between a and x. This is used for solving for the ppf."""
return integrate.quad(pdf, a, x)[0] - q | 26,056 |
def loadBar(self):
"""载入历史K线数据"""
pdData = pd.DataFrame(self.bars).set_index('datetime')
self.uiKLine.loadData(pdData)
for s in self.mainSigs:
self.plotMain(s)
for s in self.subSigs:
self.plotSub(s)
self.uiKLine.updateSig(self.sigs)
self.bar = self.strategy.bar
# ------... | 26,057 |
def update_df_slab_ids():
"""
"""
#| - update_df_slab_ids
# #####################################################
# Read Data
from methods import get_df_slab_ids
df_slab_ids = get_df_slab_ids()
from methods import get_df_slab
df_slab = get_df_slab()
# #########################... | 26,058 |
def Fcomplete(t,y,k0m,k1,k2m,k2p,k3,k4,k5m,k6m,k7,Kr0,Kr1,Kr2,Kr2p,Km5,Km6,Km7,Gt,Rt,Mt,k_Gp,Gpt,n):
"""
Right hand side of ODE y'(t) = f(t,y,...)
It receives parameters as f_args, as given py param_array (see param.py)
3 components: G, R, M
"""
k0=k0m*Kr0 # kmi =ki/Kri or ki/Kmi
k2=k2m*Kr2... | 26,059 |
def lu_solve(l: np.ndarray, u: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Решение СЛАУ, прошедшей через LU-разложение.
Требуется предварительно умножить вектор правых частей на матрицу перестановки.
:param l: нижняя треугольная матрица
:param u: верхняя треугольная матрица
:param b: вектор правых... | 26,060 |
def test_finding_logdate(dispatcher, ntbk_dir, mocker):
"""Test using --find-dir flag outputs path to specified date"""
mocker.patch('builtins.print')
expected_path = ntbk_dir / 'log/2021/01-january/2021-01-01'
dispatcher.run(['today', '--find-dir'])
print.assert_called_once_with(expected_path) | 26,061 |
def test_sum_with_incompatible_types(table):
"""
Must error out:
Invalid UpdateExpression: Incorrect operand type for operator or function; operator or function: +, operand type: S'
Returns:
"""
try:
update_expression = "SET ri = :val + :val2"
update_expression_ast = UpdateExpre... | 26,062 |
def test_order_view_permissions(client, user):
"""A user should not be able to access order data if it does not belong to them"""
random_user = UserFactory.create(is_staff=False, is_superuser=False)
order = OrderFactory.create(user=user)
client.force_login(random_user)
resp = client.get(reverse("ord... | 26,063 |
def datetime_to_httpdate(input_date):
# type: (datetime) -> Optional[str]
"""Converts datetime to http date string"""
if input_date is None:
return None
try:
return input_date.strftime(HTTP_DATE_FORMAT)
except (ValueError, TypeError) as e:
logger.debug(e)
return None | 26,064 |
def test_evolution_trigger_list(client: TestClient):
"""Test case for evolution_trigger_list
"""
params = [("limit", 56), ("offset", 56)]
headers = {
}
response = client.request(
"GET",
"/api/v2/evolution-trigger/",
headers=headers,
params=params,
)
... | 26,065 |
def scanner(url, scan_time=None):
"""
Scan files in the MDSS tape store
"""
if isinstance(url, str):
url = urlparse(url)
project = url.netloc
path = url.path
if project == '':
raise Exception('No MDSS project specified')
cmd = ['/opt/bin/mdss', '-P', project, 'dmls', '... | 26,066 |
def textToSheet(directory, filename):
"""converts text files to columns in excel worksheet
Args:
directory (str): folder containing text files
filename (str): name of excel file
Returns:
None
"""
wb = openpyxl.Workbook()
wb.create_sheet(index=0, title='result')
sheet ... | 26,067 |
def zr_bfr_tj():
"""
Real Name: b'Zr bfr Tj'
Original Eqn: b'Zr aftr Dam-Wr sup aftr Zr Dam+(Wr sup aftr Zr Dam*0.2)'
Units: b''
Limits: (None, None)
Type: component
b''
"""
return zr_aftr_dam() - wr_sup_aftr_zr_dam() + (wr_sup_aftr_zr_dam() * 0.2) | 26,068 |
def save_db():
"""Save the local db variable to the database"""
global db
database.set(bot, db, 'tell') | 26,069 |
def simplify(n):
"""Remove decimal places."""
return int(round(n)) | 26,070 |
def resnet_qc_18(**kwargs):
"""Constructs a ResNet-18 model."""
model = ResNetQC(BasicBlock, [2, 2, 2, 2], **kwargs)
return model | 26,071 |
def test_check_conda_pkg_dir():
"""
Test that the check_conda_pkg_dir correctly replaces an installed ggd .tar.bz2 if it has been removed from the conda pkg dir
"""
## Test prefix not set:
### Temp conda environment
temp_env = os.path.join(utils.conda_root(), "envs", "check_pkg_info_dir")
... | 26,072 |
def sparse_from_npz(file, **_kw):
"""
Possible dispatch function for ``from_path_impl``'s ``from_npz``.
Reads a scipy sparse matrix.
"""
import scipy.sparse
return scipy.sparse.load_npz(file) | 26,073 |
def get_config():
"""
Read the configuration
:returns: current configuration
"""
global config
return copy.deepcopy(config) | 26,074 |
def resnext20_2x64d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (2x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
p... | 26,075 |
def test_target(target):
"""Returns the label for the corresponding target in the test tree."""
label = to_label(target)
test_package = label.package.replace("src/main/", "src/test/", 1)
return Label("@{workspace}//{package}:{target_name}".format(
workspace = label.workspace_name,
packag... | 26,076 |
def save_gif(
data: Union[np.ndarray, torch.Tensor],
path: str,
duration: float = 2.0,
loop: int = 0,
):
"""Save a GIF from a tensor.
Args:
data: Tensor of shape (N, H, W).
path: Path to save the gif to.
duration: GIF duration.
loop: Number of loops. 0 means infi... | 26,077 |
def pred_fwd_rc(model, input_npy, output_fwd, output_rc, replicates=1, batch_size=512):
"""Predict pathogenic potentials from a preprocessed numpy array and its reverse-complement."""
y_fwd, _ = predict_npy(model, input_npy, output_fwd, rc=False, replicates=replicates, batch_size=batch_size)
y_rc, _ = predi... | 26,078 |
def get_ids(viva_path, dataset):
"""Get image identifiers for corresponding list of dataset identifies.
Parameters
----------
viva_path : str
Path to VIVA directory.
datasets : list of str tuples
List of dataset identifiers in the form of (year, dataset) pairs.
Returns
----... | 26,079 |
def get_api_version(version_string):
"""Returns checked APIVersion object"""
version_string = str(version_string)
api_version = APIVersion(version_string)
check_major_version(api_version)
return api_version | 26,080 |
def test_show_versions():
"""should show all versions if no value is given"""
results = yvs.get_result_list('version')
nose.assert_greater(len(results), 10) | 26,081 |
def evaluate_g9( tau7, tau8, tau9, tau10, tau11, s9 ):
"""
Evaluate the ninth constraint equation and also return the Jacobian
:param float tau7: The seventh tau parameter
:param float tau8: The eighth tau parameter
:param float tau9: The ninth tau parameter
:param float tau10: The tenth tau pa... | 26,082 |
def qmul(*q, qaxis=-1):
""" Quaternion multiplication.
Parameters
----------
q: iterable of array_like
Arrays containing quaternions to multiply. Their dtype can be
quaternion, otherwise `qaxis` specifies the axis representing
the quaternions.
qaxis: int, default -1
... | 26,083 |
def test_example_4p14():
"""Test example 4.14 in "RF and Microwave Engineering" - Gustrau """
# Waveguide cavity dimensions
a, b, d = 24*sc.milli, 10*sc.milli, 40*sc.milli
# They use c = 3e8 m/s (I mean come on...)
corr = 3e8 / sc.c
# Test values
abs_tol = 0.001e9
assert wg... | 26,084 |
def iterable(value,
allow_empty = False,
forbid_literals = (str, bytes),
minimum_length = None,
maximum_length = None,
**kwargs):
"""Validate that ``value`` is a valid iterable.
.. hint::
This validator checks to ensure that ``value`` supp... | 26,085 |
def GenerateClusterCrypto(new_cluster_cert, new_rapi_cert, new_spice_cert,
new_confd_hmac_key, new_cds,
rapi_cert_pem=None, spice_cert_pem=None,
spice_cacert_pem=None, cds=None,
nodecert_file=pathutils.NODED_CERT_FIL... | 26,086 |
def settings_notification(color: bool, messages: List[ExitMessage]) -> Form:
"""Generate a warning notification for settings errors.
:param messages: List of messages to display
:param color: Bool to reflect if color is transferred or not
:returns: The form to display
"""
# Take the initial war... | 26,087 |
def message_type(ctx: 'Context', *types):
"""Filters massage_type with one of selected types.
Assumes update_type one of message, edited_message, channel_post, edited_channel_post.
:param ctx:
:param types:
:return: True or False
"""
m = None
if ctx.update.update_type is UpdateType.me... | 26,088 |
def VSphere(R):
"""
Volume of a sphere or radius R.
"""
return 4. * math.pi * R * R * R / 3. | 26,089 |
def test_user_level_override_base_level_with_same_name():
"""Test that user level that overrides a base level with same name finds flags.."""
base_config_file = os.path.join(os.path.dirname(__file__), "rsc", "config.yaml")
user_config_file = os.path.join(
os.path.dirname(__file__), "rsc", "user-leve... | 26,090 |
def resolve_variable(
var_name: str,
var_def: BlueprintVariableTypeDef,
provided_variable: Optional[Variable],
blueprint_name: str,
) -> Any:
"""Resolve a provided variable value against the variable definition.
Args:
var_name: The name of the defined variable on a blueprint.
va... | 26,091 |
def launch_servers_and_wait():
"""
Run a prometheus and grafana server, then suspend the thread
(ensuring prometheus remains up in case a task shuts it down).
Closes resources on Ctrl-C
"""
try:
print("Servers launching...")
if not launch_grafana_server():
print("Issu... | 26,092 |
def generate_navbar(structure, pathprefix):
"""
Returns 2D list containing the nested navigational structure of the website
"""
navbar = []
for section in structure['sections']:
navbar_section = []
section_data = structure['sections'][section]
section_url = os.path.join('/', ... | 26,093 |
def process_map(file_in, validate):
"""Iteratively process each XML element and write to csv(s)"""
with codecs.open(NODES_PATH, 'w') as nodes_file, \
codecs.open(NODE_TAGS_PATH, 'w') as nodes_tags_file, \
codecs.open(WAYS_PATH, 'w') as ways_file, \
codecs.open(WAY_NODES_PATH, 'w') as... | 26,094 |
def additional_args(**kwargs):
"""
Additional command-line arguments.
Provides additional command-line arguments that are unique to the extraction process.
Returns
-------
additional_args : dict
Dictionary of tuples in the form (fixed,keyword) that can be passed to an argument... | 26,095 |
def extract_images_url(url, source):
"""
Extract image url for a chapter
"""
r = s.get(url)
tree = html.fromstring(r.text)
if source == 'blogtruyen':
return tree.xpath('//*[@id="content"]/img/@src')
elif source == 'nettruyen':
return tree.xpath('//*[@class="reading-detail box... | 26,096 |
def _ntuple_paths(
general_path: str,
region: Dict[str, Any],
sample: Dict[str, Any],
systematic: Dict[str, Any],
template: Optional[Literal["Up", "Down"]],
) -> List[pathlib.Path]:
"""Returns the paths to ntuples for a region-sample-systematic-template.
A path is built starting from the pa... | 26,097 |
def svn_ra_do_diff2(*args):
"""
svn_ra_do_diff2(svn_ra_session_t session, svn_revnum_t revision, char diff_target,
svn_boolean_t recurse, svn_boolean_t ignore_ancestry,
svn_boolean_t text_deltas,
char versus_url, svn_delta_editor_t diff_editor,
void diff_baton, apr_pool_t... | 26,098 |
def ntuple_dict_length(ntuple_dict):
"""Returns a dictionary from track types to the number of tracks of
that type. Raises an exception of any value lists within one of its
track properties dicts are different lengths."""
return dict(map(lambda track_type, track_prop_dict:
(track_type, track_pr... | 26,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.