content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def lambda_handler(event, context):
"""
Listens to SQS events fired when new data files are added to the data
bucket's data directory. If the updated key matches a set of criteria,
converts the raw data file into an index and writes to an output S3 bucket.
As per the default configuration, the buck... | 5,349,800 |
def pinghost(host):
"""
Ping target with a 1-second timeout limit
:param str host: Destination to reach. IP address or domain name
:returns: True if reached, otherwise False
"""
host = str(host).split(':')[0] # leave off the port if exists
# print "Pinging"
if os.name == 'posix':
... | 5,349,801 |
def get_trade_factors(name: str,
mp: float,
allow_zero: bool,
long_open_values: List,
long_close_values: List,
short_open_values: List = None,
short_close_values: List = None) -> dict:
... | 5,349,802 |
def mbstrlen(src):
"""Return the 'src' string (Multibytes ASCII string) length.
:param src: the source string
"""
try:
return len(src.decode("utf8", errors = "replace"))
except Exception, err:
LOG.error("String convert issue %s", err)
return len(src) | 5,349,803 |
def activate(paramOverrides={}, modelOverride=None, filename=None):
"""Activate the veneer when beginning to compile a Scenic module."""
global activity, _globalParameters, lockedParameters, lockedModel, currentScenario
if paramOverrides or modelOverride:
assert activity == 0
_globalParameters.update(paramOverri... | 5,349,804 |
def test_get_version_with_absolute_path_to_root(mock_open_fix, mock_is_dir_true,
mock_is_path_true, versioner):
"""Tests if version number is returned when absolute path to
projects root is given and default VERSION.txt is used as a file."""
assert versioner.... | 5,349,805 |
def test_dimmer_turn_off(mock_openzwave):
"""Test turning off a dimmable Z-Wave light."""
node = MockNode()
value = MockValue(data=46, node=node)
values = MockLightValues(primary=value)
device = zwave.get_device(node=node, values=values, node_config={})
device.turn_off()
assert node.set_di... | 5,349,806 |
def adapted_border_postprocessing(border_prediction, cell_prediction):
"""
:param border_prediction:
:param cell_prediction:
:return:
"""
prediction_border_bin = np.argmax(border_prediction, axis=-1)
cell_prediction = cell_prediction > 0.5
seeds = border_prediction[:, :, 1] * (1 - bord... | 5,349,807 |
def calc_bonding_volume(rc_klab, dij_bar, rd_klab=None, reduction_ratio=0.25):
"""
Calculate the association site bonding volume matrix
Dimensions of (ncomp, ncomp, nbeads, nbeads, nsite, nsite)
Parameters
----------
rc_klab : numpy.ndarray
This matrix of cutoff distances for associat... | 5,349,808 |
def scale_enum(anchor, scales):
"""Enumerate a set of anchors for each scale wrt an anchor.
"""
w_w, h_h, x_ctr, y_ctr = genwhctrs(anchor)
w_s = w_w * scales
h_s = h_h * scales
anchors = makeanchors(w_s, h_s, x_ctr, y_ctr)
return anchors | 5,349,809 |
def L1():
"""
Graph for computing 'L1'.
"""
graph = beamline(scatter=True)
for node in ['scattered_beam', 'two_theta', 'L2', 'Ltotal']:
del graph[node]
return graph | 5,349,810 |
def _highlight_scoring(
original_example, subset_adversarial_result, adversarial_span_dict
):
"""
Calculate the highlighting score using classification results of adversarial examples
:param original_example:
:param subset_adversarial_result:
:param adversarial_span_dict:
"""
original_ut... | 5,349,811 |
def aniquilar(base, eliminaciones):
"""
Eliminar todas las claves (anidado) mencionadas en ''eliminaciones'', de
``base``.
.. versionadded:: 1.0
"""
for clave, valor in six.iteritems(eliminaciones):
if isinstance(valor, dict):
# NOTE: no probar si la clave [clave] existe; si... | 5,349,812 |
def server_hello(cmd, response):
"""Test command
"""
return response | 5,349,813 |
def init_db():
"""Initialise DB"""
clear_data()
add_admin_user()
add_settings()
add_forecast_areas()
add_regular_railway_data()
add_rapid_railway_data()
add_bullet_railway_data()
db.session.commit() | 5,349,814 |
def applyRigidAlignment(outDir, refFile, inDataListSeg, inDataListImg=[], icp_iterations=200):
"""
This function takes in a filelists(binary and raw) and makes the
size and spacing the same as the reference
"""
isoValue = 1e-20
antialias_iterations = 30
print("\n############# Rigidly... | 5,349,815 |
def test_vectorised_likelihood_not_vectorised_error(model, error):
"""
Assert the value is False if the likelihood is not vectorised and raises
an error.
"""
def dummy_likelihood(x):
if hasattr(x, '__len__'):
raise error
else:
return np.log(np.random.rand())
... | 5,349,816 |
def display_timestamps_pair(time_m_2):
"""Takes a list of the following form: [(a1, b1), (a2, b2), ...] and
returns a string (a_mean+/-a_error, b_mean+/-b_error).
"""
if len(time_m_2) == 0:
return '(empty)'
time_m_2 = np.array(time_m_2)
return '({}, {})'.format(
display_timestam... | 5,349,817 |
def get_legendre(degree, length):
"""
Producesthe Legendre polynomials of order `degree`.
Parameters
----------
degree : int
Highest order desired.
length : int
Number of samples of the polynomials.
Returns
-------
legendre : np.ndarray
A `degree`*`l... | 5,349,818 |
def forbid_start():
"""Pseudo context manager to forbid BUI to start during the with clause."""
global FORBID_START
FORBID_START = True
try:
yield None
finally:
FORBID_START = False | 5,349,819 |
def _get_table_names():
"""Gets an alphabetically ordered list of table names from facet_fields.csv.
Table names are fully qualified: <project id>:<dataset id>:<table name>
"""
config_path = os.path.join(app.app.config['DATASET_CONFIG_DIR'],
'bigquery.json')
table_nam... | 5,349,820 |
def openmm_simulate_amber_explicit(
pdb_file,
top_file=None,
check_point=None,
GPU_index=0,
output_traj="output.dcd",
output_log="output.log",
output_cm=None,
report_time=10*u.picoseconds,
sim_time=10*u.nanoseconds,
reeval_time=None, ... | 5,349,821 |
def _get_controller_of(pod):
"""Get a pod's controller's reference.
This uses the pod's metadata, so there is no guarantee that
the controller object reference returned actually corresponds to a
controller object in the Kubernetes API.
Args:
- pod: kubernetes pod object
Returns: the refe... | 5,349,822 |
def proxify_device_objects(
obj: Any,
proxied_id_to_proxy: Dict[int, ProxyObject],
found_proxies: List[ProxyObject],
):
""" Wrap device objects in ProxyObject
Search through `obj` and wraps all CUDA device objects in ProxyObject.
It uses `proxied_id_to_proxy` to make sure that identical CUDA de... | 5,349,823 |
def draw_triangles_1(length):
"""
Draw a red triangle
:param length: Length of 1 side of triangle
:pre: pos:lower left, turtle down , facing east
:post: pos:lower left, turtle down , facing east
:return: None
"""
turtle.pencolor('red')
for _ in range(3):
turtle.forward(length... | 5,349,824 |
def monotonicity(x, rounding_precision = 3):
"""Calculates monotonicity metric of a value of[0-1] for a given array.\nFor an array of length n, monotonicity is calculated as follows:\nmonotonicity=abs[(num. positive gradients)/(n-1)-(num. negative gradients)/(n-1)]."""
n = x.shape[0]
grad = np.gradient(x)
... | 5,349,825 |
def get_cluster_cids():
"""return list of CIDs with pin types"""
output = subprocess.check_output([
'docker-compose', 'exec', '-T', 'cluster', 'ipfs-cluster-ctl', 'pin',
'ls'
])
return [
'-'.join([l.split()[0], l.split()[-1].lower()])
for l in output.decode('utf-8').split... | 5,349,826 |
def download(homework, version="latest", redownload=False):
"""Download data files for the specified datasets. Defaults to downloading latest version on server.
Parameters:
homework (str): The name of the dataset to download data for, or "all" to download data for all datasets
versi... | 5,349,827 |
def parse_value_namedobject(tt):
"""
<!ELEMENT VALUE.NAMEDOBJECT (CLASS | (INSTANCENAME, INSTANCE))>
"""
check_node(tt, 'VALUE.NAMEDOBJECT')
k = kids(tt)
if len(k) == 1:
object = parse_class(k[0])
elif len(k) == 2:
path = parse_instancename(kids(tt)[0])
object = par... | 5,349,828 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload Dyson cloud."""
# Nothing needs clean up
return True | 5,349,829 |
def quat_correct(quat):
""" Converts quaternion to minimize Euclidean distance from previous quaternion (wxyz order) """
for q in range(1, quat.shape[0]):
if np.linalg.norm(quat[q-1] - quat[q], axis=0) > np.linalg.norm(quat[q-1] + quat[q], axis=0):
quat[q] = -quat[q]
return quat | 5,349,830 |
def vis_bbox(im, dets):
"""Visual debugging of detections."""
for i in range(dets.shape[0]):
bbox = tuple(int(np.round(x)) for x in dets[i, :4])
# class_name = CLASS_NAME[int(dets[i, 4]) - 1]
class_name = ' '
score = 0.99
cv2.rectangle(im, bbox[0:2], bbox[2:4], (0, 204, 0... | 5,349,831 |
def parse_record1(raw_record):
"""Parse raw record and return it as a set of unique symbols without \n"""
return set(raw_record) - {"\n"} | 5,349,832 |
def test_config_start_no_api(test_microvm_with_ssh, vm_config_file):
"""Test microvm start when API server thread is disabled."""
test_microvm = test_microvm_with_ssh
log_fifo_path = os.path.join(test_microvm.path, 'log_fifo')
metrics_fifo_path = os.path.join(test_microvm.path, 'metrics_fifo')
log_... | 5,349,833 |
def execute_contract_creation(
laser_evm, contract_initialization_code, contract_name=None
) -> Account:
""" Executes a contract creation transaction from all open states"""
# TODO: Resolve circular import between .transaction and ..svm to import LaserEVM here
open_states = laser_evm.open_states[:]
... | 5,349,834 |
def isValid(text):
"""
Returns True if the input is related to the meaning of life.
Arguments:
text -- user-input, typically transcribed speech
"""
return bool(re.search(r'\byour awesome\b', text, re.IGNORECASE)) | 5,349,835 |
def list_shared_with(uri, async_req=False):
"""Return array sharing policies"""
(namespace, array_name) = split_uri(uri)
api_instance = client.client.array_api
try:
return api_instance.get_array_sharing_policies(
namespace=namespace, array=array_name, async_req=async_req
)
... | 5,349,836 |
def format_html_data_table(dataframe, list_of_malformed, addLineBreak=False):
"""
Returns the predicted values as the data table
"""
if list_of_malformed:
list_of_malformed = str(list_of_malformed)
else:
list_of_malformed = "None"
# format numeric data into string format
for... | 5,349,837 |
def colorDistance(col1, col2):
"""Returns a number between 0 and root(3) stating how similar
two colours are - distance in r,g,b, space. Only used to find
names for things."""
return math.sqrt(
(col1.red - col2.red)**2 +
(col1.green - col2.green)**2 +
(col1.bl... | 5,349,838 |
def combine_from_streaming(stream: Iterable[runtime_pb2.Tensor]) -> runtime_pb2.Tensor:
""" Restore a result of split_into_chunks into a single serialized tensor """
stream = iter(stream)
first_chunk = next(stream)
serialized_tensor = runtime_pb2.Tensor()
serialized_tensor.CopyFrom(first_chunk)
... | 5,349,839 |
def portageq_envvar(options, out, err):
"""
return configuration defined variables. Use envvar2 instead, this will be removed.
"""
return env_var.function(options, out, err) | 5,349,840 |
def create_hash_factory(hashfun, complex_types=False, universe_size=None):
"""Create a function to make hash functions
:param hashfun: hash function to use
:type hashfun: callable
:param complex_types: whether hash function supports hashing of complex types,
either through nat... | 5,349,841 |
def testParamXMLFile():
"""
@tests:
ParamXMLFile.__init__
ParamXMLFile.load
ParamXMLFile.store
"""
fh = pyopenms.ParamXMLFile()
p = pyopenms.Param()
fh.store(b"test.ini", p)
fh.load(b"test.ini", p) | 5,349,842 |
def estimate_key(note_info, method="krumhansl", *args, **kwargs):
"""
Estimate key of a piece by comparing the pitch statistics of the
note array to key profiles [2]_, [3]_.
Parameters
----------
note_info : structured array, `Part` or `PerformedPart`
Note information as a `Part` or `Pe... | 5,349,843 |
def print_parsable_dstip(data, srcip, dstip):
"""Returns a parsable data line for the destination data.
:param data: the data source
:type data: dictionary
:param scrip: the source ip
:type srcip: string
:param dstip: the destination ip
:type dstip: string
:return: a line of urls and their hitcount
"... | 5,349,844 |
def OrListSelector(*selectors) -> pyrosetta.rosetta.core.select.residue_selector.OrResidueSelector:
"""
OrResidueSelector but 2+
(not a class, but returns a Or
:param selectors:
:return:
"""
sele = pyrosetta.rosetta.core.select.residue_selector.FalseResidueSelector()
for subsele in selec... | 5,349,845 |
def plot_regress_exog(res, exog_idx, exog_name='', fig=None):
"""Plot regression results against one regressor.
This plots four graphs in a 2 by 2 figure: 'endog versus exog',
'residuals versus exog', 'fitted versus exog' and
'fitted plus residual versus exog'
Parameters
----------
res : r... | 5,349,846 |
def capture_output(output=None):
"""Temporarily redirect stdout into a string buffer."""
if output is None:
output = StringIO()
try:
setup_redirect(output)
yield output
finally:
reset_redirect() | 5,349,847 |
def get_circles_with_admin_access(account_id: int) -> List[Circle]:
"""
SELECT
management_style,
c_name
FROM (
SELECT
'SELF_ADMIN' AS management_style,
c.management_style AS c_management_style,
c.admin_circle AS c_admin_circle,
... | 5,349,848 |
def combine(arr):
""" makes overlapping sequences 1 sequence """
def first(item):
return item[0]
def second(item):
return item[1]
if len(arr) == 0 or len(arr) == 1:
return arr
sarr = []
for c, val in enumerate(arr):
sarr.append((val[0], val[1], c))
... | 5,349,849 |
def sub_fft(f_fft, g_fft):
"""Substraction of two polynomials (FFT representation)."""
return sub(f_fft, g_fft) | 5,349,850 |
def recursive_fill_fields(input, output):
"""
Fills fields from output with fields from input,
with support for nested structures.
Parameters
----------
input : ndarray
Input array.
output : ndarray
Output array.
Notes
-----
* `output` should be at least the sam... | 5,349,851 |
def create_demo():
"""
Create project cli demo
"""
typer.secho(
"Welcome to flybirds cli. Please enter any information to continue.",
fg=typer.colors.MAGENTA,
)
user_dict = {
'device_id': "127.0.0.1:8200",
'package_name': "ctrip.android.view",
'web_driver_... | 5,349,852 |
def load_parameters(model_type, parameter_file):
"""
Loads in all parameter values given in a parameter file.
Parameters:
model_type (str):
sets the type of model, which determines the exact parameter set that is needed. Possible values for
the parameter mode... | 5,349,853 |
def handle_dat_edge(data_all):
"""
把dat_edge个每一条记录的info拆开,然后输出,方便后续的计算
为了简化计算,忽略时间信息,把所有的月份的联系记录汇总起来
"""
def cal_multi_3(string):
s = string.split(',')
month_times = len(s)
df = list(map(lambda x: list(map(eval, x.split(':')[1].split('_'))), s))
times_sum, weight_sum ... | 5,349,854 |
def quadraric_distortion_scale(distortion_coefficient, r_squared):
"""Calculates a quadratic distortion factor given squared radii.
The distortion factor is 1.0 + `distortion_coefficient` * `r_squared`. When
`distortion_coefficient` is negative (barrel distortion), the distorted radius
is only monotonically in... | 5,349,855 |
def convert_pdf_to_png(source, target):
"""
Wrapper for the ImageMagick convert utility.
:param source: Source file in PDF format.
:type source: str
:param target: Output file in PNG format.
:type target: str
"""
assert os.path.exists(source), "Source file does not exist: %s" % source
... | 5,349,856 |
def run(executable: str, *args: str):
"""
Run executable using core.process configuration, replacing bin with configured one, appending and prepending args.
"""
command_list = effective_command(executable, *args)
process = subprocess.run(command_list,
check=True,
... | 5,349,857 |
def open_path(path, **kwargs):
"""
Parameters
----------
path: str
window: tuple
e.g. ('1990-01-01','2030-01-01')
kwargs: all other kwargs the particular file might take, see the module for details
Returns
-------
"""
info = _tools.path2info(path)
module = arm_prod... | 5,349,858 |
def generate_code() -> str:
"""Generates password reset code
:return: Password reset code
:rtype: str
"""
return str(uuid.uuid4()) | 5,349,859 |
def process_file(name, files, url):
"""
Save file to shared folder on server, and return
the name of the file.
"""
def allowed_file(filename):
if "." not in filename:
return False
ext = filename.rsplit(".", 1)[1].lower()
return ext in config.ALLOWED_EXTENSIONS
... | 5,349,860 |
def decode_auth_token(auth_token):
"""
Decodes the auth token
:param auth_token:
:return: integer|string
"""
try:
payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'))
return payload['sub']
except jwt.ExpiredSignatureError:
return 'Signature expired. Please log in again.'
except jwt... | 5,349,861 |
def cached(path: str, validate: bool = False):
"""Similar to ``define``, but cache to a file.
:param path:
the path of the cache file to use
:param validate:
if `True`, always execute the function. The loaded result will be
passed to the function, when the cache exists. In that case... | 5,349,862 |
def json(*arguments):
"""
Transform *arguments parameters into JSON.
"""
return ast.Json(*arguments) | 5,349,863 |
def get_default_volume_size():
"""
:returns int: the default volume size (in bytes) supported by the
backend the acceptance tests are using.
"""
default_volume_size = environ.get("FLOCKER_ACCEPTANCE_DEFAULT_VOLUME_SIZE")
if default_volume_size is None:
raise SkipTest(
"Se... | 5,349,864 |
def set_global_user(**decorator_kwargs):
"""
Wrap a Flask blueprint view function to set the global user
``flask.g.user`` to an instance of ``CurrentUser``, according to the
information from the JWT in the request headers. The validation will also
set the current token.
This requires a flask ap... | 5,349,865 |
def teleport(targets: selector, destination: Union[selector, AbsPos, RelPos, LocPos, CurrentPos], facing: Union[selector, AbsPos, RelPos, LocPos, CurrentPos] = None, facing_type: container_type = container_type.entity):
"""
Args:
targets (selector): The targets to teleport
destination (Union[sel... | 5,349,866 |
def create_game_directory(gamedir, template, setting_dict=None):
"""
Initialize a new game directory named dirname
at the current path. This means copying the
template directory from muddery's root.
"""
def copy_tree(source, destination):
"""
copy file tree
"""
... | 5,349,867 |
def test_ts_ground_elements_surfaces():
"""Check timeseries ground elements are created correctly"""
# Create timeseries coords
gnd_element_coords = TsLineCoords.from_array(
np.array([[[-1, -1], [0, 0]], [[1, 1], [0, 0]]]))
pt_coords_1 = TsPointCoords.from_array(np.array([[-0.5, -1], [0, 0]]))
... | 5,349,868 |
def async_register_implementation(
hass: HomeAssistant, domain: str, implementation: AbstractOAuth2Implementation
) -> None:
"""Register an OAuth2 flow implementation for an integration."""
if isinstance(implementation, LocalOAuth2Implementation) and not hass.data.get(
DATA_VIEW_REGISTERED, False
... | 5,349,869 |
def showIntroScreen(screenSurf, p1name, p2name):
"""This is the screen that plays if the user selected "view intro" from the starting screen."""
screenSurf.fill(SKY_COLOR)
drawText('P y t h o n G O R I L L A S', screenSurf, SCR_WIDTH / 2, 15, WHITE_COLOR, SKY_COLOR, pos='center')
drawTex... | 5,349,870 |
def sample_wfreq(sample):
"""Return the Weekly Washing Frequency as a number."""
# `sample[3:]` strips the `BB_` prefix
results = session.query(Samples_Metadata.WFREQ).\
filter(Samples_Metadata.SAMPLEID == sample[3:]).all()
wfreq = np.ravel(results)
# Return only the first integer value fo... | 5,349,871 |
def generate_static_sku_detail_html(sku_id):
"""
生成静态商品详情页
:param sku_id: 商品sku id
:return:
"""
categories = get_categories()
# 获取商品sku规格
sku = SKU.objects.get(id=sku_id)
goods = sku.goods
sku_specs = sku.skuspecification_set.all().order_by('spec_id')
sku_key = list()
f... | 5,349,872 |
def setup_shed_tools_for_test(app, tmpdir, testing_migrated_tools, testing_installed_tools):
"""Modify Galaxy app's toolbox for migrated or installed tool tests."""
if testing_installed_tools:
# TODO: Do this without modifying app - that is a pretty violation
# of Galaxy's abstraction - we shoul... | 5,349,873 |
def OffsiteRestore(
source_dir,
encryption_password=None,
dir_substitution=None,
display_only=False,
ssd=False,
output_stream=sys.stdout,
preserve_ansi_escape_sequences=False,
):
"""\
Restores content created by previous Offsite backups.
"""
dir_substitutions = ... | 5,349,874 |
def speak_google(text, filename, model):
"""Synthesizes speech from the input string of text."""
from google.cloud import texttospeech
client = texttospeech.TextToSpeechClient()
input_text = texttospeech.types.SynthesisInput(text=text)
# Note: the voice can also be specified by name.
# Names o... | 5,349,875 |
def mlp_hyperparameter_tuning(no_of_hidden_neurons, epoch, alpha, roh, n_iter_no_change, X_train, X_validation, y_train, y_validation):
"""
INPUT
no_of_hidden_neurons: 1D int arary contains different values of no of neurons
present in 1st hidden layer (hyperparameter)
epoch: ... | 5,349,876 |
def setup_work_directory(work_dir, text_file):
"""Set up a temporary working directory."""
me = os.path.realpath(__file__)
my_dir = os.path.dirname(me)
file_src = os.path.join(TEX_FILE, text_file)
file_dst = os.path.join(work_dir, text_file)
shutil.copyfile(file_src, file_dst)
# copy static ... | 5,349,877 |
def play(p1:list[int], p2:list[int]) -> list[int]:
"""Gets the final hand of the winning player"""
while p1 and p2:
a = p1.pop(0)
b = p2.pop(0)
if a > b:
p1 += [a, b]
else:
p2 += [b, a]
return p1 + p2 | 5,349,878 |
def oda_update_uhf(dFs, dDs, dE):
"""
ODA update:
lbd = 0.5 - dE / E_deriv
"""
if type(dFs) is not list:
raise Exception("arg1 and arg2 are list of alpha/beta matrices.")
E_deriv = np.sum(dFs[0] * dDs[0] + dFs[1] * dDs[1])
lbd = 0.5 * (1. - dE / E_deriv)
if lbd < 0 or lbd > 1... | 5,349,879 |
def authorize(*roles):
"""Decorator that authorizes (or not) the current user
Raises an exception if the current user does not have at least
one of the listed roles.
"""
def wrapper(func):
"""wraps the protected function"""
def authorize_and_call(*args, **kwargs):
"""che... | 5,349,880 |
def trunked_greedy_by_size_offset_calculation(usage_recorders,
show_detail=False):
"""
An offset calculation algorithm designed for variable-length inputs.
@ params:
usage_recorders : tensor usage recoders (name, start_op, end_op, size)
global trunk_size... | 5,349,881 |
def main():
"""
A program to strip a string of punctuation and reverse it
:return: None
"""
in_string = "Enter a string's text here, to test the string!"
converted_string = clean_string_to_list(in_string)
reversed_list = reverse(converted_string)
print(in_string)
print(" ".join(reve... | 5,349,882 |
def decrypt(secret, ciphertext):
"""Given the first 16 bytes of splunk.secret, decrypt a Splunk password"""
plaintext = None
if ciphertext.startswith("$1$"):
ciphertext = base64.b64decode(ciphertext[3:])
key = secret[:16]
algorithm = algorithms.ARC4(key)
cipher = Cipher(algo... | 5,349,883 |
def load_skeleton(path):
"""
Load the skeleton from a pickle
"""
# Delayed import so script can be run with both Python 2 and 3
from unet_core.vessel_analysis import VesselTree
v = VesselTree()
v.load_skeleton(path)
return v.skeleton | 5,349,884 |
def industries_hierarchy() -> pd.DataFrame:
"""Read the Dow Jones Industry hierarchy CSV file.
Reads the Dow Jones Industry hierarchy CSV file and returns
its content as a Pandas DataFrame. The root node has
the fcode `indroot` and an empty parent.
Returns
-------
DataFrame : A Pandas Data... | 5,349,885 |
def ready():
""" A readiness endpoint, checks on DB health too.
:return: a 200 OK status if this server is up, and the backing DB is ready too; otherwise, a
503 "Temporarily unavailable."
"""
try:
# TODO: Move to a DAO class
client = get_mongo_client()
info = {}
... | 5,349,886 |
def er_to_file(db_cfg, fetch_sql, tbl_names, head_row, file_path):
"""
保存oracle中指定的ER到doc文件。
:param db_cfg: dict 连接oracle的配置信息
:param fetch_sql: str 查询ER结构的语句
:param tbl_names: list 要导出ER表的表名称
:param head_row: list 表格标题行内容
:param file_path: str ER保存到的xlsx文件
... | 5,349,887 |
def setup_callback(callback: typing.Awaitable):
"""
This function is used to setup the callback.
"""
callback.is_guild = False
""" The guild of the callback. """
callback.has_permissions = []
""" The permissions of the callback. """
callback.has_roles = []
""" The roles of the... | 5,349,888 |
def print_err(txt, include_moment=True):
"""Red collor print. Include time optional."""
print '\033[31m {} {} \n'.format(txt, str(datetime.now())
if include_moment else '') | 5,349,889 |
def prepare_for_training(ds, ds_name, conf, cache):
"""
Cache -> shuffle -> repeat -> augment -> batch -> prefetch
"""
AUTOTUNE = tf.data.experimental.AUTOTUNE
# Resample dataset. NB: dataset is cached in resamler
if conf["resample"] and 'train' in ds_name:
ds = oversample(ds, ds_na... | 5,349,890 |
def residual3d(inp, is_training, relu_after=True, add_bn=True,
name=None, reuse=None):
""" 3d equivalent to 2d residual layer
Args:
inp (tensor[batch_size, d, h, w, channels]):
is_training (tensor[bool]):
relu_after (bool):
add_bn (bool): add b... | 5,349,891 |
def check_letters_presence(word_generator, available_letters):
"""
check that the allowed characters actually occur; since the generation is random, there is always a chance that
it didn't occur for the words finite amount of words generated; try N times such that the chance for any
false positive is < 0.001 (0.... | 5,349,892 |
def marks(family, glyph):
"""
:param family:
:param glyph:
:return: True when glyph has at least one anchor
"""
has_mark_anchor = False
for anchor in glyph.anchors:
if anchor.name:
if anchor.name.startswith("_"):
has_mark_anchor = True
brea... | 5,349,893 |
def generate_bom(pcb_modules, config, extra_data):
# type: (list, Config, dict) -> dict
"""
Generate BOM from pcb layout.
:param pcb_modules: list of modules on the pcb
:param config: Config object
:param extra_data: Extra fields data
:return: dict of BOM tables (qty, value, footprint, refs)... | 5,349,894 |
def make_wrapper_script(cmd):
"""Create a wrapper that runs the specified command locally and pauses."""
if os.name == 'nt':
template, ext = '@{exe}\n@pause', '.bat'
else:
# https://stackoverflow.com/questions/24016046/
# Needs testing!
template = '{exe}\necho "Press any key ... | 5,349,895 |
def _GetSharedLibraryInHost(soname, sosize, dirs):
"""Find a shared library by name in a list of directories.
Args:
soname: library name (e.g. libfoo.so)
sosize: library file size to match.
dirs: list of directories to look for the corresponding file.
Returns:
host library path if found, or None
... | 5,349,896 |
def check_n_jobs(n_jobs: int) -> int:
"""Check `n_jobs` parameter according to the scikit-learn convention.
Parameters
----------
n_jobs : int, positive or -1
The number of jobs for parallelization.
Returns
-------
n_jobs : int
Checked number of jobs.
"""
# scikit-l... | 5,349,897 |
def test_skip_banner(mock_organizer_init):
"""Test the Organizer.skip_banner() function
Arguments:
mock_organizer_init: patched to not perform constructor
"""
# Create an Organizer: skip_banner and set_metasploit_globals are patched
organizer = Organizer(planner=None, mode="system", minimum_... | 5,349,898 |
def write_itk_image(image, path):
"""Write an itk image to a path.
Parameters
----------
image : itk image or np.ndarray
Image to be written.
path : str
Path where the image should be written to.
"""
if isinstance(image, np.ndarray):
image = make_itk_image(image)
... | 5,349,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.