text
stringlengths 8
6.05M
|
|---|
#!/usr/bin/env python
# Ver. 1.0.1
import boto3
from pprint import pprint
import itertools
TAG_KEYS = 'Name', 'Env', 'Appname'
# Add credentials below
session = boto3.Session()
ec2 = session.resource('ec2')
instances = []
for instance in ec2.instances.all():
instances.append(instance.tags)
clean = filter(None,instances)
flat_list = list(itertools.chain.from_iterable(clean))
value_list = []
for instances in flat_list:
value_list.append(instances['Value'])
results = set(value_list)
print("{0:20} {1}".format("\nCount","Value\n"))
for values in results:
if values == "":
print('{0:20} {1}'.format("**BLANK VALUE**", value_list.count(values)))
else:
print('{0:20} {1}'.format(values, value_list.count(values)))
print("\n")
|
from cycler import cycler
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from dps.hyper import extract_data_from_job
from dps.utils import (
process_path, Config, sha_cache, set_clear_cache,
confidence_interval, standard_error
)
cache_dir = process_path('/home/eric/.cache/dps_plots')
plot_dir = './plots'
single_op_paths = Config()
single_op_paths['sum:dps'] = 'sample_efficiency/dps_new/sum/results.zip'
single_op_paths['sum:cnn_pretrained'] = 'sample_efficiency/cnn_pretrained/sum/results.zip'
single_op_paths['sum:cnn'] = 'sample_efficiency/cnn/sum/exp_cnn_sum_12hours_2017_10_21_00_54_52.zip'
single_op_paths['sum:cnn_pretrained_pure'] = 'sample_efficiency/cnn_pretrained_pure/sum/results.zip'
single_op_paths['sum:rnn_pure'] = 'sample_efficiency/rnn_pure/sum/results.zip'
single_op_paths['sum:rnn_pretrained_pure'] = 'sample_efficiency/rnn_pretrained_pure/sum/results.zip'
single_op_paths['prod:dps'] = 'sample_efficiency/dps_new/prod/results.zip'
single_op_paths['prod:cnn_pretrained'] = 'sample_efficiency/cnn_pretrained/prod/results.zip'
single_op_paths['prod:cnn'] = 'sample_efficiency/cnn/prod/exp_cnn_prod_12hours_2017_10_21_00_55_50.zip'
single_op_paths['prod:cnn_pretrained_pure'] = 'sample_efficiency/cnn_pretrained_pure/prod/results.zip'
single_op_paths['prod:rnn_pure'] = 'sample_efficiency/rnn_pure/prod/results.zip'
single_op_paths['prod:rnn_pretrained_pure'] = 'sample_efficiency/rnn_pretrained_pure/prod/results.zip'
single_op_paths['max:dps'] = 'sample_efficiency/dps_new/max/results.zip'
single_op_paths['max:cnn_pretrained'] = 'sample_efficiency/cnn_pretrained/max/results.zip'
single_op_paths['max:cnn'] = 'sample_efficiency/cnn/max/exp_cnn_max_12hours_2017_10_21_00_56_53.zip'
single_op_paths['max:cnn_pretrained_pure'] = 'sample_efficiency/cnn_pretrained_pure/max/results.zip'
single_op_paths['max:rnn_pure'] = 'sample_efficiency/rnn_pure/max/results.zip'
single_op_paths['max:rnn_pretrained_pure'] = 'sample_efficiency/rnn_pretrained_pure/max/results.zip'
single_op_paths['min:dps'] = 'sample_efficiency/dps_new/min/results.zip'
single_op_paths['min:cnn_pretrained'] = 'sample_efficiency/cnn_pretrained/min/results.zip'
single_op_paths['min:cnn'] = 'sample_efficiency/cnn/min/exp_cnn_min_12hours_2017_10_21_00_57_32.zip'
single_op_paths['min:cnn_pretrained_pure'] = 'sample_efficiency/cnn_pretrained_pure/min/results.zip'
single_op_paths['min:rnn_pure'] = 'sample_efficiency/rnn_pure/min/results.zip'
single_op_paths['min:rnn_pretrained_pure'] = 'sample_efficiency/rnn_pretrained_pure/min/results.zip'
combined_paths = Config()
combined_paths['dps'] = 'sample_efficiency/dps_new/combined/results.zip'
combined_paths['cnn_pretrained'] = 'sample_efficiency/cnn_pretrained/combined/results.zip'
combined_paths['cnn'] = 'sample_efficiency/cnn/combined/exp_cnn_all_2017_10_23_01_22_58.zip'
combined_paths['cnn_pretrained_pure'] = 'sample_efficiency/cnn_pretrained_pure/combined/results.zip'
combined_paths['rnn_pure'] = 'sample_efficiency/rnn_pure/combined/results.zip'
combined_paths['rnn_pretrained_pure'] = 'sample_efficiency/rnn_pretrained_pure/combined/results.zip'
parity_paths = Config()
parity_paths['B:dps'] = 'curriculum_parity/dps_new/B/results.zip'
parity_paths['B:cnn'] = 'curriculum_parity/cnn/A/exp_final_cnn_parity_A_2017_10_26_23_08_20.zip'
parity_paths['B:cnn_pretrained'] = 'curriculum_parity/cnn_pretrained/B/results.zip'
parity_paths['C:dps'] = 'curriculum_parity/dps_new/C/results.zip'
parity_paths['C:cnn'] = 'curriculum_parity/cnn/B/exp_final_cnn_parity_B_2017_10_26_23_07_11.zip'
parity_paths['C:cnn_pretrained'] = 'curriculum_parity/cnn_pretrained/C/results.zip'
size_paths = Config()
size_paths["A:dps"] = 'curriculum_size/dps_new/A/results.zip'
size_paths["A:cnn"] = 'curriculum_size/cnn/A/results.zip'
size_paths['A:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/A/results.zip'
size_paths['A:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/A/results.zip'
size_paths['A:rnn_pure'] = 'curriculum_size/rnn_pure/A/results.zip'
size_paths['A:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/A/results.zip'
size_paths["B:dps"] = 'curriculum_size/dps_new/B/results.zip'
size_paths["B:cnn"] = 'curriculum_size/cnn/B/results.zip'
size_paths['B:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/B/results.zip'
size_paths['B:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/B/results.zip'
size_paths['B:rnn_pure'] = 'curriculum_size/rnn_pure/B/results.zip'
size_paths['B:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/B/results.zip'
size_paths["C:dps"] = 'curriculum_size/dps_new/C/results.zip'
size_paths["C:cnn"] = 'curriculum_size/cnn/C/results.zip'
size_paths['C:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/C/results.zip'
size_paths['C:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/C/results.zip'
size_paths['C:rnn_pure'] = 'curriculum_size/rnn_pure/C/results.zip'
size_paths['C:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/C/results.zip'
size_paths["D:dps"] = 'curriculum_size/dps_new/D/results.zip'
size_paths["D:cnn"] = 'curriculum_size/cnn/D/results.zip'
size_paths['D:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/D/results.zip'
size_paths['D:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/D/results.zip'
size_paths['D:rnn_pure'] = 'curriculum_size/rnn_pure/D/results.zip'
size_paths['D:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/D/results.zip'
size_paths["E:dps"] = 'curriculum_size/dps_new/E/results.zip'
size_paths["E:cnn"] = 'curriculum_size/cnn/E/results.zip'
size_paths['E:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/E/results.zip'
size_paths['E:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/E/results.zip'
size_paths['E:rnn_pure'] = 'curriculum_size/rnn_pure/E/results.zip'
size_paths['E:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/E/results.zip'
size_paths["F:dps"] = 'curriculum_size/dps_new/F/results.zip'
size_paths["F:cnn"] = 'curriculum_size/cnn/F/results.zip'
size_paths['F:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/F/results.zip'
size_paths['F:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/F/results.zip'
size_paths['F:rnn_pure'] = 'curriculum_size/rnn_pure/F/results.zip'
size_paths['F:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/F/results.zip'
size_paths['G:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/G/results.zip'
size_paths['G:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/G/results.zip'
size_paths['H:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/H/results.zip'
size_paths['G:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/G/results.zip'
op_paths = Config()
op_paths['B:dps'] = 'curriculum_op/dps_new/B/results.zip'
op_paths['B:cnn'] = 'curriculum_op/cnn/A/exp_final_cnn_op_A_2017_10_26_23_08_20.zip'
op_paths['B:cnn_pretrained'] = 'curriculum_op/cnn_pretrained/B/results.zip'
op_paths['C:dps'] = 'curriculum_op/dps_new/C/results.zip'
op_paths['C:cnn'] = 'curriculum_op/cnn/B/exp_final_cnn_op_B_2017_10_26_23_07_11.zip'
op_paths['C:cnn_pretrained'] = 'curriculum_op/cnn_pretrained/C/results.zip'
ablation_paths = Config()
ablation_paths['full_interface'] = 'sample_efficiency/dps/combined/results.zip'
ablation_paths['no_modules'] = 'ablations/no_modules/results.zip'
ablation_paths['no_transformations'] = 'ablations/no_transformations/results.zip'
ablation_paths['no_classifiers'] = 'ablations/no_classifiers/results.zip'
def std_dev(ys):
y_upper = y_lower = [_y.std() for _y in ys]
return y_upper, y_lower
def ci95(ys):
conf_int = [confidence_interval(_y.values, 0.95) for _y in ys]
y = [_y.mean() for _y in ys]
y_lower = y - np.array([ci[0] for ci in conf_int])
y_upper = np.array([ci[1] for ci in conf_int]) - y
return y_upper, y_lower
def std_err(ys):
y_upper = y_lower = [standard_error(_y.values) for _y in ys]
return y_upper, y_lower
spread_measures = {func.__name__: func for func in [std_dev, ci95, std_err]}
def test_01_loss(r):
return 100 * r['test_01_loss']
@sha_cache(cache_dir)
def _extract_cnn_data(f, n_controller_units, spread_measure, y_func, groupby='n_train'):
flat = False
if isinstance(n_controller_units, int):
n_controller_units = [n_controller_units]
flat = True
if isinstance(groupby, str):
groupby = [groupby]
data = {}
df = extract_data_from_job(f, ['n_controller_units', 'curriculum:-1:do_train'] + groupby)
df.loc[df['curriculum:-1:do_train'] == False, 'curriculum:-1:n_train'] = 0
groups = df.groupby('n_controller_units')
for i, (k, _df) in enumerate(groups):
if k in n_controller_units:
_groups = _df.groupby(groupby)
values = [g for g in _groups]
x = [v[0] for v in values]
ys = [y_func(v[1]) for v in values]
y = [_y.mean() for _y in ys]
y_upper, y_lower = spread_measures[spread_measure](ys)
data[k] = np.stack([x, y, y_upper, y_lower])
if flat:
return next(iter(data.values()))
return data
@sha_cache(cache_dir)
def _extract_rl_data(f, spread_measure, y_func):
data = {}
df = extract_data_from_job(f, 'n_train')
df.loc[df['total_steps'] == 0, 'n_train'] = 0
groups = df.groupby('n_train')
values = list(groups)
x = [v[0] for v in values]
ys = [y_func(v[1]) for v in values]
y = [_y.mean() for _y in ys]
y_upper, y_lower = spread_measures[spread_measure](ys)
data = np.stack([x, y, y_upper, y_lower])
return data
def gen_sample_efficiency_single_op():
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(10, 7))
fig.text(0.52, 0.01, '# Training Examples', ha='center', fontsize=12)
fig.text(0.01, 0.51, '% Test Error', va='center', rotation='vertical', fontsize=12)
cnn_n_train = [32, 128, 512]
spread_measure = 'std_err'
pp = [
dict(title='Sum', key='sum'),
dict(title='Product', key='prod'),
dict(title='Maximum', key='max'),
dict(title='Minimum', key='min'),
]
for i, (ax, p) in enumerate(zip(axes.flatten(), pp)):
label_order = []
x, y, *yerr = _extract_rl_data(single_op_paths[p['key']]['dps'], spread_measure, test_01_loss)
label = 'RL + Interface'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--')
label_order.append(label)
data = _extract_cnn_data(
single_op_paths[p['key']]['cnn_pretrained'], cnn_n_train, spread_measure, test_01_loss, 'n_train')
for k, v in data.items():
x, y, *yerr = v
label = "CNN Pretrained - {} hidden units".format(k)
ax.errorbar(x, y, yerr=yerr, label=label)
label_order.append(label)
data = _extract_cnn_data(
single_op_paths[p['key']]['cnn_pretrained_pure'], cnn_n_train, spread_measure, test_01_loss, 'n_train')
for k, v in data.items():
x, y, *yerr = v
label = "CNN Pretrained Pure - {} hidden units".format(k)
ax.errorbar(x, y, yerr=yerr, label=label)
label_order.append(label)
data = _extract_cnn_data(
single_op_paths[p['key']]['rnn_pure'], 128, spread_measure, test_01_loss, 'n_train')
x, y, *yerr = data
label = "RNN - 128 hidden units".format(k)
ax.errorbar(x, y, yerr=yerr, label=label)
label_order.append(label)
data = _extract_cnn_data(
single_op_paths[p['key']]['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'n_train')
x, y, *yerr = data
label = "RNN Pretrained - 128 hidden units".format(k)
ax.errorbar(x, y, yerr=yerr, label=label)
label_order.append(label)
ax.set_title(p['title'])
ax.tick_params(axis='both', labelsize=14)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('log', basex=2)
ax.set_xticks(x)
legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())}
ordered_handles = [legend_handles[l] for l in label_order]
ax.legend(ordered_handles, label_order, loc='best', ncol=1)
plt.subplots_adjust(
left=0.07, bottom=0.08, right=0.98, top=0.95, wspace=0.05, hspace=0.15)
fig.savefig(os.path.join(plot_dir, 'sample_efficiency.pdf'))
return fig
def gen_sample_efficiency_combined():
fig = plt.figure(figsize=(5, 3.5))
ax = plt.gca()
cnn_n_train = [32, 128, 512]
spread_measure = 'std_err'
label_order = []
x, y, *yerr = _extract_rl_data(combined_paths['dps'], spread_measure, test_01_loss)
label = 'RL + Interface'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--')
label_order.append(label)
data = _extract_cnn_data(combined_paths['cnn_pretrained'], cnn_n_train, spread_measure, test_01_loss, 'n_train')
for k, v in data.items():
x, y, *yerr = v
label = "CNN - {} hidden units".format(k)
label_order.append(label)
ax.errorbar(x, y, yerr=yerr, label=label)
data = _extract_cnn_data(
combined_paths['cnn_pretrained_pure'], cnn_n_train, spread_measure, test_01_loss, 'n_train')
for k, v in data.items():
x, y, *yerr = v
label = "CNN Pretrained Pure - {} hidden units".format(k)
ax.errorbar(x, y, yerr=yerr, label=label)
label_order.append(label)
data = _extract_cnn_data(
combined_paths['rnn_pure'], 128, spread_measure, test_01_loss, 'n_train')
x, y, *yerr = data
label = "RNN - 128 hidden units".format(k)
ax.errorbar(x, y, yerr=yerr, label=label)
label_order.append(label)
data = _extract_cnn_data(
combined_paths['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'n_train')
x, y, *yerr = data
label = "RNN Pretrained - 128 hidden units".format(k)
ax.errorbar(x, y, yerr=yerr, label=label)
label_order.append(label)
ax.set_ylabel('% Test Error', fontsize=12)
ax.set_xlabel('# Training Examples', fontsize=12)
ax.tick_params(axis='both', labelsize=14)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('log', basex=2)
ax.set_xticks(x)
legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())}
ordered_handles = [legend_handles[l] for l in label_order]
ax.legend(ordered_handles, label_order, loc='best', ncol=1, fontsize=8)
plt.subplots_adjust(left=0.16, bottom=0.15, right=0.97, top=0.96)
fig.savefig(os.path.join(plot_dir, 'sample_efficiency_combined.pdf'))
return fig
def gen_super_sample_efficiency():
fig, _ = plt.subplots(2, 4, sharex=True, sharey=True, figsize=(10.7, 5.5))
fig.text(0.52, 0.01, '# Training Examples', ha='center', fontsize=12)
fig.text(0.01, 0.51, '% Test Error', va='center', rotation='vertical', fontsize=12)
shape = (2, 4)
indi_axes = [
plt.subplot2grid(shape, (0, 0)),
plt.subplot2grid(shape, (0, 1)),
plt.subplot2grid(shape, (1, 0)),
plt.subplot2grid(shape, (1, 1))
]
combined_ax = plt.subplot2grid(shape, (0, 2), colspan=2, rowspan=2)
pp = [
dict(title='Sum', key='sum'),
dict(title='Product', key='prod'),
dict(title='Maximum', key='max'),
dict(title='Minimum', key='min'),
]
cnn_n_train = [32, 128, 512]
spread_measure = 'std_err'
for i, (ax, p) in enumerate(zip(indi_axes, pp)):
x, y, *yerr = _extract_rl_data(single_op_paths[p['key']]['dps'], spread_measure, test_01_loss)
label = 'RL + Interface'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--')
cnn_sum_data = _extract_cnn_data(single_op_paths[p['key']]['cnn'], cnn_n_train, spread_measure, test_01_loss, 'n_train')
for k, v in cnn_sum_data.items():
x, y, *yerr = v
label = "CNN - {} hidden units".format(k)
ax.errorbar(x, y, yerr=yerr, label=label)
ax.set_title(p['title'])
ax.tick_params(axis='both', labelsize=14)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('log', basex=2)
# Combined
combined_ax.set_title("Combined Task")
combined_ax.tick_params(axis='both', labelsize=14)
combined_ax.set_ylim((0.0, 100.0))
combined_ax.set_xscale('log', basex=2)
label_order = []
x, y, *yerr = _extract_rl_data(combined_paths['dps'], spread_measure, test_01_loss)
label = 'RL + Interface'
combined_ax.errorbar(x, y, yerr=yerr, label=label, ls='--')
label_order.append(label)
cnn_all_data = _extract_cnn_data(combined_paths['cnn'], cnn_n_train, spread_measure, test_01_loss, 'n_train')
for k, v in cnn_all_data.items():
x, y, *yerr = v
label = "CNN - {} hidden units".format(k)
label_order.append(label)
combined_ax.errorbar(x, y, yerr=yerr, label=label)
legend_handles = {l: h for h, l in zip(*combined_ax.get_legend_handles_labels())}
ordered_handles = [legend_handles[l] for l in label_order]
combined_ax.legend(ordered_handles, label_order, loc='best', ncol=1)
plt.subplots_adjust(
left=0.09, bottom=0.11, right=0.97, top=0.95, wspace=0.13, hspace=0.20)
fig.savefig(os.path.join(plot_dir, 'sample_efficiency_super.pdf'))
return fig
def gen_size_curriculum():
fig, axes = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(10, 5))
spread_measure = 'std_err'
fig.text(0.52, 0.01, '# Training Examples on Test Task', ha='center', fontsize=12)
# ********************************************************************************
ax = axes[0]
xticks = set()
label_order = []
x, y, *yerr = _extract_rl_data(size_paths['A']['dps'], spread_measure, test_01_loss)
label = 'RL + Interface - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
xticks |= set(x)
rl_colour = line.get_c()
x, y, *yerr = _extract_rl_data(size_paths['D']['dps'], spread_measure, test_01_loss)
label = 'RL + Interface - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rl_colour)
label_order.append(label)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['A']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
xticks |= set(x)
cnn_colour = line.get_c()
x, y, *yerr = _extract_cnn_data(size_paths['D']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=cnn_colour)
label_order.append(label)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['A']['cnn_pretrained_pure'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN Pretrained Pure - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
xticks |= set(x)
cnn_pretrained_pure_colour = line.get_c()
x, y, *yerr = _extract_cnn_data(size_paths['D']['cnn_pretrained_pure'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN Pretrained Pure - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=cnn_pretrained_pure_colour)
label_order.append(label)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['A']['rnn_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'RNN Pure - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
xticks |= set(x)
rnn_pure_colour = line.get_c()
x, y, *yerr = _extract_cnn_data(size_paths['D']['rnn_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'RNN Pure - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rnn_pure_colour)
label_order.append(label)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['A']['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'RNN Pretrained Pure - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
xticks |= set(x)
rnn_pretrained_pure_colour = line.get_c()
x, y, *yerr = _extract_cnn_data(size_paths['D']['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'RNN Pretrained Pure - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rnn_pretrained_pure_colour)
label_order.append(label)
xticks |= set(x)
if not args.paper:
x, y, *yerr = _extract_cnn_data(size_paths['G']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN - Alternate Curric 1'
ax.errorbar(x, y, yerr=yerr, label=label, ls='-.', c=cnn_colour)
label_order.append(label)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['H']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN - Alternate Curric 2'
ax.errorbar(x, y, yerr=yerr, label=label, ls=':', c=cnn_colour)
label_order.append(label)
xticks |= set(x)
legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())}
ordered_handles = [legend_handles[l] for l in label_order]
ax.legend(ordered_handles, label_order, loc='best', ncol=1)
ax.set_title('3x3, 2-3 digits')
ax.set_ylabel('% Test Error', fontsize=12)
ax.tick_params(axis='both', labelsize=14)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('symlog', basex=2)
ax.set_xticks(sorted(xticks))
# ********************************************************************************
ax = axes[1]
xticks = set()
x, y, *yerr = _extract_rl_data(size_paths['B']['dps'], spread_measure, test_01_loss)
ax.errorbar(x, y, yerr=yerr, ls='-', c=rl_colour)
xticks |= set(x)
x, y, *yerr = _extract_rl_data(size_paths['E']['dps'], spread_measure, test_01_loss)
ax.errorbar(x, y, yerr=yerr, ls='--', c=rl_colour)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['B']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
ax.errorbar(x, y, yerr=yerr, ls='-', c=cnn_colour)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['E']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
ax.errorbar(x, y, yerr=yerr, ls='--', c=cnn_colour)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['B']['cnn_pretrained_pure'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
ax.errorbar(x, y, yerr=yerr, ls='-', c=cnn_pretrained_pure_colour)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['E']['cnn_pretrained_pure'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
ax.errorbar(x, y, yerr=yerr, ls='--', c=cnn_pretrained_pure_colour)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['B']['rnn_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train')
ax.errorbar(x, y, yerr=yerr, ls='-', c=rnn_pure_colour)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['E']['rnn_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train')
ax.errorbar(x, y, yerr=yerr, ls='--', c=rnn_pure_colour)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['B']['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train')
ax.errorbar(x, y, yerr=yerr, ls='-', c=rnn_pretrained_pure_colour)
xticks |= set(x)
x, y, *yerr = _extract_cnn_data(size_paths['E']['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train')
ax.errorbar(x, y, yerr=yerr, ls='--', c=rnn_pretrained_pure_colour)
xticks |= set(x)
ax.set_title('3x3, 4 digits')
ax.tick_params(axis='both', labelsize=14)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('symlog', basex=2)
ax.set_xticks(sorted(xticks))
# ********************************************************************************
# ax = axes[2]
# xticks = set()
# x, y, *yerr = _extract_rl_data(size_paths['C']['dps'], spread_measure, test_01_loss)
# ax.errorbar(x, y, yerr=yerr, ls='-', c=rl_colour)
# xticks |= set(x)
# x, y, *yerr = _extract_rl_data(size_paths['F']['dps'], spread_measure, test_01_loss)
# ax.errorbar(x, y, yerr=yerr, ls='--', c=rl_colour)
# xticks |= set(x)
# x, y, *yerr = _extract_cnn_data(size_paths['C']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
# ax.errorbar(x, y, yerr=yerr, ls='-', c=cnn_colour)
# xticks |= set(x)
# x, y, *yerr = _extract_cnn_data(size_paths['F']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
# ax.errorbar(x, y, yerr=yerr, ls='--', c=cnn_colour)
# xticks |= set(x)
# ax.set_title('3x3, 5 digits')
# ax.tick_params(axis='both', labelsize=14)
# ax.set_ylim((0.0, 100.0))
# ax.set_xscale('symlog', basex=2)
# ax.set_xticks(sorted(xticks))
plt.subplots_adjust(
left=0.09, bottom=0.11, right=0.97, top=0.95, wspace=0.13, hspace=0.20)
fig.savefig(os.path.join(plot_dir, 'size_curriculum.pdf'))
return fig
def gen_parity_curriculum():
fig, ax = plt.subplots(1, 1, sharex=True, sharey=True, figsize=(10, 5))
spread_measure = 'std_err'
fig.text(0.52, 0.01, '# Training Examples on Test Task', ha='center', fontsize=12)
ax.set_ylabel('% Test Error', fontsize=12)
ax.tick_params(axis='both', labelsize=14)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('log', basex=2)
label_order = []
x, y, *yerr = _extract_rl_data(parity_paths['B']['dps'], spread_measure, test_01_loss)
label = 'RL + Interface - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
rl_colour = line.get_c()
x, y, *yerr = _extract_rl_data(parity_paths['C']['dps'], spread_measure, test_01_loss)
label = 'RL + Interface - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rl_colour)
label_order.append(label)
x, y, *yerr = _extract_cnn_data(parity_paths['B']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
cnn_colour = line.get_c()
x, y, *yerr = _extract_cnn_data(parity_paths['C']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=cnn_colour)
label_order.append(label)
legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())}
ordered_handles = [legend_handles[l] for l in label_order]
ax.legend(ordered_handles, label_order, loc='best', ncol=1)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('symlog', basex=2)
plt.subplots_adjust(left=0.09, bottom=0.11, right=0.97, top=0.95, wspace=0.13, hspace=0.20)
fig.savefig(os.path.join(plot_dir, 'parity_curriculum.pdf'))
return fig
def gen_curric():
fig, axes = plt.subplots(1, 3, sharex=True, sharey=True, figsize=(10, 3.7))
spread_measure = 'std_err'
fig.text(0.52, 0.01, '# Training Examples on Test Task', ha='center', fontsize=12)
ax = axes[0]
ax.set_title('3x3, 2-3 digits')
ax.set_ylabel('% Test Error', fontsize=12)
ax.tick_params(axis='both', labelsize=14)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('log', basex=2)
label_order = []
x, y, *yerr = _extract_rl_data(size_paths['A']['dps'], spread_measure, test_01_loss)
label = 'RL + Interface - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
rl_colour = line.get_c()
x, y, *yerr = _extract_rl_data(size_paths['C']['dps'], spread_measure, test_01_loss)
label = 'RL + Interface - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rl_colour)
label_order.append(label)
x, y, *yerr = _extract_cnn_data(size_paths['A']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
cnn_colour = line.get_c()
x, y, *yerr = _extract_cnn_data(size_paths['C']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=cnn_colour)
label_order.append(label)
ax = axes[1]
ax.set_title('3x3, 4 digits')
ax.tick_params(axis='both', labelsize=14)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('log', basex=2)
x, y, *yerr = _extract_rl_data(size_paths['B']['dps'], spread_measure, test_01_loss)
ax.errorbar(x, y, yerr=yerr, ls='-', c=rl_colour)
x, y, *yerr = _extract_rl_data(size_paths['F']['dps'], spread_measure, test_01_loss)
ax.errorbar(x, y, yerr=yerr, ls='--', c=rl_colour)
x, y, *yerr = _extract_cnn_data(size_paths['B']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
ax.errorbar(x, y, yerr=yerr, ls='-', c=cnn_colour)
x, y, *yerr = _extract_cnn_data(size_paths['F']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
ax.errorbar(x, y, yerr=yerr, ls='--', c=cnn_colour)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('log', basex=2)
ax = axes[2]
ax.set_title('even -> odd')
ax.tick_params(axis='both', labelsize=14)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('log', basex=2)
label_order = []
x, y, *yerr = _extract_rl_data(parity_paths['A']['dps'], spread_measure, test_01_loss)
label = 'RL + Interface - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
rl_colour = line.get_c()
x, y, *yerr = _extract_rl_data(parity_paths['C']['dps'], spread_measure, test_01_loss)
label = 'RL + Interface - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rl_colour)
label_order.append(label)
x, y, *yerr = _extract_cnn_data(parity_paths['A']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN - With Curric'
line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
cnn_colour = line.get_c()
x, y, *yerr = _extract_cnn_data(parity_paths['C']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train')
label = 'CNN - No Curric'
ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=cnn_colour)
label_order.append(label)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('log', basex=2)
legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())}
ordered_handles = [legend_handles[l] for l in label_order]
ax.legend(ordered_handles, label_order, loc='best', ncol=1, fontsize=8)
plt.subplots_adjust(
left=0.08, bottom=0.15, right=0.98, top=0.91, wspace=0.13, hspace=0.20)
fig.savefig(os.path.join(plot_dir, 'curriculum.pdf'))
return fig
def gen_ablations():
plt.figure(figsize=(5, 3.5))
ax = plt.gca()
ax.set_ylabel('% Test Error', fontsize=12)
ax.set_xlabel('# Training Examples', fontsize=12)
ax.tick_params(axis='both', labelsize=14)
ax.set_ylim((0.0, 100.0))
ax.set_xscale('log', basex=2)
spread_measure = 'std_err'
label_order = []
x, y, *yerr = _extract_rl_data(ablation_paths['full_interface'], spread_measure, lambda r: 100 * r['test_loss'])
label = 'Full Interface'
ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
x, y, *yerr = _extract_rl_data(ablation_paths['no_modules'], spread_measure, test_01_loss)
label = 'No Modules'
ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
x, y, *yerr = _extract_rl_data(ablation_paths['no_transformations'], spread_measure, test_01_loss)
label = 'No Transformations'
ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
x, y, *yerr = _extract_rl_data(ablation_paths['no_classifiers'], spread_measure, test_01_loss)
label = 'No Classifiers'
ax.errorbar(x, y, yerr=yerr, label=label, ls='-')
label_order.append(label)
legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())}
ordered_handles = [legend_handles[l] for l in label_order]
ax.legend(ordered_handles, label_order, loc='best', ncol=1, fontsize=8)
plt.subplots_adjust(left=0.16, bottom=0.15, right=0.97, top=0.96)
fig.savefig(os.path.join(plot_dir, 'ablations.pdf'))
return fig
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("plots", nargs='+')
parser.add_argument("--style", default="bmh")
parser.add_argument("--no-block", action="store_true")
parser.add_argument("--show", action="store_true")
parser.add_argument("--clear-cache", action="store_true")
parser.add_argument("--paper", action="store_true")
args = parser.parse_args()
plt.rc('lines', linewidth=1)
color_cycle = ['tab:blue', 'tab:orange', 'tab:green', 'tab:brown']
os.makedirs(plot_dir, exist_ok=True)
if args.clear_cache:
set_clear_cache(True)
with plt.style.context(args.style):
plt.rc('axes', prop_cycle=(cycler('color', color_cycle)))
funcs = {
"single_op": gen_sample_efficiency_single_op,
"combined": gen_sample_efficiency_combined,
"super": gen_super_sample_efficiency,
"size": gen_size_curriculum,
"parity": gen_parity_curriculum,
"curriculum": gen_curric,
"ablations": gen_ablations,
}
for name, do_plot in funcs.items():
if name in args.plots:
fig = do_plot()
if args.show:
plt.show(block=not args.no_block)
|
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url, include
from core.views import IndexView, PagesView, PageView, ArticleView, ArticlesView
urlpatterns = patterns('',
url('^$', IndexView.as_view(), name='index'),
url(r'pages/', PagesView.as_view(), name='pages'),
url(r'page/(?P<slug>[-\w]+)/$', PageView.as_view(), name='page'),
url(r'articles/', ArticlesView.as_view(), name='articles'),
url(r'article/(?P<slug>[-\w]+)/$', ArticleView.as_view(), name='article'),
)
|
b = sorted(list(map(int,input().split())))
print('Yes' if b[0]+b[1] == b[2] else 'No')
|
"""
*********************************************************************
This file is part of:
The Acorn Project
https://wwww.twistedfields.com/research
*********************************************************************
Copyright (c) 2019-2021 Taylor Alexander, Twisted Fields LLC
Copyright (c) 2021 The Acorn Project contributors (cf. AUTHORS.md).
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*********************************************************************
"""
# coding: utf-8
# Loop the imports so that temporary syntax errors in imported files does not kill server.
while True:
try:
import time
from flask import Flask, render_template, request, send_from_directory, jsonify
from flask_redis import FlaskRedis
import sys
from svgpathtools import svg2paths, paths2svg
import re
import pickle
import json
import datetime
sys.path.append('../vehicle')
from master_process import Robot, RobotCommand
break
except Exception as e:
print(e)
print("Server had some error. Restarting...")
time.sleep(5)
app = Flask(__name__, template_folder="templates")
app.config['REDIS_URL'] = "redis://:@localhost:6379/0"
redis_client = FlaskRedis(app)
volatile_path = [] # When the robot is streaming a path, save it in RAM here.
active_site = "twistedfields"
date_handler = lambda obj: (
obj.isoformat() + "-07:00"
if isinstance(obj, (datetime.datetime, datetime.date))
else None
)
def send_herd_data():
keys = get_robot_keys()
robots = robots_to_json(keys)
return jsonify(robots)
def get_robot_keys():
robot_keys = []
for key in redis_client.scan_iter():
if ':robot:' in str(key):
if ':command:' not in str(key):
robot_keys.append(key)
return robot_keys
def load_first_robot(redis_client):
keys = get_robot_keys()
for key in keys:
robot = pickle.loads(redis_client.get(key))
time_stamp = json.dumps(robot.time_stamp, default=date_handler)
return robot
def robots_to_json(keys):
robots_list = []
for key in keys:
robot = pickle.loads(redis_client.get(key))
time_stamp = json.dumps(robot.time_stamp, default=date_handler)
live_path_data = robot.live_path_data
gps_path_data = robot.gps_path_data
debug_points = robot.debug_points
#print(debug_points)
robot_entry = { 'name': robot.name, 'lat': robot.location.lat, 'lon':
robot.location.lon, 'heading': robot.location.azimuth_degrees,
'speed': robot.speed, 'turn_intent_degrees': robot.turn_intent_degrees,
'voltage': robot.voltage, 'control_state': robot.control_state,
'motor_state': robot.motor_state, 'time_stamp': time_stamp,
'loaded_path_name': "" if not robot.loaded_path_name else robot.loaded_path_name.split('gpspath:')[1].split(':key')[0],
'live_path_data' : live_path_data,
'gps_path_data' : gps_path_data,
'debug_points' : debug_points,
'autonomy_hold' : robot.autonomy_hold,
'activate_autonomy' : robot.activate_autonomy,
'access_point_name' : robot.wifi_ap_name,
'wifi_signal' : robot.wifi_strength,
'gps_distances' : robot.gps_distances,
'gps_angles' : robot.gps_angles,
'gps_distance_rates' : robot.gps_path_lateral_error_rates,
'gps_angle_rates' : robot.gps_path_angular_error_rates,
'strafe' : robot.strafe,
'rotation' : robot.rotation,
'strafeD' : robot.strafeD,
'steerD' : robot.steerD
# 'front_lat': debug_points[0].lat,
# 'front_lon': debug_points[0].lat,
# 'rear_lat': debug_points[1].lat,
# 'rear_lon': debug_points[1].lat,
# 'front_close_lat': debug_points[2].lat,
# 'front_close_lon': debug_points[2].lat,
# 'rear_close_lat': debug_points[3].lat,
# 'rear_close_lon': debug_points[3].lat,
}
robots_list.append(robot_entry)
return robots_list
if __name__ == "__main__":
oldlist = None
while True:
robot = load_first_robot(redis_client)
newlist = robot.gps_path_lateral_error_rates
if oldlist:
offset = 0
counter = 0
match_found = False
while match_found == False:
#for value in old_list:
if oldlist[offset+counter] == newlist[counter]:
counter+=1
if counter > 50:
print("Found Match, offset: {}".format(offset))
match_found = True
else:
offset += 1
counter = 0
oldlist = newlist
#print(robot.gps_path_lateral_error_rates)
time.sleep(1)
|
from django import forms
from . import models
class AuthForm(forms.Form):
login = forms.CharField(max_length=32)
password = forms.CharField(max_length=32)
stay_authorized = forms.BooleanField(required=False)
class TaskForm(forms.Form):
language = forms.ChoiceField(choices=models.Language.choices)
solution = forms.CharField(required=False, empty_value=None,
max_length=256 * 1024)
solution_file = forms.FileField(required=False, max_length=256 * 1024)
|
n = int(input())
m = []
for i in range(0, n):
a, b, c = map(float, input().split(' '))
m.append((a * 2 + b * 3 + c * 5) / 10)
for j in m:
print('{:.1f}'.format(j))
|
import dash_bootstrap_components as dbc
from dash import Input, Output, State, html
collapse = html.Div(
[
dbc.Button(
"Open collapse",
id="collapse-button",
className="mb-3",
color="primary",
n_clicks=0,
),
dbc.Collapse(
dbc.Card(dbc.CardBody("This content is hidden in the collapse")),
id="collapse",
is_open=False,
),
]
)
@app.callback(
Output("collapse", "is_open"),
[Input("collapse-button", "n_clicks")],
[State("collapse", "is_open")],
)
def toggle_collapse(n, is_open):
if n:
return not is_open
return is_open
|
from math import pi
import matplotlib.pyplot as plt
import numpy as np
def relative_error(x0, x): return np.abs(x0 - x) / np.abs(x0)
def log_teylor_series(x, N=5):
print(N)
a = x - 1
a_k = a # x в степени k. Сначала k=1
y = a # Значене логарифма, пока для k=1.
for k in range(2, N): # сумма по степеням
a_k = -a_k * a # последовательно увеличиваем степень и учитываем множитель со знаком
y = y + a_k / k
return y
def get_N(eps):
return (1 - eps) / eps
# Узлы итерполяции
N = 5
xn = 1 + 1. / (1 + np.arange(N))
zn = np.arange(N)
print(zn)
un = 3 * (xn - 1) / (2 * (1 + xn))
def opt_u(a, b, zn):
return (a + b) / 2 + (b - a) / 2 * np.cos(((2 * zn + 1) * pi) / (2 * (zn + 1)))
opt = opt_u(0, 1, zn)
print(opt)
print(xn)
print(un)
yn = np.log(xn)
yyn = np.log(un)
optyn = np.log(opt)
# Тестовые точки
x = np.linspace(xn[4], xn[0], 1000)
xu = np.linspace(un[4], un[0], 1000)
xuu = np.linspace(opt[4], opt[0], 1000)
y = np.log(x)
yy = np.log(xu)
yyy = np.log(xuu)
# Многочлен лагранжа
import scipy.interpolate
L = scipy.interpolate.lagrange(xn, yn)
L1 = scipy.interpolate.lagrange(un, yyn)
Lopt = scipy.interpolate.lagrange(opt, optyn)
yl = L(x)
y2 = L1(xu)
y3 = Lopt(xuu)
plt.plot(x, y, '-k')
plt.plot(xn, yn, '.b')
plt.plot(x, yl, '-r')
#plt.plot(xu, y2, '-g')
#plt.plot(x, y3)
plt.xlabel("$x$")
plt.ylabel("$y=\ln x$")
plt.show()
plt.plot(xu, yy, '-k')
plt.plot(un, yyn, '.b')
plt.plot(xu, y2, '-g')
plt.xlabel("$x$")
plt.ylabel("$y=\ln x$")
plt.show()
plt.plot(xuu, yyy, '-k')
plt.plot(opt, optyn, '.b')
plt.plot(xuu, y3, '-g')
plt.xlabel("$x$")
plt.ylabel("$y=\ln x$")
plt.show()
plt.semilogy(x, relative_error(y, yl), '-r')
plt.semilogy(xu, relative_error(yy, y2), '-g')
plt.semilogy(x, relative_error(yyy, y3), '-b')
plt.xlabel("$Аргумент$")
plt.ylabel("$Относительная\;погрешность$")
plt.show()
|
import cv2
import requests
import io
uri = 'https://node-red-001.au-syd.mybluemix.net/sendImage'
cap = cv2.VideoCapture(0)
cv2.namedWindow("Camera", cv2.WINDOW_AUTOSIZE)
while True:
res, frame = cap.read()
if res:
resized = cv2.resize(frame, (frame.shape[1] // 2, frame.shape[0] // 2))
_, img_encoded = cv2.imencode('.jpg', frame)
files = {'file': ("image.jpg", io.BytesIO(img_encoded), 'image/jpeg')}
r = requests.post(uri, files=files)
print(r.text)
cv2.imshow("Camera", resized)
cv2.waitKey(4000)
|
"""JSON CLI formatter."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
def format(obj): # pylint: disable=W0622
"""Output object as json."""
return json.dumps(obj)
|
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
1
2
3
4
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
1
2
3
4
5
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
>>>
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
21
22
23
24
25
26
27
28
29
30
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
0
10
20
30
40
50
60
70
80
90
100
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
-1
0
1
2
3
4
5
6
7
8
9
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
0
10
20
30
40
50
60
70
80
90
100
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
10
9
8
7
6
5
4
3
2
1
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
100
95
90
85
80
75
70
65
60
55
50
45
40
35
30
25
20
15
10
5
0
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Apples
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
['Milk', 'Butter', 'Onion']
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
['Eggs', 'Milk', 'Butter', 'Onion']
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
['Apples']
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
['Onion', 'Apples']
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 26, in <module>
print groceries[0,2,4]
TypeError: list indices must be integers, not tuple
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
>>>
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 26, in <module>
print groceries[0, 2, 4]
TypeError: list indices must be integers, not tuple
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Apples
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Apples
['Milk', 'Butter', 'Onion']
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Apples
['Milk', 'Butter', 'Onion']
['Eggs', 'Milk', 'Butter', 'Onion']
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Apples
['Milk', 'Butter', 'Onion']
['Eggs', 'Milk', 'Butter', 'Onion']
['Eggs', 'Milk', 'Butter', 'Onion']
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Apples
['Milk', 'Butter', 'Onion']
['Eggs', 'Milk', 'Butter', 'Onion']
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Apples
['Milk', 'Butter', 'Onion']
['Eggs', 'Milk', 'Butter', 'Onion']
['Onion', 'Apples']
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Apples
['Milk', 'Butter', 'Onion']
['Eggs', 'Milk', 'Butter', 'Onion']
['Onion', 'Apples']
['Eggs', 'Butter', 'Apples']
>>>
>>>
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 36, in <module>
len(groceries)
NameError: name 'groceries' is not defined
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 36, in <module>
print len(groceries)
NameError: name 'groceries' is not defined
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
5
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
5
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Eggs
Milk
Butter
Onion
Apples
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Eggs
Milk
Butter
Onion
Apples
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Eggs
Milk
Butter
Onion
Apples
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Eggs
Milk
Butter
Onion
Apples
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Eggs
Milk
Butter
Onion
Apples
>>> groceries.sorted
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
groceries.sorted
AttributeError: 'list' object has no attribute 'sorted'
>>> groceries.sorted()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
groceries.sorted()
AttributeError: 'list' object has no attribute 'sorted'
>>> groceries
['Apples', 'Onion', 'Butter', 'Milk', 'Eggs']
>>> groceries.sort()
>>> groceries.reverse()
>>> groceries
['Onion', 'Milk', 'Eggs', 'Butter', 'Apples']
>>> groceries.sort(reverse=True)
>>> groceries
['Onion', 'Milk', 'Eggs', 'Butter', 'Apples']
'
>>> groceries.append('Asparagus')
>>> groceries
['Onion', 'Milk', 'Eggs', 'Butter', 'Apples', 'Asparagus']
>>> groceries.extend(['Ice Cream', 'Bananas'])
>>> groceries
['Onion', 'Milk', 'Eggs', 'Butter', 'Apples', 'Asparagus', 'Ice Cream', 'Bananas']
>>> groceries.insert(2, 'Oranges')
>>> groceries
['Onion', 'Milk', 'Oranges', 'Eggs', 'Butter', 'Apples', 'Asparagus', 'Ice Cream', 'Bananas']
>>> groceries.remove('Apples')
>>> groceries
['Onion', 'Milk', 'Oranges', 'Eggs', 'Butter', 'Asparagus', 'Ice Cream', 'Bananas']
>>> name = 'Jennifer'
>>> len(name)
8
>>> name.lower
<built-in method lower of str object at 0x0000000003D417E0>
>>> name.lower()
'jennifer'
>>> name.upper()
'JENNIFER'
>>> name.capitalize()
'Jennifer'
>>> sentence = "what will I have for dinner?"
>>> sentence
'what will I have for dinner?'
>>> sentence.capitalize
<built-in method capitalize of str object at 0x0000000003C78830>
>>> sentence.capitalize()
'What will i have for dinner?'
>>> name[7]
'r'
>>> name.replace('e', 'a')
'Jannifar'
>>> name.replace('i', 'i'*5)
'Jenniiiiifer'
>>> name.replace('e', 'a', 1)
'Jannifer'
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 79, in <module>
print cal_power(4, 2)
NameError: name 'cal_power' is not defined
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
8
15
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 84, in <module>
print cal_power(4, 2)
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 77, in cal_power
result *= base
UnboundLocalError: local variable 'result' referenced before assignment
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 85, in <module>
print cal_power(4, 2)
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 79, in cal_power
return answer
NameError: global name 'answer' is not defined
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 85, in <module>
print cal_power(4, 2)
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 78, in cal_power
answer *= base
UnboundLocalError: local variable 'answer' referenced before assignment
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
16
243
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
16
243
Enter base: 4>>> name.lower
<built-in method lower of str object at 0x0000000003D417E0>
>>> name.lower()
'jennifer'
>>> name.upper()
'JENNIFER'
>>> name.capitalize()
'Jennifer'
>>> sentence = "what will I have for dinner?"
>>> sentence
'what will I have for dinner?'
>>> sentence.capitalize
<built-in method capitalize of str object at 0x0000000003C78830>
>>> sentence.capitalize()
'What will i have for dinner?'
>>> name[7]
'r'
>>> name.replace('e', 'a')
'Jannifar'
>>> name.replace('i', 'i'*5)
'Jenniiiiifer'
>>> 4
Enter power:
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 90, in <module>
print cal_power(int(b), int(p))
ValueError: invalid literal for int() with base 10: '4>>> name.lower'
>>>
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
16
243
Enter base: 4
Enter power: 3
64
>>> import math
>>> math.pow
<built-in function pow>
>>> math.pow(4,2)
16.0
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
16
243
Enter base: 5
Enter power: 2
25
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 95, in <module>
print math.pow(5,10)
NameError: name 'math' is not defined
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Hello!
It's Thursday!
Value is June is almost over!
Value is What is your plan for July 4th?
16
243
Enter base: 5
Enter power: 2
25
1024.0
>>> import.random
SyntaxError: invalid syntax
>>> import random
>>> random.randInt(1,5)
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
random.randInt(1,5)
AttributeError: 'module' object has no attribute 'randInt'
>>> random.randInt(1,3)
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
random.randInt(1,3)
AttributeError: 'module' object has no attribute 'randInt'
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
{'Butter': 2.69, 'Yogurt': 3.19, 'Eggs': 2.59, 'Milk': 3.19}
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
2.59
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
2.59
Butter
Yogurt
Eggs
Milk
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Butter
Yogurt
Eggs
Milk
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
>>>
2.59
Butter
Yogurt
Eggs
Milk
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
2.59
Traceback (most recent call last):
File "C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py", line 107, in <module>
print item + " " + groceries_by_price[item]
TypeError: cannot concatenate 'str' and 'float' objects
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
2.59
Butter 2.69
Yogurt 3.19
Eggs 2.59
Milk 3.19
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Enter width: 8
Enter heigh: 5
########
########
########
########
########
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Enter width: 5
Enter heigh: 5
#####
#####
#####
#####
#####
>>>
== RESTART: C:\Users\daijon.bereolacarson\Desktop\javatutor\secondpython.py ==
Enter width: 20
Enter heigh: 10
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
>>>
|
# Author:ambiguoustexture
# Date: 2020-03-10
file_shaped = './enwiki-20150112-400-r100-10576_shaped.txt'
file_countries = './countries.txt'
file_compound_words = './compound_words_process_result.txt'
countries_set = set()
countries_dict = {}
with open(file_countries) as countries:
for country in countries:
words = country.split(' ')
if len(words) > 1:
countries_set.add(country.strip())
if words[0] in countries_dict:
compound_len = countries_dict[words[0]]
if not len(words) in compound_len:
compound_len.append(len(words))
compound_len.sort(reverse=True)
else:
countries_dict[words[0]] = [len(words)]
with open(file_shaped) as text_shaped, \
open(file_compound_words, 'w') as compound_words:
for line in text_shaped:
words = line.strip().split(' ')
res = []
flag_skip = 0
for i in range(len(words)):
if flag_skip > 0:
flag_skip -= 1
continue
if words[i] in countries_dict:
flag_hit = False
for length in countries_dict[words[i]]:
if ' '.join(words[i:i + length]) in countries_set:
res.append('_'.join(words[i:i+length]))
flag_skip = length - 1
flag_hit = True
break
if flag_hit:
continue
res.append(words[i])
print(*res, sep=' ', end='\n', file=compound_words)
|
import unittest
from katas.beta.beetlejuice_x3_bug_fix import beetle_juice
class BeetleJuiceTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(beetle_juice("Harry!"), "Harry! Harry! Harry!")
def test_equal_2(self):
self.assertEqual(beetle_juice("Hobie!"), "Hobie! Hobie! Hobie!")
def test_equal_3(self):
self.assertEqual(beetle_juice("Sheila!"), "Sheila! Sheila! Sheila!")
def test_equal_4(self):
self.assertEqual(beetle_juice("Shoshanna!"),
"Shoshanna! Shoshanna! Shoshanna!")
|
# -*- coding: utf-8 -*-
"""
Fundamentus Scraper
@input: Target Symbol (string)
@output: Market Data (DataFrame)
Created on Oct 2020
@author: Murilo Fregonesi Falleiros
"""
def ScrapMarketData(sym, Gui):
#%% Fundamentus Access
import bs4 as bs
from urllib.request import Request, urlopen
fund_url = 'https://fundamentus.com.br/'
tgt_url = 'detalhes.php?papel='
# Use an HTTP client to get the document behind the URL
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request((fund_url + tgt_url + sym),headers=hdr)
doc = urlopen(req)
soup_tgt = bs.BeautifulSoup(doc,'lxml') # HTML doc data structure
#%% Market Access
# Scrap Target Page
tables = soup_tgt.find_all('table') # Tables
for iTb, table in enumerate(tables):
trs = table.find_all('tr') # Lines
for iTr, tr in enumerate(trs):
tds = tr.find_all('td') # Columns
for iTd, td in enumerate(tds):
if(td.text == '?Setor'):
href = str(tds[iTd + 1].a).replace('"',' ').split()[2]
Gui.AppendLog('\nSector \'{}\', number {}'.format(tds[iTd + 1].text,href[href.find('=')+1:len(href)]))
try:
req = Request((fund_url + href),headers=hdr)
doc = urlopen(req)
soup_mkt = bs.BeautifulSoup(doc,'lxml') # HTML doc data structure
except:
return -1
#%% Market Scrap
import pandas as pd
ths = soup_mkt.table.find_all('th') # HTML table columns
df_columns = [th.text for th in ths] # Get table columns text
df_mkt = pd.DataFrame() # Market DataFrame
trs = soup_mkt.table.tbody.find_all('tr') # Table content lines
for iTr, tr in enumerate(trs):
tds = trs[iTr].find_all('td') # Columns per line
tmp_td = [td.text for td in tds] # Columns content list
# Construct market DataFrame
df_mkt = pd.concat([df_mkt, pd.DataFrame(tmp_td).transpose()], ignore_index=True)
df_mkt.columns = df_columns # Label columns
df_mkt.set_index('Papel',inplace=True) # 'Papel' as index
# Prepare Data for Modeling
for col in df_mkt.columns:
df_mkt[col] = df_mkt[col].str.replace('.','')
df_mkt[col] = df_mkt[col].str.replace(',','.')
df_mkt[col] = df_mkt[col].str.replace('%','')
df_mkt[col] = df_mkt[col].astype(float)
totCompanies = df_mkt.shape[0]
Gui.AppendLog('Total companies: {}'.format(totCompanies))
if totCompanies > 3:
return df_mkt
else:
return -1
|
__author__ = 'Sebastian Bernasek'
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from functools import reduce
from operator import add
from .base import Base
from .settings import *
from .palettes import Palette
class JointDistribution(Base):
"""
Object for constructing joint distribution plots.
Attributes:
pre_color (tuple) - grey color for progenitors
Inherited attributes:
data (pd.DataFrame) - data
fig (matplotlib.figure.Figure)
"""
# set class path and name
path = 'graphics/jointdistribution'
def __init__(self, data):
"""
Initialize object for constructing joint distribution plots.
Args:
data (pd.DataFrame)
"""
super().__init__(data)
# get color for progenitors
greys = Palette({'grey': 'grey'})
self.pre_color = greys('grey', 'light', shade=5)
@classmethod
def from_experiment(cls, experiment, cell_types='pre'):
"""
Instantiate from Experiment instance with optional constraint on included cell types.
Args:
experiment (data.experiments.Experiment)
cell_types (list or str) - included cell types
Returns:
fig_obj (figures.base.Base derivative)
"""
# select measurement data
cells = reduce(add, experiment.discs.values())
data = cells.select_cell_type(cell_types).data
return cls(data)
def render(self,
cell_types=['pre'],
height=2.65):
"""
Create figure and plot joint distribution.
Args:
cell_types (list) - included cell types
height (float) - figure height argument
"""
# plot progenitor joint distribution
self.fig = self.plot(cell_types, height=height, color=self.pre_color)
def plot(self,
cell_types=['pre'],
color='grey',
height=2.65):
"""
Plot joint distribution for specific cell type using sns.jointplot
Args:
cell_types (list) - included cell types
color (str or RGB tuple) - color for markers
height (float) - figure height argument
Returns:
fig (matplotlib.figure.Figure)
"""
# select cells
cells = self.data[self.data.label.isin(cell_types)]
# define formatting arguments
joint_kws = {'edgecolor': 'white',
'linewidth': 0.25,
'facecolor': color,
's': 10}
hist_kws = dict(edgecolor='black',
facecolor=color,
linewidth=0,
alpha=0.75)
marginal_kws = {'bins': np.arange(0, 2., .05),
'norm_hist': True,
'hist_kws': hist_kws}
# create jointplot
fig = sns.jointplot('ch2_normalized', 'ch1_normalized',
data=cells,
height=height,
ratio=3,
#color=color,
stat_func=None,
joint_kws=joint_kws,
marginal_kws=marginal_kws,
xlim=(0, 2),
ylim=(0, 2))
# add diagonal with slope equivalent to median ratio
median_ratio = 2**(cells.logratio.median())
fig.ax_joint.plot([0, 1.5], [0, 1.5*median_ratio], '-',
linewidth=1, color='k', zorder=0)
#angle = np.arctan(median_ratio) * 180/np.pi
#g.ax_joint.text(1.75, 1.75*median_ratio, 'median ratio', rotation=angle, va='center', ha='center')
# format axes
fig.ax_joint.set_ylabel('Pnt (a.u.)')
fig.ax_joint.set_xlabel('Yan (a.u.)')
return fig
class DualJointDistribution(JointDistribution):
"""
Object for constructing joint distribution plots overlayed with second cell type.
Attributes:
reference (list) - reference cell types
reference_color (RGB tuple) - color for reference cell type
Inherited attributes:
data (pd.DataFrame) - data
fig (matplotlib.figure.Figure)
pre_color (RGB tuple) - color for progenitors
"""
def __init__(self, data, reference):
"""
Instantiate joint distribution figure with two cell types.
Args:
data (pd.DataFrame) - data containing Control/Perturbation labels
reference (list) - reference cell types
"""
super().__init__(data)
self.reference = reference
# get color for reference cell type
colorer = Palette()
self.reference_color = colorer(reference[0].lower())
@classmethod
def from_experiment(cls, experiment, reference, **kwargs):
"""
Instantiate from Experiment instance with cells limited to those concurrent with a reference population.
Args:
experiment (data.experiments.Experiment)
reference (list) - reference cell types
kwargs: keyword arguments for concurrent cell selection
Returns:
fig_obj (figures.base.Base derivative)
"""
# select cells concurrent with reference
data = experiment.select_by_concurrency(reference, **kwargs)
return cls(data, reference)
def add_reference_to_fig(self):
""" Add reference cell type to joint and marginal axes. """
# select reference cells
data = self.data[self.data.Population=='Differentiated']
# scatter neurons on joint axes
self.fig.x = data['ch2_normalized']
self.fig.y = data['ch1_normalized']
self.fig.plot_joint(plt.scatter,
c=self.reference_color,
linewidth=0.25,
s=10,
edgecolor='w')
# get marginal axes limits
axx, axy = self.fig.ax_marg_x, self.fig.ax_marg_y
xlim = axx.get_xlim()
ylim = axy.get_ylim()
# add reference cell distributions to marginal x axis
axx.hist(data['ch2_normalized'],
bins=np.arange(0, 2, 0.05),
color=self.reference_color,
alpha=0.75,
density=True,
linewidth=0)
axx.set_xlim(*xlim)
# add reference cell distributions to marginal y axis
axy.hist(data['ch1_normalized'],
orientation='horizontal',
bins=np.arange(0, 2, 0.05),
color=self.reference_color,
alpha=0.75,
density=True,
linewidth=0)
axy.set_ylim(*ylim)
def render(self,
height=2.65,
**kwargs):
"""
Create figure and plot progenitor joint distribution overlayed with reference cell type.
Args:
height (float) - figure height argument for sns.jointplot
"""
# plot progenitor joint distribution
self.fig = self.plot(height=height, color=self.pre_color)
# add reference cells
self.add_reference_to_fig()
# format axes
self.format_axes()
def format_axes(self):
""" Format all axes. """
# get axes
ax_joint = self.fig.ax_joint
axx, axy = self.fig.ax_marg_x, self.fig.ax_marg_y
# add data labels
label = 'Young ' + self.data['ReferenceType'].unique()[0]
ax_joint.text(0.1, 2, label, ha='left', va='top', color=self.reference_color, fontsize=7)
ax_joint.text(0.1, 2, '\nConcurrent multipotents', ha='left', va='top', color=self.pre_color, fontsize=7)
# format ticks
axx.tick_params(length=0)
axy.tick_params(length=0)
# set axes shift
axes_shift = 0
ax_joint.spines['bottom'].set_position(('outward', axes_shift))
ax_joint.spines['left'].set_position(('outward', axes_shift))
|
# -*- coding: utf-8 -*-
import ConfigParser
from gcloud import storage
from gcloud.storage import Blob
configfile = ConfigParser.SafeConfigParser()
configfile.read("./config/config.ini")
UPLOAD_BUCKET = configfile.get("gcs","upload_bucket")
PROJECT_ID = configfile.get("gcs","project_id")
UPLOAD_FILE = configfile.get("gcs","upload_file")
OUTPUT_FILE = configfile.get("gcs","output_file")
PIN = int(configfile.get("sensor","pin"))
INTERVAL = float(configfile.get("sensor","interval"))
SHUTTER_DISTANCE = int(configfile.get("sensor","shutter_distance"))
client = storage.Client(project=PROJECT_ID)
bucket = client.get_bucket(UPLOAD_BUCKET)
blob = Blob(OUTPUT_FILE, bucket)
with open(UPLOAD_FILE, 'rb') as my_file:
blob.upload_from_file(my_file)
|
#!/usr/bin/env python
from __future__ import print_function
import fastjet as fj
import fjcontrib
import fjext
import tqdm
import argparse
import os
import pythia8
import pythiaext
import pythiafjext
from heppy.pythiautils import configuration as pyconf
from pyjetty.mputils import mputils
import ROOT
ROOT.gROOT.SetBatch(1)
def main():
parser = argparse.ArgumentParser(description='pythia8 in python', prog=os.path.basename(__file__))
pyconf.add_standard_pythia_args(parser)
args = parser.parse_args()
mycfg = []
pythia = pyconf.create_and_init_pythia_from_args(args, mycfg)
max_eta_hadron=3
jet_R0 = 0.4
# jet_selector = fj.SelectorPtMin(100.0) & fj.SelectorPtMax(125.0) & fj.SelectorAbsEtaMax(max_eta_hadron - 1.05 * jet_R0)
jet_selector = fj.SelectorPtMin(10.0) & fj.SelectorAbsEtaMax(max_eta_hadron - 1.05 * jet_R0)
parts_selector_h = fj.SelectorAbsEtaMax(max_eta_hadron)
fj.ClusterSequence.print_banner()
jet_def = fj.JetDefinition(fj.antikt_algorithm, jet_R0)
qweights = [1./iw/10. for iw in reversed(range(1, 3)) ]
qweights.insert(0, 0)
rout = ROOT.TFile('gen_quench_out.root', 'recreate')
hpt = []
for i, w in enumerate(qweights):
hname = 'hpt_{}'.format(i)
htitle = 'hpt w={}'.format(w)
h = ROOT.TH1F(hname, htitle, 10, mputils.logbins(10, 1000, 10))
hpt.append(h)
pbar = tqdm.tqdm(range(args.nev))
for i in pbar:
if not pythia.next():
pbar.update(-1)
continue
parts_pythia_h = pythiafjext.vectorize_select(pythia, [pythiafjext.kFinal], 0, False)
parts_pythia_h_selected = parts_selector_h(parts_pythia_h)
jets_h = fj.sorted_by_pt(jet_selector(jet_def(parts_pythia_h_selected)))
if len(jets_h) < 1:
continue
# do your things with jets here...
for j in jets_h:
for i, w in enumerate(qweights):
if w > 0:
_j = j * w
else:
_j = j
jpt = 0
print(j.perp(), _j.perp(), w)
for p in j.constituents():
if w > 0:
bp = p.unboost(_j)
else:
bp = p
print(' -', w, p.perp(), bp.perp())
jpt = jpt + bp.perp()
hpt[i].Fill(jpt)
rout.cd()
rout.Write()
rout.Close()
pythia.stat()
pythia.settings.writeFile(args.py_cmnd_out)
if __name__ == '__main__':
main()
|
"""
Image Data Analysis Using Numpy & OpenCV
email: deeptimalhotra27@gmail.com
author: Deepti Malhotra
"""
import numpy as np
import parseArgs
import cv2
import GrayImageProcessing as gip
import sys
# start processing
if __name__ == '__main__':
# load the image
args = parseArgs.parseInputArgs()
# extract height & width of input image
dim = args["shape"]
height, width = dim.split(',')
obj = gip.count_area ()
A_out = obj.count_areas ( args["file"] , int(height), int(width))
|
from edges import getSubsetWithEdgeAnalysis
from featureDetection import runFeature
import numpy as np
import glob
from matplotlib import pyplot as plt
import cv2 as cv
i = 5
imDir = "../artSamples/"
imnames = glob.glob(imDir + '*.jpg')
imnames = sorted(imnames)
# descriptors = np.empty((1,159))
# keypoints = np.empty((1,159))
descriptors = []
keypoints = []
matchList = []
sift = cv.xfeatures2d.SIFT_create()
for f in range(len(imnames)):
img = cv.imread(imnames[f])
kp, des = sift.detectAndCompute(img,None)
descriptors.append(des)
keypoints.append(kp)
inputImage = ''
t = 0
house = cv.imread('../queryImages/house-of-parliment-NotIdentical.jpg',0)
mona = cv.imread('../queryImages/mona-lisa.jpg',0)
wall = cv.imread('../queryImages/wall-clocks.jpg',0)
scream = cv.imread('../queryImages/the-scream.jpg',0)
starry = cv.imread('../queryImages/starry-night.jpg',0)
picasso = cv.imread('../queryImages/old-artist-chicago-picasso.jpg',0)
allColorScores = np.load('../color/results.npy')
if i == 0:
img1 = house
inputImage = 'house-of-parliment-NotIdentical'
t = 0.30
elif i == 1:
img1 = mona
inputImage = 'mona-lisa'
t = 2.00
elif i == 2:
img1 = scream
inputImage = 'the-scream'
t= 0.20
elif i == 3:
img1 = starry
inputImage = 'starry-night'
t = 0.03
elif i == 4:
img1 = picasso
inputImage = 'old-artist-chicago-picasso'
t = 0.50
elif i == 5:
img1 = wall
inputImage = 'wall-clocks'
t = 0.40
scores = np.zeros((1,159))
subsetIndxs = getSubsetWithEdgeAnalysis(inputImage,t)
featureScores = runFeature(img1, subsetIndxs, keypoints, descriptors)
colorScores = allColorScores[i]
scores[:,np.argmax(featureScores)] += .9
scores[:,np.argmax(colorScores)] += .1
resultIm = imnames[np.argmax(scores)]
name = imnames[np.argmax(scores)][14:-4]
artist = ""
date = ""
style = ""
if name == "houses-of-parliament":
name = "Houses of Parliament"
artist = "Claude Monet"
date = "1904"
style = "Impressionism"
elif name == "mona-lisa":
name = "Mona Lisa"
artist = "Leonardo da Vinci"
date = "1504"
style = "High Renaissance"
elif name == "the-scream-1893":
name = "The Scream"
artist = "Edvard Munch"
date = "1893"
style = "Expressionism"
elif name == "the-starry-night":
name = "The Starry Night"
artist = "Vincent van Gogh"
date = "1889"
style = "Post-Impressionism"
elif name == "old-guitarist-chicago":
name = "The Old Blind Guitarist"
artist = "Pablo Picasso"
date = "1903"
style = "Expressionism"
elif name == "the-persistence-of-memory-1931":
name = "The Persisence of Memory"
artist = "Salvador Dali"
date = "1931"
style = "Surrealism"
name = ("Name: " + name + " ")
artist = ("Artist: " + artist + " ")
date = ("Date: " + date + " ")
style = ("Style: " + style + " ")
im = cv.imread(resultIm)
cv.namedWindow(name + artist + date + style, flags = 0)
cv.imshow(name + artist + date + style, im)
wait = raw_input("Hit any buttong to continue")
|
# 1. How instance methods work?
class Test:
"""Testing how descriptors work."""
def __init__(self, attr=None):
self.attr = attr
def ret(self):
return self
# What's wrong here?
def show(msg):
print(msg)
# Depending on how we call the show method
# we pass it the instance or not
# The line below works
Test.show('Wrong definition works ok on class?')
# but this one is not
# since it implicitly passes self
try:
Test().show('And on instance?')
except TypeError:
print('But not on the instance.')
# Due to descriptor the signature of
# the method changes dynamically
instance = Test()
assert Test.ret.__get__(instance, Test) == instance.ret
assert Test.ret.__get__(instance, Test)() == instance
# Descriptors work onluy on the class level?
# Since these gives the same results
returned = Test.ret.__get__(instance, Test)()
assert returned == instance
# But this do not
assert not Test().ret.__get__(instance, Test)() == instance
# Altough this works fine :P
type(Test()).ret.__get__(instance, Test)() == instance
print()
# 2. Staticmethod implementation in Python
class StaticMethod:
"Emulate PyStaticMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
self.f = f
def __get__(self, obj, objtype=None):
return self.f
class StaticMethodTest:
@StaticMethod
def test(arg):
return arg
assert StaticMethodTest.test(1) == StaticMethodTest().test(1)
# What if we try to use it on regular function?
@StaticMethod
def regular_func(arg):
print(arg)
try:
regular_func(1)
except TypeError:
print('Actually it doesn\'t work. Functions don\'t use descriptors.')
print()
# 3. Classmethod implementation in Python
class ClassMethod:
"Emulate PyClassMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
self.f = f
def __get__(self, obj, objtype=None):
if objtype is None:
objtype = type(object)
def func(*args):
return self.f(objtype, *args)
return func
class ClassMethodTest:
@ClassMethod
def test(cls, arg):
return arg
assert ClassMethodTest.test(1) == ClassMethodTest().test(1)
print()
# 4. Just for fun, implmentation of InstanceMethod
# This way it would be less ambigous
# than the current implementation
class InstanceMethod:
"Emulate PyClassMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
self.f = f
def __get__(self, obj, objtype=None):
def func(*args):
if obj is None:
msg = f'{self.f.__name__}() has to be invoked from an instance'
raise TypeError(msg)
return self.f(obj, *args)
return func
class InstanceMethodTest:
@InstanceMethod
def test(self, arg):
self.arg = arg
return arg
try:
InstanceMethodTest.test()
except TypeError:
print('Can\'t invoke instance method from class')
print()
# 5. How about properties?
# Can You control setting property value?
class NonNullProperty:
def __init__(self, initval=0):
self.val = initval
def __set__(self, obj, value):
if not value:
raise AttributeError('You shall not pass!')
self.val = value
class NonNullPropertyTest:
x = NonNullProperty()
# On instance
try:
# This should not work
NonNullPropertyTest().x = None
except AttributeError:
print('Cannot set NonNullProperty to None on instance!')
else:
print('I did set NonNullProperty to None on instance!')
# And on class
try:
# But this works just fine
NonNullPropertyTest.x = None
except AttributeError:
print('Cannot set NonNullProperty to None on class!')
else:
print('I did set NonNullProperty to None on class! It is no longer NonNullProperty either...')
NonNullPropertyTest().x = None
print('And now it\'s no problem to set it to None...')
# How can You control getting property value
class InvisibleProperty:
def __init__(self, initval=0):
self.val = initval
def __get__(self, obj, objtype=None):
raise AttributeError('Can\'t see me!')
def __set__(self, obj, value):
self.val = value
class InvisiblePropertyTest:
x = InvisibleProperty()
# On instance
try:
# This should not work
print(InvisiblePropertyTest().x)
except AttributeError:
print('I really can\'t see the InvisibleProperty!')
# On class
try:
# Neither do this
print(InvisiblePropertyTest.x)
except AttributeError:
print('Even from the class!')
# What happens if we cahnge class atrribute
# On the instance level?
class ClassAttr:
x = 1
i1 = ClassAttr()
i2 = ClassAttr()
assert i1.x == i2.x
i1.x = 2
# It changes the value
assert i1.x == 2
# But only for a given instance
assert i2.x == 1
# What happens with read only property?
class ClassProperty:
@property
def x(self):
return 1
i1 = ClassProperty()
i2 = ClassProperty()
# This indeed raises and error
try:
i1.x = 10
except AttributeError:
print('Read only attributes work on instance level!')
try:
ClassProperty.x = 2
print('But You can do what You want on class level!')
except AttributeError:
pass
# To sum up:
# - descriptors work for methods on both class and instance level
# but if You invoke them on class level
# - but on attributes not so much
# when set from class level they are overriden like any other value
# no magic here, but getting works as expected
|
import requests
from bs4 import BeautifulSoup
import urllib
from telegram import ReplyKeyboardMarkup as rkm
from activity import Activity
from config import APPID
class Wolfram(Activity):
def __init__(self):
self.API = "http://api.wolframalpha.com/v2/query?input={}&appid={}"
self.exit = rkm([['Exit']])
def first_query(self, bot, update):
bot.sendMessage(
chat_id=update.message.chat.id,
text="Ask your question",
reply_markup=None
)
def process(self, query, bot, update):
bot.sendChatAction(
chat_id=update.message.chat.id,
action='typing'
)
self.ask(query, bot, update)
def ask(self, query, bot, update):
resp = requests.get(self.API.format(urllib.parse.quote_plus(query), APPID))
if resp.status_code != 200:
return None
dom = BeautifulSoup(resp.text, "lxml")
result = dom.queryresult.findAll("pod", id="Solution")
if not result:
result = dom.queryresult.findAll("pod", id="Result")
if not result:
result = dom.queryresult.findAll("pod", id="ChemicalNamesFormulas:ChemicalData")
subpods = result[0].findAll("subpod")
for pod in subpods:
bot.sendMessage(
chat_id=update.message.chat.id,
text=pod.plaintext.string
)
bot.sendMessage(
chat_id=update.message.chat.id,
text='You can enter and ask something else or exit',
reply_markup=self.exit
)
|
import csv
import numpy as np
import math
import random, sys
class makebins:
def __init__(self):
self.data=None
csvfile1=open('crimesbyday2015.csv', 'w',newline='')
self.csvfile=csv.writer(csvfile1,delimiter=',')
def drawProgressBar(self,percent, barLen = 50): #just a progress bar so that you dont lose patience
sys.stdout.write("\r")
progress = ""
for i in range(barLen):
if i<int(barLen * percent):
progress += "="
else:
progress += " "
sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
sys.stdout.flush()
def extract_crime_years(self,countx):
with open("../prediction/allfiles/original_data_files/Chicago_Crimes_2012_to_2017.csv","r") as f:
reader = csv.reader(f) #reading using CSV reader coz numpy doesn't read text
headerrow=next(reader)
self.csvfile.writerow(headerrow)
for j in range(countx):
row=next(reader)
date_time=row[3]
#print("date_time:",date_time)
date_time1=date_time.split()
date=date_time1[0]
threeparts=date.split('/')
year=int(threeparts[2])
#print("date_time:",date_time," / year:",year)
if year==2016:
self.csvfile.writerow(row)
self.drawProgressBar(j/countx) #242480)
def extract_days(self,countx):
infile=open('listofcrimes.txt','r')
intext=infile.read()
crimes=intext.split(',')
positions={}
for j in range(len(crimes)): #position of the crime
positions[crimes[j]]=j
countofcrimes={}
for j in range(len(crimes)): #initializing the numbers of each crime
countofcrimes[crimes[j]]=0
with open("crime_2015.csv","r") as f:
reader = csv.reader(f) #reading using CSV reader coz numpy doesn't read text
headerrow=next(reader)
self.csvfile.writerow(crimes)
prev=None
listofcrimes=[]
day=1
for j in range(countx):
row=next(reader)
crime=row[6]
date_time=row[3]
#print("date_time",date_time)
date_time1=date_time.split()
date=date_time1[0]
time=date_time1[1]
timespl=time.split(':')
hour=int(timespl[0])
#print(j,"crime=",crime)
if date==prev:
countofcrimes[crime]+=1
#print(countofcrimes)
else:
#listofcrimes.insert(0,day)
#print(countofcrimes)
vectorx=[]
for j in range(len(crimes)):
crimex=crimes[j]
#print(crimex,countofcrimes[crimex])
vectorx.append(countofcrimes[crimex])
countofcrimes[crimex]=0
self.csvfile.writerow(vectorx)
#for j in range(len(crimes)): #initializing the numbers of each crime
# countofcrimes[crimes[j]]=0
day+=1
prev=date
'''
timeampm=date_time[2]
if hour!=12:
if timeampm=='PM':
hour+=12
else:
if timeampm=='AM':
hour=0
else:
hour=12
threeparts=date.split('/')
year=int(threeparts[2])
if hour>=0 and hour<6:
timeofday='Night'
elif hour>=6 and hour<12:
timeofday='Morning'
elif hour>=12 and hour<18:
timeofday='Afternoon'
elif hour>=18 and hour<24:
timeofday='Evening'
if date==prev:
if crime not in listofcrimes:
listofcrimes.append(crime)
else:
self.csvfile.writerow(listofcrimes)
'''
self.drawProgressBar(j/countx) #242480)
def get_all_crimes(self,countx):
ofile=open('listofcrimes.txt','w')
with open("crime_2015.csv","r") as f:
reader = csv.reader(f) #reading using CSV reader coz numpy doesn't read text
headerrow=next(reader)
listofcrimes=[]
for j in range(countx):
row=next(reader)
crime=row[6]
if crime not in listofcrimes:
listofcrimes.append(crime)
for el in range(len(listofcrimes)):
ofile.write(listofcrimes[el]+',')
ux=makebins()
#ux.extract_crime_years(1456714)
#ux.get_all_crimes(262995)
ux.extract_days(262995)
|
from tkinter import *
root = Tk()
root.title("Hello")
root.geometry("276x116")
text = Label(root, text="請輸入暱稱:",
width="30", height="2")
text.place(x=0, y=0)
name = Entry(root, width="30")
name.place(x=0, y=36)
button = Button(root, text="執行")
button.place(x=0, y=66)
result = Label(root, text="",
width="30", height="2")
result.place(x=0, y=86)
root.mainloop()
# 檔名: hello_demo2.py
# 作者: Kaiching Chang
# 時間: June, 2018
|
"""
Name: HumbleForwarder
Author: kjp
Humble SES email forwarder. Simple address mapping is supported. Feel free to
fork it if you want more configurability.
Massively reworked and cleaned up version of
https://aws.amazon.com/blogs/messaging-and-targeting/forward-incoming-email-to-an-external-destination/
Setup instructions:
* Follow the AWS blog link above, but use this Lambda code (Python 3.8+) instead.
* Make sure your Lambda has a large enough size and timeout, I recommend
768MB and 60 seconds to be safe. Python is pretty slow and bloated.
* Consider granting the Lambda `SNS:Publish` permission, and enable its Dead Letter Queue
so you get notified via SNS if any Lambda fails after 3 async attempts.
* Read the configuration options below. If you want address mapping, you need
to go to Lambda console and do File->New->Paste Contents->Save As "config.json"
Features:
* Don't forward emails marked as spam / virus. Note you need to have scanning enabled.
* The body/content is not modified, all attachments are kept
* Send an error email if there was a problem sending (like body too large).
You can test this by setting the env var TEST_LARGE_BODY, to generate a 20MB body.
A 768MB Lambda takes 15 seconds for this test.
* JSON logging. You can run this cloudwatch logs insights query to check on your emails:
fields @timestamp, input_event.Records.0.ses.mail.commonHeaders.from.0,
input_event.Records.0.ses.mail.commonHeaders.subject
| filter input_event.Records.0.eventSource = 'aws:ses'
| sort @timestamp desc
Other Thanks:
* Got some inspiration from https://github.com/chrismarcellino/lambda-ses-email-forwarder/
"""
import unittest
import traceback
import json
import os
import logging
import email.policy
import email.parser
import email.message
import boto3
from botocore.exceptions import ClientError
###############################################################################
#
# Required configuration. Can set here, or in environment var(s), your choice
#
###############################################################################
REGION = os.getenv('Region', 'us-east-1')
INCOMING_EMAIL_BUCKET = os.getenv('MailS3Bucket', 'yourbucketname')
# Don't have a leading or trailing /, it will be added automatically
INCOMING_EMAIL_PREFIX = os.getenv('MailS3Prefix', '')
# If empty, uses the SES recipient address
SENDER = os.getenv('MailSender', '')
# The default recipient if no mappings exist
DEFAULT_RECIPIENT = os.getenv('MailRecipient', 'to@anywhere.com')
# Extra configuration file, such as where to forward the emails, based on the SES
# user and domain. See the example config.json in this directory.
# This file is currently optional, but may be the sole config source in the future.
CONFIG_FILE = os.path.join(os.environ.get('LAMBDA_TASK_ROOT', ''), "config.json")
###############################################################################
###############################################################################
X_ENVELOPE_TO = "X-Envelope-To"
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info(json.dumps(dict(input_event=event)))
# Get the unique ID of the message. This corresponds to the name of the file in S3.
message_id = event['Records'][0]['ses']['mail']['messageId']
logger.debug(json.dumps(dict(message_id=message_id)))
# Check for spam / virus
if is_ses_spam(event):
logger.error(json.dumps(dict(message="rejecting spam message", message_id=message_id)))
return
# These are the valid recipient(s) for your domain.
# Any other bogus addresses in the To: header should not be present here.
ses_recipients = get_ses_recipients(event)
# This loop is inefficient, but optimizing an email to multiple users is
# not something that's a priority for me.
for ses_recipient in ses_recipients:
forward_mail(ses_recipient, message_id)
def forward_mail(ses_recipient, message_id):
# Retrieve the original message from the S3 bucket.
message = get_message_from_s3(message_id)
config = get_runtime_config_dict()
new_headers = get_new_message_headers(config, ses_recipient, message)
# Change all the headers now. Boom, that was easy!
set_new_message_headers(message, new_headers)
if os.getenv("TEST_DEBUG_BODY"):
logger.info(json.dumps(dict(email_body=message.as_string())))
if os.getenv("TEST_LARGE_BODY"):
logger.info("setting a huge body, should cause an error")
message.clear_content()
message.set_content("x" * 20000000)
# Send the message
try:
send_raw_email(message, envelope_destination=new_headers[X_ENVELOPE_TO])
except ClientError as e:
logger.error("error sending forwarded email", exc_info=True)
traceback_string = traceback.format_exc()
error_message = create_error_email(message, traceback_string)
send_raw_email(error_message, envelope_destination=error_message["To"])
def get_message_from_s3(message_id):
# NB: This is dumb, but I'm doing it to stay compatible with the original AWS version
if INCOMING_EMAIL_PREFIX:
object_path = (INCOMING_EMAIL_PREFIX + "/" + message_id)
else:
object_path = message_id
# Create a new S3 client.
client_s3 = boto3.client("s3")
# Get the email object from the S3 bucket.
object_s3 = client_s3.get_object(Bucket=INCOMING_EMAIL_BUCKET, Key=object_path)
raw_bytes = object_s3['Body'].read()
return parse_message_from_bytes(raw_bytes)
def parse_message_from_bytes(raw_bytes):
parser = email.parser.BytesParser(policy=email.policy.SMTP)
return parser.parsebytes(raw_bytes)
def get_new_message_headers(config, ses_recipient, message):
"""
Return the complete set of new headers. This single function is where all the
forwarding logic / magic happens.
NB: This function shouldn't use any global vars, because we want it unit testable.
Unit tests can pass in their own `config` dict.
"""
new_headers = {}
# Headers we keep unchanged
headers_to_keep = [
"Date",
"Subject",
"To",
"CC",
"MIME-Version",
"Content-Type",
"Content-Disposition",
"Content-Transfer-Encoding",
]
for header in headers_to_keep:
if header in message:
new_headers[header] = message[header]
# Lookup in recipient_map, if not found, fall back to default_recipient
new_headers[X_ENVELOPE_TO] = config["recipient_map"].get(ses_recipient,
config["default_recipient"])
# From must be a verified address
if config["sender"]:
new_headers["From"] = config["sender"]
else:
new_headers["From"] = ses_recipient
if message["Reply-To"]:
new_headers["Reply-To"] = message["Reply-To"]
else:
new_headers["Reply-To"] = message["From"]
logger.info(json.dumps(dict(new_headers=new_headers), default=str))
return new_headers
def set_new_message_headers(message, new_headers):
# Clear all headers
for header in message.keys():
del message[header]
for (name, value) in new_headers.items():
if name == X_ENVELOPE_TO:
# This is only used internally
pass
else:
message[name] = value
def create_error_email(attempted_message, traceback_string):
# Create a new message
new_message = email.message.EmailMessage(policy=email.policy.SMTP)
new_message["From"] = attempted_message["From"]
new_message["To"] = attempted_message["To"]
new_message["Subject"] = "Email forwarding error"
text = f"""
There was an error forwarding an email to SES.
Original Sender: {attempted_message["Reply-To"]}
Original Subject: {attempted_message["Subject"]}
Traceback:
{traceback_string}
""".strip()
new_message.set_content(text)
return new_message
def get_runtime_config_dict():
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, "rb") as f:
config = json.load(f)
else:
logger.warn(f"config file does not exist: {CONFIG_FILE}")
config = {}
config.update(recipient_map={})
config.update(sender=SENDER)
config.update(default_recipient=DEFAULT_RECIPIENT)
return config
def get_ses_recipients(event):
receipt = event['Records'][0]['ses']['receipt']
return receipt["recipients"]
def is_ses_spam(event):
receipt = event['Records'][0]['ses']['receipt']
verdicts = ['spamVerdict', 'virusVerdict', 'spfVerdict', 'dkimVerdict', 'dmarcVerdict']
is_fail = False
for verdict in verdicts:
if verdict in receipt:
status = receipt[verdict].get("status")
logger.debug(json.dumps(dict(verdict=verdict, status=status)))
if status == "FAIL":
is_fail = True
return is_fail
def send_raw_email(message, *, envelope_destination):
client_ses = boto3.client('ses', REGION)
response = client_ses.send_raw_email(
Source=message['From'],
Destinations=[envelope_destination],
RawMessage={
'Data': message.as_string()
}
)
print("Email sent! MessageId:", response['MessageId'])
class UnitTests(unittest.TestCase):
def test_multiple_recipients(self):
text = self._read_test_file("tests/multiple_recipients.txt")
message = parse_message_from_bytes(text)
# This is why we shouldn't trust the original To header,
# it can have all kind of junk
self.assertEqual(len(message["To"].addresses), 3)
def test_header_changes(self):
text = self._read_test_file("tests/multiple_recipients.txt")
message = parse_message_from_bytes(text)
ses_recipient = "code@coder.dev"
config = dict(sender="", default_recipient="someone@secret.com", recipient_map={})
new_headers = get_new_message_headers(config, ses_recipient, message)
self.assertEqual(new_headers[X_ENVELOPE_TO], "someone@secret.com")
self.assertEqual(new_headers["From"], "code@coder.dev")
self.assertEqual(new_headers["To"], "hacker@hacker.com, code@coder.dev, code2@coder.dev")
self.assertEqual(new_headers["Subject"], "test 3 addresses")
self.assertEqual(new_headers["Reply-To"], "Alpha Sigma <user@users.com>")
self.assertEqual("Content-Disposition" in new_headers, False)
config = dict(sender="fixed@coder.dev", default_recipient="someone@secret.com", recipient_map={})
new_headers = get_new_message_headers(config, ses_recipient, message)
self.assertEqual(new_headers[X_ENVELOPE_TO], "someone@secret.com")
self.assertEqual(new_headers["From"], "fixed@coder.dev")
def test_header_changes2(self):
text = self._read_test_file("tests/reply_to.txt")
message = parse_message_from_bytes(text)
ses_recipient = "code@coder.dev"
config = dict(sender="", default_recipient="someone@secret.com", recipient_map={})
new_headers = get_new_message_headers(config, ses_recipient, message)
self.assertEqual(new_headers["Subject"], "test reply-to")
self.assertEqual(new_headers["Reply-To"], "My Alias <alias@alias.com>")
set_new_message_headers(message, new_headers)
# We don't actually expose X_ENVELOPE_TO, it's just used internally to pass data
self.assertEqual(message[X_ENVELOPE_TO], None)
self.assertEqual(message["From"], "code@coder.dev")
self.assertEqual(message["Subject"], "test reply-to")
self.assertEqual(message["Reply-To"], "My Alias <alias@alias.com>")
def test_event_parsing(self):
text = self._read_test_file("tests/event.json")
event = json.loads(text)
self.assertEqual(is_ses_spam(event), True)
self.assertEqual(get_ses_recipients(event), ['code@coder.dev', 'code2@coder.dev'])
def test_dynamic_mapping(self):
text = self._read_test_file("tests/multiple_recipients.txt")
message = parse_message_from_bytes(text)
config = dict(sender="", default_recipient="default@fallback.com")
recipient_map = {
"hacker@hacker.com": "nowhere+label@nowhere.com",
"code@coder.dev": "A Name <foo+bar@domain.com>",
}
config.update(recipient_map=recipient_map)
new_headers = get_new_message_headers(config, "hacker@hacker.com", message)
self.assertEqual(new_headers[X_ENVELOPE_TO], "nowhere+label@nowhere.com")
new_headers = get_new_message_headers(config, "code@coder.dev", message)
self.assertEqual(new_headers[X_ENVELOPE_TO], "A Name <foo+bar@domain.com>")
new_headers = get_new_message_headers(config, "code123@coder.dev", message)
self.assertEqual(new_headers[X_ENVELOPE_TO], "default@fallback.com")
def _read_test_file(self, file_name):
with open(file_name, "rb") as f:
return f.read()
if __name__ == '__main__':
print(get_runtime_config_dict())
unittest.main()
|
#!/usr/bin/python3
A={"Age":33 , "Name":"John"}
print (A['Age'])
print (A['Name'])
|
from bs4 import BeautifulSoup
import urllib3
url = 'your url'
http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data)
# soup = BeautifulSoup(, 'html.parser')
print(soup.prettify())
|
s=[0,1,2,3,4,5,6,7,8,9]
print(s[0:5:1])
print(s[1:-2])
print(s[5:])
print(s[:-1])
print(s[:])
print(s[2:-1:2])
print(s[2:-1:-1])
print(s[-1:2:-1])
print(s[::-1])
a='manikanta'
print(a[::-1])
print(a[0:4:1])
|
import TreeNode
def sumNumbers(root):
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 8 11:05:11 2019
@author: nadolsw
Created based on the following tutorial: http://ataspinar.com/2018/04/04/machine-learning-with-signal-processing-techniques/
"""
#%% IMPORT NECESSARY PACKAGES
#pip install siml
#pip install pandas
#pip install seaborn
import numpy as np
import matplotlib.pyplot as plt
from siml import *
from collections import defaultdict, Counter
from mpl_toolkits.mplot3d import Axes3D
from siml.sk_utils import *
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from scipy.signal import welch
from scipy.fftpack import fft
from scipy import signal
from scipy.fftpack import fft
#DEFINE UTILITY FUNCTIONS
def get_fft_values(y_values, nsamples, samp_freq):
f_values = np.linspace(0.0, samp_freq/2, nsamples//2)
fft_values_ = fft(y_values)
fft_values = 2.0/nsamples * np.abs(fft_values_[0:nsamples//2])
return f_values, fft_values
def get_psd_values(y_values, nsamples, samp_freq):
f_values, psd_values = welch(y_values, fs=samp_freq)
return f_values, psd_values
def autocorr(x):
result = np.correlate(x, x, mode='full')
return result[len(result)//2:]
def get_autocorr_values(y_values, samp_period, nsamples, samp_freq):
autocorr_values = autocorr(y_values)
x_values = np.array([samp_period * jj for jj in range(0, nsamples+1)])
return x_values, autocorr_values
#%% BASIC DEMONSTRATION OF FAST FOURIER TRANSFORM IN PYTHON
#Specify signal parameters
samp_duration = 10 #Total length of each signal (in seconds)
nsamples = 1000 #Total number of samples per signal
samp_period = samp_duration/nsamples #Uniform time increment between samples (sampling period in seconds)
samp_freq = 1/samp_period #Sampling frequency (number of samples per second)
x_value = np.linspace(0,samp_duration,nsamples+1)
amplitudes = [4, 6, 8, 10, 14]
frequencies = [6.5, 5, 3, 1.5, 1]
#Explicitly create input signals used to construct composite signal
y0 = [amplitudes[0]*np.sin(2*np.pi*frequencies[0]*x_value)]
y1 = [amplitudes[1]*np.sin(2*np.pi*frequencies[1]*x_value)]
y2 = [amplitudes[2]*np.sin(2*np.pi*frequencies[2]*x_value)]
y3 = [amplitudes[3]*np.sin(2*np.pi*frequencies[3]*x_value)]
y4 = [amplitudes[4]*np.sin(2*np.pi*frequencies[4]*x_value)]
y0_array = np.transpose(np.asarray(y0))
y1_array = np.transpose(np.asarray(y1))
y2_array = np.transpose(np.asarray(y2))
y3_array = np.transpose(np.asarray(y3))
y4_array = np.transpose(np.asarray(y4))
#Plot each simulated signal
def plot_fig(y,n,a,f,c):
plt.figure(figsize=(12,4))
plt.plot(x_value, y, linestyle='-', color=c)
plt.title('Signal {}'.format(n) + ': Amplitude={}'.format(a) + ' Frequency={}'.format(f), fontsize=14)
plt.xlabel('Time [Seconds]', fontsize=10)
plt.ylabel('Signal Value', fontsize=10)
plt.show()
plot_fig(y0_array,0,4,6.5,'blue')
plot_fig(y1_array,1,6,5,'red')
plot_fig(y2_array,2,8,3,'green')
plot_fig(y3_array,3,10,1.5,'orange')
plot_fig(y4_array,4,14,1,'purple')
#SIMULATE A COMPOSITE SIGNAL COMPOSED OF MULTIPLE SINE WAVES
y_values = [amplitudes[ii]*np.sin(2*np.pi*frequencies[ii]*x_value) for ii in range(0,len(amplitudes))]
composite_signal = np.sum(y_values, axis=0)
composite_array = np.transpose(np.asarray(composite_signal))
composite_matrix = np.column_stack((x_value, composite_array))
df_composite = pd.DataFrame({'Time':composite_matrix[:,0],'Signal Value':composite_matrix[:,1]})
plt.figure(figsize=(12,4))
plt.plot(x_value, composite_signal, linestyle='-', color='black')
plt.title("Composite Signal", fontsize=12)
plt.xlabel('Signal Value', fontsize=12)
plt.ylabel('Time [Seconds]', fontsize=12)
plt.show()
#PLOT FFT OUTPUT
f_values, fft_values = get_fft_values(composite_signal, nsamples, samp_freq)
FFT_matrix = np.column_stack((f_values, fft_values))
df_FFT = pd.DataFrame({'Frequency':FFT_matrix[:,0],'Amplitude':FFT_matrix[:,1]})
plt.figure(figsize=(12,4))
plt.plot(f_values, fft_values, linestyle='-', color='black')
plt.title("FFT: Frequency domain of the composite signal", fontsize=12)
plt.xlabel('Frequency [Hz]', fontsize=12)
plt.ylabel('Amplitude', fontsize=12)
plt.xticks(frequencies)
plt.xlim([0,8])
plt.show()
#EXTRACT AND PLOT POWER SPECTRAL DENSITY VALUES
f_values, psd_values = get_psd_values(composite_signal, nsamples, samp_freq)
PSD_matrix = np.column_stack((f_values, psd_values))
df_PSD = pd.DataFrame({'Frequency':PSD_matrix[:,0],'Amplitude':PSD_matrix[:,1]})
plt.figure(figsize=(12,4))
plt.plot(f_values, psd_values, linestyle='-', color='black')
plt.title("FFT: Power Spectral Density of the composite signal", fontsize=12)
plt.xlabel('Frequency [Hz]')
plt.ylabel('PSD [V**2 / Hz]')
plt.xticks(frequencies)
plt.xlim([0,8])
plt.show()
#COMPUTE AUTOCORRELATION VALUES OF SIGNAL
t_values, autocorr_values = get_autocorr_values(composite_signal, samp_period, nsamples, samp_freq)
autocorr_matrix = np.column_stack((t_values, autocorr_values))
df_autocorr = pd.DataFrame({'Time':autocorr_matrix[:,0],'Amplitude':autocorr_matrix[:,1]})
plt.figure(figsize=(12,4))
plt.plot(t_values, autocorr_values, linestyle='-', color='black')
plt.title("Autocorrelation of the composite signal", fontsize=12)
plt.xlabel('Time Delay [Seconds]')
plt.ylabel('Autocorrelation Amplitude')
plt.show()
|
import tensorflow as tf
import network as nw
def MCNN(im_data, bn=False):
with tf.variable_scope('MCNN'):
x1 = nw.conv2d(im_data, 16, kernel_size=9, padding='same', bn=bn)
x1 = tf.layers.max_pooling2d(x1, 2, 2)
x1 = nw.conv2d(x1, 32, kernel_size=7, padding='same', bn=bn)
x1 = tf.layers.max_pooling2d(x1, 2, 2)
x1 = nw.conv2d(x1, 16, kernel_size=7, padding='same', bn=bn)
x1 = nw.conv2d(x1, 8, kernel_size=7, padding='same', bn=bn)
x2 = nw.conv2d(im_data, 20, kernel_size=7, padding='same', bn=bn)
x2 = tf.layers.max_pooling2d(x2, 2, 2)
x2 = nw.conv2d(x2, 40, kernel_size=5, padding='same', bn=bn)
x2 = tf.layers.max_pooling2d(x2, 2, 2)
x2 = nw.conv2d(x2, 20, kernel_size=5, padding='same', bn=bn)
x2 = nw.conv2d(x2, 10, kernel_size=5, padding='same', bn=bn)
x3 = nw.conv2d(im_data, 24, kernel_size=5, padding='same', bn=bn)
x3 = tf.layers.max_pooling2d(x3, 2, 2)
x3 = nw.conv2d(x3, 48, kernel_size=3, padding='same', bn=bn)
x3 = tf.layers.max_pooling2d(x3, 2, 2)
x3 = nw.conv2d(x3, 24, kernel_size=3, padding='same', bn=bn)
x3 = nw.conv2d(x3, 12, kernel_size=3, padding='same', bn=bn)
_ = tf.concat([x1, x2, x3], axis=-1)
_ = nw.conv2d(_, 1, kernel_size=1, padding='same', bn=bn)
return _
|
""" Transform pixel point to object point """
import cv2
import numpy as np
import argparse
import imutils
ap = argparse.ArgumentParser()
ap.add_argument("--device","-d",type=int,default=0)
args = vars(ap.parse_args())
d = args.get("device")
cam = cv2.VideoCapture(d)
cam.set(3,1920)
cam.set(4,1080)
def mouse_callback(event,x,y,flags,param):
if event == 1:
click = param["click"]
if click < 0:
if all(param[i]["point"] for i in range(4)):
src = np.array([[(x,y)]],
dtype="float32")
dst = cv2.perspectiveTransform(src=src,
m=param["mat"])
pts = tuple([x,y] + list(dst[0][0]))
print "Transform: (%d,%d) --> (%f,%f)" % pts
else:
print "Need to calibrate points."
else:
param[click]["point"] = (x,y)
param["click"] = click + 1
if param["click"] == 4:
param["click"] = -1
src = np.array([param[i]["point"] for i in range(4)],
dtype="float32")
param["mat"] = cv2.getPerspectiveTransform(src=src,
dst=param["dst"])
clickToCoords = [(0,0),(0,1),(1,0),(1,1)]
data = {"click": -1,
"point": None,
"dst": np.array(clickToCoords,dtype="float32"),
-1: None}
for i in range(4):
data[i] = {"asked": False,
"point":None}
cv2.namedWindow("frame")
cv2.setMouseCallback("frame",mouse_callback,param=data)
while True:
if cam is not None:
grabbed,frame = cam.read()
if grabbed:
frame = imutils.resize(frame,width=1200)
cv2.imshow("frame",frame)
k = cv2.waitKey(20) & 0xFF
if k == ord("q"):
break
elif k == ord("c"):
data["click"] = 0
for i in range(4):
data[i] = {"asked":False,
"point":None}
if data["click"] >= 0:
if not data[data["click"]]["asked"]:
data[data["click"]]["asked"] = True
print "Select (%d,%d)" % clickToCoords[data["click"]]
cam.release()
cv2.destroyAllWindows()
|
def string_color(name):
first_char = length = other_chars = sum_chars = 0
prod_chars = 1
for i, a in enumerate(name):
current = ord(a)
length += 1
if i == 0:
first_char = current
else:
other_chars += current
prod_chars *= current
sum_chars += current
if length < 2:
return None
return '{:02X}{:02X}{:02X}'.format(
sum_chars % 256, prod_chars % 256, abs(first_char - other_chars) % 256
)
|
try:
from Tkinter import *
except ImportError:
from tkinter import *
class CollectionNameFrame(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.grid(row=0, column=2, padx=10, pady=10, sticky=NW)
self.collection_name_label = Label(self, text = 'Collection Name:')
self.collection_name_label.grid(row=0, column=0, sticky=W)
self.collection_name = Label(self, text = '')
self.collection_name.grid(row=0, column=1, sticky=W)
def update_name(self, name):
self.collection_name.config(text=name)
|
from __future__ import division, print_function
import unittest
import numpy as np
from smqtk.representation.descriptor_element.local_elements import \
DescriptorMemoryElement
from smqtk.algorithms.relevancy_index.libsvm_hik import LibSvmHikRelevancyIndex
if LibSvmHikRelevancyIndex.is_usable():
class TestIqrSvmHik (unittest.TestCase):
@classmethod
def setUpClass(cls):
# Don't need to clear cache because we're setting the vectors here
cls.d0 = DescriptorMemoryElement('index', 0)
cls.d0.set_vector(np.array([1, 0, 0, 0, 0], float))
cls.d1 = DescriptorMemoryElement('index', 1)
cls.d1.set_vector(np.array([0, 1, 0, 0, 0], float))
cls.d2 = DescriptorMemoryElement('index', 2)
cls.d2.set_vector(np.array([0, 0, 1, 0, 0], float))
cls.d3 = DescriptorMemoryElement('index', 3)
cls.d3.set_vector(np.array([0, 0, 0, 1, 0], float))
cls.d4 = DescriptorMemoryElement('index', 4)
cls.d4.set_vector(np.array([0, 0, 0, 0, 1], float))
cls.d5 = DescriptorMemoryElement('index', 5)
cls.d5.set_vector(np.array([0.5, 0, 0.5, 0, 0], float))
cls.d6 = DescriptorMemoryElement('index', 6)
cls.d6.set_vector(np.array([.2, .2, .2, .2, .2], float))
cls.index_descriptors = [cls.d0, cls.d1, cls.d2, cls.d3, cls.d4,
cls.d5, cls.d6]
cls.q_pos = DescriptorMemoryElement('query', 0)
cls.q_pos.set_vector(np.array([.75, .25, 0, 0, 0], float))
cls.q_neg = DescriptorMemoryElement('query', 1)
cls.q_neg.set_vector(np.array([0, 0, 0, .5, .5], float))
def test_configuration(self):
c = LibSvmHikRelevancyIndex.get_default_config()
self.assertIn('descr_cache_filepath', c)
# change default for something different
c['descr_cache_filepath'] = 'foobar.thing'
#: :type: LibSvmHikRelevancyIndex
iqr_index = LibSvmHikRelevancyIndex.from_config(c)
self.assertEqual(iqr_index.descr_cache_fp,
c['descr_cache_filepath'])
# test config idempotency
self.assertDictEqual(c, iqr_index.get_config())
def test_rank_no_neg(self):
iqr_index = LibSvmHikRelevancyIndex()
iqr_index.build_index(self.index_descriptors)
# index should auto-select some negative examples, thus not raising
# an exception.
iqr_index.rank([self.q_pos], [])
def test_rank_no_pos(self):
iqr_index = LibSvmHikRelevancyIndex()
iqr_index.build_index(self.index_descriptors)
self.assertRaises(ValueError, iqr_index.rank, [], [self.q_neg])
def test_rank_no_input(self):
iqr_index = LibSvmHikRelevancyIndex()
iqr_index.build_index(self.index_descriptors)
self.assertRaises(ValueError, iqr_index.rank, [], [])
def test_count(self):
iqr_index = LibSvmHikRelevancyIndex()
self.assertEqual(iqr_index.count(), 0)
iqr_index.build_index(self.index_descriptors)
self.assertEqual(iqr_index.count(), 7)
def test_simple_iqr_scenario(self):
# Make some descriptors;
# Pick some from created set that are close to each other and use as
# positive query, picking some other random descriptors as
# negative examples.
# Rank index based on chosen pos/neg
# Check that positive choices are at the top of the ranking (closest
# to 0) and negative choices are closest to the bottom.
iqr_index = LibSvmHikRelevancyIndex()
iqr_index.build_index(self.index_descriptors)
rank = iqr_index.rank([self.q_pos], [self.q_neg])
rank_ordered = sorted(rank.items(), key=lambda e: e[1],
reverse=True)
print("rank_ordered:")
for i, r in enumerate(rank_ordered):
print("..{}: {}".format(i, r))
# Check expected ordering
# 0-5-1-2-6-3-4
# - 2 should end up coming before 6, because 6 has more intersection
# with the negative example.
assert rank_ordered[0][0] == self.d0
assert rank_ordered[1][0] == self.d5
assert rank_ordered[2][0] == self.d1
# Results show that d2 and d6 have the same rank, so their position
# in interchangeable.
assert rank_ordered[3][0] in (self.d2, self.d6)
assert rank_ordered[4][0] in (self.d2, self.d6)
assert rank_ordered[3][0] != rank_ordered[4][0]
# d3 and d4 evaluate to the same rank based on query (no
# intersection with positive, equal intersection with negative).
assert rank_ordered[5][0] in (self.d3, self.d4)
assert rank_ordered[6][0] in (self.d3, self.d4)
assert rank_ordered[5][0] != rank_ordered[6][0]
|
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'default_installname',
'type': 'shared_library',
'sources': [ 'file.c' ],
},
{
'target_name': 'default_bundle_installname',
'product_name': 'My Framework',
'type': 'shared_library',
'mac_bundle': 1,
'sources': [ 'file.c' ],
},
{
'target_name': 'explicit_installname',
'type': 'shared_library',
'sources': [ 'file.c' ],
'xcode_settings': {
'LD_DYLIB_INSTALL_NAME': 'Trapped in a dynamiclib factory',
},
},
{
'target_name': 'explicit_installname_base',
'type': 'shared_library',
'sources': [ 'file.c' ],
'xcode_settings': {
'DYLIB_INSTALL_NAME_BASE': '@executable_path/../../..',
},
},
{
'target_name': 'explicit_installname_base_bundle',
'product_name': 'My Other Framework',
'type': 'shared_library',
'mac_bundle': 1,
'sources': [ 'file.c' ],
'xcode_settings': {
'DYLIB_INSTALL_NAME_BASE': '@executable_path/../../..',
},
},
{
'target_name': 'both_base_and_installname',
'type': 'shared_library',
'sources': [ 'file.c' ],
'xcode_settings': {
# LD_DYLIB_INSTALL_NAME wins.
'LD_DYLIB_INSTALL_NAME': 'Still trapped in a dynamiclib factory',
'DYLIB_INSTALL_NAME_BASE': '@executable_path/../../..',
},
},
{
'target_name': 'explicit_installname_with_base',
'type': 'shared_library',
'sources': [ 'file.c' ],
'xcode_settings': {
'LD_DYLIB_INSTALL_NAME': '$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)',
},
},
{
'target_name': 'explicit_installname_with_explicit_base',
'type': 'shared_library',
'sources': [ 'file.c' ],
'xcode_settings': {
'DYLIB_INSTALL_NAME_BASE': '@executable_path/..',
'LD_DYLIB_INSTALL_NAME': '$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)',
},
},
{
'target_name': 'executable',
'type': 'executable',
'sources': [ 'main.c' ],
'xcode_settings': {
'LD_DYLIB_INSTALL_NAME': 'Should be ignored for not shared_lib',
},
},
# Regression test for http://crbug.com/113918
{
'target_name': 'install_name_with_info_plist',
'type': 'shared_library',
'mac_bundle': 1,
'sources': [ 'file.c' ],
'xcode_settings': {
'INFOPLIST_FILE': 'Info.plist',
'LD_DYLIB_INSTALL_NAME': '$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)',
},
},
],
}
|
import mysql.connector
import dbconfig as cfg
db = mysql.connector.connect(
host=cfg.mysql['host'],
user=cfg.mysql['user'],
password=cfg.mysql['password'],
database=cfg.mysql['database']
)
cursor = db.cursor()
sql='insert into car (make, model, price) values (%s,%s,%s)'
values=("Subaru","Impreza",50000)
cursor.execute(sql, values)
db.commit()
print("1 record inserted, ID:", cursor.lastrowid)
|
# coding: utf-8
"""
app.py
~~~~~~
This module implements the App class for main application details and system checks / maintenance.
:license: Apache2, see LICENSE for more details
"""
import os
import vikid._version
import vikid._conf
import logging
"""
"home_dir",
"jobs_dir",
"config_filename",
"config_file_abs_path",
"logs_dir"
"""
# Provide version
version = vikid._version.__version__
from vikid._conf import home_dir, jobs_dir, config_filename, config_file_abs_path, logs_dir
# File permissions
file_perms = 0o755
# Logging configuration
logging_config = dict(
version = 1,
formatters = {
'f': {'format':
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s'}
},
handlers = {
'h': {'class': 'logging.FileHandler',
'formatter': 'f',
'filename': logs_dir + '/viki.log',
'level': logging.DEBUG}
},
root = {
'handlers': ['h'],
'level': logging.DEBUG,
},
)
def check_system_setup():
""" This will be run every time viki starts up
It will check to make sure the home directory exists,
the configuration file in viki-home exists, and
that the jobs directory exists.
If those are not setup correctly you will need to run viki with sudo to create them.
"""
# TODO some of these aren't required, create a list of those that we can accept when missing
dirs = [home_dir, jobs_dir, config_file_abs_path, logs_dir]
for j in dirs:
if not os.path.exists(j):
print('Missing file [{}]...'.format(j))
return False
return True
def create_system_setup():
"""
Creates the required files/directories
"""
dirs = [
home_dir, jobs_dir, logs_dir
]
files = [
config_file_abs_path
]
for j in dirs:
if not os.path.exists(j):
print('Creating dir [{}]...'.format(j))
os.mkdir(j)
# TODO use the helper funcs below to create these files the right way
for k in files:
if not os.path.exists(k):
with open(k, 'w') as file_obj:
print('Creating file [{}]...'.format(k))
file_obj.write('')
def create_home_dir():
""" Creates the home directory """
print('Creating home directory...')
if not home_dir:
return False
if os.path.exists(home_dir):
return False
os.mkdir(home_dir, mode=file_perms)
return True
def generate_config_file():
""" Generates a starter viki configuration file """
print('Generating configuration file...')
if not config_file_abs_path:
return False
if os.path.exists(config_file_abs_path):
return False
tmp_conf_file = """
{
"name": "viki"
}
"""
with open(job_config_path, mode='w', encoding='utf-8') as conf_file_obj:
conf_file_obj.write(tmp_conf_file)
conf_file_obj.close()
os.chmod(job_config_path, mode=file_perms)
return True
def generate_log_file():
""" Generates a blank viki log file """
print('Generating log file...')
if not logfile_path:
return False
if os.path.exists(logfile_path):
return False
tmp_logfile = ''
with open(logfile_path, mode='w', encoding='utf-8') as logfile_obj:
logfile_obj.write(tmp_logfile)
logfile_obj.close()
os.chmod(logfile_path, mode=file_perms)
return True
def create_jobs_dir():
""" Create the jobs directory under viki home """
print('Creating jobs directory...')
if not jobs_dir:
return False
if os.path.exists(jobs_dir):
return False
os.mkdir(jobs_dir, mode=file_perms)
return True
|
from .DS import DS
def start():
ds = DS("set")
return ds
|
from zimsoap import zobjects
class MethodMixin:
def create_task(self, subject, desc):
"""Create a task
:param subject: the task's subject
:param desc: the task's content in plain-text
:returns: the task's id
"""
task = zobjects.Task()
task_creator = task.to_creator(subject, desc)
resp = self.request('CreateTask', task_creator)
task_id = resp['calItemId']
return task_id
def get_task(self, task_id):
"""Retrieve one task, discriminated by id.
:param: task_id: the task id
:returns: a zobjects.Task object ;
if no task is matching, returns None.
"""
task = self.request_single('GetTask', {'id': task_id})
if task:
return zobjects.Task.from_dict(task)
else:
return None
|
def fun(arr,k):
sum = 0
for i in range(len(arr)):
if(arr[i]<k):
sum = sum+k-arr[i]
elif(arr[i]>k):
inc = k*(arr[i]//k+1)-arr[i]
dec = arr[i]%k
sum = sum + inc if inc<=dec else sum + dec
return sum
arr = [4,9,6]
print(fun(arr,5))
|
import numpy as np
from scipy.ndimage.filters import sobel, gaussian_filter
from skimage import filter, transform, feature
from skimage import img_as_float
from coins._hough import hough_circles
def compute_center_pdf(image, radius,
low_threshold, high_threshold,
gradient_sigma=0, confidence_sigma=0):
""" Creates a map representing the probability that each point on an image
is the center of a circle.
"""
# detect edges
edges = filter.canny(image, 0, low_threshold, high_threshold)
# cdef cnp.ndarray[ndim=2, dtype=cnp.double_t] dxs, dys
smoothed = gaussian_filter(image, gradient_sigma)
normals = np.transpose(np.array([sobel(smoothed, 0),
sobel(smoothed, 1)]), (1, 2, 0))
# compute circle probability map
center_pdf = hough_circles(img_as_float(edges), normals, radius, flip=True)
# blur to account for lack of confidence in tangents
# ideally this should be part of the hough transform and it should be
# possible to specify angular and radial confidence seperately but doing so
# is crazy slow
center_pdf_smoothed = gaussian_filter(center_pdf, confidence_sigma)
return center_pdf_smoothed
def detect_possible_circles(image):
"""
"""
radius = 20 # TODO magic
step = 1.1
image = img_as_float(image)
x_coords = []
y_coords = []
radii = []
weights = []
scaled_images = transform.pyramid_gaussian(image, downscale=step)
for scaled_image in scaled_images:
scale = scaled_image.shape[0] / image.shape[0]
# don't bother searching for coins larger than the image
if scaled_image.size < (2*radius)**2:
break
center_pdf = compute_center_pdf(scaled_image, radius, 0.2, 0.3, 0, 3)
# TODO better way of detecting peeks (gmm or something
# For some reason `peak_local_max` with `indices=True` returns an
# array of vectors with the x and y axis swapped.
# using `np.nonzero` and `indices=False` is a workaround.
s_x_coords, s_y_coords = np.nonzero(
feature.peak_local_max(center_pdf, indices=False)
)
s_weights = center_pdf[s_x_coords, s_y_coords]
# Convert from scaled image to image coordinates
# At some point it would be nice to detect peaks with subpixel accuracy
# so also convert to floating point
s_x_coords = s_x_coords.astype(np.float64) / scale
s_y_coords = s_y_coords.astype(np.float64) / scale
s_radii = np.repeat(radius/scale, s_weights.size)
x_coords.append(s_x_coords)
y_coords.append(s_y_coords)
radii.append(s_radii)
weights.append(s_weights)
x_coords = np.concatenate(x_coords)
y_coords = np.concatenate(y_coords)
radii = np.concatenate(radii)
weights = np.concatenate(weights)
return x_coords, y_coords, radii, weights
def prune_overlapping(x_coords, y_coords, radii, weights, threshold=1):
""" Remove coins overlapping other coins with higher weights
"""
sorted_indices = weights.argsort()[::-1]
selected_indices = []
for i in sorted_indices:
xi, yi, ri, wi = x_coords[i], y_coords[i], radii[i], weights[i]
overlapping = False
for s in selected_indices:
xs, ys, rs = x_coords[s], y_coords[s], radii[s]
if (xs - xi)**2 + (ys - yi)**2 < (threshold * max(ri, rs))**2:
overlapping = True
break
if not overlapping:
selected_indices.append(i)
return np.array(selected_indices, dtype=np.int64)
|
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
m = (n1 + n2) / 2
print(f'Tirando {n1} e {n2} a média do aluno é {m}')
if 7 > m >= 5:
print('O aluno está em RECUPERAÇÃO.')
elif m < 5:
print('O aluno está REPROVADO')
else:
print('O aluno está APROVADO')
|
import os
from unittest import TestCase
from smqtk.utils.file_utils import file_mimetype_filemagic
from smqtk.tests import TEST_DATA_DIR
try:
import magic
# We know there are multiple modules named magic. Make sure the function we
# expect is there.
# noinspection PyStatementEffect
magic.detect_from_filename
except (ImportError, AttributeError):
magic = None
if magic is not None:
class TestFile_mimetype_filemagic(TestCase):
def test_file_doesnt_exist(self):
try:
file_mimetype_filemagic('/this/path/probably/doesnt/exist.txt')
except IOError as ex:
self.assertEqual(ex.errno, 2,
"Expected directory IO error #2. "
"Got %d" % ex.errno)
def test_directory_provided(self):
try:
file_mimetype_filemagic(TEST_DATA_DIR)
except IOError as ex:
self.assertEqual(ex.errno, 21,
"Expected directory IO error #21. "
"Got %d" % ex.errno)
def test_get_mimetype_lenna(self):
m = file_mimetype_filemagic(os.path.join(TEST_DATA_DIR,
'Lenna.png'))
self.assertEqual(m, 'image/png')
def test_get_mimetype_no_extension(self):
m = file_mimetype_filemagic(
os.path.join(TEST_DATA_DIR, 'text_file')
)
self.assertEqual(m, 'text/plain')
|
#!/usr/bin/env python3
#
# This example first sets up a simple runaway scenario, which is
# then passed to a DREAM.ConvergenceScan object. The convergence
# scan is configured to apply to the most relevant resolution
# parameters for this scenario. We will use the runaway rate as
# a measure of convergence, and we will consider it to be converged
# when it no longer varies significantly. Once set up, the convergence
# scan is also executed and its result are presented.
#
# Run as
#
# $ ./run.py
#
# ###################################################################
import numpy as np
import sys
sys.path.append('../../py/')
from DREAM.ConvergenceScan import ConvergenceScan
from DREAM.ConvergenceScanPlot import ConvergenceScanPlot
from DREAM.DREAMSettings import DREAMSettings
import DREAM.Settings.Equations.HotElectronDistribution as FHot
import DREAM.Settings.Equations.IonSpecies as Ions
import DREAM.Settings.Solver as Solver
import DREAM.Settings.CollisionHandler as Collisions
###############################
# 1. Set up baseline scenario
###############################
ds = DREAMSettings()
#E = 0.3 # Electric field strength (V/m)
E = 6.745459970079014
n = 5e19 # Electron density (m^-3)
#T = 1e3 # Temperature (eV)
T = 100
# Set E_field
ds.eqsys.E_field.setPrescribedData(E)
# Set temperature
ds.eqsys.T_cold.setPrescribedData(T)
# Set ions
ds.eqsys.n_i.addIon(name='D', Z=1, iontype=Ions.IONS_PRESCRIBED_FULLY_IONIZED, n=n)
# Disable avalanche generation
ds.eqsys.n_re.avalanche = False
# Hot-tail grid settings
pmax = 2
ds.hottailgrid.setNxi(15)
ds.hottailgrid.setNp(300)
ds.hottailgrid.setPmax(pmax)
ds.collisions.collfreq_mode = Collisions.COLLFREQ_MODE_FULL
# Set initial hot electron Maxwellian
ds.eqsys.f_hot.setInitialProfiles(n0=n, T0=T)
#ds.eqsys.f_hot.setBoundaryCondition(FHot.BC_PHI_CONST)
ds.eqsys.f_hot.setBoundaryCondition(FHot.BC_F_0)
ds.eqsys.f_hot.setAdvectionInterpolationMethod(ad_int=FHot.AD_INTERP_QUICK)
# Disable runaway grid
ds.runawaygrid.setEnabled(False)
# Set up radial grid
ds.radialgrid.setB0(5)
ds.radialgrid.setMinorRadius(0.22)
ds.radialgrid.setWallRadius(0.22)
ds.radialgrid.setNr(1)
# Use the linear solver
ds.solver.setType(Solver.LINEAR_IMPLICIT)
ds.output.setTiming(stdout=True)
ds.other.include('fluid/runawayRate')
# Set time stepper
ds.timestep.setTmax(1e-3)
ds.timestep.setNt(10)
##############################
# 2. Set up convergence scan
##############################
cs = ConvergenceScan(ds, inparams=['hottailgrid.np', 'hottailgrid.nxi', 'nt'], outparams=['other.fluid.runawayRate'])
cs.run()
cs.save('convergence.h5')
#####################################
# 3. Do stuff with the finished scan
#####################################
csp = ConvergenceScanPlot(cs)
csp.plot(normalized=True)
# Alternatively, we could read back the saved file
# and plot it
#csp = ConvergenceScanPlot('convergence.h5')
#csp.plot(normalized=True)
|
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
def hello():
return {"msg":"hello world!"}
|
message = 'gux6Jz!J6rp5r7Jzr66ntrM'
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789 !?.'
# Loop through every possible key
for key in range(len(SYMBOLS)):
# It is importan to set translated to the blank string so that the previous itaration's value sor tranlated is cleared:
translated = ''
# The rest of the program is almost the same as Caesar program:
# Loop through each symbol in message:
for symbol in message:
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
translatedIndex = symbolIndex - key
# Handle the wraparound
if translatedIndex < 0:
translatedIndex = symbolIndex + len(SYMBOLS)
# Append the decrypted symbols:
translated = translated + SYMBOLS[translatedIndex]
else:
# Append the sumbol without encrypting/decrypting:
translated = translated + symbol
# Display every possible decryption:
print(translated)
|
print("===문자열 더하기===")
head = "python"
tail = " is fun"
print(head + tail)
print("\n===문자열 곱하기(복제)===")
everyday = "goodday\n"
print(everyday * 3)
print("\n===문자열 곱하기 응용===")
print("=" * 30)
print("\tProgram Start")
print("=" * 30)
|
from .base import *
from decouple import config
from boto3.session import Session
SECRET_KEY = config('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ")
DATABASES = {
"default": {
"ENGINE": config("SQL_ENGINE"),
"NAME": config("SQL_DATABASE"),
"USER": config("SQL_USER"),
"PASSWORD": config("SQL_PASSWORD"),
"HOST": config("SQL_HOST"),
"PORT": config("SQL_PORT")
}
}
STATIC_ROOT = '/static/'
boto3_session = Session(aws_access_key_id=config('AWS_ACCESS_KEY_ID'),
aws_secret_access_key=config('AWS_SECRET_ACCESS_KEY'),
region_name=config('AWS_REGION_NAME'))
LOGGING = {
'version': 1,
'handlers': {
'watchtower': {
'level': 'DEBUG', # Or some more appropriate level
'class': 'watchtower.CloudWatchLogHandler',
'boto3_session': boto3_session,
},
},
'loggers': {
'django': {
'handlers': ['watchtower'],
'level': 'DEBUG', # Or some more appropriate level
'propagate': True,
},
}
}
|
s = "leetcode"
s = list(s)
listS = []
for i in range(len(s)):
if s[i] not in listS:
listS.append([s[i], 1])
|
# from packaging import version
# packaging is not installed in pybites
def changed_dependencies(old_reqs: str, new_reqs: str) -> list:
"""Compare old vs new requirement multiline strings
and return a list of dependencies that have been upgraded
(have a newer version)
"""
old = _get_pkg_dict(old_reqs)
new = _get_pkg_dict(new_reqs)
return [
key for key in old
if _split_v(old[key]) < _split_v(new[key])
]
def _get_pkg_dict(reqs: str) -> dict:
return dict(
line.split('==')
for line in reqs.strip().splitlines()
)
def _split_v(v: list) -> list:
"""
Splits a string of numbers separated by '.'
and returns a list of ints
Alternative : use from distutils.version import StrictVersion
"""
return list(map(int, v.split('.')))
|
import numpy as np
print('Enter n > 0:')
n = int(input())
array = np.array([1, 2, 3])
print(np.tile(array, 3*n).reshape(3*n, len(array)))
|
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from pants.engine.engine_aware import EngineAwareParameter
LOCAL_ENVIRONMENT_MATCHER = "__local__"
@dataclass(frozen=True)
class EnvironmentName(EngineAwareParameter):
"""The normalized name for an environment, from `[environments-preview].names`, after applying
things like the __local__ matcher.
Note that we have this type, rather than only `EnvironmentTarget`, for a more efficient rule
graph. This node impacts the equality of many downstream nodes, so we want its identity to only
be a single string, rather than a Target instance.
"""
val: str | None
def debug_hint(self) -> str | None:
return f"environment:{self.val}" if self.val else None
@dataclass(frozen=True)
class ChosenLocalEnvironmentName:
"""Which environment name from `[environments-preview].names` that __local__ resolves to."""
val: EnvironmentName
|
'''
The autocomplete function will take in an input string and a dictionary array and
return the values from the dictionary that start with the input string. If
there are more than 5 matches, restrict your output to the first 5 results.
If there are no matches, return an empty array.
For this kata, the dictionary will always be a valid array of strings.
Please return all results in the order given in the dictionary, even if
they're not always alphabetical. The search should NOT be case sensitive,
but the case of the word should be preserved when it's returned.
For example, "Apple" and "airport" would both return for an input of 'a'.
However, they should return as "Apple" and "airport" in their original cases.
'''
import re
def autocomplete(input_, dictionary):
final = []
clean_s = "".join(re.findall('[a-zA-Z]', input_))
for word in dictionary:
if len(final) == 5:
break
if clean_s[:len(clean_s)] == word[:len(clean_s)].lower():
final.append(word)
return final
dictionary = ['airplane', 'apple', 'air', 'avenue', 'airport', 'adamantium',
'awkwardness', 'awesome', 'amazing', 'ball', 'book', 'bike', 'bill', 'billiard',
'bell', 'bowl', 'Blastoise', 'beautiful', 'car', 'cookie', 'coup', 'candle',
'change', 'champion', 'call', 'camel', 'Charizard', 'catastrophic', 'cat',
'keepsake', 'kick', 'kicker', 'knot', 'kit', 'kitten', 'lamp', 'light', 'lol', 'llama',
'lake', 'love', 'link', 'league', 'legend', 'laboratory', 'lab', 'more', 'morbid',
'move', 'mover', 'movie', 'monocle', 'murica', 'molar', 'mouth', 'muscle', 'montage',
'nope', 'no', 'naughty', 'nice', 'nail polish', 'noodles', 'niece', 'nissan', 'octopus',
'under', 'undercover', 'united', 'unbelievable', 'unimaginable', 'ultra', 'ultraviolet',
'victory', 'violin', 'viola', 'vibrant', 'video playback', 'velcro', 'velvet', 'window',
'win', 'wedding', 'wet', 'where', 'wild', 'well', 'welcome', 'wonderful', 'xylophone',
'x-ray', 'X-Men', 'Xavier', 'xenon', 'xerox', 'Xerneas', 'Yaphi', 'you', 'yourself',
'your', 'yonder', 'yodel', 'yammer', 'Yveltal', 'Zelda', 'Zygarde', 'zebra',
'zero', 'Zeus', 'zap cannon', 'zephyr', 'zig-zag']
autocomplete('$-*z', dictionary)
#Returns: ['Zelda', 'Zygarde', 'zebra', 'zero', 'Zeus']
|
import sys
import warnings
from pathlib import Path
from tqdm import tqdm
from joblib import Parallel, delayed
sys.path.append("/home/herman/git/muspy/")
import muspy
DATASET_DIR = Path("/data4/herman/muspy-new")
TARGET_DIR = DATASET_DIR / "downsampled"
DATASET_KEYS = [
"nes",
"jsb",
"maestro",
"hymnal",
"hymnal_tune",
"music21",
"music21jsb",
"nmd",
"essen",
"lmd",
"wikifonia",
]
def get_dataset(key):
if key == "lmd":
return muspy.LakhMIDIDataset(DATASET_DIR / "lmd")
if key == "wikifonia":
return muspy.WikifoniaDataset(DATASET_DIR / "wikifonia")
if key == "nes":
return muspy.NESMusicDatabase(DATASET_DIR / "nes")
if key == "jsb":
return muspy.JSBChoralesDataset(DATASET_DIR / "jsb")
if key == "maestro":
return muspy.MAESTRODatasetV2(DATASET_DIR / "maestro")
if key == "hymnal":
return muspy.HymnalDataset(DATASET_DIR / "hymnal")
if key == "hymnal_tune":
return muspy.HymnalTuneDataset(DATASET_DIR / "hymnal_tune")
if key == "music21":
return muspy.MusicDataset(DATASET_DIR / "music21")
if key == "music21jsb":
return muspy.MusicDataset(DATASET_DIR / "music21jsb")
if key == "nmd":
return muspy.NottinghamDatabase(DATASET_DIR / "nmd")
if key == "essen":
return muspy.EssenFolkSongDatabase(DATASET_DIR / "essen")
raise ValueError("Unrecognized dataset name.")
def _downsampler(d_key, music, idx, n_digits):
prefix = "0" * (n_digits - len(str(idx)))
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
music.adjust_resolution(4)
music.save_json(TARGET_DIR / d_key / (prefix + str(idx) + ".json"))
except Exception: # pylint: disable=broad-except
return False
return True
def process(d_key):
print("Start processing dataset: {}".format(d_key))
dataset = get_dataset(d_key)
(TARGET_DIR / d_key).mkdir(exist_ok=True)
n_digits = len(str(len(dataset)))
results = Parallel(n_jobs=20, verbose=5)(
delayed(_downsampler)(d_key, music, idx, n_digits)
for idx, music in enumerate(dataset)
)
count = results.count(True)
# count = 0
# for idx in tqdm(range(len(dataset))):
# prefix = "0" * (n_digits - len(str(idx)))
# try:
# with warnings.catch_warnings():
# warnings.simplefilter("ignore")
# music = dataset[idx]
# music.adjust_resolution(4)
# music.save_json(
# TARGET_DIR / d_key / (prefix + str(idx) + ".json")
# )
# count += 1
# except Exception: # pylint: disable=broad-except
# continue
print("{} out of {} files successfully saved.".format(count, len(dataset)))
if __name__ == "__main__":
if sys.argv[1].lower() == "all":
for dataset_key in DATASET_KEYS:
process(dataset_key)
else:
process(sys.argv[1].lower())
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2015 Open Business Solutions (<http://www.obsdr.com>)
# Author: Naresh Soni
# Copyright 2015 Cozy Business Solutions Pvt.Ltd(<http://www.cozybizs.com>)
# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
##############################################################################
from openerp import models, fields, api
class CheckReportConfig(models.Model):
_name = "check.report.config"
name = fields.Char("Nombre", required=True)
body_top = fields.Float(string="Margen superior del cuerpo del cheque")
name_top = fields.Float(string="Margen superior del nombre")
name_left = fields.Float(string="Margen izquierdo del nombre")
date_top = fields.Float(string="Margen superior de la fecha")
date_left = fields.Float(string="Margen izquierdo de la fecha")
amount_top = fields.Float(string="Margen superior del monto")
amount_left = fields.Float(string="Margen izquierdo del monto")
amount_letter_top = fields.Float(string="Margen superior monto en letras")
amount_letter_left = fields.Float(string="Margen izquierdo monto en letras")
# Par el concepto
concept_top = fields.Float(string="Margen superior del concepto",)
concept_left = fields.Float(string="Margen izquierdo del concepto")
# Para el debito
debit_top = fields.Float(string="Margen superior del debito",)
debit_left = fields.Float(string="Margen izquierdo del debito")
check_header_top = fields.Float("Margen superior de la Cabecera")
check_header = fields.Html("Cabecera del cheque")
check_footer_top = fields.Float("Margen superior del pie")
check_footer = fields.Html("Pie del cheque")
anc_concepto = fields.Float(string="Anchura campo Concepto", )
anc_debito = fields.Float(string="Anchura campo Debito", )
anc_credito = fields.Float(string="Anchura campo Credito", )
|
# GitPycharm HW15
print("Hello World 1 in team leader server")
|
from django.http import HttpRequest
from django.test import SimpleTestCase
from django.urls import reverse
from . import views
class HomePageTests(SimpleTestCase):
def test_home_page_status_code(self):
response = self.client.get('/')
self.assertEquals(response.status_code, 200)
#=================
# Test build flow
#=================
def test_view_url_Step1(self):
response = self.client.get('/Step1',{'type': 'gaming' , 'price': '1000'} )
self.assertEquals(response.status_code, 200)
def test_view_url_Step2(self):
response = self.client.get('/Step2',{'CPU' : '1'} )
self.assertEquals(response.status_code, 200)
def test_view_url_Step3(self):
response = self.client.get('/Step3',{'CPU':'1' , 'GPU' : '1'} )
self.assertEquals(response.status_code, 200)
def test_view_url_Step4(self):
response = self.client.get('/Step4',{'CPU' : '1' , 'GPU': '1' , 'RAM' : '0'} )
self.assertEquals(response.status_code, 200)
def test_view_url_Step5(self):
response = self.client.get('/Step5',{'CPU' : '1' , 'GPU': '1' , 'RAM' : '0', 'STORAGE' : '1'} )
self.assertEquals(response.status_code, 200)
def test_view_url_Step6(self):
response = self.client.get('/Step6',{'CPU' : '1' , 'GPU': '1' , 'RAM' : '0', 'STORAGE' : '1' , 'MB' : '2'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cart(self):
response = self.client.get('/cart',{'CPU' : '1' , 'GPU': '1' , 'RAM' : '0', 'STORAGE' : '1' , 'MB' : '2'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cart2(self):
response = self.client.get('/cart',{'CPU' : '1' , 'RAM' : '0', 'STORAGE' : '1' , 'MB' : '2'} )
self.assertEquals(response.status_code, 200)
#==================
# Test CPU details
#==================
def test_view_url_cpu_details_graph_1(self):
response = self.client.get('/cpu_details' , {'graph' : '1'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_2(self):
response = self.client.get('/cpu_details' , {'graph' : '2'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_3(self):
response = self.client.get('/cpu_details' , {'graph' : '3'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_4(self):
response = self.client.get('/cpu_details' , {'graph' : '4'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_5(self):
response = self.client.get('/cpu_details' , {'graph' : '5'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_6(self):
response = self.client.get('/cpu_details' , {'graph' : '6'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_7(self):
response = self.client.get('/cpu_details' , {'graph' : '7'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_8(self):
response = self.client.get('/cpu_details' , {'graph' : '8'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_9(self):
response = self.client.get('/cpu_details' , {'graph' : '9'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_10(self):
response = self.client.get('/cpu_details' , {'graph' : '10'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_11(self):
response = self.client.get('/cpu_details' , {'graph' : '11'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_11(self):
response = self.client.get('/cpu_details' , {'graph' : '12'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_11(self):
response = self.client.get('/cpu_details' , {'graph' : '13'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_11(self):
response = self.client.get('/cpu_details' , {'graph' : '14'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_11(self):
response = self.client.get('/cpu_details' , {'graph' : '15'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_11(self):
response = self.client.get('/cpu_details' , {'graph' : '16'} )
self.assertEquals(response.status_code, 200)
def test_view_url_cpu_details_graph_11(self):
response = self.client.get('/cpu_details' , {'graph' : '17'} )
self.assertEquals(response.status_code, 200)
#==========================
# Test motherboard details
#==========================
def test_view_url_motherboard_details(self):
'''
Tests the webpage motherboard_details for all possible graphs
'''
for i in range(1, 7):
self.is_motherboard_details_graph_ok(i)
def is_motherboard_details_graph_ok(self, graph_num):
'''
Test the webpage motherboard_details for a specific graph.
Arguments:
graph_num: The graph number to test
'''
response = self.client.get('/motherboard_details' , {'graph' : str(graph_num)})
self.assertEquals(response.status_code, 200)
#==========================
# Test gpu details
#==========================
def test_view_url_gpu_details(self):
'''
Tests the webpage gpu_details for all possible graphs
'''
for i in range(1, 7):
self.is_gpu_details_graph_ok(i)
def is_gpu_details_graph_ok(self, graph_num):
'''
Test the webpage gpu_details for a specific graph.
Arguments:
graph_num: The graph number to test
'''
response = self.client.get('/gpu_details' , {'graph' : str(graph_num)})
self.assertEquals(response.status_code, 200)
#==========================
# Test storage details
#==========================
def test_view_url_storage_details(self):
'''
Tests the webpage storage_details for all possible graphs
'''
for i in range(1, 9):
self.is_storage_details_graph_ok(i)
def is_storage_details_graph_ok(self, graph_num):
'''
Test the webpage storage_details for a specific graph.
Arguments:
graph_num: The graph number to test
'''
response = self.client.get('/storage_details' , {'graph' : str(graph_num)})
self.assertEquals(response.status_code, 200)
#==================
# Test memory details
#==================
def test_view_url_memory_details_graph_1(self):
response = self.client.get('/memory_details' , {'graph' : '1'} )
self.assertEquals(response.status_code, 200)
def test_view_url_memory_details_graph_2(self):
response = self.client.get('/memory_details' , {'graph' : '2'} )
self.assertEquals(response.status_code, 200)
def test_view_url_memory_details_graph_3(self):
response = self.client.get('/memory_details' , {'graph' : '3'} )
self.assertEquals(response.status_code, 200)
def test_view_url_memory_details_graph_4(self):
response = self.client.get('/memory_details' , {'graph' : '4'} )
self.assertEquals(response.status_code, 200)
def test_view_url_memory_details_graph_5(self):
response = self.client.get('/memory_details' , {'graph' : '5'} )
self.assertEquals(response.status_code, 200)
def test_view_url_memory_details_graph_6(self):
response = self.client.get('/memory_details' , {'graph' : '6'} )
self.assertEquals(response.status_code, 200)
def test_view_url_memory_details_graph_7(self):
response = self.client.get('/memory_details' , {'graph' : '7'} )
self.assertEquals(response.status_code, 200)
def test_view_url_memory_details_graph_8(self):
response = self.client.get('/memory_details' , {'graph' : '8'} )
self.assertEquals(response.status_code, 200)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-10-01 21:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='post_info',
fields=[
('message', models.TextField()),
('story', models.TextField(blank=True)),
('time', models.DateTimeField(blank=True)),
('id', models.CharField(max_length=100, primary_key=True, serialize=False)),
('no_of_likes', models.IntegerField(blank=True)),
('category', models.CharField(blank=True, max_length=10)),
],
),
]
|
# using Tkinter's Optionmenu() as a combobox
try:
# Python2
from vcenter_performance_monitoring import VcenterTest
import Tkinter as tk
import tkMessageBox
vpm = VcenterTest()
except ImportError as err:
print err
def select():
matrick = var.get()
vm = var2.get()
res=vpm.get_summary(vm,matrick)
tkMessageBox.showinfo( "", res)
root = tk.Tk()
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (330, 80, 200, 150))
root.title("Vcenter performance monitoring")
var = tk.StringVar(root)
var2 = tk.StringVar(root)
# initial value
vms = vpm.get_all_vms()
var.set('summary')
var2.set(vms[0])
metricks = ['summary','powerState','quickStats','overallStatus','guest','config','storage']
matrick_dropdown = tk.OptionMenu(root, var, *metricks)
matrick_dropdown.pack(side='left', padx=10, pady=10)
vms_dropdown = tk.OptionMenu(root,var2,*vms)
vms_dropdown.pack()
button = tk.Button(root, text="Pollit", command=select)
button.pack(side='left', padx=20, pady=10)
root.mainloop()
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\alvar_000\Documents\registro\dialog.ui'
#
# Created by: PyQt5 UI code generator 5.8.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(606, 562)
self.cerrarBtn = QtWidgets.QPushButton(Dialog)
self.cerrarBtn.setGeometry(QtCore.QRect(480, 520, 75, 23))
self.cerrarBtn.setObjectName("cerrarBtn")
self.actualizarBtn = QtWidgets.QPushButton(Dialog)
self.actualizarBtn.setGeometry(QtCore.QRect(60, 520, 75, 23))
self.actualizarBtn.setObjectName("actualizarBtn")
self.textEdit = QtWidgets.QTextEdit(Dialog)
self.textEdit.setGeometry(QtCore.QRect(60, 60, 491, 431))
self.textEdit.setReadOnly(True)
self.textEdit.setObjectName("textEdit")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(190, 20, 231, 31))
font = QtGui.QFont()
font.setFamily("Century")
font.setPointSize(18)
self.label.setFont(font)
self.label.setTextFormat(QtCore.Qt.RichText)
self.label.setObjectName("label")
self.actualizarBtn.clicked.connect(self.actualizaText)
self.cerrarBtn.clicked.connect(self.cerrar)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.cerrarBtn.setText(_translate("Dialog", "Cerrar"))
self.actualizarBtn.setText(_translate("Dialog", "Actualizar"))
self.label.setText(_translate("Dialog", "Registro de cambios"))
self.cerrarBtn.setVisible(False)
self.actualizaText()
def actualizaText(self):
self.textEdit.clear()
fileHandle = open("Resultados.txt", "r+")
tmp = fileHandle.read()
print("Abriendo acrh " + tmp)
self.textEdit.setText(tmp)
fileHandle.close()
def cerrar(self):
self.hide()
class Log(QtWidgets.QDialog):
def __init__(self, parent):
QtWidgets.QDialog.__init__(self)
self.ventana = QtWidgets.QDialog()
self.ui = Ui_Dialog()
self.ui.setupUi(self.ventana)
self.ventana.show()
|
# -*- coding:utf-8 -*-
import sqlite3
import re
import requests
# 创建表
def create_table(cursor1):
# PRECAUTIONS TEXT);''')
cursor1.execute('''CREATE TABLE CILIN
(ID INT PRIMARY KEY NOT NULL,
LABELS TEXT NOT NULL,
WORD TEXT NOT NULL);''')
# 清空表
def delete_items(cursor1):
cursor1.execute("DELETE FROM CILIN")
# 添加
def add(cursor1):
with open('../files/cilin.txt','rb') as f:
lines = f.readlines()
num = 0
for i in lines:
item = i.decode('gbk')
label = item[0:8]
words_list = item[9:].replace('\r\n','').split(' ')
for j in words_list:
cursor1.execute("insert into CILIN(ID,LABELS,WORD) values(?,?,?)", (num, label, j))
num += 1
def show_table(cursor1):
cursor1.execute("select * from CILIN where word = '骄傲'")
# cursor1.execute("select * from CILIN where WORD like '%牙龈出血%'")
values = cursor1.fetchall()
for i in values:
print(i)
if __name__ == '__main__':
conn = sqlite3.connect('cilin.db')
cursor = conn.cursor()
# create_table(cursor)
# add(cursor)
show_table(cursor)
cursor.close()
conn.commit()
conn.close()
|
import json
import os
products = []
with open("scans.json", "r") as f:
data = json.load(f)
for e in data:
id = e['id']
name = e['name']
type = e['type']
t = str(e["timestamp"])
l = e["location"]
l = [str(i) for i in l]
l = ' '.join(l)
found = False
for p in products:
if p[0] == id:
p[3].append(t+" "+l)
found = True
break
if not found:
products.append(
[id, name, type, [t+" "+l]]
)
os.chdir("Packages")
for i in products:
name = i[0]
with open(name+".pac", "w") as f:
for j in i[:3]:
print(j, file=f)
for j in i[3]:
print(j, file=f)
|
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Node2Link
A QGIS plugin
Drawing lines with points
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2020-09-02
git sha : $Format:%H$
copyright : (C) 2020 by wemap
email : wemap
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt, QVariant
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QMessageBox, QActionGroup, QAction, QInputDialog, QLineEdit
# Initialize Qt resources from file resources.py
from .resources import *
from qgis.core import edit, QgsMarkerSymbol, QgsProject, QgsGeometry, QgsPoint, QgsFeature
from qgis.utils import iface
from qgis.gui import QtCore
# Import the code for the DockWidget
from .node_to_link_dockwidget import Node2LinkDockWidget
import os.path
class Node2Link:
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'Node2Link_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Node to Link')
# TODO: We are going to let the user set this up in a future iteration
self.toolbar = self.iface.addToolBar(u'Node2Link')
self.toolbar.setObjectName(u'Node2Link')
#print "** INITIALIZING Node2Link"
self.pluginIsActive = False
self.dockwidget = None
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
# icon_path = ':/plugins/node_to_link/icon.png'
icon_add = ':/plugins/node_to_link/icon_add.png'
icon_delete = ':/plugins/node_to_link/icon_delete.png'
icon_heading = ':/plugins/node_to_link/icon_heading.png'
icon_move = ':/plugins/node_to_link/icon_move.png'
icon_check = ':/plugins/node_to_link/icon_check.png'
# link 입력 button
self.add_link_action = self.add_action(
icon_add,
text=self.tr(u'Add link'),
callback=self.run_add_action,
checkable=True, # 추가
enabled_flag=True, # 추가
parent=self.iface.mainWindow())
# state 추가 -> add_action 함수의 checkable 사용하는 것으로 수정
# self.start_action.setCheckable(True)
# link 삭제 button
self.delete_link_action = self.add_action(
icon_delete,
text=self.tr(u'Delete link'),
callback=self.run_delete_action,
checkable=True,
enabled_flag=True,
parent=self.iface.mainWindow())
# 노드정위치 button
self.move_node_action = self.add_action(
icon_move,
text=self.tr(u'Move node and link'),
callback=self.run_move_action,
checkable=True,
enabled_flag=True,
parent=self.iface.mainWindow())
# heading 입력 button
self.change_heading_action = self.add_action(
icon_heading,
text=self.tr(u'Change heading of node'),
callback=self.run_heading_action,
checkable=True,
enabled_flag=True,
parent=self.iface.mainWindow())
# link 작업 상태 변경 button
self.change_status_action = self.add_action(
icon_check,
text=self.tr(u'Change link status'),
callback=self.run_status_action,
checkable=True,
enabled_flag=True,
parent=self.iface.mainWindow())
# 현재 action
self.currTool = None
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('Node2Link', message)
def add_action(
self,
icon_path,
text,
callback,
checkable=False, # 추가함
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
action.setCheckable(checkable) # 추가함.
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
return action
#--------------------------------------------------------------------------
def onClosePlugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed"""
#print "** CLOSING Node2Link"
# disconnects
self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docked window:
# self.dockwidget = None
# self.dockwidget = None
self.pluginIsActive = False
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
#print "** UNLOAD Node2Link"
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&Node to Link'),
action)
self.iface.removeToolBarIcon(action)
# remove the toolbar
del self.toolbar
#--------------------------------------------------------------------------
## layer 선택 함수, qgis의 layer와, 플러그인의 로딩 시점 차이 때문에 layer 선택 확인 필요
def layer_selector(self):
# 프로젝트마다 layer 달라질 수 있어서 레이어 이름으로 선택하는 것으로 수정.
nodelayer_by_name = QgsProject.instance().mapLayersByName('alley_node')
linklayer_by_name = QgsProject.instance().mapLayersByName('alley_link')
self.node_layer = QgsProject.instance().mapLayer(nodelayer_by_name[0].id()) # DB 레이어
self.link_layer = QgsProject.instance().mapLayer(linklayer_by_name[0].id()) # DB 레이어
if self.node_layer == None:
QMessageBox.information(self.iface.mainWindow(), "레이어 설정", "노드 레이어 설정실패")
# ToDo! self kill ???
if self.link_layer == None:
QMessageBox.information(self.iface.mainWindow(), "레이어 설정", "링크 레이어 설정실패")
# ToDo! self kill ???
## 하나의 action 버튼만 활성화하기위한 action change 함수
def changeTool(self, nextTool):
# print("before currTool: ", self.currTool) # test
# 이전 tool버튼을 직접 다시 클릭해서 종료한 경우 제외하기 위해 isChecked() == True인지 확인한다.
if self.currTool != None and self.currTool != nextTool and self.currTool.isChecked() == True:
self.currTool.trigger() # 이전 작업 종료
# 바뀐 action을 현재 action으로 지정해준다.
self.currTool = nextTool
# print("after currTool: ", self.currTool) # test
## link 입력 button의 run 함수
def run_add_action(self):
# layer 설정
self.layer_selector()
# assert문으로 layer가 설정되었는지 검증
assert self.node_layer != None, "self.node_layer != None"
# checked 상태 확인
# print("self.add_link_action.isChecked()=", self.add_link_action.isChecked())
# checked 상태이면 node레이어에 selectionChanged 이벤트를 connect
if self.add_link_action.isChecked() == True:
# 버튼 change
self.changeTool(self.add_link_action)
print("Link 추가 작업이 시작되었습니다.")
# 기존에 선택됐던 피쳐 선택 취소하기 위해 deselect action trigger
self.deselectAll()
# selection 버튼 call
iface.actionSelect().trigger()
# node_layer 활성화
iface.setActiveLayer(self.node_layer)
# selectionChanged 이벤트함수 연결
self.node_layer.selectionChanged.connect(self.onNodeSelected)
# checked 아니면 disconnect
else:
self.node_layer.selectionChanged.disconnect(self.onNodeSelected)
print("Link 추가 작업이 종료되었습니다.")
## node의 selection change 이벤트가 발생했을 때, 처리 할 메서드
def onNodeSelected(self, selected, deselected, clearAndSelect):
# selected, deselected 는 array type
# print("selected : ", selected)
# print("deselected : ", deselected)
# 선택된 2개의 node들을 nodefr, nodeto에 지정한다.
# nodefr, nodeto 선언
nodefr, nodeto = None, None
# 현재 선택된 node가 있을 경우
if len(selected) > 0:
# 이전에 선택된 node가 있을 경우
if len(deselected) > 0:
# array type이기 때문에 [0]으로 배열의 첫 번째 요소 선택해서 from, to 노드로 지정
nodefr, nodeto = deselected[0], selected[0]
# 이전에 선택된 node가 없을 경우, 현재 node가 from 노드가 됨
else:
nodefr, nodeto = selected[0], None
# from, to 노드가 모두 존재할 경우 link 생성
if nodefr != None and nodeto != None:
# print("nodeFr : ", nodefr, "nodeTo : ", nodeto)
# node_fr, node_to 중복검사하기
# True 체크해서 return 으로 함수 아래문장 종료
if self.checkLinkDups(nodefr, nodeto):
return print("Link가 중복됩니다. 새로운 Link를 생성할 수 없습니다.")
# link 생성 함수
self.createLink(nodefr, nodeto)
## 선택된 2개의 node로 link 생성
def createLink(self, from_node, to_node):
# https://github.com/peterahlstrom/PointConnector/blob/master/point_connector.py
# https://anitagraser.com/pyqgis-101-introduction-to-qgis-python-programming-for-non-programmers/pyqgis101-creating-editing-a-new-vector-layer/
# feature 추가
# select된 피쳐 id를 사용해 feature로 넘겨주기 위해 node layer 불러옴 -> self.layer 사용하는 걸로 수정함.
# node_layer = QgsProject.instance().mapLayer('alley_node_7ba9c802_33d6_4a6a_9ddc_856bd360da0c')
# from, to 노드 id로 feature 선택
frPoint, toPoint = self.node_layer.getFeature(from_node), self.node_layer.getFeature(to_node)
frGeom, toGeom = frPoint.geometry(), toPoint.geometry()
# print("attributes : ", frPoint.attributes()) # test
# attrs = [0, from_node, to_node] # test [link_id, fr_id, to_id], link_id auto increment 설정?
new_line = QgsGeometry.fromPolyline([QgsPoint(frGeom.asPoint()), QgsPoint(toGeom.asPoint())])
# print("attr: ", attrs, "newline: ", new_line) # test
feat = QgsFeature(self.link_layer.fields())
feat.setGeometry(new_line)
# feat.setAttributes(attrs)
# https://docs.qgis.org/3.10/en/docs/pyqgis_developer_cookbook/vector.html
# Or set a single attribute by key or by index:
# link_id는 auto_increment이므로 from_node, to_node id만 지정해준다.
feat.setAttribute(1, from_node)
feat.setAttribute(2, to_node)
# status : check complete 상태로 추가
# feat.setAttribute(3, 1) // link 수정상태 기본 0 으로 수정함.
try:
with edit(self.link_layer):
self.link_layer.addFeatures([feat])
print("Link가 생성되었습니다! from node: ", from_node, "to node: ", to_node)
except Exception as err:
print(repr(err))
## 링크의 노드 중복 검사 함수
def checkLinkDups(self, from_node, to_node):
# 똑같은 link 거나, fr&to 순서만 다를 경우 True반환
for feat in self.link_layer.getFeatures():
if from_node == feat["node_fr"] and to_node == feat["node_to"]:
return True
if to_node == feat["node_fr"] and from_node == feat["node_to"]:
return True
## link 삭제 버튼 run 함수
def run_delete_action(self):
self.layer_selector()
assert self.link_layer != None, "self.link_layer != None"
if self.delete_link_action.isChecked() == True:
self.changeTool(self.delete_link_action)
print("link 삭제 작업이 시작되었습니다.")
# deselect all
self.deselectAll()
# selection 버튼 call
iface.actionSelect().trigger()
#link_layer 활성화
iface.setActiveLayer(self.link_layer)
# # delete a feature with specified ID
# layer.deleteFeature(fid)
# selection 이벤트 함수 연결
self.link_layer.selectionChanged.connect(self.deleteLink)
else:
self.link_layer.selectionChanged.disconnect(self.deleteLink)
print("link 삭제 작업이 종료되었습니다.")
## 링크 삭제 함수
def deleteLink(self, selected):
# self.link_layer.deleteFeature(selected) # 개별 id로 받아올 때
# selected : list 형태로 받아옴
# self.link_layer.dataProvider().deleteFeatures(selected) # dataProvider 사용하면 undo,redo 사용 X
# with edit(layer) 구문 사용, commit 자동으로 됨.
# https://www.opengis.ch/2015/08/12/with-edit-layer/
try:
with edit(self.link_layer):
self.link_layer.deleteFeatures(selected)
print(" 선택된 link가 삭제되었습니다. Link_id: ", selected)
except Exception as err:
print(repr(err))
## 노드정위치 버튼 run 함수
def run_move_action(self):
self.layer_selector()
assert self.node_layer != None, "self.node_layer != None"
assert self.link_layer != None, "self.link_layer != None"
if self.move_node_action.isChecked() == True:
self.changeTool(self.move_node_action)
print("node정위치 작업이 시작되었습니다.")
# node 이동
self.moveNode()
## node 레이어에 feature geometry changed 이벤트 함수 연결
# node 이동 시, link 자동 수정
self.node_layer.geometryChanged.connect(self.updateLink)
else:
# checked 아니면 이벤트함수 disconnect
self.node_layer.geometryChanged.disconnect(self.updateLink)
# commit
self.node_layer.commitChanges()
## edit 종료
iface.vectorLayerTools().stopEditing(self.node_layer)
print("node정위치 작업이 종료되었습니다.")
## link 동기화 함수
def updateLink(self, fid, new_geom):
# print("fid: ", fid, "geom: ", new_geom, "노드가 변경되었습니다.")
## link_layer 수정, node 따라서 geometry만 수정
# changeGeometry 함수가 적용되기 위해 레이어의 edit 모드가 활성화 되어야 한다.
iface.setActiveLayer(self.link_layer)
# self.link_layer.startEditing()
# link_layer의 모든 feature 확인
for feat in self.link_layer.getFeatures():
# 이동한 node와 같은 id의 fr, to 노드를 가진 link 찾기
# from 노드가 수정된 경우
if fid == feat["node_fr"] :
link_id = feat["link_id"]
# to 노드는 기존에 있는 값 그대로 사용
toPoint = self.node_layer.getFeature(feat["node_to"])
# frGeom, toGeom = new_geom, feat.geometry().get()[-1] # feature의 geometry에 바로 접근하는 방법
frGeom, toGeom = new_geom, toPoint.geometry()
new_link_geom = QgsGeometry.fromPolyline([QgsPoint(frGeom.asPoint()), QgsPoint(toGeom.asPoint())])
# link geometry 수정
try:
with edit(self.link_layer):
ok = self.link_layer.changeGeometry(link_id, new_link_geom)
# feat.setGeometry(new_link_geom)
# 결과 출력
print("Changed?: ", ok, "link id: ", link_id)
except Exception as err:
print(repr(err))
# to 노드가 수정된 경우
if fid == feat["node_to"]:
link_id = feat["link_id"]
frPoint = self.node_layer.getFeature(feat["node_fr"])
frGeom, toGeom = frPoint.geometry(), new_geom
new_link_geom = QgsGeometry.fromPolyline([QgsPoint(frGeom.asPoint()), QgsPoint(toGeom.asPoint())])
try:
with edit(self.link_layer):
ok = self.link_layer.changeGeometry(link_id, new_link_geom)
print("Changed?: ", ok, "link id: ", link_id)
except Exception as err:
print(repr(err))
## node수정작업 연속으로 하기위해 다시 node_layer 활성화
self.moveNode()
# node를 move mode로 바꿔주는 함수
def moveNode(self):
self.deselectAll()
## node_layer 활성화
iface.setActiveLayer(self.node_layer)
## edit mode 시작
self.node_layer.startEditing()
# move feature 버튼 call
# https://gis.stackexchange.com/questions/141371/implementing-add-feature-action-using-pyqgis?rq=1
iface.actionMoveFeature().trigger()
## heading 입력 버튼 run 함수
def run_heading_action(self):
self.layer_selector()
assert self.node_layer != None, "self.node_layer != None"
if self.change_heading_action.isChecked() == True:
self.changeTool(self.change_heading_action)
print("heading 입력 작업이 시작되었습니다.")
self.deselectAll()
iface.actionSelect().trigger()
iface.setActiveLayer(self.node_layer)
# selection 이벤트에 함수 연결
self.node_layer.selectionChanged.connect(self.changeHeading)
else:
# checked 아니면 disconnect
self.node_layer.selectionChanged.disconnect(self.changeHeading)
print("heading 입력 작업이 종료되었습니다.")
## heading 입력 함수
def changeHeading(self, selected):
if len(selected) > 0:
## Dialog 상자 띄워서 angle값 입력 받기
# http://www.green-forums.info/greenlib/geolibrary/Lawhead%20J/QGIS%20Python%20Programming%20Cookbook.%2020%20%2852%29/QGIS%20Python%20Programming%20Cookboo%20-%20Lawhead%20J.pdf
# initialize the dialog
# qid = QInputDialog()
# configure the dialog
new_heading, ok = QInputDialog.getInt(self.iface.mainWindow(), "Change heading", "Enter heading value", 0, 0, 360, 1)
# dialog 창 뜨면, text 입력하고, ok 버튼 누른다.
# 입력 결과 출력
print("입력된 heading 값: ", new_heading)
## heading 값 업데이트
# update an attribute with given field index (int) to a given value
fid = selected[0]
fieldIndex = 2
value = new_heading
try:
with edit(self.node_layer):
self.node_layer.changeAttributeValue(fid, fieldIndex, value)
# 수정 결과 출력
print("heading 값이 수정됐습니다! fid: ", fid, "value: ", value)
except Exception as err:
print(repr(err))
## link 작업 상태 변경 run 함수
def run_status_action(self):
self.layer_selector()
assert self.link_layer != None, "self.link_layer != None"
if self.change_status_action.isChecked() == True:
self.changeTool(self.change_status_action)
print("link 작업상태 변경이 시작되었습니다.")
self.deselectAll()
iface.actionSelect().trigger()
iface.setActiveLayer(self.link_layer)
# selection 이벤트 함수 연결
self.link_layer.selectionChanged.connect(self.changeStatus)
else:
# checked 아니면 disconnect
self.link_layer.selectionChanged.disconnect(self.changeStatus)
print("link 작업상태 변경이 종료되었습니다.")
## link 상태변경 함수
def changeStatus(self, selected):
# 필드 이름으로 필드 인덱스 구하는 법
# layer.fields().indexFromName('status')
# https://docs.qgis.org/3.10/en/docs/pyqgis_developer_cookbook/vector.html#modifying-vector-layers
## update an attribute with given field index (int) to a given value
# fieldIndex =1
# value ='My new name'
# layer.changeAttributeValue(fid, fieldIndex, value)
# status 필드의 필드 인덱스 : 3
fieldIndex = 3
for i in selected:
try:
with edit(self.link_layer):
# 선택된 피쳐의 status가 0(auto입력)이면 1(check complete)로 수정한다.
if self.link_layer.getFeature(i)[3] == 0:
self.link_layer.changeAttributeValue(i, fieldIndex, 1)
print("link id: ", i, ", status: ", self.link_layer.getFeature(i)[3])
except KeyError:
pass
except Exception as err:
print(repr(err))
## 기존에 선택됐던 피쳐 선택 취소하기 위한 deselect action trigger 함수
# https://gis.stackexchange.com/questions/155709/where-is-the-qgis-api-action-for-deselect
def deselectAll(self):
# for a in iface.attributesToolBar().actions():
# if a.objectName() == 'mActionDeselectAll':
# a.trigger()
# break
# deselect함수 수정
# https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html#selecting-features
# To clear the selection:
self.node_layer.removeSelection()
self.link_layer.removeSelection()
## Original Run method
"""
def run(self):
"Run method that loads and starts the plugin"
if not self.pluginIsActive:
self.pluginIsActive = True
print("** STARTING Node2Link")
# dockwidget may not exist if:
# first run of plugin
# removed on close (see self.onClosePlugin method)
if self.dockwidget == None:
# Create the dockwidget (after translation) and keep reference
self.dockwidget = Node2LinkDockWidget()
# connect to provide cleanup on closing of dockwidget
self.dockwidget.closingPlugin.connect(self.onClosePlugin)
# show the dockwidget
# TODO: fix to allow choice of dock location
self.iface.addDockWidget(Qt.TopDockWidgetArea, self.dockwidget)
self.dockwidget.show()
## # dock위젯 사용할 경우, 버튼에 함수 binding
## self.dockwidget.modify.clicked.connect(self.test)
## self.dockwidget.sync.clicked.connect(self.test)
"""
## 파이썬 콘솔창에서 layer id 구하는 방법
"""
layers = QgsProject.instance().mapLayersByName('alley_node')
layers[0].id()
'alley_node_0cec2e3f_5398_4336_8273_93e30c501d55'
"""
# commit
# self.link_layer.commitChanges()
# iface.vectorLayerTools().stopEditing(self.link_layer)
# change geometry
# # set new geometry (QgsGeometry instance) for a feature
# geometry = QgsGeometry.fromPolyline([QgsPoint(frGeom.asPoint()), QgsPoint(toGeom.asPoint())])
# layer.changeGeometry(fid, geometry)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 14 14:30:34 2020
@author: Hal
"""
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
def read_responses():
"""Get results from spreadsheet
"""
SPREADSHEET_ID = 'CENSORED'
RANGE_NAME = "Form responses 1!A2:ZZZ"
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute()
values = result.get('values', [])
res = []
for row in values:
if (not row) or (row[1] == ""):
pass
else:
res.append(row)
return res
def delete_responses(finalidx=20):
if finalidx == 1:
print("Nothing to delete, exited early")
return
"""
Deletes all current responses
"""
SPREADSHEET_ID = 'CENSORED'
#SHEET_ID = "Form responses 1"
SHEET_ID = 604944233
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
body = {"requests": [
{
"deleteDimension": {
"range": {
"sheetId": SHEET_ID,
"dimension": "ROWS",
"startIndex": 1,
"endIndex": finalidx
}
}
}
]
}
response = service.spreadsheets().batchUpdate(spreadsheetId=SPREADSHEET_ID, body=body).execute()
return response
|
import glob
import os
from pathlib import Path
import joblib
import pandas as pd
from tqdm import tqdm
def save_concat_karte(kartes_path, all_karte_path):
kartes = glob.glob(kartes_path)
karte_list = list()
for karte in kartes:
karte_data = pd.read_excel(karte)
if len(karte_data.columns) >= 10:
karte_data = karte_data.rename(columns={
'検査プライマリ': 'primary',
'患者ID': 'patient_id',
'質的診断': 'data_label'})
karte_list.append(karte_data)
all_karte = pd.concat(karte_list, sort=False)
print(all_karte['patient_id'])
all_karte = all_karte.dropna(subset=['primary']).astype({'primary': int})
all_karte = all_karte.drop_duplicates(keep='first')
print(all_karte.info())
with open(all_karte_path, mode="wb") as f:
joblib.dump(all_karte, f, compress=3)
def save_primary_patient_id_dict(all_karte_path, primary_patient_id_path):
with open(all_karte_path, mode="rb") as f:
all_karte = joblib.load(f)
all_karte = all_karte[['data_label', 'primary', 'patient_id']]
primary = None
primary_patient_id_dict = dict()
for karte in all_karte.itertuples():
if primary is None or primary != karte.primary:
if primary is not None:
if primary in primary_patient_id_dict.keys():
assert primary_patient_id_dict[primary] == karte.patient_id
else:
if karte.patient_id is not None:
primary_patient_id_dict[primary] = str(karte.patient_id)
primary = karte.primary
else:
if primary is not None:
if primary in primary_patient_id_dict.keys():
assert primary_patient_id_dict[primary] == str(karte.patient_id)
else:
if karte.patient_id is not None:
primary_patient_id_dict[primary] = str(karte.patient_id)
with open(primary_patient_id_path, mode="wb") as f:
joblib.dump(primary_patient_id_dict, f, compress=3)
return primary_patient_id_dict
def save_primary_images_dict(images_path, primary_images_path):
images = glob.iglob(images_path, recursive=True)
primary_images_dict = dict()
for image in tqdm(images):
if os.stat(image).st_size == 0:
continue
primary = int(image.split("/")[-2])
if primary in primary_images_dict.keys():
primary_images_dict[primary].append(image)
else:
primary_images_dict[primary] = [image]
primary_images_dict = {i: sorted(list(set(j))) for i, j in primary_images_dict.items()}
with open(primary_images_path, mode="wb") as f:
joblib.dump(primary_images_dict, f, compress=3)
return primary_images_dict
def save_exited_patient(primary_patient_id_dict, primary_images_dict, existed_patient_path):
existed_patient_list = list()
for target_patient in primary_images_dict.keys():
if target_patient in primary_patient_id_dict.keys():
existed_patient_list.append(primary_patient_id_dict[target_patient])
with open(existed_patient_path, mode="wb") as f:
joblib.dump(existed_patient_list, f, compress=3)
print(existed_patient_list)
print(len(existed_patient_list))
def get_existed_patient(dataset_name):
file_path = Path(__file__)
data_path = (file_path / '..' / '..' / 'data').resolve()
kartes_path = str(data_path / '*' / '*.xlsx')
datasets_path = (file_path / '..' / '..' / 'datasets').resolve()
dataset_path = datasets_path / dataset_name
os.makedirs(dataset_path, exist_ok=True)
all_karte_path = str(dataset_path / 'all_karte.joblib')
save_concat_karte(kartes_path, all_karte_path)
primary_patient_id_path = str(dataset_path / 'primary_patient_id.joblib')
primary_patient_id_dict = save_primary_patient_id_dict(all_karte_path, primary_patient_id_path)
images_path = str(data_path / '**' / '[0-1][0-9]' / '[0-3][0-9]' / '*' / '*')
primary_images_path = str(dataset_path / 'primary_images.joblib')
primary_images_dict = save_primary_images_dict(images_path, primary_images_path)
exited_patient_path = str(dataset_path / 'existed_patient.joblib')
save_exited_patient(primary_patient_id_dict, primary_images_dict, exited_patient_path)
def save_removed_patient_csv(dataset_name, data_name):
file_path = Path(__file__)
datasets_path = (file_path / '..' / '..' / 'datasets').resolve()
dataset_path = datasets_path / dataset_name
exited_patient_path = str(dataset_path / 'existed_patient.joblib')
with open(exited_patient_path, mode="rb") as f:
exited_patient_list = joblib.load(f)
data_path = (file_path / '..' / '..' / 'data').resolve()
csv_path = str(data_path / data_name / '*.csv')
csv_files = glob.glob(csv_path)
for csv_file in csv_files:
original_csv_file = csv_file[:-4] + '_original' + csv_file[-4:]
os.rename(csv_file, original_csv_file)
csv_data = pd.read_csv(original_csv_file, encoding='shift_jis')
print(csv_data)
drop_index_list = list()
for csv_row in csv_data.itertuples():
if str(csv_row[1]) in exited_patient_list:
drop_index_list.append(csv_row[0])
new_csv_data = csv_data.drop(csv_data.index[drop_index_list])
print(new_csv_data)
new_csv_data.to_csv(csv_file, index=False, encoding='shift_jis')
if __name__ == "__main__":
# get_existed_patient('patient_check')
save_removed_patient_csv('patient_check', 'existed_patient_check')
|
a="jggjkh"
print(a)
|
import cs50
import sys
def main():
# checking if command line is acceptable.
if len(sys.argv) != 2:
print("Missing command-line argument.")
exit(1)
# Insert Key
key = int(sys.argv[1])
print("plaintext: ", end = "")
plaintext = cs50.get_string()
# Print out cypher-text
print("ciphertext: ", end = "")
for c in plaintext:
if (c.islower()):
#(c + key) % 26
print(chr((ord(c) - ord('a') + key) % 26 + ord('a')) , end = "")
elif (c.isupper()):
print(chr((ord(c) - ord('A') + key) % 26 + ord('A')) , end = "")
else:
print(c , end = "")
print()
if __name__ == "__main__":
main()
|
/Users/samnayrouz/anaconda3/lib/python3.6/base64.py
|
from collections import defaultdict
file = "Day1/frequency.txt"
sum = 0
# for storing the frequency changes from the file
freqchanges = []
# for keeping track of the current frequency
values = defaultdict(lambda:-1)
# Reads the file
f = open(file,'r')
while True:
line = f.readline()
if not line:
break
freqchanges.append(int(line.strip()))
# First loops through to get sum of frequency changes in text file, then loops until a frequency is repeated
index = 0
values[0]=1
firstLoop=True
while True:
sum+=freqchanges[index]
if values[sum]>0:
break
values[sum]=1
index = index + 1
if index == len(freqchanges):
if firstLoop:
print('Part 1, sum = %d' % sum)
firstLoop=False
index = 0
print('Part 2, first repeated frequency is %d' % sum)
|
from django.contrib import admin
from django.urls import reverse
from django.utils.safestring import mark_safe
from .models import Post, Category, Tag
# Register your models here.
class PostAdmin(admin.ModelAdmin):
list_display = ('get_title', 'get_name', 'publication_date', 'is_published', 'get_categories', 'get_image')
list_display_links = ('get_title', 'get_image')
search_fields = ('meta_title', 'post_content')
filter_horizontal = ('post_tag',)
list_editable = ('is_published',)
list_per_page = 25
def view_on_site(self, obj):
# adds link to view from django admin object
url = reverse('posts:post_preview', kwargs={'post_id': obj.pk,
'post_slug': obj.post_slug})
return url
def get_categories(self, obj):
# loop through and dsiplay category names
return ', '.join([c.category_name for c in obj.post_category.all()])
def get_image(self, obj):
# show image in object grid
if obj.featured_image:
# must check if object exists otherwise throws an error
# mark_safe() used to display html
return mark_safe('<img src="{thumb}" width="100" />'.format(thumb=obj.featured_image.url,))
else:
return 'No image available'
def get_title(self, obj):
# method foundation for user friendly title name in list display
if obj.meta_title:
return obj.meta_title
else:
return 'No title available'
def get_name(self, obj):
# user friendly author name display
return '%s %s' % (obj.author.first_name, obj.author.last_name)
get_image.allow_tags = True
# user friendly names in list display
get_categories.short_description = 'Categories'
get_image.short_description = 'Featured Image'
get_title.short_description = 'Title'
get_name.short_description = 'Author'
class CategoryAdmin(admin.ModelAdmin):
list_display = ('category_name', 'is_published', 'get_image', 'get_posts')
list_display_links = ('category_name', 'get_image')
list_editable = ('is_published',)
list_per_page = 10
def get_image(self, obj):
# show image in object grid
if obj.category_image:
# must check if object exists otherwise throws an error
# mark_safe() used to display html
return mark_safe('<img src="{thumb}" width="100" />'.format(thumb=obj.category_image.url,))
else:
return 'No image available'
def get_posts(self, obj):
# gets number of posts in category
return Post.objects.filter(post_category__pk=obj.pk).count()
# user friendly names in list display
get_image.short_description = 'Featured Image'
get_posts.short_description = '# of posts'
class TagAdmin(admin.ModelAdmin):
list_display = ('tag_name', 'get_posts')
list_display_links = ('tag_name',)
list_per_page = 25
def get_posts(self, obj):
# gets number of posts in category
return Post.objects.filter(post_tag__pk=obj.pk).count()
# user friendly names in list display
get_posts.short_description = '# of posts'
admin.site.register(Post, PostAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Tag, TagAdmin)
|
from ..bepasty_xstatic import serve_files
from flask import send_from_directory
from werkzeug.exceptions import NotFound
from . import blueprint
@blueprint.route('/xstatic/<name>', defaults=dict(filename=''))
@blueprint.route('/xstatic/<name>/<path:filename>')
def xstatic(name, filename):
"""Route to serve the xstatic files (from serve_files)"""
try:
base_path = serve_files[name]
except KeyError:
raise NotFound()
if not filename:
raise NotFound()
return send_from_directory(base_path, filename)
|
#!/usr/bin/env python
from __future__ import print_function
import liblo, sys
# send all messages to port 4242 on the local machine
def oscsend(path,val):
port = 4242
target = liblo.Address(port)
msg = liblo.Message('/spot'+path)
msg.add(val)
liblo.send(target,msg)
|
from django.urls import path, include, re_path
from api.endpoint import email_view
urlpatterns = [
re_path(r'invitation', email_view.InvitationView.as_view()),
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-04-14 22:04:53
# @Author : Fallen (xdd043@qq.com)
# @Link : https://github.com/fallencrasher/python-learning
# @Version : $Id$
'''
测试自定义模块的导入
'''
import a
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 12 17:45:15 2020
@author: Joe
"""
import wx
import ukbiobank
class M_AM_B(wx.Frame, ukbiobank.ukbio):
pass
class SelectIllnessFrame(wx.Frame, ukbiobank.ukbio):
__metaclass__ = M_AM_B
def __init__(self, parent, ukb):
super().__init__(parent=parent, title="Select Illness", size=wx.DefaultSize)
# Create a panel and notebook (tabs holder)
p = wx.Panel(self)
nb = wx.Notebook(p)
# Set noteboook in a sizer to create the layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(nb, 1, wx.EXPAND)
# Create the tab windows
self.tab1 = Tab(nb, ukb, diagnosisType="self")
self.tab2 = Tab(nb, ukb, diagnosisType="ICD9")
self.tab3 = Tab(nb, ukb, diagnosisType="ICD10")
# Add the windows to tabs and name them.
nb.AddPage(self.tab1, "Self-Reported Non-Cancer Illnesses")
nb.AddPage(self.tab2, "ICD 9 Main Diagnosis")
nb.AddPage(self.tab3, "ICD 10 Main Diagnosis")
# Submit button
submit = wx.Button(p, label="Submit")
submit.Bind(wx.EVT_BUTTON, lambda evt, ukb=ukb: self.submit(evt, parent, ukb))
sizer.Add(submit, 1, wx.EXPAND)
p.SetSizer(sizer)
self.Show()
# set selections
def submit(self, event, parent, ukb):
self_reported = list(self.tab1.getSelections())
icd9 = list(self.tab2.getSelections())
icd10 = list(self.tab3.getSelections())
selections = {}
# Selections are saved as a key value pair whereby:
# key: ukbiobank field ID (correspinding to self-report/icd9/icd10 column)
# values: selected illnessess
# TODO: Include 'Secondary diagnoses', cancer illnesses, cause of death etc etc...
selections["include_illnesses"] = {
"Non-cancer illness code, self-reported": self_reported,
"Diagnoses - main ICD9": icd9,
"Diagnoses - ICD10": icd10,
}
selections["include_illnesses_coded"] = {
20002: ukb.nonCancerIllnessCoding["coding"][
ukb.nonCancerIllnessCoding["meaning"].isin(self_reported)
].tolist(),
41203: ukb.icd9Coding["coding"][
ukb.icd9Coding["meaning"].isin(icd9)
].tolist(),
41270: ukb.icd10Coding["coding"][
ukb.icd10Coding["meaning"].isin(icd10)
].tolist(),
}
# Setting selections, passing through parent MenuFrame
parent.selectionsSetter(arg1=selections)
self.Hide()
return
# Define the tab content as classes (in this case each tab will have the same structure so base 'Tab' class will suffice)
class Tab(wx.Panel, ukbiobank.ukbio):
def __init__(self, parent, ukb, diagnosisType):
wx.Panel.__init__(self, parent)
# wx.StaticText(self, -1, "This is the first tab", (20,20))
p = wx.Panel(self)
my_sizer = wx.BoxSizer(wx.VERTICAL)
if diagnosisType == "self":
# Getting list of illnesses
df = ukb.nonCancerIllnessCoding
illness_list = (
df.loc[(df["coding"] != -1) & (df["coding"] != 99999), "meaning"]
).tolist()
illness_list.sort()
elif diagnosisType == "ICD9":
illness_list = ukb.icd9Coding.meaning.tolist()
elif diagnosisType == "ICD10":
illness_list = ukb.icd10Coding.meaning.tolist()
# Variables checkbox
self.checkbox = wx.CheckListBox(self, choices=illness_list)
my_sizer.Add(self.checkbox, 1, wx.EXPAND)
p.SetSizer(my_sizer)
def getSelections(self):
return self.checkbox.GetCheckedStrings()
|
__author__ = 'Justin'
def pathSimilarity(pathA,pathB):
num_same_nodes = 0
for node in pathA:
if node in pathB:
num_same_nodes += 1
percentage = num_same_nodes/max(len(pathA),len(pathB))
return percentage
|
''' Application wide properties.
.. REVIEWED 11 November 2018
This module defines a singleton that hides some application-wide properties.
As any singleton, any instantiation returns always the same object.
This one specifically re-routes the ``__init__`` method to ensure that all variables
are only updated at the first instantiation and are never changed again.
The attributes are only accessible with getters and there are no setters.
'''
import logging
import os.path
import argparse
import json
from mqttgateway.init_logger import initloghandlers
from mqttgateway.load_config import loadconfig
DEFAULT_CONF_FILENAME = u'default.conf'
class AppProperties(object):
''' Singleton holding application properties.'''
def __new__(cls, *args, **kwargs):
# pylint: disable=protected-access
if not hasattr(cls, 'instance'):
#cls.instance = super(AppProperties, cls).__new__(cls, *args, **kwargs) # not for py3
cls.instance = super(AppProperties, cls).__new__(cls)
cls.instance._init_pointer = cls.instance._init_properties
else:
cls.instance._init_pointer = cls.instance._dummy
# pylint: enable=protected-access
return cls.instance
def __init__(self, *args, **kwargs):
# pylint: disable=no-self-use
self._init_pointer(*args, **kwargs)
# pylint: enable=no-self-use
return
def _dummy(self, *args, **kwargs):
# pylint: disable=unused-argument, no-self-use
''' Method that does nothing.'''
# pylint: enable=unused-argument, no-self-use
return
def _init_properties(self, app_path, app_name=None, parse_dict=None):
''' Initialisation of the properties.
This is effectively the constructor of the class.
At first instantiation of this singleton, the ``__init__`` method points to
this method.
For the following instantiations, the ``__init__`` method points to
the ``_dummy`` function.
Args:
app_path (string): the full path of the launching script, including filename
app_name (string): the application name if different from the filename
parse_dict (dict): not implemented
'''
# Define some default directories used throughout
script_dir = os.path.realpath(os.path.dirname(app_path)) # full path of app_path
current_working_dir = os.getcwd()
self._directories = (current_working_dir, script_dir)
# Compute app_name from app_path, if not available
if not app_name:
app_name = os.path.splitext(os.path.basename(app_path))[0] # filename without extension
self._name = app_name
# Configure the parser for the command line arguments
parser = argparse.ArgumentParser(description=self._name)
parser.add_argument('-c', '--conf', help='provide the path to the configuration file',
dest='config_file', default='')
# Add the user arguments to the parser, if any
if parse_dict:
# TODO: to implement
pass
# Process the command line arguments
self._cmdline_args = parser.parse_args()
# Find and process configuration file. default.conf should be in the same dir as this file
self._config = None
config_file_path = self.get_path(self._cmdline_args.config_file.strip(),
extension='.conf',
dft_name=self._name,
dft_dirs=self._directories)
default_config_path = os.path.join(os.path.dirname(__file__), DEFAULT_CONF_FILENAME)
self._config = self.load_config(default_config_path, config_file_path)
# In this case add the configuration file directory as a default directory as well
config_file_dir = os.path.dirname(config_file_path)
self._directories = (config_file_dir, current_working_dir, script_dir)
# Declare log attributes
self._log_handlers = []
self._loggers = []
def get_path(self, path_given, extension=None, dft_name=None, dft_dirs=None):
''' Returns the absolute path of a file based on defined rules.
The rules are:
- the default name is ``dft_name`` + ``extension``;
- the default directories are provided by the ``dft_dirs`` argument;
- file paths can be directory only (ends with a ``/``) and are appended with the default name;
- file paths can be absolute or relative; absolute start with a ``/`` and
relative are prepended with the default directory;
- file paths can be file only (no ``/`` whatsoever) and are prepended with the default directory;
- use forward slashes ``/`` in all cases, it should work even for Windows systems;
- however for Windows systems, use of the drive letter might be an issue and has not been tested.
Currently this method could return a path to a file that does not exist, if a
file corresponding to the rules is not found.
Args:
path_given (string): any type pf path; see rules
extension (string): the default extension of the file
dft_name (string): the default name to be used, usually the application name
dft_dirs (list of strings): the default directories where to look for the file
Returns:
string: the full path of the file found.
'''
if dft_name is None: dft_name = self._name
if dft_dirs is None: dft_dirs = self._directories
if not extension: extension = ''
elif extension[0] != '.': extension = '.' + extension
if not path_given or path_given == '.': path_given = './'
if path_given == '..': path_given = '../'
dirname, filename = os.path.split(path_given.strip())
if filename == '': filename = ''.join((dft_name, extension)) # default name
dirname = os.path.normpath(dirname) # not sure it is necessary
if os.path.isabs(dirname):
return os.path.normpath(os.path.join(dirname, filename))
else: # dirname is relative
paths = [os.path.normpath(os.path.join(pth, dirname, filename)) for pth in dft_dirs]
for pth in paths:
if os.path.exists(pth): return pth
return paths[0] # even if it will fail, return the first path in the list
def get_file(self, path_given, extension=None, dft_name=None, dft_dirs=None):
''' Returns the content of the file defined by the arguments.
This method uses the :py:meth:`get_path`
to determine the file sought.
All the usual exceptions are raised in case of problems.
It is assumed the content of the file is text and that the size is small
enough to be returned at once.
The arguments are the same as :py:meth:`get_path`.
Args:
path_given (string): any type pf path; see rules
extension (string): the default extension of the file
dft_name (string): the default name to be used, usually the application name
dft_dirs (list of strings): the default directories where to look for the file
Returns:
string: the full content of the file.
'''
file_path = self.get_path(path_given, extension, dft_name, dft_dirs)
with open(file_path, 'r') as file_handler:
file_data = file_handler.read()
return file_data
def get_jsonfile(self, path_given, extension=None, dft_name=None, dft_dirs=None):
''' Returns a dictionary with the content of the JSON file defined by the arguments.
This method uses the :py:meth:`get_path`
to determine the file sought.
All the usual exceptions are raised in case of problems.
The arguments are the same as :py:meth:`get_path`.
Args:
path_given (string): any type pf path; see rules
extension (string): the default extension of the file
dft_name (string): the default name to be used, usually the application name
dft_dirs (list of strings): the default directories where to look for the file
Returns:
dict: the content of the JSON file in dictionary format.
'''
file_path = self.get_path(path_given, extension, dft_name, dft_dirs)
with open(file_path, 'r') as file_handler:
json_dict = json.load(file_handler)
return json_dict
def load_config(self, cfg_dflt_string, cfg_filepath):
# pylint: disable=no-self-use
''' See :py:meth:`loadconfig <mqttgateway.load_config.loadconfig>` for documentation.'''
# pylint: enable=no-self-use
return loadconfig(cfg_dflt_string, cfg_filepath)
def init_log_handlers(self, log_data):
''' Creates new handlers from log_data and add the new ones to the log handlers list.
Also updates the registered loggers with the newly created handlers.
See method :py:meth:`initloghandlers <mqttgateway.init_logger.initloghandlers>`
for documentation on log_data format.
Args:
log_data (string): see related doc for more info.
Returns:
string: a message indicating what has been done, to be potentially logged.
'''
log_handlers_list, msg = initloghandlers(log_data)
for handler in log_handlers_list:
if handler not in self._log_handlers:
self._log_handlers.append(handler)
for logger in self._loggers:
if handler not in logger.handlers:
logger.addHandler(handler)
return msg # TODO: the message will be incorrect if there are duplicate handlers.
def register_logger(self, logger):
''' Register the logger and add the existing handlers to it.
Call this method to add the logger in the registry held
in :py:class:`AppProperties <mqttgateway.app_properties.AppProperties>`.
Doing so, the logger will inherit all the pre-defined handlers.
Args:
logger (`logging.Logger` object): the logger to register
'''
if logger not in self._loggers:
logger.setLevel(logging.DEBUG)
self._loggers.append(logger)
for handler in self._log_handlers:
if handler not in logger.handlers:
logger.addHandler(handler)
return
def get_name(self):
''' Name getter.
Returns:
string: the name of the application.
'''
return self._name
def get_directories(self):
''' Directories getter.
The relevant directories of the application are computed and stored at once
at the launch of the application. If they have been deleted, moved or their name
is changed while the application is running, they will not be valid anymore.
The relevant directories are the current working directory, the directory of
the launching script and the directory where the configuration file was found
(which could be different from the first 2 because of the option to provide it in
the command line).
Returns:
list: a list of full paths of relevant directories for the application.
'''
return self._directories
def get_cmdline_args(self):
''' Command line arguments getter.
Returns:
dict: the dictionary returned by ``parser.parse_args()``.
'''
return self._cmdline_args
def get_config(self):
''' Configuration getter.
Returns:
dict: the dictionary returned by ``ConfigParser.RawConfigParser()``
'''
return self._config
if __name__ == '__main__':
pass
|
from docxtpl import DocxTemplate,RichText
ds = DocxTemplate('word1.docx')
context = {'sb' : RichText("林康琪",color='FF0000',bold=True,underline=True,size=40,font="Simson"),"SB":"林son"}
ds.render(context)
ds.save("SB.docx")
|
import sys
mybook = open("file1.txt")
dictionary = {}
for lines in mybook:
word_list = lines.split()
for word in word_list:
letter = word[0]
letter = letter.upper()
if letter in dictionary.keys():
dictionary[letter]+=1
else:
dictionary[letter]=1
mybook.close()
outfile = open("file2.txt","r+")
key_list = list(dictionary.keys())
key_list.sort()
newprint = ""
finalprint = ""
for key in key_list:
newprint = "The number of words starting with " + str(key) + " is "
if newprint in outfile:
newprint += str(dictionary[key]) + ".\n"
outfile.write(newprint)
newprint = ""
else:
finalprint = "The number of words starting with " + str(key)+ " is "
finalprint += str(dictionary[key]) + ".\n"
outfile.write(finalprint)
finalprint = ""
outfile.close()
|
# ======================
# Create annual median composites
# ======================
import ee
def addDate(image):
'''
Function to add date to imagery
'''
date = ee.Date(image.get('system:time_start'))
dateString = date.format('YYYY-MM-dd')
return image.set('date', dateString)
def median_composite(imageCollection):
'''
Creates yearly median composites from image collection.
Args:
imageCollection (ee.ImageCollection): image collection to create yearly median composites from
Returns:
medianComp (ee.ImageCollection): image collection of yearly median composites
'''
# group images by year by first adding a new 'year' property
imageCollection_withyear = imageCollection.map(lambda img : img.set('year', img.date().get('year')))
distinct_imageCollection_withyear = imageCollection_withyear.distinct('year')
filter = ee.Filter.equals(leftField='year', rightField='year')
join = ee.Join.saveAll('year_matches')
join_imgCol = ee.ImageCollection(join.apply(distinct_imageCollection_withyear, imageCollection_withyear, filter))
def medianReduction(img):
'''
Function to apply median reduction among matching year collections for an ee.imageCollection
'''
yearLS = ee.ImageCollection.fromImages(img.get('year_matches'))
return yearLS.reduce(ee.Reducer.median()).set('system:time_start',
img.date().update(month=6, day=1)).set('year',
img.date().get('year'))
medianComp = join_imgCol.map(medianReduction)
# sort medianComp to get in date order
medianComp = medianComp.sort('system:time_start')
return medianComp
# # group images by year by first adding a new 'year' property
# growing_LS = growing_LS.map(lambda img : img.set('year', img.date().get('year')))
# distinctYearLS = growing_LS.distinct('year')
# filter = ee.Filter.equals(leftField='year', rightField='year')
# join = ee.Join.saveAll('year_matches')
# joinLS = ee.ImageCollection(join.apply(distinctYearLS, growing_LS, filter))
# def medianReduction(img):
# """Function to apply median reduction among matching year collections for an ee.imageCollectio"""
# yearLS = ee.ImageCollection.fromImages(img.get('year_matches'))
# return yearLS.reduce(ee.Reducer.median()).set('system:time_start',
# img.date().update(month=6, day=1)).set('year',
# img.date().get('year'))
# medianComp = joinLS.map(medianReduction)
# # sort medianComp to get in date order
# medianComp = medianComp.sort('system:time_start')
# # print(medianComp.size().getInfo())
|
from pathlib import Path
import iprPy
for name, CalcClass in iprPy.calculation.loaded.items():
calc = CalcClass()
print(name)
infilename = Path(calc.directory, f'calc_{name}.in')
emptydict = {}
for key in calc.allkeys:
emptydict[key] = ''
with open(infilename, 'w') as infile:
infile.write(iprPy.tools.filltemplate(calc.template, emptydict, '<', '>'))
|
#!/usr/bin/env python
# python3 predict.py
# from pathlib import Path
# import numpy as np
# from PIL import Image
# from keras.models import load_model
# import sys
# sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
# from __future__ import print_function
#Image_checker
import roslib
# roslib.load_manifest('my_package')
import sys
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Empty
#Cnn_classifier
import numpy as np
import tensorflow as tf
from keras.models import load_model
#cv2
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
import cv2
def image_to_numpy(msg):
if not msg.encoding == "bgr8":
raise TypeError('Unrecognized encoding {}'.format(msg.encoding))
dtype_class = np.uint8
channels = 3
dtype = np.dtype(dtype_class)
dtype = dtype.newbyteorder('>' if msg.is_bigendian else '<')
shape = (msg.height, msg.width, channels)
data = np.fromstring(msg.data, dtype=dtype).reshape(shape)
data.strides = (
msg.step,
dtype.itemsize * channels,
dtype.itemsize
)
if channels == 1:
data = data[...,0]
data = data / 255.0
return data
class Image_checker:
def __init__(self):
self.positive_pub = rospy.Publisher("/result/positive", Empty, queue_size=10)
self.negative_pub = rospy.Publisher("/result/negative", Empty, queue_size=10)
self.msg_sub = rospy.Subscriber("/pf_score/image", Image, self.callback)
# 事前に適当に呼び出しておく
X = np.zeros((1, 21, 21, 3))
model_path = "../model/learning-image.h5"
self.model = load_model(model_path)
self.model.predict(X)
# print("a",model)
print('image_predict start')
def callback(self, data):
image_np = image_to_numpy(data)
image_np = image_np[:, :, ::-1]
image_np = [image_np]
image_np = np.asarray(image_np)
predicted = self.model.predict_classes(image_np)
probas = self.model.predict_proba(image_np)
if predicted[0] == 1:
for proba in probas:
proba_ = max(proba)
# print("\033[1;32m This is positive\033[0m\r", end="")
print("\033[1;32m This is positive\033[0m", proba_)
self.positive_pub.publish(Empty())
else:
for proba in probas:
proba_ = min(proba)
# print("\033[1;31m This is negative\033[0m\r", end="")
print("\033[1;31m This is negative\033[0m", proba_)
# self.positive_pub.publish(Empty())
self.negative_pub.publish(Empty())
# print(image_np.shape)
# def image_to_numpy(self, msg):
# if not msg.encoding == "bgr8":
# raise TypeError('Unrecognized encoding {}'.format(msg.encoding))
# dtype_class = np.uint8
# channels = 3
# dtype = np.dtype(dtype_class)
# dtype = dtype.newbyteorder('>' if msg.is_bigendian else '<')
# shape = (msg.height, msg.width, channels)
# data = np.fromstring(msg.data, dtype=dtype).reshape(shape)
# data.strides = (
# msg.step,
# dtype.itemsize * channels,
# dtype.itemsize
# )
# if channels == 1:
# data = data[...,0]
# return data
def main(args):
ic = Image_checker()
rospy.init_node('node_estimate_checker.py', anonymous=True)
print("node_estimate_checker")
print("\033[2J")
try:
rospy.spin()
except KeyboardInterrupt:
print("Shut down")
if __name__ == '__main__':
main(sys.argv)
|
from troposphere import (
Parameter,
Ref,
Template,
Condition,
Equals,
And,
Or,
Not,
If,
Sub
)
from troposphere.codepipeline import (
Pipeline,
Stages,
Actions,
ActionTypeId,
OutputArtifacts,
InputArtifacts,
ArtifactStore,
DisableInboundStageTransitions
)
from troposphere.sns import (
Topic
)
from troposphere.cloudformation import (
CustomResource
)
t = Template()
t.set_version("2010-09-09")
t.set_description("""
(qs-1ph8nehb7)
Serverless CICD Quick Start
Codepipeline shared resources and security
""")
PipelineParam = {
"AppName": t.add_parameter(
Parameter(
"AppName",
Description="Application name, used for the repository and child stack name",
Type="String",
Default="Sample"
)
),
"BuildImageName": t.add_parameter(
Parameter(
"BuildImageName",
Description="Docker image for application build",
Type="String",
Default="aws/codebuild/nodejs:10.1.0"
)
),
"DevAwsAccountId": t.add_parameter(
Parameter(
"DevAwsAccountId",
Description="AWS account ID for development account",
Type="String",
AllowedPattern="(\\d{12}|^$)",
ConstraintDescription="Must be an AWS account ID",
Default="159527342995"
)
),
"ProdAwsAccountId": t.add_parameter(
Parameter(
"ProdAwsAccountId",
Description="AWS account ID for production account",
Type="String",
AllowedPattern="(\\d{12}|^$)",
ConstraintDescription="Must be an AWS account ID",
Default="159527342995"
)
),
"Branch": t.add_parameter(
Parameter(
"Branch",
Description="Repository branch name",
Type="String",
Default="master"
)
),
"Suffix": t.add_parameter(
Parameter(
"Suffix",
Description="Repository branch name (adapted to use in CloudFormation stack name)",
Type="String",
Default="master"
)
),
"ArtifactBucket": t.add_parameter(
Parameter(
"ArtifactBucket",
Description="Artifact S3 bucket",
Type="String"
)
),
"ArtifactBucketKeyArn": t.add_parameter(
Parameter(
"ArtifactBucketKeyArn",
Description="ARN of the artifact bucket KMS key",
Type="String",
)
),
"PipelineServiceRoleArn": t.add_parameter(
Parameter(
"PipelineServiceRoleArn",
Description="Pipeline service role ARN",
Type="String"
)
),
"SamTranslationBucket": t.add_parameter(
Parameter(
"SamTranslationBucket",
Description="S3 bucket for SAM translations",
Type="String"
)
),
"DynamicPipelineCleanupLambdaArn": t.add_parameter(
Parameter(
"DynamicPipelineCleanupLambdaArn",
Description="ARN of Lambda function to clean up dynamic pipeline",
Type="String",
)
),
"SecretArnDev": t.add_parameter(
Parameter(
"SecretArnDev",
Description="ARN for Secrets Manager secret for dev",
Type="String",
)
),
"SecretArnProd": t.add_parameter(
Parameter(
"SecretArnProd",
Description="ARN for Secrets Manager secret for production",
Type="String",
Default=""
)
),
"SecretsManagerKey": t.add_parameter(
Parameter(
"SecretsManagerKey",
Description="KMS key for the use of secrets across accounts",
Type="String"
)
),
}
conditions = {
"IsProdStage": Equals(
Ref("Branch"),
"master"
)
}
resources = {
"PipelineNotificationsTopic":
Topic(
"PipelineNotificationsTopic",
Condition="IsProdStage",
DisplayName=Sub("${AppName}-notifications-${AWS::Region}"),
),
"DynamicPipelineCleanupDev":
CustomResource(
"DynamicPipelineCleanupDev",
Version="1.0",
ServiceToken=Ref("DynamicPipelineCleanupLambdaArn"),
RoleArn=Sub("arn:aws:iam::${DevAwsAccountId}:role/CodePipelineServiceRole-${AWS::Region}-${"
"DevAwsAccountId}-dev"),
Region=Ref("AWS::Region"),
StackName=If("IsProdStage",
Sub("${AppName}-dev"),
Sub("${AppName}-dev-${Suffix}")
)
),
"DynamicPipelineCleanupProd":
CustomResource(
"DynamicPipelineCleanupProd",
Condition="IsProdStage",
Version="1.0",
ServiceToken=Ref("DynamicPipelineCleanupLambdaArn"),
RoleArn=Sub("arn:aws:iam::${DevAwsAccountId}:role/CodePipelineServiceRole-${AWS::Region}-${"
"DevAwsAccountId}-dev"),
Region=Ref("AWS::Region"),
StackName=Sub("${AppName}-prod")
),
"Pipeline":
Pipeline(
"Pipeline",
RoleArn=Ref("PipelineServiceRoleArn"),
Stages=[
Stages(
Name="Source",
Actions=[
Actions(
Name="CodeCommitSourceAction",
RunOrder=1,
ActionTypeId=ActionTypeId(
Category="Source",
Provider="CodeCommit",
Owner="AWS",
Version='1'
)
)
]
)
]
)
}
for c in conditions:
t.add_condition(c, conditions[c])
for r in resources.values():
t.add_resource(r)
print(t.to_yaml())
|
from os.path import join as j
tmp_dir = "/tmp/mot"
project_dir = "/home/mot"
data_dir = j(project_dir, "data")
experiment_dir = j(data_dir, "experiments")
training_dir = j(data_dir, "training")
model_dir = j(project_dir, "py", "lib", "models")
detection_threshold = 75
CPUs = 16
GPUs = 4
crop_size = 64
use_magic_pixel_segmentation = True
ms_metric_cal = 13.94736842
ms_rescale = 1 / 1
ms_detection_threshold = 0.75
ms_fps = 300.
ms_roi = ((950, 1450), (650, 1150))
|
import os
import yaml
# The purpose of this file is to load the yaml file in memory and pass it
# around to other module around.
config_path = os.environ.get('some shell variable if you want')
if config_path is None:
config = yaml.load(open(os.path.dirname(__file__) + '/../settings.yaml'))
else:
config = yaml.load(open(config_path))
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TP INGE 2 FOR PYTHON ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (Phone Book Project) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ due on March, 25, 2016 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ by Louise RAPILLY, Aurélien LABAUTE & Matthieu CLEMENT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class 2C1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ || VIEW FILE || ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Libraries imported
from PyQt5 import QtWidgets, QtCore, QtGui
class View(QtWidgets.QMainWindow):
"""Represent the data shown in the main window"""
def __init__(self, control, nom, app):
"""Constructor of View"""
super(View, self).__init__()
# Initialization of important variables:
self.control = control
self.app = app
self.tableOfContact = QtWidgets.QTreeWidget()
self.editBox = EditBox(self)
self.contactBox = ContactBox(self)
self.toolBar = QtWidgets.QToolBar()
self.searchBar = QtWidgets.QLineEdit()
self.mainWidget = QtWidgets.QWidget()
self.mainLayout = QtWidgets.QHBoxLayout()
self.isModified = False
# Function calls to create all the interface:
self.createAction()
self.createMenu()
self.createToolBar()
self.createTable()
# To set the design of the View:
self.setWindowTitle(nom)
self.setFixedSize(1000, 600)
self.mainLayout.addWidget(self.tableOfContact)
self.mainWidget.setLayout(self.mainLayout)
self.setCentralWidget(self.mainWidget)
self.searchBar.setStyleSheet("color: #1ED760;"
"background-color: #545454;"
"border: 1px solid #1ED760;"
"border-radius: 2px")
self.mainWidget.setStyleSheet("color: solid black;"
"background-color: #282828;"
"font-family: Comic sans MS, Arial, sans-serif")
self.tableOfContact.setAlternatingRowColors(True)
self.tableOfContact.setStyleSheet("color: #1ED760;"
"alternate-background-color: #545454;"
"font-family: Comic sans MS, Arial, sans-serif")
self.searchBar.setToolTip("Search Contact")
self.setCursor(QtGui.QCursor(QtGui.QPixmap(r"Images/mouse.png"),0.85,1.66))
self.setWindowIcon(QtGui.QIcon(r"Images/logopyqt.png"))
def beforeClose(self):
"""Function to ask the user to save before closing the program"""
if self.isModified:
ret = QtWidgets.QMessageBox.warning(self, "Warning !","The table has not been saved !\n"
"Do you want to save your changes before closing?",
QtWidgets.QMessageBox.Save |
QtWidgets.QMessageBox.Discard |
QtWidgets.QMessageBox.Cancel)
if ret == QtWidgets.QMessageBox.Save:
self.exportContacts()
return True
elif ret == QtWidgets.QMessageBox.Cancel:
return False
return True
def closeEvent(self, event):
"""Function called when we close a window"""
if self.beforeClose():
event.accept()
QtWidgets.QMainWindow.close(self)
self.app.quit()
else:
event.ignore()
def handleItemDoubleClicked(self):
"""Function called when we double click on an item"""
self.displayContact()
def handleItemSelected(self):
"""Function to change the color of selected items to see them better"""
for index in range(self.tableOfContact.topLevelItemCount()):
for column in range(7):
self.tableOfContact.topLevelItem(index).setForeground(column, QtGui.QBrush(QtGui.QColor(30, 215, 96)))
if self.tableOfContact.currentItem() is not None:
for column in range(7):
self.tableOfContact.currentItem().setForeground(column, QtGui.QBrush(QtGui.QColor(255,0,0)))
def indexOfCurrentElement(self):
"""Returns the the index of the current element"""
return self.tableOfContact.indexOfTopLevelItem(self.tableOfContact.currentItem())
def createAction(self):
"""Creates the actions"""
self.actionQuit = QtWidgets.QAction("&Quit", self) # Name
self.actionQuit.setShortcut(QtGui.QKeySequence.Close) # Shortcut
self.actionQuit.setIcon(QtGui.QIcon(r"Images/exit.png")) # Icon
self.actionNewContact = QtWidgets.QAction("&New Contact", self)
self.actionNewContact.setShortcut(QtGui.QKeySequence.New)
self.actionNewContact.setIcon(QtGui.QIcon(r"Images/newcontact.png"))
self.actionModContact = QtWidgets.QAction("&Modify Contact", self)
self.actionModContact.setShortcut(QtGui.QKeySequence.Replace)
self.actionModContact.setIcon(QtGui.QIcon(r"Images/modifycontact.png"))
self.actionDelContact = QtWidgets.QAction("&Delete Contact", self)
self.actionDelContact.setShortcut(QtGui.QKeySequence.Delete)
self.actionDelContact.setIcon(QtGui.QIcon(r"Images/deletecontact.png"))
self.actionImportFile = QtWidgets.QAction("&Open File", self)
self.actionImportFile.setShortcut(QtGui.QKeySequence.Open)
self.actionImportFile.setIcon(QtGui.QIcon(r"Images/open.png"))
self.actionExportFile = QtWidgets.QAction("&Save File", self)
self.actionExportFile.setShortcut(QtGui.QKeySequence.Save)
self.actionExportFile.setIcon(QtGui.QIcon(r"Images/save.png"))
self.actionDisplay = QtWidgets.QAction("Display &Contact", self)
self.actionDisplay.setIcon(QtGui.QIcon(r"Images/displaycontact.png"))
self.actionSearch = QtWidgets.QAction("Searc&h", self)
self.actionSearch.setShortcut(QtCore.Qt.Key_Return)
self.actionAbout = QtWidgets.QAction("&About", self)
self.actionAbout.setShortcut(QtGui.QKeySequence.HelpContents)
# Connections of the buttons:
self.actionQuit.triggered.connect(self.close)
self.actionNewContact.triggered.connect(self.newContact)
self.actionModContact.triggered.connect(self.modContact)
self.actionDelContact.triggered.connect(self.delContact)
self.actionExportFile.triggered.connect(self.exportContacts)
self.actionImportFile.triggered.connect(self.importContacts)
self.actionDisplay.triggered.connect(self.displayContact)
self.actionAbout.triggered.connect(self.app.aboutQt)
self.actionSearch.triggered.connect(self.searchContact)
self.searchBar.textChanged.connect(self.searchContact)
self.tableOfContact.itemSelectionChanged.connect(self.handleItemSelected)
self.tableOfContact.itemDoubleClicked.connect(self.handleItemDoubleClicked)
def createMenu(self):
"""Creates the menu and add the actions"""
self.menuFile = self.menuBar().addMenu("&File")
self.menuFile.addAction(self.actionQuit)
self.menuFile.addAction(self.actionImportFile)
self.menuFile.addAction(self.actionExportFile)
self.menuContacts = self.menuBar().addMenu("&Contact")
self.menuContacts.addAction(self.actionNewContact)
self.menuContacts.addAction(self.actionModContact)
self.menuContacts.addAction(self.actionDelContact)
self.menuContacts.addAction(self.actionDisplay)
self.menuHelp = self.menuBar().addMenu("&?")
self.menuHelp.addAction(self.actionAbout)
def createToolBar(self):
"""Creates the toolbar"""
self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) # Add it on top of the main window
spacer = QtWidgets.QWidget()
spacer.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.toolBar.addAction(self.actionNewContact)
self.toolBar.addAction(self.actionModContact)
self.toolBar.addAction(self.actionDelContact)
self.toolBar.addAction(self.actionDisplay)
self.toolBar.addSeparator()
self.toolBar.addAction(self.actionExportFile)
self.toolBar.addAction(self.actionImportFile)
self.toolBar.addSeparator()
self.toolBar.addWidget(self.searchBar)
self.toolBar.addWidget(spacer)
self.toolBar.addAction(self.actionQuit)
self.toolBar.setStyleSheet("color: black;"
"background-color: #545454")
def createTable(self):
"""Creates the the table containing the contacts"""
self.tableOfContact.setColumnCount(7)
self.listHeaderLabels = ["Family name", "First name",
"Telephone number", "Address",
"Postal code",
"City", "Mail"]
self.tableOfContact.setHeaderLabels(self.listHeaderLabels)
for i in range(7):
self.tableOfContact.setColumnWidth(i, 130)
def searchContact(self):
"""Function to search a contact in the list of contact"""
self.control.searchContact(self.searchBar.text())
def newContact(self):
"""Function to add a new contact to the list of contact"""
self.editBox.modification = False
self.editBox.show()
def modContact(self):
"""Function to modify a contact already registered"""
if self.tableOfContact.currentItem() is not None:
self.editBox.modification = True
self.editBox.show()
else:
QtWidgets.QMessageBox.information(self,"Information", "There isn't any selected contact to modify.")
def delContact(self):
"""Function to delete a contact"""
if self.tableOfContact.currentItem() is not None:
answer = QtWidgets.QMessageBox.question(self, "Warning !","Are you sure you want to delete this contact ?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
if answer == QtWidgets.QMessageBox.Yes:
if self.control.eraseContact(self.tableOfContact.currentItem()):
self.tableOfContact.takeTopLevelItem(self.indexOfCurrentElement())
QtWidgets.QMessageBox.information(self,"Information","The contact has been successfully deleted.")
self.isModified = True
else:
QtWidgets.QMessageBox.warning(self,"Warning ! ","There isn't any contact to delete!")
else:
QtWidgets.QMessageBox.information(self,"Information","The contact has not been deleted.")
else:
QtWidgets.QMessageBox.warning(self,"Warning !", "There isn't any selected contact to delete!")
def registerContact(self, modification):
"""Function to send the contact to control"""
if not modification:
self.control.registerContact(self.editBox.contact.clone())
else:
self.control.registerContact(self.editBox.contact.clone(), self.tableOfContact.currentItem())
self.sortContacts()
self.isModified = True
def exportContacts(self):
"""Function to save the contact list, send it to control"""
self.control.exportCSV()
def importContacts(self):
"""Function to add a list of contact from control"""
self.control.importCSV()
self.sortContacts()
def sortContacts(self):
"""Function to sort the list of contact by alphabetic order"""
self.tableOfContact.sortByColumn(0, QtCore.Qt.AscendingOrder)
def displayContact(self):
"""Function to call the Contact Box to display contact information"""
if (self.tableOfContact.currentItem() != None):
self.contactBox.show()
else:
QtWidgets.QMessageBox.information(self,"Information", "There isn't any selected contact to display.")
def clearAll(self):
"""Delete every contact"""
self.control.clearAll()
class EditBox(QtWidgets.QDialog):
""" Edit Interface for editing Class"""
def __init__(self, parent=None):
"""Contructor of EditBox"""
super(EditBox, self).__init__(None, QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowCloseButtonHint |
QtCore.Qt.WindowSystemMenuHint)
# Initialization of important variables:
self.view = parent
self.buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok |
QtWidgets.QDialogButtonBox.Cancel |
QtWidgets.QDialogButtonBox.Reset)
self.contact = QtWidgets.QTreeWidgetItem()
self.modification = False
self.mainLayout = QtWidgets.QVBoxLayout()
self.frameWidget = QtWidgets.QGroupBox("New Contact")
self.formLayout = QtWidgets.QFormLayout()
# To set each field to fill:
self.familyNameField = QtWidgets.QLineEdit()
familyNameFont = QtGui.QFont()
familyNameFont.setCapitalization(QtGui.QFont.AllUppercase)
self.familyNameField.setFont(familyNameFont)
self.familyNameField.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("[a-zA-Z\- ]*")))
self.firstNameField = QtWidgets.QLineEdit()
firstNameFont = QtGui.QFont()
firstNameFont.setCapitalization(QtGui.QFont.Capitalize)
self.firstNameField.setFont(firstNameFont)
self.firstNameField.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("[a-zA-Zà-ü\- ]*")))
self.numberField = QtWidgets.QLineEdit()
self.numberField.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("(00|\+)33[1-9][0-9]{8}|0[0-9]{9}")))
self.addressField = QtWidgets.QLineEdit()
self.addressField.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("[a-zA-Z0-9à-ü\- ]*")))
self.postalCodeField = QtWidgets.QLineEdit()
self.postalCodeField.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("[0-9]{5}")))
self.cityField = QtWidgets.QLineEdit()
self.cityField.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("[a-zA-Zà-ü\- ]*")))
self.mailField = QtWidgets.QLineEdit()
self.mailField.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("[a-zA-Z0-9\-_\.]*"
"@[a-zA-Z0-9\-_]*"
"\.[a-zA-Z]*")))
# To add each row to the form:
self.formLayout.addRow("Family &Name", self.familyNameField)
self.formLayout.addRow("&First Name", self.firstNameField)
self.formLayout.addRow("&Telephone Number", self.numberField)
self.formLayout.addRow("&Address", self.addressField)
self.formLayout.addRow("&Postal Code", self.postalCodeField)
self.formLayout.addRow("&City", self.cityField)
self.formLayout.addRow("&Mail", self.mailField)
self.frameWidget.setLayout(self.formLayout)
self.mainLayout.addWidget(self.frameWidget)
self.mainLayout.addWidget(self.buttonBox)
# For the design:
self.setLayout(self.mainLayout)
self.frameWidget.setStyleSheet( "border: 1px solid #1ED760;"
"border-radius: 2px;"
"margin-top: 5px;"
"padding: 2 3px")
self.setWindowTitle("Edit")
self.setStyleSheet("color: #ADAFB2;"
"background-color: #282828;"
"font-family: Verdana, Arial, sans-serif")
self.setFixedSize(500, 300)
self.setModal(True)
self.setCursor(QtGui.QCursor(QtGui.QPixmap(r"Images/mouse.png"),0.85,1.66))
# Connections for each buttons:
self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).clicked.connect(self.OKPressed)
self.buttonBox.button(QtWidgets.QDialogButtonBox.Reset).clicked.connect(self.clearForm)
self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).clicked.connect(self.hide)
def OKPressed(self):
"""Pick each elements of the form and send them to the View for registering"""
self.contact.setText(0, self.familyNameField.text().upper())
self.contact.setText(1, self.firstNameField.text().title())
self.contact.setText(2, self.numberField.text())
self.contact.setText(3, self.addressField.text())
self.contact.setText(4, self.postalCodeField.text())
self.contact.setText(5, self.cityField.text())
self.contact.setText(6, self.mailField.text().lower())
if not self.isEmpty():
self.view.registerContact(self.modification)
self.hide()
else:
QtWidgets.QMessageBox.warning(self,"Warning !","You can't register an empty contact!")
self.view.contactBox.updateContact()
def showEvent(self, QShowEvent):
"""Function called when the window is shown"""
self.clearForm()
if self.modification is True:
self.frameWidget.setTitle("Modifying Contact")
self.setWindowIcon(QtGui.QIcon(r"modifycontact.png"))
self.fillForm(self.view.tableOfContact.currentItem())
else:
self.frameWidget.setTitle("New Contact")
self.setWindowIcon(QtGui.QIcon(r"Images/newcontact.png"))
def clearForm(self):
"""To clear all the fields of the form"""
self.familyNameField.setText("")
self.firstNameField.setText("")
self.numberField.setText("")
self.addressField.setText("")
self.postalCodeField.setText("")
self.cityField.setText("")
self.mailField.setText("")
self.familyNameField.setFocus()
def fillForm(self, element):
"""To fill the form with a specified element (to modify an already existing element)"""
self.contact = element.clone()
if not self.isEmpty():
self.familyNameField.setText(element.text(0))
self.firstNameField.setText(element.text(1))
self.numberField.setText(element.text(2))
self.addressField.setText(element.text(3))
self.postalCodeField.setText(element.text(4))
self.cityField.setText(element.text(5))
self.mailField.setText(element.text(6))
def isEmpty(self):
"""To check if the fields of the form are all empty"""
for i in range(self.contact.columnCount()):
if self.contact.text(i) != "":
return False
return True
class ContactBox(QtWidgets.QDialog):
""" Contact Interface to look at information about the contact Class"""
def __init__(self, parent = None):
"""Constructor of ContactBox"""
super(ContactBox, self).__init__()
self.view = parent
self.contact = QtWidgets.QTreeWidgetItem()
self.contactLayout = QtWidgets.QHBoxLayout()
self.mainLayout = QtWidgets.QVBoxLayout()
self.modifyButton = QtWidgets.QPushButton("Modify contact")
self.buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Close)
self.buttonBox.addButton(self.modifyButton, QtWidgets.QDialogButtonBox.ActionRole)
self.infoBox = QtWidgets.QLabel()
self.imageBox = QtWidgets.QLabel()
self.image = QtGui.QPixmap()
self.image.load(r"Images/social.png")
self.imageBox.setPixmap(self.image.scaled(100, 100))
self.text = ""
self.contactLayout.addWidget(self.infoBox)
self.contactLayout.addWidget(self.imageBox)
self.mainLayout.addLayout(self.contactLayout)
self.mainLayout.addWidget(self.buttonBox)
self.setLayout(self.mainLayout)
# For design:
self.setFixedSize(400, 200)
self.setStyleSheet("color: #ADAFB2;"
"background-color: #282828")
self.setWindowIcon(QtGui.QIcon(r"Images/social.png"))
self.setCursor(QtGui.QCursor(QtGui.QPixmap(r"Images/mouse.png"),0.85,1.66))
self.setModal(True)
# Connections of the buttons:
self.buttonBox.button(QtWidgets.QDialogButtonBox.Close).clicked.connect(self.hide)
self.modifyButton.clicked.connect(self.modContact)
def updateContact(self):
"""To update the contact's display in the Contact Box"""
self.contact = self.view.tableOfContact.currentItem()
self.setWindowTitle("Contact : %s %s" % (self.contact.text(0), self.contact.text(1)))
for column in range(7):
self.text += str(self.view.listHeaderLabels[column] + " : " + self.contact.text(column) + "\n")
self.infoBox.setText(self.text)
self.text = ""
def modContact(self):
"""To modify the contact in view"""
self.view.modContact()
def showEvent(self, QShowEvent):
"""Function called when the window is shown"""
self.updateContact()
|
#encoding=utf-8
from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from appium.webdriver.common.touch_action import TouchAction
import base64
import time
import os
import codecs
# 获取手机基本信息
def get_phonemsg():
# 获取设备号
devices = os.system('adb devices')
# 获取应用包名及启动名,需事先手工启动再获取
app_message = os.system('adb shell dumpsys window windows | findstr mFocusedApp')
class Phone_Basic_Operate():
def __init__(self):
# 定义手机设备启动参数,字典型数据
desired_caps = {}
# 设备系统名
desired_caps['platformName'] = 'Android'
# desired_caps['platformVersion']='9'#如果不清楚可不定义该参数,但千万不要传错
# 设备号
desired_caps['deviceName'] = '8CYNW19912004879'
# 应用包名
appPackage = "com.digitalchina.mobile.dfhfz1"
desired_caps['appPackage'] = appPackage
# 应用启动名
appActivity = 'com.systoon.toon.user.login.view.WelcomeActivity'
desired_caps['appActivity'] = appActivity
#防止APP每次启动时都需要重新登录
desired_caps['noReset'] = True
desired_caps['fullReset'] = False
desired_caps['unicodeKeyboard'] = True # unicode设置(允许中文输入)
desired_caps['resetKeyboard'] = True # 键盘设置(允许中文输入)
desired_caps['autoGrantPermissions'] = True # 自动决定获取安装app需要的权限
# 声明手机驱动对象,http://127.0.0.1:4723为appium自动工具的启动地址及端口
self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',desired_caps)
def __del__(self):
self.driver_quit()
def driver_quit(self):
self.driver.quit()
#根据不同的定位方式进行单个元素的定位
def locate_element(self,locate_type,value):
'''
:param locate_type: 定位类型 如 id,class,xpath 三种定位类型
:param value: 元素定位值 如xpath路径的值 //*[@content-desc="外卖"]
:return:
value='name' 返回content-desc / text属性值
value='text' 返回text的属性值
value='className' 返回 class属性值,只有 API=>18 才能支持
value='resourceId' 返回 resource-id属性值,只有 API=>18 才能支持
'''
el=None
if locate_type=="id":
# 显式等待,每0.5秒轮询一次,超时10秒抛出错误
el = WebDriverWait(self.driver,10,0.5).until(lambda x: x.find_element_by_id(value))
#el=self.driver.find_element_by_id(value)
elif locate_type=="name":
# 显式等待,每0.5秒轮询一次,超时10秒抛出错误
el = WebDriverWait(self.driver,10,0.5).until(lambda x: x.find_element_by_name(value))
elif locate_type=="class":
# 显式等待,每0.5秒轮询一次,超时10秒抛出错误
el = WebDriverWait(self.driver,10,0.5).until(lambda x: x.find_element_by_class_name(value))
#el=self.driver.find_element_by_class_name(value)
elif locate_type=="xpath":
#显式等待,每0.5秒轮询一次,超时10秒抛出错误
#value="//*[contains(@text,'交通出行')"]
el=WebDriverWait(self.driver,10,0.5).until(lambda x:x.find_element_by_xpath(value))
#el=self.driver.find_element_by_xpath(value)
return el
# 根据不同的定位方式进行多个元素的定位
def locate_more_elements(self, locate_type, value):
el = None
if locate_type == "id":
# 显式等待,每0.5秒轮询一次,超时10秒抛出错误
el = WebDriverWait(self.driver, 10, 0.5).until(lambda x: x.find_elements_by_id(value))
# el=self.driver.find_elements_by_id(value)
elif locate_type == "name":
# 显式等待,每0.5秒轮询一次,超时10秒抛出错误
el = WebDriverWait(self.driver,10,0.5).until(lambda x: x.find_elements_by_name(value))
#el = self.driver.find_elements_by_name(value)
elif locate_type == "class":
# 显式等待,每0.5秒轮询一次,超时10秒抛出错误
el = WebDriverWait(self.driver, 10, 0.5).until(lambda x: x.find_elements_by_class_name(value))
# el=self.driver.find_elements_by_class_name(value)
elif locate_type == "xpath":
# 显式等待,每0.5秒轮询一次,超时10秒抛出错误
# value="//*[contains(@text,'交通出行')"]
el = WebDriverWait(self.driver, 10, 0.5).until(lambda x: x.find_elements_by_xpath(value))
# el=self.driver.find_elements_by_xpath(value)
return el
#获取元素坐标
def get_positon(self,locate_type,value):
el=self.locate_element(locate_type,value)
positon=el.location
print("元素坐标:",positon)
return positon
#获取元素属性名
def get_attriname(self,loate_type,locate_value,attribute_type):
"""
:param loate_type: 元素定位方式
:param locate_value: 元素定位值
:param attribute_type: 属性类型如
value='name' 返回content-desc / text属性值
value='text' 返回text的属性值
value='className' 返回 class属性值,只有 API=>18 才能支持
value='resourceId' 返回 resource-id属性值,只有 API=>18 才能支持
:return:
"""
el=self.locate_element(loate_type,locate_value)
attriname_text=el.get_attribute(attribute_type)
print("属性类型:%s,属性值:%s"%(attribute_type,attriname_text))
return attriname_text
#获取截图
def get_screen(self):
#img_folder=os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) +'//screenshots'
img_folder="E:\\AppProject\\screenshot" +'//screenshots'
screentime=time.strftime('%Y%m%d%H%M',time.localtime(time.time()))
screen_save_path=img_folder+ screentime +'.png'
self.driver.get_screenshot_as_file(screen_save_path)
#点击元素
def click(self,locate_type,value):
el=self.locate_element(locate_type,value)
el.click()
#元素文本录入
def input(self,locate_type,value,text):
el=self.locate_element(locate_type,value)
el.clear()
el.send_keys(text)
#获取打印手机时间
def get_time(self):
phone_time=self.driver.device_time
print(phone_time)
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
return phone_time
# 获取打印手机分辨率
def get_size(self):
window_size= self.driver.get_window_size()
width_size=window_size.get("width")
height_size=window_size.get("height")
print("Width:",width_size)
print("Height:",height_size)
return window_size
#从一个坐标滑动到另外一个坐标,持续时间的单位为毫秒
def ele_swip(self,start_x, start_y, end_x, end_y,duration=None):
self.driver.swipe(start_x,start_y,end_x,end_y,duration)
#从一个元素滑动到另外一个元素,直到页面自己停止
def ele_scroll(self,origin_el, destination_el,duration=None):
self.driver.scroll(origin_el,destination_el,duration)
#从一个元素拖动到另外一个元素处放开(有可能是点击的效果?)
def ele_dragdrop(self,origin_el,destination_el):
self.driver.drag_and_drop(origin_el,destination_el)
#长按某个元素,时间单位为毫秒
def ele_longpress(self,press_ele,duration_time=None):
TouchAction(self.driver).long_press(press_ele,duration=duration_time).perform().release()
#点击某个元素
def ele_tap(self,tap_ele):
TouchAction(self.driver).tap(tap_ele).perform().release()
#模拟粘贴 v:50 ctrl:4096
def ctrlv(self):
self.driver.keyevent(50,4096)
#将应用置于后台一段时间
def background(self,seconds_n):
self.driver.background_app(seconds_n)
#打开通知栏
def open_notifications(self):
self.driver.open_notifications()
#点击home键
def back_home(self):
self.driver.keyevent(3)
#获取手机当前网络
def get_network(self):
network=self.driver.network_connection
print(network)
return network
#将电脑端文件发送到手机目录下
#pc_data_path="D:\\AppProject\\data_file\\wuhan.txt"
#phone_path="/sdcard/wuhan14.txt"
def push_to_phone(self,pc_data_path,phone_path):
#读取文件路径中的数据
with open(pc_data_path,encoding='utf-8') as f:
pc_data=f.read()
#print(pc_data)
#转化为utf-8格式
pc_data_utf8=pc_data.encode('utf-8')
#转化为b64格式
pc_data_b64=str(base64.b64encode(pc_data_utf8),'utf-8')
self.driver.push_file(phone_path,pc_data_b64)
#从手机上拉取文件
def pull_from_phone(self,phone_path):
#返回的是b64格式数据
data_b64=self.driver.pull_file(phone_path)
#解码b64格式数据
data_b64decode = base64.b64decode(data_b64.encode('utf-8'))
data=str(data_b64decode,'utf-8')
print("pull:\n",data)
#
# def operate(self):
# # 判断是否安装app
# print(self.driver.is_app_installed(self.appPackage))
# app_path = "D:\\AppProject\\AppPackage\\ZUOYEBAN12.9.0.apk"
# self.driver.install_app(app_path)
# #关闭当前操作的app,但不关闭driver
# self.driver.close_app()
#
# #关闭驱动对象
# self.driver.quit()
# #启动应用
# self.driver.start_activity(self.appPackage,self.appActivity)
if __name__ == '__main__':
#获取手机应用基本信息
#get_msg=get_phonemsg()
PBOperate=Phone_Basic_Operate()
#点击【交通出行】
xpath_value="/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.RelativeLayout/android.view.ViewGroup/android.widget.ScrollView/android.widget.RelativeLayout/android.support.v7.widget.RecyclerView/android.widget.LinearLayout[1]/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.GridView/android.widget.RelativeLayout[1]/android.widget.RelativeLayout/android.widget.ImageView"
ele=PBOperate.locate_element("xpath",xpath_value)
print(ele.location())
#PBOperate.click("xpath",xpath_value)
#PBOperate.click("class","android.view.View")
#PBOperate.click('xpath','//*[@content-desc="外卖"]')
time.sleep(2)
#PBOperate.click('xpath','//*[contains(@content-desc,"外卖")]')
#PBOperate.click('xpath','//android.view.View[@content-desc="外卖"]')
time.sleep(3)
#PBOperate.click('id','//*[@resource-id="com.sankuai.meituan:id/gridview_major_category"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]') #点击美食
|
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df_swing=pd.read_csv('E:\csvdhf5xlsxurlallfiles/2008_swing_states.csv')
print(df_swing.columns)
_=sns.swarmplot(x='state', y='dem_share', data=df_swing)
_=plt.xlabel('state')
_=plt.ylabel('percen of vote for obama')
plt.show()
|
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import sys
sys.path.append('../../py/')
from DREAM.DREAMOutput import DREAMOutput
plt.rcParams.update({'font.size': 14})
do = DREAMOutput('output.h5')
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(10,4))
# 1.Distribution function evolution
do.eqsys.f_hot.semilogy(t=[0,4,9], ax=axs[0])
axs[0].set_title('Distribution function')
# 2. Runaway rate
rr = do.other.fluid.runawayRate[:,0]
axs[1].plot(do.grid.t[1:], rr, linewidth=2, color='k')
axs[1].set_xlim([0,do.grid.t[-1]])
axs[1].set_ylim([0, 1.2*np.amax(rr)])
axs[1].set_xlabel('Time $t$ (s)')
axs[1].set_ylabel('Runaway rate (s$^{-1}$)')
axs[1].set_title('Runaway rate')
plt.tight_layout()
plt.show()
|
#python2.7, requires torch
from __future__ import division
from __future__ import print_function
import loadModelMNIST
import testModel
import random
import pdb
import matplotlib.pyplot as plt
import torch
from torch.autograd import Variable
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import pickle
from ProjectImageHandler import ProjectImageHandler as PM
def getAdversarialAccuracy(dataSet,noise,advLabels):
classes = testModel.classes
correct = 0
advCorrect = 0
total = len(dataSet)
model.eval()
for i in (range(len(dataSet))):
image,label = dataSet[i]
advImg = image + noise[i]
advVar = Variable(advImg).cuda()
output = model(advVar)
_,idx = torch.max(output,1)
classifiedlabel = classes[idx.data[0]]
if str(classifiedlabel) == str(label):
correct += 1
elif str(classifiedlabel) == str(advLabels[i]):
advCorrect += 1
accuracy = (correct / float(total)) * 100
advAcc = (advCorrect / float(total)) * 100
return(accuracy,advAcc)
def readNoiseFile(noiseFile):
noise,labels = pickle.load(open(noiseFile))
return noise,labels
if __name__ == "__main__":
model = loadModelMNIST.loadRandom().cuda()
model.eval()
transform = transforms.Compose( [transforms.ToTensor(),
transforms.Normalize( (0.1307,), (0.3081,)) ] )
MNIST = torchvision.datasets.MNIST( root='./data', train=False,
download=True, transform=transform)
noiseFile = "adversary_SGD_Testset"
noise,advLabels = readNoiseFile(noiseFile)
accuracy,advAcc = getAdversarialAccuracy(MNIST,noise,advLabels)
print("accuracy = %.3f%%\nadversarial label accuracy = %.3f%%" % (accuracy,advAcc))
|
# Author:ambiguoustexture
# Date: 2020-03-04
import gzip
import json
import pymongo
from pymongo import MongoClient
file_gz = './artist.json.gz'
unit_bulk = 10000
client = MongoClient()
db = client.db_MusicBrainz
collection = db.artists
with gzip.open(file_gz, 'rt') as artists:
buf = []
for i, artist in enumerate(artists, 1):
artist_json_line = json.loads(artist)
buf.append(artist_json_line)
if i % unit_bulk == 0:
collection.insert_many(buf)
buf = []
print('%d records have been recored.' % i)
if len(buf) > 0:
collection.insert_many(buf)
print('%d records have been recored.' % i)
collection.create_index([('name', pymongo.ASCENDING)])
collection.create_index([('aliases.name', pymongo.ASCENDING)])
collection.create_index([('tags.value', pymongo.ASCENDING)])
collection.create_index([('rating.value', pymongo.ASCENDING)])
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 19:49:25 2019
@author: Rui Kong
"""
import numpy as np
import math
import random
import matplotlib.pyplot as plt
'''
差分进化算法:初始化、变异、交叉、边界处理、计算fitness、选择
种群数量一般为4D-10D,必须大于4
变异算子F一般取为0.5
交叉算子CR一般为0.1或0.9
最大进化代数G为100-500
此处为求最小值的问题,若要进行修改,则需要将fitness的地方全部进行修改。
'''
def caculate_fitness(x):
return sum(x**2)
population_num=100 #种群数量
variable_dimension=10 #变量的个数
iteration_count=200
FC=0.5
CROSS_OVER=0.1
Xlarge=20
Xsmall=-20
Yz=1e-6 #阈值
#初始化-----------------------
initial_population=np.zeros((variable_dimension,population_num))
cross_population=np.zeros((variable_dimension,population_num))
selection_population=np.zeros((variable_dimension,population_num))
#赋予初始值
initial_population = np.random.rand(variable_dimension,population_num)*(Xlarge-Xsmall) + Xsmall
fitness1=[] #存放每次计算的fitness
for i in range (population_num):
fitness1.append(caculate_fitness(initial_population[:,i]))
print(min(fitness1))
trace=[] #记录每次迭代过程中的最优值
trace.append(min(fitness1))
#---------------------差分进化选择--------------------------------------
for i in range(population_num):
#------------------------自适应变异算子-------------------------
lamda = np.exp(1-iteration_count/(iteration_count+1-i))
F = FC*2**lamda
#------r1\r2\r3与m互不相同
for j in range(population_num):
r1 = np.random.randint(0,population_num)
while r1 == j :
r1 = np.random.randint(0,population_num)
r2 = np.random.randint(0,population_num)
while r2==j or r2==r1:
r2 = np.random.randint(0,population_num)
r3 = np.random.randint(0,population_num)
while r3==j or r3==r2 or r3==r1:
r3 = np.random.randint(0,population_num)
cross_population[:,j] = initial_population[:,r1] + F*(initial_population[:,r2]-initial_population[:,r3])
#-------------------交叉操作cross_over-------------------------------------------------------------
r=np.random.randint(0,variable_dimension)
for n in range(variable_dimension):
cross_posi=np.random.rand()
if cross_posi<=CROSS_OVER or r==n:
selection_population[n,:] = cross_population[n,:]
else:
selection_population[n,:] = initial_population[n,:]
#--------------------边界处理----------------------------------------
for n in range(variable_dimension):
for m in range(population_num):
if(selection_population[n,m] < Xsmall) or (selection_population[n,m]>Xlarge):
selection_population[n,m] = np.random.rand()*(Xlarge-Xsmall) + Xsmall
#--------------------选择操作-----------------------------------------------------------
fitness2=[]
for n in range(population_num):
fitness2.append(caculate_fitness(selection_population[:,n]))
for m in range(population_num):
if(fitness2[m]<fitness1[m]): #调整最大最小值的位置,可以改变不同的问题
initial_population[:,m] = selection_population[:,m]
for m in range(population_num):
fitness1[m]=caculate_fitness(initial_population[:,m])
trace.append(min(fitness1)) #修改的地方
if min(trace)< Yz :
break
#-------------------------------------------------------end----------------------------
index=np.argsort(fitness1)
BestX=initial_population[:,index[0]]
BestY=min(fitness1)
print("最优值与最优结果分别为:",BestX,"-------------",BestY)
plt.plot(trace)
|
import pandas as pd
TRIPS_DF = {'distance_end': {0: 147.404368166875},
'distance_start': {0: 318.361754800303},
'lat_end': {0: 47.050889099999999},
'lat_start': {0: 47.2013301},
'lon_end': {0: 8.3093702999999994},
'lon_start': {0: 7.4539675000000001},
'mot_segment_id': {0: '86a42e1a-fc08-459f-82e1-2b113d4be97b'},
'stop_id_end': {0: '8505000'},
'stop_id_start': {0: '8500204'},
'time_end': {0: pd.Timestamp('2016-06-27 07:11:13')},
'time_start': {0: pd.Timestamp('2016-06-27 05:29:59')},
'timezone_end': {0: 'Europe/Zurich'},
'timezone_start': {0: 'Europe/Zurich'},
'trip_time_end': {0: pd.Timestamp('2016-06-27 07:43:27')},
'trip_time_start': {0: pd.Timestamp('2016-06-27 04:49:41')},
'vid': {0: 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7'},
'visit_id_end': {0: 13514},
'visit_id_start': {0: 13500}}
TRIP_LINK_DF = {'mot_segment_id': {('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'012aa915-76b6-4cf7-aac0-20b698dbb61f'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'03ddbeba-c800-462b-97b1-de096365402b'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'0c17d884-a4ef-4126-bd5c-7de593acdab8'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'122c7530-47f5-4f98-aa59-e666ee86b4a9'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'1921bee8-d213-477b-af87-acdb786a6685'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'1db8f3d3-8f12-4cf2-8a4c-2df4d822b901'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'1fd28d4a-909c-4464-a62c-6b30fd2179aa'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'223ef721-0bc2-4c4f-ba4f-ee24b4e4364b'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'24710d17-5227-4764-a583-9a2d58e64f76'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'2c138c72-d1b0-4cd5-917b-7a39062f258e'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'305486cc-5929-457b-821d-f89fb01a51c2'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'450a71eb-42b9-4a49-ac45-405c954a9e8d'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'4b3d9739-2d37-4c9d-ae98-84b3929775ee'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'531ce286-4994-43ce-a580-65e5b073bdca'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'53604b52-75ac-4bbe-8114-8f29a876ef28'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'6b623efa-1f2d-4767-863f-93286950f9e4'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'6e6bdbda-12bd-4dee-b95d-abdc3cd770e4'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'722b31f3-e5c0-47e4-96ed-67216dd625a9'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'7a4afb37-42ab-4fec-85ed-a78fcbe8c5fc'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'82253015-eaab-46a8-b319-a459891fda73'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'8c6e4b22-9163-4290-8e6a-702952268532'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'9577411f-9c7f-4d1c-8047-60941e7af1d5'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'a7afe35d-a4a2-4bfa-bc53-41793139eb09'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'c0989f31-0767-403d-b24e-199bba8d1ec0'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'c31016fc-a2a9-4d49-a8bd-af7a2bb0a72d'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'c402357d-2bc6-4191-ae69-3686657e308b'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'c6e350ef-edda-4e63-b340-550a5b096970'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'd7c64592-e040-46fd-a353-1de5984a4777'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'd81a6237-270f-4623-8660-32f21ea3776b'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'd93509e3-33ac-4210-be1d-8d1030d2a84d'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'f41d67e8-06d4-4fb4-b2a7-67752d722594'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'f5dae2fc-fb1e-4d5b-8c81-1ed8dbb9b027'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'86737744-4799-4581-9d9d-71d77edd3a61',
''): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'aa9cd53d-ed99-43a7-b600-e2d1877db330',
'7c74103d-5625-4e70-bac1-f9aaec68e9c1'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'aa9cd53d-ed99-43a7-b600-e2d1877db330',
'd85e62e2-579e-4d71-9a34-107977f45713'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'aa9cd53d-ed99-43a7-b600-e2d1877db330',
'ed20dffa-61bb-4c70-882c-bdc75f029a6d'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('175d5093-b137-491f-9ffb-b027fba20319',
'd72e2276-5b11-4d61-a098-84568f9eacc1',
''): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'05986180-bc1d-45d6-a52d-287c947d130b'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'12500fe0-312e-40bd-b468-de2afd5ac794'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'3f1145cd-dfe0-4084-aa03-4e0c539438c1'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'84e48ab6-cbbf-46ed-acca-07f1ab9e0f65'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'e7f533c0-36f3-4a90-a284-de213fbd230c'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'f3c7ca99-0b09-4d94-b950-808fb8474b96'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'62e9135b-91a5-4706-bdec-ece3772e202f',
''): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'05325e3b-8b2b-46b8-958c-0ce5799cfae8'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'08d5da2d-a63e-4cd3-8c1c-815c78f71423'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'174f96e0-bcae-456f-8bd1-5685f428c82a'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'1b0a2867-aaff-449f-8b55-7fb3a3c28a0a'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'1c563a19-f1bb-4fc3-83b4-738f6e6b8a31'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'1e7b1ffa-2e66-4dc4-b401-85c4c92ee602'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'1ffd4d7d-6c77-40aa-8f17-ff2f7c5011ac'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'27e28e55-ea6c-44eb-98be-e80a93682fc5'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'2c4f85d0-1b8e-4738-bde8-1f880b57e5e6'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'4a2ae77d-71e5-45b3-be16-3cfedd75abda'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'5627b65c-aead-4b6e-86af-a25540c28b1e'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'5ef10673-4d9b-4f32-8727-ee716d3a4236'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'626eefd5-f049-4626-8b8b-aa0c93f58b16'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'708ef2ee-e653-44bc-b885-297df0d91d71'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'7633869e-2c46-48de-8640-63c799c7fc9c'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'76a31790-1f32-4263-b1e2-eb3a15d02bdb'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'b45d8be3-5b19-40d1-b7c4-1359862ac30c'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'ce8006ec-4dea-44d8-9934-33824910e681'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'dd8a01c1-210e-4002-8d9d-a273cf98f5af'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'ea6ad5bd-600a-45c4-aa58-1fada234c6ef'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'f7efc04b-be14-43eb-944e-b5f0b77f52e3'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'221973b6-f6bb-442d-9164-9c96a825e4fd'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'30dd1aa1-f689-4073-a75c-65dbe99398c7'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'66fc3195-a832-4837-9350-341ea37c6a53'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'8e45deed-7596-4b55-ae8c-e1ad31394b59'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'91a486ed-7cfe-486d-b30e-425b6e52b30b'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'978e3375-98d2-4cc5-b014-96a6c395bb1f'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'bc91e6c3-44d3-4e57-9cc7-49e3056e38fc'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'f131ba54-ae59-4992-80aa-8def87bb0f0a'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7',
''): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'017245ba-4666-4ad9-8378-96389be01377'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'0449c892-8239-49c1-addd-0b307f5f42bd'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'0ca89763-863d-485e-881b-232e3de5f7e7'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'10619f79-f684-4bf9-8c83-165e809ba5f4'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'12bc1db9-8a2a-46ff-b804-d0e320a71c69'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'13cee614-8001-4f11-81f0-89d272d00db0'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'28abe4d6-5f4e-4aac-9f88-febd5ac05d68'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'29a2c8c7-3706-426a-961e-88444fabdc6e'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'2ab31818-3093-4ae3-b48e-e206475fe071'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'31559fd8-4179-4b37-882a-783ea5e5a00c'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'401f4497-62da-4c95-85a5-f7212091e780'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'4da55de8-3ac9-43f5-86d3-baee4db4bf0b'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'660db5e9-55c3-49da-b520-d4683976c4dc'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'681c6d37-9f34-4085-9fda-6134a7bc224e'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'70a72fbe-9804-4be0-9e6f-81e44fcf8cce'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'70aa2417-3a72-4375-a1a1-163e1a3c5c3c'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'769b2118-4507-46bd-9355-1549f6972384'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'86598728-fee2-4bc8-b543-fc3eb4bc3614'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'92f1c22e-350f-46f3-ba19-f0bc64cbf1d7'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'96c10154-1e94-4df6-9a37-2167edd00a04'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'9f447e9b-e70e-4a46-aa22-7d3544d6dd35'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'a9f50608-77e0-4778-a6ec-132994d5765c'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'ad652142-4f71-403c-93d4-efea27ed601e'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'afc7b5ff-468a-433d-b800-311ab180eabd'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'c4e850a9-4c76-4a87-afd6-02ae086f1448'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'c85bd7b1-4d8e-4760-b832-d420b29c8d1b'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'd5e552c5-8acd-451d-bdc9-6bec8fa227bf'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'd772bc3b-4a68-4cc4-b25c-bbae66c26e81'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'e07585f8-d9ae-42ff-9c0a-cf697732d359'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'f5d8a7f9-5e40-429b-8443-1842bc7d288f'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'f8f501fb-3680-4a13-9ae2-ffddc9bba865'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'fba76c03-a7c9-4147-9dce-a22c6ecd53bf'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'49802738-12bf-4215-88e6-60f4b2311f62',
''): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'28e4d325-287a-43de-86ee-e60cc60977c2'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'5c3743fc-2023-4c29-a90c-07de6a56a71a'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'6c7265b8-d053-4b8b-8d75-46787b1c1bfa'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'76380e8c-0e6f-4447-ab1a-0cf588f9fb3c'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'd0a2c20b-a795-473b-bb29-3d71636b14f8'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'd145e943-2e42-451b-ae43-bc4f991f333d'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'e87e9770-2ce8-4e28-8dee-89f42ecaa4c5'): '300986b9-d5f6-4590-9f62-622f4f17106c',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0',
''): '300986b9-d5f6-4590-9f62-622f4f17106c'},
'vid': {('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'012aa915-76b6-4cf7-aac0-20b698dbb61f'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'03ddbeba-c800-462b-97b1-de096365402b'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'0c17d884-a4ef-4126-bd5c-7de593acdab8'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'122c7530-47f5-4f98-aa59-e666ee86b4a9'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'1921bee8-d213-477b-af87-acdb786a6685'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'1db8f3d3-8f12-4cf2-8a4c-2df4d822b901'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'1fd28d4a-909c-4464-a62c-6b30fd2179aa'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'223ef721-0bc2-4c4f-ba4f-ee24b4e4364b'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'24710d17-5227-4764-a583-9a2d58e64f76'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'2c138c72-d1b0-4cd5-917b-7a39062f258e'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'305486cc-5929-457b-821d-f89fb01a51c2'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'450a71eb-42b9-4a49-ac45-405c954a9e8d'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'4b3d9739-2d37-4c9d-ae98-84b3929775ee'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'531ce286-4994-43ce-a580-65e5b073bdca'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'53604b52-75ac-4bbe-8114-8f29a876ef28'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'6b623efa-1f2d-4767-863f-93286950f9e4'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'6e6bdbda-12bd-4dee-b95d-abdc3cd770e4'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'722b31f3-e5c0-47e4-96ed-67216dd625a9'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'7a4afb37-42ab-4fec-85ed-a78fcbe8c5fc'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'82253015-eaab-46a8-b319-a459891fda73'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'8c6e4b22-9163-4290-8e6a-702952268532'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'9577411f-9c7f-4d1c-8047-60941e7af1d5'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'a7afe35d-a4a2-4bfa-bc53-41793139eb09'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'c0989f31-0767-403d-b24e-199bba8d1ec0'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'c31016fc-a2a9-4d49-a8bd-af7a2bb0a72d'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'c402357d-2bc6-4191-ae69-3686657e308b'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'c6e350ef-edda-4e63-b340-550a5b096970'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'd7c64592-e040-46fd-a353-1de5984a4777'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'd81a6237-270f-4623-8660-32f21ea3776b'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'd93509e3-33ac-4210-be1d-8d1030d2a84d'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'f41d67e8-06d4-4fb4-b2a7-67752d722594'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'4d220719-9d58-4bef-a856-81ba1c3eee48',
'f5dae2fc-fb1e-4d5b-8c81-1ed8dbb9b027'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'86737744-4799-4581-9d9d-71d77edd3a61',
''): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'aa9cd53d-ed99-43a7-b600-e2d1877db330',
'7c74103d-5625-4e70-bac1-f9aaec68e9c1'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'aa9cd53d-ed99-43a7-b600-e2d1877db330',
'd85e62e2-579e-4d71-9a34-107977f45713'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'aa9cd53d-ed99-43a7-b600-e2d1877db330',
'ed20dffa-61bb-4c70-882c-bdc75f029a6d'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('175d5093-b137-491f-9ffb-b027fba20319',
'd72e2276-5b11-4d61-a098-84568f9eacc1',
''): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'05986180-bc1d-45d6-a52d-287c947d130b'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'12500fe0-312e-40bd-b468-de2afd5ac794'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'3f1145cd-dfe0-4084-aa03-4e0c539438c1'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'84e48ab6-cbbf-46ed-acca-07f1ab9e0f65'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'e7f533c0-36f3-4a90-a284-de213fbd230c'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'5b9ddde6-9299-4523-960c-f57b7bac5668',
'f3c7ca99-0b09-4d94-b950-808fb8474b96'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'62e9135b-91a5-4706-bdec-ece3772e202f',
''): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'05325e3b-8b2b-46b8-958c-0ce5799cfae8'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'08d5da2d-a63e-4cd3-8c1c-815c78f71423'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'174f96e0-bcae-456f-8bd1-5685f428c82a'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'1b0a2867-aaff-449f-8b55-7fb3a3c28a0a'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'1c563a19-f1bb-4fc3-83b4-738f6e6b8a31'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'1e7b1ffa-2e66-4dc4-b401-85c4c92ee602'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'1ffd4d7d-6c77-40aa-8f17-ff2f7c5011ac'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'27e28e55-ea6c-44eb-98be-e80a93682fc5'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'2c4f85d0-1b8e-4738-bde8-1f880b57e5e6'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'4a2ae77d-71e5-45b3-be16-3cfedd75abda'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'5627b65c-aead-4b6e-86af-a25540c28b1e'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'5ef10673-4d9b-4f32-8727-ee716d3a4236'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'626eefd5-f049-4626-8b8b-aa0c93f58b16'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'708ef2ee-e653-44bc-b885-297df0d91d71'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'7633869e-2c46-48de-8640-63c799c7fc9c'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'76a31790-1f32-4263-b1e2-eb3a15d02bdb'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'b45d8be3-5b19-40d1-b7c4-1359862ac30c'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'ce8006ec-4dea-44d8-9934-33824910e681'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'dd8a01c1-210e-4002-8d9d-a273cf98f5af'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'ea6ad5bd-600a-45c4-aa58-1fada234c6ef'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6d4598b9-9b74-41a1-8931-16b21de65679',
'f7efc04b-be14-43eb-944e-b5f0b77f52e3'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'221973b6-f6bb-442d-9164-9c96a825e4fd'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'30dd1aa1-f689-4073-a75c-65dbe99398c7'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'66fc3195-a832-4837-9350-341ea37c6a53'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'8e45deed-7596-4b55-ae8c-e1ad31394b59'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'91a486ed-7cfe-486d-b30e-425b6e52b30b'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'978e3375-98d2-4cc5-b014-96a6c395bb1f'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'bc91e6c3-44d3-4e57-9cc7-49e3056e38fc'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b',
'f131ba54-ae59-4992-80aa-8def87bb0f0a'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('6b5ab506-a853-412c-bd23-1afb88f61907',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7',
''): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'017245ba-4666-4ad9-8378-96389be01377'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'0449c892-8239-49c1-addd-0b307f5f42bd'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'0ca89763-863d-485e-881b-232e3de5f7e7'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'10619f79-f684-4bf9-8c83-165e809ba5f4'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'12bc1db9-8a2a-46ff-b804-d0e320a71c69'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'13cee614-8001-4f11-81f0-89d272d00db0'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'28abe4d6-5f4e-4aac-9f88-febd5ac05d68'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'29a2c8c7-3706-426a-961e-88444fabdc6e'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'2ab31818-3093-4ae3-b48e-e206475fe071'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'31559fd8-4179-4b37-882a-783ea5e5a00c'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'401f4497-62da-4c95-85a5-f7212091e780'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'4da55de8-3ac9-43f5-86d3-baee4db4bf0b'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'660db5e9-55c3-49da-b520-d4683976c4dc'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'681c6d37-9f34-4085-9fda-6134a7bc224e'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'70a72fbe-9804-4be0-9e6f-81e44fcf8cce'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'70aa2417-3a72-4375-a1a1-163e1a3c5c3c'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'769b2118-4507-46bd-9355-1549f6972384'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'86598728-fee2-4bc8-b543-fc3eb4bc3614'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'92f1c22e-350f-46f3-ba19-f0bc64cbf1d7'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'96c10154-1e94-4df6-9a37-2167edd00a04'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'9f447e9b-e70e-4a46-aa22-7d3544d6dd35'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'a9f50608-77e0-4778-a6ec-132994d5765c'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'ad652142-4f71-403c-93d4-efea27ed601e'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'afc7b5ff-468a-433d-b800-311ab180eabd'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'c4e850a9-4c76-4a87-afd6-02ae086f1448'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'c85bd7b1-4d8e-4760-b832-d420b29c8d1b'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'd5e552c5-8acd-451d-bdc9-6bec8fa227bf'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'd772bc3b-4a68-4cc4-b25c-bbae66c26e81'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'e07585f8-d9ae-42ff-9c0a-cf697732d359'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'f5d8a7f9-5e40-429b-8443-1842bc7d288f'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'f8f501fb-3680-4a13-9ae2-ffddc9bba865'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'33b319d1-7dfb-4817-9b61-7004405114b5',
'fba76c03-a7c9-4147-9dce-a22c6ecd53bf'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'49802738-12bf-4215-88e6-60f4b2311f62',
''): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'28e4d325-287a-43de-86ee-e60cc60977c2'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'5c3743fc-2023-4c29-a90c-07de6a56a71a'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'6c7265b8-d053-4b8b-8d75-46787b1c1bfa'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'76380e8c-0e6f-4447-ab1a-0cf588f9fb3c'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'd0a2c20b-a795-473b-bb29-3d71636b14f8'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'd145e943-2e42-451b-ae43-bc4f991f333d'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'b1117ada-6eae-418a-8722-e3b1f3593826',
'e87e9770-2ce8-4e28-8dee-89f42ecaa4c5'): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
('bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0',
''): 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7'}}
ITINERARY_DF = {'context_reconstruction': {'175d5093-b137-491f-9ffb-b027fba20319': u'G@F$A=2@O=unknown@X=7453972@Y=47201332@u=0@a=128@$A=1@O=Selzach@L=8500204@a=128@$201606270534$201606270540$$\xa7T$A=1@O=Selzach@L=8500204@a=128@$A=1@O=Olten@L=8500218@a=128@$201606270540$201606270624$R 7807$\xa7T$A=1@O=Olten@L=8500218@a=128@$A=1@O=Luzern@L=8505000@a=128@$201606270630$201606270705$IR 2311$\xa7G@F$A=1@O=Luzern@L=8505000@a=128@$A=2@O=unknown@X=8309368@Y=47050889@u=0@a=128@$201606270705$201606270708$$',
'6b5ab506-a853-412c-bd23-1afb88f61907': u'G@F$A=2@O=unknown@X=7453972@Y=47201332@u=0@a=128@$A=1@O=Selzach@L=8500204@a=128@$201606270513$201606270519$$\xa7T$A=1@O=Selzach@L=8500204@a=128@$A=1@O=Grenchen S\xfcd@L=8500202@a=128@$201606270519$201606270523$R 7606$\xa7T$A=1@O=Grenchen S\xfcd@L=8500202@a=128@$A=1@O=Olten@L=8500218@a=128@$201606270525$201606270557$ICN 1507$\xa7T$A=1@O=Olten@L=8500218@a=128@$A=1@O=Luzern@L=8505000@a=128@$201606270606$201606270655$RE 4709$\xa7G@F$A=1@O=Luzern@L=8505000@a=128@$A=2@O=unknown@X=8309368@Y=47050889@u=0@a=128@$201606270655$201606270658$$',
'bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9': u'G@F$A=2@O=unknown@X=7453972@Y=47201332@u=0@a=128@$A=1@O=Selzach@L=8500204@a=128@$201606270534$201606270540$$\xa7T$A=1@O=Selzach@L=8500204@a=128@$A=1@O=Olten@L=8500218@a=128@$201606270540$201606270624$R 7807$\xa7T$A=1@O=Olten@L=8500218@a=128@$A=1@O=Luzern@L=8505000@a=128@$201606270649$201606270730$IR 2459$\xa7G@F$A=1@O=Luzern@L=8505000@a=128@$A=2@O=unknown@X=8309368@Y=47050889@u=0@a=128@$201606270730$201606270733$$'},
'num_legs': {'175d5093-b137-491f-9ffb-b027fba20319': 2.0,
'6b5ab506-a853-412c-bd23-1afb88f61907': 3.0,
'bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9': 2.0},
'time_end': {'175d5093-b137-491f-9ffb-b027fba20319': pd.Timestamp('2016-06-27 07:05:00'),
'6b5ab506-a853-412c-bd23-1afb88f61907': pd.Timestamp('2016-06-27 06:55:00'),
'bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9': pd.Timestamp('2016-06-27 07:30:00')},
'time_start': {'175d5093-b137-491f-9ffb-b027fba20319': pd.Timestamp('2016-06-27 05:40:00'),
'6b5ab506-a853-412c-bd23-1afb88f61907': pd.Timestamp('2016-06-27 05:19:00'),
'bf8ea7cb-6acc-4efc-ac1e-416bf6bdb0b9': pd.Timestamp('2016-06-27 05:40:00')}}
LEGS_DF = {'agency_id': {'33b319d1-7dfb-4817-9b61-7004405114b5': '000011',
'49802738-12bf-4215-88e6-60f4b2311f62': '',
'4d220719-9d58-4bef-a856-81ba1c3eee48': '000011',
'5b9ddde6-9299-4523-960c-f57b7bac5668': '000011',
'62e9135b-91a5-4706-bdec-ece3772e202f': '',
'6d4598b9-9b74-41a1-8931-16b21de65679': '000011',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': '000011',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': '',
'86737744-4799-4581-9d9d-71d77edd3a61': '',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': '000011',
'b1117ada-6eae-418a-8722-e3b1f3593826': '000011',
'd72e2276-5b11-4d61-a098-84568f9eacc1': '',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': ''},
'leg_number': {'33b319d1-7dfb-4817-9b61-7004405114b5': 1.0,
'49802738-12bf-4215-88e6-60f4b2311f62': 0.0,
'4d220719-9d58-4bef-a856-81ba1c3eee48': 1.0,
'5b9ddde6-9299-4523-960c-f57b7bac5668': 1.0,
'62e9135b-91a5-4706-bdec-ece3772e202f': 0.0,
'6d4598b9-9b74-41a1-8931-16b21de65679': 3.0,
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': 2.0,
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': 4.0,
'86737744-4799-4581-9d9d-71d77edd3a61': 0.0,
'aa9cd53d-ed99-43a7-b600-e2d1877db330': 2.0,
'b1117ada-6eae-418a-8722-e3b1f3593826': 2.0,
'd72e2276-5b11-4d61-a098-84568f9eacc1': 3.0,
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': 3.0},
'leg_type': {'33b319d1-7dfb-4817-9b61-7004405114b5': '',
'49802738-12bf-4215-88e6-60f4b2311f62': 'FUSSWEG',
'4d220719-9d58-4bef-a856-81ba1c3eee48': '',
'5b9ddde6-9299-4523-960c-f57b7bac5668': '',
'62e9135b-91a5-4706-bdec-ece3772e202f': 'FUSSWEG',
'6d4598b9-9b74-41a1-8931-16b21de65679': '',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': '',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': 'FUSSWEG',
'86737744-4799-4581-9d9d-71d77edd3a61': 'FUSSWEG',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': '',
'b1117ada-6eae-418a-8722-e3b1f3593826': '',
'd72e2276-5b11-4d61-a098-84568f9eacc1': 'FUSSWEG',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': 'FUSSWEG'},
'nb_train_stops': {'33b319d1-7dfb-4817-9b61-7004405114b5': 16.0,
'49802738-12bf-4215-88e6-60f4b2311f62': 0.0,
'4d220719-9d58-4bef-a856-81ba1c3eee48': 16.0,
'5b9ddde6-9299-4523-960c-f57b7bac5668': 3.0,
'62e9135b-91a5-4706-bdec-ece3772e202f': 0.0,
'6d4598b9-9b74-41a1-8931-16b21de65679': 11.0,
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': 4.0,
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': 0.0,
'86737744-4799-4581-9d9d-71d77edd3a61': 0.0,
'aa9cd53d-ed99-43a7-b600-e2d1877db330': 2.0,
'b1117ada-6eae-418a-8722-e3b1f3593826': 4.0,
'd72e2276-5b11-4d61-a098-84568f9eacc1': 0.0,
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': 0.0},
'num_segments': {'33b319d1-7dfb-4817-9b61-7004405114b5': 32.0,
'49802738-12bf-4215-88e6-60f4b2311f62': 0.0,
'4d220719-9d58-4bef-a856-81ba1c3eee48': 32.0,
'5b9ddde6-9299-4523-960c-f57b7bac5668': 6.0,
'62e9135b-91a5-4706-bdec-ece3772e202f': 0.0,
'6d4598b9-9b74-41a1-8931-16b21de65679': 21.0,
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': 8.0,
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': 0.0,
'86737744-4799-4581-9d9d-71d77edd3a61': 0.0,
'aa9cd53d-ed99-43a7-b600-e2d1877db330': 3.0,
'b1117ada-6eae-418a-8722-e3b1f3593826': 7.0,
'd72e2276-5b11-4d61-a098-84568f9eacc1': 0.0,
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': 0.0},
'platform_end': {'33b319d1-7dfb-4817-9b61-7004405114b5': '1',
'49802738-12bf-4215-88e6-60f4b2311f62': None,
'4d220719-9d58-4bef-a856-81ba1c3eee48': '1',
'5b9ddde6-9299-4523-960c-f57b7bac5668': '2',
'62e9135b-91a5-4706-bdec-ece3772e202f': None,
'6d4598b9-9b74-41a1-8931-16b21de65679': '9',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': '2',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': None,
'86737744-4799-4581-9d9d-71d77edd3a61': None,
'aa9cd53d-ed99-43a7-b600-e2d1877db330': '7',
'b1117ada-6eae-418a-8722-e3b1f3593826': '8',
'd72e2276-5b11-4d61-a098-84568f9eacc1': None,
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': None},
'platform_start': {'33b319d1-7dfb-4817-9b61-7004405114b5': '1',
'49802738-12bf-4215-88e6-60f4b2311f62': None,
'4d220719-9d58-4bef-a856-81ba1c3eee48': '1',
'5b9ddde6-9299-4523-960c-f57b7bac5668': '2',
'62e9135b-91a5-4706-bdec-ece3772e202f': None,
'6d4598b9-9b74-41a1-8931-16b21de65679': '11',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': '1',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': None,
'86737744-4799-4581-9d9d-71d77edd3a61': None,
'aa9cd53d-ed99-43a7-b600-e2d1877db330': '12',
'b1117ada-6eae-418a-8722-e3b1f3593826': '12',
'd72e2276-5b11-4d61-a098-84568f9eacc1': None,
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': None},
'route_category': {'33b319d1-7dfb-4817-9b61-7004405114b5': 'R',
'49802738-12bf-4215-88e6-60f4b2311f62': '',
'4d220719-9d58-4bef-a856-81ba1c3eee48': 'R',
'5b9ddde6-9299-4523-960c-f57b7bac5668': 'R',
'62e9135b-91a5-4706-bdec-ece3772e202f': '',
'6d4598b9-9b74-41a1-8931-16b21de65679': 'RE',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': 'ICN',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': '',
'86737744-4799-4581-9d9d-71d77edd3a61': '',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': 'IR',
'b1117ada-6eae-418a-8722-e3b1f3593826': 'IR',
'd72e2276-5b11-4d61-a098-84568f9eacc1': '',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': ''},
'route_full_name': {'33b319d1-7dfb-4817-9b61-7004405114b5': 'R 7807',
'49802738-12bf-4215-88e6-60f4b2311f62': '',
'4d220719-9d58-4bef-a856-81ba1c3eee48': 'R 7807',
'5b9ddde6-9299-4523-960c-f57b7bac5668': 'R 7606',
'62e9135b-91a5-4706-bdec-ece3772e202f': '',
'6d4598b9-9b74-41a1-8931-16b21de65679': 'RE 4709',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': 'ICN 1507',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': '',
'86737744-4799-4581-9d9d-71d77edd3a61': '',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': 'IR 2311',
'b1117ada-6eae-418a-8722-e3b1f3593826': 'IR 2459',
'd72e2276-5b11-4d61-a098-84568f9eacc1': '',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': ''},
'route_line': {'33b319d1-7dfb-4817-9b61-7004405114b5': None,
'49802738-12bf-4215-88e6-60f4b2311f62': '',
'4d220719-9d58-4bef-a856-81ba1c3eee48': None,
'5b9ddde6-9299-4523-960c-f57b7bac5668': None,
'62e9135b-91a5-4706-bdec-ece3772e202f': '',
'6d4598b9-9b74-41a1-8931-16b21de65679': None,
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': None,
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': '',
'86737744-4799-4581-9d9d-71d77edd3a61': '',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': None,
'b1117ada-6eae-418a-8722-e3b1f3593826': None,
'd72e2276-5b11-4d61-a098-84568f9eacc1': '',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': ''},
'route_name': {'33b319d1-7dfb-4817-9b61-7004405114b5': 'R 7807',
'49802738-12bf-4215-88e6-60f4b2311f62': ' ',
'4d220719-9d58-4bef-a856-81ba1c3eee48': 'R 7807',
'5b9ddde6-9299-4523-960c-f57b7bac5668': 'R 7606',
'62e9135b-91a5-4706-bdec-ece3772e202f': ' ',
'6d4598b9-9b74-41a1-8931-16b21de65679': 'RE 4709',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': 'ICN 1507',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': ' ',
'86737744-4799-4581-9d9d-71d77edd3a61': ' ',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': 'IR 2311',
'b1117ada-6eae-418a-8722-e3b1f3593826': 'IR 2459',
'd72e2276-5b11-4d61-a098-84568f9eacc1': ' ',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': ' '},
'route_number': {'33b319d1-7dfb-4817-9b61-7004405114b5': '7807',
'49802738-12bf-4215-88e6-60f4b2311f62': '',
'4d220719-9d58-4bef-a856-81ba1c3eee48': '7807',
'5b9ddde6-9299-4523-960c-f57b7bac5668': '7606',
'62e9135b-91a5-4706-bdec-ece3772e202f': '',
'6d4598b9-9b74-41a1-8931-16b21de65679': '4709',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': '1507',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': '',
'86737744-4799-4581-9d9d-71d77edd3a61': '',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': '2311',
'b1117ada-6eae-418a-8722-e3b1f3593826': '2459',
'd72e2276-5b11-4d61-a098-84568f9eacc1': '',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': ''},
'station_name_end': {'33b319d1-7dfb-4817-9b61-7004405114b5': 'Olten',
'49802738-12bf-4215-88e6-60f4b2311f62': 'Selzach',
'4d220719-9d58-4bef-a856-81ba1c3eee48': 'Olten',
'5b9ddde6-9299-4523-960c-f57b7bac5668': u'Grenchen S\xfcd',
'62e9135b-91a5-4706-bdec-ece3772e202f': 'Selzach',
'6d4598b9-9b74-41a1-8931-16b21de65679': 'Luzern',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': 'Olten',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': 'unknown',
'86737744-4799-4581-9d9d-71d77edd3a61': 'Selzach',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': 'Luzern',
'b1117ada-6eae-418a-8722-e3b1f3593826': 'Luzern',
'd72e2276-5b11-4d61-a098-84568f9eacc1': 'unknown',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': 'unknown'},
'station_name_start': {'33b319d1-7dfb-4817-9b61-7004405114b5': 'Selzach',
'49802738-12bf-4215-88e6-60f4b2311f62': 'unknown',
'4d220719-9d58-4bef-a856-81ba1c3eee48': 'Selzach',
'5b9ddde6-9299-4523-960c-f57b7bac5668': 'Selzach',
'62e9135b-91a5-4706-bdec-ece3772e202f': 'unknown',
'6d4598b9-9b74-41a1-8931-16b21de65679': 'Olten',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': u'Grenchen S\xfcd',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': 'Luzern',
'86737744-4799-4581-9d9d-71d77edd3a61': 'unknown',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': 'Olten',
'b1117ada-6eae-418a-8722-e3b1f3593826': 'Olten',
'd72e2276-5b11-4d61-a098-84568f9eacc1': 'Luzern',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': 'Luzern'},
'stop_id_end': {'33b319d1-7dfb-4817-9b61-7004405114b5': '8500218',
'49802738-12bf-4215-88e6-60f4b2311f62': '8500204',
'4d220719-9d58-4bef-a856-81ba1c3eee48': '8500218',
'5b9ddde6-9299-4523-960c-f57b7bac5668': '8500202',
'62e9135b-91a5-4706-bdec-ece3772e202f': '8500204',
'6d4598b9-9b74-41a1-8931-16b21de65679': '8505000',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': '8500218',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': '',
'86737744-4799-4581-9d9d-71d77edd3a61': '8500204',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': '8505000',
'b1117ada-6eae-418a-8722-e3b1f3593826': '8505000',
'd72e2276-5b11-4d61-a098-84568f9eacc1': '',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': ''},
'stop_id_start': {'33b319d1-7dfb-4817-9b61-7004405114b5': '8500204',
'49802738-12bf-4215-88e6-60f4b2311f62': '',
'4d220719-9d58-4bef-a856-81ba1c3eee48': '8500204',
'5b9ddde6-9299-4523-960c-f57b7bac5668': '8500204',
'62e9135b-91a5-4706-bdec-ece3772e202f': '',
'6d4598b9-9b74-41a1-8931-16b21de65679': '8500218',
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': '8500202',
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': '8505000',
'86737744-4799-4581-9d9d-71d77edd3a61': '',
'aa9cd53d-ed99-43a7-b600-e2d1877db330': '8500218',
'b1117ada-6eae-418a-8722-e3b1f3593826': '8500218',
'd72e2276-5b11-4d61-a098-84568f9eacc1': '8505000',
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': '8505000'},
'time_end': {'33b319d1-7dfb-4817-9b61-7004405114b5': pd.Timestamp('2016-06-27 06:24:00'),
'49802738-12bf-4215-88e6-60f4b2311f62': pd.Timestamp('2016-06-27 05:40:00'),
'4d220719-9d58-4bef-a856-81ba1c3eee48': pd.Timestamp('2016-06-27 06:24:00'),
'5b9ddde6-9299-4523-960c-f57b7bac5668': pd.Timestamp('2016-06-27 05:23:00'),
'62e9135b-91a5-4706-bdec-ece3772e202f': pd.Timestamp('2016-06-27 05:19:00'),
'6d4598b9-9b74-41a1-8931-16b21de65679': pd.Timestamp('2016-06-27 06:55:00'),
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': pd.Timestamp('2016-06-27 05:57:00'),
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': pd.Timestamp('2016-06-27 06:58:00'),
'86737744-4799-4581-9d9d-71d77edd3a61': pd.Timestamp('2016-06-27 05:40:00'),
'aa9cd53d-ed99-43a7-b600-e2d1877db330': pd.Timestamp('2016-06-27 07:05:00'),
'b1117ada-6eae-418a-8722-e3b1f3593826': pd.Timestamp('2016-06-27 07:30:00'),
'd72e2276-5b11-4d61-a098-84568f9eacc1': pd.Timestamp('2016-06-27 07:08:00'),
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': pd.Timestamp('2016-06-27 07:33:00')},
'time_planned_end': {'33b319d1-7dfb-4817-9b61-7004405114b5': pd.Timestamp('2016-06-27 06:24:00'),
'49802738-12bf-4215-88e6-60f4b2311f62': pd.Timestamp('2016-06-27 05:40:00'),
'4d220719-9d58-4bef-a856-81ba1c3eee48': pd.Timestamp('2016-06-27 06:24:00'),
'5b9ddde6-9299-4523-960c-f57b7bac5668': pd.Timestamp('2016-06-27 05:23:00'),
'62e9135b-91a5-4706-bdec-ece3772e202f': pd.Timestamp('2016-06-27 05:19:00'),
'6d4598b9-9b74-41a1-8931-16b21de65679': pd.Timestamp('2016-06-27 06:55:00'),
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': pd.Timestamp('2016-06-27 05:57:00'),
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': pd.Timestamp('2016-06-27 06:58:00'),
'86737744-4799-4581-9d9d-71d77edd3a61': pd.Timestamp('2016-06-27 05:40:00'),
'aa9cd53d-ed99-43a7-b600-e2d1877db330': pd.Timestamp('2016-06-27 07:05:00'),
'b1117ada-6eae-418a-8722-e3b1f3593826': pd.Timestamp('2016-06-27 07:30:00'),
'd72e2276-5b11-4d61-a098-84568f9eacc1': pd.Timestamp('2016-06-27 07:08:00'),
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': pd.Timestamp('2016-06-27 07:33:00')},
'time_planned_start': {'33b319d1-7dfb-4817-9b61-7004405114b5': pd.Timestamp('2016-06-27 05:40:00'),
'49802738-12bf-4215-88e6-60f4b2311f62': pd.Timestamp('2016-06-27 05:34:00'),
'4d220719-9d58-4bef-a856-81ba1c3eee48': pd.Timestamp('2016-06-27 05:40:00'),
'5b9ddde6-9299-4523-960c-f57b7bac5668': pd.Timestamp('2016-06-27 05:19:00'),
'62e9135b-91a5-4706-bdec-ece3772e202f': pd.Timestamp('2016-06-27 05:13:00'),
'6d4598b9-9b74-41a1-8931-16b21de65679': pd.Timestamp('2016-06-27 06:06:00'),
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': pd.Timestamp('2016-06-27 05:25:00'),
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': pd.Timestamp('2016-06-27 06:55:00'),
'86737744-4799-4581-9d9d-71d77edd3a61': pd.Timestamp('2016-06-27 05:34:00'),
'aa9cd53d-ed99-43a7-b600-e2d1877db330': pd.Timestamp('2016-06-27 06:30:00'),
'b1117ada-6eae-418a-8722-e3b1f3593826': pd.Timestamp('2016-06-27 06:49:00'),
'd72e2276-5b11-4d61-a098-84568f9eacc1': pd.Timestamp('2016-06-27 07:05:00'),
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': pd.Timestamp('2016-06-27 07:30:00')},
'time_start': {'33b319d1-7dfb-4817-9b61-7004405114b5': pd.Timestamp('2016-06-27 05:40:00'),
'49802738-12bf-4215-88e6-60f4b2311f62': pd.Timestamp('2016-06-27 05:34:00'),
'4d220719-9d58-4bef-a856-81ba1c3eee48': pd.Timestamp('2016-06-27 05:40:00'),
'5b9ddde6-9299-4523-960c-f57b7bac5668': pd.Timestamp('2016-06-27 05:19:00'),
'62e9135b-91a5-4706-bdec-ece3772e202f': pd.Timestamp('2016-06-27 05:13:00'),
'6d4598b9-9b74-41a1-8931-16b21de65679': pd.Timestamp('2016-06-27 06:06:00'),
'6efda0f7-e918-44e2-9c43-ea1732ac7f6b': pd.Timestamp('2016-06-27 05:25:00'),
'722918b5-6bbe-4a1e-9b6a-10ee06ff1bc7': pd.Timestamp('2016-06-27 06:55:00'),
'86737744-4799-4581-9d9d-71d77edd3a61': pd.Timestamp('2016-06-27 05:34:00'),
'aa9cd53d-ed99-43a7-b600-e2d1877db330': pd.Timestamp('2016-06-27 06:30:00'),
'b1117ada-6eae-418a-8722-e3b1f3593826': pd.Timestamp('2016-06-27 06:49:00'),
'd72e2276-5b11-4d61-a098-84568f9eacc1': pd.Timestamp('2016-06-27 07:05:00'),
'fd566beb-bd42-46a3-8be0-538c9a6b39b0': pd.Timestamp('2016-06-27 07:30:00')}}
SEGMENTS_DF = {'is_long_stop': {'012aa915-76b6-4cf7-aac0-20b698dbb61f': False,
'017245ba-4666-4ad9-8378-96389be01377': False,
'03ddbeba-c800-462b-97b1-de096365402b': False,
'0449c892-8239-49c1-addd-0b307f5f42bd': False,
'05325e3b-8b2b-46b8-958c-0ce5799cfae8': False,
'05986180-bc1d-45d6-a52d-287c947d130b': False,
'08d5da2d-a63e-4cd3-8c1c-815c78f71423': False,
'0c17d884-a4ef-4126-bd5c-7de593acdab8': False,
'0ca89763-863d-485e-881b-232e3de5f7e7': True,
'10619f79-f684-4bf9-8c83-165e809ba5f4': False,
'122c7530-47f5-4f98-aa59-e666ee86b4a9': False,
'12500fe0-312e-40bd-b468-de2afd5ac794': False,
'12bc1db9-8a2a-46ff-b804-d0e320a71c69': False,
'13cee614-8001-4f11-81f0-89d272d00db0': False,
'174f96e0-bcae-456f-8bd1-5685f428c82a': False,
'1921bee8-d213-477b-af87-acdb786a6685': False,
'1b0a2867-aaff-449f-8b55-7fb3a3c28a0a': False,
'1c563a19-f1bb-4fc3-83b4-738f6e6b8a31': False,
'1db8f3d3-8f12-4cf2-8a4c-2df4d822b901': False,
'1e7b1ffa-2e66-4dc4-b401-85c4c92ee602': False,
'1fd28d4a-909c-4464-a62c-6b30fd2179aa': False,
'1ffd4d7d-6c77-40aa-8f17-ff2f7c5011ac': False,
'221973b6-f6bb-442d-9164-9c96a825e4fd': False,
'223ef721-0bc2-4c4f-ba4f-ee24b4e4364b': False,
'24710d17-5227-4764-a583-9a2d58e64f76': False,
'27e28e55-ea6c-44eb-98be-e80a93682fc5': False,
'28abe4d6-5f4e-4aac-9f88-febd5ac05d68': False,
'28e4d325-287a-43de-86ee-e60cc60977c2': False,
'29a2c8c7-3706-426a-961e-88444fabdc6e': False,
'2ab31818-3093-4ae3-b48e-e206475fe071': False,
'2c138c72-d1b0-4cd5-917b-7a39062f258e': False,
'2c4f85d0-1b8e-4738-bde8-1f880b57e5e6': False,
'305486cc-5929-457b-821d-f89fb01a51c2': False,
'30dd1aa1-f689-4073-a75c-65dbe99398c7': False,
'31559fd8-4179-4b37-882a-783ea5e5a00c': False,
'3f1145cd-dfe0-4084-aa03-4e0c539438c1': False,
'401f4497-62da-4c95-85a5-f7212091e780': False,
'450a71eb-42b9-4a49-ac45-405c954a9e8d': False,
'4a2ae77d-71e5-45b3-be16-3cfedd75abda': False,
'4b3d9739-2d37-4c9d-ae98-84b3929775ee': False,
'4da55de8-3ac9-43f5-86d3-baee4db4bf0b': False,
'531ce286-4994-43ce-a580-65e5b073bdca': False,
'53604b52-75ac-4bbe-8114-8f29a876ef28': False,
'5627b65c-aead-4b6e-86af-a25540c28b1e': False,
'5c3743fc-2023-4c29-a90c-07de6a56a71a': False,
'5ef10673-4d9b-4f32-8727-ee716d3a4236': False,
'626eefd5-f049-4626-8b8b-aa0c93f58b16': False,
'660db5e9-55c3-49da-b520-d4683976c4dc': False,
'66fc3195-a832-4837-9350-341ea37c6a53': False,
'681c6d37-9f34-4085-9fda-6134a7bc224e': False,
'6b623efa-1f2d-4767-863f-93286950f9e4': False,
'6c7265b8-d053-4b8b-8d75-46787b1c1bfa': True,
'6e6bdbda-12bd-4dee-b95d-abdc3cd770e4': False,
'708ef2ee-e653-44bc-b885-297df0d91d71': True,
'70a72fbe-9804-4be0-9e6f-81e44fcf8cce': False,
'70aa2417-3a72-4375-a1a1-163e1a3c5c3c': False,
'722b31f3-e5c0-47e4-96ed-67216dd625a9': False,
'7633869e-2c46-48de-8640-63c799c7fc9c': False,
'76380e8c-0e6f-4447-ab1a-0cf588f9fb3c': False,
'769b2118-4507-46bd-9355-1549f6972384': False,
'76a31790-1f32-4263-b1e2-eb3a15d02bdb': False,
'7a4afb37-42ab-4fec-85ed-a78fcbe8c5fc': False,
'7c74103d-5625-4e70-bac1-f9aaec68e9c1': True,
'82253015-eaab-46a8-b319-a459891fda73': False,
'84e48ab6-cbbf-46ed-acca-07f1ab9e0f65': True,
'86598728-fee2-4bc8-b543-fc3eb4bc3614': False,
'8c6e4b22-9163-4290-8e6a-702952268532': False,
'8e45deed-7596-4b55-ae8c-e1ad31394b59': False,
'91a486ed-7cfe-486d-b30e-425b6e52b30b': False,
'92f1c22e-350f-46f3-ba19-f0bc64cbf1d7': False,
'9577411f-9c7f-4d1c-8047-60941e7af1d5': False,
'96c10154-1e94-4df6-9a37-2167edd00a04': False,
'978e3375-98d2-4cc5-b014-96a6c395bb1f': False,
'9f447e9b-e70e-4a46-aa22-7d3544d6dd35': False,
'a7afe35d-a4a2-4bfa-bc53-41793139eb09': False,
'a9f50608-77e0-4778-a6ec-132994d5765c': False,
'ad652142-4f71-403c-93d4-efea27ed601e': False,
'afc7b5ff-468a-433d-b800-311ab180eabd': False,
'b45d8be3-5b19-40d1-b7c4-1359862ac30c': False,
'bc91e6c3-44d3-4e57-9cc7-49e3056e38fc': False,
'c0989f31-0767-403d-b24e-199bba8d1ec0': True,
'c31016fc-a2a9-4d49-a8bd-af7a2bb0a72d': False,
'c402357d-2bc6-4191-ae69-3686657e308b': False,
'c4e850a9-4c76-4a87-afd6-02ae086f1448': False,
'c6e350ef-edda-4e63-b340-550a5b096970': False,
'c85bd7b1-4d8e-4760-b832-d420b29c8d1b': False,
'ce8006ec-4dea-44d8-9934-33824910e681': False,
'd0a2c20b-a795-473b-bb29-3d71636b14f8': False,
'd145e943-2e42-451b-ae43-bc4f991f333d': False,
'd5e552c5-8acd-451d-bdc9-6bec8fa227bf': False,
'd772bc3b-4a68-4cc4-b25c-bbae66c26e81': False,
'd7c64592-e040-46fd-a353-1de5984a4777': False,
'd81a6237-270f-4623-8660-32f21ea3776b': False,
'd85e62e2-579e-4d71-9a34-107977f45713': False,
'd93509e3-33ac-4210-be1d-8d1030d2a84d': False,
'dd8a01c1-210e-4002-8d9d-a273cf98f5af': False,
'e07585f8-d9ae-42ff-9c0a-cf697732d359': False,
'e7f533c0-36f3-4a90-a284-de213fbd230c': False,
'e87e9770-2ce8-4e28-8dee-89f42ecaa4c5': False,
'ea6ad5bd-600a-45c4-aa58-1fada234c6ef': False,
'ed20dffa-61bb-4c70-882c-bdc75f029a6d': False,
'f131ba54-ae59-4992-80aa-8def87bb0f0a': False,
'f3c7ca99-0b09-4d94-b950-808fb8474b96': False,
'f41d67e8-06d4-4fb4-b2a7-67752d722594': False,
'f5d8a7f9-5e40-429b-8443-1842bc7d288f': False,
'f5dae2fc-fb1e-4d5b-8c81-1ed8dbb9b027': False,
'f7efc04b-be14-43eb-944e-b5f0b77f52e3': False,
'f8f501fb-3680-4a13-9ae2-ffddc9bba865': False,
'fba76c03-a7c9-4147-9dce-a22c6ecd53bf': False},
'segment_number': {'012aa915-76b6-4cf7-aac0-20b698dbb61f': 29.0,
'017245ba-4666-4ad9-8378-96389be01377': 9.0,
'03ddbeba-c800-462b-97b1-de096365402b': 16.0,
'0449c892-8239-49c1-addd-0b307f5f42bd': 26.0,
'05325e3b-8b2b-46b8-958c-0ce5799cfae8': 2.0,
'05986180-bc1d-45d6-a52d-287c947d130b': 2.0,
'08d5da2d-a63e-4cd3-8c1c-815c78f71423': 14.0,
'0c17d884-a4ef-4126-bd5c-7de593acdab8': 12.0,
'0ca89763-863d-485e-881b-232e3de5f7e7': 0.0,
'10619f79-f684-4bf9-8c83-165e809ba5f4': 30.0,
'122c7530-47f5-4f98-aa59-e666ee86b4a9': 31.0,
'12500fe0-312e-40bd-b468-de2afd5ac794': 3.0,
'12bc1db9-8a2a-46ff-b804-d0e320a71c69': 2.0,
'13cee614-8001-4f11-81f0-89d272d00db0': 22.0,
'174f96e0-bcae-456f-8bd1-5685f428c82a': 11.0,
'1921bee8-d213-477b-af87-acdb786a6685': 26.0,
'1b0a2867-aaff-449f-8b55-7fb3a3c28a0a': 0.0,
'1c563a19-f1bb-4fc3-83b4-738f6e6b8a31': 8.0,
'1db8f3d3-8f12-4cf2-8a4c-2df4d822b901': 14.0,
'1e7b1ffa-2e66-4dc4-b401-85c4c92ee602': 10.0,
'1fd28d4a-909c-4464-a62c-6b30fd2179aa': 18.0,
'1ffd4d7d-6c77-40aa-8f17-ff2f7c5011ac': 15.0,
'221973b6-f6bb-442d-9164-9c96a825e4fd': 1.0,
'223ef721-0bc2-4c4f-ba4f-ee24b4e4364b': 20.0,
'24710d17-5227-4764-a583-9a2d58e64f76': 1.0,
'27e28e55-ea6c-44eb-98be-e80a93682fc5': 19.0,
'28abe4d6-5f4e-4aac-9f88-febd5ac05d68': 8.0,
'28e4d325-287a-43de-86ee-e60cc60977c2': 4.0,
'29a2c8c7-3706-426a-961e-88444fabdc6e': 4.0,
'2ab31818-3093-4ae3-b48e-e206475fe071': 21.0,
'2c138c72-d1b0-4cd5-917b-7a39062f258e': 21.0,
'2c4f85d0-1b8e-4738-bde8-1f880b57e5e6': 18.0,
'305486cc-5929-457b-821d-f89fb01a51c2': 9.0,
'30dd1aa1-f689-4073-a75c-65dbe99398c7': 0.0,
'31559fd8-4179-4b37-882a-783ea5e5a00c': 31.0,
'3f1145cd-dfe0-4084-aa03-4e0c539438c1': 4.0,
'401f4497-62da-4c95-85a5-f7212091e780': 5.0,
'450a71eb-42b9-4a49-ac45-405c954a9e8d': 15.0,
'4a2ae77d-71e5-45b3-be16-3cfedd75abda': 6.0,
'4b3d9739-2d37-4c9d-ae98-84b3929775ee': 8.0,
'4da55de8-3ac9-43f5-86d3-baee4db4bf0b': 11.0,
'531ce286-4994-43ce-a580-65e5b073bdca': 23.0,
'53604b52-75ac-4bbe-8114-8f29a876ef28': 19.0,
'5627b65c-aead-4b6e-86af-a25540c28b1e': 3.0,
'5c3743fc-2023-4c29-a90c-07de6a56a71a': 5.0,
'5ef10673-4d9b-4f32-8727-ee716d3a4236': 4.0,
'626eefd5-f049-4626-8b8b-aa0c93f58b16': 17.0,
'660db5e9-55c3-49da-b520-d4683976c4dc': 10.0,
'66fc3195-a832-4837-9350-341ea37c6a53': 3.0,
'681c6d37-9f34-4085-9fda-6134a7bc224e': 16.0,
'6b623efa-1f2d-4767-863f-93286950f9e4': 10.0,
'6c7265b8-d053-4b8b-8d75-46787b1c1bfa': 6.0,
'6e6bdbda-12bd-4dee-b95d-abdc3cd770e4': 4.0,
'708ef2ee-e653-44bc-b885-297df0d91d71': 20.0,
'70a72fbe-9804-4be0-9e6f-81e44fcf8cce': 28.0,
'70aa2417-3a72-4375-a1a1-163e1a3c5c3c': 29.0,
'722b31f3-e5c0-47e4-96ed-67216dd625a9': 22.0,
'7633869e-2c46-48de-8640-63c799c7fc9c': 12.0,
'76380e8c-0e6f-4447-ab1a-0cf588f9fb3c': 2.0,
'769b2118-4507-46bd-9355-1549f6972384': 25.0,
'76a31790-1f32-4263-b1e2-eb3a15d02bdb': 9.0,
'7a4afb37-42ab-4fec-85ed-a78fcbe8c5fc': 5.0,
'7c74103d-5625-4e70-bac1-f9aaec68e9c1': 2.0,
'82253015-eaab-46a8-b319-a459891fda73': 30.0,
'84e48ab6-cbbf-46ed-acca-07f1ab9e0f65': 0.0,
'86598728-fee2-4bc8-b543-fc3eb4bc3614': 3.0,
'8c6e4b22-9163-4290-8e6a-702952268532': 6.0,
'8e45deed-7596-4b55-ae8c-e1ad31394b59': 7.0,
'91a486ed-7cfe-486d-b30e-425b6e52b30b': 5.0,
'92f1c22e-350f-46f3-ba19-f0bc64cbf1d7': 27.0,
'9577411f-9c7f-4d1c-8047-60941e7af1d5': 11.0,
'96c10154-1e94-4df6-9a37-2167edd00a04': 13.0,
'978e3375-98d2-4cc5-b014-96a6c395bb1f': 6.0,
'9f447e9b-e70e-4a46-aa22-7d3544d6dd35': 18.0,
'a7afe35d-a4a2-4bfa-bc53-41793139eb09': 24.0,
'a9f50608-77e0-4778-a6ec-132994d5765c': 19.0,
'ad652142-4f71-403c-93d4-efea27ed601e': 6.0,
'afc7b5ff-468a-433d-b800-311ab180eabd': 14.0,
'b45d8be3-5b19-40d1-b7c4-1359862ac30c': 16.0,
'bc91e6c3-44d3-4e57-9cc7-49e3056e38fc': 4.0,
'c0989f31-0767-403d-b24e-199bba8d1ec0': 0.0,
'c31016fc-a2a9-4d49-a8bd-af7a2bb0a72d': 25.0,
'c402357d-2bc6-4191-ae69-3686657e308b': 2.0,
'c4e850a9-4c76-4a87-afd6-02ae086f1448': 7.0,
'c6e350ef-edda-4e63-b340-550a5b096970': 28.0,
'c85bd7b1-4d8e-4760-b832-d420b29c8d1b': 12.0,
'ce8006ec-4dea-44d8-9934-33824910e681': 1.0,
'd0a2c20b-a795-473b-bb29-3d71636b14f8': 1.0,
'd145e943-2e42-451b-ae43-bc4f991f333d': 0.0,
'd5e552c5-8acd-451d-bdc9-6bec8fa227bf': 1.0,
'd772bc3b-4a68-4cc4-b25c-bbae66c26e81': 15.0,
'd7c64592-e040-46fd-a353-1de5984a4777': 27.0,
'd81a6237-270f-4623-8660-32f21ea3776b': 7.0,
'd85e62e2-579e-4d71-9a34-107977f45713': 1.0,
'd93509e3-33ac-4210-be1d-8d1030d2a84d': 17.0,
'dd8a01c1-210e-4002-8d9d-a273cf98f5af': 5.0,
'e07585f8-d9ae-42ff-9c0a-cf697732d359': 17.0,
'e7f533c0-36f3-4a90-a284-de213fbd230c': 5.0,
'e87e9770-2ce8-4e28-8dee-89f42ecaa4c5': 3.0,
'ea6ad5bd-600a-45c4-aa58-1fada234c6ef': 7.0,
'ed20dffa-61bb-4c70-882c-bdc75f029a6d': 0.0,
'f131ba54-ae59-4992-80aa-8def87bb0f0a': 2.0,
'f3c7ca99-0b09-4d94-b950-808fb8474b96': 1.0,
'f41d67e8-06d4-4fb4-b2a7-67752d722594': 3.0,
'f5d8a7f9-5e40-429b-8443-1842bc7d288f': 23.0,
'f5dae2fc-fb1e-4d5b-8c81-1ed8dbb9b027': 13.0,
'f7efc04b-be14-43eb-944e-b5f0b77f52e3': 13.0,
'f8f501fb-3680-4a13-9ae2-ffddc9bba865': 20.0,
'fba76c03-a7c9-4147-9dce-a22c6ecd53bf': 24.0},
'stop_id_end': {'012aa915-76b6-4cf7-aac0-20b698dbb61f': '8500218',
'017245ba-4666-4ad9-8378-96389be01377': '8500208',
'03ddbeba-c800-462b-97b1-de096365402b': '8500211',
'0449c892-8239-49c1-addd-0b307f5f42bd': '8500216',
'05325e3b-8b2b-46b8-958c-0ce5799cfae8': '8502000',
'05986180-bc1d-45d6-a52d-287c947d130b': '8500203',
'08d5da2d-a63e-4cd3-8c1c-815c78f71423': '8502007',
'0c17d884-a4ef-4126-bd5c-7de593acdab8': '8500209',
'0ca89763-863d-485e-881b-232e3de5f7e7': '8500204',
'10619f79-f684-4bf9-8c83-165e809ba5f4': '8500218',
'122c7530-47f5-4f98-aa59-e666ee86b4a9': '8500218',
'12500fe0-312e-40bd-b468-de2afd5ac794': '8500202',
'12bc1db9-8a2a-46ff-b804-d0e320a71c69': '8500205',
'13cee614-8001-4f11-81f0-89d272d00db0': '8500214',
'174f96e0-bcae-456f-8bd1-5685f428c82a': '8502006',
'1921bee8-d213-477b-af87-acdb786a6685': '8500216',
'1b0a2867-aaff-449f-8b55-7fb3a3c28a0a': '8500218',
'1c563a19-f1bb-4fc3-83b4-738f6e6b8a31': '8502004',
'1db8f3d3-8f12-4cf2-8a4c-2df4d822b901': '8500210',
'1e7b1ffa-2e66-4dc4-b401-85c4c92ee602': '8502005',
'1fd28d4a-909c-4464-a62c-6b30fd2179aa': '8500212',
'1ffd4d7d-6c77-40aa-8f17-ff2f7c5011ac': '8502009',
'221973b6-f6bb-442d-9164-9c96a825e4fd': '8500207',
'223ef721-0bc2-4c4f-ba4f-ee24b4e4364b': '8500213',
'24710d17-5227-4764-a583-9a2d58e64f76': '8500205',
'27e28e55-ea6c-44eb-98be-e80a93682fc5': '8505000',
'28abe4d6-5f4e-4aac-9f88-febd5ac05d68': '8500207',
'28e4d325-287a-43de-86ee-e60cc60977c2': '8502007',
'29a2c8c7-3706-426a-961e-88444fabdc6e': '8518963',
'2ab31818-3093-4ae3-b48e-e206475fe071': '8500214',
'2c138c72-d1b0-4cd5-917b-7a39062f258e': '8500214',
'2c4f85d0-1b8e-4738-bde8-1f880b57e5e6': '8502021',
'305486cc-5929-457b-821d-f89fb01a51c2': '8500208',
'30dd1aa1-f689-4073-a75c-65dbe99398c7': '8500202',
'31559fd8-4179-4b37-882a-783ea5e5a00c': '8500218',
'3f1145cd-dfe0-4084-aa03-4e0c539438c1': '8500202',
'401f4497-62da-4c95-85a5-f7212091e780': '8500206',
'450a71eb-42b9-4a49-ac45-405c954a9e8d': '8500211',
'4a2ae77d-71e5-45b3-be16-3cfedd75abda': '8502003',
'4b3d9739-2d37-4c9d-ae98-84b3929775ee': '8500207',
'4da55de8-3ac9-43f5-86d3-baee4db4bf0b': '8500209',
'531ce286-4994-43ce-a580-65e5b073bdca': '8500215',
'53604b52-75ac-4bbe-8114-8f29a876ef28': '8500213',
'5627b65c-aead-4b6e-86af-a25540c28b1e': '8502001',
'5c3743fc-2023-4c29-a90c-07de6a56a71a': '8505000',
'5ef10673-4d9b-4f32-8727-ee716d3a4236': '8502001',
'626eefd5-f049-4626-8b8b-aa0c93f58b16': '8502021',
'660db5e9-55c3-49da-b520-d4683976c4dc': '8500208',
'66fc3195-a832-4837-9350-341ea37c6a53': '8500212',
'681c6d37-9f34-4085-9fda-6134a7bc224e': '8500211',
'6b623efa-1f2d-4767-863f-93286950f9e4': '8500208',
'6c7265b8-d053-4b8b-8d75-46787b1c1bfa': '8505000',
'6e6bdbda-12bd-4dee-b95d-abdc3cd770e4': '8518963',
'708ef2ee-e653-44bc-b885-297df0d91d71': '8505000',
'70a72fbe-9804-4be0-9e6f-81e44fcf8cce': '8500217',
'70aa2417-3a72-4375-a1a1-163e1a3c5c3c': '8500218',
'722b31f3-e5c0-47e4-96ed-67216dd625a9': '8500214',
'7633869e-2c46-48de-8640-63c799c7fc9c': '8502006',
'76380e8c-0e6f-4447-ab1a-0cf588f9fb3c': '8502001',
'769b2118-4507-46bd-9355-1549f6972384': '8500216',
'76a31790-1f32-4263-b1e2-eb3a15d02bdb': '8502005',
'7a4afb37-42ab-4fec-85ed-a78fcbe8c5fc': '8500206',
'7c74103d-5625-4e70-bac1-f9aaec68e9c1': '8505000',
'82253015-eaab-46a8-b319-a459891fda73': '8500218',
'84e48ab6-cbbf-46ed-acca-07f1ab9e0f65': '8500204',
'86598728-fee2-4bc8-b543-fc3eb4bc3614': '8518963',
'8c6e4b22-9163-4290-8e6a-702952268532': '8500206',
'8e45deed-7596-4b55-ae8c-e1ad31394b59': '8500218',
'91a486ed-7cfe-486d-b30e-425b6e52b30b': '8500218',
'92f1c22e-350f-46f3-ba19-f0bc64cbf1d7': '8500217',
'9577411f-9c7f-4d1c-8047-60941e7af1d5': '8500209',
'96c10154-1e94-4df6-9a37-2167edd00a04': '8500210',
'978e3375-98d2-4cc5-b014-96a6c395bb1f': '8500218',
'9f447e9b-e70e-4a46-aa22-7d3544d6dd35': '8500212',
'a7afe35d-a4a2-4bfa-bc53-41793139eb09': '8500215',
'a9f50608-77e0-4778-a6ec-132994d5765c': '8500213',
'ad652142-4f71-403c-93d4-efea27ed601e': '8500206',
'afc7b5ff-468a-433d-b800-311ab180eabd': '8500210',
'b45d8be3-5b19-40d1-b7c4-1359862ac30c': '8502009',
'bc91e6c3-44d3-4e57-9cc7-49e3056e38fc': '8500212',
'c0989f31-0767-403d-b24e-199bba8d1ec0': '8500204',
'c31016fc-a2a9-4d49-a8bd-af7a2bb0a72d': '8500216',
'c402357d-2bc6-4191-ae69-3686657e308b': '8500205',
'c4e850a9-4c76-4a87-afd6-02ae086f1448': '8500207',
'c6e350ef-edda-4e63-b340-550a5b096970': '8500217',
'c85bd7b1-4d8e-4760-b832-d420b29c8d1b': '8500209',
'ce8006ec-4dea-44d8-9934-33824910e681': '8502000',
'd0a2c20b-a795-473b-bb29-3d71636b14f8': '8502001',
'd145e943-2e42-451b-ae43-bc4f991f333d': '8500218',
'd5e552c5-8acd-451d-bdc9-6bec8fa227bf': '8500205',
'd772bc3b-4a68-4cc4-b25c-bbae66c26e81': '8500211',
'd7c64592-e040-46fd-a353-1de5984a4777': '8500217',
'd81a6237-270f-4623-8660-32f21ea3776b': '8500207',
'd85e62e2-579e-4d71-9a34-107977f45713': '8505000',
'd93509e3-33ac-4210-be1d-8d1030d2a84d': '8500212',
'dd8a01c1-210e-4002-8d9d-a273cf98f5af': '8502003',
'e07585f8-d9ae-42ff-9c0a-cf697732d359': '8500212',
'e7f533c0-36f3-4a90-a284-de213fbd230c': '8500202',
'e87e9770-2ce8-4e28-8dee-89f42ecaa4c5': '8502007',
'ea6ad5bd-600a-45c4-aa58-1fada234c6ef': '8502004',
'ed20dffa-61bb-4c70-882c-bdc75f029a6d': '8500218',
'f131ba54-ae59-4992-80aa-8def87bb0f0a': '8500207',
'f3c7ca99-0b09-4d94-b950-808fb8474b96': '8500203',
'f41d67e8-06d4-4fb4-b2a7-67752d722594': '8518963',
'f5d8a7f9-5e40-429b-8443-1842bc7d288f': '8500215',
'f5dae2fc-fb1e-4d5b-8c81-1ed8dbb9b027': '8500210',
'f7efc04b-be14-43eb-944e-b5f0b77f52e3': '8502007',
'f8f501fb-3680-4a13-9ae2-ffddc9bba865': '8500213',
'fba76c03-a7c9-4147-9dce-a22c6ecd53bf': '8500215'},
'stop_id_start': {'012aa915-76b6-4cf7-aac0-20b698dbb61f': '8500217',
'017245ba-4666-4ad9-8378-96389be01377': '8500207',
'03ddbeba-c800-462b-97b1-de096365402b': '8500211',
'0449c892-8239-49c1-addd-0b307f5f42bd': '8500216',
'05325e3b-8b2b-46b8-958c-0ce5799cfae8': '8502000',
'05986180-bc1d-45d6-a52d-287c947d130b': '8500203',
'08d5da2d-a63e-4cd3-8c1c-815c78f71423': '8502007',
'0c17d884-a4ef-4126-bd5c-7de593acdab8': '8500209',
'0ca89763-863d-485e-881b-232e3de5f7e7': '8500204',
'10619f79-f684-4bf9-8c83-165e809ba5f4': '8500218',
'122c7530-47f5-4f98-aa59-e666ee86b4a9': '8500218',
'12500fe0-312e-40bd-b468-de2afd5ac794': '8500203',
'12bc1db9-8a2a-46ff-b804-d0e320a71c69': '8500205',
'13cee614-8001-4f11-81f0-89d272d00db0': '8500214',
'174f96e0-bcae-456f-8bd1-5685f428c82a': '8502005',
'1921bee8-d213-477b-af87-acdb786a6685': '8500216',
'1b0a2867-aaff-449f-8b55-7fb3a3c28a0a': '8500218',
'1c563a19-f1bb-4fc3-83b4-738f6e6b8a31': '8502004',
'1db8f3d3-8f12-4cf2-8a4c-2df4d822b901': '8500210',
'1e7b1ffa-2e66-4dc4-b401-85c4c92ee602': '8502005',
'1fd28d4a-909c-4464-a62c-6b30fd2179aa': '8500212',
'1ffd4d7d-6c77-40aa-8f17-ff2f7c5011ac': '8502007',
'221973b6-f6bb-442d-9164-9c96a825e4fd': '8500202',
'223ef721-0bc2-4c4f-ba4f-ee24b4e4364b': '8500213',
'24710d17-5227-4764-a583-9a2d58e64f76': '8500204',
'27e28e55-ea6c-44eb-98be-e80a93682fc5': '8502021',
'28abe4d6-5f4e-4aac-9f88-febd5ac05d68': '8500207',
'28e4d325-287a-43de-86ee-e60cc60977c2': '8502007',
'29a2c8c7-3706-426a-961e-88444fabdc6e': '8518963',
'2ab31818-3093-4ae3-b48e-e206475fe071': '8500213',
'2c138c72-d1b0-4cd5-917b-7a39062f258e': '8500213',
'2c4f85d0-1b8e-4738-bde8-1f880b57e5e6': '8502021',
'305486cc-5929-457b-821d-f89fb01a51c2': '8500207',
'30dd1aa1-f689-4073-a75c-65dbe99398c7': '8500202',
'31559fd8-4179-4b37-882a-783ea5e5a00c': '8500218',
'3f1145cd-dfe0-4084-aa03-4e0c539438c1': '8500202',
'401f4497-62da-4c95-85a5-f7212091e780': '8518963',
'450a71eb-42b9-4a49-ac45-405c954a9e8d': '8500210',
'4a2ae77d-71e5-45b3-be16-3cfedd75abda': '8502003',
'4b3d9739-2d37-4c9d-ae98-84b3929775ee': '8500207',
'4da55de8-3ac9-43f5-86d3-baee4db4bf0b': '8500208',
'531ce286-4994-43ce-a580-65e5b073bdca': '8500214',
'53604b52-75ac-4bbe-8114-8f29a876ef28': '8500212',
'5627b65c-aead-4b6e-86af-a25540c28b1e': '8502000',
'5c3743fc-2023-4c29-a90c-07de6a56a71a': '8502007',
'5ef10673-4d9b-4f32-8727-ee716d3a4236': '8502001',
'626eefd5-f049-4626-8b8b-aa0c93f58b16': '8502009',
'660db5e9-55c3-49da-b520-d4683976c4dc': '8500208',
'66fc3195-a832-4837-9350-341ea37c6a53': '8500207',
'681c6d37-9f34-4085-9fda-6134a7bc224e': '8500211',
'6b623efa-1f2d-4767-863f-93286950f9e4': '8500208',
'6c7265b8-d053-4b8b-8d75-46787b1c1bfa': '8505000',
'6e6bdbda-12bd-4dee-b95d-abdc3cd770e4': '8518963',
'708ef2ee-e653-44bc-b885-297df0d91d71': '8505000',
'70a72fbe-9804-4be0-9e6f-81e44fcf8cce': '8500217',
'70aa2417-3a72-4375-a1a1-163e1a3c5c3c': '8500217',
'722b31f3-e5c0-47e4-96ed-67216dd625a9': '8500214',
'7633869e-2c46-48de-8640-63c799c7fc9c': '8502006',
'76380e8c-0e6f-4447-ab1a-0cf588f9fb3c': '8502001',
'769b2118-4507-46bd-9355-1549f6972384': '8500215',
'76a31790-1f32-4263-b1e2-eb3a15d02bdb': '8502004',
'7a4afb37-42ab-4fec-85ed-a78fcbe8c5fc': '8518963',
'7c74103d-5625-4e70-bac1-f9aaec68e9c1': '8505000',
'82253015-eaab-46a8-b319-a459891fda73': '8500218',
'84e48ab6-cbbf-46ed-acca-07f1ab9e0f65': '8500204',
'86598728-fee2-4bc8-b543-fc3eb4bc3614': '8500205',
'8c6e4b22-9163-4290-8e6a-702952268532': '8500206',
'8e45deed-7596-4b55-ae8c-e1ad31394b59': '8500218',
'91a486ed-7cfe-486d-b30e-425b6e52b30b': '8500212',
'92f1c22e-350f-46f3-ba19-f0bc64cbf1d7': '8500216',
'9577411f-9c7f-4d1c-8047-60941e7af1d5': '8500208',
'96c10154-1e94-4df6-9a37-2167edd00a04': '8500209',
'978e3375-98d2-4cc5-b014-96a6c395bb1f': '8500218',
'9f447e9b-e70e-4a46-aa22-7d3544d6dd35': '8500212',
'a7afe35d-a4a2-4bfa-bc53-41793139eb09': '8500215',
'a9f50608-77e0-4778-a6ec-132994d5765c': '8500212',
'ad652142-4f71-403c-93d4-efea27ed601e': '8500206',
'afc7b5ff-468a-433d-b800-311ab180eabd': '8500210',
'b45d8be3-5b19-40d1-b7c4-1359862ac30c': '8502009',
'bc91e6c3-44d3-4e57-9cc7-49e3056e38fc': '8500212',
'c0989f31-0767-403d-b24e-199bba8d1ec0': '8500204',
'c31016fc-a2a9-4d49-a8bd-af7a2bb0a72d': '8500215',
'c402357d-2bc6-4191-ae69-3686657e308b': '8500205',
'c4e850a9-4c76-4a87-afd6-02ae086f1448': '8500206',
'c6e350ef-edda-4e63-b340-550a5b096970': '8500217',
'c85bd7b1-4d8e-4760-b832-d420b29c8d1b': '8500209',
'ce8006ec-4dea-44d8-9934-33824910e681': '8500218',
'd0a2c20b-a795-473b-bb29-3d71636b14f8': '8500218',
'd145e943-2e42-451b-ae43-bc4f991f333d': '8500218',
'd5e552c5-8acd-451d-bdc9-6bec8fa227bf': '8500204',
'd772bc3b-4a68-4cc4-b25c-bbae66c26e81': '8500210',
'd7c64592-e040-46fd-a353-1de5984a4777': '8500216',
'd81a6237-270f-4623-8660-32f21ea3776b': '8500206',
'd85e62e2-579e-4d71-9a34-107977f45713': '8500218',
'd93509e3-33ac-4210-be1d-8d1030d2a84d': '8500211',
'dd8a01c1-210e-4002-8d9d-a273cf98f5af': '8502001',
'e07585f8-d9ae-42ff-9c0a-cf697732d359': '8500211',
'e7f533c0-36f3-4a90-a284-de213fbd230c': '8500202',
'e87e9770-2ce8-4e28-8dee-89f42ecaa4c5': '8502001',
'ea6ad5bd-600a-45c4-aa58-1fada234c6ef': '8502003',
'ed20dffa-61bb-4c70-882c-bdc75f029a6d': '8500218',
'f131ba54-ae59-4992-80aa-8def87bb0f0a': '8500207',
'f3c7ca99-0b09-4d94-b950-808fb8474b96': '8500204',
'f41d67e8-06d4-4fb4-b2a7-67752d722594': '8500205',
'f5d8a7f9-5e40-429b-8443-1842bc7d288f': '8500214',
'f5dae2fc-fb1e-4d5b-8c81-1ed8dbb9b027': '8500209',
'f7efc04b-be14-43eb-944e-b5f0b77f52e3': '8502006',
'f8f501fb-3680-4a13-9ae2-ffddc9bba865': '8500213',
'fba76c03-a7c9-4147-9dce-a22c6ecd53bf': '8500215'},
'time_end': {'012aa915-76b6-4cf7-aac0-20b698dbb61f': pd.Timestamp('2016-06-27 06:24:00'),
'017245ba-4666-4ad9-8378-96389be01377': pd.Timestamp('2016-06-27 05:51:00'),
'03ddbeba-c800-462b-97b1-de096365402b': pd.Timestamp('2016-06-27 06:02:00'),
'0449c892-8239-49c1-addd-0b307f5f42bd': pd.Timestamp('2016-06-27 06:17:00'),
'05325e3b-8b2b-46b8-958c-0ce5799cfae8': pd.Timestamp('2016-06-27 06:09:00'),
'05986180-bc1d-45d6-a52d-287c947d130b': pd.Timestamp('2016-06-27 05:21:00'),
'08d5da2d-a63e-4cd3-8c1c-815c78f71423': pd.Timestamp('2016-06-27 06:32:00'),
'0c17d884-a4ef-4126-bd5c-7de593acdab8': pd.Timestamp('2016-06-27 05:54:00'),
'0ca89763-863d-485e-881b-232e3de5f7e7': pd.Timestamp('2016-06-27 05:40:00'),
'10619f79-f684-4bf9-8c83-165e809ba5f4': pd.Timestamp('2016-06-27 06:24:00'),
'122c7530-47f5-4f98-aa59-e666ee86b4a9': pd.Timestamp('2016-06-27 06:30:00'),
'12500fe0-312e-40bd-b468-de2afd5ac794': pd.Timestamp('2016-06-27 05:23:00'),
'12bc1db9-8a2a-46ff-b804-d0e320a71c69': pd.Timestamp('2016-06-27 05:42:00'),
'13cee614-8001-4f11-81f0-89d272d00db0': pd.Timestamp('2016-06-27 06:11:00'),
'174f96e0-bcae-456f-8bd1-5685f428c82a': pd.Timestamp('2016-06-27 06:26:00'),
'1921bee8-d213-477b-af87-acdb786a6685': pd.Timestamp('2016-06-27 06:17:00'),
'1b0a2867-aaff-449f-8b55-7fb3a3c28a0a': pd.Timestamp('2016-06-27 06:06:00'),
'1c563a19-f1bb-4fc3-83b4-738f6e6b8a31': pd.Timestamp('2016-06-27 06:19:00'),
'1db8f3d3-8f12-4cf2-8a4c-2df4d822b901': pd.Timestamp('2016-06-27 05:57:00'),
'1e7b1ffa-2e66-4dc4-b401-85c4c92ee602': pd.Timestamp('2016-06-27 06:23:00'),
'1fd28d4a-909c-4464-a62c-6b30fd2179aa': pd.Timestamp('2016-06-27 06:05:00'),
'1ffd4d7d-6c77-40aa-8f17-ff2f7c5011ac': pd.Timestamp('2016-06-27 06:38:00'),
'221973b6-f6bb-442d-9164-9c96a825e4fd': pd.Timestamp('2016-06-27 05:31:00'),
'223ef721-0bc2-4c4f-ba4f-ee24b4e4364b': pd.Timestamp('2016-06-27 06:08:00'),
'24710d17-5227-4764-a583-9a2d58e64f76': pd.Timestamp('2016-06-27 05:42:00'),
'27e28e55-ea6c-44eb-98be-e80a93682fc5': pd.Timestamp('2016-06-27 06:55:00'),
'28abe4d6-5f4e-4aac-9f88-febd5ac05d68': pd.Timestamp('2016-06-27 05:49:00'),
'28e4d325-287a-43de-86ee-e60cc60977c2': pd.Timestamp('2016-06-27 07:11:00'),
'29a2c8c7-3706-426a-961e-88444fabdc6e': pd.Timestamp('2016-06-27 05:44:00'),
'2ab31818-3093-4ae3-b48e-e206475fe071': pd.Timestamp('2016-06-27 06:11:00'),
'2c138c72-d1b0-4cd5-917b-7a39062f258e': pd.Timestamp('2016-06-27 06:11:00'),
'2c4f85d0-1b8e-4738-bde8-1f880b57e5e6': pd.Timestamp('2016-06-27 06:46:00'),
'305486cc-5929-457b-821d-f89fb01a51c2': pd.Timestamp('2016-06-27 05:51:00'),
'30dd1aa1-f689-4073-a75c-65dbe99398c7': pd.Timestamp('2016-06-27 05:25:00'),
'31559fd8-4179-4b37-882a-783ea5e5a00c': pd.Timestamp('2016-06-27 06:47:00'),
'3f1145cd-dfe0-4084-aa03-4e0c539438c1': pd.Timestamp('2016-06-27 05:24:00'),
'401f4497-62da-4c95-85a5-f7212091e780': pd.Timestamp('2016-06-27 05:45:00'),
'450a71eb-42b9-4a49-ac45-405c954a9e8d': pd.Timestamp('2016-06-27 06:02:00'),
'4a2ae77d-71e5-45b3-be16-3cfedd75abda': pd.Timestamp('2016-06-27 06:17:00'),
'4b3d9739-2d37-4c9d-ae98-84b3929775ee': pd.Timestamp('2016-06-27 05:49:00'),
'4da55de8-3ac9-43f5-86d3-baee4db4bf0b': pd.Timestamp('2016-06-27 05:54:00'),
'531ce286-4994-43ce-a580-65e5b073bdca': pd.Timestamp('2016-06-27 06:14:00'),
'53604b52-75ac-4bbe-8114-8f29a876ef28': pd.Timestamp('2016-06-27 06:08:00'),
'5627b65c-aead-4b6e-86af-a25540c28b1e': pd.Timestamp('2016-06-27 06:13:00'),
'5c3743fc-2023-4c29-a90c-07de6a56a71a': pd.Timestamp('2016-06-27 07:30:00'),
'5ef10673-4d9b-4f32-8727-ee716d3a4236': pd.Timestamp('2016-06-27 06:13:00'),
'626eefd5-f049-4626-8b8b-aa0c93f58b16': pd.Timestamp('2016-06-27 06:46:00'),
'660db5e9-55c3-49da-b520-d4683976c4dc': pd.Timestamp('2016-06-27 05:51:00'),
'66fc3195-a832-4837-9350-341ea37c6a53': pd.Timestamp('2016-06-27 05:44:00'),
'681c6d37-9f34-4085-9fda-6134a7bc224e': pd.Timestamp('2016-06-27 06:02:00'),
'6b623efa-1f2d-4767-863f-93286950f9e4': pd.Timestamp('2016-06-27 05:51:00'),
'6c7265b8-d053-4b8b-8d75-46787b1c1bfa': pd.Timestamp('2016-06-27 07:40:00'),
'6e6bdbda-12bd-4dee-b95d-abdc3cd770e4': pd.Timestamp('2016-06-27 05:44:00'),
'708ef2ee-e653-44bc-b885-297df0d91d71': pd.Timestamp('2016-06-27 07:05:00'),
'70a72fbe-9804-4be0-9e6f-81e44fcf8cce': pd.Timestamp('2016-06-27 06:19:00'),
'70aa2417-3a72-4375-a1a1-163e1a3c5c3c': pd.Timestamp('2016-06-27 06:24:00'),
'722b31f3-e5c0-47e4-96ed-67216dd625a9': pd.Timestamp('2016-06-27 06:11:00'),
'7633869e-2c46-48de-8640-63c799c7fc9c': pd.Timestamp('2016-06-27 06:26:00'),
'76380e8c-0e6f-4447-ab1a-0cf588f9fb3c': pd.Timestamp('2016-06-27 06:58:00'),
'769b2118-4507-46bd-9355-1549f6972384': pd.Timestamp('2016-06-27 06:17:00'),
'76a31790-1f32-4263-b1e2-eb3a15d02bdb': pd.Timestamp('2016-06-27 06:22:00'),
'7a4afb37-42ab-4fec-85ed-a78fcbe8c5fc': pd.Timestamp('2016-06-27 05:45:00'),
'7c74103d-5625-4e70-bac1-f9aaec68e9c1': pd.Timestamp('2016-06-27 07:15:00'),
'82253015-eaab-46a8-b319-a459891fda73': pd.Timestamp('2016-06-27 06:24:00'),
'84e48ab6-cbbf-46ed-acca-07f1ab9e0f65': pd.Timestamp('2016-06-27 05:19:00'),
'86598728-fee2-4bc8-b543-fc3eb4bc3614': pd.Timestamp('2016-06-27 05:44:00'),
'8c6e4b22-9163-4290-8e6a-702952268532': pd.Timestamp('2016-06-27 05:45:00'),
'8e45deed-7596-4b55-ae8c-e1ad31394b59': pd.Timestamp('2016-06-27 06:06:00'),
'91a486ed-7cfe-486d-b30e-425b6e52b30b': pd.Timestamp('2016-06-27 05:57:00'),
'92f1c22e-350f-46f3-ba19-f0bc64cbf1d7': pd.Timestamp('2016-06-27 06:19:00'),
'9577411f-9c7f-4d1c-8047-60941e7af1d5': pd.Timestamp('2016-06-27 05:54:00'),
'96c10154-1e94-4df6-9a37-2167edd00a04': pd.Timestamp('2016-06-27 05:57:00'),
'978e3375-98d2-4cc5-b014-96a6c395bb1f': pd.Timestamp('2016-06-27 05:59:00'),
'9f447e9b-e70e-4a46-aa22-7d3544d6dd35': pd.Timestamp('2016-06-27 06:05:00'),
'a7afe35d-a4a2-4bfa-bc53-41793139eb09': pd.Timestamp('2016-06-27 06:14:00'),
'a9f50608-77e0-4778-a6ec-132994d5765c': pd.Timestamp('2016-06-27 06:08:00'),
'ad652142-4f71-403c-93d4-efea27ed601e': pd.Timestamp('2016-06-27 05:45:00'),
'afc7b5ff-468a-433d-b800-311ab180eabd': pd.Timestamp('2016-06-27 05:57:00'),
'b45d8be3-5b19-40d1-b7c4-1359862ac30c': pd.Timestamp('2016-06-27 06:38:00'),
'bc91e6c3-44d3-4e57-9cc7-49e3056e38fc': pd.Timestamp('2016-06-27 05:45:00'),
'c0989f31-0767-403d-b24e-199bba8d1ec0': pd.Timestamp('2016-06-27 05:40:00'),
'c31016fc-a2a9-4d49-a8bd-af7a2bb0a72d': pd.Timestamp('2016-06-27 06:17:00'),
'c402357d-2bc6-4191-ae69-3686657e308b': pd.Timestamp('2016-06-27 05:42:00'),
'c4e850a9-4c76-4a87-afd6-02ae086f1448': pd.Timestamp('2016-06-27 05:48:00'),
'c6e350ef-edda-4e63-b340-550a5b096970': pd.Timestamp('2016-06-27 06:19:00'),
'c85bd7b1-4d8e-4760-b832-d420b29c8d1b': pd.Timestamp('2016-06-27 05:54:00'),
'ce8006ec-4dea-44d8-9934-33824910e681': pd.Timestamp('2016-06-27 06:09:00'),
'd0a2c20b-a795-473b-bb29-3d71636b14f8': pd.Timestamp('2016-06-27 06:56:00'),
'd145e943-2e42-451b-ae43-bc4f991f333d': pd.Timestamp('2016-06-27 06:49:00'),
'd5e552c5-8acd-451d-bdc9-6bec8fa227bf': pd.Timestamp('2016-06-27 05:42:00'),
'd772bc3b-4a68-4cc4-b25c-bbae66c26e81': pd.Timestamp('2016-06-27 06:02:00'),
'd7c64592-e040-46fd-a353-1de5984a4777': pd.Timestamp('2016-06-27 06:19:00'),
'd81a6237-270f-4623-8660-32f21ea3776b': pd.Timestamp('2016-06-27 05:48:00'),
'd85e62e2-579e-4d71-9a34-107977f45713': pd.Timestamp('2016-06-27 07:05:00'),
'd93509e3-33ac-4210-be1d-8d1030d2a84d': pd.Timestamp('2016-06-27 06:05:00'),
'dd8a01c1-210e-4002-8d9d-a273cf98f5af': pd.Timestamp('2016-06-27 06:17:00'),
'e07585f8-d9ae-42ff-9c0a-cf697732d359': pd.Timestamp('2016-06-27 06:05:00'),
'e7f533c0-36f3-4a90-a284-de213fbd230c': pd.Timestamp('2016-06-27 05:24:00'),
'e87e9770-2ce8-4e28-8dee-89f42ecaa4c5': pd.Timestamp('2016-06-27 07:10:00'),
'ea6ad5bd-600a-45c4-aa58-1fada234c6ef': pd.Timestamp('2016-06-27 06:19:00'),
'ed20dffa-61bb-4c70-882c-bdc75f029a6d': pd.Timestamp('2016-06-27 06:30:00'),
'f131ba54-ae59-4992-80aa-8def87bb0f0a': pd.Timestamp('2016-06-27 05:33:00'),
'f3c7ca99-0b09-4d94-b950-808fb8474b96': pd.Timestamp('2016-06-27 05:21:00'),
'f41d67e8-06d4-4fb4-b2a7-67752d722594': pd.Timestamp('2016-06-27 05:44:00'),
'f5d8a7f9-5e40-429b-8443-1842bc7d288f': pd.Timestamp('2016-06-27 06:14:00'),
'f5dae2fc-fb1e-4d5b-8c81-1ed8dbb9b027': pd.Timestamp('2016-06-27 05:57:00'),
'f7efc04b-be14-43eb-944e-b5f0b77f52e3': pd.Timestamp('2016-06-27 06:31:00'),
'f8f501fb-3680-4a13-9ae2-ffddc9bba865': pd.Timestamp('2016-06-27 06:08:00'),
'fba76c03-a7c9-4147-9dce-a22c6ecd53bf': pd.Timestamp('2016-06-27 06:14:00')},
'time_start': {'012aa915-76b6-4cf7-aac0-20b698dbb61f': pd.Timestamp('2016-06-27 06:19:00'),
'017245ba-4666-4ad9-8378-96389be01377': pd.Timestamp('2016-06-27 05:49:00'),
'03ddbeba-c800-462b-97b1-de096365402b': pd.Timestamp('2016-06-27 06:02:00'),
'0449c892-8239-49c1-addd-0b307f5f42bd': pd.Timestamp('2016-06-27 06:17:00'),
'05325e3b-8b2b-46b8-958c-0ce5799cfae8': pd.Timestamp('2016-06-27 06:09:00'),
'05986180-bc1d-45d6-a52d-287c947d130b': pd.Timestamp('2016-06-27 05:21:00'),
'08d5da2d-a63e-4cd3-8c1c-815c78f71423': pd.Timestamp('2016-06-27 06:31:00'),
'0c17d884-a4ef-4126-bd5c-7de593acdab8': pd.Timestamp('2016-06-27 05:54:00'),
'0ca89763-863d-485e-881b-232e3de5f7e7': pd.Timestamp('2016-06-27 05:30:00'),
'10619f79-f684-4bf9-8c83-165e809ba5f4': pd.Timestamp('2016-06-27 06:24:00'),
'122c7530-47f5-4f98-aa59-e666ee86b4a9': pd.Timestamp('2016-06-27 06:24:00'),
'12500fe0-312e-40bd-b468-de2afd5ac794': pd.Timestamp('2016-06-27 05:21:00'),
'12bc1db9-8a2a-46ff-b804-d0e320a71c69': pd.Timestamp('2016-06-27 05:42:00'),
'13cee614-8001-4f11-81f0-89d272d00db0': pd.Timestamp('2016-06-27 06:11:00'),
'174f96e0-bcae-456f-8bd1-5685f428c82a': pd.Timestamp('2016-06-27 06:23:00'),
'1921bee8-d213-477b-af87-acdb786a6685': pd.Timestamp('2016-06-27 06:17:00'),
'1b0a2867-aaff-449f-8b55-7fb3a3c28a0a': pd.Timestamp('2016-06-27 06:06:00'),
'1c563a19-f1bb-4fc3-83b4-738f6e6b8a31': pd.Timestamp('2016-06-27 06:19:00'),
'1db8f3d3-8f12-4cf2-8a4c-2df4d822b901': pd.Timestamp('2016-06-27 05:57:00'),
'1e7b1ffa-2e66-4dc4-b401-85c4c92ee602': pd.Timestamp('2016-06-27 06:22:00'),
'1fd28d4a-909c-4464-a62c-6b30fd2179aa': pd.Timestamp('2016-06-27 06:05:00'),
'1ffd4d7d-6c77-40aa-8f17-ff2f7c5011ac': pd.Timestamp('2016-06-27 06:32:00'),
'221973b6-f6bb-442d-9164-9c96a825e4fd': pd.Timestamp('2016-06-27 05:25:00'),
'223ef721-0bc2-4c4f-ba4f-ee24b4e4364b': pd.Timestamp('2016-06-27 06:08:00'),
'24710d17-5227-4764-a583-9a2d58e64f76': pd.Timestamp('2016-06-27 05:40:00'),
'27e28e55-ea6c-44eb-98be-e80a93682fc5': pd.Timestamp('2016-06-27 06:46:00'),
'28abe4d6-5f4e-4aac-9f88-febd5ac05d68': pd.Timestamp('2016-06-27 05:48:00'),
'28e4d325-287a-43de-86ee-e60cc60977c2': pd.Timestamp('2016-06-27 07:10:00'),
'29a2c8c7-3706-426a-961e-88444fabdc6e': pd.Timestamp('2016-06-27 05:44:00'),
'2ab31818-3093-4ae3-b48e-e206475fe071': pd.Timestamp('2016-06-27 06:08:00'),
'2c138c72-d1b0-4cd5-917b-7a39062f258e': pd.Timestamp('2016-06-27 06:08:00'),
'2c4f85d0-1b8e-4738-bde8-1f880b57e5e6': pd.Timestamp('2016-06-27 06:46:00'),
'305486cc-5929-457b-821d-f89fb01a51c2': pd.Timestamp('2016-06-27 05:49:00'),
'30dd1aa1-f689-4073-a75c-65dbe99398c7': pd.Timestamp('2016-06-27 05:24:00'),
'31559fd8-4179-4b37-882a-783ea5e5a00c': pd.Timestamp('2016-06-27 06:24:00'),
'3f1145cd-dfe0-4084-aa03-4e0c539438c1': pd.Timestamp('2016-06-27 05:23:00'),
'401f4497-62da-4c95-85a5-f7212091e780': pd.Timestamp('2016-06-27 05:44:00'),
'450a71eb-42b9-4a49-ac45-405c954a9e8d': pd.Timestamp('2016-06-27 05:57:00'),
'4a2ae77d-71e5-45b3-be16-3cfedd75abda': pd.Timestamp('2016-06-27 06:17:00'),
'4b3d9739-2d37-4c9d-ae98-84b3929775ee': pd.Timestamp('2016-06-27 05:48:00'),
'4da55de8-3ac9-43f5-86d3-baee4db4bf0b': pd.Timestamp('2016-06-27 05:51:00'),
'531ce286-4994-43ce-a580-65e5b073bdca': pd.Timestamp('2016-06-27 06:11:00'),
'53604b52-75ac-4bbe-8114-8f29a876ef28': pd.Timestamp('2016-06-27 06:05:00'),
'5627b65c-aead-4b6e-86af-a25540c28b1e': pd.Timestamp('2016-06-27 06:09:00'),
'5c3743fc-2023-4c29-a90c-07de6a56a71a': pd.Timestamp('2016-06-27 07:11:00'),
'5ef10673-4d9b-4f32-8727-ee716d3a4236': pd.Timestamp('2016-06-27 06:13:00'),
'626eefd5-f049-4626-8b8b-aa0c93f58b16': pd.Timestamp('2016-06-27 06:38:00'),
'660db5e9-55c3-49da-b520-d4683976c4dc': pd.Timestamp('2016-06-27 05:51:00'),
'66fc3195-a832-4837-9350-341ea37c6a53': pd.Timestamp('2016-06-27 05:33:00'),
'681c6d37-9f34-4085-9fda-6134a7bc224e': pd.Timestamp('2016-06-27 06:02:00'),
'6b623efa-1f2d-4767-863f-93286950f9e4': pd.Timestamp('2016-06-27 05:51:00'),
'6c7265b8-d053-4b8b-8d75-46787b1c1bfa': pd.Timestamp('2016-06-27 07:30:00'),
'6e6bdbda-12bd-4dee-b95d-abdc3cd770e4': pd.Timestamp('2016-06-27 05:44:00'),
'708ef2ee-e653-44bc-b885-297df0d91d71': pd.Timestamp('2016-06-27 06:55:00'),
'70a72fbe-9804-4be0-9e6f-81e44fcf8cce': pd.Timestamp('2016-06-27 06:19:00'),
'70aa2417-3a72-4375-a1a1-163e1a3c5c3c': pd.Timestamp('2016-06-27 06:19:00'),
'722b31f3-e5c0-47e4-96ed-67216dd625a9': pd.Timestamp('2016-06-27 06:11:00'),
'7633869e-2c46-48de-8640-63c799c7fc9c': pd.Timestamp('2016-06-27 06:26:00'),
'76380e8c-0e6f-4447-ab1a-0cf588f9fb3c': pd.Timestamp('2016-06-27 06:56:00'),
'769b2118-4507-46bd-9355-1549f6972384': pd.Timestamp('2016-06-27 06:14:00'),
'76a31790-1f32-4263-b1e2-eb3a15d02bdb': pd.Timestamp('2016-06-27 06:19:00'),
'7a4afb37-42ab-4fec-85ed-a78fcbe8c5fc': pd.Timestamp('2016-06-27 05:44:00'),
'7c74103d-5625-4e70-bac1-f9aaec68e9c1': pd.Timestamp('2016-06-27 07:05:00'),
'82253015-eaab-46a8-b319-a459891fda73': pd.Timestamp('2016-06-27 06:24:00'),
'84e48ab6-cbbf-46ed-acca-07f1ab9e0f65': pd.Timestamp('2016-06-27 05:09:00'),
'86598728-fee2-4bc8-b543-fc3eb4bc3614': pd.Timestamp('2016-06-27 05:42:00'),
'8c6e4b22-9163-4290-8e6a-702952268532': pd.Timestamp('2016-06-27 05:45:00'),
'8e45deed-7596-4b55-ae8c-e1ad31394b59': pd.Timestamp('2016-06-27 05:59:00'),
'91a486ed-7cfe-486d-b30e-425b6e52b30b': pd.Timestamp('2016-06-27 05:45:00'),
'92f1c22e-350f-46f3-ba19-f0bc64cbf1d7': pd.Timestamp('2016-06-27 06:17:00'),
'9577411f-9c7f-4d1c-8047-60941e7af1d5': pd.Timestamp('2016-06-27 05:51:00'),
'96c10154-1e94-4df6-9a37-2167edd00a04': pd.Timestamp('2016-06-27 05:54:00'),
'978e3375-98d2-4cc5-b014-96a6c395bb1f': pd.Timestamp('2016-06-27 05:57:00'),
'9f447e9b-e70e-4a46-aa22-7d3544d6dd35': pd.Timestamp('2016-06-27 06:05:00'),
'a7afe35d-a4a2-4bfa-bc53-41793139eb09': pd.Timestamp('2016-06-27 06:14:00'),
'a9f50608-77e0-4778-a6ec-132994d5765c': pd.Timestamp('2016-06-27 06:05:00'),
'ad652142-4f71-403c-93d4-efea27ed601e': pd.Timestamp('2016-06-27 05:45:00'),
'afc7b5ff-468a-433d-b800-311ab180eabd': pd.Timestamp('2016-06-27 05:57:00'),
'b45d8be3-5b19-40d1-b7c4-1359862ac30c': pd.Timestamp('2016-06-27 06:38:00'),
'bc91e6c3-44d3-4e57-9cc7-49e3056e38fc': pd.Timestamp('2016-06-27 05:44:00'),
'c0989f31-0767-403d-b24e-199bba8d1ec0': pd.Timestamp('2016-06-27 05:30:00'),
'c31016fc-a2a9-4d49-a8bd-af7a2bb0a72d': pd.Timestamp('2016-06-27 06:14:00'),
'c402357d-2bc6-4191-ae69-3686657e308b': pd.Timestamp('2016-06-27 05:42:00'),
'c4e850a9-4c76-4a87-afd6-02ae086f1448': pd.Timestamp('2016-06-27 05:45:00'),
'c6e350ef-edda-4e63-b340-550a5b096970': pd.Timestamp('2016-06-27 06:19:00'),
'c85bd7b1-4d8e-4760-b832-d420b29c8d1b': pd.Timestamp('2016-06-27 05:54:00'),
'ce8006ec-4dea-44d8-9934-33824910e681': pd.Timestamp('2016-06-27 06:06:00'),
'd0a2c20b-a795-473b-bb29-3d71636b14f8': pd.Timestamp('2016-06-27 06:49:00'),
'd145e943-2e42-451b-ae43-bc4f991f333d': pd.Timestamp('2016-06-27 06:47:00'),
'd5e552c5-8acd-451d-bdc9-6bec8fa227bf': pd.Timestamp('2016-06-27 05:40:00'),
'd772bc3b-4a68-4cc4-b25c-bbae66c26e81': pd.Timestamp('2016-06-27 05:57:00'),
'd7c64592-e040-46fd-a353-1de5984a4777': pd.Timestamp('2016-06-27 06:17:00'),
'd81a6237-270f-4623-8660-32f21ea3776b': pd.Timestamp('2016-06-27 05:45:00'),
'd85e62e2-579e-4d71-9a34-107977f45713': pd.Timestamp('2016-06-27 06:30:00'),
'd93509e3-33ac-4210-be1d-8d1030d2a84d': pd.Timestamp('2016-06-27 06:02:00'),
'dd8a01c1-210e-4002-8d9d-a273cf98f5af': pd.Timestamp('2016-06-27 06:13:00'),
'e07585f8-d9ae-42ff-9c0a-cf697732d359': pd.Timestamp('2016-06-27 06:02:00'),
'e7f533c0-36f3-4a90-a284-de213fbd230c': pd.Timestamp('2016-06-27 05:24:00'),
'e87e9770-2ce8-4e28-8dee-89f42ecaa4c5': pd.Timestamp('2016-06-27 06:58:00'),
'ea6ad5bd-600a-45c4-aa58-1fada234c6ef': pd.Timestamp('2016-06-27 06:17:00'),
'ed20dffa-61bb-4c70-882c-bdc75f029a6d': pd.Timestamp('2016-06-27 06:30:00'),
'f131ba54-ae59-4992-80aa-8def87bb0f0a': pd.Timestamp('2016-06-27 05:31:00'),
'f3c7ca99-0b09-4d94-b950-808fb8474b96': pd.Timestamp('2016-06-27 05:19:00'),
'f41d67e8-06d4-4fb4-b2a7-67752d722594': pd.Timestamp('2016-06-27 05:42:00'),
'f5d8a7f9-5e40-429b-8443-1842bc7d288f': pd.Timestamp('2016-06-27 06:11:00'),
'f5dae2fc-fb1e-4d5b-8c81-1ed8dbb9b027': pd.Timestamp('2016-06-27 05:54:00'),
'f7efc04b-be14-43eb-944e-b5f0b77f52e3': pd.Timestamp('2016-06-27 06:26:00'),
'f8f501fb-3680-4a13-9ae2-ffddc9bba865': pd.Timestamp('2016-06-27 06:08:00'),
'fba76c03-a7c9-4147-9dce-a22c6ecd53bf': pd.Timestamp('2016-06-27 06:14:00')},
'waypoint': {'012aa915-76b6-4cf7-aac0-20b698dbb61f': False,
'017245ba-4666-4ad9-8378-96389be01377': False,
'03ddbeba-c800-462b-97b1-de096365402b': False,
'0449c892-8239-49c1-addd-0b307f5f42bd': False,
'05325e3b-8b2b-46b8-958c-0ce5799cfae8': False,
'05986180-bc1d-45d6-a52d-287c947d130b': False,
'08d5da2d-a63e-4cd3-8c1c-815c78f71423': False,
'0c17d884-a4ef-4126-bd5c-7de593acdab8': False,
'0ca89763-863d-485e-881b-232e3de5f7e7': False,
'10619f79-f684-4bf9-8c83-165e809ba5f4': False,
'122c7530-47f5-4f98-aa59-e666ee86b4a9': False,
'12500fe0-312e-40bd-b468-de2afd5ac794': False,
'12bc1db9-8a2a-46ff-b804-d0e320a71c69': False,
'13cee614-8001-4f11-81f0-89d272d00db0': False,
'174f96e0-bcae-456f-8bd1-5685f428c82a': False,
'1921bee8-d213-477b-af87-acdb786a6685': False,
'1b0a2867-aaff-449f-8b55-7fb3a3c28a0a': False,
'1c563a19-f1bb-4fc3-83b4-738f6e6b8a31': False,
'1db8f3d3-8f12-4cf2-8a4c-2df4d822b901': False,
'1e7b1ffa-2e66-4dc4-b401-85c4c92ee602': False,
'1fd28d4a-909c-4464-a62c-6b30fd2179aa': False,
'1ffd4d7d-6c77-40aa-8f17-ff2f7c5011ac': False,
'221973b6-f6bb-442d-9164-9c96a825e4fd': False,
'223ef721-0bc2-4c4f-ba4f-ee24b4e4364b': False,
'24710d17-5227-4764-a583-9a2d58e64f76': False,
'27e28e55-ea6c-44eb-98be-e80a93682fc5': False,
'28abe4d6-5f4e-4aac-9f88-febd5ac05d68': False,
'28e4d325-287a-43de-86ee-e60cc60977c2': False,
'29a2c8c7-3706-426a-961e-88444fabdc6e': False,
'2ab31818-3093-4ae3-b48e-e206475fe071': False,
'2c138c72-d1b0-4cd5-917b-7a39062f258e': False,
'2c4f85d0-1b8e-4738-bde8-1f880b57e5e6': False,
'305486cc-5929-457b-821d-f89fb01a51c2': False,
'30dd1aa1-f689-4073-a75c-65dbe99398c7': False,
'31559fd8-4179-4b37-882a-783ea5e5a00c': False,
'3f1145cd-dfe0-4084-aa03-4e0c539438c1': False,
'401f4497-62da-4c95-85a5-f7212091e780': False,
'450a71eb-42b9-4a49-ac45-405c954a9e8d': False,
'4a2ae77d-71e5-45b3-be16-3cfedd75abda': False,
'4b3d9739-2d37-4c9d-ae98-84b3929775ee': False,
'4da55de8-3ac9-43f5-86d3-baee4db4bf0b': False,
'531ce286-4994-43ce-a580-65e5b073bdca': False,
'53604b52-75ac-4bbe-8114-8f29a876ef28': False,
'5627b65c-aead-4b6e-86af-a25540c28b1e': False,
'5c3743fc-2023-4c29-a90c-07de6a56a71a': False,
'5ef10673-4d9b-4f32-8727-ee716d3a4236': False,
'626eefd5-f049-4626-8b8b-aa0c93f58b16': False,
'660db5e9-55c3-49da-b520-d4683976c4dc': False,
'66fc3195-a832-4837-9350-341ea37c6a53': False,
'681c6d37-9f34-4085-9fda-6134a7bc224e': False,
'6b623efa-1f2d-4767-863f-93286950f9e4': False,
'6c7265b8-d053-4b8b-8d75-46787b1c1bfa': False,
'6e6bdbda-12bd-4dee-b95d-abdc3cd770e4': False,
'708ef2ee-e653-44bc-b885-297df0d91d71': False,
'70a72fbe-9804-4be0-9e6f-81e44fcf8cce': False,
'70aa2417-3a72-4375-a1a1-163e1a3c5c3c': False,
'722b31f3-e5c0-47e4-96ed-67216dd625a9': False,
'7633869e-2c46-48de-8640-63c799c7fc9c': False,
'76380e8c-0e6f-4447-ab1a-0cf588f9fb3c': False,
'769b2118-4507-46bd-9355-1549f6972384': False,
'76a31790-1f32-4263-b1e2-eb3a15d02bdb': False,
'7a4afb37-42ab-4fec-85ed-a78fcbe8c5fc': False,
'7c74103d-5625-4e70-bac1-f9aaec68e9c1': False,
'82253015-eaab-46a8-b319-a459891fda73': False,
'84e48ab6-cbbf-46ed-acca-07f1ab9e0f65': False,
'86598728-fee2-4bc8-b543-fc3eb4bc3614': False,
'8c6e4b22-9163-4290-8e6a-702952268532': False,
'8e45deed-7596-4b55-ae8c-e1ad31394b59': False,
'91a486ed-7cfe-486d-b30e-425b6e52b30b': False,
'92f1c22e-350f-46f3-ba19-f0bc64cbf1d7': False,
'9577411f-9c7f-4d1c-8047-60941e7af1d5': False,
'96c10154-1e94-4df6-9a37-2167edd00a04': False,
'978e3375-98d2-4cc5-b014-96a6c395bb1f': False,
'9f447e9b-e70e-4a46-aa22-7d3544d6dd35': False,
'a7afe35d-a4a2-4bfa-bc53-41793139eb09': False,
'a9f50608-77e0-4778-a6ec-132994d5765c': False,
'ad652142-4f71-403c-93d4-efea27ed601e': False,
'afc7b5ff-468a-433d-b800-311ab180eabd': False,
'b45d8be3-5b19-40d1-b7c4-1359862ac30c': False,
'bc91e6c3-44d3-4e57-9cc7-49e3056e38fc': False,
'c0989f31-0767-403d-b24e-199bba8d1ec0': False,
'c31016fc-a2a9-4d49-a8bd-af7a2bb0a72d': False,
'c402357d-2bc6-4191-ae69-3686657e308b': False,
'c4e850a9-4c76-4a87-afd6-02ae086f1448': False,
'c6e350ef-edda-4e63-b340-550a5b096970': False,
'c85bd7b1-4d8e-4760-b832-d420b29c8d1b': False,
'ce8006ec-4dea-44d8-9934-33824910e681': False,
'd0a2c20b-a795-473b-bb29-3d71636b14f8': False,
'd145e943-2e42-451b-ae43-bc4f991f333d': False,
'd5e552c5-8acd-451d-bdc9-6bec8fa227bf': False,
'd772bc3b-4a68-4cc4-b25c-bbae66c26e81': False,
'd7c64592-e040-46fd-a353-1de5984a4777': False,
'd81a6237-270f-4623-8660-32f21ea3776b': False,
'd85e62e2-579e-4d71-9a34-107977f45713': False,
'd93509e3-33ac-4210-be1d-8d1030d2a84d': False,
'dd8a01c1-210e-4002-8d9d-a273cf98f5af': False,
'e07585f8-d9ae-42ff-9c0a-cf697732d359': False,
'e7f533c0-36f3-4a90-a284-de213fbd230c': False,
'e87e9770-2ce8-4e28-8dee-89f42ecaa4c5': False,
'ea6ad5bd-600a-45c4-aa58-1fada234c6ef': False,
'ed20dffa-61bb-4c70-882c-bdc75f029a6d': False,
'f131ba54-ae59-4992-80aa-8def87bb0f0a': False,
'f3c7ca99-0b09-4d94-b950-808fb8474b96': False,
'f41d67e8-06d4-4fb4-b2a7-67752d722594': False,
'f5d8a7f9-5e40-429b-8443-1842bc7d288f': False,
'f5dae2fc-fb1e-4d5b-8c81-1ed8dbb9b027': False,
'f7efc04b-be14-43eb-944e-b5f0b77f52e3': False,
'f8f501fb-3680-4a13-9ae2-ffddc9bba865': False,
'fba76c03-a7c9-4147-9dce-a22c6ecd53bf': False}}
TRIP_SERIES = {'distance_end': 147.404368166875,
'distance_start': 318.361754800303,
'lat_end': 47.0508891,
'lat_start': 47.2013301,
'lon_end': 8.3093703,
'lon_start': 7.4539675,
'mot_segment_id': '715b7d80-4746-486e-8ea0-c79a580b2e59',
'stop_id_end': '8505000',
'stop_id_start': '8500204',
'time_end': pd.Timestamp('2016-06-27 07:11:13'),
'time_start': pd.Timestamp('2016-06-27 05:29:59'),
'timezone_end': 'Europe/Zurich',
'timezone_start': 'Europe/Zurich',
'trip_time_end': pd.Timestamp('2016-06-27 07:43:27'),
'trip_time_start': pd.Timestamp('2016-06-27 04:49:41'),
'vid': 'AVAND631-52E9-4D4D-3AED-C27A2FE7B5D7',
'visit_id_end': 13514,
'visit_id_start': 13500}
|
# -*- coding: utf-8 -*-
# import stdlibs
import os
import re
# import third party libs
import pytest
# import local libs
@pytest.fixture
def organization_context():
return {
"ansible_role_organization_name": "myorg",
}
def test_default_configuration(cookies):
result = cookies.bake()
assert result.exit_code == 0
assert result.exception is None
assert result.project.basename == 'ansible_role'
assert result.project.isdir()
def test_organization_configuration(cookies, organization_context):
result = cookies.bake(extra_context=organization_context)
print result
assert result.exit_code == 0
assert result.exception is None
assert result.project.basename == 'myorg.ansible_role'
assert result.project.isdir()
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import rospy
from math import pow, atan2, sqrt
from tf.transformations import *
import smach
import smach_ros
from smach_ros import SimpleActionState
from smach_ros import ServiceState
import threading
import time
# Navigation
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist,Vector3
# Manipulator
from geometry_msgs.msg import Pose
from open_manipulator_msgs.msg import JointPosition
from open_manipulator_msgs.msg import KinematicsPose
from open_manipulator_msgs.srv import SetJointPosition
from open_manipulator_msgs.srv import SetKinematicsPose
# AR Markers
from ar_track_alvar_msgs.msg import AlvarMarker
from ar_track_alvar_msgs.msg import AlvarMarkers
from getObjectPose import getPoseOfTheObject
from getCloserGoal import getCloserToGoal
# 流程总述:
# 1、准备阶段:(机械臂归零,获取目标位置)
# 1.1、首先 init_pose->open_gripper->get_object_pose->
# 1.2、为了避免重复位置导致机械臂重启,这里设置了另一组初始位置。和1.1的对应 SET_Abort_INIT_POSITION->ABort_OPEN_GRIPPER->ABort_GET_POSE_OF_THE_OBJECT
# 2、伸手去抓阶段:ALIGN_ARM_WITH_OBJECT->CLOSE_TO_OBJECT->GRIP_OBJECT
# 3、抓住收回阶段:drop_UP_OBJECT -> SET_HOLDING_POSITION
def drop(drop_center):
with drop_center:
def joint_position_request_cb(userdata, request):
joint = JointPosition()
joint.position = userdata.input_position
joint.max_velocity_scaling_factor = 1.0
joint.max_accelerations_scaling_factor = 1.0
request.planning_group = userdata.input_planning_group
request.joint_position = joint
return request
def joint_position_response_cb(userdata, response):
if response.is_planned == False:
return 'aborted'
else:
rospy.sleep(3.)
return 'succeeded'
def eef_pose_request_cb(userdata, request):
eef = KinematicsPose()
eef.pose = userdata.input_pose
rospy.loginfo('eef.position.x : %f', eef.pose.position.x)
rospy.loginfo('eef.position.y : %f', eef.pose.position.y)
rospy.loginfo('eef.position.z : %f', eef.pose.position.z)
eef.max_velocity_scaling_factor = 1.0
eef.max_accelerations_scaling_factor = 1.0
eef.tolerance = userdata.input_tolerance
request.planning_group = userdata.input_planning_group
request.kinematics_pose = eef
return request
def align_arm_with_object_response_cb(userdata, response):
if response.is_planned == False:
drop_center.userdata.align_arm_with_object_tolerance += 0.005
rospy.logwarn('Set more tolerance[%f]', drop_center.userdata.align_arm_with_object_tolerance)
return 'aborted'
else:
OFFSET_FOR_STRETCH = 0.030
drop_center.userdata.object_pose.position.x += OFFSET_FOR_STRETCH
rospy.sleep(3.)
return 'succeeded'
def close_to_object_response_cb(userdata, response):
if response.is_planned == False:
drop_center.userdata.close_to_object_tolerance += 0.005
rospy.logwarn('Set more tolerance[%f]', drop_center.userdata.close_to_object_tolerance)
return 'aborted'
else:
OFFSET_FOR_OBJECT_HEIGHT = 0.020
drop_center.userdata.object_pose.position.z += OFFSET_FOR_OBJECT_HEIGHT
rospy.sleep(3.)
return 'succeeded'
def drop_up_object_response_cb(userdata, response):
if response.is_planned == False:
drop_center.userdata.drop_up_object_tolerance += 0.005
rospy.logwarn('Set more tolerance[%f]', drop_center.userdata.drop_up_object_tolerance)
return 'aborted'
else:
rospy.sleep(3.)
return 'succeeded'
def gripper_request_cb(userdata, request):
joint = JointPosition()
joint.position = userdata.input_gripper
joint.max_velocity_scaling_factor = 1.0
joint.max_accelerations_scaling_factor = 1.0
request.planning_group = userdata.input_planning_group
request.joint_position = joint
return request
def gripper_response_cb(userdata, response):
rospy.sleep(1.)
return 'succeeded'
namespace=rospy.get_param("~robot_name")
planning_group=rospy.get_param("~planning_group")
# 0、 这里定义了机械臂的几个关键位置节点
drop_center.userdata.planning_group = planning_group
drop_center.userdata.init_position = [0.0, -0.65, 1.20, -0.54]
drop_center.userdata.abort_position = [0.0, -0.55, 1.10, -0.44]
drop_center.userdata.holding_position = [0.0, 0, -0.8, 0.20]
drop_center.userdata.drop_position = [1.57, 0.0, 0.00, 0.4]
drop_center.userdata.release_position = [1.57, 0.0, -0.80, 0.4]
drop_center.userdata.end_init_position = [0.0, -0.8, 0.5, -0.54]
drop_center.userdata.object_pose = Pose()
drop_center.userdata.close_gripper = [-0.005]
drop_center.userdata.open_gripper = [0.005]
drop_center.userdata.drop_up_object_tolerance = 0.01
drop_center.userdata.close_to_object_tolerance = 0.01
drop_center.userdata.align_arm_with_object_tolerance = 0.01
smach.StateMachine.add('SET_DROP_POSITION',
ServiceState(planning_group + '/moveit/set_joint_position',
SetJointPosition,
request_cb=joint_position_request_cb,
response_cb=joint_position_response_cb,
input_keys=['input_planning_group',
'input_position']),
transitions={'succeeded':'OPEN_GRIPPER_DROP'},
remapping={'input_planning_group':'planning_group',
'input_position':'drop_position'})
smach.StateMachine.add('OPEN_GRIPPER_DROP',
ServiceState(namespace + '/gripper',
SetJointPosition,
request_cb=gripper_request_cb,
response_cb=gripper_response_cb,
input_keys=['input_planning_group',
'input_gripper']),
transitions={'succeeded':'SET_RELEASE_POSITION'},
remapping={'input_planning_group':'planning_group',
'input_gripper':'open_gripper'})
smach.StateMachine.add('SET_RELEASE_POSITION',
ServiceState(planning_group + '/moveit/set_joint_position',
SetJointPosition,
request_cb=joint_position_request_cb,
response_cb=joint_position_response_cb,
input_keys=['input_planning_group',
'input_position']),
transitions={'succeeded':'SET_ENDINIT_POSITION'},
remapping={'input_planning_group':'planning_group',
'input_position':'release_position'})
smach.StateMachine.add('SET_ENDINIT_POSITION',
ServiceState(planning_group + '/moveit/set_joint_position',
SetJointPosition,
request_cb=joint_position_request_cb,
response_cb=joint_position_response_cb,
input_keys=['input_planning_group',
'input_position']),
transitions={'succeeded':'succeeded'},
remapping={'input_planning_group':'planning_group',
'input_position':'end_init_position'})
return drop_center
|
import requests
import os
import json
import encode_multipart
class ActionsManager():
def __init__(self, address):
self.address = address
def new(self, name, description, language,
containerTag, in_out, cloud, timeout, filePath):
fields = {
"type": "action",
"name": name,
"description": description,
"language": language,
"containerTag": containerTag,
"in/out": json.dumps(in_out),
"cloud": cloud,
"timeout": str(timeout)
}
f = open(filePath, "rb")
files = {
"file": {'filename': os.path.basename(filePath), 'content': f.read()}
}
f.close()
data, headers = encode_multipart.encode_multipart(fields, files)
resp = requests.post(self.address, data=data, headers=headers)
return resp.status_code, resp.text
def list(self):
resp = requests.get(self.address)
return resp.status_code, resp.text
def delete(self, actionName, force=False, token=None):
address = self.address + "/" + actionName
if (token):
resp = requests.delete(address, json={"token": token})
else:
resp = requests.delete(address)
if (resp.status_code == 202):
if (force):
token = json.loads(resp.text)["token"]
resp = requests.delete(address, json={"token": token})
return resp.status_code, resp.text
|
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import difflib
import json
import re
import textwrap
from itertools import cycle
from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple, cast
from typing_extensions import Literal
from pants.base.build_environment import pants_version
from pants.help.help_formatter import HelpFormatter
from pants.help.help_info_extracter import AllHelpInfo, HelpJSONEncoder
from pants.help.help_tools import ToolHelpInfo
from pants.help.maybe_color import MaybeColor
from pants.option.arg_splitter import (
AllHelp,
HelpRequest,
NoGoalHelp,
ThingHelp,
UnknownGoalHelp,
VersionHelp,
)
from pants.option.scope import GLOBAL_SCOPE
from pants.util.docutil import bin_name, terminal_width
from pants.util.strutil import first_paragraph, hard_wrap, pluralize, softwrap
class HelpPrinter(MaybeColor):
"""Prints general and goal-related help to the console."""
def __init__(
self,
*,
help_request: HelpRequest,
all_help_info: AllHelpInfo,
color: bool,
) -> None:
super().__init__(color)
self._help_request = help_request
self._all_help_info = all_help_info
self._width = terminal_width()
self._reserved_names = {
"api-types",
"backends",
"global",
"goals",
"subsystems",
"symbols",
"targets",
"tools",
}
def print_help(self) -> Literal[0, 1]:
"""Print help to the console."""
def print_hint() -> None:
print(f"Use `{self.maybe_green(bin_name() + ' help')}` to get help.")
print(f"Use `{self.maybe_green(bin_name() + ' help goals')}` to list goals.")
if isinstance(self._help_request, VersionHelp):
print(pants_version())
return 0
elif isinstance(self._help_request, AllHelp):
self._print_all_help()
return 0
elif isinstance(self._help_request, ThingHelp):
return self._print_thing_help()
elif isinstance(self._help_request, UnknownGoalHelp):
# Only print help and suggestions for the first unknown goal.
# It gets confusing to try and show suggestions for multiple cases.
unknown_goal = self._help_request.unknown_goals[0]
print(f"Unknown goal: {self.maybe_red(unknown_goal)}")
self._print_alternatives(unknown_goal, self._all_help_info.name_to_goal_info.keys())
print_hint()
return 1
elif isinstance(self._help_request, NoGoalHelp):
print("No goals specified.")
print_hint()
return 1
else:
# Unexpected.
return 1
def _print_alternatives(self, match: str, all_things: Iterable[str]) -> None:
did_you_mean = difflib.get_close_matches(match, all_things)
if did_you_mean:
formatted_matches = self._format_did_you_mean_matches(did_you_mean)
print(f"Did you mean {formatted_matches}?")
def _print_title(self, title_text: str) -> None:
title = self.maybe_green(f"{title_text}\n{'-' * len(title_text)}")
print(f"\n{title}\n")
def _print_table(self, table: Dict[str, Optional[str]]) -> None:
longest_key = max(len(key) for key, value in table.items() if value is not None)
for key, value in table.items():
if value is None:
continue
print(
self.maybe_cyan(f"{key:{longest_key}}:"),
self.maybe_magenta(
f"\n{' ':{longest_key+2}}".join(
hard_wrap(value, width=self._width - longest_key - 2)
)
),
)
def _get_thing_help_table(self) -> Dict[str, Callable[[str, bool], None]]:
def _help_table(
things: Iterable[str], help_printer: Callable[[str, bool], None]
) -> Dict[str, Callable[[str, bool], None]]:
return dict(zip(things, cycle((help_printer,))))
top_level_help_items = _help_table(self._reserved_names, self._print_top_level_help)
return {
**top_level_help_items,
**_help_table(self._all_help_info.scope_to_help_info.keys(), self._print_options_help),
**_help_table(
self._all_help_info.name_to_target_type_info.keys(), self._print_target_help
),
**_help_table(self._symbol_names(include_targets=False), self._print_symbol_help),
**_help_table(
self._all_help_info.name_to_api_type_info.keys(), self._print_api_type_help
),
**_help_table(self._all_help_info.name_to_rule_info.keys(), self._print_rule_help),
**_help_table(
self._all_help_info.env_var_to_help_info.keys(), self._print_env_var_help
),
}
@staticmethod
def _disambiguate_things(
things: Iterable[str], all_things: Iterable[str]
) -> Tuple[Set[str], Set[str]]:
"""Returns two sets of strings, one with disambiguated things and the second with
unresolvable things."""
disambiguated: Set[str] = set()
unknown: Set[str] = set()
for thing in things:
# Look for typos and close matches first.
alternatives = tuple(difflib.get_close_matches(thing, all_things))
if len(alternatives) == 1 and thing in alternatives[0]:
disambiguated.add(alternatives[0])
continue
# For api types and rules, see if we get a match, by ignoring the leading module path.
found_things: List[str] = []
suffix = f".{thing}"
for known_thing in all_things:
if known_thing.endswith(suffix):
found_things.append(known_thing)
if len(found_things) == 1:
disambiguated.add(found_things[0])
continue
unknown.add(thing)
return disambiguated, unknown
def _format_summary_description(self, descr: str, chars_before_description: int) -> str:
lines = textwrap.wrap(descr, self._width - chars_before_description)
if len(lines) > 1:
lines = [
lines[0],
*(f"{' ' * chars_before_description}{line}" for line in lines[1:]),
]
return "\n".join(lines)
def _print_all_help(self) -> None:
print(self._get_help_json())
def _print_thing_help(self) -> Literal[0, 1]:
"""Print a help screen.
Assumes that self._help_request is an instance of OptionsHelp.
Note: Ony useful if called after options have been registered.
"""
help_request = cast(ThingHelp, self._help_request)
# API types may end up in `likely_specs`, so include them in things to get help for.
things = set(help_request.things + help_request.likely_specs)
help_table = self._get_thing_help_table()
maybe_unknown_things = {thing for thing in things if thing not in help_table}
disambiguated_things, unknown_things = self._disambiguate_things(
maybe_unknown_things, help_table.keys()
)
things = things - maybe_unknown_things | disambiguated_things
# Filter out likely specs from unknown things, as we don't want them to interfere.
unknown_things -= set(help_request.likely_specs)
if unknown_things:
# Only print help and suggestions for the first unknown thing.
# It gets confusing to try and show suggestions for multiple cases.
thing = unknown_things.pop()
print(self.maybe_red(f"Unknown entity: {thing}"))
self._print_alternatives(
thing,
set(help_table.keys()) - self._reserved_names
| {
canonical_name.rsplit(".", 1)[-1]
for canonical_name in help_table.keys()
if "." in canonical_name
},
)
return 1
if not things:
self._print_global_help()
return 0
for thing in sorted(things):
help_table[thing](thing, help_request.advanced)
return 0
def _print_top_level_help(self, thing: str, show_advanced: bool) -> None:
if thing == "goals":
self._print_all_goals()
elif thing == "subsystems":
self._print_all_subsystems()
elif thing == "targets":
self._print_all_targets()
elif thing == "global":
self._print_options_help(GLOBAL_SCOPE, show_advanced)
elif thing == "tools":
self._print_all_tools()
elif thing == "api-types":
self._print_all_api_types()
elif thing == "backends":
self._print_all_backends(show_advanced)
elif thing == "symbols":
self._print_all_symbols(show_advanced)
def _print_all_goals(self) -> None:
goal_descriptions: Dict[str, str] = {}
for goal_info in self._all_help_info.name_to_goal_info.values():
if goal_info.is_implemented:
goal_descriptions[goal_info.name] = goal_info.description
self._print_title("Goals")
max_width = max((len(name) for name in goal_descriptions.keys()), default=0)
chars_before_description = max_width + 2
def format_goal(name: str, descr: str) -> str:
name = self.maybe_cyan(name.ljust(chars_before_description))
descr = self._format_summary_description(descr, chars_before_description)
return f"{name}{descr}\n"
for name, description in sorted(goal_descriptions.items()):
print(format_goal(name, first_paragraph(description)))
specific_help_cmd = f"{bin_name()} help <goal>"
print(
softwrap(
f"""
Use `{self.maybe_green(specific_help_cmd)}` to get help for a specific goal. If
you expect to see more goals listed, you may need to activate backends; run
`{bin_name()} help backends`.
"""
)
)
def _print_all_subsystems(self) -> None:
self._print_title("Subsystems")
subsystem_description: Dict[str, str] = {}
for help_info in self._all_help_info.non_deprecated_option_scope_help_infos():
if not help_info.is_goal and help_info.scope:
subsystem_description[help_info.scope] = first_paragraph(help_info.description)
longest_subsystem_alias = max(len(alias) for alias in subsystem_description.keys())
chars_before_description = longest_subsystem_alias + 2
for alias, description in sorted(subsystem_description.items()):
alias = self.maybe_cyan(alias.ljust(chars_before_description))
description = self._format_summary_description(description, chars_before_description)
print(f"{alias}{description}\n")
specific_help_cmd = f"{bin_name()} help $subsystem"
print(
f"Use `{self.maybe_green(specific_help_cmd)}` to get help for a "
f"specific subsystem.\n"
)
def _print_all_targets(self) -> None:
self._print_title("Target types")
longest_target_alias = max(
len(alias) for alias in self._all_help_info.name_to_target_type_info.keys()
)
chars_before_description = longest_target_alias + 2
for alias, target_type_info in sorted(
self._all_help_info.name_to_target_type_info.items(), key=lambda x: x[0]
):
if alias.startswith("_"):
continue
alias_str = self.maybe_cyan(f"{alias}".ljust(chars_before_description))
summary = self._format_summary_description(
target_type_info.summary, chars_before_description
)
print(f"{alias_str}{summary}\n")
specific_help_cmd = f"{bin_name()} help $target_type"
print(
f"Use `{self.maybe_green(specific_help_cmd)}` to get help for a specific "
f"target type.\n"
)
def _print_all_tools(self) -> None:
self._print_title("External Tools")
ToolHelpInfo.print_all(ToolHelpInfo.iter(self._all_help_info), self)
tool_help_cmd = f"{bin_name()} help $tool"
print(f"Use `{self.maybe_green(tool_help_cmd)}` to get help for a specific tool.\n")
def _print_all_api_types(self) -> None:
self._print_title("Plugin API Types")
api_type_descriptions: Dict[str, Tuple[str, str]] = {}
indent_api_summary = 0
for api_info in self._all_help_info.name_to_api_type_info.values():
name = api_info.name
if name.startswith("_"):
continue
if api_info.is_union:
name += " <union>"
summary = (api_info.documentation or "").split("\n", 1)[0]
api_type_descriptions[name] = (api_info.module, summary)
indent_api_summary = max(indent_api_summary, len(name) + 2, len(api_info.module) + 2)
for name, (module, summary) in api_type_descriptions.items():
name = self.maybe_cyan(name.ljust(indent_api_summary))
description_lines = hard_wrap(
summary or " ", indent=indent_api_summary, width=self._width
)
# Juggle the description lines, to inject the api type module on the second line flushed
# left just below the type name (potentially sharing the line with the second line of
# the description that will be aligned to the right).
if len(description_lines) > 1:
# Place in front of the description line.
description_lines[
1
] = f"{module:{indent_api_summary}}{description_lines[1][indent_api_summary:]}"
else:
# There is no second description line.
description_lines.append(module)
# All description lines are indented, but the first line should be indented by the api
# type name, so we strip that.
description_lines[0] = description_lines[0][indent_api_summary:]
description = "\n".join(description_lines)
print(f"{name}{description}\n")
api_help_cmd = f"{bin_name()} help [api_type/rule_name]"
print(
f"Use `{self.maybe_green(api_help_cmd)}` to get help for a specific API type or rule.\n"
)
def _print_all_backends(self, include_experimental: bool) -> None:
self._print_title("Backends")
print(
softwrap(
"""
List with all known backends for Pants.
Enabled backends are marked with `*`. To enable a backend add it to
`[GLOBAL].backend_packages`.
"""
),
"\n",
)
backends = self._all_help_info.name_to_backend_help_info
provider_col_width = 3 + max(map(len, (info.provider for info in backends.values())))
enabled_col_width = 4
for info in backends.values():
if not (include_experimental or info.enabled) and ".experimental." in info.name:
continue
enabled = "[*] " if info.enabled else "[ ] "
name_col_width = max(
len(info.name) + 1, self._width - enabled_col_width - provider_col_width
)
name = self.maybe_cyan(f"{info.name:{name_col_width}}")
provider = self.maybe_magenta(info.provider) if info.enabled else info.provider
print(f"{enabled}{name}[{provider}]")
if info.description and self._width > 10:
print(
"\n".join(
hard_wrap(
softwrap(info.description),
indent=enabled_col_width + 1,
width=self._width - enabled_col_width - 1,
)
)
)
def _symbol_names(self, include_targets: bool) -> Iterable[str]:
return sorted(
{
symbol.name
for symbol in self._all_help_info.name_to_build_file_info.values()
if (include_targets or not symbol.is_target) and not re.match("_[^_]", symbol.name)
}
)
def _print_all_symbols(self, include_targets: bool) -> None:
self._print_title("BUILD file symbols")
symbols = self._all_help_info.name_to_build_file_info
names = self._symbol_names(include_targets)
longest_symbol_name = max(len(name) for name in names)
chars_before_description = longest_symbol_name + 2
for name in sorted(names):
name_str = self.maybe_cyan(f"{name}".ljust(chars_before_description))
summary = self._format_summary_description(
first_paragraph(symbols[name].documentation or ""), chars_before_description
)
print(f"{name_str}{summary}\n")
def _print_global_help(self):
def print_cmd(args: str, desc: str):
cmd = self.maybe_green(f"{bin_name()} {args}".ljust(41))
print(f" {cmd} {desc}")
print(f"\nPants {pants_version()}")
print("\nUsage:\n")
print_cmd(
"[options] [goals] [inputs]",
"Attempt the specified goals on the specified inputs.",
)
print_cmd("help", "Display this usage message.")
print_cmd("help goals", "List all installed goals.")
print_cmd("help targets", "List all installed target types.")
print_cmd("help subsystems", "List all configurable subsystems.")
print_cmd("help tools", "List all external tools.")
print_cmd("help backends", "List all available backends.")
print_cmd("help-advanced backends", "List all backends, including experimental/preview.")
print_cmd("help symbols", "List available BUILD file symbols.")
print_cmd(
"help-advanced symbols",
"List all available BUILD file symbols, including target types.",
)
print_cmd("help api-types", "List all plugin API types.")
print_cmd("help global", "Help for global options.")
print_cmd("help-advanced global", "Help for global advanced options.")
print_cmd(
"help [name]",
"Help for a target type, goal, subsystem, plugin API type or rule.",
)
print_cmd(
"help-advanced [goal/subsystem]", "Help for a goal or subsystem's advanced options."
)
print_cmd("help-all", "Print a JSON object containing all help info.")
print("")
print(" [inputs] can be:")
print(f" A file, e.g. {self.maybe_cyan('path/to/file.ext')}")
glob_str = self.maybe_cyan("'**/*.ext'")
print(f" A path glob, e.g. {glob_str} (in quotes to prevent premature shell expansion)")
print(f" A directory, e.g. {self.maybe_cyan('path/to/dir')}")
print(
f" A directory ending in `::` to include all subdirectories, e.g. {self.maybe_cyan('path/to/dir::')}"
)
print(f" A target address, e.g. {self.maybe_cyan('path/to/dir:target_name')}.")
print(
f" Any of the above with a `-` prefix to ignore the value, e.g. {self.maybe_cyan('-path/to/ignore_me::')}"
)
print(f"\nDocumentation at {self.maybe_magenta('https://www.pantsbuild.org')}")
pypi_url = f"https://pypi.org/pypi/pantsbuild.pants/{pants_version()}"
print(f"Download at {self.maybe_magenta(pypi_url)}")
def _print_options_help(self, scope: str, show_advanced_and_deprecated: bool) -> None:
"""Prints a human-readable help message for the options registered on this object.
Assumes that self._help_request is an instance of OptionsHelp.
"""
help_formatter = HelpFormatter(
show_advanced=show_advanced_and_deprecated,
show_deprecated=show_advanced_and_deprecated,
color=self.color,
)
oshi = self._all_help_info.scope_to_help_info.get(scope)
if not oshi:
return
formatted_lines = help_formatter.format_options(oshi)
goal_info = self._all_help_info.name_to_goal_info.get(scope)
if goal_info:
related_scopes = sorted(set(goal_info.consumed_scopes) - {GLOBAL_SCOPE, goal_info.name})
if related_scopes:
related_subsystems_label = self.maybe_green("Related subsystems:")
formatted_lines.append(f"{related_subsystems_label} {', '.join(related_scopes)}")
formatted_lines.append("")
for line in formatted_lines:
print(line)
def _print_target_help(self, target_alias: str, _: bool) -> None:
self._print_title(f"`{target_alias}` target")
tinfo = self._all_help_info.name_to_target_type_info[target_alias]
if tinfo.description:
formatted_desc = "\n".join(hard_wrap(tinfo.description, width=self._width))
print(formatted_desc)
print(f"\n\nActivated by {self.maybe_magenta(tinfo.provider)}")
print("Valid fields:")
for field in sorted(tinfo.fields, key=lambda x: (-x.required, x.alias)):
print()
print(self.maybe_magenta(field.alias))
indent = " "
required_or_default = "required" if field.required else f"default: {field.default}"
if field.provider not in ["", tinfo.provider]:
print(self.maybe_cyan(f"{indent}from: {field.provider}"))
print(self.maybe_cyan(f"{indent}type: {field.type_hint}"))
print(self.maybe_cyan(f"{indent}{required_or_default}"))
if field.description:
formatted_desc = "\n".join(
hard_wrap(field.description, indent=len(indent), width=self._width)
)
print("\n" + formatted_desc)
print()
def _print_symbol_help(self, name: str, _: bool) -> None:
self._print_title(f"`{name}` BUILD file symbol")
symbol = self._all_help_info.name_to_build_file_info[name]
if symbol.signature:
print(self.maybe_magenta(f"Signature: {symbol.name}{symbol.signature}\n"))
print("\n".join(hard_wrap(symbol.documentation or "Undocumented.", width=self._width)))
def _print_api_type_help(self, name: str, show_advanced: bool) -> None:
self._print_title(f"`{name}` api type")
type_info = self._all_help_info.name_to_api_type_info[name]
print("\n".join(hard_wrap(type_info.documentation or "Undocumented.", width=self._width)))
print()
self._print_table(
{
"activated by": type_info.provider,
"union type": type_info.union_type,
"union members": "\n".join(type_info.union_members) if type_info.is_union else None,
"dependencies": "\n".join(type_info.dependencies) if show_advanced else None,
"dependents": "\n".join(type_info.dependents) if show_advanced else None,
f"returned by {pluralize(len(type_info.returned_by_rules), 'rule')}": "\n".join(
type_info.returned_by_rules
)
if show_advanced
else None,
f"consumed by {pluralize(len(type_info.consumed_by_rules), 'rule')}": "\n".join(
type_info.consumed_by_rules
)
if show_advanced
else None,
f"used in {pluralize(len(type_info.used_in_rules), 'rule')}": "\n".join(
type_info.used_in_rules
)
if show_advanced
else None,
}
)
print()
if not show_advanced:
print(
self.maybe_green(
f"Include API types and rules dependency information by running "
f"`{bin_name()} help-advanced {name}`.\n"
)
)
def _print_rule_help(self, rule_name: str, show_advanced: bool) -> None:
rule = self._all_help_info.name_to_rule_info[rule_name]
title = f"`{rule_name}` rule"
self._print_title(title)
if rule.description:
print(rule.description + "\n")
print("\n".join(hard_wrap(rule.documentation or "Undocumented.", width=self._width)))
print()
self._print_table(
{
"activated by": rule.provider,
"returns": rule.output_type,
f"takes {pluralize(len(rule.input_types), 'input')}": ", ".join(rule.input_types),
f"awaits {pluralize(len(rule.input_gets), 'get')}": "\n".join(rule.input_gets)
if show_advanced
else None,
}
)
print()
def _print_env_var_help(self, env_var: str, show_advanced_and_deprecated: bool) -> None:
ohi = self._all_help_info.env_var_to_help_info[env_var]
help_formatter = HelpFormatter(
show_advanced=show_advanced_and_deprecated,
show_deprecated=show_advanced_and_deprecated,
color=self.color,
)
for line in help_formatter.format_option(ohi):
print(line)
print()
def _get_help_json(self) -> str:
"""Return a JSON object containing all the help info we have."""
return json.dumps(
self._all_help_info.asdict(), sort_keys=True, indent=2, cls=HelpJSONEncoder
)
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
class LoginForm (FlaskForm):
pass
|
#This is Tic Tac Toe by Vanessa Tostado
from graphics import *
from random import *
def grid(win):
rect1 = Rectangle(Point(0,700),Point(200, 500))# Rectangle 1
rect1.draw(win)
label=Text(Point(100,600), "1")
label.draw(win)
rect2 = Rectangle(Point(0,500),Point(200, 300))# Rectangle 2
rect2.draw(win)
labe2=Text(Point(100,400), "2")
labe2.draw(win)
rect3 = Rectangle(Point(0,300),Point(200, 100))# Rectangle 3
rect3.draw(win)
label3=Text(Point(100,200), "3")
label3.draw(win)
rect4 = Rectangle(Point(200,700),Point(400, 500))# Rectangle 4
rect4.draw(win)
label4=Text(Point(300,600), "4")
label4.draw(win)
rect5 = Rectangle(Point(200,500),Point(400, 300))# Rectangle 5
rect5.draw(win)
label5=Text(Point(300,400), "5")
label5.draw(win)
rect6 = Rectangle(Point(200,300),Point(400, 100))# Rectangle 6
rect6.draw(win)
label6=Text(Point(300,200), "6")
label6.draw(win)
rect7 = Rectangle(Point(400,700),Point(600, 500))# Rectangle 7
rect7.draw(win)
label7=Text(Point(500,600), "7")
label7.draw(win)
rect8 = Rectangle(Point(400,500),Point(600, 300))# Rectangle 8
rect8.draw(win)
label8=Text(Point(500,400), "8")
label8.draw(win)
rect9 = Rectangle(Point(400,300),Point(600, 100))# Rectangle 9
rect9.draw(win)
label9=Text(Point(500,200), "9")
label9.draw(win)
def game(win):
Player1="X"
Player2="Y"
point = win.getMouse()
PointX= point.getX()
PointY=point.getY()
print PointX
print PointY
available=[1,2,3,4,5,6,7,8,9]
winning=[]
lose=[]
possibilities=[[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]]
User = True
while User == True:
point = win.getMouse()
PointX= point.getX()
PointY=point.getY()
print PointX
print PointY
if 0<PointX<200 and 500<PointY<700:#Square 1- set parameters for square that has the #1
X= Text(Point(100,600), "X")#Places a red X on where the user clicked
X.setTextColor("red")
X.setSize(36)
X.draw(win)
available.remove(1)# appends the number 1 from list of available places computer can choose from
winning.append(1)
if 0<PointX<200 and 300<PointY<500:#2
X= Text(Point(100,400), "X")
X.setTextColor("red")
X.setSize(36)
X.draw(win)
available.remove(2)
winning.append(2)
if 0<PointX<200 and 100<PointY<300:#3
X= Text(Point(100,200), "X")
X.setTextColor("red")
X.setSize(36)
X.draw(win)
available.remove(3)
winning.append(3)
if 200<PointX<400 and 500<PointY<700:#4
X= Text(Point(300,600), "X")
X.setTextColor("red")
X.setSize(36)
X.draw(win)
available.remove(4)
winning.append(4)
if 200<PointX<400 and 300<PointY<500:#5
X= Text(Point(300,400), "X")
X.setTextColor("red")
X.setSize(36)
X.draw(win)
available.remove(5)
winning.append(5)
if 200<PointX<400 and 100<PointY<300:#6
X= Text(Point(300,200), "X")
X.setTextColor("red")
X.setSize(36)
X.draw(win)
available.remove(6)
winning.append(6)
if 400<PointX<600 and 500<PointY<700:#7
X= Text(Point(500,600), "X")
X.setTextColor("red")
X.setSize(36)
X.draw(win)
available.remove(7)
winning.append(7)
if 400<PointX<600 and 300<PointY<500:#8
X= Text(Point(500,400), "X")
X.setTextColor("red")
X.setSize(36)
X.draw(win)
available.remove(8)
winning.append(8)
if 400<PointX<600 and 100<PointY<300:#9
X= Text(Point(500,200), "X")
X.setTextColor("red")
X.setSize(36)
X.draw(win)
available.remove(9)
winning.append(9)
print "winning" + str(winning)
randNum = choice(available)
print "Random number " + str( randNum)
time.sleep(1)
if randNum== 1:
O=Text(Point(100,600), "O")
O.setTextColor("blue")
O.setSize(36)
O.draw(win)
available.remove(1)
lose.append(1)
if randNum==2:
O= Text(Point(100,400), "O")
O.setTextColor("blue")
O.setSize(36)
O.draw(win)
available.remove(2)
lose.append(2)
if randNum==3:
O= Text(Point(100,200), "O")
O.setTextColor("blue")
O.setSize(36)
O.draw(win)
available.remove(3)
lose.append(3)
if randNum==4:
O= Text(Point(300,600), "O")
O.setTextColor("blue")
O.setSize(36)
O.draw(win)
available.remove(4)
lose.append(4)
if randNum==5:
O= Text(Point(300,400), "O")
O.setTextColor("blue")
O.setSize(36)
O.draw(win)
available.remove(5)
lose.append(5)
if randNum==6:
O=Text(Point(300,200), "O")
O.setTextColor("blue")
O.setSize(36)
O.draw(win)
available.remove(6)
lose.append(6)
if randNum==7:
O= Text(Point(500,600), "O")
O.setTextColor("blue")
O.setSize(36)
O.draw(win)
available.remove(7)
lose.append(7)
if randNum==8:
O= Text(Point(500,400), "O")
O.setTextColor("blue")
O.setSize(36)
O.draw(win)
available.remove(8)
lose.append(8)
if randNum ==9:
O= Text(Point(500,200), "O")
O.setTextColor("blue")
O.setSize(36)
O.draw(win)
available.remove(9)
lose.append(9)
print "Lose" + str(lose)
if winning in possibilities:
print "You Win"
User== False
elif lose in possibilities:
print "You Lose"
User == False
def main():
win = GraphWin('Tic Tac Toe', 700,700) # give title and dimensions
win.yUp()
grid(win)
game(win)
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.