content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def generate_theme(
corethemepath: Path,
theme_options: ThemeOptions,
outdirpath: Path,
additional: Tuple[Theme, Path] = ()
) -> Tuple[Theme, Path]:
"""Tema üretir ve dosyaya yazar
Arguments:
corethemepath {Path} -- Üretim yapılacak çekirdek temanın yolu
theme_options {ThemeOpti... | 5,294,900 |
def get_expression(
string: str, inputs: CWLObjectType, self: Optional[CWLOutputType]
) -> Optional[str]:
"""
Find and return a normalized CWL expression, if any.
CWL expressions in the $() form are converted to the ${} form.
"""
if not isinstance(string, str):
return None
if string... | 5,294,901 |
def neighbours(row_number: int, column_number: int) -> set[tuple[int, int]]:
"""
Returns all the neighboring cells within the grid
"""
output: set[tuple[int, int]] = set()
for i in (-1, 0, 1):
for j in (-1, 0, 1):
if i == 0 and j == 0:
continue
new_row... | 5,294,902 |
def appprotect_setup(
request, kube_apis, ingress_controller_endpoint, test_namespace
) -> AppProtectSetup:
"""
Deploy simple application and all the AppProtect(dataguard-alarm) resources under test in one namespace.
:param request: pytest fixture
:param kube_apis: client apis
:param ingress_co... | 5,294,903 |
def plot_psvae_training_curves(
lab, expt, animal, session, alphas, betas, gammas, n_ae_latents, rng_seeds_model,
experiment_name, n_labels, dtype='val', save_file=None, format='pdf', **kwargs):
"""Create training plots for each term in the ps-vae objective function.
The `dtype` argument contro... | 5,294,904 |
def _mrci_energy(output_str):
""" Reads the MRCISD+Q energy from the output file string.
Returns the energy in Hartrees.
:param output_str: string of the program's output file
:type output_str: str
:rtype: float
"""
ene = ar.energy.read(
output_str,
app.LINE... | 5,294,905 |
def format_csv(factor_name, entry):
"""Format a data entry as a csv line."""
return "%s, %s, %s" % (entry[factor_name], entry['quarter'], entry['count']) | 5,294,906 |
async def test_discovery_update_unchanged_light(hass, mqtt_mock, caplog):
"""Test update of discovered light."""
data1 = (
'{ "name": "Beer",'
' "schema": "template",'
' "state_topic": "test_topic",'
' "command_topic": "test_topic",'
' "command_on_template": "on",'
... | 5,294,907 |
def create_security_group(security_group_name: str, vpc_id: str, other_group: Optional[SecurityGroup] = None):
"""Creates security group with proper ports open. Optionally allows all traffic from other_group"""
print("Creating security group " + security_group_name)
ec2 = u.get_ec2_resource()
security_group: S... | 5,294,908 |
def p_stat_val_indirect_indexed(p):
"""stat_val : '(' arithmetic ')' ',' REGISTER"""
if p[5][0] != 'Y':
raise ParseError(f"Only register Y can be used for indexed indirect addressing, found {p[5][0]} at "
f"{p.lineno(5)}, column {_get_column(p, index=5)}")
p[0] = Addressing(... | 5,294,909 |
def _remove_quotes(values):
"""Remove any quotes from quoted values."""
removed = []
for value in values:
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
removed.append(value)
return removed | 5,294,910 |
def write_yaml(data, file_path):
"""Write plain data to a file as yaml
Parameters
----------
data
Data to write (should be lists, dicts and simple values)
file_path : str
The path of the configuration file to write
"""
with open(file_path, 'w+') as file_handle:
yaml ... | 5,294,911 |
def Protein_2_Function_table_InterPro_STS(fn_in_string2interpro, fn_in_Functions_table_InterPro, fn_in_interpro_parent_2_child_tree, fn_out_Protein_2_Function_table_InterPro, number_of_processes=1, verbose=True):
"""
:param fn_in_string2interpro: String (e.g. /mnt/mnemo5/dblyon/agotool/data/PostgreSQL/downloads... | 5,294,912 |
def diff_schedule_embed_dicts(old_embed: Dict, new_embed: Dict) -> str:
"""Takes 2 schedule embed dicts and returns a string containing the differences"""
diffs = []
# old_embed can be empty if we have reset it, new_embed will always have a title.
if old_embed.get("title", "") != new_embed["title"]:
... | 5,294,913 |
def bootstrapped_ecdf(variable, weights, seeds, ax,
bootstraps=200, normalisation=None, x_count=10000,
log_scale=(False, False), color="tab:blue", label=None,
**kwargs):
"""Create a bootstrapped weighted ECDF plot.
Parameters
----------
... | 5,294,914 |
def process_permission_boundary_to_user(target_iam_client,
policy_arn,
account,
render_policy_version_document_json,
s3_object_key):
"""
The main functi... | 5,294,915 |
def warning_msg(text):
"""Colorize warning message with prefix"""
msg(colorize("Warning: " + str(text), "yellow")) | 5,294,916 |
def consolidate(voice, length):
"""
Join notes of the same pitch together, and increase their duration. No attempt is made to handle ties between bars,
They are just treated as separate notes.
:param voice:
:param length:
:return:
"""
out = list()
try:
for bars in range(0, ... | 5,294,917 |
def do_alias(args: str): # TODO: clean this shit
"""Register or check a command alias. It autosaves it to the alias file.
Usage: alias <alias> [command] [args...]"""
args_list = args.split(' ')
# print(l)
if args == '':
sh.stdout.write(sh.do_alias.__doc__)
sh.stdout.write(f"\nAliases:... | 5,294,918 |
def make_output_to_cli(report):
"""Make output to cli."""
print('--------------------')
print('Report:')
print('--------------------')
[print(f'"{tuple_[0]}" - {tuple_[1]}') for tuple_ in report if report]
print('--------------------') | 5,294,919 |
def test_berendsen_attributes_attached(simulation_factory,
two_particle_snapshot_factory):
"""Test attributes of the Berendsen integrator after attaching."""
all_ = hoomd.filter.All()
constant = hoomd.variant.Constant(2.0)
berendsen = hoomd.md.methods.Berendsen(fil... | 5,294,920 |
def batch_generator(data, batch_size):
"""Generate minibatches from data.
Args:
data: array-like, supporting slicing along first dimension
batch_size: int, batch size
Yields:
minibatches of maximum size batch_size
"""
for i in range(0, len(data), batch_size):
yield data[i... | 5,294,921 |
def get_filename(training_datasets, testing_datasets, beta, sr_model):
"""Get filename for saving results."""
if sr_model == 'convolutional_embedding':
model_str = '' # For past consistency.
else:
model_str = '_%s' % sr_model
file_name = ('end_to_end%s_stim_%s_resp_%s_beta_%d_taskid_%d'
... | 5,294,922 |
def create_args()->dict:
"""[summary]
Returns:
dict: [a dictionary contains the args and non args parameters]
"""
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--D', default=2, type=int,
help='dimension of sample')
parser.add_argument('-m', '--M'... | 5,294,923 |
def get_dimensions(cube_id):
"""
For this test data we will use a predefined dimension object matching cube-420 in the acceptance environment,
but this could be read from the TAP service.
"""
dims = json.loads(
'{"axes": [{"name": "RA", "numPixels": "4096", "pixelSize": "5.5555555555560e-04... | 5,294,924 |
def test_report_get_custom_severity(cbcsdk_mock, init_data, feed, watchlist, do_request, expectation, result):
"""Tests getting the custom severity for a report."""
if do_request:
cbcsdk_mock.mock_request("GET", "/threathunter/watchlistmgr/v3/orgs/test/reports/"
"... | 5,294,925 |
def validateRouterDetails(result):
"""
Runs device validations on each Router object that is returned by
getRouterDetails, if a device requires normalization return it for
processing by normalizeRouters
"""
print "Validating router details"
devicesToCorrect = []
for device, results in r... | 5,294,926 |
def test_count_block():
"""Test gp.count_block by considering page 10 on
https://www.maa.org/sites/default/files/pdf/upload_library/22/Chauvenet/Gethner.pdf"""
assert gp.count_block(20785207 - 10, 0, 20, 10) == 1 | 5,294,927 |
def load_yaml_config(file_path: str | Path) -> dict:
"""
Parameters
----------
file_path : str or Path
Yaml config file name. The file is assumed to be in
the repo's config directory.
Returns
-------
config : dict
Configuration parameters stored in a dictionary.
... | 5,294,928 |
def advice(aa):
"""If a user asks for health advice or tips, then bot wil reply with an randomly generated advice"""
for ab in aa.split():
if ab.lower() in advice_questions:
return rndm.choice(advice_reply) | 5,294,929 |
def serve(
host,
port,
app: Sanic,
ssl: Optional[SSLContext] = None,
sock: Optional[socket.socket] = None,
unix: Optional[str] = None,
reuse_port: bool = False,
loop=None,
protocol: Type[asyncio.Protocol] = HttpProtocol,
backlog: int = 100,
register_sys_signals: bool = True,
... | 5,294,930 |
def dmp_strip(f, u):
"""
Remove leading zeros from ``f`` in ``K[X]``.
Examples
========
>>> from sympy.polys.densebasic import dmp_strip
>>> dmp_strip([[], [0, 1, 2], [1]], 1)
[[0, 1, 2], [1]]
"""
if not u:
return dup_strip(f)
if dmp_zero_p(f, u):
return f
... | 5,294,931 |
def mvdr_beamformer(
noise_psd: ComplexTensor,
steering_vector: ComplexTensor,
eps=1e-15
) -> ComplexTensor:
"""
Standard MVDR beamformer
Args:
noise_psd: time-averaged noise psd of shape [B, F, C, C]
steering_vector: [B, F, C, 1]
eps: eps
Returns:
... | 5,294,932 |
def divide_chrom_dirs_into_chunks(l, n):
"""Breaks input into to chunks of n-size for multiprocessing"""
for i in range(0, len(l), n):
yield l[i:i + n] | 5,294,933 |
def split_in_words(text, num_letters):
"""
Split a long text (without space) into words of num_letters letters.
For instance if text is niijighkqj and num_letters is 4, will return
["niij", "iiji", "ijig", "jigh", "ighk", "ghkg", "hkgj"]
:param text: Text to split into words
:param num_letters: ... | 5,294,934 |
def _get_delivery_voucher_discount_for_cart(voucher, cart):
"""Calculate discount value for a voucher of delivery type."""
if not cart.is_delivery_required():
msg = pgettext(
'Voucher not applicable',
'Your task does not require delivery.')
raise NotApplicable(msg)
de... | 5,294,935 |
def rname(node):
""" Obtains names from different types of AST nodes. """
if isinstance(node, str):
return node
if isinstance(node, ast.Num):
return str(node.n)
if isinstance(node, ast.Name): # form x
return node.id
if isinstance(node, ast.Constant):
return str(node... | 5,294,936 |
def utr(diff, meta, i, ii, orbnum, rowmedian, rowmedian_absder, peaks):
"""
Saves a plot of up-the-ramp sample, the row by row sum and the derivate of the latter. It furthermore shows the aperture used for the analysis.
"""
cmin = int(meta.refpix[
orbnum, 2] + meta.POSTARG1 / meta.pla... | 5,294,937 |
def test(test_loader, model, args):
"""Test the model.
Args:
test_loader (DataLoader): The data set loader.
model: The network.
criterion (Loss): The loss function.
args: The hyperparameter arguments.
Returns:
The NMI score.
The recall@k results.
"""
... | 5,294,938 |
def main():
"""Main entry point for command line interface."""
parser = argparse.ArgumentParser(description='Extend GTFS effective date range.')
parser.add_argument('--download-directory', '-d',
default=os.path.join(os.getcwd(), DOWNLOAD_DIRECTORY),
help='Full... | 5,294,939 |
def mod_align(indirs, ref, outdir, threads, recursive=False, storeQuals=False, bamdir="minimap2"):
"""Align *.fq.gz files from input dirs and store sorted .bam in outdir/minimap2"""
logger("Aligning FastQ files from %s directories...\n"%len(indirs))
# prepare output directory
if not os.path.isdir(os.pat... | 5,294,940 |
def modo_sleep():
""" En este modo se apaga la camara, los leds de la camara y """
print("modo sleep")
# apagar_camara() %?
print("camara apagada")
global t_lectura_bateria, t_shutdown, modo_actual, interrupcion_activo, stop_parpadeo_led
modo_actual = "sleep"
potencia_leds_camara(1)
... | 5,294,941 |
def get_file(station):
"""Download the file from NCEI, if necessary!"""
# IPv6, use 205.167.25.102 rather than www1.ncdc.noaa.gov
uri = ("http://www1.ncdc.noaa.gov/pub/data/ghcn/daily/all/%s.dly"
) % (station, )
localfn = "%s/%s.dly" % (BASEDIR, station)
if not os.path.isfile(localfn):
... | 5,294,942 |
def get_specified_file(file_names, *args):
"""Get specified filename extension from a list of file names."""
specified_filename = []
if args is ():
raise Exception('get_specified_file() missing at least 1 required specified argument')
for name in file_names:
for extension in args:
... | 5,294,943 |
def has_sh_placeholders(message):
"""Returns true if the message has placeholders."""
return re.search(r'\$\{(\w+)\}', message) is not None | 5,294,944 |
def _verify_python3_env():
"""Ensures that the environment is good for unicode on Python 3."""
if PY2:
return
try:
import locale
fs_enc = codecs.lookup(locale.getpreferredencoding()).name
except Exception:
fs_enc = "ascii"
if fs_enc != "ascii":
return
ex... | 5,294,945 |
def _find_char(input_char):
"""
find english char in input string
"""
result = re.findall(r'[a-zA-Z=_/0-9.]+', str(input_char))
return result | 5,294,946 |
def p_group_expr_2(p):
"""
group_expr : LPAR expression AS VAR RPAR
"""
p[0] = Expression(p[1], "AS", RDFTerm(p[3], is_const=False)) | 5,294,947 |
def generate_inventory(baremetal_info, server_info):
"""Generate ansible inventory in json format"""
hosts = defaultdict(list)
hosts_meta = {}
for node in baremetal_info:
if node['Provisioning State'].lower() == 'active':
role = re.findall('.*profile:(compute|control)', node['Prope... | 5,294,948 |
def research_report(
instrument_ids, research_study_id, acting_user_id, patch_dstu2,
request_url, response_format, lock_key, celery_task):
"""Generates the research report
Designed to be executed in a background task - all inputs and outputs are
easily serialized (executing celery_task pare... | 5,294,949 |
def get_P_TU_aux_HWH(CG_category):
"""35. タンクユニットの補機消費電力 (温水暖房)
Args:
CG_category(str): コージェネレーション設備の種類
Returns:
float: タンクユニットの補機消費電力 (温水暖房)
"""
return get_value(CG_category, 35) | 5,294,950 |
def type_to_tf_structure(type_spec):
"""Returns nested `tf.data.experimental.Structure` for a given TFF type.
Args:
type_spec: Type specification, either an instance of
`computation_types.Type`, or something convertible to it. Ther type
specification must be composed of only named tuples and tensor... | 5,294,951 |
def _get_effective_areas(detector):
"""
Returns the effective detector areas for EIS, in a dictionary from floats
(in Angstroms) to Quantities.
"""
areas_dic = eff_areas_a if detector == 'A' else eff_areas_b
if len(areas_dic) > 0:
return areas_dic
url = darts + 'response/EIS_EffArea_... | 5,294,952 |
def verifyrun(func):
"""Prints whether the decorated function ran."""
@functools.wraps(func)
def wrapper_verifyrun(*args, **kwargs):
print(f'Ran {func.__name__!r} from {func.__module__}.')
value = func(*args, **kwargs)
return value
return wrapper_verifyrun | 5,294,953 |
def bold_viewed(val, viewed_pages):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
weight = 'bold' if val in viewed_pages else 'normal'
return 'font-weight: %s' % weight | 5,294,954 |
def execute(commands):
"""
execute the commands that are included in the \n separated string line by line
:param commands: the commands
:return:
"""
lines = commands.split("\n")
for command in lines:
if dry_run:
print("DRY RUN - skipping command:\n{}".format(comm... | 5,294,955 |
def cut_map_chunks(c):
"""
Cut a map into many chunks based on the chunk_size variable (note_group_size).
"""
r = [];
for i in range(0, (c.shape[0] - chunk_size) // step_size):
chunk = c[i * step_size:i * step_size + chunk_size];
r.append(chunk);
return tf.stack(r); | 5,294,956 |
def register_package(path):
"""Registers the plugin at the given path."""
portable_popen([sys.executable, "setup.py", "register"], cwd=path).wait() | 5,294,957 |
def get_state_cmds(cmds):
"""Get the state-changing commands need to create LOAD_EVENT OBS commands.
:param cmds: CommandTable of input commands.
:returns: CommandTable of state-changing commands.
"""
state_tlmsids = [
'AOSTRCAT',
'COAOSQID',
'AOMANUVR',
'AONMMODE',
... | 5,294,958 |
def test_deuteration():
"""Test if the DEUTERATION is defined."""
assert DEUTERATION is not None | 5,294,959 |
def get_grid_search(X, y):
"""
Perform Grid Search on dataset with SVM classifier.
:param X:
:param y:
:return: the C_range and gamma_range of the search, then the GridSearch obj itself
"""
C_range = np.logspace(-1, 5, 7)
gamma_range = np.logspace(-6, 2, 9)
param_grid = dict(gamma=... | 5,294,960 |
def get_can_reach_set(n, reach_dic, max_trip_duration=150):
"""Return the set of all nodes whose trip to node n takes
less than "max_trip_duration" seconds.
Arguments:
n {int} -- target node id
reach_dic {dict[int][dict[int][set]]} -- Stores the node ids whose distance to n
is w... | 5,294,961 |
def vis_square_f(data):
"""Take an array of shape (n, height, width) or (n, height, width, 3)
and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)"""
# normalize data for display
data = (data - data.min()) / (data.max() - data.min())
# force the number of... | 5,294,962 |
def n4_bias_field_correction(img, mask=None, shrink_factor=4,
convergence={'iters':[50,50,50,50], 'tol':1e-07},
spline_param=200, verbose=False, weight_mask=None):
"""
N4 Bias Field Correction
"""
iters = convergence['iters']
tol = convergenc... | 5,294,963 |
def normaliseContinuum(spec):
"""
Based on example.py
normalize_whole_spectrum_strategy1_ignoring_prefixed_strong_lines function
"""
model = 'Splines'
degree = 2
nknots = None
from_resolution = INSTRUMENT['RESOLUTION']
# continuum fit
order = 'median+max'
median_wave_range =... | 5,294,964 |
def buildOCSPRequest(*reqs, **kwargs):
"""
reqs
(cert, serial), ...
kwargs
'nonce'
True to generate a nonce
:return:
OCSPRequest object
"""
ocspBuilder = OCSPRequestBuilder()
for c, serial in reqs:
ocspBuilder.addRequest(c, int(serial))
if 'non... | 5,294,965 |
def get_functional_model(config):
"""Construct keras functional model from Galaxy tool parameters
Parameters
-----------
config : dictionary, galaxy tool parameters loaded by JSON
"""
layers = config['layers']
all_layers = []
for layer in layers:
options = layer['layer_selection... | 5,294,966 |
def get_carpet(parameterized_line, distance, step):
"""
Return M x N x 2 numpy array.
It contains the centers of the ParameterizedLine, but perpendicularly
repeated by step along the normals to the segments of the
ParameterizedLine, until distance is reached.
"""
# length must be uneven, an... | 5,294,967 |
def freq_to_band(freq):
"""converts a Frequency [kHz] into the band and mode according to the IARU bandplan
Args:
frequency (float): Frequency in kHz
Returns:
dict: Dictionary containing the band (int) and mode (str)
Raises:
KeyError: Wrong frequency or... | 5,294,968 |
def __find_sign_against_plane(pmx, old_vert, new_vert, mat_idx, moreinfo):
"""
Find all faces that contain [old_vert] and look if [new_vert] is in front of at least one of them.
"""
from kkpmx_core import from_vertices_get_faces
from sympy import Plane
new_point = pmx.verts[new_vert].pos
if moreinfo: prin... | 5,294,969 |
def create_empty_gid_matrix(width, height):
"""Creates a matrix of the given size initialized with all zeroes."""
return [[0] * width for row_index in range(height)] | 5,294,970 |
async def on_ready():
"""on_ready"""
print('Online!') | 5,294,971 |
def test_class_osco_rules_kind(tmp_path):
"""Test class osco.Rules when no kind==Config."""
rules = osco.Rules({'kind': 'notConfigMap'})
assert len(rules.instances) == 0 | 5,294,972 |
def random_noise_levels() -> tuple:
""" Generates random noise levels from a log-log
linear distribution.
"""
log_min_shot_noise = np.log(0.0001)
log_max_shot_noise = np.log(0.012)
log_shot_noise = np.random.uniform(log_min_shot_noise, log_max_shot_noise)
shot_noise = np.exp(log_shot_no... | 5,294,973 |
def schedule_runs(mode: str, directory: Path, gpu_ids: List[int], runs_per_gpu: int):
"""Schedule multiple runs across one or multiple GPUs.
Parameters
----------
mode : {'train', 'evaluate', 'finetune'}
Use 'train' if you want to schedule training of multiple models, 'evaluate' if you want... | 5,294,974 |
def _read_signing_keys(key_filename):
"""Reads the given file as a WIF formatted key.
Args:
key_filename: The filename where the key is stored.
Returns:
tuple (str, str): the public and private key pair
Raises:
CliException: If unable to read the file.
"""
filename = ... | 5,294,975 |
def load_mosaic(self, index):
"""
concatenate four images into one mosaic image
:param self:
:param index: the index of requied images
:return:
"""
# loads images in a mosaic
labels4 = [] # concatenate the labels
s = self.img_size
# choose a random center point for the concaten... | 5,294,976 |
def placeholder_imputer(df: pd.DataFrame,
columns_to_impute: List[str],
placeholder_value: Any = -999) -> LearnerReturnType:
"""
Fills missing values with a fixed value.
Parameters
----------
df : pandas.DataFrame
A Pandas' DataFrame with col... | 5,294,977 |
def run_framework(framework, on_stop):
"""
Handles Pelix framework starting and main loop.
Waits for the framework to stop before stopping Qt and returning.
This method should be executed in a new thread.
:param framework: The Pelix framework to run
:param on_stop: Method to call once the fram... | 5,294,978 |
def test_equilibrium_raises_when_no_phases_can_be_active():
"""Equliibrium raises when the components passed cannot give any active phases"""
# all phases contain AL and/or FE in a sublattice, so no phases can be active
equilibrium(ALFE_DBF, ['VA'], list(ALFE_DBF.phases.keys()), {v.T: 300, v.P: 101325}) | 5,294,979 |
def query_token(token, session=None):
"""
Validate an authentication token using the database. This method will only be called
if no entry could be found in the according cache.
:param token: Authentication token as a variable-length string.
:param session: The database session in use.
:return... | 5,294,980 |
def copyParams():
""" Copies memories that were generated by the user to the circuit folder """
if os.path.exists(project_folder+"tfArgs/"):
mifFiles = glob.glob(project_folder+"tfArgs/*.mif")
for m in mifFiles:
shutil.copy(m,project_folder) | 5,294,981 |
def value_to_none_low_medium_high(confidence_value):
"""
This method will transform an integer value into the None / Low / Med /
High scale string representation.
The scale for this confidence representation is the following:
.. list-table:: STIX Confidence to None, Low, Med, High
:header-... | 5,294,982 |
def _decrypted_todolist_protobuf(pb):
"""Args: pb: bytes; Returns the serialized bytes of a pyatdl_pb2.ChecksumAndData."""
# We should never see InvalidToken. If we see it, let it become a 500.
try:
return _protobuf_fernet().decrypt(pb)
except InvalidToken:
_debug_log('Invalid encrypted pb')
raise | 5,294,983 |
def main():
"""Start the bot."""
logger.info("The bot is starting...")
BOT_TOKEN = os.environ.get("BOT_TOKEN")
if BOT_TOKEN is None:
logger.critical("Please set the BOT_TOKEN env variable")
return
updater = Updater(BOT_TOKEN)
dp = updater.dispatcher
dp.add_handler(CommandH... | 5,294,984 |
def setup_all_datasets(dataset_dir, image_root_corruption_prefix=None):
"""
Registers all datasets as instances from COCO
Args:
dataset_dir(str): path to dataset directory
"""
setup_voc_dataset(dataset_dir)
setup_coco_dataset(
dataset_dir,
image_root_corruption_prefix=i... | 5,294,985 |
def get_disc_df(date, filepath, offset=60):
"""[summary]
Returns:
dataframe:
"""
def fix_timestamp(x):
if ".500" in str(x):
return datetime.strptime(str(x)[0:19], "%Y-%m-%d %H:%M:%S")
else:
return x
disc_df = pd.read_csv(filepath, sep="\t", skiprows... | 5,294,986 |
def get_interfaces():
"""
Enumerate interfaces (name, ip, mac, subnet).
yield return a 3-tuple:
interface_name, interface_ip_address, interface_mac_address, interface_subnet_mask
"""
max_possible = 128 # arbitrary. raise if needed.
bytes = max_possible * 32
s = socket.socket(so... | 5,294,987 |
def ping() -> models.Pong:
"""A simple ping/pong endpoint for aliveness checks."""
return models.Pong() | 5,294,988 |
def install_dependencies(
dependencies: List[Dependency], logger: Logger, install_timeout: float = 300,
) -> None:
"""
Install python dependencies to the current python environment.
:param dependencies: dict of dependency name and specification
:param logger: the logger
:param install_timeout: ... | 5,294,989 |
def split_srf_by_mult_crv(srf,crvs):
""" Split a surface with multiple curves. """
srfb = srf.ToBrep()
faces_ = srfb.Faces[0]
splits = faces_.Split(crvs,TOLER).Faces
split_return = []
for s in splits:
split_return.append(s.DuplicateFace(False))
return split_return | 5,294,990 |
def process_detail(hvr_client, hub_name, channel, source, target):
"""
Get all process details
"""
rt = {}
jobs = hvr_client.get_hubs_jobs(hub=hub_name)
for job_name in jobs:
if (
job_name == f"{channel}-activate"
or job_name == f"{channel}-refr-{source}-{targ... | 5,294,991 |
def _action_set_pwm_expire_on(server: socket.socket, shelf_id: str,
date_str: str) -> None:
"""Set shelf PWM override expiration to date_str"""
logger.debug("Setting PWM override on %s for %s", date_str, shelf_id)
if sys.version_info < (3, 7) and re.search(r'[+-]\d\d:\d\d$', da... | 5,294,992 |
def mixed_canonical_full_ret_sv(data_tensor, max_bond_dimension, batch_size_position):
"""
Performs a full mixed canonical MPS decomposition of a pre-partitioned data tensor.
See "The density matrix renormalization group in the age of Matrix Product States" (https://arxiv.org/abs/1008.3477)
pages 43-55... | 5,294,993 |
def test_embeddings(embeddings, id_to_word, word_to_id, test_emb_setup):
"""
:param embeddings: Word embeddings
:param id_to_word: Dictionary from id to word
:param word_to_id: Dictionary from word to id
:param test_emb_setup: Setup variables
:prints: A chosen amount of words and their clo... | 5,294,994 |
def download_model(url, dest, verbose=True):
"""
Downloads a model from tfhub and unzips it.
The function assumes the format is `.tar.gz`.
"""
if not os.path.exists(dest):
os.makedirs(dest)
fpath = os.path.join(dest, "model.tar.gz")
if not os.path.exists(fpath):
if verbose:
... | 5,294,995 |
def doclist():
"""List all the documents."""
docs = Document.query.all()
docsd = {d.slug: d for d in docs}
fs = os.listdir(app.config['DOCPATH'])
fs.remove('__ARCHIVE')
docs = []
for d in docsd:
if d not in fs:
_ = docsd[d]
_.status = 0b10
docs.ap... | 5,294,996 |
def scroll_page_down(b):
"""
Scroll current buffer one page-size down.
"""
b.scroll_page_down() | 5,294,997 |
def _get_process_task_request_test_cases():
"""Returns a lit of
targets, send_order, request_client_idx
"""
num_clients = 3
clients = [create_client(name=f"__test_client{i}") for i in range(num_clients)]
return [
[clients, SendOrder.ANY, 0],
[clients, SendOrder.ANY, 1],
... | 5,294,998 |
def parsebody(body):
"""Parse a message from the server returning a dict."""
data = dict()
lines = body.splitlines()
for line in lines:
equal_ix = line.find('=')
if equal_ix > 0:
key = line[:equal_ix]
data[key] = unquote(line[equal_ix + 1:])
return data | 5,294,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.