content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def eig_min(a, eps=1e-7, kmax=1e3, log=False):
"""
:param a: matrix to find min eigenvalue of
:param eps: desired precision
:param kmax: max number of iterations allowed
:param log: whether to log the iterations
"""
mu_1 = eig_max_abs(a, eps, kmax, log)
return mu_1 - eig_max_abs(mu_1 * np.eye(a.shape[0]) - a... | 8,200 |
def relacao(lista):
"""Crie uma função que recebe uma lista de números reais e retorna uma outra lista de tamanho 3 em que
(i) o primeiro elemento é a quantidade de números maiores que zero,
(ii) o segundo elemento é a quantidade de números menores que zero e
(iii) o último elemento é a quantidade de... | 8,201 |
def require_python(minimum):
"""Python version check."""
if sys.hexversion < minimum:
hversion = hex(minimum)[2:]
if len(hversion) % 2 != 0:
hversion = "0" + hversion
split = list(hversion)
parts = []
while split:
parts.append(int("".join((split.po... | 8,202 |
def _input_to_dictionary(input_):
"""Convert.
Args:
input_: GraphQL "data" dictionary structure from mutation
Returns:
result: Dict of inputs
"""
# 'column' is a dict of DB model 'non string' column names and their types
column = {
'idx_user': DATA_INT,
'enable... | 8,203 |
def creature_ability_116(field, player, opponent, virtual, target, itself):
"""
Fanfare: Put Coco and Mimi into your hand.
"""
put_card_in_hand(field,player,virtual,name="Mimi",card_category="Spell")
put_card_in_hand(field, player, virtual, name="Coco", card_category="Spell") | 8,204 |
def validate(request):
"""Validate an authentication request."""
email_token = request.GET.get('a')
client_token = request.GET.get('b')
user = authenticate(email_token=email_token, counter_token=client_token)
if user:
login(request, user)
return redirect(request.GET.get('success', '/... | 8,205 |
def strip_chr(bt):
"""Strip 'chr' from chromosomes for BedTool object
Parameters
----------
bt : pybedtools.BedTool
BedTool to strip 'chr' from.
Returns
-------
out : pybedtools.BedTool
New BedTool with 'chr' stripped from chromosome names.
"""
try:
df = pd... | 8,206 |
def fit_slice(fitter, sliceid, lbda_range=[5000, 8000], nslices=5, **kwargs):
""" """
fitvalues = fitter.fit_slice(lbda_ranges=lbda_range, metaslices=nslices,
sliceid=sliceid, **kwargs)
return fitvalues | 8,207 |
def test(monkeypatch, is_windows, mode):
"""Test function.
:param monkeypatch: pytest fixture.
:param bool is_windows: Monkeypatch terminal_io.IS_WINDOWS
:param str mode: Scenario to test for.
"""
monkeypatch.setattr('terminaltables.terminal_io.IS_WINDOWS', is_windows)
kernel32 = MockKernel... | 8,208 |
def test_all_shorthand(count):
""" scope.all is a shorthand for creating a scope and runninig things in it """
async def foo(mark):
count(mark)
@ayo.run_as_main()
async def main(run):
run.all(foo(1), foo(2), foo(3))
assert count == 3, "All coroutines have been called exactly once" | 8,209 |
def create_project(name=None, id=None, description=None, clientRequestToken=None, sourceCode=None, toolchain=None, tags=None):
"""
Creates a project, including project resources. This action creates a project based on a submitted project request. A set of source code files and a toolchain template file can be i... | 8,210 |
def test_chain_rewrite_save_last():
"""Take chain of length 5, save last node. This saved no memory, and is
and edge case that should raise exception by rewriter."""
tf.reset_default_graph()
tf_dev = tf.device('/cpu:0')
tf_dev.__enter__()
n = 5
a0, a1, a2, a3, a4 = make_chain_tanh(n)
try:
gr... | 8,211 |
def build_routes(app):
"""Register routes to given app instance."""
app.config.update({
'APISPEC_SPEC':
APISpec(
title=SERVICE_NAME,
openapi_version=OPENAPI_VERSION,
version=API_VERSION,
plugins=[MarshmallowPlugin()],
... | 8,212 |
def execute_sync(function, sync_type):
"""
Synchronize with the disassembler for safe database access.
Modified from https://github.com/vrtadmin/FIRST-plugin-ida
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
output = [None]
#
# this inline function defin... | 8,213 |
def mk_living_arrangements(data_id, data): # measurement group 11
"""
transforms a f-living-arrangements.json form into the triples used by insertMeasurementGroup to
store each measurement that is in the form
:param data_id: unique id from the json form
:param da... | 8,214 |
def command_report(subargv):
"""Output a report from the results of the jobs command."""
# Directory in which the reports are
# [positional]
reports: Argument
# Comparison file
compare: Argument & config = default(None)
# Weights file to compute the score
weights: Argument & config = ... | 8,215 |
def process_reporter(data_inserter):
"""
Process device aircraft data
"""
total_inserted, errors = data_inserter()
print(f'INFO: Total inserted records: {total_inserted}')
if errors:
for (record, err) in errors:
record_json = json.dumps(record) if record else 'NotFound'
joined_errors = json.... | 8,216 |
def ids_in(table):
"""Returns the ids in the given dataframe, either as a list of ints or a single int."""
entity, id_colname = get_entity_and_id_colname(table)
# Series.to_list() converts to a list of Python int rather than numpy.int64
# Conversion to the list type and the int type are both necessary f... | 8,217 |
def transformer_ae_base_tpu():
"""Base config adjusted for TPU."""
hparams = transformer_ae_base()
transformer.update_hparams_for_tpu(hparams)
hparams.batch_size = 512
return hparams | 8,218 |
def test_minor_bump(admin_client, transactional_db, studies, worker):
""" Test that the major version number is bumped upon publish """
release = {
'name': 'First Release',
'studies': ['SD_00000001'],
'author': 'bob',
'is_major': True,
}
resp = admin_client.post('http://t... | 8,219 |
def attribute_volume(tree, altitudes, area=None):
"""
Volume of each node the given tree.
The volume :math:`V(n)` of a node :math:`n` is defined recursively as:
.. math::
V(n) = area(n) * | altitude(n) - altitude(parent(n)) | + \sum_{c \in children(n)} V(c)
:param tree: input tree
:p... | 8,220 |
def save_plot(
fig, filepath=None, format="png", interactive=False, return_filepath=False
):
"""Saves fig to filepath if specified, or to a default location if not.
Args:
fig (Figure): Figure to be saved.
filepath (str or Path, optional): Location to save file. Default is with filename "tes... | 8,221 |
def updateCalibrationCoefs(inputCsvFile, outputCsvFile):
"""read summary .csv file and update coefs for those with poor calibration
Look through all processed accelerometer files, and find participants that
did not have good calibration data. Then assigns the calibration coefs from
previous good use of... | 8,222 |
def stats_roll():
""" creates 4 random int's between 1 and 6 for each
items in starting_stats, dops the lowest and calculates
the total
"""
starting_stats = {'Strength': 0, 'Dexterity': 0, 'Constitution': 0, 'Intelligence': 0, 'Wisdom': 0, 'Charisma': 0}
num = 0
for key, value in starting_... | 8,223 |
def test_image_equality():
"""Images with the same pixels should equal each other,
as long as Pillow doesn't break
"""
a = Image.new("RGBA", (1, 1))
b = Image.new("RGBA", (1, 1))
assert a == b
b.putpixel((0, 0), (1, 0, 0, 1))
assert a != b
a.putpixel((0, 0), (1, 0, 0, 1))
a... | 8,224 |
def devstack(args):
"""
Start the devstack lms or studio server
"""
parser = argparse.ArgumentParser(prog='paver devstack')
parser.add_argument('system', type=str, nargs=1, help="lms or studio")
parser.add_argument('--fast', action='store_true', default=False, help="Skip updating assets")
pa... | 8,225 |
def write_jenkins_file():
"""Write changed_ext_attrs and changed_scripts to jenkins file.
$eas will contains the changed extension attributes,
$scripts will contains the changed scripts
If there are no changes, the variable will be set to 'None' """
if len(changed_ext_at... | 8,226 |
def _parse_config_result(response, source) -> None:
"""Checks if the source received in manifest is in the trusted repository list response from config agent
@param response: String response received from configuration agent for the command requested
@param source: the repository path where the package is s... | 8,227 |
def populate_canary(canary_id, protocol, domain, dns, filename, rdir,
settings):
"""Create actual canary URI / URL."""
if protocol not in ['unc', 'http', 'https']:
raise ValidationError('Unknown protocol specified')
if dns:
domain = f"{canary_id}.{domain}"
else:
... | 8,228 |
def get_wastewater_location_data():
"""Read in data of wastewater facility location data.
:return: dataframe of wastewater location values
"""
data = pkg_resources.resource_filename('interflow', 'input_data/WW_Facility_Loc.csv')
# return dataframe
return pd.read_csv(dat... | 8,229 |
def generate_accounts(seeds):
"""Create private keys and addresses for all seeds.
"""
return {
seed: {
'privatekey': encode_hex(sha3(seed)),
'address': encode_hex(privatekey_to_address(sha3(seed))),
}
for seed in seeds
} | 8,230 |
def get_annotation_df(
state: State,
piece: Piece,
root_type: PitchType,
tonic_type: PitchType,
) -> pd.DataFrame:
"""
Get a df containing the labels of the given state.
Parameters
----------
state : State
The state containing harmony annotations.
piece : Piece
T... | 8,231 |
def prettify(elem):
"""Return a pretty-printed XML string for the Element."""
rough_string = ET.tostring(elem, "utf-8")
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | 8,232 |
def plot_confusion_matrix_full(model,X_train, y_train, X_val, y_val):
"""Score Models and return results as a dataframe
Parameters
----------
model: model
Model passed into function
X_train : Numpy Array
X_train data
y_train : Numpy Array
Train target
X_val : Numpy A... | 8,233 |
def parse_new_multipart_upload(data):
"""
Parser for new multipart upload response.
:param data: Response data for new multipart upload.
:return: Returns a upload id.
"""
root = S3Element.fromstring('InitiateMultipartUploadResult', data)
return root.get_child_text('UploadId') | 8,234 |
def mech_name_for_species(mech1_csv_str, mech2_csv_str, ich):
""" build dictionaries to get the name for a given InCHI string
"""
mech1_inchi_dct = mechparser.mechanism.species_inchi_name_dct(
mech1_csv_str)
mech2_inchi_dct = mechparser.mechanism.species_inchi_name_dct(
mech2_csv_str)
... | 8,235 |
def get_api(api, cors_handler, marshal=None, resp_model=None,
parser=None, json_resp=True):
"""Returns default API decorator for GET request.
:param api: Flask rest_plus API
:param cors_handler: CORS handler
:param marshal: The API marshaller, e.g. api.marshal_list_with
:param resp_mode... | 8,236 |
def construct_chain_config_params(args):
"""
Helper function for constructing the kwargs to initialize a ChainConfig object.
"""
yield 'network_id', args.network_id
if args.data_dir is not None:
yield 'data_dir', args.data_dir
if args.nodekey_path and args.nodekey:
raise ValueE... | 8,237 |
def fetch_total_n_items(num_items, uniform_distribution=False):
"""Get num_items files from internet archive in our dirty categories list"""
logger.info(f"Fetching info for {num_items} internetarchive items...")
categories_weights = CATEGORIES_WEIGHTS
if uniform_distribution:
categories_weights ... | 8,238 |
def ListLigandsInfo(MolName, ChainIDs):
"""List ligand information across all chains."""
if not (OptionsInfo["All"] or OptionsInfo["Ligands"]):
return
ListSelectionResiduesInfo(MolName, ChainIDs, "Ligands") | 8,239 |
def full_formation_file_call(fit_directory):
"""full_formation_file_call
Casm query to generate composition of species "A", formation energy, DFT hull distance, cluster expansion energies and cluster expansion hull distance.
Args:
fit_directory (str): absolute path to the current genetic fit direc... | 8,240 |
def german_weekday_name(date):
"""Return the german weekday name for a given date."""
days = [u'Montag', u'Dienstag', u'Mittwoch', u'Donnerstag', u'Freitag', u'Samstag', u'Sonntag']
return days[date.weekday()] | 8,241 |
def load_data(database_filepath):
"""
Input:
database_filepath - path of the cleaned data file
Output:
X and Y for model training
Category names
"""
# load data from database
engine = create_engine('sqlite:///{}'.format(database_filepath))
df = pd.read_s... | 8,242 |
def real_spherical_harmonics(phi, theta, l, m):
"""Real spherical harmonics, also known as tesseral spherical harmonics
with condon shortley phase.
Only for scalar phi and theta!!!
"""
from scipy.special import lpmn, factorial
if m == 0:
y = np.sqrt(
(2 * l + 1) / ... | 8,243 |
def get_replace_function(replace_multiple: bool) -> Callable:
"""given bool:replace_multiple flag,
return replace function from modifier
"""
if replace_multiple:
return distend.modifier.replace_multiple
else:
return distend.modifier.replace_single | 8,244 |
def setup_restart(signum=signal.SIGHUP, restart_callback=None):
"""Install a signal handler that calls :func:`restart` when :const:`SIGHUP`
is received.
Parameters
----------
signum : int, optional
Signum number for the signal handler to install
restart_callback : callable
If sp... | 8,245 |
def accuracy(X,Y,w):
"""
First, evaluate the classifier on training data.
"""
n_correct = 0
for i in range(len(X)):
if predict(w, X[i]) == Y[i]:
n_correct += 1
return n_correct * 1.0 / len(X) | 8,246 |
def reduce_matrix(indices_to_remove: List[int], matrix: np.ndarray) -> np.ndarray:
"""
Removes indices from indices_to_remove from binary associated to indexing of matrix,
producing a new transition matrix.
To do so, it assigns all transition probabilities as the given state in the remaining
indices... | 8,247 |
def kdj(df, n=9):
"""
随机指标KDJ
N日RSV=(第N日收盘价-N日内最低价)/(N日内最高价-N日内最低价)×100%
当日K值=2/3前1日K值+1/3×当日RSV=SMA(RSV,M1)
当日D值=2/3前1日D值+1/3×当日K= SMA(K,M2)
当日J值=3 ×当日K值-2×当日D值
"""
_kdj = pd.DataFrame()
_kdj['date'] = df['date']
rsv = (df.close - df.low.rolling(n).min()) / (df.high.rolling(n).m... | 8,248 |
def identity_func(x):
"""The identify (a.k.a. transparent) function that returns it's input as is."""
return x | 8,249 |
def vapp(ctx, operation, vdc, vapp, catalog, template,
network, mode, vm_name, cust_file,
media, disk_name, count, cpu, ram, ip):
"""Operations with vApps"""
if vdc == '':
vdc = ctx.obj['vdc']
vca = _getVCA_vcloud_session(ctx)
if not vca:
print_error('User not authentic... | 8,250 |
def make_choice_validator(
choices, default_key=None, normalizer=None):
"""
Returns a callable that accepts the choices provided.
Choices should be provided as a list of 2-tuples, where the first
element is a string that should match user input (the key); the
second being the value associat... | 8,251 |
def main():
"""
Simple tester for the classifier
"""
# definte the sample data
sd = SampleData(2, 5, [-3, 3], [0.1, 0.1])
# initialize a new classifier with some sample data
clf = Classifier(sd.get_points(500))
# sample some points and see how many the classifier classifies correctly
sample_size ... | 8,252 |
def find_best_polycomp_parameters(samples, num_of_coefficients_range,
samples_per_chunk_range, max_error,
algorithm, delta_coeffs=1, delta_samples=1,
period=None, callback=None, max_iterations=0):
"""Performs an o... | 8,253 |
def moving_average(data, window_size=100): #used this approach https://stackoverflow.com/questions/11352047/finding-moving-average-from-data-points-in-python
"""
Calculates a moving average for all the data
Args:
data: set of values
window_size: number of data points to consider in window
... | 8,254 |
def _change_TRAVDV_to_TRAVdashDV(s:str):
"""
Reconciles mixcr name like TRAV29/DV5*01 to tcrdist2 name TRAV29DV5*01
Parameters
----------
s : str
Examples
--------
>>> _change_TRAVDV_to_TRAVdashDV('TRAV29DV5*01')
'TRAV29/DV5*01'
>>> _change_TRAVDV_to_TRAVdashDV('TRAV38-... | 8,255 |
def fixMayapy2011SegFault():
"""
# Have all the checks inside here, in case people want to insert this in their
# userSetup... it's currently not always on
"""
pass | 8,256 |
def gen_event_type_entry_str(event_type_name, event_type, event_config):
"""
return string like:
{"cpu-cycles", PERF_TYPE_HARDWARE, PERF_COUNT_HW_CPU_CYCLES},
"""
return '{"%s", %s, %s},\n' % (event_type_name, event_type, event_config) | 8,257 |
def encode_rotate_authentication_key_script(new_key: bytes) -> Script:
"""# Summary
Rotates the transaction sender's authentication key to the supplied new authentication key.
May
be sent by any account.
# Technical Description
Rotate the `account`'s `DiemAccount::DiemAccount` `authentication_... | 8,258 |
def retrieval_visualizations(model, savefig=True):
"""
Plots incremental retrieval contexts and supports, as heatmaps, and prints recalled items.
**Required model attributes**:
- item_count: specifies number of items encoded into memory
- context: vector representing an internal contextual state
... | 8,259 |
def save_image(image, path, filename, format):
"""Saves the image file in the specified format to the specified path
Args:
image (np.array): The image data
path (str): The path to the folder in which to save
filename (str): the name of the image file
format (str): The format in ... | 8,260 |
def get_force_charge() -> str:
"""
Gets the command object for the force charge command
Returns:
The command object as a json string
"""
force_charge = Path('force_charge.json').read_text()
return force_charge | 8,261 |
def start(update, context):
"""Send a message when the command /start is issued."""
context.bot.send_message(chat_id=update.effective_chat.id, text=TEXT + '') | 8,262 |
def asin(x: float32) -> float:
"""
Return arcsin of x in radians. Inputs are automatically clamped to [-1.0, 1.0].
"""
... | 8,263 |
def prune_motifs(ts, sorted_dic_list, r):
"""
:param ts: 1-dimensional time-series either resulting from the PCA method or the original 1-dimensional time-series
:type ts: 1d array
:param sorted_dic_list: list of motif dictionaries returned from the emd algorithm, ordered by relevance
:type sorted_... | 8,264 |
def xor_columns(col, parity):
""" XOR a column with the parity values from the state """
result = []
for i in range(len(col)):
result.append(col[i] ^ parity[i])
return result | 8,265 |
def initiate_default_resource_metadata(aws_resource):
"""
:type aws_resource: BaseAWSObject
"""
if not isinstance(aws_resource, BaseAWSObject):
raise TypeError
try:
metadata = aws_resource.Metadata
if not isinstance(metadata, dict):
raise TypeError("`troposphere.... | 8,266 |
def token_vault_single(chain, team_multisig, token, freeze_ends_at, token_vault_balances) -> Contract:
"""Another token vault deployment with a single customer."""
total = 1000
args = [
team_multisig,
freeze_ends_at,
token.address,
total,
0 # Disable the tap
]
... | 8,267 |
def test_namechooser__NameSuffix__1():
"""`NameSuffix` conforms to INameChooser."""
assert verifyObject(INameSuffix, NameSuffix()) | 8,268 |
def pixel_pick():
"""Pick the value from a pixel.
Args:
body parameters:
catalog (str): catalog to query
asset_id (str): asset id to query
lng (float): longitude coordinate
lat (float): latitude coordinate
Returns:
{'val': val, 'x': x, 'y': y... | 8,269 |
def read_eep_track(fp, colnames=None):
""" read MIST eep tracks """
# read lines
f = open(fp, "r+")
s = f.readlines()
# get info
MIST_version = re.split(r"\s+", s[0].strip())[-1]
MESA_revision = re.split(r"\s*", s[1].strip())[-1]
Yinit, Zinit, FeH, aFe, vvcrit = re.split(r"\s*", s[4].s... | 8,270 |
def fontwidth(string, font='sans-serif'):
"""Function: Returns the px width of a string assuming a base size of 16px."""
_fontwidth = json.load(open(os.path.join(abs_path(), 'fonts.json'), encoding='utf-8'))
codes_len = 127
default_width = 32
default_width_idx = 120
for _fontrow in _fontwidth:
... | 8,271 |
def create_model():
"""ResNet34 inspired analog model.
Returns:
nn.Modules: created model
"""
block_per_layers = (3, 4, 6, 3)
base_channel = 16
channel = (base_channel, 2*base_channel, 4*base_channel)
l0 = nn.Sequential(
nn.Conv2d(3, channel[0], kernel_size=3, stride=1, pad... | 8,272 |
def kv_get(key: Union[str, bytes],
*,
namespace: Optional[str] = None) -> bytes:
"""Fetch the value of a binary key."""
if isinstance(key, str):
key = key.encode()
assert isinstance(key, bytes)
return global_state_client.kv_get(key, namespace) | 8,273 |
def mode(dev, target):
"""Gets or sets the active mode."""
click.echo("Current mode: %s" % dev.mode_readable)
if target:
click.echo("Setting mode: %s" % target)
dev.mode = target | 8,274 |
def decrypt_file(key: bytes, infile: Path, outfile: Path):
"""Decrypt infile and save as outfile"""
plaintext = read_decrypted(key, infile)
outfile.open('wb').write(plaintext) | 8,275 |
def construct_model(data, local_settings, covariate_multipliers, covariate_data_spec):
"""Makes a Cascade model from EpiViz-AT settings and data.
Args:
data: An object with both ``age_specific_death_rate`` and ``locations``.
local_settings: A settings object from ``cascade_plan``.
covar... | 8,276 |
def test_cli_config_template(cli):
"""Verify the --template option works correctly."""
filename = 'build-magic_template.yaml'
current = Path().cwd().resolve()
res = cli.invoke(build_magic, ['--template'])
assert current.joinpath(filename).exists()
os.remove(filename)
assert res.exit_code == ... | 8,277 |
def active():
"""Print currently active element to screen."""
o(driver.switch_to.active_element.text.split("\n")[0]) | 8,278 |
def test_owe_unsupported_group(dev, apdev):
"""Opportunistic Wireless Encryption and unsupported group"""
try:
run_owe_unsupported_group(dev, apdev)
finally:
dev[0].request("VENDOR_ELEM_REMOVE 13 *") | 8,279 |
def set_off():
"""
Turns OFF the lamp.
"""
unicorn.set_status(False)
return OK | 8,280 |
def get_all_active_bets():
"""
Gets all the active bets for all
active discord ritoman users
"""
return session.query(LoLBets).filter(LoLBets.completed == false()).all() | 8,281 |
def get_quantize_pos_min_diffs(inputs, f_min, f_max, q_min, q_max, bit_width):
"""Get quantize pos which makes min difference between float and quantzed. """
with tf.name_scope("GetQuantizePosMinDiffs"):
min_scale_inv = tf.math.divide(f_min, q_min)
max_scale_inv = tf.math.divide(f_max, q_max)
float_scal... | 8,282 |
def save_color_map(map_name, output_path):
"""
Gets 256 colors from the color map and saves the [0, 1] RGB values of those colors to the
corresponding tab-separated file in the output_path.
"""
file_name = os.path.join(output_path, f'{map_name}.tsv')
cmap = plt.get_cmap(map_name)
colors = No... | 8,283 |
def _non_string_elements(x):
"""
Simple helper to check that all values of x are string. Returns all non string elements as (position, element).
:param x: Iterable
:return: [(int, !String), ...]
"""
problems = []
for i in range(0, len(x)):
if not isinstance(x[i], str):
p... | 8,284 |
def configure_dirs(base_path: str, config_name: str, dataset_name: str) -> str:
"""
Performs configuration of directories for storing vectors
:param base_path:
:param config_name:
:param dataset_name:
:return: Full configuration path
"""
base_path = Path(base_path)
base_path.mkdir(e... | 8,285 |
def test_wet_bulb_temperature_1d():
"""Test wet bulb calculation with 1d list."""
pressures = [1013, 1000, 990] * units.hPa
temperatures = [25, 20, 15] * units.degC
dewpoints = [20, 15, 10] * units.degC
val = wet_bulb_temperature(pressures, temperatures, dewpoints)
truth = [21.44487, 16.73673, 1... | 8,286 |
def generate_output_file(final_model,out_name):
""" This function takes as input both the final model created with the building algorithm and the output filename given by the user (if not defined, is macrocomplex by default). Eventually, it returns the file saved in either ".pdb" or ".mmcif" format. """
out_name = s... | 8,287 |
def config_entry_version_fixture():
"""Define a config entry version fixture."""
return 2 | 8,288 |
def edge_dfs(G, source=None, orientation=None):
"""A directed, depth-first-search of edges in `G`, beginning at `source`.
Yield the edges of G in a depth-first-search order continuing until
all edges are generated.
Parameters
----------
G : graph
A directed/undirected graph/multigraph.... | 8,289 |
async def _md5_by_reading(filepath: str, chunk_size: int = DEFAULT_BUFFER_SIZE) -> str:
"""
Compute md5 of a filepath.
"""
file_hash = hashlib.md5()
async with async_open(filepath, "rb") as reader:
async for chunk in reader.iter_chunked(chunk_size):
file_hash.update(chunk)
r... | 8,290 |
def client_authenticator_factory(mechanism,password_manager):
"""Create a client authenticator object for given SASL mechanism and
password manager.
:Parameters:
- `mechanism`: name of the SASL mechanism ("PLAIN", "DIGEST-MD5" or "GSSAPI").
- `password_manager`: name of the password manager... | 8,291 |
def wait_for_cell_data_connection(
log,
ad,
state,
timeout_value=EventDispatcher.DEFAULT_TIMEOUT):
"""Wait for data connection status to be expected value for default
data subscription.
Wait for the data connection status to be DATA_STATE_CONNECTED
or DATA_STATE_D... | 8,292 |
def _parse_lists(config_parser: configparser.ConfigParser, section: str = '') -> t.Dict:
"""Parses multiline blocks in *.cfg files as lists."""
config = dict(config_parser.items(section))
for key, val in config.items():
if '/' in val and 'parameters' not in section:
config[key] = parse_... | 8,293 |
def get_filename_pair(filename):
"""
Given the name of a VASF data file (*.rsd) or parameter file (*.rsp) return
a tuple of (parameters_filename, data_filename). It doesn't matter if the
filename is a fully qualified path or not.
- assumes extensions are all caps or all lower
"""
param_file... | 8,294 |
def parseArgs(app):
""" Args parser """
if not os.path.isdir(app.iconCacheDir):
os.system("mkdir -p "+app.iconCacheDir)
try:
opts, args = getopt.getopt(sys.argv[1:], "ha:r:lt:pbs", ["help", "append=", "remove=", 'list', 'daemonize', 'type', 'list-plugins', 'list-types', 'config=', 'value='... | 8,295 |
def test_random(client):
"""Testing shows.random"""
response = client.get("/shows/random")
assert response.status_code == 302
assert response.location | 8,296 |
async def get_reposet(client, headers, reposet_id):
"""Get the reposet by id."""
url = f"https://api.athenian.co/v1/reposet/{reposet_id}"
return await do_request(client, url, headers) | 8,297 |
def conditions(converted: str) -> bool:
"""Conditions function is used to check the message processed.
Uses the keywords to do a regex match and trigger the appropriate function which has dedicated task.
Args:
converted: Takes the voice recognized statement as argument.
Returns:
bool:... | 8,298 |
def detect_os_flavour(os_type):
"""Detect Linux flavours and return the current version"""
if os_type:
# linux
try:
return platform.linux_distribution()[0]
except Exception, e:
return None
else:
# windows
return platform.platform() | 8,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.