hexsha
stringlengths
40
40
size
int64
5
2.06M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
248
max_stars_repo_name
stringlengths
5
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
248
max_issues_repo_name
stringlengths
5
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
248
max_forks_repo_name
stringlengths
5
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
2.06M
avg_line_length
float64
1
1.02M
max_line_length
int64
3
1.03M
alphanum_fraction
float64
0
1
count_classes
int64
0
1.6M
score_classes
float64
0
1
count_generators
int64
0
651k
score_generators
float64
0
1
count_decorators
int64
0
990k
score_decorators
float64
0
1
count_async_functions
int64
0
235k
score_async_functions
float64
0
1
count_documentation
int64
0
1.04M
score_documentation
float64
0
1
9a2921aafee477055d03e47abb30d023e2f9b7df
2,645
py
Python
2017/day06/redistribution.py
kmcginn/advent-of-code
96a8d7d723f6f222d431fd9ede88d0a303d86761
[ "MIT" ]
null
null
null
2017/day06/redistribution.py
kmcginn/advent-of-code
96a8d7d723f6f222d431fd9ede88d0a303d86761
[ "MIT" ]
null
null
null
2017/day06/redistribution.py
kmcginn/advent-of-code
96a8d7d723f6f222d431fd9ede88d0a303d86761
[ "MIT" ]
null
null
null
""" from: http://adventofcode.com/2017/day/6 --- Day 6: Memory Reallocation --- A debugger program here is having an issue: it is trying to repair a memory reallocation routine, but it keeps getting stuck in an infinite loop. In this area, there are sixteen memory banks; each memory bank can hold any number of blocks. The goal of the reallocation routine is to balance the blocks between the memory banks. The reallocation routine operates in cycles. In each cycle, it finds the memory bank with the most blocks (ties won by the lowest-numbered memory bank) and redistributes those blocks among the banks. To do this, it removes all of the blocks from the selected bank, then moves to the next (by index) memory bank and inserts one of the blocks. It continues doing this until it runs out of blocks; if it reaches the last memory bank, it wraps around to the first one. The debugger would like to know how many redistributions can be done before a blocks-in-banks configuration is produced that has been seen before. For example, imagine a scenario with only four memory banks: The banks start with 0, 2, 7, and 0 blocks. The third bank has the most blocks, so it is chosen for redistribution. Starting with the next bank (the fourth bank) and then continuing to the first bank, the second bank, and so on, the 7 blocks are spread out over the memory banks. The fourth, first, and second banks get two blocks each, and the third bank gets one back. The final result looks like this: 2 4 1 2. Next, the second bank is chosen because it contains the most blocks (four). Because there are four memory banks, each gets one block. The result is: 3 1 2 3. Now, there is a tie between the first and fourth memory banks, both of which have three blocks. The first bank wins the tie, and its three blocks are distributed evenly over the other three banks, leaving it with none: 0 2 3 4. The fourth bank is chosen, and its four blocks are distributed such that each of the four banks receives one: 1 3 4 1. The third bank is chosen, and the same thing happens: 2 4 1 2. At this point, we've reached a state we've seen before: 2 4 1 2 was already seen. The infinite loop is detected after the fifth block redistribution cycle, and so the answer in this example is 5. Given the initial block counts in your puzzle input, how many redistribution cycles must be completed before a configuration is produced that has been seen before? """ def main(): """Solve the problem!""" with open('input.txt') as input_file: data = input_file.read() banks = [int(x) for x in data.split()] print(banks) if __name__ == "__main__": main()
56.276596
100
0.761815
0
0
0
0
0
0
0
0
2,473
0.934972
9a29485e3ae58c67b4c0c486240c276c76016ab2
3,328
py
Python
redress/tests/test_geometries.py
maximlamare/REDRESS
a6caa9924d0f6df7ed49f188b35a7743fde1486e
[ "MIT" ]
1
2021-09-16T08:03:31.000Z
2021-09-16T08:03:31.000Z
redress/tests/test_geometries.py
maximlamare/REDRESS
a6caa9924d0f6df7ed49f188b35a7743fde1486e
[ "MIT" ]
null
null
null
redress/tests/test_geometries.py
maximlamare/REDRESS
a6caa9924d0f6df7ed49f188b35a7743fde1486e
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Unittests for the GDAl tools. This file is part of the REDRESS algorithm M. Lamare, M. Dumont, G. Picard (IGE, CEN). """ import pytest from geojson import Polygon, Feature, FeatureCollection, dump from redress.geospatial.gdal_ops import (build_poly_from_coords, build_poly_from_geojson, geom_contains) @pytest.fixture(scope="session") def write_geojson(tmpdir_factory): """ Write a geojson file with predetermined coordinates.""" # Create a polygon poly = Polygon([[(5.51, 44.71), (6.91, 44.71), (6.91, 45.46), (5.51, 45.46)]]) # Create a feature features = [] features.append(Feature(geometry=poly)) # Add to collection feature_collection = FeatureCollection(features) # Write to file fn = tmpdir_factory.mktemp("data").join("poly.geojson") with open(fn, 'w') as f: dump(feature_collection, f) return fn class Test_polygons(object): """Test the extent of built polygons and if they overlap.""" def test_built_poly(self): """Test that a polygon is correctly built from coordinates.""" # Create 4 coordinates that form a rectangle coord_box = [(5.51, 44.71), (6.91, 44.71), (6.91, 45.46), (5.51, 45.46)] # Build a polygon poly = build_poly_from_coords(coord_box) # Test if the coords are correctly built assert min(poly.GetEnvelope()) == coord_box[0][0] assert max(poly.GetEnvelope()) == coord_box[-1][1] def test_geojson_poly(self, write_geojson): """Test that a polygon is correctly built from a geojson file.""" # Get polygon from file poly = build_poly_from_geojson(str(write_geojson)) # Create base coordinates coord_box = [(5.51, 44.71), (6.91, 44.71), (6.91, 45.46), (5.51, 45.46)] # Test if the coords are correctly built assert min(poly.GetEnvelope()) == coord_box[0][0] assert max(poly.GetEnvelope()) == coord_box[-1][1] def test_poly_contains(self): """Test if a created polygon is contained with an other""" # Creat a first polygon (not a rectangle) main_coord_box = [(6.2869, 45.2729), (6.6165, 45.0735), (6.0919, 45.0191)] main_poly = build_poly_from_coords(main_coord_box) # Create a polygon inside of the main one inside_coords = [(6.2855, 45.1316), (6.3871, 45.1316), (6.3871, 45.1810), (6.2855, 45.1810)] inside_poly = build_poly_from_coords(inside_coords) # Create a polygon that overlaps the main one overlap_coords = [(5.9559, 45.0977), (6.0026, 44.9259), (6.6384, 45.0356)] overlap_poly = build_poly_from_coords(overlap_coords) # Create a polygon outside the main one outside_coords = [(6.6439, 45.7119), (6.8829, 45.7119), (6.8829, 45.8708), (6.6439, 45.8708)] outside_poly = build_poly_from_coords(outside_coords) assert geom_contains(main_poly, inside_poly) assert not geom_contains(main_poly, overlap_poly) assert not geom_contains(main_poly, outside_poly)
36.571429
73
0.60607
2,305
0.692608
0
0
582
0.17488
0
0
930
0.279447
9a2995b77fe8a7759abd5fe12be41e28897fa1b0
112
py
Python
output/models/ms_data/regex/letterlike_symbols_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/ms_data/regex/letterlike_symbols_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/ms_data/regex/letterlike_symbols_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from output.models.ms_data.regex.letterlike_symbols_xsd.letterlike_symbols import Doc __all__ = [ "Doc", ]
18.666667
85
0.776786
0
0
0
0
0
0
0
0
5
0.044643
9a2ad5d8f34b4182942a86d8ef3f197c1b06c12e
1,296
py
Python
test.py
MarkMurillo/python_ctype_structure_example
9e889cc4cbdeab8433c396262f086071bb961e13
[ "MIT" ]
null
null
null
test.py
MarkMurillo/python_ctype_structure_example
9e889cc4cbdeab8433c396262f086071bb961e13
[ "MIT" ]
null
null
null
test.py
MarkMurillo/python_ctype_structure_example
9e889cc4cbdeab8433c396262f086071bb961e13
[ "MIT" ]
null
null
null
"""test.py Python3 Test script that demonstrates the passing of an initialized python structure to C and retrieving the structure back. """ import testMod from ctypes import * class TESTSTRUCT(Structure): pass TESTSTRUCT._fields_ = [ ("name", c_char_p), ("next", POINTER(TESTSTRUCT), #We can use a structure pointer for a linked list. ("next2", c_void_p) #We can use void pointers for structures as well! ] struct1 = TESTSTRUCT(c_char_p("Hello!".encode()), None, None) struct2 = TESTSTRUCT(c_char_p("Goodbye!".encode()), None, None) struct22 = TESTSTRUCT(c_char_p("My Love!".encode()), None, None) struct1.next = pointer(struct2) #Must cast lp to void p before assigning it or it will complain... struct1.next2 = cast(pointer(struct22), c_void_p) outbytes = testMod.py_returnMe(struct1) #Must cast outbytes back into pointer for a struct and retrieve contents. struct3 = cast(outbytes, POINTER(TESTSTRUCT)).contents #Next is already a pointer so all we need are just the contents. nextStruct = struct3.next.contents #Next2 is a void p so we need to cast it back to TESTSTRUCT pointer and get #the contents. next2Struct = cast(struct3.next2, POINTER(TESTSTRUCT)).contents print ("Result: {}, {}, {}".format(struct3.name, nextStrut.name, next2Struct.name)
31.609756
88
0.73534
37
0.028549
0
0
0
0
0
0
597
0.460648
9a2bcb820df0cd2448d9d527aa5328ae749fbcf6
246
py
Python
calculations.py
DikshaAGowda/Project3
675d4d80ad4b44b3a49e8962c9f85709898d0a94
[ "MIT" ]
null
null
null
calculations.py
DikshaAGowda/Project3
675d4d80ad4b44b3a49e8962c9f85709898d0a94
[ "MIT" ]
null
null
null
calculations.py
DikshaAGowda/Project3
675d4d80ad4b44b3a49e8962c9f85709898d0a94
[ "MIT" ]
null
null
null
def addition(num1, num2): return num1 + num2 def subtraction(num1, num2): return num1 - num2 def multiplication(num1, num2): return num1 * num2 def division(num1, num2): if num2 == 0: return None return num1 / num2
17.571429
31
0.642276
0
0
0
0
0
0
0
0
0
0
9a2cec396ceac73b9f9e17a3fefcecf0959ae15d
33,258
py
Python
utility/visualize.py
richban/behavioral.neuroevolution
bb850bda919a772538dc86a9624a6e86623f9b80
[ "Apache-2.0" ]
null
null
null
utility/visualize.py
richban/behavioral.neuroevolution
bb850bda919a772538dc86a9624a6e86623f9b80
[ "Apache-2.0" ]
2
2020-03-31T01:45:13.000Z
2020-09-25T23:39:43.000Z
utility/visualize.py
richban/behavioral.neuroevolution
bb850bda919a772538dc86a9624a6e86623f9b80
[ "Apache-2.0" ]
null
null
null
from __future__ import print_function import os import csv import graphviz import numpy as np import plotly.graph_objs as go import plotly import plotly.plotly as py import matplotlib.pyplot as plt import matplotlib.pylab as pylab import copy import warnings import matplotlib as mpl from plotly.offline import download_plotlyjs, plot, iplot mpl.use('TkAgg') plotly.tools.set_credentials_file(username=os.environ['PLOTLY_USERNAME'], api_key=os.environ['PLOTLY_API_KEY']) def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'): """ Plots the population's average and best fitness. """ if plt is None: warnings.warn( "This display is not available due to a missing optional dependency (matplotlib)") return generation = range(len(statistics.most_fit_genomes)) best_fitness = [c.fitness for c in statistics.most_fit_genomes] avg_fitness = np.array(statistics.get_fitness_mean()) stdev_fitness = np.array(statistics.get_fitness_stdev()) median_fitness = np.array(statistics.get_fitness_median()) plt.figure(figsize=(12, 9)) ax = plt.subplot(111) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.plot(generation, avg_fitness, 'b-', label="average") plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd") plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd") plt.plot(generation, best_fitness, 'r-', label="best") plt.plot(generation, median_fitness, 'y-', label="median") plt.title("Population's average and best fitness") plt.xlabel("Generations") plt.ylabel("Fitness") plt.grid() plt.legend(loc="best") if ylog: plt.gca().set_yscale('symlog') plt.savefig(filename) if view: plt.show() plt.close() def plot_spikes(spikes, view=False, filename=None, title=None): """ Plots the trains for a single spiking neuron. """ t_values = [t for t, I, v, u, f in spikes] v_values = [v for t, I, v, u, f in spikes] u_values = [u for t, I, v, u, f in spikes] I_values = [I for t, I, v, u, f in spikes] f_values = [f for t, I, v, u, f in spikes] fig = plt.figure() plt.subplot(4, 1, 1) plt.ylabel("Potential (mv)") plt.xlabel("Time (in ms)") plt.grid() plt.plot(t_values, v_values, "g-") if title is None: plt.title("Izhikevich's spiking neuron model") else: plt.title("Izhikevich's spiking neuron model ({0!s})".format(title)) plt.subplot(4, 1, 2) plt.ylabel("Fired") plt.xlabel("Time (in ms)") plt.grid() plt.plot(t_values, f_values, "r-") plt.subplot(4, 1, 3) plt.ylabel("Recovery (u)") plt.xlabel("Time (in ms)") plt.grid() plt.plot(t_values, u_values, "r-") plt.subplot(4, 1, 4) plt.ylabel("Current (I)") plt.xlabel("Time (in ms)") plt.grid() plt.plot(t_values, I_values, "r-o") if filename is not None: plt.savefig(filename) if view: plt.show() plt.close() fig = None plt.close() return fig def plot_species(statistics, view=False, filename='speciation.svg'): """ Visualizes speciation throughout evolution. """ if plt is None: warnings.warn( "This display is not available due to a missing optional dependency (matplotlib)") return species_sizes = statistics.get_species_sizes() num_generations = len(species_sizes) curves = np.array(species_sizes).T plt.figure(figsize=(12, 9)) _, ax = plt.subplots() ax.stackplot(range(num_generations), *curves) plt.title("Speciation") plt.ylabel("Size per Species") plt.xlabel("Generations") plt.savefig(filename) if view: plt.show() plt.close() def draw_net(config, genome, view=False, filename=None, node_names=None, show_disabled=True, prune_unused=False, node_colors=None, fmt='svg'): """ Receives a genome and draws a neural network with arbitrary topology. """ # Attributes for network nodes. if graphviz is None: warnings.warn( "This display is not available due to a missing optional dependency (graphviz)") return if node_names is None: node_names = {} assert type(node_names) is dict if node_colors is None: node_colors = {} assert type(node_colors) is dict node_attrs = { 'shape': 'circle', 'fontsize': '9', 'height': '0.2', 'width': '0.2'} dot = graphviz.Digraph(format=fmt, node_attr=node_attrs) inputs = set() for k in config.genome_config.input_keys: inputs.add(k) name = node_names.get(k, str(k)) input_attrs = {'style': 'filled', 'shape': 'box'} input_attrs['fillcolor'] = node_colors.get(k, 'lightgray') dot.node(name, _attributes=input_attrs) outputs = set() for k in config.genome_config.output_keys: outputs.add(k) name = node_names.get(k, str(k)) node_attrs = {'style': 'filled'} node_attrs['fillcolor'] = node_colors.get(k, 'lightblue') dot.node(name, _attributes=node_attrs) if prune_unused: connections = set() for cg in genome.connections.values(): if cg.enabled or show_disabled: connections.add((cg.in_node_id, cg.out_node_id)) used_nodes = copy.copy(outputs) pending = copy.copy(outputs) while pending: new_pending = set() for a, b in connections: if b in pending and a not in used_nodes: new_pending.add(a) used_nodes.add(a) pending = new_pending else: used_nodes = set(genome.nodes.keys()) for n in used_nodes: if n in inputs or n in outputs: continue attrs = {'style': 'filled', 'fillcolor': node_colors.get(n, 'white')} dot.node(str(n), _attributes=attrs) for cg in genome.connections.values(): if cg.enabled or show_disabled: # if cg.input not in used_nodes or cg.output not in used_nodes: # continue input, output = cg.key a = node_names.get(input, str(input)) b = node_names.get(output, str(output)) style = 'solid' if cg.enabled else 'dotted' color = 'green' if cg.weight > 0 else 'red' width = str(0.1 + abs(cg.weight / 5.0)) dot.edge(a, b, _attributes={ 'style': style, 'color': color, 'penwidth': width}) dot.render(filename, view=view) return dot def plot_species_stagnation(body, imgfilename): body = body[3:-2] stagnation = [] id = [] fitness = [] size = [] adj_fit = [] age = [] for line in body: line = line.split(' ') line = [x for x in line if x] line[-1] = line[-1].strip() id.append(line[0]) age.append(line[1]) size.append(line[2]) fitness.append(line[3]) adj_fit.append(line[4]) stagnation.append(line[5]) if len(id) < 2: return None plt.figure(figsize=(12, 9)) stagnation = np.array(stagnation).astype(np.float) id = np.array(id) points = plt.bar(id, stagnation, width=0.7) for ind, bar in enumerate(points): height = bar.get_height() plt.text(bar.get_x() + bar.get_width() / 2, height + 1, 'fit {} / size {}'.format(fitness[ind], size[ind]), ha='center', va='bottom', rotation=90, fontsize=7) plt.ylabel('stagnation') plt.xlabel('Species ID') plt.axis([0, plt.axis()[1], 0, plt.axis()[3] + 20]) plt.xticks(rotation='vertical') plt.tight_layout() plt.subplots_adjust(top=0.85) plt.savefig(imgfilename) plt.clf() plt.close('all') return imgfilename def plot_fitness_over_gen(file, imgfilename): with open(file, 'r') as csvfile: data = csv.reader(csvfile) gen = [] avg_fit = [] stdv = [] max_fit = [] median = [] for row in data: gen.append(int(row[0])) avg_fit.append(float(row[1])) stdv.append(float(row[2])) max_fit.append(float(row[3])) median.append(float(row[4])) if len(gen) < 2: return None plt.figure(figsize=(12, 9)) ax = plt.subplot(111) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.grid() plt.plot(gen, avg_fit, 'b', linewidth=0.5,) plt.plot(gen, stdv, 'g', linewidth=0.5,) plt.plot(gen, max_fit, 'r', linewidth=0.5,) plt.plot(gen, median, 'y', linewidth=0.5,) plt.plot(gen, max_fit, 'r', markersize=5, label='Max fitness') plt.plot(gen, avg_fit, 'b', markersize=5, label='Average fitness') plt.plot(gen, stdv, 'g', markersize=5, label='Standard deviation') plt.plot(gen, median, 'y', markersize=5, label='Median') plt.ylabel('Fitness') plt.xlabel('Generation') # xmin, xmax, ymin, ymax = plt.axis() # plt.axis([xmin, xmax, ymin, ymax]) plt.legend(bbox_to_anchor=(1, 1), loc='best') plt.tight_layout() plt.savefig(imgfilename) plt.clf() plt.close('all') return imgfilename def plot_single_run_scatter(scatter, dt, title): """Plots a single run with MAX, AVG, MEDIAN, All individuals""" l = [] y = [] N = len(scatter.gen.unique()) c = ['hsl('+str(h)+',50%'+',50%)' for h in np.linspace(0, 360, N)] for i in range(int(N)): subset = scatter.loc[scatter['gen'] == i] trace0 = go.Scatter( x=subset.loc[:, 'gen'], y=subset.loc[:, 'fitness'], mode='markers', marker=dict(size=7, line=dict(width=1), color=c[i], opacity=0.5 ), name='gen {}'.format(i), text=subset.loc[:, 'genome'] ) l.append(trace0) trace0 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'max'], mode='lines', name='Max', line=dict( color="rgb(204, 51, 51)", dash="solid", shape="spline", smoothing=1.0, width=2 ), ) trace1 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'median'], mode='lines', name='Median', line=dict( color="rgb(173, 181, 97)", shape="spline", dash="solid", smoothing=1.0, width=2 ) ) trace2 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'avg'], mode='lines', name='Average', line=dict( color="rgb(62, 173, 212)", shape="spline", dash="solid", smoothing=1.0, width=2 ) ) data = [trace0, trace1, trace2] layout = go.Layout( title='Fitness of Population Individuals - {}'.format(title), hovermode='closest', xaxis=dict( title='Generations', ticklen=5, zeroline=False, gridwidth=2, ), yaxis=dict( title='Fitness', ticklen=5, gridwidth=1, ), showlegend=False ) fig = go.Figure(data=data+l, layout=layout) return py.iplot(fig, filename='single-run-scater-line-plot', layout=layout) def _set_plot_params(title, ratio): # Optionally fix the aspect ratio if ratio: plt.figure(figsize=plt.figaspect(ratio)) mpl.style.use('seaborn-dark-palette') if title: plt.title(title) def _save_or_show(save): if save: plt.savefig(save) else: plt.show() # exit() def plot_single_run(gen, fit_mins, fit_avgs, fit_maxs, title=None, ratio=None, save=None): _set_plot_params(title, ratio) line1 = plt.plot(gen, fit_mins, 'C1:', label="Minimum Fitness") line2 = plt.plot(gen, fit_avgs, "C2-", label="Average Fitness") line3 = plt.plot(gen, fit_maxs, "C3:", label="Max Fitness") lns = line1 + line2 + line3 labs = [l.get_label() for l in lns] plt.legend(lns, labs, loc="lower right") _save_or_show(save) def plot_runs(dt, title, offline=True): """Plots the Max/Average/Median""" trace0 = go.Scatter( x=dt.index, y=dt.loc[:, 'max'], mode='lines', name='Max', line=dict( color="rgb(204, 51, 51)", dash="solid", shape="spline", smoothing=0.0, width=2 ), ) trace1 = go.Scatter( x=dt.index, y=dt.loc[:, 'median'], mode='lines', name='Median', line=dict( color="rgb(173, 181, 97)", shape="spline", dash="solid", smoothing=0.0, width=2 ) ) trace2 = go.Scatter( x=dt.index, y=dt.loc[:, 'avg'], mode='lines', name='Average', line=dict( color="rgb(62, 173, 212)", shape="spline", dash="solid", smoothing=0.0, width=2 ) ) layout = go.Layout( showlegend=True, hovermode='closest', title=title, xaxis=dict( autorange=False, range=[0, 20], showspikes=False, title="Generations", ticklen=5, gridwidth=1, ), yaxis=dict( autorange=True, title="Fitness", ticklen=5, gridwidth=1, ), ) data = [trace0, trace1, trace2] fig = go.Figure(data, layout=layout) return py.iplot(fig, filename=title) l = [] y = [] N = len(scatter.gen.unique()) c = ['hsl('+str(h)+',50%'+',50%)' for h in np.linspace(0, 360, N)] for i in range(int(N)): subset = scatter.loc[scatter['gen'] == i] trace0 = go.Scatter( x=subset.loc[:, 'gen'], y=subset.loc[:, 'fitness'], mode='markers', marker=dict(size=7, line=dict(width=1), color=c[i], opacity=0.5 ), name='gen {}'.format(i), text=subset.loc[:, 'genome'] ) l.append(trace0) trace0 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'max'], mode='lines', name='Max', line=dict( color="rgb(204, 51, 51)", dash="solid", shape="spline", smoothing=0.0, width=2 ), ) trace1 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'median'], mode='lines', name='Median', line=dict( color="rgb(173, 181, 97)", shape="spline", dash="solid", smoothing=0.0, width=2 ) ) trace2 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'avg'], mode='lines', name='Average', line=dict( color="rgb(62, 173, 212)", shape="spline", dash="solid", smoothing=0.0, width=2 ) ) data = [trace0, trace1, trace2] layout = go.Layout( title='Fitness of Population Individuals - {}'.format(title), hovermode='closest', xaxis=dict( title='Generations', ticklen=5, zeroline=False, gridwidth=2, ), yaxis=dict( title='Fitness', ticklen=5, gridwidth=1, ), showlegend=False ) fig = go.Figure(data=data+l, layout=layout) return py.iplot(fig, filename='fitness-average-n-runs', layout=layout) def plot_scatter(dt, title): """Plots a Scatter plot of each individual in the population""" l = [] y = [] N = len(dt.gen.unique()) c = ['hsl('+str(h)+',50%'+',50%)' for h in np.linspace(0, 360, N)] for i in range(int(N)): subset = dt.loc[dt['gen'] == i] trace0 = go.Scatter( x=subset.loc[:, 'gen'], y=subset.loc[:, 'fitness'], mode='markers', marker=dict(size=14, line=dict(width=1), color=c[i], opacity=0.3 ), name='gen {}'.format(i), text=subset.loc[:, 'genome'], ) l.append(trace0) layout = go.Layout( title='Fitness of Population Individuals - {}'.format(title), hovermode='closest', xaxis=dict( title='Generations', ticklen=5, zeroline=False, gridwidth=2, ), yaxis=dict( title='Fitness', ticklen=5, gridwidth=1, ), showlegend=False ) fig = go.Figure(data=l, layout=layout) return py.iplot(fig, filename='population-scatter') def plot_grid(grid): trace = go.Heatmap(z=grid, colorscale='Viridis') data = [trace] layout = go.Layout( title='Environment and obstacles', showlegend=False ) return py.iplot(data, filename='grid-heatmap', layout=layout) def plot_fitness(dt, title): upper_bound = go.Scatter( name='75%', x=dt.index.values, y=dt.loc[:, 'q3'], mode='lines', marker=dict(color="#444"), line=dict(width=0), fillcolor='rgba(68, 68, 68, 0.3)', fill='tonexty') trace = go.Scatter( name='Median', x=dt.index.values, y=dt.loc[:, 'q2'], mode='lines', line=dict(color='rgb(31, 119, 180)'), fillcolor='rgba(68, 68, 68, 0.3)', fill='tonexty') lower_bound = go.Scatter( name='25%', x=dt.index.values, y=dt.loc[:, 'q1'], marker=dict(color="#444"), line=dict(width=0), mode='lines') trace_max = go.Scatter( x=dt.index.values, y=dt.loc[:, 'q4'], mode='lines', name='Max', line=dict( color="rgb(204, 51, 51)", dash="solid", shape="spline", smoothing=0.0, width=2 ), ) data = [lower_bound, trace, upper_bound, trace_max] layout = go.Layout( title=title, hovermode='closest', xaxis=dict( title='Generations', ticklen=5, zeroline=False, gridwidth=1, ), yaxis=dict( title='Fitness', ticklen=5, gridwidth=1, ), showlegend=True ) fig = go.Figure(data=data, layout=layout) return py.iplot(fig, filename='fitness-graph-quartile') def plot_n_fitness(dt_list, title): rgb_colors = [ "rgb(204, 51, 51)", "rgb(255, 153, 204)", "rgb(255, 204, 102)", "rgb(102, 204, 0)", "rgb(51, 51, 255)" ] data = [ go.Scatter( name=str(dt.genome_id.iloc[0]), x=dt.index.values, y=dt.loc[:, 'fitness'], mode='lines', line=dict( color=rgb, dash="solid", shape="spline", smoothing=0.0, width=2 ) ) for (rgb, dt) in zip(rgb_colors, dt_list) ] layout = go.Layout( title=title, hovermode='closest', xaxis=dict( title='# of the post-evaluation', ticklen=5, zeroline=False, gridwidth=1, ), yaxis=dict( title='Fitness', ticklen=5, gridwidth=1, ), showlegend=True ) fig = go.Figure(data=data, layout=layout) return py.iplot(fig, filename='fitness-post-evaluated-individuals') def plot_boxplot_sensors(dt): colors = [ "#3D9970", "#FF4136", "#ff9933", "#6666ff", "#33cccc", "#39e600", "#3333cc" ] data = [ go.Box( y=dt.loc[:, 's{}'.format(i+1)], name='sensor {}'.format(i+1), marker=dict(color=color) ) for i, color in enumerate(colors) ] layout = go.Layout( yaxis=dict( title='Sensors Activations', zeroline=False ), title='Sensors Behavioral Features of Individual {}'.format( dt.loc[:, 'genome_id'].iloc[0]), ) fig = go.Figure(data=data, layout=layout) return py.iplot(fig) def plot_boxplot_fitness(dt_list): colors = [ "#3D9970", "#FF4136", "#ff9933", "#6666ff", "#33cccc", "#39e600", "#3333cc" ] data = [ go.Box( y=dt.loc[:, 'fitness'], name='Individual {}'.format(dt.loc[:, 'genome_id'].iloc[0]), marker=dict(color=color) ) for (color, dt) in zip(colors, dt_list) ] layout = go.Layout( yaxis=dict( title='Fitness', zeroline=False ), title='Noise in fitness performance of best controllers.', ) fig = go.Figure(data=data, layout=layout) return py.iplot(fig) def plot_boxplot_wheels(dt_list): data = [ go.Box( x=['individual {0}'.format(genome_id) for genome_id in dt.loc[:, 'genome_id']], y=dt.loc[:, '{}'.format(wheel)], name='individual {0} {1}'.format( dt.loc[:, 'genome_id'].iloc[0], wheel), marker=dict(color=color), ) for dt in dt_list for (color, wheel) in zip(['#FF9933', '#6666FF'], ['avg_left', 'avg_right']) ] layout = go.Layout( yaxis=dict( title='Wheel Speed Activation Values', zeroline=False ), boxmode='group' ) fig = go.Figure(data=data, layout=layout) return py.iplot(fig) def plot_path(genomes, title): colors = [ "#3D9970", "#FF4136", "#ff9933", "#6666ff", "#33cccc", "#39e600", "#3333cc", "#42f498", "#3c506d", "#ada387" ] data = [ go.Scatter( x=np.array(genome.position)[:, 0], y=np.array(genome.position)[:, 1], mode='lines', name='path {0} {1}'.format(genome.key, genome.evaluation), marker=dict(color=color) ) for (color, genome) in zip(colors, genomes) ] layout = go.Layout( title=title, #.format(genomes[0].key), xaxis=dict( zeroline=True, showline=True, mirror='ticks', zerolinecolor='#969696', zerolinewidth=4, linecolor='#636363', linewidth=6, range=[0.06, 1.10] ), yaxis=dict( zeroline=True, showline=True, mirror='ticks', zerolinecolor='#969696', zerolinewidth=4, linecolor='#636363', linewidth=6, range=[0.0, 0.78] ), shapes=[ # filled Rectangle dict( type='rect', x0=0.83, y0=0.0, x1= 0.89, y1= 0.3, line=dict( color="rgba(128, 0, 128, 1)", width=2, ), fillcolor='rgba(128, 0, 128, 0.7)', ), dict( type='rect', x0=0.06, y0=0.40, x1= 0.33, y1= 0.46, line=dict( color="rgba(128, 0, 128, 1)", width=2, ), fillcolor='rgba(128, 0, 128, 0.7)', ), dict( type='rect', x0=0.57, y0=0.40, x1= 0.68, y1= 0.78, line=dict( color="rgba(128, 0, 128, 1)", width=2, ), fillcolor='rgba(128, 0, 128, 0.7)', ) ] ) fig = go.Figure(data=data, layout=layout) return iplot(fig, filename='path-traveled-genomes') def plot_thymio_fitness(thymio1, thymio2, title): thymio1 = go.Scatter( name='Thymio 1 - genome_id: {0}'.format(thymio1.genome_id.iloc[0]), x=thymio1.index.values, y=thymio1.loc[:, 'fitness'], mode='lines', line=dict( color="rgb(255, 204, 102)", dash="solid", shape="spline", smoothing=0.0, width=2 ) ) thymio2 = go.Scatter( name='Thymio 2 - genome_id: {0}'.format(thymio2.genome_id.iloc[0]), x=thymio2.index.values, y=thymio2.loc[:, 'fitness'], mode='lines', line=dict( color="rgb(102, 204, 0)", dash="solid", shape="spline", smoothing=0.0, width=2 ) ) data = [thymio1, thymio2] layout = go.Layout( title=title, hovermode='closest', xaxis=dict( title='# of the post-evaluation', ticklen=5, zeroline=False, gridwidth=1, ), yaxis=dict( title='Fitness', ticklen=5, gridwidth=1, ), showlegend=True ) fig = go.Figure(data=data, layout=layout) return py.iplot(fig, filename='fitness-difference-thymio1-thymio2') def plot_thymio_behaviors(behaviors_list): colors = [ "#3D9970", "#FF4136", "#ff9933", "#6666ff", "#33cccc", "#39e600", "#3333cc", "#42f498", "#3c506d", "#ada387" ] data = [ go.Box( y=dt.iloc[:, 2:].sum(axis=1), name='Behavioral Features {0}'.format(dt.loc[:, 'genome_id'].iloc[0]), marker=dict(color=color) ) for (color, dt) in zip(colors, behaviors_list) ] # thymio1 = go.Box( # y=thymio1, # name='Behavioral Features Thymio 1', # marker=dict(color="#FF4136") # ) # thymio2 = go.Box( # y=thymio2, # name='Behavioral Features Thymio 2', # marker=dict(color="#39e600") # ) # data = [thymio1, thymio2] layout = go.Layout( yaxis=dict( title='Summed Behavioral Featuers of 10 runs', zeroline=False ), title='Behavioral differences of controllers' ) fig = go.Figure(data=data, layout=layout) return py.iplot(fig) def plot_moea_fitness(fitness_data, hof, title='Evaluation objectives. MOEA. Transferability.'): trace1 = go.Scatter3d( x=fitness_data.loc[:, 'fitness'], y=fitness_data.loc[:, 'str_disparity'], z=fitness_data.loc[:, 'diversity'], mode='markers', marker=dict( size=4, # color=fitness_data.loc[:, 'diversity'], # set color to an array/list of desired values # colorscale='Viridis', # choose a colorscale opacity=0.8 ), text=fitness_data.loc[:, 'genome_id'], ) data = [trace1] layout = go.Layout( title=title, margin=dict( l=0, r=0, b=0, t=0 ), scene = dict( xaxis = dict( title='Task-fitness'), yaxis = dict( title='STR Disparity'), zaxis = dict( title='Diversity'), annotations= [dict( showarrow = True, x = ind.fitness.values[0], y = ind.fitness.values[1], z = ind.fitness.values[2], text = ind.key, xanchor = "left", xshift = 10, opacity = 0.7, textangle = 0, ax = 0, ay = -75, font = dict( color = "black", size = 12 ), arrowcolor = "black", arrowsize = 3, arrowwidth = 1, arrowhead = 1 ) for ind in hof ] ), showlegend=True ) fig = go.Figure(data=data, layout=layout) return py.iplot(fig, filename='3d-scatter-colorscale') def plot_surrogate_model(fitness_data, title='STR Disparity Over Generations'): dt = fitness_data[['gen', 'str_disparity']].groupby('gen').first() trace0 = go.Scatter( x=dt.index, y=dt.loc[:, 'str_disparity'], mode='lines', name='STR Disparity', line=dict( color="rgb(204, 51, 51)", dash="solid", shape="spline", smoothing=0.0, width=2 ), ) layout = go.Layout( showlegend=True, hovermode='closest', title=title, xaxis=dict( autorange=False, range=[0, 20], showspikes=False, title="Generations", ticklen=5, gridwidth=1, ), yaxis=dict( autorange=True, title="Approximated STR Disparity", ticklen=5, gridwidth=1, ), ) data = [trace0] fig = go.Figure(data, layout=layout) return iplot(fig, filename=title) def plot_str_disparity(str_disparities, title='STR Disparities of transfered controllers'): genome_id = np.array([str_disparity[1] for str_disparity in str_disparities]) str_disparity = np.array([str_disparity[3] for str_disparity in str_disparities]) real_disparity = np.array([real_disparity[4] for real_disparity in str_disparities]) trace0 = go.Scatter( x=str_disparity, y=real_disparity, mode='markers', name='STR Disparity values', line=dict( color="rgb(204, 51, 51)", dash="solid", shape="spline", smoothing=0.0, width=2 ), text=genome_id ) trace1 = go.Scatter( x=np.arange(0, 15), y=np.arange(0, 15), mode='lines', line=dict(color='rgb(31, 119, 180)'), ) layout = go.Layout( showlegend=True, hovermode='closest', title=title, xaxis=dict( autorange=False, range=[0, 20], showspikes=False, title="Approximated STR Disparity value", ticklen=5, gridwidth=1, ), yaxis=dict( autorange=True, title="Exact STR Disparity value", ticklen=5, gridwidth=1, ), ) data = [trace0, trace1] fig = go.Figure(data, layout=layout) return iplot(fig, filename=title) def plot_moea_fitness_2d(fitness_data, hof, title='Evaluation objectives. MOEA. Transferability.'): trace1 = go.Scatter( x=fitness_data.loc[:, 'fitness'], y=fitness_data.loc[:, 'str_disparity'], mode='markers', marker=dict( size=6, opacity=0.8 ), text=fitness_data.loc[:, 'genome_id'], name='Individuals' ) pareto_x = [ind.fitness.values[0] for ind in hof] pareto_y = [ind.fitness.values[1] for ind in hof] pareto_ids = [ind.key for ind in hof] pareto_front = go.Scatter( x=pareto_x, y=pareto_y, mode='lines+markers', marker=dict( size=6, opacity=0.8, color="red" ), text=pareto_ids, name='Pareto-front' ) data = [trace1, pareto_front] layout = go.Layout( title=title, xaxis = dict( title='Task-fitness'), yaxis = dict( title='STR Disparity'), # annotations= [dict( # showarrow = True, # x = ind.fitness.values[0], # y = ind.fitness.values[1], # xref = 'x', # yref = 'y', # text = ind.key, # ax = 0, # ay = -40, # font = dict( # color = "black", # size = 12 # ), # arrowcolor = "#636363", # arrowsize = 1, # arrowwidth = 1, # arrowhead = 7 # ) for ind in hof # ], showlegend=True ) fig = go.Figure(data=data, layout=layout) return iplot(fig, filename='moea-scatter-colorscale')
25.7017
115
0.500992
0
0
0
0
0
0
0
0
6,167
0.185429
9a2d4e4783b1e8d97223132070735cfa9ed1e2ca
1,683
py
Python
CUMCM2014/Problem-A/2014-A-Python_SC/梯度图.py
Amoiensis/Mathmatic_Modeling_CUMCM
c64ec097d764ec3ae14e26e840bf5642be372d7c
[ "Apache-2.0" ]
27
2019-08-30T07:09:53.000Z
2021-08-29T07:37:24.000Z
CUMCM2014/Problem-A/2014-A-Python_SC/梯度图.py
Amoiensis/Mathmatic_Modeling_CUMCM
c64ec097d764ec3ae14e26e840bf5642be372d7c
[ "Apache-2.0" ]
2
2020-08-10T03:11:32.000Z
2020-08-24T13:39:24.000Z
CUMCM2014/Problem-A/2014-A-Python_SC/梯度图.py
Amoiensis/Mathmatic_Modeling_CUMCM
c64ec097d764ec3ae14e26e840bf5642be372d7c
[ "Apache-2.0" ]
28
2019-12-14T03:54:42.000Z
2022-03-12T14:38:22.000Z
# -*- coding: utf-8 -*- """ --------------------------------------------- File Name: 粗避障 Desciption: Author: fanzhiwei date: 2019/9/5 9:58 --------------------------------------------- Change Activity: 2019/9/5 9:58 --------------------------------------------- """ import numpy as np import math import matplotlib.pyplot as plt from scipy import ndimage from PIL import Image LongRangeScanRaw = plt.imread("./1.tif") ShortRangeScanRaw = plt.imread("./2.tif") ShortRangeScanMean = ndimage.median_filter(ShortRangeScanRaw, 10) LongRangeScanMean = ndimage.median_filter(LongRangeScanRaw, 10) SizeLong = math.sqrt(LongRangeScanRaw.size) SizeShort = math.sqrt(ShortRangeScanRaw.size) def ToBinary(map_data): mean = map_data.mean() diff = np.abs(map_data - mean) variance = math.sqrt(map_data.var()) * 0.7 x, y = np.gradient(map_data) graded_map = np.hypot(x, y) # 梯度图 mean_graded = graded_map.mean() diff_graded = np.abs(graded_map - 0) variance_graded = math.sqrt(graded_map.var()) * 0.84 low_value_indices = diff < variance high_value_indices = diff >= variance map_data[low_value_indices] = 0 map_data[high_value_indices] = 255 low_value_indices = diff_graded < variance_graded high_value_indices = diff_graded >= variance_graded # map_data[low_value_indices] = 0 map_data[high_value_indices] = 255 return map_data if __name__ == "__main__": Longimage = Image.fromarray(ToBinary(LongRangeScanMean)) Shortimage = Image.fromarray(ToBinary(ShortRangeScanMean)) Longimage.save("new_1.bmp") Shortimage.save("new_2.bmp")
29.017241
65
0.633393
0
0
0
0
0
0
0
0
434
0.256047
9a2d7ee04fd9497228365f3b015187758913933a
965
py
Python
models.py
curieos/Django-Blog-TDD
ba40b285d87c88aa33b1e2eb3d4bda014a88a319
[ "MIT" ]
null
null
null
models.py
curieos/Django-Blog-TDD
ba40b285d87c88aa33b1e2eb3d4bda014a88a319
[ "MIT" ]
8
2019-04-14T13:53:55.000Z
2019-07-11T18:06:57.000Z
models.py
curieos/Django-Blog-TDD
ba40b285d87c88aa33b1e2eb3d4bda014a88a319
[ "MIT" ]
null
null
null
from django.utils.text import slugify from django_extensions.db.fields import AutoSlugField from django.db import models from datetime import datetime def get_current_date_time(): return datetime.now() # Create your models here. class Post(models.Model): title = models.CharField(max_length=50) slug = AutoSlugField(max_length=50, populate_from=('title')) projects = models.ManyToManyField("projects.Project", verbose_name="Related Projects", blank=True) tags = models.ManyToManyField("Tag") date_created = models.DateTimeField(primary_key=True, default=get_current_date_time, editable=False) last_modified = models.DateTimeField(auto_now=True) content = models.TextField() def __str__(self): return self.title class Tag(models.Model): name = models.CharField(max_length=50, primary_key=True) slug = AutoSlugField(max_length=50, populate_from=('name')) def __str__(self): return self.name def popularity(self): return self.related.all()
29.242424
101
0.78342
727
0.753368
0
0
0
0
0
0
80
0.082902
9a2e437ae8b03063acc62700c14efeca6658092a
145
py
Python
brl_gym/estimators/learnable_bf/__init__.py
gilwoolee/brl_gym
9c0784e9928f12d2ee0528c79a533202d3afb640
[ "BSD-3-Clause" ]
2
2020-08-07T05:50:44.000Z
2022-03-03T08:46:10.000Z
brl_gym/estimators/learnable_bf/__init__.py
gilwoolee/brl_gym
9c0784e9928f12d2ee0528c79a533202d3afb640
[ "BSD-3-Clause" ]
null
null
null
brl_gym/estimators/learnable_bf/__init__.py
gilwoolee/brl_gym
9c0784e9928f12d2ee0528c79a533202d3afb640
[ "BSD-3-Clause" ]
null
null
null
from brl_gym.estimators.learnable_bf.learnable_bf import LearnableBF #from brl_gym.estimators.learnable_bf.bf_dataset import BayesFilterDataset
36.25
74
0.889655
0
0
0
0
0
0
0
0
74
0.510345
9a337713256137d5fcba2e7758391c4a3d42f204
4,156
py
Python
scripts/figures/kernels.py
qbhan/sample_based_MCdenoising
92f5220802ef0668105cdee5fd7e2af8a66201db
[ "Apache-2.0" ]
78
2019-10-02T01:34:46.000Z
2022-03-21T11:18:04.000Z
scripts/figures/kernels.py
qbhan/sample_based_MCdenoising
92f5220802ef0668105cdee5fd7e2af8a66201db
[ "Apache-2.0" ]
17
2019-10-04T17:04:00.000Z
2021-05-17T19:02:12.000Z
scripts/figures/kernels.py
qbhan/sample_based_MCdenoising
92f5220802ef0668105cdee5fd7e2af8a66201db
[ "Apache-2.0" ]
18
2019-10-03T05:02:21.000Z
2021-06-22T15:54:15.000Z
import os import argparse import logging import numpy as np import torch as th from torch.utils.data import DataLoader from torchvision import transforms import ttools from ttools.modules.image_operators import crop_like import rendernet.dataset as dset import rendernet.modules.preprocessors as pre import rendernet.modules.models as models import rendernet.interfaces as interfaces import rendernet.callbacks as cb import rendernet.viz as viz from sbmc.utils import make_variable import skimage.io as skio log = logging.getLogger("rendernet") def main(args): log.info("Loading model {}".format(args.checkpoint)) meta_params = ttools.Checkpointer.load_meta(args.checkpoint) spp = meta_params["spp"] use_p = meta_params["use_p"] use_ld = meta_params["use_ld"] use_bt = meta_params["use_bt"] # use_coc = meta_params["use_coc"] mode = "sample" if "DisneyPreprocessor" == meta_params["preprocessor"]: mode = "disney_pixel" elif "SampleDisneyPreprocessor" == meta_params["preprocessor"]: mode = "disney_sample" log.info("Rendering at {} spp".format(spp)) log.info("Setting up dataloader, p:{} bt:{} ld:{}".format(use_p, use_bt, use_ld)) data = dset.FullImageDataset(args.data, dset.RenderDataset, spp=spp, use_p=use_p, use_ld=use_ld, use_bt=use_bt) preprocessor = pre.get(meta_params["preprocessor"])(data) xforms = transforms.Compose([dset.ToTensor(), preprocessor]) data.transform = xforms dataloader = DataLoader(data, batch_size=1, shuffle=False, num_workers=0, pin_memory=True) model = models.get(preprocessor, meta_params["model_params"]) model.cuda() model.train(False) checkpointer = ttools.Checkpointer(args.checkpoint, model, None) extras, meta = checkpointer.load_latest() log.info("Loading latest checkpoint {}".format("failed" if meta is None else "success")) for scene_id, batch in enumerate(dataloader): batch_v = make_variable(batch, cuda=True) with th.no_grad(): klist = [] out_ = model(batch_v, kernel_list=klist) lowspp = batch["radiance"] target = batch["target_image"] out = out_["radiance"] cx = 70 cy = 20 c = 128 target = crop_like(target, out) lowspp = crop_like(lowspp.squeeze(), out) lowspp = lowspp[..., cy:cy+c, cx:cx+c] lowspp = lowspp.permute(1, 2, 0, 3) chan, h, w, s = lowspp.shape lowspp = lowspp.contiguous().view(chan, h, w*s) sum_r = [] sum_w = [] max_w = [] maxi = crop_like(klist[-1]["max_w"].unsqueeze(1), out) kernels = [] updated_kernels = [] for k in klist: kernels.append(th.exp(crop_like(k["kernels"], out)-maxi)) updated_kernels.append(th.exp(crop_like(k["updated_kernels"], out)-maxi)) out = out[..., cy:cy+c, cx:cx+c] target = target[..., cy:cy+c, cx:cx+c] updated_kernels = [k[..., cy:cy+c, cx:cx+c] for k in updated_kernels] kernels = [k[..., cy:cy+c, cx:cx+c] for k in kernels] u_kernels_im = viz.kernels2im(kernels) kmean = u_kernels_im.mean(0) kvar = u_kernels_im.std(0) n, h, w = u_kernels_im.shape u_kernels_im = u_kernels_im.permute(1, 0, 2).contiguous().view(h, w*n) fname = os.path.join(args.output, "lowspp.png") save(fname, lowspp) fname = os.path.join(args.output, "target.png") save(fname, target) fname = os.path.join(args.output, "output.png") save(fname, out) fname = os.path.join(args.output, "kernels_gather.png") save(fname, u_kernels_im) fname = os.path.join(args.output, "kernels_variance.png") print(kvar.max()) save(fname, kvar) import ipdb; ipdb.set_trace() break def save(fname, im): os.makedirs(os.path.dirname(fname), exist_ok=True) im = im.squeeze().cpu() if len(im.shape) >= 3: im = im.permute(1, 2, 0) im = th.clamp(im, 0, 1).numpy() skio.imsave(fname, im) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--checkpoint", required=True) parser.add_argument("--data", required=True) parser.add_argument("--output", required=True) args = parser.parse_args() ttools.set_logger(True) main(args)
31.24812
113
0.677334
0
0
0
0
0
0
0
0
526
0.126564
9a33a34b59f215b243d9da922749fa4b6ad17b64
1,002
py
Python
code/analytics/models.py
harryface/url-condenser
800b573a82f41dd4900c8264007c1a0260a1a8b4
[ "MIT" ]
null
null
null
code/analytics/models.py
harryface/url-condenser
800b573a82f41dd4900c8264007c1a0260a1a8b4
[ "MIT" ]
null
null
null
code/analytics/models.py
harryface/url-condenser
800b573a82f41dd4900c8264007c1a0260a1a8b4
[ "MIT" ]
null
null
null
from django.db import models # Create your models here. from shortener.models import CondenseURL class UrlViewedManager(models.Manager): def create_event(self, condensed_object, ip_address): if isinstance(condensed_object, CondenseURL): obj, created = self.get_or_create(url=condensed_object) if created: obj.ip_address = ip_address else: obj.ip_address += f"\n{ip_address}" obj.count += 1 obj.save() return return class UrlViews(models.Model): url = models.OneToOneField(CondenseURL, on_delete=models.CASCADE) ip_address = models.TextField(blank=True, null=True) count = models.IntegerField(default=0) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = UrlViewedManager() def __str__(self): return f"{self.url} - {self.count}" class Meta: verbose_name = "Url View"
31.3125
69
0.653693
901
0.899202
0
0
0
0
0
0
81
0.080838
9a3726435cdad9b9e21619560262a26d9cbff99c
299
py
Python
scripts/alan/clean_pycache.py
Pix-00/olea
98bee1fd8866a3929f685a139255afb7b6813f31
[ "Apache-2.0" ]
2
2020-06-18T03:25:52.000Z
2020-06-18T07:33:45.000Z
scripts/alan/clean_pycache.py
Pix-00/olea
98bee1fd8866a3929f685a139255afb7b6813f31
[ "Apache-2.0" ]
15
2021-01-28T07:11:04.000Z
2021-05-24T07:11:37.000Z
scripts/alan/clean_pycache.py
Pix-00/olea
98bee1fd8866a3929f685a139255afb7b6813f31
[ "Apache-2.0" ]
null
null
null
def clean_pycache(dir_, ignores=''): import shutil for path in dir_.glob('**/__pycache__'): if ignores and path.match(ignores): continue shutil.rmtree(path) if __name__ == "__main__": from pathlib import Path clean_pycache(Path(__file__).parents[2])
19.933333
44
0.638796
0
0
0
0
0
0
0
0
28
0.093645
9a3a8f8810da891a7c03436b0f8a519f17f8d1e7
212
py
Python
orb_simulator/orbsim_language/orbsim_ast/tuple_creation_node.py
dmguezjaviersnet/IA-Sim-Comp-Project
8165b9546efc45f98091a3774e2dae4f45942048
[ "MIT" ]
1
2022-01-19T22:49:09.000Z
2022-01-19T22:49:09.000Z
orb_simulator/orbsim_language/orbsim_ast/tuple_creation_node.py
dmguezjaviersnet/IA-Sim-Comp-Project
8165b9546efc45f98091a3774e2dae4f45942048
[ "MIT" ]
15
2021-11-10T14:25:02.000Z
2022-02-12T19:17:11.000Z
orb_simulator/orbsim_language/orbsim_ast/tuple_creation_node.py
dmguezjaviersnet/IA-Sim-Comp-Project
8165b9546efc45f98091a3774e2dae4f45942048
[ "MIT" ]
null
null
null
from dataclasses import dataclass from typing import List from orbsim_language.orbsim_ast.expression_node import ExpressionNode @dataclass class TupleCreationNode(ExpressionNode): elems: List[ExpressionNode]
30.285714
69
0.858491
72
0.339623
0
0
83
0.391509
0
0
0
0
9a4004b98dc117b5e58a273f30a560e340d87721
1,345
py
Python
csv_merge_col.py
adrianpope/VelocityCompression
eb35f586b18890da93a7ad2e287437118c0327a2
[ "BSD-3-Clause" ]
null
null
null
csv_merge_col.py
adrianpope/VelocityCompression
eb35f586b18890da93a7ad2e287437118c0327a2
[ "BSD-3-Clause" ]
null
null
null
csv_merge_col.py
adrianpope/VelocityCompression
eb35f586b18890da93a7ad2e287437118c0327a2
[ "BSD-3-Clause" ]
null
null
null
import sys import numpy as np import pandas as pd def df_add_keys(df): ax = df['fof_halo_angmom_x'] ay = df['fof_halo_angmom_y'] az = df['fof_halo_angmom_z'] mag = np.sqrt(ax**2 + ay**2 + az**2) dx = ax/mag dy = ay/mag dz = az/mag df['fof_halo_angmom_dx'] = dx df['fof_halo_angmom_dy'] = dy df['fof_halo_angmom_dz'] = dz df['fof_halo_angmom_mag'] = mag mass = df['fof_halo_mass'] df['fof_halo_specific_angmom_mag'] = mag/mass return df def df_merge(df1, df1_suffix, df2, df2_suffix): merged = pd.DataFrame() kl = df1.keys() for i in range(len(kl)): k = kl[i] k1 = k + '_' + df1_suffix k2 = k + '_' + df2_suffix merged[k1] = df1[k] merged[k2] = df2[k] return merged if __name__ == '__main__': argv = sys.argv if len(argv) < 7: print('USAGE: %s <in1_name> <in1_suffix> <in2_name> <in2_suffix> <out_name> <add_keys>'%argv[0]) sys.exit(-1) in1_name = argv[1] in1_suffix = argv[2] in2_name = argv[3] in2_suffix = argv[4] out_name = argv[5] add_keys = int(argv[6]) in1 = pd.read_csv(in1_name) in2 = pd.read_csv(in2_name) if add_keys: df_add_keys(in1) df_add_keys(in2) merged = df_merge(in1, in1_suffix, in2, in2_suffix) merged.to_csv(out_name)
24.907407
104
0.594052
0
0
0
0
0
0
0
0
280
0.208178
9a409844ea8ff87b62a343aba1bddbe1b4acc686
649
py
Python
Toolkits/VCS/mygulamali__repo-mine/mine/helpers.py
roscopecoltran/SniperKit-Core
4600dffe1cddff438b948b6c22f586d052971e04
[ "MIT" ]
null
null
null
Toolkits/VCS/mygulamali__repo-mine/mine/helpers.py
roscopecoltran/SniperKit-Core
4600dffe1cddff438b948b6c22f586d052971e04
[ "MIT" ]
null
null
null
Toolkits/VCS/mygulamali__repo-mine/mine/helpers.py
roscopecoltran/SniperKit-Core
4600dffe1cddff438b948b6c22f586d052971e04
[ "MIT" ]
null
null
null
from sys import stdout def print_action(action): def print_action_decorator(function): def puts(string): stdout.write(string) stdout.flush() def function_wrapper(*args, **kwargs): puts("{0}... ".format(action)) return_value = function(*args, **kwargs) puts("Done!\n") return return_value return function_wrapper return print_action_decorator def format_plot_axes(axes): axes.xaxis.set_ticks_position('bottom') axes.yaxis.set_ticks_position('none') axes.spines['top'].set_color('none') axes.spines['right'].set_color('none')
27.041667
52
0.628659
0
0
0
0
0
0
0
0
56
0.086287
9a4099a116dd4efb8f2b5619fb34ffe71a578a58
1,845
py
Python
scripts/check-silknow-urls.py
silknow/crawler
d2632cea9b98ab64a8bca56bc70b34edd3c2de31
[ "Apache-2.0" ]
1
2019-04-21T07:09:52.000Z
2019-04-21T07:09:52.000Z
scripts/check-silknow-urls.py
silknow/crawler
d2632cea9b98ab64a8bca56bc70b34edd3c2de31
[ "Apache-2.0" ]
35
2019-01-21T23:53:52.000Z
2022-02-12T04:28:17.000Z
scripts/check-silknow-urls.py
silknow/crawler
d2632cea9b98ab64a8bca56bc70b34edd3c2de31
[ "Apache-2.0" ]
null
null
null
import argparse import csv import os parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', help="Input path of the missing urls CSV file") parser.add_argument('-o', '--output', help="Output directory where the new CSV files will be stored") parser.add_argument('-q', '--quiet', action='store_true', help="Do not print the list of missing files") args = parser.parse_args() with open(args.input) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') missing_urls_output = os.path.join(args.output, 'silknow-missing-urls.csv') missing_files_output = os.path.join(args.output, 'silknow-missing-files.csv') with open(missing_urls_output, mode='w') as missing_url: missing_url_writer = csv.writer(missing_url, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) with open(missing_files_output, mode='w') as missing_file: missing_file_writer = csv.writer(missing_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) header = next(csv_reader) missing_file_writer.writerow(header); filepath_cache = [] for row in csv_reader: museum = row[3].split('/')[5] filename = os.path.basename(row[3]) filepath = os.path.normpath(os.path.join(museum, filename)) filepath_cache.append(filepath) if not os.path.exists(filepath): missing_file_writer.writerow(row) if not args.quiet: print(filepath + ' does not exist in files') for root, dirs, files in os.walk('./'): for file in files: if file.endswith('.jpg'): filepath = os.path.normpath(os.path.join(root, file)) if filepath not in filepath_cache: missing_url_writer.writerow([filepath]) if not args.quiet: print(filepath + ' does not exist in query result')
38.4375
105
0.666667
0
0
0
0
0
0
0
0
336
0.182114
9a40c18aa2fcf755b162532d605ac1593ac74650
2,302
py
Python
Trabajo 3/auxFunc.py
francaracuel/UGR-GII-CCIA-4-VC-Vision_por_computador-17-18-Practicas
cb801eb5dfc4a8ea0300eae66a3b9bb2943fe8ab
[ "Apache-2.0" ]
1
2019-01-28T09:43:41.000Z
2019-01-28T09:43:41.000Z
Trabajo 3/auxFunc.py
francaracuel/UGR-GII-CCIA-4-VC-Vision_por_computador-17-18-Practicas
cb801eb5dfc4a8ea0300eae66a3b9bb2943fe8ab
[ "Apache-2.0" ]
null
null
null
Trabajo 3/auxFunc.py
francaracuel/UGR-GII-CCIA-4-VC-Vision_por_computador-17-18-Practicas
cb801eb5dfc4a8ea0300eae66a3b9bb2943fe8ab
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Tue Nov 21 11:20:06 2017 @author: NPB """ import cv2 import pickle def loadDictionary(filename): with open(filename,"rb") as fd: feat=pickle.load(fd) return feat["accuracy"],feat["labels"], feat["dictionary"] def loadAux(filename, flagPatches): if flagPatches: with open(filename,"rb") as fd: feat=pickle.load(fd) return feat["descriptors"],feat["patches"] else: with open(filename,"rb") as fd: feat=pickle.load(fd) return feat["descriptors"] def click_and_draw(event,x,y,flags,param): global refPt, imagen,FlagEND # if the left mouse button was clicked, record the starting # (x, y) coordinates and indicate that cropping is being # performed if event == cv2.EVENT_LBUTTONDBLCLK: FlagEND= False cv2.destroyWindow("image") elif event == cv2.EVENT_LBUTTONDOWN: refPt.append((x, y)) #cropping = True print("rfePt[0]",refPt[0]) elif (event == cv2.EVENT_MOUSEMOVE) & (len(refPt) > 0) & FlagEND: # check to see if the mouse move clone=imagen.copy() nPt=(x,y) print("npt",nPt) sz=len(refPt) cv2.line(clone,refPt[sz-1],nPt,(0, 255, 0), 2) cv2.imshow("image", clone) cv2.waitKey(0) elif event == cv2.EVENT_RBUTTONDOWN: # record the ending (x, y) coordinates and indicate that # the cropping operation is finished refPt.append((x, y)) #cropping = False sz=len(refPt) print("refPt[sz]",sz,refPt[sz-1]) cv2.line(imagen,refPt[sz-2],refPt[sz-1],(0, 255, 0), 2) cv2.imshow("image", imagen) cv2.waitKey(0) def extractRegion(image): global refPt, imagen,FlagEND imagen=image.copy() # load the image and setup the mouse callback function refPt=[] FlagEND=True #image = cv2.imread(filename) cv2.namedWindow("image") # keep looping until the 'q' key is pressed cv2.setMouseCallback("image", click_and_draw) # while FlagEND: # display the image and wait for a keypress cv2.imshow("image", image) cv2.waitKey(0) # print('FlagEND', FlagEND) refPt.pop() refPt.append(refPt[0]) cv2.destroyWindow("image") return refPt
26.45977
69
0.613814
0
0
0
0
0
0
0
0
695
0.301911
9a417a0a839c157704c0bb9c7d9a86e16b358f3e
22,087
py
Python
pdb_profiling/processors/uniprot/api.py
NatureGeorge/pdb-profiling
b29f93f90fccf03869a7a294932f61d8e0b3470c
[ "MIT" ]
5
2020-10-27T12:02:00.000Z
2021-11-05T06:51:59.000Z
pdb_profiling/processors/uniprot/api.py
NatureGeorge/pdb-profiling
b29f93f90fccf03869a7a294932f61d8e0b3470c
[ "MIT" ]
9
2021-01-07T04:47:58.000Z
2021-09-22T13:20:35.000Z
pdb_profiling/processors/uniprot/api.py
NatureGeorge/pdb-profiling
b29f93f90fccf03869a7a294932f61d8e0b3470c
[ "MIT" ]
null
null
null
# @Created Date: 2019-12-08 06:46:49 pm # @Filename: api.py # @Email: [email protected] # @Author: ZeFeng Zhu # @Last Modified: 2020-02-16 10:54:32 am # @Copyright (c) 2020 MinghuiGroup, Soochow University from typing import Iterable, Iterator, Optional, Union, Generator, Dict, List from time import perf_counter from numpy import nan, array from pathlib import Path from unsync import unsync, Unfuture from copy import deepcopy from pdb_profiling.log import Abclog from pdb_profiling.utils import init_semaphore, init_folder_from_suffix, init_folder_from_suffixes, a_read_csv from pdb_profiling.fetcher.webfetch import UnsyncFetch from uuid import uuid4 from pdb_profiling.cif_gz_stream import iter_index from aiohttp import ClientSession from aiofiles import open as aiofiles_open from pdb_profiling.ensure import EnsureBase from tenacity import wait_random, stop_after_attempt ensure = EnsureBase() rt_kw = dict(wait=wait_random(max=20), stop=stop_after_attempt(6)) """QUERY_COLUMNS: List[str] = [ 'id', 'length', 'reviewed', 'comment(ALTERNATIVE%20PRODUCTS)', 'feature(ALTERNATIVE%20SEQUENCE)', 'genes', 'organism', 'protein%20names'] RESULT_COLUMNS: List[str] = [ 'Entry', 'Length', 'Status', 'Alternative products (isoforms)', 'Alternative sequence', 'Gene names', 'Organism', 'Protein names'] COLUMNS_DICT: Dict = dict(zip(QUERY_COLUMNS, RESULT_COLUMNS)) RESULT_NEW_COLUMN: List[str] = ['yourlist', 'isomap']""" BASE_URL: str = 'https://www.uniprot.org' """PARAMS: Dict = { # 'fil': 'organism%3A"Homo+sapiens+(Human)+[9606]"+AND+reviewed%3Ayes', # reviewed:yes+AND+organism:9606 'columns': None, 'query': None, 'from': None, 'to': 'ACC', 'format': 'tab'}""" """ class MapUniProtID(Abclog): ''' Implement UniProt Retrieve/ID Mapping API ''' def __init__(self, id_col: str, id_type: str, dfrm: Optional[DataFrame], ids: Optional[Iterable] = None, sites: Optional[Iterable] = None, genes: Optional[Iterable] = None, usecols: Optional[Iterable] = QUERY_COLUMNS, site_col: Optional[str] = None, gene_col: Optional[str] = None, logger: Optional[logging.Logger] = None, loggingPath: Optional[str] = None): self.init_logger(self.__class__.__name__, logger) if dfrm is not None: self.dfrm = dfrm.drop_duplicates().reset_index(drop=True) else: ''' the length of dataframe is based on: * the num of `ids` if there is more than one id * the num of `sites` if there is just one id with specified `sites` ''' if isinstance(ids, str): if sites is not None and not isinstance(sites, str): index_len = len(sites) else: index_len = 1 else: index_len = len(ids) self.dfrm = DataFrame(dict(zip( (col for col in (id_col, site_col, gene_col) if col is not None), (value for value in (ids, sites, genes) if value is not None))), index=list(range(index_len))) self.index = dfrm.index self.id_col = id_col self.id_type = id_type self.site_col = site_col self.gene_col = gene_col self.loggingPath = loggingPath if isinstance(usecols, str): PARAMS['columns'] = usecols usecols = usecols.split(',') elif isinstance(usecols, (Iterable, Iterator)): PARAMS['columns'] = ','.join(usecols) else: raise ValueError('Invalid usecols') self.usecols = usecols PARAMS['from'] = id_type if isinstance(loggingPath, (str, Path)): self.set_logging_fileHandler(loggingPath) @property def sites(self) -> Generator: if self.site_col is not None: for name, group in self.dfrm.groupby(by=self.id_col, sort=False): yield name, group[self.site_col] else: yield None @staticmethod def split_df(dfrm, colName, sep): '''Split DataFrame''' df = dfrm.copy() return df.drop([colName], axis=1).join(df[colName].str.split(sep, expand=True).stack().reset_index(level=1, drop=True).rename(colName)) def yieldTasks(self, lyst: Iterable, chunksize: int = 100, sep: str = ',') -> Generator: fileName = self.outputPath.stem for i in range(0, len(lyst), chunksize): cur_fileName = f'{fileName}+{i}' cur_params = deepcopy(PARAMS) cur_params['query'] = sep.join(lyst[i:i+chunksize]) # self.outputPath.suffix yield ('get', {'url': f'{BASE_URL}/uploadlists/', 'params': cur_params}, str(Path(self.outputPath.parent, cur_fileName+'.tsv'))) def retrieve(self, outputPath: Union[str, Path], finishedPath: Optional[str] = None, sep: str = '\t', chunksize: int = 100, concur_req: int = 20, rate: float = 1.5, ret_res: bool = True, semaphore = None): finish_id = list() self.outputPath = Path(outputPath) self.result_cols = [COLUMNS_DICT.get( i, i) for i in self.usecols] + RESULT_NEW_COLUMN if finishedPath is not None: try: target_col = RESULT_NEW_COLUMN[0] finish: Series = read_csv( finishedPath, sep=sep, usecols=[target_col], names=self.result_cols, skiprows=1, header=None)[target_col] except Exception as e: col_to_add = RESULT_NEW_COLUMN[1] self.logger.warning( f"{e}\nSomething wrong with finished raw file, probably without '{col_to_add}' column.") finish_df = read_csv( finishedPath, sep=sep, names=self.result_cols[:-1], skiprows=1, header=None) finish_df[col_to_add] = nan finish_df.to_csv(finishedPath, sep=sep, index=False) finish: Series = finish_df[target_col] for query_id in finish: if ',' in query_id: finish_id.extend(query_id.split(',')) else: finish_id.append(query_id) query_id: Series = self.dfrm[self.id_col] if finish_id: rest_id = list(set(query_id) - set(finish_id)) else: rest_id = query_id.unique() self.logger.info( f"Have finished {len(finish_id)} ids, {len(rest_id)} ids left.") res = UnsyncFetch.multi_tasks( tasks=self.yieldTasks(rest_id, chunksize), to_do_func=self.process, concur_req=concur_req, rate=rate, ret_res=ret_res, semaphore=semaphore) return res def getCanonicalInfo(self, dfrm: DataFrame): ''' Will Change the dfrm * Add new column (canonical_isoform) * Change the content of column (UniProt) ''' # Get info from Alt Product file if self.altProPath is None: dfrm['canonical_isoform'] = nan return dfrm else: usecols = ["IsoId", "Sequence", "Entry", "UniProt"] altPro_df = read_csv(self.altProPath, sep="\t", usecols=usecols) altPro_df = altPro_df[altPro_df["Sequence"] == "Displayed"].reset_index(drop=True) altPro_df.rename( columns={"IsoId": "canonical_isoform"}, inplace=True) # Modify dfrm dfrm = merge( dfrm, altPro_df[["canonical_isoform", "Entry"]], how="left") return dfrm def getGeneStatus(self, handled_df: DataFrame, colName: str = 'GENE_status'): ''' Will Change the dfrm, add Gene Status * Add new column (GENE) # if id_col != gene_col * Add new column (GENE_status) **About GENE_status** * ``False`` : First element of Gene names is not correspond with refSeq's GENE (e.g) * others(corresponding GENE) ''' self.gene_status_col = colName if self.id_type != 'GENENAME': if self.gene_col is None: handled_df[colName] = True return None gene_map = self.dfrm[[self.id_col, self.gene_col]].drop_duplicates() gene_map = gene_map.groupby(self.id_col)[self.gene_col].apply( lambda x: array(x) if len(x) > 1 else list(x)[0]) handled_df['GENE'] = handled_df.apply( lambda z: gene_map[z['yourlist']], axis=1) handled_df[colName] = handled_df.apply(lambda x: x['GENE'] == x['Gene names'].split( ' ')[0] if not isinstance(x['Gene names'], float) else False, axis=1) handled_df['GENE'] = handled_df['GENE'].apply( lambda x: ','.join(x) if not isinstance(x, str) else x) else: handled_df[colName] = handled_df.apply(lambda x: x['yourlist'] == x['Gene names'].split( ' ')[0] if not isinstance(x['Gene names'], float) else False, axis=1) def label_mapping_status(self, dfrm: DataFrame, colName: str = 'Mapping_status'): self.mapping_status_col = colName gene_status_col = self.gene_status_col dfrm[colName] = 'No' dfrm[gene_status_col] = dfrm[gene_status_col].apply( lambda x: x.any() if isinstance(x, Iterable) else x) if self.id_col == 'GENENAME': pass_df = dfrm[ (dfrm[gene_status_col] == True) & (dfrm['Status'] == 'reviewed') & (dfrm['unp_map_tage'] != 'Untrusted & No Isoform')] else: pass_df = dfrm[ (dfrm['Status'] == 'reviewed') & (dfrm['unp_map_tage'] != 'Untrusted & No Isoform')] pass_index = pass_df.index dfrm.loc[pass_index, colName] = 'Yes' # Deal with 'one to many' situation multipleCounter = Counter(dfrm.loc[pass_index, 'yourlist']) err_li = [i for i, j in multipleCounter.items() if j > 1] err_index = pass_df[pass_df['yourlist'].isin(err_li)].index dfrm.loc[err_index, colName] = 'Error' @unsync async def process(self, path: Union[str, Path, Unfuture], sep: str = '\t'): self.logger.debug("Start to handle id mapping result") if not isinstance(path, (Path, str)): path = await path # .result() if not Path(path).stat().st_size: return None self.altSeqPath, self.altProPath = ExtractIsoAlt.main(path=path) try: df = read_csv( path, sep='\t', names=self.result_cols, skiprows=1, header=None) except ValueError: df = read_csv( path, sep='\t', names=self.result_cols[:-1], skiprows=1, header=None) # Add New Column: canonical_isoform df = self.getCanonicalInfo(df) # Add New Column: unp_map_tage df['unp_map_tage'] = nan # Classification df_with_no_isomap = df[df['isomap'].isnull()] # Class A df_with_isomap = df[df['isomap'].notnull()] # Class B # ---------------------------------------------------------------------- # In Class A # ---------------------------------------------------------------------- if len(df_with_no_isomap) > 0: df_wni_split = self.split_df(df_with_no_isomap, 'yourlist', ',') df_wni_split.drop(columns=['isomap'], inplace=True) # [yourlist <-> UniProt] df_wni_split['UniProt'] = df_wni_split['Entry'] df_wni_split['unp_map_tage'] = 'Trusted & No Isoform' # Find out special cases 1 df_wni_split_warn = df_wni_split[df_wni_split['Alternative products (isoforms)'].notnull( )].index df_wni_split.loc[df_wni_split_warn, 'unp_map_tage'] = 'Untrusted & No Isoform' # 'Entry', 'Gene names', 'Status', 'Alternative products (isoforms)', 'Organism', 'yourlist', 'UniProt' # ---------------------------------------------------------------------- # In Class B # ---------------------------------------------------------------------- if len(df_with_isomap) > 0: wi_yourlist_count = df_with_isomap.apply( lambda x: x['yourlist'].count(','), axis=1) wi_isomap_count = df_with_isomap.apply( lambda x: x['isomap'].count(','), axis=1) # In subClass 1 df_wi_eq = df_with_isomap.loc[wi_yourlist_count[wi_yourlist_count == wi_isomap_count].index] if len(df_wi_eq) > 0: df_wi_eq_split = self.split_df( df_wi_eq.drop(columns=['yourlist']), 'isomap', ',') df_wi_eq_split[['yourlist', 'UniProt']] = df_wi_eq_split['isomap'].str.split( ' -> ', expand=True) # [yourlist <-> UniProt] df_wi_eq_split.drop(columns=['isomap'], inplace=True) df_wi_eq_split['unp_map_tage'] = 'Trusted & Isoform' # # 'Entry', 'Gene names', 'Status', 'Alternative products (isoforms)', 'Organism', 'yourlist', 'UniProt' # In subClass 2 df_wi_ne = df_with_isomap.loc[wi_yourlist_count[wi_yourlist_count != wi_isomap_count].index] if len(df_wi_ne) > 0: df_wi_ne_split = self.split_df(df_wi_ne, 'isomap', ',') df_wi_ne_split.rename( columns={'yourlist': 'checkinglist'}, inplace=True) df_wi_ne_split[['yourlist', 'UniProt']] = df_wi_ne_split['isomap'].str.split( ' -> ', expand=True) df_wi_ne_split.drop(columns=['isomap'], inplace=True) df_wi_ne_split['unp_map_tage'] = 'Trusted & Isoform & Contain Warnings' # 'Entry', 'Gene names', 'Status', 'Alternative products (isoforms)', 'Organism', 'yourlist', 'UniProt', 'checkinglist' # Find out special cases 2 usecols = Index(set(df_wi_ne_split.columns) - {'yourlist', 'UniProt'}) df_wi_ne_warn = self.split_df( df_wi_ne_split[usecols].drop_duplicates(), 'checkinglist', ',') df_wi_ne_warn = df_wi_ne_warn[~df_wi_ne_warn['checkinglist'].isin( df_wi_ne_split['yourlist'])].rename(columns={'checkinglist': 'yourlist'}) df_wi_ne_warn['UniProt'] = df_wi_ne_warn['Entry'] # sequence conflict df_wi_ne_warn['unp_map_tage'] = 'Untrusted & No Isoform' df_wi_ne_split.drop(columns=['checkinglist'], inplace=True) # Concat Dfrm variables = ["df_wni_split", "df_wi_eq_split", "df_wi_ne_split", "df_wi_ne_warn"] lvs = locals() varLyst = [lvs[variable] for variable in variables if variable in lvs] final_df = concat(varLyst, sort=False).reset_index(drop=True) cano_index = final_df[final_df["canonical_isoform"].notnull()].index if len(cano_index) > 0: final_df.loc[cano_index, "UniProt"] = final_df.loc[cano_index, ].apply( lambda x: x["Entry"] if x["UniProt"] in x["canonical_isoform"] else x["UniProt"], axis=1) # Add Gene Status self.getGeneStatus(final_df) # Label Mapping Status self.label_mapping_status(final_df) pathOb = Path(path) edPath = str(Path(pathOb.parent, f'{pathOb.stem}_ed.tsv')) # {pathOb.suffix} final_df.to_csv(edPath, sep=sep, index=False) self.logger.debug(f"Handled id mapping result saved in {edPath}") return edPath """ class UniProtAPI(Abclog): ''' Implement UniProt Retrieve/ID Mapping API * focus on tabular format * <https://www.uniprot.org/help/uploadlists> * <https://www.uniprot.org/help/api_idmapping> ''' headers = {'Cache-Control': 'no-cache'} params = { 'columns': 'id,feature(ALTERNATIVE%20SEQUENCE)', 'query': None, 'from': 'ACC+ID', 'to': 'ACC', 'format': 'tab'} with_name_suffix = True @classmethod def task_unit(cls, chunk, i, folder, name, sep): cur_params = deepcopy(cls.params) cur_params['query'] = sep.join(chunk) return ('get', {'url': f'{BASE_URL}/uploadlists/', 'params': cur_params, 'headers': cls.headers}, folder/f'{name}+{i}.tsv') @classmethod def yieldTasks(cls, lyst: Iterable, chunksize: int, folder, name: str, sep: str = ',') -> Generator: name_with_suffix = f'{name}+{uuid4().hex}' if cls.with_name_suffix else name for i in range(0, len(lyst), chunksize): yield cls.task_unit(lyst[i:i+chunksize], i, folder, name_with_suffix, sep) @classmethod @unsync async def set_web_semaphore(cls, web_semaphore_value: int): cls.web_semaphore = await init_semaphore(web_semaphore_value) @classmethod def set_folder(cls, folder: Union[Path, str]): cls.folder = init_folder_from_suffix(folder, 'UniProt/uploadlists/') @classmethod def retrieve(cls, lyst: Iterable, name: str, sep: str = ',', chunksize: int = 100, rate: float = 1.5, semaphore=None, **kwargs): return [UnsyncFetch.single_task( task, semaphore=cls.web_semaphore if semaphore is None else semaphore, rate=rate) for task in cls.yieldTasks(lyst, chunksize, cls.folder, name, sep)] class UniProtINFO(Abclog): ''' * Download UniProt Fasta Sequences * Download UniProt Features ''' @classmethod @unsync async def set_web_semaphore(cls, web_semaphore_value:int): cls.web_semaphore = await init_semaphore(web_semaphore_value) @classmethod def set_folder(cls, folder: Union[Path, str]): cls.fasta_folder, cls.txt_folder = tuple(init_folder_from_suffixes(folder, ('UniProt/fasta', 'UniProt/txt'))) @classmethod def get_fasta_folder(cls): return cls.fasta_folder @classmethod def get_txt_folder(cls): return cls.txt_folder def __init__(self, api_suffix): if api_suffix == 'fasta': self.get_cur_folder = self.get_fasta_folder self.params = {'include': 'no'} elif api_suffix == 'txt': self.get_cur_folder = self.get_txt_folder self.params = {} else: raise AssertionError(f'Invalid api_suffix: {api_suffix} for UniProt') self.suffix = api_suffix def task_unit(self, unp:str): cur_fileName = f'{unp}.{self.suffix}' return ('get', {'url': f'{BASE_URL}/uniprot/{cur_fileName}', 'params': self.params}, self.get_cur_folder()/cur_fileName) def single_retrieve(self, identifier: str, rate: float = 1.5): return UnsyncFetch.single_task( task=self.task_unit(identifier), semaphore=self.web_semaphore, rate=rate) @classmethod async def txt_reader(cls, url): remain_part = b'' async with cls.web_semaphore: async with ClientSession() as session: async with session.get(url=url, timeout=3600) as resp: if resp.status == 200: async for rv in resp.content.iter_any(): if rv: index = (None, *iter_index(rv, b'\n', 1), None) if len(index) == 2: remain_part += rv continue if remain_part: yield remain_part + rv[:index[1]] remain_part = b'' for start, end in zip(index[1:-1], index[2:-1]): yield rv[start:end] else: for start, end in zip(index[:-1], index[1:-1]): yield rv[start:end] if index[-2] != len(rv): remain_part = rv[index[-2]:] if remain_part: yield remain_part else: raise Exception( "code={resp.status}, message={resp.reason}, headers={resp.headers}".format(resp=resp) + f"\nurl={url}") @staticmethod @unsync @ensure.make_sure_complete(**rt_kw) async def txt_writer(handle, path, header: bytes = b'', start_key: bytes = b'FT VAR_SEQ', content_key: bytes = b'FT '): start = False async with aiofiles_open(path, 'wb') as fileOb: if header: await fileOb.write(header) async for line in handle: if line.startswith(start_key): start = True elif start and not line.startswith(content_key): return path if start: await fileOb.write(line) def stream_retrieve_txt(self, identifier, name_suffix='VAR_SEQ', **kwargs): assert self.suffix == 'txt' return self.txt_writer(handle=self.txt_reader(f'{BASE_URL}/uniprot/{identifier}.{self.suffix}'), path=self.get_cur_folder()/f'{identifier}+{name_suffix}.{self.suffix}', **kwargs)
42.55684
186
0.55467
5,772
0.26133
1,846
0.083579
3,949
0.178793
2,342
0.106035
16,434
0.744058
9a41e415317ae7c881f36ab4cbf51cbe613df940
9,409
py
Python
hep_spt/stats/poisson.py
mramospe/hepspt
11f74978a582ebc20e0a7765dafc78f0d1f1d5d5
[ "MIT" ]
null
null
null
hep_spt/stats/poisson.py
mramospe/hepspt
11f74978a582ebc20e0a7765dafc78f0d1f1d5d5
[ "MIT" ]
null
null
null
hep_spt/stats/poisson.py
mramospe/hepspt
11f74978a582ebc20e0a7765dafc78f0d1f1d5d5
[ "MIT" ]
1
2021-11-03T03:36:15.000Z
2021-11-03T03:36:15.000Z
''' Function and classes representing statistical tools. ''' __author__ = ['Miguel Ramos Pernas'] __email__ = ['[email protected]'] from hep_spt.stats.core import chi2_one_dof, one_sigma from hep_spt.core import decorate, taking_ndarray from hep_spt import PACKAGE_PATH import numpy as np import os from scipy.stats import poisson from scipy.optimize import fsolve import warnings __all__ = ['calc_poisson_fu', 'calc_poisson_llu', 'gauss_unc', 'poisson_fu', 'poisson_llu', 'sw2_unc' ] # Number after which the poisson uncertainty is considered to # be the same as that of a gaussian with "std = sqrt(lambda)". __poisson_to_gauss__ = 200 def _access_db(name): ''' Access a database table under 'data/'. :param name: name of the file holding the data. :type name: str :returns: Array holding the data. :rtype: numpy.ndarray ''' ifile = os.path.join(PACKAGE_PATH, 'data', name) table = np.loadtxt(ifile) return table @decorate(np.vectorize) def calc_poisson_fu(m, cl=one_sigma): ''' Return the lower and upper frequentist uncertainties for a poisson distribution with mean "m". :param m: mean of the Poisson distribution. :type m: float or np.ndarray(float) :param cl: confidence level (between 0 and 1). :type cl: float or np.ndarray(float) :returns: Lower and upper uncertainties. :rtype: (float, float) or np.ndarray(float, float) .. note:: This function might turn very time consuming. Consider using :func:`poisson_fu` instead. ''' sm = np.sqrt(m) alpha = (1. - cl)/2. il, ir = _poisson_initials(m) if m < 1: # In this case there is only an upper uncertainty, so # the coverage is reset so it covers the whole "cl" lw = m alpha *= 2. else: def fleft(l): return 1. - \ (poisson.cdf(m, l) - poisson.pmf(m, l)) - alpha lw = fsolve(fleft, il)[0] def fright(l): return poisson.cdf(m, l) - alpha up = fsolve(fright, ir)[0] return _process_poisson_unc(m, lw, up) @decorate(np.vectorize) def calc_poisson_llu(m, cl=one_sigma): ''' Calculate poisson uncertainties based on the logarithm of likelihood. :param m: mean of the Poisson distribution. :type m: float or numpy.ndarray(float) :param cl: confidence level (between 0 and 1). :type cl: float or numpy.ndarray(float) :returns: Lower and upper uncertainties. :rtype: (float, float) or numpy.ndarray(float, float) .. note:: This function might turn very time consuming. Consider using :func:`poisson_llu` instead. ''' ns = np.sqrt(chi2_one_dof.ppf(cl)) def nll(x): return -2.*np.log(poisson.pmf(m, x)) ref = nll(m) def func(x): return nll(x) - ref - ns il, ir = _poisson_initials(m) if m < 1: lw = m else: lw = fsolve(func, il)[0] up = fsolve(func, ir)[0] return _process_poisson_unc(m, lw, up) def gauss_unc(s, cl=one_sigma): ''' Calculate the gaussian uncertainty for a given confidence level. :param s: standard deviation of the gaussian. :type s: float or numpy.ndarray(float) :param cl: confidence level. :type cl: float :returns: Gaussian uncertainty. :rtype: float or numpy.ndarray(float) .. seealso:: :func:`poisson_fu`, :func:`poisson_llu`, :func:`sw2_unc` ''' n = np.sqrt(chi2_one_dof.ppf(cl)) return n*s def poisson_fu(m): ''' Return the poisson frequentist uncertainty at one standard deviation of confidence level. :param m: measured value(s). :type m: int or numpy.ndarray(int) :returns: Lower and upper frequentist uncertainties. :rtype: numpy.ndarray(float, float) .. seealso:: :func:`gauss_unc`, :func:`poisson_llu`, :func:`sw2_unc` ''' return _poisson_unc_from_db(m, 'poisson_fu.dat') def poisson_llu(m): ''' Return the poisson uncertainty at one standard deviation of confidence level. The lower and upper uncertainties are defined by those two points with a variation of one in the value of the negative logarithm of the likelihood multiplied by two: .. math:: \\sigma_\\text{low} = n_\\text{obs} - \\lambda_\\text{low} .. math:: \\alpha - 2\\log P(n_\\text{obs}|\\lambda_\\text{low}) = 1 .. math:: \\sigma_\\text{up} = \\lambda_\\text{up} - n_\\text{obs} .. math:: \\alpha - 2\\log P(n_\\text{obs}|\\lambda_\\text{up}) = 1 where :math:`\\alpha = 2\\log P(n_\\text{obs}|n_\\text{obs})`. :param m: measured value(s). :type m: int or numpy.ndarray(int) :returns: Lower and upper frequentist uncertainties. :rtype: numpy.ndarray(float, float) .. seealso:: :func:`gauss_unc`, :func:`poisson_fu`, :func:`sw2_unc` ''' return _poisson_unc_from_db(m, 'poisson_llu.dat') @taking_ndarray def _poisson_initials(m): ''' Return the boundaries to use as initial values in scipy.optimize.fsolve when calculating poissonian uncertainties. :param m: mean of the Poisson distribution. :type m: float or numpy.ndarray(float) :returns: Upper and lower boundaries. :rtype: (float, float) or numpy.ndarray(float, float) ''' sm = np.sqrt(m) il = m - sm ir = m + sm # Needed by "calc_poisson_llu" if il.ndim == 0: if il <= 0: il = 0.1 else: il[il <= 0] = 0.1 return il, ir def _poisson_unc_from_db(m, database): ''' Used in functions to calculate poissonian uncertainties, which are partially stored on databases. If "m" is above the maximum number stored in the database, the gaussian approximation is taken instead. :param m: measured value(s). :type m: int or numpy.ndarray(int) :param database: name of the database. :type database: str :returns: Lower and upper frequentist uncertainties. :rtype: (float, float) or numpy.ndarray(float, float) :raises TypeError: if the input is a (has) non-integer value(s). :raises ValueError: if the input value(s) is(are) not positive. ''' m = np.array(m) if not np.issubdtype(m.dtype, np.integer): raise TypeError('Calling function with a non-integer value') if np.any(m < 0): raise ValueError('Values must be positive') scalar_input = False if m.ndim == 0: m = m[None] scalar_input = True no_app = (m < __poisson_to_gauss__) if np.count_nonzero(no_app) == 0: # We can use the gaussian approximation in all out = np.array(2*[np.sqrt(m)]).T else: # Non-approximated uncertainties table = _access_db(database) out = np.zeros((len(m), 2), dtype=np.float64) out[no_app] = table[m[no_app]] mk_app = np.logical_not(no_app) if mk_app.any(): # Use the gaussian approximation for the rest out[mk_app] = np.array(2*[np.sqrt(m[mk_app])]).T if scalar_input: return np.squeeze(out) return out def _process_poisson_unc(m, lw, up): ''' Calculate the uncertainties and display an error if they have been incorrectly calculated. :param m: mean value. :type m: float :param lw: lower bound. :type lw: float :param up: upper bound. :type up: float :returns: Lower and upper uncertainties. :type: numpy.ndarray(float, float) ''' s_lw = m - lw s_up = up - m if any(s < 0 for s in (s_lw, s_up)): warnings.warn('Poisson uncertainties have been ' 'incorrectly calculated') # numpy.vectorize needs to know the exact type of the output return float(s_lw), float(s_up) def sw2_unc(arr, bins=20, range=None, weights=None): ''' Calculate the errors using the sum of squares of weights. The uncertainty is calculated as follows: .. math:: \\sigma_i = \\sqrt{\\sum_{j = 0}^{n - 1} \\omega_{i,j}^2} where *i* refers to the i-th bin and :math:`j \\in [0, n)` refers to each entry in that bin with weight :math:`\\omega_{i,j}`. If "weights" is None, then this coincides with the square root of the number of entries in each bin. :param arr: input array of data to process. :param bins: see :func:`numpy.histogram`. :type bins: int, sequence of scalars or str :param range: range to process in the input array. :type range: None or tuple(float, float) :param weights: possible weights for the histogram. :type weights: None or numpy.ndarray(value-type) :returns: Symmetric uncertainty. :rtype: numpy.ndarray .. seealso:: :func:`gauss_unc`, :func:`poisson_fu`, :func:`poisson_llu` ''' if weights is not None: values = np.histogram(arr, bins, range, weights=weights*weights)[0] else: values = np.histogram(arr, bins, range)[0] return np.sqrt(values) if __name__ == '__main__': ''' Generate the tables to store the pre-calculated values of some uncertainties. ''' m = np.arange(__poisson_to_gauss__) print('Creating databases:') for func in (calc_poisson_fu, calc_poisson_llu): ucts = np.array(func(m, one_sigma)).T name = func.__name__.replace('calc_', r'') + '.dat' fpath = os.path.join('data', name) print('- {}'.format(fpath)) np.savetxt(fpath, ucts)
27.755162
103
0.636199
0
0
0
0
2,553
0.271336
0
0
5,981
0.635668
9a43ea16514e92431028e9e426f7d3c0a8b72e9b
3,088
py
Python
src/octopus/core/framework/__init__.py
smaragden/OpenRenderManagement
cf3ab356f96969d7952b60417b48e941955e435c
[ "BSD-3-Clause" ]
35
2015-02-23T23:13:13.000Z
2021-01-03T05:56:39.000Z
src/octopus/core/framework/__init__.py
smaragden/OpenRenderManagement
cf3ab356f96969d7952b60417b48e941955e435c
[ "BSD-3-Clause" ]
15
2015-01-12T12:58:29.000Z
2016-03-30T13:10:19.000Z
src/octopus/core/framework/__init__.py
mikrosimage/OpenRenderManagement
6f9237a86cb8e4b206313f9c22424c8002fd5e4d
[ "BSD-3-Clause" ]
20
2015-03-18T06:57:13.000Z
2020-07-01T15:09:36.000Z
import tornado import logging import httplib try: import simplejson as json except ImportError: import json from octopus.core.framework.wsappframework import WSAppFramework, MainLoopApplication from octopus.core.framework.webservice import MappingSet from octopus.core.communication.http import Http400 from octopus.core.tools import Workload __all__ = ['WSAppFramework', 'MainLoopApplication'] __all__ += ['Controller', 'ControllerError', 'ResourceNotFoundErro', 'BaseResource'] logger = logging.getLogger('main.dispatcher.webservice') def queue(func): def queued_func(self, *args, **kwargs): return self.queueAndWait(func, self, *args, **kwargs) return queued_func class ControllerError(Exception): """ Raised by a controller to report a problem. Subclass at will. """ class ResourceNotFoundError(ControllerError): """ Raised by a controller to report access to a missing resource. """ def __init__(self, *args, **kwargs): Exception.__init__(self, *args) for name, value in kwargs.items(): setattr(self, name, value) class Controller(object): def __init__(self, framework, root): self.framework = framework self.root = root self.mappings = MappingSet() def __call__(self, request, path, *args): return self.mappings.match(request, path, *args) def getDispatchTree(self): return self.framework.application.dispatchTree def map(self, pathPattern, methodDict): self.mappings.add((pathPattern, methodDict)) class BaseResource(tornado.web.RequestHandler): def initialize(self, framework): self.framework = framework def getDispatchTree(self): return self.framework.application.dispatchTree def get_error_html(self, status_code, exception=None, **kwargs): message = httplib.responses[status_code] if exception is not None and isinstance(exception, tornado.web.HTTPError): message = exception.log_message return "%(code)d: %(message)s" % { "code": status_code, "message": message, } @property def dispatcher(self): return self.framework.application def getBodyAsJSON(self): try: if self.request.body == "" or self.request.body is None: return "" return json.loads(self.request.body) except: raise Http400("The HTTP body is not a valid JSON object") def getServerAddress(self): server_address = self.request.host.split(':') if len(server_address) == 2: return server_address[0], server_address[1] return server_address[0], "" def queueAndWait(self, func, *args): workload = Workload(lambda: func(*args)) self.framework.application.queueWorkload(workload) return workload.wait() def writeCallback(self, chunk): data = self.request.arguments if 'callback' in data: chunk = ('%s(%s);' % (data['callback'][0], chunk)) self.write(chunk)
29.409524
85
0.663536
2,378
0.770078
0
0
77
0.024935
0
0
403
0.130505
9a4542a7758b9c15cb5e2c79c2e2a38319b81b96
127
py
Python
provstore/__init__.py
vinisalazar/provstore-api
0dd506b4f0e00623b95a52caa70debe758817179
[ "MIT" ]
5
2015-03-09T20:07:08.000Z
2018-07-26T19:59:11.000Z
provstore/__init__.py
vinisalazar/provstore-api
0dd506b4f0e00623b95a52caa70debe758817179
[ "MIT" ]
2
2016-03-16T06:13:59.000Z
2020-11-06T20:53:28.000Z
provstore/__init__.py
vinisalazar/provstore-api
0dd506b4f0e00623b95a52caa70debe758817179
[ "MIT" ]
2
2016-09-01T09:09:05.000Z
2020-11-06T22:13:58.000Z
from provstore.document import Document from provstore.bundle_manager import BundleManager from provstore.bundle import Bundle
31.75
50
0.88189
0
0
0
0
0
0
0
0
0
0
9a45c1430c4ad59b5117e98f3291087d7df4a619
834
py
Python
print-server/src/auth/Singleton.py
Multi-Agent-io/feecc-io-consolidated
9ba60176346ca9e15b22c09c2d5f1e1a5ac3ced6
[ "Apache-2.0" ]
null
null
null
print-server/src/auth/Singleton.py
Multi-Agent-io/feecc-io-consolidated
9ba60176346ca9e15b22c09c2d5f1e1a5ac3ced6
[ "Apache-2.0" ]
2
2021-11-27T09:31:12.000Z
2022-03-23T13:15:57.000Z
print-server/src/auth/Singleton.py
Multi-Agent-io/feecc-io-consolidated
9ba60176346ca9e15b22c09c2d5f1e1a5ac3ced6
[ "Apache-2.0" ]
2
2021-12-09T13:23:17.000Z
2022-03-23T13:04:41.000Z
from __future__ import annotations import typing as tp from loguru import logger class SingletonMeta(type): """ The Singleton class ensures there is always only one instance of a certain class that is globally available. This implementation is __init__ signature agnostic. """ _instances: tp.Dict[tp.Any, tp.Any] = {} def __call__(cls: SingletonMeta, *args: tp.Any, **kwargs: tp.Any) -> tp.Any: """ Possible changes to the value of the `__init__` argument do not affect the returned instance. """ if cls not in cls._instances: instance = super().__call__(*args, **kwargs) cls._instances[cls] = instance logger.info(f"Initialized a new instance of {cls.__name__} at {id(cls._instances[cls])}") return cls._instances[cls]
33.36
113
0.655875
749
0.898082
0
0
0
0
0
0
382
0.458034
9a467e6fc069bf386281b9a110e435f9e100a70b
139
py
Python
exercises/spotify/auth_data.py
introprogramming/exercises
8e52f3fa87d29a14ddcf00e8d87598d0721a41f6
[ "MIT" ]
2
2018-08-20T22:44:40.000Z
2018-09-14T17:03:35.000Z
exercises/spotify/auth_data.py
introprogramming/exercises
8e52f3fa87d29a14ddcf00e8d87598d0721a41f6
[ "MIT" ]
31
2015-08-06T16:25:57.000Z
2019-06-11T12:22:35.000Z
exercises/spotify/auth_data.py
introprogramming/exercises
8e52f3fa87d29a14ddcf00e8d87598d0721a41f6
[ "MIT" ]
1
2016-08-15T15:06:40.000Z
2016-08-15T15:06:40.000Z
# Login to https://developer.spotify.com/dashboard/, create an application and fill these out before use! client_id = "" client_secret = ""
46.333333
105
0.755396
0
0
0
0
0
0
0
0
109
0.784173
9a47729e5dc9d9a2649d73a1b1f6d29309683f2b
7,871
py
Python
augmentation.py
Harlequln/C1M18X-Behavioural_Cloning
0c49ad2432b2694848a7b83fddeea04c3306aa80
[ "MIT" ]
null
null
null
augmentation.py
Harlequln/C1M18X-Behavioural_Cloning
0c49ad2432b2694848a7b83fddeea04c3306aa80
[ "MIT" ]
null
null
null
augmentation.py
Harlequln/C1M18X-Behavioural_Cloning
0c49ad2432b2694848a7b83fddeea04c3306aa80
[ "MIT" ]
null
null
null
import cv2 import numpy as np import matplotlib.image as mpimg from pathlib import Path from model import * CAMERA_STEERING_CORRECTION = 0.2 def image_path(sample, camera="center"): """ Transform the sample path to the repository structure. Args: sample: a sample (row) of the data dataframe. Usually drawn of a batch by the generator camera: the camera to extract the path for Returns: the converted image path string """ return str(Path(f"./data/{sample[camera].split('data')[-1]}")) def crop_image(image, top=60, bot=25): """ Crop the upper and lower borders of the given image. Args: image: the image to crop top: the pixels to crop from the upper part bot: the pixels to crop from the bottom part Returns: the cropped image """ return image[top:-bot, :, :] def resize_image(image, shape=NVIDIA_SHAPE[0:2]): """ Resize the image to shape. Args: image: input image shape: (height, width) tuple, defaults to Nvidia input shape (66, 200) Returns: the resized image """ h, w = shape return cv2.resize(image, dsize=(w, h), interpolation=cv2.INTER_AREA) def rgb2yuv(rgb_image): """ Convert the RGB image to YUV space. """ return cv2.cvtColor(rgb_image, cv2.COLOR_RGB2YUV) def rgb2hsv(rgb_image): """ Convert the RGB image to HSV space. """ return cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV) def hsv2rgb(hsv_image): """ Convert the HSV image to RGB space. """ return cv2.cvtColor(hsv_image, cv2.COLOR_HSV2RGB) def choose_camera(sample, camera='random', probs=None): """ Choose an image for a specific camera and eventually adjust the steering. The steering of the left and right cameras is adjusted according to the defined constant CAMERA_STEERING_CONSTANT Args: sample: a sample (row) of the data dataframe. Usually drawn of a batch by the generator camera: 'random', 'left', 'center' or 'right'. If 'random' choose the camera with the given probabilities. probs: the probabilities to choose the left, center or right cameras. If None, the probabilities are uniform. Returns: a (image, steering) tuple """ if camera == 'random': camera = np.random.choice(["left", "center", "right"], p=probs) image = mpimg.imread(image_path(sample, camera=camera)) steering = sample["steer"] if camera == "left": steering += CAMERA_STEERING_CORRECTION elif camera == "right": steering -= CAMERA_STEERING_CORRECTION return image, steering def flip(image, steering, prob=0.5): """ Flip the image and steering with the given probability. Args: image: the image to flip steering: the steering corresponding to the image prob: the flip probability Returns: the augmented image """ if np.random.random() < prob: image = cv2.flip(image, 1) steering *= -1 return image, steering def shadow(rgb_image, prob=0.5): """ Add a shadow to the rgb image with the given probability. The shadow is created by converting the RGB image into HSV space and modifying the value channel in a random range. The area in which the value is modified is defined by a convex hull created for 6 randomly chosen points in the lower half of the image. Args: rgb_image: the image to add the shadow to. Has to be in RGB space. prob: the probability to add the shadow Returns: the augmented image """ if np.random.random() < prob: width, height = rgb_image.shape[1], rgb_image.shape[0] # Get 6 random vertices in the lower half of the image x = np.random.randint(-0.1 * width, 1.1 * width, 6) y = np.random.randint(height * 0.5, 1.1 * height, 6) vertices = np.column_stack((x, y)).astype(np.int32) vertices = cv2.convexHull(vertices).squeeze() # Intilialize mask mask = np.zeros((height, width), dtype=np.int32) # Create the polygon mask cv2.fillPoly(mask, [vertices], 1) # Adjust value hsv = rgb2hsv(rgb_image) v = hsv[:, :, 2] hsv[:, :, 2] = np.where(mask, v * np.random.uniform(0.5, 0.8), v) rgb_image = hsv2rgb(hsv) return rgb_image def brightness(rgb_image, low=0.6, high=1.4, prob=0.5): """ Modify the brighntess of the rgb image with the given probability. The brightness is modified by converting the RGB image into HSV space and adusting the value channel in a random range between the low and high bounds. Args: rgb_image: the image to modify the brightness. Has to be in RGB space. low: lower value bound high: upper value bound prob: the probability to modify the brightness Returns: the augmented image """ if np.random.random() < prob: hsv = rgb2hsv(rgb_image) value = hsv[:, :, 2] hsv[:, :, 2] = np.clip(value * np.random.uniform(low, high), 0, 255) rgb_image = hsv2rgb(hsv) return rgb_image def shift(image, steering, shiftx=60, shifty=20, prob=0.5): """ Shift the image and adjust the steering with the given probability. The steering of the shifted image is adjusted depending on the amount of pixels shifted in the width direction. Args: image: the image to shift. steering: the corresponding steering. shiftx: the upper bound of pixels to shift in the width direction shifty: the upper bound of pixels to shift in the height direction prob: the probability to shift the image Returns: the augmented image """ if np.random.random() < prob: # The angle correction per pixel is derived from the angle correction # specified for the side cameras. It is estimated that the images of two # adjacent cameras are shifted by 80 pixels (at the bottom of the image) angle_correction_per_pixel = CAMERA_STEERING_CORRECTION / 80 # Draw translations in x and y directions from a uniform distribution tx = int(np.random.uniform(-shiftx, shiftx)) ty = int(np.random.uniform(-shifty, shifty)) # Transformation matrix mat = np.float32([[1, 0, tx], [0, 1, ty]]) # Transform image and correct steering angle height, width, _ = image.shape image = cv2.warpAffine(image, mat, (width, height), borderMode=cv2.BORDER_REPLICATE) steering += tx * angle_correction_per_pixel return image, steering def augment(sample, camera_probs=None, flip_prob=0.5, shadow_prob=0.5, bright_prob=0.5, shift_prob=0.5, ): """ Augment the sample with the given probabilities. Args: sample: a sample (row) of the data dataframe. Usually drawn of a batch by the generator camera_probs: the probabilities to draw left, center or right camera images flip_prob: probability for an image to be flipped shadow_prob: probability of shadow additon to the image bright_prob: probability to modify the brightness of the image shift_prob: probability for and image to be shifed """ image, steering = choose_camera(sample, probs=camera_probs) image, steering = flip(image, steering, prob=flip_prob) image = shadow(image, prob=shadow_prob) image = brightness(image, prob=bright_prob) image, steering = shift(image, steering, prob=shift_prob) return image, steering
35.138393
81
0.632575
0
0
0
0
0
0
0
0
4,465
0.567272
9a483acc0e1727f56a550dc2b790cfba50c01c45
4,848
py
Python
test_zeroshot.py
airbert-vln/airbert
a4f667db9fb4021094c738dd8d23739aee3785a5
[ "MIT" ]
17
2021-07-30T14:08:24.000Z
2022-03-30T13:57:02.000Z
test_zeroshot.py
airbert-vln/airbert
a4f667db9fb4021094c738dd8d23739aee3785a5
[ "MIT" ]
4
2021-09-09T03:02:18.000Z
2022-03-24T13:55:55.000Z
test_zeroshot.py
airbert-vln/airbert
a4f667db9fb4021094c738dd8d23739aee3785a5
[ "MIT" ]
2
2021-08-30T11:51:16.000Z
2021-09-03T09:18:50.000Z
import json import logging from typing import List import os import sys import numpy as np import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer, BertTokenizer from vilbert.vilbert import BertConfig from utils.cli import get_parser from utils.dataset.common import pad_packed, load_json_data from utils.dataset.zero_shot_dataset import ZeroShotDataset from utils.dataset import PanoFeaturesReader from airbert import Airbert from train import get_model_input, get_mask_options logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, stream=sys.stdout, ) logger = logging.getLogger(__name__) def main(): # ----- # # setup # # ----- # # command line parsing parser = get_parser(training=False) parser.add_argument( "--split", choices=["train", "val_seen", "val_unseen", "test"], required=True, help="Dataset split for evaluation", ) args = parser.parse_args() # force arguments args.num_beams = 1 args.batch_size = 1 print(args) # create output directory save_folder = os.path.join(args.output_dir, f"run-{args.save_name}") if not os.path.exists(save_folder): os.makedirs(save_folder) # ------------ # # data loaders # # ------------ # # load a dataset # tokenizer = BertTokenizer.from_pretrained(args.bert_tokenizer, do_lower_case=True) tokenizer = AutoTokenizer.from_pretrained(args.bert_tokenizer) if not isinstance(tokenizer, BertTokenizer): raise ValueError("fix mypy") features_reader = PanoFeaturesReader(args.img_feature, args.in_memory) vln_data = f"data/task/{args.prefix}R2R_{args.split}.json" print(vln_data) dataset = ZeroShotDataset( vln_path=vln_data, tokenizer=tokenizer, features_reader=features_reader, max_instruction_length=args.max_instruction_length, max_path_length=args.max_path_length, max_num_boxes=args.max_num_boxes, default_gpu=True, highlighted_language=args.highlighted_language, ) data_loader = DataLoader( dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=True, ) # ----- # # model # # ----- # config = BertConfig.from_json_file(args.config_file) config.cat_highlight = args.cat_highlight model = Airbert.from_pretrained(args.from_pretrained, config, default_gpu=True) model.cuda() logger.info(f"number of parameters: {sum(p.numel() for p in model.parameters()):,}") # ---------- # # evaluation # # ---------- # with torch.no_grad(): all_scores = eval_epoch(model, data_loader, args) # save scores scores_path = os.path.join(save_folder, f"{args.prefix}_scores_{args.split}.json") json.dump(all_scores, open(scores_path, "w")) logger.info(f"saving scores: {scores_path}") # convert scores into results format vln_data = load_json_data(vln_data) instr_id_to_beams = { f"{item['path_id']}_{i}": item["beams"] for item in vln_data for i in range(len(item["instructions"])) } all_results = convert_scores(all_scores, instr_id_to_beams) # save results results_path = os.path.join(save_folder, f"{args.prefix}_results_{args.split}.json") json.dump(all_results, open(results_path, "w")) logger.info(f"saving results: {results_path}") def eval_epoch(model, data_loader, args): device = next(model.parameters()).device model.eval() all_scores = [] for batch in tqdm(data_loader): # load batch on gpu batch = tuple(t.cuda(device=device, non_blocking=True) for t in batch) instr_ids = get_instr_ids(batch) # get the model output output = model(*get_model_input(batch)) opt_mask = get_mask_options(batch) vil_logit = pad_packed(output[0].squeeze(1), opt_mask) for instr_id, logit in zip(instr_ids, vil_logit): all_scores.append((instr_id, logit.tolist())) return all_scores def convert_scores(all_scores, instr_id_to_beams): output = [] for instr_id, scores in all_scores: idx = np.argmax(scores) beams = instr_id_to_beams[instr_id] trajectory = [] trajectory += [beams[idx], 0, 0] output.append({"instr_id": instr_id, "trajectory": trajectory}) # assert len(output) == len(beam_data) return output # ------------- # # batch parsing # # ------------- # def get_instr_ids(batch) -> List[str]: instr_ids = batch[12] return [str(item[0].item()) + "_" + str(item[1].item()) for item in instr_ids] if __name__ == "__main__": main()
27.545455
88
0.65821
0
0
0
0
0
0
0
0
1,034
0.213284
9a49459be97466ed19cf1a661276df8eb41c082e
3,184
py
Python
refp.py
jon2718/ipycool_2.0
34cf74ee99f4a725b997c50a7742ba788ac2dacd
[ "MIT" ]
null
null
null
refp.py
jon2718/ipycool_2.0
34cf74ee99f4a725b997c50a7742ba788ac2dacd
[ "MIT" ]
null
null
null
refp.py
jon2718/ipycool_2.0
34cf74ee99f4a725b997c50a7742ba788ac2dacd
[ "MIT" ]
null
null
null
from modeledcommandparameter import * from pseudoregion import * class Refp(ModeledCommandParameter, PseudoRegion): """ Reference particle """ begtag = 'REFP' endtag = '' models = { 'model_descriptor': {'desc': 'Phase model', 'name': 'phmodref', 'num_parms': 5, 'for001_format': {'line_splits': [5]}}, '0_crossing': {'desc': '0-crossing phase iterative procedure', 'doc': 'Uses iterative procedure to find 0-crossing phase; tracks through all regions. Only works with ACCEL modesl 1,2 and 13.', 'icool_model_name': 2, 'parms': {'phmodref': {'pos': 5, 'type': 'String', 'doc': ''}, 'bmtype': {'pos': 1, 'type': 'Int', 'doc': ''}}}, 'const_v': {'desc': 'Assumes constant reference particle velocity', 'doc': 'Applies to any region', 'icool_model_name': 3, 'parms': {'phmodref': {'pos': 5, 'type': 'String', 'doc': ''}, 'bmtype': {'pos': 1, 'type': 'Int', 'doc': ''}, 'pz0': {'pos': 2, 'type': 'Real', 'doc': ''}, 't0': {'pos': 3, 'type': 'Real', 'doc': ''}}}, 'en_loss': {'desc': 'Assumes constant reference particle velocity', 'doc': 'Applies to any region', 'icool_model_name': 4, 'parms': {'phmodref': {'pos': 5, 'type': 'String', 'doc': ''}, 'bmtype': {'pos': 1, 'type': 'Int', 'doc': ''}, 'pz0': {'pos': 2, 'type': 'Real', 'doc': ''}, 't0': {'pos': 3, 'type': 'Real', 'doc': ''}, 'dedz': {'pos': 4, 'type': 'Real', 'doc': ''}}}, 'delta_quad_cav': {'desc': 'Assumes constant reference particle velocity', 'doc': 'Applies to any region', 'icool_model_name': 5, 'parms': {'phmodref': {'pos': 5, 'type': 'String', 'doc': ''}, 'bmtype': {'pos': 1, 'type': 'Int', 'doc': ''}, 'e0': {'pos': 2, 'type': 'Real', 'doc': ''}, 'dedz': {'pos': 3, 'type': 'Real', 'doc': ''}, 'd2edz2': {'pos': 4, 'type': 'Real', 'doc': ''}}}, 'delta_quad_any': {'desc': 'Assumes constant reference particle velocity', 'doc': 'Applies to any region', 'icool_model_name': 6, 'parms': {'phmodref': {'pos': 5, 'type': 'String', 'doc': ''}, 'bmtype': {'pos': 1, 'type': 'Int', 'doc': ''}, 'e0': {'pos': 2, 'type': 'Real', 'doc': ''}, 'dedz': {'pos': 3, 'type': 'Real', 'doc': ''}, 'd2edz2': {'pos': 4, 'type': 'Real', 'doc': ''}}}, } def __init__(self, **kwargs): if ModeledCommandParameter.check_command_params_init(self, Refp.models, **kwargs) is False: sys.exit(0) def __call__(self, **kwargs): pass def __setattr__(self, name, value): self.__modeled_command_parameter_setattr__(name, value, Refp.models) def __str__(self): pass
38.829268
139
0.451005
3,117
0.978957
0
0
0
0
0
0
1,471
0.461997
9a4a243b2c4f9a84354c254f16486d8c603e8178
10,620
py
Python
utils/dataloaders.py
sinahmr/parted-vae
261f0654de605c6a260784e47e9a17a737a1a985
[ "MIT" ]
5
2021-06-26T07:45:50.000Z
2022-03-31T11:41:29.000Z
utils/dataloaders.py
sinahmr/parted-vae
261f0654de605c6a260784e47e9a17a737a1a985
[ "MIT" ]
null
null
null
utils/dataloaders.py
sinahmr/parted-vae
261f0654de605c6a260784e47e9a17a737a1a985
[ "MIT" ]
1
2021-11-26T09:14:03.000Z
2021-11-26T09:14:03.000Z
import numpy as np import torch from torch.nn import functional as F from torch.utils.data import Dataset, DataLoader from torchvision import datasets, transforms from torchvision.utils import save_image from utils.fast_tensor_dataloader import FastTensorDataLoader def get_mnist_dataloaders(batch_size=128, path_to_data='../data', warm_up=True, device=None): data_transforms = transforms.Compose([ transforms.Resize(32), transforms.ToTensor() ]) target_transform = lambda x: F.one_hot(torch.tensor(x), num_classes=10) train_data = datasets.MNIST(path_to_data, train=True, download=True, transform=data_transforms, target_transform=target_transform) test_data = datasets.MNIST(path_to_data, train=False, transform=data_transforms, target_transform=target_transform) train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True) test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=True) warm_up_loader = None if warm_up: warm_up_x, warm_up_y = WarmUpMNISTDataset(path_to_data, count=256, transform=data_transforms, target_transform=target_transform, device=device).get_tensors() warm_up_loader = FastTensorDataLoader(warm_up_x, warm_up_y, batch_size=batch_size, shuffle=True) return train_loader, test_loader, warm_up_loader class WarmUpMNISTDataset(datasets.MNIST): def __init__(self, root, transform=None, target_transform=None, download=False, count=256, device=None): self.__class__.__name__ = 'MNIST' # This is used in directory structure of datasets.MNIST super(WarmUpMNISTDataset, self).__init__(root, train=True, transform=transform, target_transform=target_transform, download=download) self.device = device self.count = count self.delete = set() self.mapping = list(set(range(count + len(self.delete))) - self.delete) self.save_all_images() def __len__(self): return self.count def __getitem__(self, index): translated_index = self.mapping[index] return super().__getitem__(translated_index) def get_tensors(self): x_shape, y_shape = self[0][0].shape, self[0][1].shape x, y = torch.zeros(self.count, *x_shape, device=self.device), torch.zeros(self.count, *y_shape, device=self.device) for i, (data, label) in enumerate(self): x[i], y[i] = data.to(self.device), label.to(self.device) return x, y def save_all_images(self): x_shape = self[0][0].shape all_images = torch.zeros(self.count, *x_shape) for i, (data, label) in enumerate(self): all_images[i] = data save_image(all_images, 'warm_up.png', nrow=(len(self) // 16)) def get_celeba_dataloader(batch_size=128, path_to_data='../celeba_64', device=None, warm_up=True): data_transforms = transforms.Compose([ # transforms.Resize(64), # transforms.CenterCrop(64), transforms.ToTensor(), # transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) dataset_kwargs = { 'target_type': 'attr', 'transform': data_transforms, } train_data = datasets.CelebA(path_to_data, split='train', download=True, **dataset_kwargs) test_data = datasets.CelebA(path_to_data, split='test', **dataset_kwargs) # warm_up_data = WarmUpCelebADataset(path_to_data, split='train', target_transform=target_transforms, **dataset_kwargs) dataloader_kwargs = { 'batch_size': batch_size, 'shuffle': True, 'pin_memory': device.type != 'cpu', # 'pin_memory': False, 'num_workers': 0 if device.type == 'cpu' else 4, } train_loader = DataLoader(train_data, **dataloader_kwargs) test_loader = DataLoader(test_data, **dataloader_kwargs) # warm_up_loader = DataLoader(warm_up_data, **dataloader_kwargs) warm_up_loader = None if warm_up: # target_transforms = transforms.Compose([ # lambda x: x[celeba_good_columns], # # lambda x: torch.flatten(F.one_hot(x, num_classes=2)) # my_celeba_target_transfrom # ]) warm_up_x, warm_up_y = WarmUpCelebADataset(path_to_data, count=800, device=device, **dataset_kwargs).get_tensors() # TODO: If it is good, make the class simpler warm_up_loader = FastTensorDataLoader(warm_up_x, warm_up_y, batch_size=batch_size, shuffle=True) return train_loader, test_loader, warm_up_loader class WarmUpCelebADataset(datasets.CelebA): def __init__(self, root, split="train", target_type="attr", transform=None, target_transform=None, download=False, count=256, device=None): super().__init__(root, split, target_type, transform, target_transform, download) self.count = count self.device = device # self.delete = {2, 36, 43, 66, 74, 96, 119, 148, 149, 162, 166, 168, 183, 188, 198} # From 0 to 255+15 # self.delete = {43, 74, 162, 183} # From 0 to 299 self.delete = set() self.mapping = list(set(range(count + len(self.delete))) - self.delete) self.labels = torch.tensor(np.genfromtxt('warm_up_labels.csv', delimiter=','), dtype=torch.float) # self.save_all_images() def __len__(self): return self.count def __getitem__(self, index): # return super().__getitem__(index) translated_index = self.mapping[index] x, _ = super().__getitem__(translated_index) return x, self.labels[translated_index] def get_tensors(self): x_shape, y_shape = self[0][0].shape, self[0][1].shape x, y = torch.zeros(self.count, *x_shape, device=self.device), torch.zeros(self.count, *y_shape, device=self.device) for i, (data, label) in enumerate(self): x[i], y[i] = data.to(self.device), label.to(self.device) return x, y def save_all_images(self): x_shape = self[0][0].shape all_images = torch.zeros(self.count, *x_shape) for i, (data, label) in enumerate(self): all_images[i] = data save_image(all_images, 'warm_up.png', nrow=(len(self) // 16)) def get_dsprites_dataloader(batch_size=128, path_to_data='../dsprites/ndarray.npz', fraction=1., device=None, warm_up=False): dsprites_data = DSpritesDataset(path_to_data, fraction=fraction, device=device) # dsprites_loader = FastTensorDataLoader(*dsprites_data.get_tensors(), batch_size=batch_size, shuffle=True) # Comment if you have memory limits, and uncomment the next line dataloader_kwargs = { 'batch_size': batch_size, 'shuffle': True, 'pin_memory': device.type != 'cpu', 'num_workers': 0 if device.type == 'cpu' else 4, } dsprites_loader = DataLoader(dsprites_data, **dataloader_kwargs) warm_up_loader = None if warm_up: warm_up_data = DSpritesWarmUpDataset(path_to_data, device=device) warm_up_loader = FastTensorDataLoader(*warm_up_data.get_tensors(), batch_size=batch_size, shuffle=True) return dsprites_loader, warm_up_loader class DSpritesWarmUpDataset(Dataset): # Color[1], Shape[3], Scale, Orientation, PosX, PosY def __init__(self, path_to_data, size=10000, device=None): # was 100, 737, 1000, 3686, 10000 self.device = device data = np.load(path_to_data) indices = self.good_indices(size) self.imgs = np.expand_dims(data['imgs'][indices], axis=1) shape_value = data['latents_classes'][indices, 1] self.classes = np.zeros((size, 3)) self.classes[np.arange(size), shape_value] = 1 print(np.mean(self.classes, axis=0)) def good_indices(self, size): # if size < 3 * 6 * 2 * 2 * 2: # raise Exception('Too small!') indices = np.zeros(size, dtype=np.long) # [1, 3, 6, 40, 32, 32] module = np.array([737280, 245760, 40960, 1024, 32, 1]) i = 0 while True: for y_span in range(2): for x_span in range(2): for orientation_span in range(2): for scale in range(6): for shape in range(3): orientation = int(np.random.randint(0, 20, 1) + orientation_span * 20) x = int(np.random.randint(0, 16, 1) + x_span * 16) y = int(np.random.randint(0, 16, 1) + y_span * 16) sample = np.array([0, shape, scale, orientation, x, y]) indices[i] = np.sum(sample * module) i += 1 if i >= size: return indices def __len__(self): return len(self.imgs) def __getitem__(self, idx): return self.imgs[idx], self.classes[idx] def get_tensors(self): return torch.tensor(self.imgs, dtype=torch.float, device=self.device), torch.tensor(self.classes, device=self.device) class DSpritesDataset(Dataset): # Color[1], Shape[3], Scale, Orientation, PosX, PosY def __init__(self, path_to_data, fraction=1., device=None): self.device = device data = np.load(path_to_data) self.imgs = data['imgs'] self.imgs = np.expand_dims(self.imgs, axis=1) self.classes = data['latents_classes'] if fraction < 1: indices = np.random.choice(737280, size=int(fraction * 737280), replace=False) self.imgs = self.imgs[indices] self.classes = self.classes[indices] # self.attrs = data['latents_values'][indices] # self.transform = transform def __len__(self): return len(self.imgs) def __getitem__(self, idx): # # Each image in the dataset has binary values so multiply by 255 to get # # pixel values # sample = self.imgs[idx] * 255 # # Add extra dimension to turn shape into (H, W) -> (H, W, C) # sample = sample.reshape(sample.shape + (1,)) # if self.transform: # sample = self.transform(sample) # Since there are no labels, we just return 0 for the "label" here # return sample, (self.classes[idx], self.attrs[idx]) # return torch.tensor(self.imgs[idx], dtype=torch.float, device=self.device), torch.tensor(self.classes[idx], device=self.device) return torch.tensor(self.imgs[idx], dtype=torch.float), torch.tensor(self.classes[idx]) def get_tensors(self): return torch.tensor(self.imgs, dtype=torch.float, device=self.device), torch.tensor(self.classes, device=self.device)
44.06639
177
0.645104
6,632
0.624482
0
0
0
0
0
0
2,127
0.200282
9a4a26f9a634d7ab72a8a79970898804d2a1b1c4
1,780
py
Python
posts.py
girish97115/anonymail
f2eb741464ce7b780e4de6de6043c6eed1e13b9a
[ "MIT" ]
null
null
null
posts.py
girish97115/anonymail
f2eb741464ce7b780e4de6de6043c6eed1e13b9a
[ "MIT" ]
null
null
null
posts.py
girish97115/anonymail
f2eb741464ce7b780e4de6de6043c6eed1e13b9a
[ "MIT" ]
null
null
null
from flask import ( Blueprint,session, flash, g, redirect, render_template, request, url_for ) from werkzeug.exceptions import abort from anonymail.auth import login_required from anonymail.db import get_db import datetime now = datetime.datetime.now() current_year = now.year bp = Blueprint('posts', __name__) @bp.route('/') @login_required def index(): user_id = session.get('user_id') db = get_db() posts = db.execute( 'SELECT p.id, body, created' ' FROM post p JOIN user u ON p.dest = u.id' ' WHERE u.id = {}' ' ORDER BY created DESC'.format(user_id) ).fetchall() return render_template('posts/index.html', posts=posts, year=current_year) @bp.route('/<string:username>/send', methods=('GET', 'POST')) def create(username): db = get_db() if request.method == 'POST': body = request.form['body'] dest=db.execute( 'SELECT id from user where username= ?',(username,) ).fetchone()['id'] error = None if(dest is None): error='User doesn\'t exist' if error is not None: flash(error) else: db = get_db() db.execute( 'INSERT INTO post (body, dest)' ' VALUES (?, ?)', (body, dest) ) db.commit() return render_template('posts/sent.html',user=username) if(request.method=='GET'): dest = db.execute( 'SELECT id from user where username= ?', (username,) ).fetchone() if dest is None: abort(404) else: return render_template('posts/create.html',user=username) @bp.route('/sendsomeone') def send(): return render_template('send_a_message.html')
28.253968
78
0.580337
0
0
0
0
1,458
0.819101
0
0
424
0.238202
9a4a94c02a87e8e977bec5709e692ef62684b7c3
959
py
Python
app.py
pic-metric/data-science
89bf6e3733a3595220c945269b66befcaf82a3be
[ "MIT" ]
null
null
null
app.py
pic-metric/data-science
89bf6e3733a3595220c945269b66befcaf82a3be
[ "MIT" ]
null
null
null
app.py
pic-metric/data-science
89bf6e3733a3595220c945269b66befcaf82a3be
[ "MIT" ]
3
2020-01-31T22:34:00.000Z
2020-03-06T01:56:06.000Z
# from python-decouple import config from flask import Flask, request, jsonify from .obj_detector import object_detection # from flask_sqlalchemy import SQLAlchemy from dotenv import load_dotenv load_dotenv() def create_app(): app = Flask(__name__) @app.route('/img_summary', methods=['GET']) def predictor(): ''' route receives an image/image id, returns processed image and a dict of attributes ''' if request.method == 'GET': return 'this works' # # @app.rout('/batch_summary', method=['POST']) # def predict_batch(): # # we need to have a separate endpoint for batch uploads so that # # we can work with as set of pictures, and return a set of pictures # # with a combined summary. # for image in batch: # pass return app if __name__ == "__main__": app.run(debug=True, port=8080)
28.205882
78
0.607925
0
0
0
0
262
0.273201
0
0
532
0.554745
9a4bcff10fc3fa7d7e56bb3812a166c957678a62
2,579
py
Python
src/subroutines/array_subroutine.py
cyrilico/aoco-code-correction
3a780df31eea6caaa37213f6347fb71565ce11e8
[ "MIT" ]
4
2020-08-30T08:56:57.000Z
2020-08-31T21:32:03.000Z
src/subroutines/array_subroutine.py
cyrilico/aoco-code-correction
3a780df31eea6caaa37213f6347fb71565ce11e8
[ "MIT" ]
null
null
null
src/subroutines/array_subroutine.py
cyrilico/aoco-code-correction
3a780df31eea6caaa37213f6347fb71565ce11e8
[ "MIT" ]
1
2020-10-01T22:15:33.000Z
2020-10-01T22:15:33.000Z
from .subroutine import subroutine from parameters.string_parameter import string_parameter as String from parameters.numeric_parameter import numeric_parameter as Numeric from parameters.array_parameter import array_parameter as Array from ast import literal_eval class array_subroutine(subroutine): """Subroutine that returns one or more arrays""" def __init__(self, name, parameters, outputs): super().__init__(name, parameters) self.outputs = outputs def get_nr_outputs(self): return len(self.outputs) def build_test_call(self): return '{} {} {} printf("\\n");'.format(\ #Declare output variables beforehand, so we have access to them after subroutine call ''.join([parameter.get_test_declaration_representation() for parameter in self.parameters]),\ #Actually make subroutine call '{}({});'.format(self.name, ','.join([parameter.get_test_call_representation() for parameter in self.parameters])),\ #Access previously declared variables to print their final values 'printf("\\n");'.join(filter(lambda x: x != '', [parameter.get_test_call_output_representation() for parameter in self.parameters]))) def process_parameters(self, parameters): for idx, parameter in enumerate(parameters): if parameter == 'string': self.parameters.append(String(idx, True if idx >= (len(parameters) - len(self.outputs)) else False)) elif 'array' in parameter: self.parameters.append(Array(idx, parameter.replace('array','').strip(), True if idx >= (len(parameters) - len(self.outputs)) else False)) else: #numeric self.parameters.append(Numeric(idx, parameter)) def compare_outputs(self, expected, real, precision): if(len(expected) != len(real)): return False for out_type, exp, re in zip(self.outputs, expected, real): if out_type == 'string' and exp != real: return False else: #Array arr_type = out_type.replace('array','').strip() re_arr = literal_eval(re) if(len(exp) != len(re_arr)): return False for exp_el, re_el in zip(exp, re_arr): if arr_type == 'int' and exp_el != re_el: return False elif abs(exp_el-re_el) > precision: return False return True
47.759259
154
0.606437
2,311
0.896084
0
0
0
0
0
0
345
0.133773
9a4cab617527bcae29b76af4b2c39e67572e4127
1,164
py
Python
auth.py
nivw/onna_test
518c726a656493a5efd7ed6f548f68b2f5350260
[ "BSD-2-Clause" ]
null
null
null
auth.py
nivw/onna_test
518c726a656493a5efd7ed6f548f68b2f5350260
[ "BSD-2-Clause" ]
null
null
null
auth.py
nivw/onna_test
518c726a656493a5efd7ed6f548f68b2f5350260
[ "BSD-2-Clause" ]
1
2020-06-24T16:52:59.000Z
2020-06-24T16:52:59.000Z
import requests import json from config import config from logbook import Logger, StreamHandler import sys StreamHandler(sys.stdout).push_application() log = Logger('auth') class Auth(object): def __init__(self): self.config = config self.auth_code = self.token =None def get_auth_code(self): if self.auth_code is not None: return self.auth_code response = requests.get(self.config.oauth_url, headers=self.config.headers) self.auth_code = response.json()['auth_code'] log.info(f"Using auth_code: {self.auth_code}") return self.auth_code def get_token(self): if self.token is not None: return self.token data = self.config.auth.login_data_request data.update({"code": self.get_auth_code()}) response = requests.post(config.auth.auth_url, data=json.dumps(data), headers=config.headers) self.token = response.content.decode("utf-8") return self.token def get_login_token(self): return {'authorization': ' '.join(('Bearer', self.get_token()))}
31.459459
83
0.629725
987
0.847938
0
0
0
0
0
0
92
0.079038
9a4d61b4c436761ff6069be2e39ac836e18b0130
1,540
py
Python
tests/regressions/python/942_lazy_fmap.py
NanmiaoWu/phylanx
295b5f82cc39925a0d53e77ba3b6d02a65204535
[ "BSL-1.0" ]
83
2017-08-27T15:09:13.000Z
2022-01-18T17:03:41.000Z
tests/regressions/python/942_lazy_fmap.py
NanmiaoWu/phylanx
295b5f82cc39925a0d53e77ba3b6d02a65204535
[ "BSL-1.0" ]
808
2017-08-27T15:35:01.000Z
2021-12-14T17:30:50.000Z
tests/regressions/python/942_lazy_fmap.py
NanmiaoWu/phylanx
295b5f82cc39925a0d53e77ba3b6d02a65204535
[ "BSL-1.0" ]
55
2017-08-27T15:09:22.000Z
2022-03-25T12:07:34.000Z
# Copyright (c) 2019 Bita Hasheminezhad # # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # #942: `fold_left`, `fold_right` and `fmap` do not work with a lazy function import numpy as np from phylanx import Phylanx, PhylanxSession, execution_tree PhylanxSession.init(1) def variable(value, dtype=None, name=None, constraint=None): if dtype is None: dtype = "float32" if constraint is not None: raise TypeError("Constraint is the projection function to be " "applied to the variable after an optimizer update") if isinstance(value, execution_tree.variable): if dtype is not None: value.dtype = dtype if name is not None: value.name = name return value return execution_tree.variable(value, dtype=dtype, name=name) def eval(func): return func.eval() def fmap(fn, elems): pass # make flake happy @Phylanx def map_fn_eager(fn, elems, dtype=None): return fmap(fn, elems) def map_fn(fn, elems, dtype=None): return map_fn_eager.lazy(fn, elems, dtype) @Phylanx def sum_eager(x, axis=None, keepdims=False): return np.sum(x, axis, keepdims) sum = Phylanx.lazy(sum_eager) def test_map(x): return eval(map_fn(sum, variable(x))) result = test_map(np.array([[1, 2, 3]])) assert(np.all(result == [6])), result result = test_map(np.array([1, 2, 3])) assert(np.all(result == [1, 2, 3])), result
24.0625
79
0.670779
0
0
0
0
166
0.107792
0
0
393
0.255195
9a4f44e640692a4adea1bc6d6ea01c4fe9188da3
644
py
Python
main.py
DanTheBow/Fibonacci
6b2b694174041c59c1cc151f775772056d88749b
[ "Unlicense" ]
1
2022-01-02T19:50:55.000Z
2022-01-02T19:50:55.000Z
main.py
DanTheBow/Fibonacci
6b2b694174041c59c1cc151f775772056d88749b
[ "Unlicense" ]
null
null
null
main.py
DanTheBow/Fibonacci
6b2b694174041c59c1cc151f775772056d88749b
[ "Unlicense" ]
null
null
null
# Die Fibonacci-Folge ist die unendliche Folge natürlicher Zahlen, die (ursprünglich) mit zweimal der Zahl 1 beginnt # oder (häufig, in moderner Schreibweise) zusätzlich mit einer führenden Zahl 0 versehen ist. # Im Anschluss ergibt jeweils die Summe zweier aufeinanderfolgender Zahlen die unmittelbar danach folgende Zahl: # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 -> Hier fangen wir mit der 0 an zu zählen. # 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 -> Hier fangen wir mit der 1 an zu zählen. def fib(n): if n < 2: return n return fib(n-2) + fib(n-1) # Hier ruft sich die Funktion selbst auf (Rekursion), bis die Bedingung erfüllt ist.
58.545455
116
0.706522
0
0
0
0
0
0
0
0
570
0.874233
9a51a2dfb9ee0eb5c3e19b169561bb01b5b7ae90
4,063
py
Python
application/api/generate_label.py
Florian-Barthel/stylegan2
4ef87038bf9370596cf2b729e1d1a1bc3ebcddd8
[ "BSD-Source-Code" ]
null
null
null
application/api/generate_label.py
Florian-Barthel/stylegan2
4ef87038bf9370596cf2b729e1d1a1bc3ebcddd8
[ "BSD-Source-Code" ]
null
null
null
application/api/generate_label.py
Florian-Barthel/stylegan2
4ef87038bf9370596cf2b729e1d1a1bc3ebcddd8
[ "BSD-Source-Code" ]
null
null
null
import numpy as np import dnnlib.tflib as tflib from training import dataset tflib.init_tf() class LabelGenerator: def __init__(self, tfrecord_dir: str = None): if tfrecord_dir: self.training_set = dataset.TFRecordDataset(tfrecord_dir, shuffle_mb=0) self.labels_available = True else: self.labels_available = False self.label_names = [ 'Model', 'Color', 'Manufacturer', 'Body', 'Rotation', 'Ratio', 'Background' ] def payload_to_label_vector_rotation( self, payload: dict, label_version: str, num_interpolation_steps: int, interpolation_type: str ) -> np.ndarray: if label_version in ['v6', 'v7']: if interpolation_type == 'spherical': total_steps = num_interpolation_steps * 8 label = np.zeros((total_steps, 1, 121), dtype=np.float32) for i in range(total_steps): payload['Rotation'] = i * 360 / (total_steps - 1) label[i] = self.payload_to_label_vector(payload, label_version) return label else: label = np.zeros((8, 1, 121), dtype=np.float32) for i in range(8): payload['Rotation'] = i * 45 label[i] = self.payload_to_label_vector(payload, label_version) return label label = np.zeros((8, 1, 127), dtype=np.float32) if label_version in ['v4']: rotation_order = [0, 1, 3, 6, 5, 7, 4, 2] else: rotation_order = [0, 1, 2, 3, 4, 5, 6, 7] for i in range(8): payload['Rotation'] = rotation_order[i] label[i] = self.payload_to_label_vector(payload, label_version) return label def payload_to_label_vector( self, payload: dict, label_version: str ) -> np.ndarray: if label_version in ['v4']: rotation_order = [0, 1, 3, 6, 5, 7, 4, 2] else: rotation_order = [0, 1, 2, 3, 4, 5, 6, 7] if label_version in ['v6', 'v7']: offsets = [1, 67, 12, 18, 10, 2, 5, 6] else: offsets = [1, 67, 12, 18, 10, 8, 5, 6] onehot = np.zeros((1, sum(offsets)), dtype=np.float32) onehot[0, 0] = 1 offset = 0 for i, label_name in enumerate(self.label_names): current_label = int(payload[label_name]) offset += offsets[i] if label_name is 'Rotation': if label_version in ['v6', 'v7']: rotation = (current_label / 360) * 2 * np.pi onehot[0, offset] = np.cos(rotation) onehot[0, offset + 1] = np.sin(rotation) else: onehot[0, offset + rotation_order[current_label]] = 1 elif current_label >= 0: onehot[0, offset + current_label] = 1 return onehot def get_real_label_dict(self, version: str) -> dict: if not self.labels_available: label_dict = {} for i in range(len(self.label_names)): label_dict[self.label_names[i]] = -1 return label_dict label = self.training_set.get_random_labels_np(1) label = label[0] if version in ['v6', 'v7']: offsets = [67, 12, 18, 10, 2, 5, 6] else: offsets = [67, 12, 18, 10, 8, 5, 6] offset = 1 label_dict = {} for i in range(len(self.label_names)): if np.max(label[offset:offset + offsets[i]]) < 1: label_dict[self.label_names[i]] = -1 else: label_dict[self.label_names[i]] = int(np.argmax(label[offset:offset + offsets[i]])) offset += offsets[i] return label_dict
35.330435
99
0.502092
3,965
0.97588
0
0
0
0
0
0
154
0.037903
9a51f5406e8b8b4afa3d8bc309049e92a8011b92
3,333
py
Python
tests/test_urls.py
LaudateCorpus1/apostello
1ace89d0d9e1f7a1760f6247d90a60a9787a4f12
[ "MIT" ]
69
2015-10-03T20:27:53.000Z
2021-04-06T05:26:18.000Z
tests/test_urls.py
LaudateCorpus1/apostello
1ace89d0d9e1f7a1760f6247d90a60a9787a4f12
[ "MIT" ]
73
2015-10-03T17:53:47.000Z
2020-10-01T03:08:01.000Z
tests/test_urls.py
LaudateCorpus1/apostello
1ace89d0d9e1f7a1760f6247d90a60a9787a4f12
[ "MIT" ]
29
2015-10-23T22:00:13.000Z
2021-11-30T04:48:06.000Z
from collections import namedtuple import pytest from rest_framework.authtoken.models import Token from tests.conftest import twilio_vcr from apostello import models StatusCode = namedtuple("StatusCode", "anon, user, staff") @pytest.mark.slow @pytest.mark.parametrize( "url,status_code", [ ("/", StatusCode(302, 200, 200)), ("/api/v2/config/", StatusCode(403, 403, 200)), ("/api/v2/elvanto/groups/", StatusCode(403, 403, 200)), ("/api/v2/groups/", StatusCode(403, 200, 200)), ("/api/v2/keywords/", StatusCode(403, 200, 200)), ("/api/v2/queued/sms/", StatusCode(403, 403, 200)), ("/api/v2/recipients/", StatusCode(403, 200, 200)), ("/api/v2/responses/", StatusCode(403, 403, 200)), ("/api/v2/setup/", StatusCode(403, 403, 200)), ("/api/v2/sms/in/", StatusCode(403, 200, 200)), ("/api/v2/sms/out/", StatusCode(403, 200, 200)), ("/api/v2/users/", StatusCode(403, 200, 200)), ("/api/v2/users/profiles/", StatusCode(403, 403, 200)), ("/config/first_run/", StatusCode(302, 302, 302)), ("/graphs/contacts/", StatusCode(302, 302, 200)), ("/graphs/groups/", StatusCode(302, 302, 200)), ("/graphs/keywords/", StatusCode(302, 302, 200)), ("/graphs/recent/", StatusCode(302, 200, 200)), ("/graphs/sms/in/bycontact/", StatusCode(302, 302, 200)), ("/graphs/sms/out/bycontact/", StatusCode(302, 302, 200)), ("/graphs/sms/totals/", StatusCode(302, 302, 200)), ("/keyword/responses/csv/test/", StatusCode(302, 302, 200)), ("/not_approved/", StatusCode(200, 200, 200)), ("/recipient/new/", StatusCode(302, 200, 200)), ], ) @pytest.mark.django_db class TestUrls: """Test urls and access.""" def test_not_logged_in(self, url, status_code, users): """Test not logged in.""" assert users["c_out"].get(url).status_code == status_code.anon def test_in(self, url, status_code, users): """Test site urls when logged in a normal user""" assert users["c_in"].get(url).status_code == status_code.user def test_staff(self, url, status_code, users): """Test logged in as staff""" assert users["c_staff"].get(url).status_code == status_code.staff @pytest.mark.slow @pytest.mark.django_db class TestAPITokens: """Test Auth Token Access to API.""" def test_no_access(self, users): assert users["c_out"].get("/api/v2/recipients/").status_code == 403 def test_good_token_staff(self, users, recipients): t = Token.objects.create(user=users["staff"]) r = users["c_out"].get("/api/v2/recipients/", **{"HTTP_AUTHORIZATION": "Token {}".format(t.key)}) assert r.status_code == 200 data = r.json() assert data["count"] == len(data["results"]) assert data["count"] == models.Recipient.objects.count() def test_good_token_not_staff(self, users, recipients): t = Token.objects.create(user=users["notstaff"]) r = users["c_out"].get("/api/v2/recipients/", **{"HTTP_AUTHORIZATION": "Token {}".format(t.key)}) assert r.status_code == 200 data = r.json() assert data["count"] == len(data["results"]) assert data["count"] == models.Recipient.objects.filter(is_archived=False).count()
40.646341
105
0.615362
1,551
0.465347
0
0
3,099
0.929793
0
0
909
0.272727
9a52f446636c4417f93211b5960e9ec09c902310
2,491
py
Python
guestbook/main.py
bradmontgomery/mempy-flask-tutorial
8113562460cfa837e7b26df29998e0b6950dd46f
[ "MIT" ]
1
2018-01-10T17:54:18.000Z
2018-01-10T17:54:18.000Z
guestbook/main.py
bradmontgomery/mempy-flask-tutorial
8113562460cfa837e7b26df29998e0b6950dd46f
[ "MIT" ]
null
null
null
guestbook/main.py
bradmontgomery/mempy-flask-tutorial
8113562460cfa837e7b26df29998e0b6950dd46f
[ "MIT" ]
null
null
null
""" A *really* simple guestbook flask app. Data is stored in a SQLite database that looks something like the following: +------------+------------------+------------+ | Name | Email | signed_on | +============+==================+============+ | John Doe | [email protected] | 2012-05-28 | +------------+------------------+------------+ | Jane Doe | [email protected] | 2012-05-28 | +------------+------------------+------------+ This can be created with the following SQL (see bottom of this file): create table guestbook (name text, email text, signed_on date); Related Docs: * `sqlite3 <http://docs.python.org/library/sqlite3.html>`_ * `datetime <http://docs.python.org/library/datetime.html>`_ * `Flask <http://flask.pocoo.org/docs/>`_ """ from datetime import date from flask import Flask, redirect, request, url_for, render_template import sqlite3 app = Flask(__name__) # our Flask app DB_FILE = 'guestbook.db' # file for our Database def _select(): """ just pull all the results from the database """ connection = sqlite3.connect(DB_FILE) cursor = connection.cursor() cursor.execute("SELECT * FROM guestbook") return cursor.fetchall() def _insert(name, email): """ put a new entry in the database """ params = {'name':name, 'email':email, 'date':date.today()} connection = sqlite3.connect(DB_FILE) cursor = connection.cursor() cursor.execute("insert into guestbook (name, email, signed_on) VALUES (:name, :email, :date)", params) connection.commit() cursor.close() @app.route('/') def index(): """ List everyone who's signed the guestbook """ entries = [dict(name=row[0], email=row[1], signed_on=row[2] ) for row in _select()] return render_template('index.html', entries=entries) @app.route('/sign', methods=['POST']) def sign(): """ Accepts POST requests, and processes the form; Redirect to index when completed. """ _insert(request.form['name'], request.form['email']) return redirect(url_for('index')) if __name__ == '__main__': # Make sure our database exists connection = sqlite3.connect(DB_FILE) cursor = connection.cursor() try: cursor.execute("select count(rowid) from guestbook") except sqlite3.OperationalError: cursor.execute("create table guestbook (name text, email text, signed_on date)") cursor.close() app.run(host='0.0.0.0', debug=True)
29.654762
106
0.609394
0
0
0
0
492
0.197511
0
0
1,419
0.569651
9a555159031db4d7f16f4b7224046ffb7dcc0810
25,673
py
Python
lingvodoc/scripts/lingvodoc_converter.py
SegFaulti4/lingvodoc
8b296b43453a46b814d3cd381f94382ebcb9c6a6
[ "Apache-2.0" ]
5
2017-03-30T18:02:11.000Z
2021-07-20T16:02:34.000Z
lingvodoc/scripts/lingvodoc_converter.py
SegFaulti4/lingvodoc
8b296b43453a46b814d3cd381f94382ebcb9c6a6
[ "Apache-2.0" ]
15
2016-02-24T13:16:59.000Z
2021-09-03T11:47:15.000Z
lingvodoc/scripts/lingvodoc_converter.py
Winking-maniac/lingvodoc
f037bf0e91ccdf020469037220a43e63849aa24a
[ "Apache-2.0" ]
22
2015-09-25T07:13:40.000Z
2021-08-04T18:08:26.000Z
import sqlite3 import base64 import requests import json import hashlib import logging from lingvodoc.queue.client import QueueClient def get_dict_attributes(sqconn): dict_trav = sqconn.cursor() dict_trav.execute("""SELECT dict_name, dict_identificator, dict_description FROM dict_attributes WHERE id = 1;""") req = dict() for dictionary in dict_trav: req['dictionary_name'] = dictionary[0] req['dialeqt_id'] = dictionary[1] return req def upload_audio(upload_url, audio_sequence, markup_sequence, session): log = logging.getLogger(__name__) status = session.post(upload_url, json=audio_sequence) log.debug(status.text) audio_ids_list = json.loads(status.text) if markup_sequence: for k in range(0, len(audio_ids_list)): parent_client_id = audio_ids_list[k]['client_id'] parent_object_id = audio_ids_list[k]['object_id'] markup_sequence[k]["parent_client_id"] = parent_client_id markup_sequence[k]["parent_object_id"] = parent_object_id status = session.post(upload_url, json=markup_sequence) log.debug(status.text) def upload_markup(upload_url, search_url, markup_sequence, session): log = logging.getLogger(__name__) for entry in markup_sequence: audio_hash = entry[0] markup_element = entry[1] entity_metadata_search = search_url + '&searchstring=%s&searchtype=ound'% audio_hash # TODO: change ound to sound, when found how to do lowercase like status = session.get(entity_metadata_search) ents = json.loads(status.text) if ents: existing_entity = ents[0] if existing_entity: parent_client_id = existing_entity['client_id'] parent_object_id = existing_entity['object_id'] markup_element["parent_client_id"] = parent_client_id markup_element["parent_object_id"] = parent_object_id new_markup_sequence = [o[1] for o in markup_sequence if o[1].get("parent_client_id")] result = [o for o in markup_sequence if o[1].get("parent_client_id") is None] status = session.post(upload_url, json=new_markup_sequence) log.debug(status.text) return result def upload_audio_simple(session, ids_mapping, sound_and_markup_cursor, upload_url, audio_hashes, entity_types, client_id, is_a_regular_form, locale_id=1): audio_sequence = [] for cursor in sound_and_markup_cursor: blob_id = cursor[0] audio = cursor[1] filename = cursor[2] word_id = cursor[3] audio_hash = hashlib.sha224(audio).hexdigest() if audio_hash not in audio_hashes: audio_hashes.add(audio_hash) audio_element = {"locale_id": locale_id, "level": "leveloneentity", "data_type": "sound", "filename": filename, "entity_type": entity_types[0], "parent_client_id": ids_mapping[int(word_id)][0], "parent_object_id": ids_mapping[int(word_id)][1], "content": base64.urlsafe_b64encode(audio).decode()} if not is_a_regular_form: audio_element['additional_metadata'] = json.dumps({"hash": audio_hash, "client_id": client_id, "row_id": cursor[4]}) else: audio_element['additional_metadata'] = json.dumps({"hash": audio_hash }) audio_sequence.append(audio_element) if len(audio_sequence) > 50: upload_audio(upload_url, audio_sequence, None, session) audio_sequence = [] if len(audio_sequence) != 0: upload_audio(upload_url, audio_sequence, None, session) audio_sequence = [] def upload_audio_with_markup(session, ids_mapping, sound_and_markup_cursor, upload_url, search_url, audio_hashes, markup_hashes, entity_types, client_id, is_a_regular_form, locale_id=1): audio_sequence = [] markup_sequence = [] markup__without_audio_sequence = [] for cursor in sound_and_markup_cursor: blob_id = cursor[0] audio = cursor[1] markup = cursor[2] common_name = cursor[3] word_id = cursor[4] if not audio or not markup: continue audio_hash = hashlib.sha224(audio).hexdigest() markup_hash = hashlib.sha224(markup).hexdigest() if audio_hash not in audio_hashes: audio_hashes.add(audio_hash) audio_element = {"locale_id": locale_id, "level": "leveloneentity", "data_type": "sound", "filename": common_name + ".wav", "entity_type": entity_types[0], "parent_client_id": ids_mapping[int(word_id)][0], "parent_object_id": ids_mapping[int(word_id)][1], "content": base64.urlsafe_b64encode(audio).decode()} if not is_a_regular_form: audio_element['additional_metadata'] = json.dumps({"hash": audio_hash, "client_id": client_id, "row_id": cursor[5]}) else: audio_element['additional_metadata'] = json.dumps({"hash": audio_hash }) audio_sequence.append(audio_element) markup_hashes.add(markup_hash) markup_element = { "locale_id": locale_id, "level": "leveltwoentity", "data_type": "markup", "filename": common_name + ".TextGrid", "entity_type": entity_types[1], # need to set after push "parent_client_id": ids_mapping[int(word_id)][0], # need to set after push "parent_object_id": ids_mapping[int(word_id)][1], "content": base64.urlsafe_b64encode(markup).decode(), "additional_metadata": json.dumps({"hash": markup_hash})} markup_sequence.append(markup_element) else: if markup_hash not in markup_hashes: markup_hashes.add(markup_hash) markup_element = { "locale_id": locale_id, "level": "leveltwoentity", "data_type": "markup", "filename": common_name + ".TextGrid", "entity_type": entity_types[1], "content": base64.urlsafe_b64encode(markup).decode(), "additional_metadata": json.dumps({"hash": markup_hash})} markup__without_audio_sequence.append((audio_hash, markup_element)) if len(markup__without_audio_sequence) > 50: markup__without_audio_sequence = upload_markup(upload_url, search_url, markup__without_audio_sequence, session) if len(audio_sequence) > 50: upload_audio(upload_url, audio_sequence, markup_sequence, session) audio_sequence = [] markup_sequence = [] if len(markup__without_audio_sequence) > 50: markup__without_audio_sequence = upload_markup(upload_url, search_url, markup__without_audio_sequence, session) if len(audio_sequence) != 0: upload_audio(upload_url, audio_sequence, markup_sequence, session) audio_sequence = [] markup_sequence = [] if len(markup__without_audio_sequence) != 0: markup__without_audio_sequence = upload_markup(upload_url, search_url, markup__without_audio_sequence, session) #def change_dict_status(session, converting_status_url, status, task_id, progress): # def change_dict_status(task_id, progress): # #session.put(converting_status_url, json={'status': status}) # QueueClient.update_progress(task_id, progress) def convert_db_new(sqconn, session, language_client_id, language_object_id, server_url, dictionary_client_id, dictionary_object_id, perspective_client_id, perspective_object_id, locale_id=1, task_id=None): log = logging.getLogger(__name__) dict_attributes = get_dict_attributes(sqconn) if not dictionary_client_id or not dictionary_object_id: create_dictionary_request = {"parent_client_id": language_client_id, "parent_object_id": language_object_id, "translation": dict_attributes['dictionary_name'], "translation_string": dict_attributes['dictionary_name']} status = session.post(server_url + 'dictionary', json=create_dictionary_request) dictionary = json.loads(status.text) else: dictionary = {'client_id': dictionary_client_id, 'object_id': dictionary_object_id} client_id = dictionary['client_id'] converting_status_url = server_url + 'dictionary/%s/%s/state' % (dictionary['client_id'], dictionary['object_id']) # There is no way to move this redefinition because single-task version uses `converting_status_url` # which is assigned here def async_progress_bar(progress): QueueClient.update_progress(task_id, progress) def single_progress_bar(progress): session.put(converting_status_url, json={'status': 'Converting {0}%'.format(str(progress))}) change_dict_status = single_progress_bar if task_id is None else async_progress_bar change_dict_status(5) perspective_create_url = server_url + 'dictionary/%s/%s/perspective' % ( dictionary['client_id'], dictionary['object_id']) if not perspective_client_id or not perspective_object_id: create_perspective_request = {"translation": "Этимологический словарь из Lingvodoc 0.98", "translation_string": "Lingvodoc 0.98 etymology dictionary", "import_source": "Lingvodoc-0.98", "import_hash": dict_attributes['dialeqt_id']} status = session.post(perspective_create_url, json=create_perspective_request) perspective = json.loads(status.text) else: perspective = {'client_id': perspective_client_id, 'object_id': perspective_object_id} converting_perspective_status_url = server_url + 'dictionary/%s/%s/perspective/%s/%s/state' % \ (dictionary['client_id'], dictionary['object_id'], perspective['client_id'], perspective['object_id']) change_dict_status(10) create_perspective_fields_request = session.get(server_url + 'dictionary/1/6/perspective/1/7/fields') perspective_fields_create_url = perspective_create_url + '/%s/%s/fields' % (perspective['client_id'], perspective['object_id']) status = session.post(perspective_fields_create_url, json=create_perspective_fields_request.text) get_all_ids = sqconn.cursor() get_all_ids.execute("select id from dictionary where is_a_regular_form=1") create_lexical_entries_url = perspective_create_url + '/%s/%s/lexical_entries' % ( perspective['client_id'], perspective['object_id']) count_cursor = sqconn.cursor() count_cursor.execute("select count(*) from dictionary where is_a_regular_form=1") words_count = count_cursor.fetchone()[0] lexical_entries_create_request = {"count": words_count} status = session.post(create_lexical_entries_url, json=lexical_entries_create_request) ids_dict = json.loads(status.text) ids_mapping = dict() i = 0 for id_cursor in get_all_ids: id = id_cursor[0] client_id = ids_dict[i]['client_id'] object_id = ids_dict[i]['object_id'] ids_mapping[id] = (client_id, object_id) i += 1 create_entities_url = server_url + 'dictionary/%s/%s/perspective/%s/%s/entities' % (dictionary['client_id'], dictionary['object_id'], perspective['client_id'], perspective['object_id']) change_dict_status(15) def create_entity_list(mapping, cursor, level, data_type, entity_type, is_a_regular_form, locale_id=1): push_list = [] for ld_cursor in cursor: ld_id = int(ld_cursor[0]) content = ld_cursor[1] parent_client_id = mapping[ld_id][0] parent_object_id = mapping[ld_id][1] element = {"locale_id": locale_id, "level": level, "data_type": data_type, "entity_type": entity_type, "parent_client_id": parent_client_id, "parent_object_id": parent_object_id, "content": content} if not is_a_regular_form: element['additional_metadata'] = json.dumps({"client_id": client_id, "row_id": ld_cursor[2]}) push_list.append(element) return push_list def prepare_and_upload_text_entities(id_column, is_a_regular_form, text_column, entity_type): sqcursor = sqconn.cursor() if is_a_regular_form: sqcursor.execute("select %s,%s from dictionary where is_a_regular_form=1" % (id_column, text_column)) else: sqcursor.execute("select %s,%s,id from dictionary where is_a_regular_form=0" % (id_column, text_column)) push_list = create_entity_list(ids_mapping, sqcursor, "leveloneentity", 'text', entity_type, is_a_regular_form) return session.post(create_entities_url, json=push_list) for column_and_type in [("word", "Word"), ("transcription", "Transcription"), ("translation", "Translation")]: status = prepare_and_upload_text_entities("id", True, column_and_type[0], column_and_type[1]) log.debug(status.text) for column_and_type in [("word", "Paradigm word"), ("transcription", "Paradigm transcription"), ("translation", "Paradigm translation")]: status = prepare_and_upload_text_entities("regular_form", False, column_and_type[0], column_and_type[1]) log.debug(status.text) change_dict_status(35) sound_and_markup_word_cursor = sqconn.cursor() sound_and_markup_word_cursor.execute("""select blobs.id, blobs.secblob, blobs.mainblob, dict_blobs_description.name, dictionary.id from blobs, dict_blobs_description, dictionary where dict_blobs_description.blobid=blobs.id and dict_blobs_description.wordid=dictionary.id and dict_blobs_description.type=2 and dictionary.is_a_regular_form=1;""") audio_hashes = set() markup_hashes = set() perspective_search = server_url + 'dictionary/%s/%s/perspective/%s/%s/all' % (dictionary['client_id'], dictionary['object_id'], perspective['client_id'], perspective['object_id']) search_url = server_url + 'meta_search' \ '?perspective_client_id=%d&perspective_object_id=%d' % (perspective['client_id'], perspective['object_id']) status = session.get(perspective_search) lexes = json.loads(status.text)['lexical_entries'] sound_types = ['Sound', 'Paradigm sound'] markup_types = ['Praat markup', "Paradigm Praat markup"] for lex in lexes: for entry in lex['contains']: meta = entry.get('additional_metadata') if meta: hsh = meta.get('hash') if hsh: if entry['entity_type'] in sound_types: audio_hashes.add(hsh) if entry.get('contains'): for ent in entry['contains']: meta = entry.get('additional_metadata') if meta: hsh = meta.get('hash') if hsh: if ent['entity_type'] in markup_types: markup_hashes.add(hsh) entity_types = ['Sound', 'Praat markup'] upload_audio_with_markup(session, ids_mapping, sound_and_markup_word_cursor, create_entities_url, search_url, audio_hashes, markup_hashes, entity_types, client_id, True, locale_id) log.debug(audio_hashes) change_dict_status(45) paradigm_sound_and_markup_cursor = sqconn.cursor() paradigm_sound_and_markup_cursor.execute("""select blobs.id, blobs.secblob, blobs.mainblob, dict_blobs_description.name, dictionary.regular_form, dictionary.id from blobs, dict_blobs_description, dictionary where dict_blobs_description.blobid=blobs.id and dict_blobs_description.wordid=dictionary.id and dict_blobs_description.type=2 and dictionary.is_a_regular_form=0;""") entity_types = ['Paradigm sound', "Paradigm Praat markup"] upload_audio_with_markup(session, ids_mapping, paradigm_sound_and_markup_cursor, create_entities_url, search_url, audio_hashes, markup_hashes, entity_types, client_id, False, locale_id) log.debug(audio_hashes) change_dict_status(60) simple_word_sound_cursor = sqconn.cursor() simple_word_sound_cursor.execute("""select blobs.id, blobs.mainblob, dict_blobs_description.name, dictionary.id from blobs, dict_blobs_description, dictionary where dict_blobs_description.blobid=blobs.id and dict_blobs_description.wordid=dictionary.id and dict_blobs_description.type=1 and dictionary.is_a_regular_form=1;""") entity_types = ['Sound'] upload_audio_simple(session, ids_mapping, simple_word_sound_cursor, create_entities_url, audio_hashes, entity_types, client_id, True, locale_id) change_dict_status(70) simple_paradigm_sound_cursor = sqconn.cursor() simple_paradigm_sound_cursor.execute("""select blobs.id, blobs.mainblob, dict_blobs_description.name, dictionary.regular_form, dictionary.id from blobs, dict_blobs_description, dictionary where dict_blobs_description.blobid=blobs.id and dict_blobs_description.wordid=dictionary.id and dict_blobs_description.type=1 and dictionary.is_a_regular_form=0;""") entity_types = ['Paradigm sound'] upload_audio_simple(session, ids_mapping, simple_paradigm_sound_cursor, create_entities_url, audio_hashes, entity_types, client_id, False, locale_id) change_dict_status(80) connect_url = server_url + 'dictionary/%s/%s/perspective/%s/%s/lexical_entry/connect' % (dictionary['client_id'], dictionary['object_id'], perspective['client_id'], perspective['object_id']) etymology_cursor = sqconn.cursor() etymology_cursor.execute("""select id, etimology_tag FROM dictionary WHERE etimology_tag NOT NULL and dictionary.is_a_regular_form=1; """) for cursor in etymology_cursor: id = int(cursor[0]) client_id = ids_mapping[id][0] object_id = ids_mapping[id][1] item = {"entity_type": "Etymology", "tag": cursor[1], "connections": [{"client_id": client_id, "object_id": object_id}]} status = session.post(connect_url, json=item) log.debug(status.text) suggestions_url = server_url + 'merge/suggestions' suggestions_params = {'threshold': 1.0, 'levenstein': 0, 'client_id': perspective['client_id'], 'object_id': perspective['object_id']} status = session.post(suggestions_url, json=suggestions_params) for entry in json.loads(status.text): if entry['confidence'] >= 1.0: first_entry = entry['suggestion'][0] second_entry = entry['suggestion'][1] lex_move_url = server_url + 'lexical_entry/%d/%d/move' % (second_entry['lexical_entry_client_id'], second_entry['lexical_entry_object_id']) move_params = {'client_id': first_entry['lexical_entry_client_id'], 'object_id': first_entry['lexical_entry_object_id'], 'real_delete': True} status = session.patch(lex_move_url, json=move_params) else: break change_dict_status(95) change_dict_status(100) return dictionary def convert_one(filename, login, password_hash, language_client_id, language_object_id, dictionary_client_id, dictionary_object_id, perspective_client_id, perspective_object_id, server_url="http://localhost:6543/", task_id=None): log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) log.debug("Starting convert_one") log.debug("Creating session") session = requests.Session() session.headers.update({'Connection': 'Keep-Alive'}) adapter = requests.adapters.HTTPAdapter(pool_connections=1, pool_maxsize=1, max_retries=10) session.mount('http://', adapter) log.debug("Going to login") login_data = {"login": login, "passwordhash": password_hash} log.debug("Login data: " + login_data['login'] + login_data['passwordhash']) cookie_set = session.post(server_url + 'cheatlogin', json=login_data) log.debug("Login status:" + str(cookie_set.status_code)) if cookie_set.status_code != 200: log.error("Cheat login for conversion was unsuccessful") exit(-1) sqconn = sqlite3.connect(filename) log.debug("Connected to sqlite3 database") try: status = convert_db_new(sqconn, session, language_client_id, language_object_id, server_url, dictionary_client_id, dictionary_object_id, perspective_client_id, perspective_object_id, task_id=task_id) except Exception as e: log.error("Converting failed") log.error(e.__traceback__) raise log.debug(status) return status if __name__ == "__main__": log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) logging.basicConfig(format='%(asctime)s\t%(levelname)s\t[%(name)s]\t%(message)s') log.debug("!!!!!!!!!! YOU SHOULD NOT SEE IT !!!!!!!!") convert_one(filename="/home/student/dicts-current/nenets_kaninski.sqlite", login="Test", password_hash="$2a$12$zBMnhV9oUfKehlHJCHnsPuGM98Wwq/g9hlWWNqg8ZGDuLNyUSfxza", language_client_id=1, language_object_id=1, dictionary_client_id=None, dictionary_object_id=None, perspective_client_id=None, perspective_object_id=None, server_url="http://lingvodoc.ispras.ru/")
51.346
159
0.569158
0
0
0
0
0
0
0
0
7,547
0.293692
9a56a9cb8a9973d77c62dc8bff13ecc6a5a858c1
1,550
py
Python
tests/test_all.py
euranova/DAEMA
29fec157c34afcc9abe95bc602a3012615b3c36b
[ "MIT" ]
6
2021-09-17T02:09:29.000Z
2022-03-20T04:15:15.000Z
tests/test_all.py
Jason-Xu-Ncepu/DAEMA
29fec157c34afcc9abe95bc602a3012615b3c36b
[ "MIT" ]
null
null
null
tests/test_all.py
Jason-Xu-Ncepu/DAEMA
29fec157c34afcc9abe95bc602a3012615b3c36b
[ "MIT" ]
4
2021-06-29T22:57:18.000Z
2022-03-09T09:19:17.000Z
""" Tests the code. """ from torch.utils.data import DataLoader from models import MODELS from pipeline import argument_parser from pipeline.datasets import DATASETS, get_dataset from run import main def test_datasets(): """ Tests all the datasets defined in pipeline.datasets.DATASETS. """ for ds_name in DATASETS: train_set, test_set, _ = get_dataset(ds_name, seed=42) for set_ in (train_set, test_set): dl = DataLoader(list(zip(*set_)), batch_size=5) for data, missing_data, mask in dl: assert len(data) == 5, f"The {ds_name} dataset has less than 5 samples." assert data.shape[1] > 1, f"The {ds_name} dataset has none or one column only." print("data:", data, "missing_data:", missing_data, "mask:", mask, sep="\n") break def test_general(capsys): """ Tests most of the code by checking it produces the expected result. """ main(argument_parser.get_args(["--metric_steps", "50", "--datasets", "Boston", "--seeds", "0", "1"])) captured = capsys.readouterr() with open("tests/current_output.txt", "w") as f: assert f.write(captured.out) with open("tests/gold_output.txt", "r") as f: assert captured.out == f.read() def test_models(): """ Tests all the models (only checks if these run). """ for model in MODELS: main(argument_parser.get_args(["--model", model, "--metric_steps", "0", "1", "5", "--datasets", "Boston", "--seeds", "0"]))
38.75
113
0.614839
0
0
0
0
0
0
0
0
534
0.344516
9a586ac04d9d83458edb9f23d9cb90fb787462de
2,185
py
Python
src/preprocessing.py
Wisteria30/GIM-RL
085ba3b8c10590f82226cd1675ba96c5f90740f3
[ "Apache-2.0" ]
3
2021-10-15T00:57:05.000Z
2021-12-16T13:00:05.000Z
src/preprocessing.py
Wisteria30/GIM-RL
085ba3b8c10590f82226cd1675ba96c5f90740f3
[ "Apache-2.0" ]
null
null
null
src/preprocessing.py
Wisteria30/GIM-RL
085ba3b8c10590f82226cd1675ba96c5f90740f3
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- import numpy as np import random import os import sys import torch from src.agent import ( EpsilonGreedyAgent, MaxAgent, RandomAgent, RandomCreateBVAgent, ProbabilityAgent, QAgent, QAndUtilityAgent, MultiEpsilonGreedyAgent, MultiMaxAgent, MultiProbabilityAgent, MultiQAgent, MultiQAndUtilityAgent, ) def set_seed(seed=0): np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) def set_agent(env, cfg): if cfg.agent.name == "q": agent = QAgent(env, cfg) elif cfg.agent.name == "qandutility": agent = QAndUtilityAgent(env, cfg) elif cfg.agent.name == "max": agent = MaxAgent(env, cfg) elif cfg.agent.name == "probability": agent = ProbabilityAgent(env, cfg) elif cfg.agent.name == "random": agent = RandomAgent(env, cfg) elif cfg.agent.name == "randombv": agent = RandomCreateBVAgent(env, cfg) elif cfg.agent.name == "egreedy": agent = EpsilonGreedyAgent(env, cfg) else: print("illegal agent name.") sys.exit(1) return agent def set_multi_agent(env, cfg): if cfg.agent.name == "q": agent = MultiQAgent(env, cfg) elif cfg.agent.name == "qandutility": agent = MultiQAndUtilityAgent(env, cfg) elif cfg.agent.name == "max": agent = MultiMaxAgent(env, cfg) elif cfg.agent.name == "probability": agent = MultiProbabilityAgent(env, cfg) elif cfg.agent.name == "random": agent = RandomAgent(env, cfg) elif cfg.agent.name == "randombv": agent = RandomCreateBVAgent(env, cfg) elif cfg.agent.name == "egreedy": agent = MultiEpsilonGreedyAgent(env, cfg) else: print("illegal agent name.") sys.exit(1) return agent def set_common_tag(writer, cfg): writer.set_runname(os.path.join(os.getcwd(), ".hydra/overrides.yaml")) writer.set_tag("mlflow.note.content", cfg.content) writer.set_tag("mlflow.user", cfg.user) writer.set_tag("mlflow.source.name", os.path.abspath(__file__)) writer.set_tag("mlflow.source.git.commit", cfg.commit)
27.3125
74
0.644851
0
0
0
0
0
0
0
0
290
0.132723
9a599c01b7e7a6eb5de9e8bf5a694c44420b04db
101
py
Python
python/testData/editing/spaceDocStringStubInFunction.after.py
jnthn/intellij-community
8fa7c8a3ace62400c838e0d5926a7be106aa8557
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
python/testData/editing/spaceDocStringStubInFunction.after.py
jnthn/intellij-community
8fa7c8a3ace62400c838e0d5926a7be106aa8557
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
python/testData/editing/spaceDocStringStubInFunction.after.py
jnthn/intellij-community
8fa7c8a3ace62400c838e0d5926a7be106aa8557
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
def func(x, y, z): """ :param x: <caret> :param y: :param z: :return: """
14.428571
21
0.386139
0
0
0
0
0
0
0
0
78
0.772277
9a5ad370a80119a4cd36243d371bcf4ccf37a3ae
1,439
py
Python
src/leaf/file_tools.py
Pix-00/olea-v2_flask_1_
7ddfa83a7a2a7dfbe55b78da002c1193f38781c0
[ "Apache-2.0" ]
null
null
null
src/leaf/file_tools.py
Pix-00/olea-v2_flask_1_
7ddfa83a7a2a7dfbe55b78da002c1193f38781c0
[ "Apache-2.0" ]
null
null
null
src/leaf/file_tools.py
Pix-00/olea-v2_flask_1_
7ddfa83a7a2a7dfbe55b78da002c1193f38781c0
[ "Apache-2.0" ]
null
null
null
from hashlib import sha3_256 import magic from enums import Dep, MangoType MIME_MTYPE = { 'text/plain': MangoType.text, 'audio/flac': MangoType.audio_flac, 'audio/wav': MangoType.audio_wav, 'image/png': MangoType.picture_png, 'image/jpeg': MangoType.picture_jpg, 'video/x-matroska': MangoType.video_mkv, 'video/mp4': MangoType.video_mp4 } def special_save(f, path: str) -> (bytes, MangoType): hasher = sha3_256() with open(path, 'wb') as tf: chunk = f.read(4096) tf.write(chunk) hasher.update(chunk) mime: str = magic.from_buffer(chunk, mime=True) while True: chunk = f.read(4096) if not chunk: break hasher.update(chunk) tf.write(chunk) fp = hasher.digest() mtype = MIME_MTYPE[mime] if mime in MIME_MTYPE else MangoType.unknown return fp, mtype TYPE_ALLOWED = { Dep.d51: (MangoType.audio_flac, ), Dep.d59: (MangoType.audio_flac, ), Dep.d60: (MangoType.picture_png, ), Dep.d71: (MangoType.audio_flac, ), Dep.d72: (MangoType.text, ), Dep.d73: (MangoType.video_mkv, MangoType.video_mp4) } def is_allowed_type(dep: Dep, mtype: MangoType) -> bool: return mtype in TYPE_ALLOWED[dep] EXTS = { MangoType.audio_flac: 'flac', MangoType.picture_png: 'png', MangoType.text: 'txt', MangoType.video_mkv: 'mkv', MangoType.video_mp4: 'mp4' }
24.810345
73
0.635858
0
0
0
0
0
0
0
0
117
0.081306
9a5cc32eb8d423266537616c2fd2072b4114deb3
2,258
py
Python
fabric_cm/credmgr/swagger_server/__main__.py
fabric-testbed/CredentialManager
da8ce54ab78544ff907af81d8cd7723ff48f6652
[ "MIT" ]
1
2021-05-24T17:20:07.000Z
2021-05-24T17:20:07.000Z
fabric_cm/credmgr/swagger_server/__main__.py
fabric-testbed/CredentialManager
da8ce54ab78544ff907af81d8cd7723ff48f6652
[ "MIT" ]
4
2021-06-07T16:18:45.000Z
2021-06-29T20:13:21.000Z
fabric_cm/credmgr/swagger_server/__main__.py
fabric-testbed/CredentialManager
da8ce54ab78544ff907af81d8cd7723ff48f6652
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Author Komal Thareja ([email protected]) """ Main Entry Point """ import os import signal import connexion import prometheus_client import waitress from flask import jsonify from fabric_cm.credmgr.swagger_server import encoder from fabric_cm.credmgr.config import CONFIG_OBJ from fabric_cm.credmgr.logging import LOG def main(): """ Main Entry Point """ log = LOG try: app = connexion.App(__name__, specification_dir='swagger/') app.app.json_encoder = encoder.JSONEncoder app.add_api('swagger.yaml', arguments={'title': 'Fabric Credential Manager API'}, pythonic_params=True) port = CONFIG_OBJ.get_rest_port() # prometheus server prometheus_port = CONFIG_OBJ.get_prometheus_port() prometheus_client.start_http_server(prometheus_port) # Start up the server to expose the metrics. waitress.serve(app, port=port) except Exception as ex: log.error("Exception occurred while starting Flask app") log.error(ex) raise ex if __name__ == '__main__': main()
32.724638
80
0.724978
0
0
0
0
0
0
0
0
1,390
0.615589
9a5d1a5d6e04e787d275225f739fe6d7102b20fa
1,529
py
Python
backendapi/icon/migrations/0001_initial.py
fredblade/Pictogram
d5cc4a25f28b6d80facf51fa9528e8ff969f7c46
[ "MIT" ]
null
null
null
backendapi/icon/migrations/0001_initial.py
fredblade/Pictogram
d5cc4a25f28b6d80facf51fa9528e8ff969f7c46
[ "MIT" ]
null
null
null
backendapi/icon/migrations/0001_initial.py
fredblade/Pictogram
d5cc4a25f28b6d80facf51fa9528e8ff969f7c46
[ "MIT" ]
null
null
null
# Generated by Django 3.1.2 on 2022-02-27 17:59 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import versatileimagefield.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='IconImage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('image', versatileimagefield.fields.VersatileImageField(upload_to='icons/', verbose_name='Icon')), ('image_ppoi', versatileimagefield.fields.PPOIField(default='0.5x0.5', editable=False, max_length=20)), ], ), migrations.CreateModel( name='IconItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', versatileimagefield.fields.VersatileImageField(upload_to='icons/', verbose_name='Icon')), ('image_ppoi', versatileimagefield.fields.PPOIField(default='0.5x0.5', editable=False, max_length=20)), ('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='iconitem', related_query_name='iconitem', to=settings.AUTH_USER_MODEL)), ], ), ]
41.324324
177
0.646828
1,336
0.873774
0
0
0
0
0
0
203
0.132767
9a5f6f4fdf92f5d8e97feaed00a42aa430e9c51a
424,971
py
Python
src/fmiprot.py
tanisc/FMIPROT
9035b5f89768e1028edd08dc7568b3208552f164
[ "Apache-2.0" ]
4
2019-02-25T11:53:55.000Z
2021-03-16T20:16:56.000Z
src/fmiprot.py
tanisc/FMIPROT
9035b5f89768e1028edd08dc7568b3208552f164
[ "Apache-2.0" ]
2
2021-09-14T09:54:42.000Z
2021-11-12T13:30:10.000Z
src/fmiprot.py
tanisc/FMIPROT
9035b5f89768e1028edd08dc7568b3208552f164
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # python version 2.7 # Cemal Melih Tanis (C) ############################################################################### import os import shutil import datetime from pytz import timezone from uuid import uuid4 from definitions import * import fetchers import calculations from calculations import calcnames, calccommands, paramnames, paramdefs, paramopts, calcids, calcdescs,paramhelps, calcnames_en import maskers import parsers import sources from data import * import readers import calcfuncs import matplotlib, sys import numpy as np if sysargv['gui']: matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import Tkinter, Tkconstants, tkFileDialog, tkMessageBox, tkSimpleDialog, tkFont import Tkinter as tk import ttk import matplotlib.dates as mdate import PIL from PIL import Image,ImageDraw, ImageFont if sysargv['gui']: from PIL import ImageTk if os.path.sep == '/': from PIL import _tkinter_finder import mahotas from copy import deepcopy import subprocess from auxdata import auxlist, auxnamelist import auxdata import comparators import webbrowser import h5py import textwrap import gc if sysargv['gui']: import FileDialog if not sysargv['gui']: Tkinter = None import noTk as Tkinter import noTk as tk import noTk as tkMessageBox import noTk as tkSimpleDialog import noTk as webbrowser import noTk as tkFont class monimet_gui(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.resizable(False, False) screen_sizes = [self.winfo_screenwidth(),self.winfo_screenheight()] self.UnitSize = min(screen_sizes) if screen_sizes.index(self.UnitSize) == 0: self.UnitSize /= 640 else: self.UnitSize /= 360 self.FontSize = self.UnitSize*3 self.DefFont = tkFont.nametofont("TkDefaultFont") self.DefFont.configure(size=self.FontSize) self.option_add("*Font", self.DefFont) self.PasAnaY = 2*self.UnitSize self.TableX = 3*self.UnitSize self.TableY = 3*self.UnitSize self.FolderX = 3*self.UnitSize self.FolderY = 3*self.UnitSize self.BannerY = 16*self.UnitSize self.BannerX = 10*self.UnitSize self.PasParchX = 10*self.UnitSize self.PasParchIn = 3*self.UnitSize self.MenuHeaderX = 10*self.UnitSize self.LogY = 16*self.UnitSize self.MenuY = 203*self.UnitSize self.MenuX = 118*self.UnitSize self.WindowX = self.TableX+self.FolderX+self.PasParchX+self.MenuHeaderX+self.MenuX+self.TableX+self.FolderX self.WindowY = 2*self.TableY+3*self.FolderY+self.BannerY+self.MenuY+self.LogY self.SensVariableDef = 10 self.SensVariable = Tkinter.IntVar() self.SensVariable.set(self.SensVariableDef) self.geometry(str(self.WindowX)+"x"+str(self.WindowY)) self.centerWindow() self.CheckButtonX = 5*self.UnitSize self.CheckButtonY = 5*self.UnitSize self.ScrollbarX = 5*self.UnitSize self.MenuItemMax = 16 #even number #self.centerWindow() self.LogWindowOn() self.initialize() self.centerWindow(self.LogWindow,ontheside=True) def initialize(self): self.MenuTitleBgColor = 'RoyalBlue4' self.MenuTitleTextColor = 'white' #innervariables self.prevonlist = ["Camera","Choose Picture ","Choose Picture for Preview","Polygonic Masking"] self.plotonlist = ["Customize Graph","Axes","Variables",'Result Viewer',"Extent","Style"] self.MenuPage = Tkinter.IntVar() self.MenuPage.set(1) self.Message = Tkinter.StringVar() self.Message.trace('w',self.LogMessage) self.Log = Tkinter.StringVar() self.LogLL = Tkinter.StringVar() self.LogFileName = ['',''] self.LogNew(self) self.MessagePrev= {} self.Message.set("Initializing...|busy:True") print "\nBy running this program, you agree to the terms of the license, described in the file 'LICENSE'. Use argument --license to see the license.\n" self.Message.set("Initializing GUI...") self.ActiveMenu = Tkinter.StringVar() self.MenuEnablerFunc = Tkinter.StringVar() self.ActiveMenu.set("Main Menu") self.AnalysisNoVariable = Tkinter.IntVar() self.AnalysisNoVariable.trace_variable('w',self.callbackAnalysisNo) self.ScenarioNameVariable = Tkinter.StringVar() self.ResultsCanvasSwitch = Tkinter.BooleanVar() self.ResultsCanvasSwitch.set(False) self.PolygonNoVariable = Tkinter.IntVar() self.NetworkNameVariable = Tkinter.StringVar() self.NetworkNameVariablePre = Tkinter.StringVar() self.NetworkNameVariable.trace_variable('w',self.callbackNetworkName) self.CameraNameVariable = Tkinter.StringVar() self.CameraNameVariablePre = Tkinter.StringVar() self.CameraNameVariable.trace_variable('w',self.callbackCameraName) self.ExceptionSwitches_ComingFromCallbackAnalysis = Tkinter.BooleanVar() self.ExceptionSwitches_ComingFromCallbackAnalysis.set(True) self.ExceptionSwitches_ComingFromStartupSetupFileSetupReset = Tkinter.BooleanVar() self.ExceptionSwitches_ComingFromStartupSetupFileSetupReset.set(True) self.RedLTVariable = Tkinter.DoubleVar() self.RedUTVariable = Tkinter.DoubleVar() self.GreenLTVariable = Tkinter.DoubleVar() self.GreenUTVariable = Tkinter.DoubleVar() self.BlueLTVariable = Tkinter.DoubleVar() self.BlueUTVariable = Tkinter.DoubleVar() self.GreyLTVariable = Tkinter.DoubleVar() self.GreyUTVariable = Tkinter.DoubleVar() self.RedFLTVariable = Tkinter.DoubleVar() self.RedFUTVariable = Tkinter.DoubleVar() self.GreenFLTVariable = Tkinter.DoubleVar() self.GreenFUTVariable = Tkinter.DoubleVar() self.BlueFLTVariable = Tkinter.DoubleVar() self.BlueFUTVariable = Tkinter.DoubleVar() self.RedFILTVariable = Tkinter.DoubleVar() self.RedFIUTVariable = Tkinter.DoubleVar() self.GreenFILTVariable = Tkinter.DoubleVar() self.GreenFIUTVariable = Tkinter.DoubleVar() self.BlueFILTVariable = Tkinter.DoubleVar() self.BlueFIUTVariable = Tkinter.DoubleVar() self.BrightnessLTVariable = Tkinter.DoubleVar() self.BrightnessUTVariable = Tkinter.DoubleVar() self.LuminanceLTVariable = Tkinter.DoubleVar() self.LuminanceUTVariable = Tkinter.DoubleVar() self.DateStartVariable = Tkinter.StringVar() self.DateEndVariable = Tkinter.StringVar() self.TimeStartVariable = Tkinter.StringVar() self.TimeEndVariable = Tkinter.StringVar() self.TemporalModeVariable = Tkinter.StringVar() self.TemporalModeVariable.trace_variable('w',self.callbackTemporalMode) self.PolygonCoordinatesVariable = Tkinter.StringVar() self.PolygonMultiRoiVariable = Tkinter.BooleanVar() self.PolygonMultiRoiVariable.set(True) self.MaskingPolygonPen = Tkinter.IntVar() self.MaskingPolygonPen.set(0) self.PictureID = Tkinter.IntVar() self.PictureID.set(99) self.NumResultsVariable = Tkinter.IntVar() self.ResultPlotNoVariable = Tkinter.IntVar() self.CalculationNoVariable = Tkinter.IntVar() self.CalculationNoVariable.set(1) self.CalculationNoVariable.trace_variable('w',self.callbackCalculationNo) self.CalculationNameVariable = Tkinter.StringVar() self.CalculationNameVariable.trace_variable('w',self.callbackCalculationName) self.CalculationDescriptionVariable = Tkinter.StringVar() self.CalculationDescriptionVariable.set(calcdescs[0]) self.ResultFolderNameVariable = Tkinter.StringVar() self.ResultNameVariable = Tkinter.StringVar() self.ResultVariableNameVariable = Tkinter.StringVar() self.ResultVariableNameVariable.trace('w',self.callbackResultVariable) self.ResultsFileNameVariable = Tkinter.StringVar() self.ResultNameVariable.trace('w',self.callbackResultsName) self.ResultFolderNameVariable.set('Results Directory') self.ResultFolderNameVariable.trace('w',self.callbackResultsFolder) self.PlotXStartVariable = Tkinter.StringVar() self.PlotXEndVariable = Tkinter.StringVar() self.PlotYStartVariable = Tkinter.StringVar() self.PlotYEndVariable = Tkinter.StringVar() self.PlotXStartFactor = Tkinter.DoubleVar() self.PlotXEndFactor = Tkinter.DoubleVar() self.PlotYStartFactor = Tkinter.DoubleVar() self.PlotYEndFactor = Tkinter.DoubleVar() self.LegendVar = Tkinter.IntVar() self.LegendVar.set(1) self.LegendVar.trace_variable('w',self.callbackResultsVar) self.PreviewCanvasSwitch = Tkinter.BooleanVar() self.PreviewCanvasSwitch.set(False) self.PreviewCanvasSwitch.trace_variable('w',self.callbackPreviewCanvasSwitch) self.PlotCanvasSwitch = Tkinter.BooleanVar() self.PlotCanvasSwitch.set(False) self.PlotCanvasSwitch.trace_variable('w',self.callbackResultsVar) self.Colors = COLORS self.PolygonColor0 = Tkinter.StringVar() self.PolygonColor1 = Tkinter.StringVar() self.PolygonColor0.set(COLORS[14]) self.PolygonColor1.set(COLORS[8]) self.PolygonColor0.trace('w',self.callbackPreviewCanvasSwitch) self.PolygonColor1.trace('w',self.callbackPreviewCanvasSwitch) self.PolygonWidth = Tkinter.IntVar() self.PolygonWidth.set(4) self.PolygonWidth.trace('w',self.callbackPreviewCanvasSwitch) self.configFileVariable = Tkinter.StringVar() self.setupFileVariable = Tkinter.StringVar() self.PictureFileName = Tkinter.StringVar() self.PictureFile2 = Tkinter.BooleanVar() self.PictureFile2.set(False) #settings self.initSettings() self.ActiveMenu.trace('w',self.callbackActiveMenu) global scenario_def, setup_def ,temporal_modes, output_modes (self.networklist,self.sourcelist,self.proxylist) = sources.readSources(self, self.proxy, self.connection, self.Message) self.makeDirStorage() scenario_def = {'source':self.sourcelist[0],'name':'Scenario-1','previewimagetime':'','temporal':['01.01.1970','31.12.2026','00:00','23:59','All'],'polygonicmask':[0,0,0,0,0,0,0,0],'multiplerois':1,'thresholds':[0.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,255.0,0.0,255.0,0.0,255.0,0.0,1.0,0.0,255.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0],'analyses':['analysis-1'],'analysis-1':{'id':calcids[calcids.index("0")],'name':calcnames[calcids.index("0")]}} for i,v in enumerate(paramnames[calcids.index("0")]): scenario_def['analysis-1'].update({paramnames[calcids.index("0")][i]:paramdefs[calcids.index("0")][i]}) setup_def = [scenario_def] temporal_modes = ['All','Date and time intervals','Time of day','Earliest date and time intervals','Latest date and time intervals','Yesterday only','Today only','Latest 1 hour','Latest image only','Latest one year','Latest one month','Latest one week','Latest 48 hours','Latest 24 hours','Last one year','Last one month','Last one week','Last 48 hours','Last 24 hours'] output_modes = ['New directory in results directory','Existing empty directory','Merge with existing results'] if sysargv['resultdir'] is not None: sysargv['resultdir'] = os.path.realpath(sysargv['resultdir']) if not os.path.exists(sysargv['resultdir']): os.makedirs(sysargv['resultdir']) if not os.path.exists(sysargv['resultdir']) or len(os.listdir(sysargv['resultdir'])) == 0: self.outputmodevariable.set(output_modes[1]) else: self.outputmodevariable.set(output_modes[2]) self.outputpath.set(sysargv['resultdir']) else: self.outputmodevariable.set(output_modes[0]) if sysargv['offline']: self.imagesdownload.set(False) else: self.imagesdownload.set(True) if not sysargv['gui']: if sysargv['license']: self.License() os._exit(1) if sysargv['config_settings']: self.configSettings() os._exit(1) if sysargv['config_proxies']: self.configProxies() os._exit(1) if sysargv['setupfile'] is None: tkMessageBox.showerror('Usage error','Setup file must be provided if GUI is off.') os._exit(1) self.setupFileClear() self.ExceptionSwitches_ComingFromStartupSetupFileSetupReset.set(False) self.setupFileLoad() self.RunAnalyses() os._exit(1) else: self.Menu_Base() self.Menu_Menu() if sysargv['setupfile'] is not None: sysargv['setupfile'] = os.path.realpath(sysargv['setupfile']) self.setupFileClear() self.ExceptionSwitches_ComingFromStartupSetupFileSetupReset.set(False) self.setupFileLoad() sysargv['setupfile'] = None else: self.setupFileClear() self.ExceptionSwitches_ComingFromStartupSetupFileSetupReset.set(False) self.Menu_Main() self.Message.set("GUI initialized.") self.Message.set("Program initialized.|busy:False") def initSettings(self): if not os.path.isfile(settingsFile): f = open(settingsFile,'wb') f.close() settingv = parsers.readSettings(settingsFile,self.Message) self.http_proxy = Tkinter.StringVar() self.https_proxy = Tkinter.StringVar() self.ftp_proxy = Tkinter.StringVar() self.http_proxy.set(settingv[settings.index('http_proxy')]) self.https_proxy.set(settingv[settings.index('https_proxy')]) self.ftp_proxy.set(settingv[settings.index('ftp_proxy')]) self.imagesdownload = Tkinter.BooleanVar() self.imagesdownload.set(bool(float(settingv[settings.index('images_download')]))) self.ftp_passive = Tkinter.BooleanVar() self.ftp_passive.set(bool(float(settingv[settings.index('ftp_passive')]))) self.ftp_numberofconnections = Tkinter.IntVar() self.ftp_numberofconnections.set(int(settingv[settings.index('ftp_numberofconnections')])) self.ftp_numberofconnections.set(1) #temp until fix self.imagespath = Tkinter.StringVar() self.resultspath = Tkinter.StringVar() self.outputpath = Tkinter.StringVar() self.outputmodevariable = Tkinter.StringVar() self.outputmodevariable.trace_variable('w',self.callbackoutputmode) self.imagespath.set(settingv[settings.index('images_path')]) self.resultspath.set(settingv[settings.index('results_path')]) self.TimeZone = Tkinter.StringVar() self.TimeZone.set(settingv[settings.index('timezone')]) self.TimeZoneConversion = Tkinter.BooleanVar() self.TimeZoneConversion.set(bool(float(settingv[settings.index('convert_timezone')]))) self.outputreportvariable = Tkinter.BooleanVar() self.outputreportvariable.set(bool(float(settingv[settings.index('generate_report')]))) self.memorylimit = Tkinter.IntVar() self.memorylimit.set(int(settingv[settings.index('memory_limit')])) self.updateProxy() self.updateStorage() self.updateConnection() self.updateProxy() self.updateProcessing() for source in auxnamelist: for setk in auxlist[source]["settings"]: auxlist[source]["settings"].update({setk:settingv[settings.index(source+'-'+setk)]}) parsers.writeSettings(parsers.dictSettings(settingv),settingsFile,self.Message) def configSettings(self): ans = '' while True: if ans == '0': break settingv = parsers.readSettings(settingsFile,self.Message) print 'ID','\t', 'Parameter',' : ', 'Value' for s,setting in enumerate(settings): if s == len(settingsn): break print str(s+1),'\t', settingsn[settings.index(setting)],' : ', settingv[settings.index(setting)] ans = raw_input('Enter ID to modify the parameter or 0 to exit\n') try: if int(ans) <= 0 or int(ans) > len(settingv): fail except: if ans != '0': print 'Incorrect input.' continue s = int(ans)-1 val = raw_input('Enter new value for ' + settingsn[s] + ' '+settingso[s]+'\n') conf = '' while conf not in ['y','n','Y','N']: conf = raw_input('Are you sure? (y/n)') if conf not in ['y','n','Y','N']: print 'Incorrect answer. ', if conf in ['y','Y']: settingv[s] = val parsers.writeSettings(parsers.dictSettings(settingv),settingsFile,self.Message) def configProxies(self): ans = '' self.manager_proxy_window = Tkinter.Toplevel(self,padx=10,pady=10) self.manager_proxylist = self.proxylist[:] self.manager_proxy_number = Tkinter.IntVar() self.manager_proxy_number.set(1) self.manager_proxy_number.trace('w',self.Networks_LoadProxy) self.manager_proxy_protocol = Tkinter.StringVar() self.manager_proxy_host = Tkinter.StringVar() self.manager_proxy_username = Tkinter.StringVar() self.manager_proxy_password = Tkinter.StringVar() self.manager_proxy_path = Tkinter.StringVar() self.manager_proxy_filenameformat = Tkinter.StringVar() self.manager_proxy_protocol_target = Tkinter.StringVar() self.manager_proxy_host_target = Tkinter.StringVar() self.manager_proxy_username_target = Tkinter.StringVar() self.manager_proxy_password_target = Tkinter.StringVar() self.manager_proxy_path_target = Tkinter.StringVar() self.manager_proxy_filenameformat_target = Tkinter.StringVar() labels = ['Camera Comm. Protocol','Image archive Host','Username for host','Password for host','Path to images','File name convention'] variables = [self.manager_proxy_protocol,self.manager_proxy_protocol_target,self.manager_proxy_host,self.manager_proxy_host_target,self.manager_proxy_username,self.manager_proxy_username_target,self.manager_proxy_password,self.manager_proxy_password_target,self.manager_proxy_path,self.manager_proxy_path_target,self.manager_proxy_filenameformat,self.manager_proxy_filenameformat_target] while True: self.Networks_LoadProxy() print 'Edit camera network proxies' print 'When reaching images of a camera with parameters on the "Original value" side, instead the parameters in "Proxy value" will be used. Use "*" as a wildcard to include any value for a parameter. Check the user manual for detailed information and examples.' print '| <(P)revious | Proxy No: ',self.manager_proxy_number.get(), ' | (N)ext> | (A)dd | (R)emove |' print '|Parameter', print '\t\t|', print 'Original Value', print '|', print 'Proxy Value' for i in range(len(labels)): print '|'+labels[i], print '\t|', print variables[i*2].get(), print ' ('+str(i*2+1)+')', print '|', print variables[i*2+1].get(), print ' ('+str(i*2+2)+')', print '|' print '| (S)ave changes | (D)iscard changes | (E)xit |' if len(self.proxylist) == 0: tkMessageBox.showinfo('Camera Network Proxy Manager','There is no camera network proxy defined yet. In the manager window, a proxy with default values to edit is added. To quit editing, simply close the manager window.') ans = raw_input('Enter (C)haracters for related action or enter numbers to edit fields\n') if ans in ['E','e']: break if ans in ['P','p','N','n','A','a','R','r','S','s','D','d']: if ans in ['P','p']: self.Networks_PrevProxy() if ans in ['N','n']: self.Networks_NextProxy() if ans in ['A','a']: self.Networks_AddProxy() if ans in ['R','r']: self.Networks_RemoveProxy() if ans in ['S','s']: self.Networks_Proxy_Save() if ans in ['D','d']: self.Networks_Proxy_Discard() else: try: if int(ans) <= 1 or int(ans) > 12: print 'Incorrect input.' continue except: print 'Incorrect input' continue else: i = int(ans) val = raw_input('Enter new value for ' + labels[(i-1)/2] + ' ['+variables[i-1].get()+']\n') conf = '' while conf not in ['y','n','Y','N']: conf = raw_input('Are you sure? (y/n)') if conf not in ['y','n','Y','N']: print 'Incorrect answer. ', if conf in ['y','Y']: variables[i-1].set(val) print self.Networks_UpdateProxy() def centerWindow(self,toplevel=None,ontheside=False): if toplevel != None: toplevel.update_idletasks() sizet = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x')) sizem = tuple(int(_) for _ in self.geometry().split('+')[0].split('x')) x = self.winfo_x() + sizem[0]/2 - sizet[0]/2 y = self.winfo_y() + sizem[1]/2 - sizet[1]/2 if ontheside: x = self.winfo_x() + sizem[0] y = self.winfo_y() #- sizet[1]/2 toplevel.geometry("%dx%d+%d+%d" % (sizet + (x, y))) else: self.update_idletasks() w = self.winfo_screenwidth() h = self.winfo_screenheight() size = tuple(int(_) for _ in self.geometry().split('+')[0].split('x')) x = w/2 - size[0]/2 y = h/2 - size[1]/2 self.geometry("%dx%d+%d+%d" % (size + (x, y))) def ClearMenu(self): self.MenuEnablerFunc.set('') for i in range(self.MenuItemMax*100): try: exec("self.MenuItem"+str(i)+".destroy()") except: pass try: self.MenuItem111.destroy() self.MenuItem112.destroy() self.MenuItem113.destroy() except: pass #enablervars for i in range(self.MenuItemMax): exec("self.MenuItem"+str(i)+"Switch = Tkinter.IntVar()") exec("self.MenuItem"+str(i)+"Switch.set(2)") exec("self.MenuItem"+str(i)+"Switch.trace_variable('w',self.callbackMenuItemSwitch)") self.UpdateSetup() def Menu_Prev(self,name,command): name = "Back" exec("self.MenuItem00 = Tkinter.Button(self,text='"+name+"',anchor='c',wraplength=1,command="+command+",relief=Tkinter.GROOVE,activebackground='RoyalBlue4',activeforeground='white')") self.MenuItem00.place(x=self.TableX+self.FolderX+self.PasParchX*0.1,y=self.TableY+self.FolderY+self.FolderY+self.BannerY+self.PasParchIn+(self.WindowY-2*self.TableY-3*self.FolderY-self.BannerY-2*self.PasParchIn-self.LogY)*0.51,width=self.PasParchX*0.8,height=(self.WindowY-2*self.TableY-3*self.FolderY-self.BannerY-2*self.PasParchIn-self.LogY)*0.48) self.MenuItem01 = Tkinter.Button(self,text='Main Menu',anchor='c',wraplength=1,command=self.Menu_Main,relief=Tkinter.GROOVE,activebackground='RoyalBlue4',activeforeground='white') self.MenuItem01.place(x=self.TableX+self.FolderX+self.PasParchX*0.1,y=self.TableY+self.FolderY+self.FolderY+self.BannerY+self.PasParchIn+(self.WindowY-2*self.TableY-3*self.FolderY-self.BannerY-2*self.PasParchIn-self.LogY)*0.01,width=self.PasParchX*0.8,height=(self.WindowY-2*self.TableY-3*self.FolderY-self.BannerY-2*self.PasParchIn-self.LogY)*0.48) def Menu_Menu(self): #menu menubar = Tkinter.Menu(self) setupmenu = Tkinter.Menu(menubar, tearoff=0) setupmenu.add_command(label="New", command=self.setupFileClear) setupmenu.add_command(label="Load..", command=self.setupFileLoad) setupmenu.add_command(label="Save", command=self.setupFileSave) setupmenu.add_command(label="Save As...", command=self.setupFileSaveas) #setupmenu.add_command(label="Save a copy with modified sources...", command=self.setupFileSaveasModified) setupmenu.add_separator() setupmenu.add_command(label="Generate report", command=self.setupFileReport) setupmenu.add_separator() setupmenu.add_command(label="Run all scenarios...", command=self.RunAnalyses) menubar.add_cascade(label="Setup", menu=setupmenu) anamenu = Tkinter.Menu(menubar, tearoff=0) anamenu.add_command(label="Add New", command=self.AnalysisNoNew) anamenu.add_command(label="Delete", command=self.AnalysisNoDelete) anamenu.add_command(label="Duplicate", command=self.AnalysisNoDuplicate) anamenu.add_command(label="Duplicate without masking", command=self.AnalysisNoDuplicateNoMask) anamenu.add_separator() anamenu.add_command(label="Run current scenario...", command=self.RunAnalysis) menubar.add_cascade(label="Scenario", menu=anamenu) NetMenu = Tkinter.Menu(menubar, tearoff=0) NetMenu.add_command(label="Camera network manager...",command=self.Networks_NetworkManager) NetMenu.add_command(label="Add camera network from an online CNIF...",command=self.Networks_AddOnlineCNIF) NetMenu.add_command(label="Single directory wizard...",command=self.Networks_Wizard) NetMenu.add_command(label="Camera network proxy manager...",command=self.Networks_ProxyManager) NetMenu.add_separator() #NetMenu.add_command(label="Import camera network(s)...",command=self.Networks_Import) #NetMenu.add_command(label="Export camera network(s)...",command=self.Networks_Export) NetMenu.add_command(label="Quantity report...",command=self.CheckArchive) NetMenu.add_command(label="Download images...",command=self.DownloadArchive) NetMenu.add_command(label="Update preview images...",command=self.UpdatePreviewPictureFilesAll) menubar.add_cascade(label="Camera networks", menu=NetMenu) self.config(menu=menubar) ToolsMenu = Tkinter.Menu(menubar, tearoff=0) ToolsMenu.add_command(label="Add Plugin...",command=self.Plugins_Add) ToolsMenu.add_command(label="Remove Plugin...",command=self.Plugins_Remove) # ToolsMenu.add_command(label="Comparison tool...",command=self.Tools_Comparison) ToolsMenu.add_command(label="Georectification tool...",command=self.Tools_Georectification) menubar.add_cascade(label="Tools", menu=ToolsMenu) self.config(menu=menubar) SetMenu = Tkinter.Menu(menubar, tearoff=0) SetMenu.add_command(label="Storage Settings...",command=self.Settings_Storage) SetMenu.add_command(label="Proxy Settings...",command=self.Settings_Proxy) SetMenu.add_command(label="Connection Settings...",command=self.Settings_Connection) SetMenu.add_command(label="Processing Settings...",command=self.Settings_Processing) SetMenu.add_command(label="Auxiliary data sources...",command=self.Settings_Aux_Sources) SetMenu.add_separator() SetMenu.add_command(label="Export Settings...",command=self.Settings_Export) SetMenu.add_command(label="Import Settings...",command=self.Settings_Import) menubar.add_cascade(label="Settings", menu=SetMenu) self.config(menu=menubar) HelpMenu = Tkinter.Menu(menubar, tearoff=0) HelpMenu.add_command(label="FMIPROT on web...",command=self.WebFMIPROT) HelpMenu.add_command(label="Open user manual",command=self.ManualFileOpen) HelpMenu.add_separator() HelpMenu.add_command(label="Open log",command=self.LogOpen) HelpMenu.add_command(label="Open log file",command=self.LogFileOpen) HelpMenu.add_separator() HelpMenu.add_command(label="About...",command=self.About) HelpMenu.add_command(label="License agreement...",command=self.License) HelpMenu.add_command(label="MONIMET Project on web...",command=self.WebMONIMET) menubar.add_cascade(label="Help", menu=HelpMenu) self.config(menu=menubar) def Networks_NetworkManager(self): self.manager_network_window = Tkinter.Toplevel(self,padx=10,pady=10) self.manager_network_window.grab_set() self.manager_network_window.wm_title('Network Manager') self.manager_network_window.columnconfigure(2, minsize=100) self.manager_network_window.columnconfigure(3, minsize=100) self.manager_network_window.columnconfigure(4, minsize=100) self.manager_network_window.columnconfigure(5, minsize=100) self.manager_network_window.columnconfigure(6, minsize=25) self.manager_networklist = self.networklist[:] self.manager_sourcelist = self.sourcelist[:] self.manager_network_name = Tkinter.StringVar() self.manager_network_name_nxt = Tkinter.StringVar() self.manager_network_name_pre = Tkinter.StringVar() self.manager_network_protocol = Tkinter.StringVar() self.manager_network_host = Tkinter.StringVar() self.manager_network_username = Tkinter.StringVar() self.manager_network_password = Tkinter.StringVar() self.manager_network_file = Tkinter.StringVar() self.manager_network_id = Tkinter.StringVar() #set auto self.manager_network_localfile = Tkinter.StringVar() #set auto self.manager_network_name.set(self.manager_networklist[0]['name']) self.manager_network_name_nxt.set(self.manager_networklist[0]['name']) self.manager_network_name_pre.set(self.manager_networklist[0]['name']) self.Networks_LoadNetwork() r = 0 Tkinter.Label(self.manager_network_window,bg="RoyalBlue4",fg='white',anchor='w',text='Choose camera network').grid(sticky='w'+'e',row=r,column=1,columnspan=6) r += 1 #in func Tkinter.Button(self.manager_network_window,text='Add new camera network',command=self.Networks_AddNetwork).grid(sticky='w'+'e',row=r,column=2,columnspan=5) r += 1 Tkinter.Label(self.manager_network_window,anchor='w',text="Camera Network:").grid(sticky='w'+'e',row=r,column=1) #in func Tkinter.Button(self.manager_network_window,text='Remove',command=self.Networks_RemoveNetwork).grid(sticky='w'+'e',row=r,column=6,columnspan=1) r += 1 Tkinter.Label(self.manager_network_window,bg="RoyalBlue4",fg='white',anchor='w',text='Edit camera network parameters').grid(sticky='w'+'e',row=r,column=1,columnspan=6) r += 1 Tkinter.Label(self.manager_network_window,anchor='w',text="Network name:").grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_network_window,textvariable=self.manager_network_name).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_network_window,text='?',command=lambda: tkMessageBox.showinfo('Network Manager','Name of the network can be edited here. It should not be same as or similar (e.g. Helsinki North, HelsinkiNorth, Helsinki-North etc.) to any other camera network name. The manage will warn you in such case.\n')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_network_window,anchor='w',text='CNIF Communication Protocol:').grid(sticky='w'+'e',row=r,column=1) Tkinter.OptionMenu(self.manager_network_window,self.manager_network_protocol,'FTP','HTTP','HTTPS','LOCAL').grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_network_window,text='?',command=lambda: tkMessageBox.showinfo('Network Manager','The communication protocol to reach CNIF. If the CNIF is/will be in this computer, select LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_network_window,anchor='w',text='CNIF Host:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_network_window,textvariable=self.manager_network_host).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_network_window,text='?',command=lambda: tkMessageBox.showinfo('Network Manager','Host address of the server that bears CNIF. \nDo not include the protocol here. For example, do not enter \'ftp://myserver.com\' but enter \'myserver.com\' instead.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_network_window,anchor='w',text='Username for host:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_network_window,textvariable=self.manager_network_username).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_network_window,text='?',command=lambda: tkMessageBox.showinfo('Network Manager','Username for the host that bears CNIF, if applicable.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_network_window,anchor='w',text='Password for host:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_network_window,textvariable=self.manager_network_password).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_network_window,text='?',command=lambda: tkMessageBox.showinfo('Network Manager','Password for the username for the host that bears CNIF, if applicable.\nIf \'*\' is used, the program will ask for the password each time it is trying to connect to the host. For security, prefer \'*\', because that information is saved in a file in your local disk.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_network_window,anchor='w',text='Path to CNIF:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_network_window,textvariable=self.manager_network_file).grid(sticky='w'+'e',row=r,column=2,columnspan=3) Tkinter.Button(self.manager_network_window,text='Browse...',command=self.Networks_BrowseCNIF).grid(sticky='w'+'e',row=r,column=5) Tkinter.Button(self.manager_network_window,text='?',command=lambda: tkMessageBox.showinfo('Network Manager','The path to the CNIF and filename of the CNIF. For example, \'mycameranetwork/mycnif.tsvx\'. If the protocol is LOCAL (i.e. CNIF is in this computer) use browse to find the file.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_network_window,bg="RoyalBlue4",fg='white',anchor='w',text='Edit sources and CNIF').grid(sticky='w'+'e',row=r,column=1,columnspan=6) r += 1 Tkinter.Button(self.manager_network_window,text='Read CNIF and load cameras...',command=self.Networks_ReadCNIF).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_network_window,text='?',command=lambda: tkMessageBox.showinfo('Network Manager','Reads CNIF to add the cameras of the network to the program.\nIf you are creating a new network and do not have a CNIF yet, do not use that option, but use \'Set up cameras and create/update CNIF\' instead.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Button(self.manager_network_window,text='Set up cameras and create/update CNIF...',command=self.Networks_SetUpSources).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_network_window,text='?',command=lambda: tkMessageBox.showinfo('Network Manager','Opens \'Edit sources\' window to add/remove/edit cameras in the camera network.\nIf you are creating a new network and do not have a CNIF yet, use that option, set up your cameras and export/save CNIF.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_network_window,anchor='w',text='').grid(sticky='w'+'e',row=r,column=1) Tkinter.Button(self.manager_network_window,bg="darkgreen",fg='white',text='Save changes',command=self.Networks_Network_Save).grid(sticky='w'+'e'+'s'+'n',row=r,column=2,columnspan=2,rowspan=2) Tkinter.Button(self.manager_network_window,bg="brown",fg='white',text='Discard changes',command=self.Networks_Network_Discard).grid(sticky='w'+'e'+'s'+'n',row=r,column=4,columnspan=2,rowspan=2) self.centerWindow(self.manager_network_window) def Networks_SetUpSources(self): if self.Networks_UpdateNetwork(): self.Networks_SourceManager() def modifySourcesInSetup(self,setup): for s,scenario in enumerate(setup): self.modify_source_window = Tkinter.Toplevel(self,padx=10,pady=10) self.modify_source_window.grab_set() self.modify_source_window.wm_title('Edit Sources') self.modify_source_window.columnconfigure(2, minsize=100) self.modify_source_window.columnconfigure(3, minsize=100) self.modify_source_window.columnconfigure(4, minsize=100) self.modify_source_window.columnconfigure(5, minsize=100) self.modify_source_window.columnconfigure(6, minsize=25) self.modify_source_source = deepcopy(scenario['source']) self.modify_source_name = Tkinter.StringVar() self.modify_source_protocol = Tkinter.StringVar() self.modify_source_host = Tkinter.StringVar() self.modify_source_username = Tkinter.StringVar() self.modify_source_password = Tkinter.StringVar() self.modify_source_path = Tkinter.StringVar() self.modify_source_filenameformat = Tkinter.StringVar() self.modifySourcesInSetup_loadSource() r = 0 r += 1 Tkinter.Label(self.modify_source_window,bg="RoyalBlue4",fg='white',anchor='w',text='Edit camera parameters').grid(sticky='w'+'e',row=r,column=1,columnspan=6) r += 1 Tkinter.Label(self.modify_source_window,anchor='w',text="Camera name:").grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.modify_source_window,textvariable=self.modify_source_name).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.modify_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Name of the camera can be edited here. It should not be same as or similar (e.g. Helsinki North, HelsinkiNorth, Helsinki-North etc.) to any other camera name. The manage will warn you in such case.\n')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.modify_source_window,anchor='w',text='Camera Communication Protocol:').grid(sticky='w'+'e',row=r,column=1) Tkinter.OptionMenu(self.modify_source_window,self.modify_source_protocol,'FTP','HTTP','HTTPS','LOCAL').grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.modify_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','The communication protocol to fetch camera images. If the images are/will be in this computer, select LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.modify_source_window,anchor='w',text='Image archive Host:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.modify_source_window,textvariable=self.modify_source_host).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.modify_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Host address of the server that bears the images. \nDo not include the protocol here. For example, do not enter \'ftp://myserver.com\' but enter \'myserver.com\' instead.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.modify_source_window,anchor='w',text='Username for host:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.modify_source_window,textvariable=self.modify_source_username).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.modify_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Username for the host that bears the images, if applicable.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.modify_source_window,anchor='w',text='Password for host:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.modify_source_window,textvariable=self.modify_source_password).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.modify_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Password for the username for the host that bears the images, if applicable.\nIf \'*\' is used, the program will ask for the password each time it is trying to connect to the host. For security, prefer \'*\', because that information is saved in a file in your local disk.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.modify_source_window,anchor='w',text='Path to images:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.modify_source_window,textvariable=self.modify_source_path).grid(sticky='w'+'e',row=r,column=2,columnspan=3) Tkinter.Button(self.modify_source_window,text='Browse...',command=self.Networks_BrowseImages).grid(sticky='w'+'e',row=r,column=5) Tkinter.Button(self.modify_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','The path of the image directory. For example, \'mycameranetwork/mycnif.tsvx\'. If the protocol is LOCAL (i.e. CNIF is in this computer) use browse to find the file.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.modify_source_window,anchor='w',text='File name convention of images:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.modify_source_window,textvariable=self.modify_source_filenameformat).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.modify_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','File name convention is how the files are named according to the time of the image. For example, if the file name convention is \'researchsite_1_north_%Y_%m_%d_%H:%M:%S.jpg\' and an image is named as \'researchsite_1_north_2016_09_24_18:27:05.jpg\', then the time that the image taken is 24 September 2016 18:27:05. Do not forget to include the extension (e.g. \'.jpg\', \'.png\'). For the meanings of time directives, refer to the user manual or visit https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.modify_source_window,anchor='w',text='').grid(sticky='w'+'e',row=r,column=1) Tkinter.Button(self.modify_source_window,bg="darkgreen",fg='white',text='Save and continue',command=self.modify_source_window.destroy).grid(sticky='w'+'e'+'s'+'n',row=r,column=2,columnspan=2,rowspan=2) Tkinter.Button(self.modify_source_window,bg="brown",fg='white',text='Discard changes',command=self.modifySourcesInSetup_loadSource).grid(sticky='w'+'e'+'s'+'n',row=r,column=4,columnspan=2,rowspan=2) self.centerWindow(self.modify_source_window) self.modify_source_window.wait_window() source = deepcopy(self.modify_source_source) source['name'] = self.modify_source_name.get() source['protocol'] = self.modify_source_protocol.get() source['host'] = self.modify_source_host.get() source['username'] = self.modify_source_username.get() source['password'] = self.modify_source_password.get() source['path'] = self.modify_source_path.get() source['filenameformat'] = self.modify_source_filenameformat.get() setup[s]['source'] = deepcopy(source) return setup def modifySourcesInSetup_loadSource(self): self.modify_source_name.set(self.modify_source_source['name']) self.modify_source_protocol.set(self.modify_source_source['protocol']) self.modify_source_host.set(self.modify_source_source['host']) self.modify_source_username.set(self.modify_source_source['username']) self.modify_source_password.set(self.modify_source_source['password']) self.modify_source_path.set(self.modify_source_source['path']) self.modify_source_filenameformat.set(self.modify_source_source['filenameformat']) def Networks_SourceManager(self): #self.manager_network_window.grab_release() self.manager_source_window = Tkinter.Toplevel(self,padx=10,pady=10) self.manager_source_window.grab_set() self.manager_source_window.wm_title('Edit Sources') self.manager_source_window.columnconfigure(2, minsize=100) self.manager_source_window.columnconfigure(3, minsize=100) self.manager_source_window.columnconfigure(4, minsize=100) self.manager_source_window.columnconfigure(5, minsize=100) self.manager_source_window.columnconfigure(6, minsize=25) self.manager_source_name = Tkinter.StringVar() self.manager_source_name_nxt = Tkinter.StringVar() self.manager_source_name_pre = Tkinter.StringVar() self.manager_source_protocol = Tkinter.StringVar() self.manager_source_host = Tkinter.StringVar() self.manager_source_username = Tkinter.StringVar() self.manager_source_password = Tkinter.StringVar() self.manager_source_path = Tkinter.StringVar() self.manager_source_filenameformat = Tkinter.StringVar() if len(sources.listSources(self.Message,self.manager_sourcelist,self.manager_network_name_nxt.get())) == 0: self.Networks_AddSource() self.manager_source_name.set(sources.getSource(self.Message,self.manager_sourcelist,self.manager_network_name_nxt.get(),'network')['name']) self.manager_source_name_nxt.set(sources.getSource(self.Message,self.manager_sourcelist,self.manager_network_name_nxt.get(),'network')['name']) self.manager_source_name_pre.set(sources.getSource(self.Message,self.manager_sourcelist,self.manager_network_name_nxt.get(),'network')['name']) self.Networks_LoadSource() r = 0 r += 1 Tkinter.Label(self.manager_source_window,bg="RoyalBlue4",fg='white',anchor='w',text='Edit cameras in the network').grid(sticky='w'+'e',row=r,column=1,columnspan=6) r += 1 #in func Tkinter.Button(self.manager_source_window,text='Add new camera',command=self.Networks_AddSource).grid(sticky='w'+'e',row=r,column=2,columnspan=2) Tkinter.Button(self.manager_source_window,text='Duplicate camera',command=self.Networks_DuplicateSource).grid(sticky='w'+'e',row=r,column=4,columnspan=2) Tkinter.Button(self.manager_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Add a new camera with default parameters or duplicate the current camera with a different name.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_source_window,anchor='w',text="Camera:").grid(sticky='w'+'e',row=r,column=1) #in func Tkinter.Button(self.manager_source_window,text='Remove',command=self.Networks_RemoveSource).grid(sticky='w'+'e',row=r,column=6,columnspan=1) r += 1 Tkinter.Label(self.manager_source_window,bg="RoyalBlue4",fg='white',anchor='w',text='Edit camera parameters').grid(sticky='w'+'e',row=r,column=1,columnspan=6) r += 1 Tkinter.Label(self.manager_source_window,anchor='w',text="Camera name:").grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_source_window,textvariable=self.manager_source_name).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Name of the camera can be edited here. It should not be same as or similar (e.g. Helsinki North, HelsinkiNorth, Helsinki-North etc.) to any other camera name. The manage will warn you in such case.\n')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_source_window,anchor='w',text='Camera Communication Protocol:').grid(sticky='w'+'e',row=r,column=1) Tkinter.OptionMenu(self.manager_source_window,self.manager_source_protocol,'FTP','HTTP','HTTPS','LOCAL').grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','The communication protocol to fetch camera images. If the images are/will be in this computer, select LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_source_window,anchor='w',text='Image archive Host:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_source_window,textvariable=self.manager_source_host).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Host address of the server that bears the images. \nDo not include the protocol here. For example, do not enter \'ftp://myserver.com\' but enter \'myserver.com\' instead.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_source_window,anchor='w',text='Username for host:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_source_window,textvariable=self.manager_source_username).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Username for the host that bears the images, if applicable.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_source_window,anchor='w',text='Password for host:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_source_window,textvariable=self.manager_source_password).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Password for the username for the host that bears the images, if applicable.\nIf \'*\' is used, the program will ask for the password each time it is trying to connect to the host. For security, prefer \'*\', because that information is saved in a file in your local disk.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_source_window,anchor='w',text='Path to images:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_source_window,textvariable=self.manager_source_path).grid(sticky='w'+'e',row=r,column=2,columnspan=3) Tkinter.Button(self.manager_source_window,text='Browse...',command=self.Networks_BrowseImages).grid(sticky='w'+'e',row=r,column=5) Tkinter.Button(self.manager_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','The path of the image directory.')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_source_window,anchor='w',text='File name convention of images:').grid(sticky='w'+'e',row=r,column=1) Tkinter.Entry(self.manager_source_window,textvariable=self.manager_source_filenameformat).grid(sticky='w'+'e',row=r,column=2,columnspan=4) Tkinter.Button(self.manager_source_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','File name convention is how the files are named according to the time of the image. For example, if the file name convention is \'researchsite_1_north_%Y_%m_%d_%H:%M:%S.jpg\' and an image is named as \'researchsite_1_north_2016_09_24_18:27:05.jpg\', then the time that the image taken is 24 September 2016 18:27:05. Do not forget to include the extension (e.g. \'.jpg\', \'.png\'). For the meanings of time directives, refer to the user manual or visit https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior')).grid(sticky='w'+'e',row=r,column=6) r += 1 Tkinter.Label(self.manager_source_window,anchor='w',text='').grid(sticky='w'+'e',row=r,column=1) Tkinter.Button(self.manager_source_window,bg="darkgreen",fg='white',text='Save changes',command=self.Networks_Source_Save).grid(sticky='w'+'e'+'s'+'n',row=r,column=2,columnspan=2,rowspan=2) Tkinter.Button(self.manager_source_window,bg="brown",fg='white',text='Discard changes',command=self.Networks_Source_Discard).grid(sticky='w'+'e'+'s'+'n',row=r,column=4,columnspan=2,rowspan=2) self.centerWindow(self.manager_source_window) def Networks_CheckNetwork(self): errors = 'There is an error with the parameters of the camera network. Please fix it to continue:\n' #name if parsers.validateName(self.manager_network['name']).lower() != parsers.validateName(self.manager_network_name_pre.get()).lower(): for network in self.manager_networklist: if parsers.validateName(network['name']).lower() == parsers.validateName(self.manager_network['name']).lower() or parsers.validateName(network['localfile']) == parsers.validateName(self.manager_network['localfile']): errors += 'There is already a network with the same or too similar name. Name of the network should be unique.\n' tkMessageBox.showwarning('Invalid parameters',errors) return False #connection if self.manager_network['protocol'] == 'LOCAL': if self.manager_network['username'] != None and self.manager_network['password'] != None and self.manager_network['host'] != None: errors += 'Host, username and password can not be defined if the protocol is LOCAL.\n' tkMessageBox.showwarning('Invalid parameters',errors) return False else: if self.manager_network['host'] == None: errors += 'At least host should be defined if the protocol is '+self.manager_network['protocol']+'.\n' tkMessageBox.showwarning('Invalid parameters',errors) return False if self.manager_network['username'] == None and self.manager_network['password'] != None and self.manager_network['host'] != None: errors += 'If password is defined, username can not be undefined.\n' tkMessageBox.showwarning('Invalid parameters',errors) return False return True def Networks_CheckSource(self): errors = 'There is an error with the parameters of the camera network. Please fix it to continue:\n' #name if parsers.validateName(self.manager_source['name']).lower() != parsers.validateName(self.manager_source_name_pre.get()).lower(): for source in sources.getSources(self.Message,self.manager_sourcelist,self.manager_network_name_pre.get(),'network'): if parsers.validateName(source['name']).lower() == parsers.validateName(self.manager_source['name']).lower(): errors += 'There is already a source with the same or too similar name in the same network. Name of the source should be unique. Click ? next to the field for more information.\n' tkMessageBox.showwarning('Invalid parameters',errors) return False #connection if self.manager_source['protocol'] == 'LOCAL': if self.manager_source['username'] != None and self.manager_source['password'] != None and self.manager_source['host'] != None: errors += 'Host, username and password can not be defined if the protocol is LOCAL.\n' tkMessageBox.showwarning('Invalid parameters',errors) return False else: if self.manager_source['host'] == None: errors += 'At least host should be defined if the protocol is '+self.manager_source['protocol']+'.\n' tkMessageBox.showwarning('Invalid parameters',errors) return False if self.manager_source['username'] == None and self.manager_source['password'] != None and self.manager_source['host'] != None: errors += 'If password is defined, username can not be undefined.\n' tkMessageBox.showwarning('Invalid parameters',errors) return False return True def Networks_UpdateNetworkLists(self,*args): try: self.manager_network_widget1.destroy() self.manager_network_widget2.destroy() except: pass networks_to_show = [] for network in sources.listNetworks(self.Message,self.manager_networklist): if 'temporary' not in sources.getSource(self.Message,self.manager_networklist,network) or not sources.getSource(self.Message,self.manager_networklist,network)['temporary']: networks_to_show.append(network) self.manager_network_widget1 = Tkinter.OptionMenu(self.manager_network_window,self.manager_network_name_nxt,*networks_to_show,command=self.Networks_UpdateNetwork).grid(sticky='w'+'e',row=2,column=2,columnspan=4) self.manager_network_widget2 = Tkinter.Label(self.manager_network_window,anchor='w',text='Number of camera networks: ' + str(len(networks_to_show))).grid(sticky='w'+'e',row=1,column=1) def Networks_UpdateSourceLists(self,*args): try: self.manager_source_widget1.destroy() self.manager_source_widget2.destroy() except: pass self.manager_source_widget1 = Tkinter.OptionMenu(self.manager_source_window,self.manager_source_name_nxt,*sources.listSources(self.Message,self.manager_sourcelist,self.manager_network_name.get()),command=self.Networks_UpdateSource).grid(sticky='w'+'e',row=3,column=2,columnspan=4) self.manager_source_widget2 = Tkinter.Label(self.manager_source_window,anchor='w',text='Number of cameras in network: ' + str(len(sources.listSources(self.Message,self.manager_sourcelist,self.manager_network_name.get())))).grid(sticky='w'+'e',row=2,column=1) def Networks_UpdateNetwork(self,*args): self.manager_network.update({'name':self.manager_network_name.get()}) self.manager_network.update({'protocol':self.manager_network_protocol.get()}) self.manager_network.update({'host':self.manager_network_host.get()}) self.manager_network.update({'username':self.manager_network_username.get()}) self.manager_network.update({'password':self.manager_network_password.get()}) self.manager_network.update({'file':self.manager_network_file.get()}) self.manager_network.update({'id':self.manager_network_id.get()}) self.manager_network_localfile.set(parsers.validateName(self.manager_network_name.get()).lower()+'.tsvx') self.manager_network.update({'localfile':self.manager_network_localfile.get()}) if self.manager_network['host'] == '': self.manager_network.update({'host':None}) if self.manager_network['username'] == '': self.manager_network.update({'username':None}) if self.manager_network['username'] == '*': self.manager_network.update({'username':'*'+parsers.validateName(self.manager_network['protocol']+self.manager_network['host']).lower()+'*username*'}) if self.manager_network['password'] == '': self.manager_network.update({'password':None}) if self.manager_network['password'] == '*': self.manager_network.update({'password':'*'+parsers.validateName(self.manager_network['protocol']+self.manager_network['host']).lower()+'*password*'}) if self.manager_network['file'] == '': self.manager_network.update({'file':None}) ans = self.Networks_CheckNetwork() if ans: #network ok. #save network self.manager_networklist.remove(sources.getSource(self.Message,self.manager_networklist,self.manager_network_name_pre.get())) self.manager_networklist.append(self.manager_network) if self.manager_network_name.get() != self.manager_network_name_pre.get():# and self.manager_network_name_pre.get() != 'MONIMET': #if name edited self.manager_sourcelist = self.Networks_RenameNetworkSources(self.manager_sourcelist,self.manager_network_name_pre.get(),self.manager_network_name.get()) if self.manager_network_name_nxt.get() != self.manager_network_name_pre.get(): #if network switched self.manager_network_name.set(self.manager_network_name_nxt.get()) self.manager_network_name_pre.set(self.manager_network_name_nxt.get()) else: self.manager_network_name_pre.set(self.manager_network_name.get()) self.manager_network_name_nxt.set(self.manager_network_name.get()) self.Networks_LoadNetwork() else: #network not ok self.manager_network_name_nxt.set(self.manager_network_name_pre.get()) return ans def Networks_UpdateSource(self,*args): self.manager_source.update({'name':self.manager_source_name.get()}) self.manager_source.update({'network':self.manager_network_name.get()}) self.manager_source.update({'protocol':self.manager_source_protocol.get()}) self.manager_source.update({'host':self.manager_source_host.get()}) self.manager_source.update({'username':self.manager_source_username.get()}) self.manager_source.update({'password':self.manager_source_password.get()}) self.manager_source.update({'path':self.manager_source_path.get()}) self.manager_source.update({'filenameformat':self.manager_source_filenameformat.get()}) if self.manager_source['host'] == '': self.manager_source.update({'host':None}) if self.manager_source['username'] == '': self.manager_source.update({'username':None}) if self.manager_source['username'] == '*': self.manager_source.update({'username':'*'+parsers.validateName(self.manager_source['protocol']+self.manager_source['host']).lower()+'*username*'}) if self.manager_source['password'] == '': self.manager_source.update({'password':None}) if self.manager_source['password'] == '*': self.manager_source.update({'password':'*'+parsers.validateName(self.manager_source['protocol']+self.manager_source['host']).lower()+'*password*'}) #add metadata - check metadata ans = self.Networks_CheckSource() if ans: #network ok. #save network self.manager_sourcelist.remove(sources.getSource(self.Message,sources.getSources(self.Message,self.manager_sourcelist,self.manager_source_name_pre.get()),self.manager_network_name.get(),'network')) self.manager_sourcelist.append(self.manager_source) if self.manager_source_name_nxt.get() != self.manager_source_name_pre.get(): #if network switched self.manager_source_name.set(self.manager_source_name_nxt.get()) self.manager_source_name_pre.set(self.manager_source_name_nxt.get()) else: self.manager_source_name_pre.set(self.manager_source_name.get()) self.manager_source_name_nxt.set(self.manager_source_name.get()) self.Networks_LoadSource() else: #network not ok self.manager_source_name_nxt.set(self.manager_source_name_pre.get()) return ans def Networks_LoadNetwork(self,*args): self.manager_network = deepcopy(sources.getSource(self.Message,self.manager_networklist,self.manager_network_name.get())) self.manager_network_protocol.set(self.manager_network['protocol']) if self.manager_network['host'] != None: self.manager_network_host.set(self.manager_network['host']) else: self.manager_network_host.set('') if self.manager_network['username'] != None: if self.manager_network['username'] == '*'+parsers.validateName(self.manager_network['protocol']+self.manager_network['host']).lower()+'*username*': self.manager_network_username.set('*') else: self.manager_network_username.set(self.manager_network['username']) else: self.manager_network_username.set('') if self.manager_network['password'] != None: if self.manager_network['password'] == '*'+parsers.validateName(self.manager_network['protocol']+self.manager_network['host']).lower()+'*password*': self.manager_network_password.set('*') else: self.manager_network_password.set(self.manager_network['password']) else: self.manager_network_password.set('') if self.manager_network['file'] != None: self.manager_network_file.set(self.manager_network['file']) else: self.manager_network_file.set('') self.manager_network_id.set(self.manager_network['id']) self.manager_network_localfile.set(self.manager_network['localfile']) self.Networks_UpdateNetworkLists() def Networks_LoadSource(self,*args): self.manager_source = deepcopy(sources.getSource(self.Message,sources.getSources(self.Message,self.manager_sourcelist,self.manager_source_name.get()),self.manager_network_name.get(),'network')) self.manager_source_protocol.set(self.manager_source['protocol']) if self.manager_source['host'] != None: self.manager_source_host.set(self.manager_source['host']) else: self.manager_source_host.set('') if self.manager_source['username'] != None: if self.manager_source['username'] == '*'+parsers.validateName(self.manager_source['protocol']+self.manager_source['host']).lower()+'*username*': self.manager_source_username.set('*') else: self.manager_source_username.set(self.manager_source['username']) else: self.manager_source_username.set('') if self.manager_source['password'] != None: if self.manager_source['password'] == '*'+parsers.validateName(self.manager_source['protocol']+self.manager_source['host']).lower()+'*password*': self.manager_source_password.set('*') else: self.manager_source_password.set(self.manager_source['password']) else: self.manager_source_password.set('') self.manager_source_path.set(self.manager_source['path']) self.manager_source_filenameformat.set(self.manager_source['filenameformat']) self.Networks_UpdateSourceLists() def Networks_AddNetwork(self): i = 1 ids = [] for network in self.manager_networklist: ids.append(network['id']) while len(ids) > 0 and str(i) in ids: i += 1 j = 1 nname = sources.listNetworks(self.Message,self.manager_networklist) for n,v in enumerate(nname): nname[n] = parsers.validateName(v).lower() while parsers.validateName('New network ' + str(j)).lower() in nname: j += 1 nname = 'New network ' + str(j) if len(sources.getSources(self.Message,self.manager_networklist,'network')) == 0 or self.Networks_UpdateNetwork(): self.manager_networklist.append({'id':str(i),'name':nname,'protocol':'LOCAL','host':None,'username':None,'password':None,'file':None,'localfile':parsers.validateName(nname).lower()+'.tsvx'}) self.manager_network_name_nxt.set(nname) self.manager_network_name_pre.set(nname) self.manager_network_name.set(nname) self.Networks_LoadNetwork() def Networks_AddSource(self): nname = sources.listSources(self.Message,self.manager_sourcelist,self.manager_network_name_pre.get()) j = 1 for n,v in enumerate(nname): nname[n] = parsers.validateName(v).lower() while parsers.validateName('New camera ' + str(j)).lower() in nname: j += 1 nname = 'New camera ' + str(j) if len(sources.getSources(self.Message,self.manager_sourcelist,self.manager_network_name_nxt.get(),'network')) == 0 or self.Networks_UpdateSource(): sourcedict = {'network':self.manager_network_name_nxt.get(),'networkid':sources.getSource(self.Message,self.manager_networklist,self.manager_network_name_nxt.get())['id'],'name':nname,'protocol':'LOCAL','host':None,'username':None,'password':None,'path':None,'filenameformat':None} #add metadata self.manager_sourcelist.append(sourcedict) self.manager_source_name_nxt.set(nname) if len(sources.getSources(self.Message,self.manager_sourcelist,self.manager_network_name_nxt.get(),'network')) > 1: if self.Networks_UpdateSource(): self.Networks_LoadSource() else: self.manager_source_name_pre.set(nname) self.manager_source_name.set(nname) self.Networks_LoadSource() def Networks_DuplicateSource(self): if self.Networks_UpdateSource(): sourcedict = deepcopy(self.manager_source) nname = sources.listSources(self.Message,self.manager_sourcelist,self.manager_network_name_pre.get()) j = 1 for n,v in enumerate(nname): nname[n] = parsers.validateName(v).lower() while parsers.validateName('New camera ' + str(j)).lower() in nname: j += 1 nname = 'New camera ' + str(j) sourcedict.update({'name':nname}) self.manager_sourcelist.append(sourcedict) self.manager_source_name_nxt.set(nname) self.Networks_UpdateSource() self.Networks_LoadSource() def Networks_RemoveNetwork(self): self.manager_networklist.remove(sources.getSource(self.Message,self.manager_networklist,self.manager_network_name_nxt.get())) self.manager_sourcelist = self.Networks_RenameNetworkSources(self.manager_sourcelist,self.manager_network['name'],None) if len(self.manager_networklist) > 0: self.manager_network_name.set(self.manager_networklist[0]['name']) self.manager_network_name_pre.set(self.manager_networklist[0]['name']) self.manager_network_name_nxt.set(self.manager_networklist[0]['name']) self.Networks_LoadNetwork() else: self.Networks_AddNetwork() def Networks_RenameNetworkSources(self,sourcelist,oldname,newname): #or remove (newname=None) removelist = [] if newname == None: for s,source in enumerate(sourcelist): if source['network'] == oldname: removelist.append(source) for source in removelist: sourcelist.remove(source) else: for s,source in enumerate(sourcelist): if source['network'] == oldname: sourcelist[s].update({'network':newname}) return sourcelist def Networks_RemoveSource(self): self.manager_sourcelist.remove(sources.getSource(self.Message,sources.getSources(self.Message,self.manager_sourcelist,self.manager_source_name_nxt.get()),self.manager_network_name.get(),'network')) try: self.manager_source_name_nxt.set(sources.getSource(self.Message,self.manager_sourcelist,self.manager_network_name.get(),'network')['name']) self.manager_source_name_pre.set(self.manager_source_name_nxt.get()) self.manager_source_name.set(self.manager_source_name_nxt.get()) self.Networks_LoadSource() except: self.Networks_AddSource() def Networks_BrowseCNIF(self): if self.manager_network_protocol.get() == 'LOCAL': self.file_opt = options = {} options['defaultextension'] = '.tsvx' options['filetypes'] = [ ('Extended tab seperated value files', '.tsvx'),('all files', '.*')] options['title'] = 'Select CNIF...' ans = tkFileDialog.askopenfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) self.manager_network_file.set(ans) else: tkMessageBox.showwarning('Browse CNIF','CNIF can only be browsed if the protocol is LOCAL (if the file is in the local computer).') def Networks_BrowseImages(self): if self.manager_source_protocol.get() == 'LOCAL': self.file_opt = options = {} options['title'] = 'Select the directory to the images...' ans = tkFileDialog.askdirectory(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) self.manager_source_path.set(ans) else: tkMessageBox.showwarning('Browse directory to the images','Directory to the images can only be browsed if the protocol is LOCAL (if the images are in the local computer).') def Networks_ReadCNIF(self): self.manager_network['file'] = self.manager_network_file.get() if self.manager_network['file'] == None:# or not os.path.exists(self.manager_network['file']): tkMessageBox.showwarning('Fail', self.manager_network['name'] + ' CNIF can not be found or not set up. Check network parameters') return False if self.Networks_UpdateNetwork(): f = fetchers.fetchFile(self,self.Message,TmpDir, self.manager_network['localfile'], self.manager_network['protocol'],self.manager_network['host'], self.manager_network['username'], self.manager_network['password'], self.manager_network['file'], self.proxy, self.connection) if f is False: tkMessageBox.showwarning('Fail','Can not fetch or download CNIF. Check network parameters. If protocol is FTP, HTTP or HTTPS, check proxy settings and internet connection.') return False else: n = sources.readTSVx(os.path.join(TmpDir,f)) if not self.manager_network['name'] in sources.listNetworks(self.Message,self.manager_networklist): new_net = deepcopy(self.manager_network) i = 1 ids = [] for network in self.manager_networklist: ids.append(network['id']) while len(ids) > 0 and str(i) in ids: i += 1 new_net.update({'id':str(i)}) self.manager_networklist.append(new_net) self.Message.set(self.manager_network['name']+' added to the camera networks.') for source in n: if source['name'] in sources.listSources(self.Message,self.manager_sourcelist,self.manager_network['name']): self.manager_sourcelist.remove(sources.getSource(self.Message,sources.getSources(self.Message,self.manager_sourcelist,self.manager_network['name'],'network'),source['name'])) self.Message.set(source['name'] + ' is removed from the camera network '+self.manager_network['name']) source.update({'networkid':sources.getSource(self.Message,self.manager_networklist,self.manager_network['name'])['id'],'network':self.manager_network['name']}) self.manager_sourcelist.append(source) self.Message.set(source['name']+'is added to the camera network: ' + self.manager_network['name']) self.Networks_LoadNetwork() tkMessageBox.showwarning('Read CNIF',str(len(n)) + ' cameras found in the CNIF and added/replaced to the camera network '+self.manager_network['name']+'.') else: return False def Networks_Network_Discard(self): if tkMessageBox.askyesno('Discard changes','Changes in all camera networks will be discarded. Are you sure?'): self.manager_networklist = self.networklist[:] self.manager_sourcelist = self.sourcelist[:] self.manager_network_name.set(self.manager_networklist[0]['name']) self.manager_network_name_nxt.set(self.manager_networklist[0]['name']) self.manager_network_name_pre.set(self.manager_networklist[0]['name']) self.Networks_LoadNetwork() self.manager_network_window.grab_set() self.manager_network_window.lift() def Networks_Network_Save(self): if self.Networks_UpdateNetwork(): if tkMessageBox.askyesno('Save changes','Changes will be permanent. Are you sure?'): dictlist = deepcopy(self.manager_networklist[:]) for d,dict in enumerate(dictlist): if isinstance(dictlist[d]['password'],str) and dictlist[d]['password'] == '*'+validateName(dictlist[d]['protocol']+dictlist[d]['host']).lower()+'*password*': dictlist[d]['password'] = '*' if isinstance(dictlist[d]['username'],str) and dictlist[d]['username'] == '*'+validateName(dictlist[d]['protocol']+dictlist[d]['host']).lower()+'*username*': dictlist[d]['username'] = '*' if dictlist[d]['file'] == None:# or (dictlist[d]['protocol'] == 'LOCAL' and not os.path.exists(dictlist[d]['file'])): tkMessageBox.showwarning('Fail', dictlist[d]['name'] + ' CNIF can not be found or not set up. Check network parameters') return False self.networklist = deepcopy(self.manager_networklist[:]) sourcelist_pre = deepcopy(self.sourcelist) self.sourcelist = deepcopy(self.manager_sourcelist[:]) if self.NetworkNameVariable.get() not in sources.listNetworks(self.Message,self.networklist): self.NetworkNameVariable.set(self.networklist[0]['name']) sources.writeTSVx(NetworklistFile,dictlist) self.manager_network_window.destroy() self.lift() self.makeDirStorage() self.migrateStorage(self.imagespath.get(),sourcelist_pre,self.imagespath.get(),self.sourcelist) if self.ActiveMenu.get() == "Camera": self.Menu_Main_Camera() def Networks_Source_Discard(self): if tkMessageBox.askyesno('Discard changes','Changes in all cameras will be discarded. Are you sure?'): self.manager_sourcelist = self.sourcelist[:] self.manager_source_name.set(sources.getSource(self.Message,self.manager_sourcelist,self.manager_network_name.get(),'network')['name']) self.manager_source_name_nxt.set(sources.getSource(self.Message,self.manager_sourcelist,self.manager_network_name.get(),'network')['name']) self.manager_source_name_pre.set(sources.getSource(self.Message,self.manager_sourcelist,self.manager_network_name.get(),'network')['name']) self.Networks_LoadSource() self.manager_source_window.grab_set() self.manager_source_window.lift() def Networks_Source_Save(self): if self.Networks_UpdateSource(): dictlist = deepcopy(sources.getSources(self.Message,self.manager_sourcelist,self.manager_network_name.get(),'network')) for d,dict in enumerate(dictlist): del dictlist[d]['networkid'] if isinstance(dictlist[d]['password'],str) and dictlist[d]['password'] == '*'+validateName(dictlist[d]['protocol']+dictlist[d]['host']).lower()+'*password*': dictlist[d]['password'] = '*' if isinstance(dictlist[d]['username'],str) and dictlist[d]['username'] == '*'+validateName(dictlist[d]['protocol']+dictlist[d]['host']).lower()+'*username*': dictlist[d]['username'] = '*' if self.manager_network_protocol.get() == 'LOCAL': tkMessageBox.showinfo('Save changes','Program now will export the CNIF. Select the location you want to keep it. CNIF should not be removed before removing the camera network from the camera manager.') else: tkMessageBox.showinfo('Save changes','Program now will export the CNIF. Upload it to the host \''+self.manager_network_host.get()+'\' under directory \'' +os.path.split(self.manager_network_file.get())[0]+ ' \'with the name \''+os.path.split(self.manager_network_file.get())[1]+'\'. Notice that for HTTP connections, it might take some time until the updated file is readable.') self.file_opt = options = {} options['defaultextension'] = '.tsvx' options['filetypes'] = [ ('Extended tab seperated value files', '.tsvx'),('all files', '.*')] options['title'] = 'Set filename to export CNIF to...' ans = tkFileDialog.asksaveasfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) sources.writeTSVx(ans,dictlist) if self.manager_network_protocol.get() == 'LOCAL': self.manager_network_file.set(ans) self.manager_source_window.destroy() self.manager_network_window.grab_set() self.manager_network_window.lift() def Networks_AddOnlineCNIF(self): self.manager_network_addonline_window = Tkinter.Toplevel(self,padx=10,pady=10) self.manager_network_addonline_window.grab_set() self.manager_network_addonline_window.wm_title('Add camera network') self.manager_network_addonline_window.columnconfigure(1,minsize=self.MenuX) self.manager_network_nname = Tkinter.StringVar() self.manager_network_link = Tkinter.StringVar() self.manager_network_user = Tkinter.StringVar() self.manager_network_pass = Tkinter.StringVar() r = 0 Tkinter.Label(self.manager_network_addonline_window,anchor='w',text='Camera network name:').grid(sticky='w'+'e',row=r,column=1,columnspan=2) r += 1 Tkinter.Button(self.manager_network_addonline_window,text='?',width=1,command=lambda: tkMessageBox.showinfo('Network Manager','A name for the camera network to be added. The name should be different than the ones already exist.')).grid(sticky='w'+'e',row=r,column=2) Tkinter.Entry(self.manager_network_addonline_window,textvariable=self.manager_network_nname).grid(sticky='w'+'e',row=r,column=1) r += 1 Tkinter.Label(self.manager_network_addonline_window,anchor='w',text='Link to CNIF:').grid(sticky='w'+'e',row=r,column=1,columnspan=2) r += 1 Tkinter.Button(self.manager_network_addonline_window,text='?',width=1,command=lambda: tkMessageBox.showinfo('Network Manager','Hyperlink to the CNIF, e.g. http://johnsnetwork.com/network/cnif.tsvx , ftp://myftpserver.com/mycams/cnif.tsvx , http://192.168.23.5/cnif.tsvx)')).grid(sticky='w'+'e',row=r,column=2) Tkinter.Entry(self.manager_network_addonline_window,textvariable=self.manager_network_link).grid(sticky='w'+'e',row=r,column=1) r += 1 Tkinter.Label(self.manager_network_addonline_window,anchor='w',text='Username for host:').grid(sticky='w'+'e',row=r,column=1,columnspan=2) r += 1 Tkinter.Button(self.manager_network_addonline_window,text='?',width=1,command=lambda: tkMessageBox.showinfo('Network Manager','Username for the host that bears CNIF, if applicable.')).grid(sticky='w'+'e',row=r,column=2) Tkinter.Entry(self.manager_network_addonline_window,textvariable=self.manager_network_user).grid(sticky='w'+'e',row=r,column=1) r += 1 Tkinter.Label(self.manager_network_addonline_window,anchor='w',text='Password for host:').grid(sticky='w'+'e',row=r,column=1,columnspan=2) r += 1 Tkinter.Button(self.manager_network_addonline_window,text='?',width=1,command=lambda: tkMessageBox.showinfo('Network Manager','Password for the username for the host that bears CNIF, if applicable.\nIf \'*\' is used, the program will ask for the password each time it is trying to connect to the host. For security, prefer \'*\', because that information is saved in a file in your local disk.')).grid(sticky='w'+'e',row=r,column=2) Tkinter.Entry(self.manager_network_addonline_window,textvariable=self.manager_network_pass).grid(sticky='w'+'e',row=r,column=1) r += 1 Tkinter.Button(self.manager_network_addonline_window,text='Fetch CNIF and add the network...',width=50,command=self.Networks_AddOnlineCNIF_ReadCNIF).grid(sticky='w'+'e',row=r,column=1,columnspan=2) self.centerWindow(self.manager_network_addonline_window) def Networks_AddOnlineCNIF_ReadCNIF(self): if 'http://' not in self.manager_network_link.get() and 'https://' not in self.manager_network_link.get() and 'ftp://' not in self.manager_network_link.get(): tkMessageBox.showwarning('Incorrect link','Link is incorrect. Click ? for help.') return False elif len(self.manager_network_link.get().split('/'))<3 or '.' not in self.manager_network_link.get().split('/')[2]: tkMessageBox.showwarning('Incorrect link','Link is incorrect. Click ? for help.') return False self.Networks_NetworkManager() self.manager_network_window.geometry("0x0") self.manager_network_addonline_window.lift() self.Networks_AddNetwork() if 'http://' in self.manager_network_link.get() or 'https://' in self.manager_network_link.get(): self.manager_network_host.set(self.manager_network_link.get().split('/')[2]) self.manager_network_file.set(self.manager_network_link.get().replace(self.manager_network_link.get().split('/')[0]+'//'+self.manager_network_link.get().split('/')[2]+'/','')) self.manager_network_protocol.set('HTTP') if 'ftp://' in self.manager_network_link.get(): self.manager_network_host.set(self.manager_network_link.get().split('/')[2]) self.manager_network_file.set(self.manager_network_link.get().replace(self.manager_network_link.get().split('/')[0]+'//'+self.manager_network_link.get().split('/')[2],'')) self.manager_network_protocol.set('FTP') self.manager_network_name.set(self.manager_network_nname.get()) self.manager_network_username.set(self.manager_network_user.get()) self.manager_network_password.set(self.manager_network_pass.get()) if self.Networks_CheckNetwork(): if self.Networks_ReadCNIF() is not False: self.Networks_Network_Save() self.manager_network_window.destroy() self.manager_network_addonline_window.destroy() else: self.Networks_RemoveNetwork() self.manager_network_window.destroy() self.manager_network_addonline_window.lift() self.manager_network_addonline_window.grab_set() def Networks_Wizard(self): tkMessageBox.showinfo('Single directory wizard','This wizard helps you to add a directory of camera images in your computer to FMIPROT or remove one you have added before. ') self.wizard = Tkinter.Toplevel(self,padx=10,pady=10) var = Tkinter.IntVar() self.wizard.grab_set() self.wizard.wm_title('Single directory wizard') Tkinter.Button(self.wizard ,text='I want to add a directory',command=lambda : var.set(1)).grid(sticky='w'+'e',row=1,column=1,columnspan=1) Tkinter.Button(self.wizard ,text='I want to remove a directory',command=lambda : var.set(2)).grid(sticky='w'+'e',row=2,column=1,columnspan=1) var.trace_variable('w',self.Networks_Wizard_destroy) self.centerWindow(self.wizard) self.wizard.wait_window() if var.get() == 1: #add directory protocol = 'LOCAL' tkMessageBox.showinfo('Single directory wizard','Please find the directory that you have the images inside with the next dialog.') file_opt = options = {} options['title'] = '(Choose) Custom directory' datetimelist = [] while datetimelist == []: filepath = str(os.path.normpath(tkFileDialog.askdirectory(**file_opt))) if filepath == '.': tkMessageBox.showinfo('Single directory wizard','You have cancelled the wizard.') return False else: self.wizard = Tkinter.Toplevel(self,padx=10,pady=10) var = Tkinter.StringVar() self.wizard.grab_set() self.wizard.wm_title('Single directory wizard') Tkinter.Label(self.wizard ,anchor='w',wraplength=500,text='Enter the file name convention of the image files. File name convention is how the files are named according to the time of the image.\nFor example, if the file name convention is \'researchsite_1_north_%Y_%m_%d_%H:%M:%S.jpg\' and an image is named as \'researchsite_1_north_2016_09_24_18:27:05.jpg\', then the time that the image taken is 24 September 2016 18:27:05. Do not forget to include the extension (e.g. \'.jpg\', \'.png\').\nFor the meanings of time directives (e.g. %Y, %m) refer the user manual or https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior .').grid(sticky='w',row=1,column=1,columnspan=1) Tkinter.Entry(self.wizard ,textvariable=var).grid(sticky='w'+'e',row=2,column=1,columnspan=1) Tkinter.Button(self.wizard ,text='OK',command=self.Networks_Wizard_destroy).grid(sticky='w'+'e',row=4,column=1,columnspan=1) self.centerWindow(self.wizard) self.wizard.wait_window() filenameformat = str(var.get()) imglist = os.listdir(filepath) for i, img in enumerate(imglist): try: datetimelist.append(parsers.strptime2(str(img),filenameformat)[0]) except: pass if len(datetimelist) == 0: tkMessageBox.showinfo('Single directory wizard','Wizard can not find any images that fits the file name conventions in the directory. Select the directoy and input the filename convention again to continue.') continue else: tkMessageBox.showinfo('Single directory wizard',str(len(datetimelist)) + ' images are found in the directory, from '+ str(min(datetimelist))+' to '+ str(max(datetimelist))+'.') var3 = Tkinter.BooleanVar() var3.set(False) while not var3.get(): self.wizard = Tkinter.Toplevel(self,padx=10,pady=10) var1 = Tkinter.StringVar() var2 = Tkinter.StringVar() self.wizard.grab_set() self.wizard.wm_title('Single directory wizard') Tkinter.Label(self.wizard ,anchor='w',wraplength=500,text='Enter a camera network name and camera name for the images.').grid(sticky='w',row=1,column=1,columnspan=1) Tkinter.Label(self.wizard ,wraplength=500,text='Network name').grid(sticky='w',row=2,column=1,columnspan=1) Tkinter.Entry(self.wizard ,textvariable=var1).grid(sticky='w'+'e',row=3,column=1,columnspan=1) Tkinter.Label(self.wizard ,anchor='w',wraplength=500,text='Camera name').grid(sticky='w',row=4,column=1,columnspan=1) Tkinter.Entry(self.wizard ,textvariable=var2).grid(sticky='w'+'e',row=5,column=1,columnspan=1) Tkinter.Button(self.wizard ,text='OK',command=self.Networks_Wizard_destroy).grid(sticky='w'+'e',row=6,column=1,columnspan=1) Tkinter.Button(self.wizard ,text='Cancel',command=lambda : var3.set(True)).grid(sticky='w'+'e',row=7,column=1,columnspan=1) self.centerWindow(self.wizard) self.wizard.wait_window() nets = sources.listNetworks(self.Message,self.networklist) nets_ = nets[:] for n,net in enumerate(nets): nets[n] = parsers.validateName(net).lower() if parsers.validateName(var1.get()).lower() in nets: if sources.getSource(self.Message,self.networklist,nets_[nets.index(parsers.validateName(var1.get()).lower())])['protocol'] == 'LOCAL': sours = sources.listSources(self.Message,self.sourcelist,nets_[nets.index(parsers.validateName(var1.get()).lower())]) sours_ = sours[:] for s, sour in enumerate(sours): sours[s] = parsers.validateName(sour).lower() if parsers.validateName(var2.get()).lower() in sours: tkMessageBox.showwarning('Single directory wizard','The network name you have entered is already existing or too similar with '+nets_[nets.index(parsers.validateName(var1.get()).lower())]+' and the camera name you have entered is already existing or too similar with '+sours_[sours.index(parsers.validateName(var2.get()).lower())]+'. Please change either the network name or the camera name.') else: if tkMessageBox.askyesno('Single directory wizard','The network name you have entered is already existing or too similar with '+nets_[nets.index(parsers.validateName(var1.get()).lower())]+'. Do you want to add the images as a camera to that network?'): #add source to network sourcedict = {'network':nets_[nets.index(parsers.validateName(var1.get()).lower())],'networkid':sources.getSource(self.Message,self.networklist,nets_[nets.index(parsers.validateName(var1.get()).lower())])['id'],'name':var2.get(),'protocol':'LOCAL','host':None,'username':None,'password':None,'path':filepath,'filenameformat':filenameformat} self.sourcelist.append(sourcedict) parsers.writeTSVx(sources.getSource(self.Message,self.networklist,nets_[nets.index(parsers.validateName(var1.get()).lower())])['file'],sources.getSources(self.Message,self.sourcelist,sourcedict['network'],'network')) tkMessageBox.showinfo('Single directory wizard','The camera is added to the network.') break else: tkMessageBox.showwarning('Single directory wizard','Please enter a different camera network name.') else: 'Single directory wizard','The network name you have entered is already existing or too similar with '+nets_[nets.index(parsers.validateName(var1.get()).lower())]+'. But the CNIF of this network is not stored in this computer. Thus FMIPROT can not add the directory to that network. Please enter a different camera network name.' else: #add network and source i = 1 ids = [] for network in self.networklist: ids.append(network['id']) while len(ids) > 0 and str(i) in ids: i += 1 networkdict = {'id':str(i),'name':var1.get(),'protocol':'LOCAL','host':None,'username':None,'password':None,'file':os.path.join(SourceDir,parsers.validateName(var1.get()).lower()+'.tsvx'),'localfile':parsers.validateName(var1.get()).lower()+'.tsvx'} self.networklist.append(networkdict) sourcedict = {'network':var1.get(),'networkid':sources.getSource(self.Message,self.networklist,var1.get())['id'],'name':var2.get(),'protocol':'LOCAL','host':None,'username':None,'password':None,'path':filepath,'filenameformat':filenameformat} self.sourcelist.append(sourcedict) parsers.writeTSVx(NetworklistFile,self.networklist) parsers.writeTSVx(networkdict['file'],[sourcedict]) tkMessageBox.showinfo('Single directory wizard','The camera network is created and the camera is added to the network.') break if var.get() == 2: #remove directory removelist = [] removelist_names = [] for network in self.networklist: if network['protocol'] == 'LOCAL': for source in sources.getSources(self.Message,self.sourcelist,network['name'],'network'): if source['protocol'] == 'LOCAL': removelist.append([network['name'],source['name']]) removelist_names.append(network['name']+' - '+ source['name']) if len(removelist) == 0: tkMessageBox.showinfo('Single directory wizard','There is no single-directory-type camera or camera network to be removed.') else: self.wizard = Tkinter.Toplevel(self,padx=10,pady=10) var = Tkinter.StringVar() var.set(removelist_names[0]) self.wizard.grab_set() self.wizard.wm_title('Single directory wizard') Tkinter.Label(self.wizard ,anchor='w',wraplength=500,text='Choose a camera to remove:').grid(sticky='w'+'e',row=1,column=1,columnspan=1) Tkinter.OptionMenu(self.wizard ,var,*removelist_names).grid(sticky='w'+'e',row=2,column=1,columnspan=1) Tkinter.Button(self.wizard ,text='Remove',command=self.Networks_Wizard_destroy).grid(sticky='w'+'e',row=3,column=1,columnspan=1) Tkinter.Button(self.wizard ,text='Cancel',command=lambda : var.set('')).grid(sticky='w'+'e',row=4,column=1,columnspan=1) self.centerWindow(self.wizard) self.wizard.wait_window() if var.get() != '': rem = removelist[removelist_names.index(var.get())] if len(sources.getSources(self.Message,self.sourcelist,rem[0],'network')) == 1: self.networklist.remove(sources.getSource(self.Message,self.networklist,rem[0])) self.sourcelist.remove(sources.getSource(self.Message,sources.getSources(self.Message,self.sourcelist,rem[0],'network'),rem[1])) else: self.sourcelist.remove(sources.getSource(self.Message,sources.getSources(self.Message,self.sourcelist,rem[0],'network'),rem[1])) parsers.writeTSVx(sources.getSource(self.Message,self.networklist,rem[0])['file'],sources.getSources(self.Message,self.sourcelist,rem[0],'network')) parsers.writeTSVx(NetworklistFile,self.networklist) tkMessageBox.showinfo('Single directory wizard',var.get() + ' removed.') def Networks_Wizard_destroy(self,*args): self.wizard.destroy() self.lift() def Networks_Import(self): return False def Networks_Export(self): return False def Networks_ProxyManager(self): self.manager_proxy_window = Tkinter.Toplevel(self,padx=10,pady=10) self.manager_proxy_window.grab_set() self.manager_proxy_window.wm_title('Camera Network Proxy Manager') self.manager_proxy_window.columnconfigure(1, minsize=20) self.manager_proxy_window.columnconfigure(2, minsize=40) self.manager_proxy_window.columnconfigure(3, minsize=20) self.manager_proxy_window.columnconfigure(4, minsize=20) self.manager_proxy_window.columnconfigure(5, minsize=100) self.manager_proxy_window.columnconfigure(6, minsize=100) self.manager_proxy_window.columnconfigure(7, minsize=25) self.manager_proxylist = self.proxylist[:] self.manager_proxy_number = Tkinter.IntVar() self.manager_proxy_number.set(1) self.manager_proxy_number.trace('w',self.Networks_LoadProxy) self.manager_proxy_protocol = Tkinter.StringVar() self.manager_proxy_host = Tkinter.StringVar() self.manager_proxy_username = Tkinter.StringVar() self.manager_proxy_password = Tkinter.StringVar() self.manager_proxy_path = Tkinter.StringVar() self.manager_proxy_filenameformat = Tkinter.StringVar() self.manager_proxy_protocol_target = Tkinter.StringVar() self.manager_proxy_host_target = Tkinter.StringVar() self.manager_proxy_username_target = Tkinter.StringVar() self.manager_proxy_password_target = Tkinter.StringVar() self.manager_proxy_path_target = Tkinter.StringVar() self.manager_proxy_filenameformat_target = Tkinter.StringVar() r = 0 r += 1 Tkinter.Label(self.manager_proxy_window,bg="RoyalBlue4",fg='white',anchor='w',text='Edit camera network proxies').grid(sticky='w'+'e',row=r,column=1,columnspan=7) r += 1 Tkinter.Button(self.manager_proxy_window,text='<',command=self.Networks_PrevProxy).grid(sticky='w'+'e',row=r,column=1) Tkinter.Label(self.manager_proxy_window,anchor='w',text="Proxy No:").grid(sticky='w'+'e',row=r,column=2) Tkinter.Label(self.manager_proxy_window,anchor='e',textvariable=self.manager_proxy_number).grid(sticky='w'+'e',row=r,column=3) Tkinter.Button(self.manager_proxy_window,text='>',command=self.Networks_NextProxy).grid(sticky='w'+'e',row=r,column=4) Tkinter.Button(self.manager_proxy_window,text='Add',command=self.Networks_AddProxy).grid(sticky='w'+'e',row=r,column=5) Tkinter.Button(self.manager_proxy_window,text='Duplicate',command=self.Networks_DuplicateProxy).grid(sticky='w'+'e',row=r,column=6) Tkinter.Button(self.manager_proxy_window,text='Remove',command=self.Networks_RemoveProxy).grid(sticky='w'+'e',row=r,column=7) r += 1 Tkinter.Label(self.manager_proxy_window,bg="RoyalBlue4",fg='white',anchor='w',text='Edit proxy parameters').grid(sticky='w'+'e',row=r,column=1,columnspan=7) r += 1 Tkinter.Label(self.manager_proxy_window,anchor='w',text='Parameter').grid(sticky='w'+'e',row=r,column=1,columnspan=4) Tkinter.Label(self.manager_proxy_window,anchor='w',text='Original value').grid(sticky='w'+'e',row=r,column=5,columnspan=1) Tkinter.Label(self.manager_proxy_window,anchor='w',text='Proxy value').grid(sticky='w'+'e',row=r,column=6,columnspan=1) Tkinter.Button(self.manager_proxy_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','When reaching images of a camera with parameters on the "Original value" side, instead the parameters in "Proxy value" will be used. Use "*" as a wildcard to include any value for a parameter. Check the user manual for detailed information and examples.')).grid(sticky='w'+'e',row=r,column=7) r += 1 Tkinter.Label(self.manager_proxy_window,anchor='w',text='Camera Communication Protocol:').grid(sticky='w'+'e',row=r,column=1,columnspan=4) Tkinter.OptionMenu(self.manager_proxy_window,self.manager_proxy_protocol,'FTP','HTTP','HTTPS','LOCAL').grid(sticky='w'+'e',row=r,column=5) Tkinter.OptionMenu(self.manager_proxy_window,self.manager_proxy_protocol_target,'FTP','HTTP','HTTPS','LOCAL').grid(sticky='w'+'e',row=r,column=6) Tkinter.Button(self.manager_proxy_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','The communication protocol to fetch camera images. If the images are/will be in this computer, select LOCAL.')).grid(sticky='w'+'e',row=r,column=7) r += 1 Tkinter.Label(self.manager_proxy_window,anchor='w',text='Image archive Host:').grid(sticky='w'+'e',row=r,column=1,columnspan=4) Tkinter.Entry(self.manager_proxy_window,textvariable=self.manager_proxy_host).grid(sticky='w'+'e',row=r,column=5) Tkinter.Entry(self.manager_proxy_window,textvariable=self.manager_proxy_host_target).grid(sticky='w'+'e',row=r,column=6) Tkinter.Button(self.manager_proxy_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Host address of the server that bears the images. \nDo not include the protocol here. For example, do not enter \'ftp://myserver.com\' but enter \'myserver.com\' instead.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=7) r += 1 Tkinter.Label(self.manager_proxy_window,anchor='w',text='Username for host:').grid(sticky='w'+'e',row=r,column=1,columnspan=4) Tkinter.Entry(self.manager_proxy_window,textvariable=self.manager_proxy_username).grid(sticky='w'+'e',row=r,column=5) Tkinter.Entry(self.manager_proxy_window,textvariable=self.manager_proxy_username_target).grid(sticky='w'+'e',row=r,column=6) Tkinter.Button(self.manager_proxy_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Username for the host that bears the images, if applicable.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=7) r += 1 Tkinter.Label(self.manager_proxy_window,anchor='w',text='Password for host:').grid(sticky='w'+'e',row=r,column=1,columnspan=4) Tkinter.Entry(self.manager_proxy_window,textvariable=self.manager_proxy_password).grid(sticky='w'+'e',row=r,column=5) Tkinter.Entry(self.manager_proxy_window,textvariable=self.manager_proxy_password_target).grid(sticky='w'+'e',row=r,column=6) Tkinter.Button(self.manager_proxy_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','Password for the username for the host that bears the images, if applicable.\nIf \'*\' is used, the program will ask for the password each time it is trying to connect to the host. For security, prefer \'*\', because that information is saved in a file in your local disk.\nLeave empty if protocol is LOCAL.')).grid(sticky='w'+'e',row=r,column=7) r += 1 Tkinter.Label(self.manager_proxy_window,anchor='w',text='Path to images:').grid(sticky='w'+'e',row=r,column=1,columnspan=4) Tkinter.Entry(self.manager_proxy_window,textvariable=self.manager_proxy_path).grid(sticky='w'+'e',row=r,column=5) Tkinter.Entry(self.manager_proxy_window,textvariable=self.manager_proxy_path_target).grid(sticky='w'+'e',row=r,column=6) Tkinter.Button(self.manager_proxy_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','The path of the image directory.')).grid(sticky='w'+'e',row=r,column=7) r += 1 Tkinter.Label(self.manager_proxy_window,anchor='w',text='File name convention of images:').grid(sticky='w'+'e',row=r,column=1,columnspan=4) Tkinter.Entry(self.manager_proxy_window,textvariable=self.manager_proxy_filenameformat).grid(sticky='w'+'e',row=r,column=5) Tkinter.Entry(self.manager_proxy_window,textvariable=self.manager_proxy_filenameformat_target).grid(sticky='w'+'e',row=r,column=6) Tkinter.Button(self.manager_proxy_window,text='?',command=lambda: tkMessageBox.showinfo('Edit Sources','File name convention is how the files are named according to the time of the image. For example, if the file name convention is \'researchsite_1_north_%Y_%m_%d_%H:%M:%S.jpg\' and an image is named as \'researchsite_1_north_2016_09_24_18:27:05.jpg\', then the time that the image taken is 24 September 2016 18:27:05. Do not forget to include the extension (e.g. \'.jpg\', \'.png\'). For the meanings of time directives, refer to the user manual or visit https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior')).grid(sticky='w'+'e',row=r,column=7) r += 1 Tkinter.Label(self.manager_proxy_window,anchor='w',text='').grid(sticky='w'+'e',row=r,column=1) Tkinter.Button(self.manager_proxy_window,bg="darkgreen",fg='white',text='Save changes',command=self.Networks_Proxy_Save).grid(sticky='w'+'e'+'s'+'n',row=r,column=5,rowspan=2) Tkinter.Button(self.manager_proxy_window,bg="brown",fg='white',text='Discard changes',command=self.Networks_Proxy_Discard).grid(sticky='w'+'e'+'s'+'n',row=r,column=6,rowspan=2) self.centerWindow(self.manager_proxy_window) self.manager_proxy_window.grab_set() self.manager_proxy_window.lift() self.Networks_LoadProxy() if len(self.proxylist) == 0: tkMessageBox.showinfo('Camera Network Proxy Manager','There is no camera network proxy defined yet. In the manager window, a proxy with default values to edit is added. To quit editing, simply close the manager window.') self.manager_proxy_window.grab_set() self.manager_proxy_window.lift() def Networks_LoadProxy(self,*args): if len(self.manager_proxylist) == 0: self.Networks_AddProxy() self.manager_proxy_protocol.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol']) self.manager_proxy_host.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['host']) self.manager_proxy_username.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['username']) self.manager_proxy_password.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['password']) self.manager_proxy_path.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['path']) self.manager_proxy_filenameformat.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['filenameformat']) self.manager_proxy_protocol_target.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol_proxy']) self.manager_proxy_host_target.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['host_proxy']) self.manager_proxy_username_target.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['username_proxy']) self.manager_proxy_password_target.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['password_proxy']) self.manager_proxy_path_target.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['path_proxy']) self.manager_proxy_filenameformat_target.set(self.manager_proxylist[self.manager_proxy_number.get()-1]['filenameformat_proxy']) def Networks_UpdateProxy(self,*args): if len(self.manager_proxylist) != 0: self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol'] = self.manager_proxy_protocol.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['host'] = self.manager_proxy_host.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['username'] = self.manager_proxy_username.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['password'] = self.manager_proxy_password.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['path'] = self.manager_proxy_path.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['filenameformat'] = self.manager_proxy_filenameformat.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol_proxy'] = self.manager_proxy_protocol_target.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['host_proxy'] = self.manager_proxy_host_target.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['username_proxy'] = self.manager_proxy_username_target.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['password_proxy'] = self.manager_proxy_password_target.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['path_proxy'] = self.manager_proxy_path_target.get() self.manager_proxylist[self.manager_proxy_number.get()-1]['filenameformat_proxy'] = self.manager_proxy_filenameformat_target.get() proxyvalid = True errors = 'There is an error with the parameters of the camera network proxy. Please fix it to continue:\n' if (self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol'] == 'LOCAL' and self.manager_proxylist[self.manager_proxy_number.get()-1]['username'] != '' and self.manager_proxylist[self.manager_proxy_number.get()-1]['password'] != '' and self.manager_proxylist[self.manager_proxy_number.get()-1]['host'] != '') or (self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol_proxy'] == 'LOCAL' and self.manager_proxylist[self.manager_proxy_number.get()-1]['username_proxy'] != '' and self.manager_proxylist[self.manager_proxy_number.get()-1]['password_proxy'] != None and self.manager_proxylist[self.manager_proxy_number.get()-1]['host_proxy'] != ''): errors += 'Host, username and password can not be defined (have to be empty) if the protocol is LOCAL.\n' proxyvalid = False if (self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol'] != 'LOCAL' and self.manager_proxylist[self.manager_proxy_number.get()-1]['host'] == '') or (self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol_proxy'] != 'LOCAL' and self.manager_proxylist[self.manager_proxy_number.get()-1]['host_proxy'] == ''): errors += 'Host can not be empty if protocol is HTTP or FTP.' proxyvalid = False if self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol_proxy'] and self.manager_proxylist[self.manager_proxy_number.get()-1]['host'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['host_proxy'] and self.manager_proxylist[self.manager_proxy_number.get()-1]['username'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['username_proxy'] and self.manager_proxylist[self.manager_proxy_number.get()-1]['password'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['password_proxy'] and self.manager_proxylist[self.manager_proxy_number.get()-1]['path'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['path_proxy'] and self.manager_proxylist[self.manager_proxy_number.get()-1]['filenameformat'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['filenameformat_proxy']: errors += 'Proxy is identical with the original camera parameters. Proxy is useless.' proxyvalid = False if self.manager_proxylist[self.manager_proxy_number.get()-1]['filenameformat'] == '' or self.manager_proxylist[self.manager_proxy_number.get()-1]['filenameformat_proxy'] == '': errors += 'File name convention of the images can not be empty.' for i,proxy in enumerate(self.manager_proxylist): if i == self.manager_proxy_number.get() -1: continue if proxy['protocol'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['protocol'] and proxy['host'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['host'] and proxy['username'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['username'] and proxy['password'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['password'] and proxy['path'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['path'] and proxy['filenameformat'] == self.manager_proxylist[self.manager_proxy_number.get()-1]['filenameformat']: errors += 'A proxy for identical camera network parameters exists. (Proxy no: '+str(i+1)+')' proxyvalid = False break if not proxyvalid: tkMessageBox.showerror('Invalid parameters',errors) self.manager_proxy_window.grab_set() self.manager_proxy_window.lift() return False else: return True else: return True def Networks_NextProxy(self): if self.Networks_UpdateProxy(): if self.manager_proxy_number.get() == len(self.manager_proxylist): self.manager_proxy_number.set(1) else: self.manager_proxy_number.set(self.manager_proxy_number.get()+1) self.Networks_LoadProxy() def Networks_PrevProxy(self): if self.Networks_UpdateProxy(): if self.manager_proxy_number.get() == 1: self.manager_proxy_number.set(len(self.manager_proxylist)) else: self.manager_proxy_number.set(self.manager_proxy_number.get()-1) self.Networks_LoadProxy() def Networks_AddProxy(self): if self.Networks_UpdateProxy(): proxydict = {'protocol':'FTP','host':'*','username':'*','password':'*','path':'*','filenameformat':'*','protocol_proxy':'FTP','host_proxy':'*','username_proxy':'*','password_proxy':'*','path_proxy':'*','filenameformat_proxy':'*'} if len(self.manager_proxylist) != 0 and self.manager_proxylist[self.manager_proxy_number.get()-1] == proxydict: self.Message.set('No need to add a camera network proxy. It is the default which needs to be edited.') else: self.manager_proxylist.append(proxydict) self.Message.set('New camera network proxy added.') self.manager_proxy_number.set(len(self.manager_proxylist)) self.Networks_LoadProxy() def Networks_DuplicateProxy(self): if self.Networks_UpdateProxy(): proxydict = {'protocol':'FTP','host':'*','username':'*','password':'*','path':'*','filenameformat':'*','protocol_proxy':'FTP','host_proxy':'*','username_proxy':'*','password_proxy':'*','path_proxy':'*','filenameformat_proxy':'*'} if self.manager_proxylist[self.manager_proxy_number.get()-1] == proxydict: self.Message.set('No need to duplicate the camera network proxy. It is the default which needs to be edited.') else: self.manager_proxylist.append(self.manager_proxylist[self.manager_proxy_number.get()-1]) self.Message.set('Camera network proxy duplicated.') self.manager_proxy_number.set(len(self.manager_proxylist)) self.Networks_LoadProxy() def Networks_RemoveProxy(self): del self.manager_proxylist[self.manager_proxy_number.get()-1] self.Message.set('Camera network proxy removed.') if len(self.manager_proxylist) == 0: self.Networks_AddProxy() else: self.manager_proxy_number.set(len(self.manager_proxylist)) self.Networks_LoadProxy() def Networks_Proxy_Discard(self): if tkMessageBox.askyesno('Discard changes','Changes in all camera network proxies will be discarded. Are you sure?'): self.manager_proxylist = self.proxylist[:] if len(self.manager_proxylist) != 0: self.manager_proxy_number.set(len(self.manager_proxylist)) self.Networks_LoadProxy() self.manager_proxy_window.grab_set() self.manager_proxy_window.lift() def Networks_Proxy_Save(self): if self.Networks_UpdateProxy(): if tkMessageBox.askyesno('Save changes','Changes will be permanent. Are you sure?'): sources.writeTSVx(ProxylistFile,self.manager_proxylist) self.Message.set('Camera network proxy list saved.') self.proxylist = deepcopy(self.manager_proxylist) self.manager_proxy_window.grab_set() self.manager_proxy_window.lift() self.makeDirStorage() def Settings_Storage(self): self.ClearMenu() self.ActiveMenu.set("Storage Settings") self.Menu_Prev("Main Menu","self.cancelStorage") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Local image directory:",anchor="c",bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.6,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 3 self.MenuItem2 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Browse...",anchor="c",command=self.selectImagespath) self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.7,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Entry(self,textvariable=self.imagespath,justify="center") self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Results directory:",anchor="c",bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.6,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem5 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Browse...",anchor="c",command=self.selectResultspath) self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.7,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem6 = Tkinter.Entry(self,textvariable=self.resultspath,justify="center") self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem11 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Save",anchor="c",command=self.saveStorage) self.MenuItem11.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem8 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Cancel",anchor="c",command=self.cancelStorage) self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem9 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Defaults",anchor="c",command=self.defaultsStorage) self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def updateStorage(self): self.storage = {'results_path': self.resultspath.get(),'images_path': self.imagespath.get()} def cancelStorage(self): self.resultspath.set(self.storage['results_path']) self.imagespath.set(self.storage['images_path']) self.Menu_Main() def defaultsStorage(self): from definitions import ImagesDir, ResultsSeparate, ResultsDir self.resultspath.set(ResultsDir) self.imagespath.set(ImagesDir) def saveStorage(self): imagespath_pre = deepcopy(self.storage['images_path']) self.updateStorage() storage = deepcopy(self.storage) parsers.writeSettings(storage,settingsFile,self.Message) self.makeDirStorage() self.migrateStorage(imagespath_pre,self.sourcelist,self.imagespath.get(),self.sourcelist) self.Menu_Main() def makeDirStorage(self): #create image directories if not os.path.exists(self.resultspath.get()): os.makedirs(self.resultspath.get()) if not os.path.exists(self.imagespath.get()): os.makedirs(self.imagespath.get()) for source_ in self.sourcelist: source = sources.getProxySource(self.Message,source_,self.proxylist) if source['protocol'] != 'LOCAL': if 'temporary' in source and source['temporary']: local_path = os.path.join(os.path.join(TmpDir,'tmp_images'),validateName(source['network'])+'-'+source['protocol']+'-'+source['host']+'-'+validateName(source['username'])+'-'+validateName(source['path'])) if not os.path.exists(local_path): os.makedirs(local_path) else: local_path = os.path.join(self.imagespath.get(),source['networkid']+'-'+validateName(source['network'])) if not os.path.exists(local_path): os.makedirs(local_path) local_path = os.path.join(local_path,validateName(source['name'])) if not os.path.exists(local_path): os.makedirs(local_path) def migrateStorage(self,imgdirp,sourcelistp,imgdirn,sourcelistn): if imgdirp != imgdirn and sourcelistp==sourcelistn: #coming from storage settings title = 'Image storage directory change' message = 'Image storage directory is changed. The images that are downloaded before from HTTP and FTP based networks are still in the old directory.\n' message += 'Images should be moved from the old directory to the new directory to be used in analysis. If not moved, images will be downloaded again from camera networks if downloading of images is enabled. ' message += 'Unfornately, this operation is not supported by the toolbox at the moment. Thus, user should do it manually.\n' message += 'Old image storage directory:\n' message += imgdirp message += '\nNew image storage directory:\n' message += imgdirn tkMessageBox.showwarning(title,message) def Settings_Proxy(self): self.ClearMenu() self.ActiveMenu.set("Proxy Settings") self.Menu_Prev("Main Menu","self.cancelProxy") self.callbackCameraName(0,0) NItems = 9 space = 0.02 Item = 1 self.MenuItem2 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Leave fields blank to disable proxy",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 2 self.MenuItem5 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="HTTP Proxy:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem6 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="HTTPS Proxy:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem7 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="FTP Proxy:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem10 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Save",anchor="c",command=self.saveProxy) self.MenuItem10.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 9 self.MenuItem8 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Cancel",anchor="c",command=self.cancelProxy) self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 9 self.MenuItem9 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Defaults",anchor="c",command=self.defaultsProxy) self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item=3 self.MenuItem0 = Tkinter.Entry(self,textvariable=self.http_proxy,justify="center") self.MenuItem0.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item=5 self.MenuItem1 = Tkinter.Entry(self,textvariable=self.https_proxy,justify="center") self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item=7 self.MenuItem3 = Tkinter.Entry(self,textvariable=self.ftp_proxy,justify="center") self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def updateProxy(self): self.proxy = {'http_proxy': self.http_proxy.get(),'https_proxy': self.https_proxy.get(),'ftp_proxy': self.ftp_proxy.get()} proxy_ = [] for k in self.proxy: if self.proxy[k] == '': proxy_.append(k) for k in proxy_: del self.proxy[k] def cancelProxy(self): if 'http_proxy' in self.proxy: self.http_proxy.set(self.proxy['http_proxy']) if 'https_proxy' in self.proxy: self.https_proxy.set(self.proxy['https_proxy']) if 'ftp_proxy' in self.proxy: self.ftp_proxy.set(self.proxy['ftp_proxy']) self.Menu_Main() def defaultsProxy(self): self.http_proxy.set('') self.https_proxy.set('') self.ftp_proxy.set('') def saveProxy(self): self.updateProxy() proxy = deepcopy(self.proxy) if 'http_proxy' not in proxy: proxy.update({'http_proxy':''}) if 'https_proxy' not in proxy: proxy.update({'https_proxy':''}) if 'ftp_proxy' not in proxy: proxy.update({'ftp_proxy':''}) parsers.writeSettings(proxy,settingsFile,self.Message) (self.networklist,self.sourcelist) = sources.readSources(self, self.proxy,self.connection, self.Message) self.Menu_Main() def Settings_Connection(self): self.ClearMenu() self.ActiveMenu.set("Connection Settings") self.Menu_Prev("Main Menu","self.cancelConnection") NItems = 9 space = 0.02 Item = 3 self.MenuItem3 = Tkinter.Checkbutton(self,variable=self.imagesdownload,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX, text="Check and download new images from the camera network server") self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem10 = Tkinter.Checkbutton(self,variable=self.ftp_passive,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text="Use passive mode for FTP connections") self.MenuItem10.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) if False: #temp until fix Item = 5 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.7,text="Number of FTP connections for download (1-10)",anchor="c",bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.7,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem2 = Tkinter.Entry(self,textvariable=self.ftp_numberofconnections,justify="center") self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.8,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.1,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem7 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Save",anchor="c",command=self.saveConnection) self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem8 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Cancel",anchor="c",command=self.cancelConnection) self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem9 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Defaults",anchor="c",command=self.defaultsConnection) self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def updateConnection(self): if int(self.ftp_numberofconnections.get()) == 0: self.ftp_numberofconnections.set(1) self.Message.set('Number of FTP connections for download can not be less than 1. It is set to 1.') if int(self.ftp_numberofconnections.get()) > 10: self.ftp_numberofconnections.set(10) self.Message.set('Number of FTP connections for download can not be more than 10. It is set to 10.') self.connection = {'ftp_passive': str(int(self.ftp_passive.get())), 'ftp_numberofconnections': str(int(self.ftp_numberofconnections.get())),'images_download': str(int(self.imagesdownload.get()))} def cancelConnection(self): self.ftp_passive.set(self.connection['ftp_passive']) self.ftp_numberofconnections.set(self.connection['ftp_numberofconnections']) self.imagesdownload.set(self.connection['images_download']) self.Menu_Main() def defaultsConnection(self): self.ftp_passive.set('1') self.ftp_numberofconnections.set('1') self.imagesdownload.set(ImagesDownload) def saveConnection(self): self.updateConnection() connection = deepcopy(self.connection) if 'ftp_passive' not in connection: connection.update({'ftp_passive':'1'}) if 'ftp_numberofconnections' not in connection: connection.update({'ftp_numberofconnections':'1'}) parsers.writeSettings(connection,settingsFile,self.Message) self.Menu_Main() def Settings_Processing(self): self.ClearMenu() self.ActiveMenu.set("Processing Settings") self.Menu_Prev("Main Menu","self.cancelProcessing") NItems = 10 space = 0.02 Item = 2 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Time zone (UTC Offset):",anchor="c",bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 3 self.MenuItem3 = Tkinter.Entry(self,textvariable=self.TimeZone,justify="center") self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem7 = Tkinter.Checkbutton(self,variable=self.TimeZoneConversion,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text="Convert time zone of timestamps") self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem4 = Tkinter.Checkbutton(self,variable=self.outputreportvariable,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text="Generate setup report with analysis results") self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem12 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Memory usage limit [MB]",anchor="c",bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem12.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem13 = Tkinter.Entry(self,textvariable=self.memorylimit,justify="center") self.MenuItem13.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem11 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Save",anchor="c",command=self.saveProcessing) self.MenuItem11.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 9 self.MenuItem8 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Cancel",anchor="c",command=self.cancelProcessing) self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 9 self.MenuItem9 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Defaults",anchor="c",command=self.defaultsProcessing) self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def updateProcessing(self): self.processing = {'timezone': self.TimeZone.get(),'convert_timezone': str(int(self.TimeZoneConversion.get())),'generate_report': str(int(self.outputreportvariable.get())),'memory_limit': str(int(self.memorylimit.get()))} def cancelProcessing(self): self.TimeZone.set(self.processing['timezone']) self.TimeZoneConversion.set(bool(int(self.processing['convert_timezone']))) self.outputreportvariable.set(bool(int(self.processing['generate_report']))) self.memorylimit.set(int(self.processing['memory_limit'])) self.Menu_Main() def defaultsProcessing(self): self.TimeZone.set('+0000') self.TimeZoneConversion.set(False) self.outputreportvariable.set(True) self.memorylimit.set(4000) def saveProcessing(self): self.updateProcessing() processing = deepcopy(self.processing) parsers.writeSettings(processing,settingsFile,self.Message) self.Menu_Main() def Settings_Aux_Sources(self): self.Win1 = Tkinter.Toplevel(self,padx=10,pady=10) self.Win1.grab_set() self.Win1.wm_title('Auxiliary data sources') self.Win1.columnconfigure(1, minsize=150*self.UnitSize) Tkinter.Label(self.Win1,text="Data sources",anchor='c').grid(sticky='w'+'e',row=1,column=1,columnspan=3) self.Win1.columnconfigure(2, minsize=150*self.UnitSize) listlen=11 scrollbar1 = Tkinter.Scrollbar(self.Win1) self.AuxSourcesList = Tkinter.Listbox(self.Win1,yscrollcommand=scrollbar1.set) scrollbar1.config(command=self.AuxSourcesList.yview) scrollbar1.grid(sticky='n'+'s',row=2,column=3,columnspan=1,rowspan=listlen) self.AuxSourcesList.grid(sticky='n'+'s'+'w'+'e',row=2,column=1,columnspan=2,rowspan=listlen) Tkinter.Button(self.Win1 ,text='Close Window',command=self.CloseWin_1).grid(sticky='w'+'e',row=6+listlen,column=1,columnspan=1) Tkinter.Button(self.Win1 ,text='Settings...',command=self.SetupSource).grid(sticky='w'+'e',row=6+listlen,column=2,columnspan=1) self.AuxSourcesList.delete(0,"end") for name in auxnamelist: self.AuxSourcesList.insert("end",name) self.centerWindow(self.Win1) self.Win1.wait_window() def CloseWin_1(self): self.Win1.destroy() self.grab_set() self.lift() def CloseWin_2(self): self.Win2.destroy() self.Win1.grab_set() self.Win1.lift() def CloseWin_3(self): self.Win3.destroy() self.Win2.grab_set() self.Win2.lift() def SetupSource(self): sname = self.AuxSourcesList.get(self.AuxSourcesList.curselection()) if len(auxlist[sname]["settings"]) == 1 and "datadir" in auxlist[sname]["settings"]: self.Win2 = Tkinter.Toplevel(self,padx=10,pady=10) self.Win2.grab_set() self.Win2.lift() self.Win2.wm_title('Reference data') self.Win2.columnconfigure(1, minsize=100*self.UnitSize) self.Win2.columnconfigure(2, minsize=100*self.UnitSize) self.Win2.columnconfigure(3, minsize=100*self.UnitSize) self.Win2.sdir = Tkinter.StringVar() self.Win2.sdir.set(auxlist[sname]["settings"]["datadir"]) self.Win2.sname = Tkinter.StringVar() self.Win2.sname.set(sname) Tkinter.Label(self.Win2,anchor='w',text='Data directory:').grid(sticky='w'+'e',row=1,column=1,columnspan=1) Tkinter.Label(self.Win2,textvariable=self.Win2.sdir,wraplength=100*self.UnitSize).grid(sticky='w',row=1,column=2,columnspan=2) Tkinter.Button(self.Win2 ,text='Cancel',command=self.CloseWin_2).grid(sticky='w'+'e',row=3,column=1,columnspan=1) Tkinter.Button(self.Win2,text='Browse...',command=self.BrowseSourceDataDir).grid(sticky='w'+'e',row=3,column=2) Tkinter.Button(self.Win2 ,text='Save',command=self.SaveSourceDataDir).grid(sticky='w'+'e',row=3,column=3,columnspan=1) self.centerWindow(self.Win2) self.Win2.wait_window() def BrowseSourceDataDir(self): self.file_opt = options = {} options['title'] = 'Select data directory...' ans = str(os.path.normpath(tkFileDialog.askdirectory(**self.file_opt))) if ans != '' and ans != '.': self.Win2.sdir.set(ans) self.Win2.grab_set() self.Win2.lift() self.Win2.geometry("") def SaveSourceDataDir(self): auxlist[self.Win2.sname.get()]["settings"]["datadir"] = self.Win2.sdir.get() settingv = {} for source in auxnamelist: for setk in auxlist[source]: settingv.update({self.Win2.sname.get()+'-datadir':self.Win2.sdir.get()}) parsers.writeSettings(settingv,settingsFile,self.Message) self.CloseWin_2() def Settings_Export(self): self.Message.set("Choosing file to export settings to...") self.file_opt = options = {} options['defaultextension'] = '.ini' options['filetypes'] = [ ('INI files', '.ini'),('all files', '.*')] options['title'] = 'Set filename to export the settings to...' ans = tkFileDialog.asksaveasfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) parsers.writeSettings(parsers.dictSettings(parsers.readSettings(settingsFile,self.Message)),ans,self.Message) self.Message.set("Settings are exported to "+ans) else: self.Message.set("Exporting settings is cancelled.") def Settings_Import(self): self.Message.set("Choosing file to import settings from...") self.file_opt = options = {} options['defaultextension'] = '.ini' options['filetypes'] = [ ('INI files', '.ini'),('all files', '.*')] options['title'] = 'Set filename to import the settings from...' ans = tkFileDialog.askopenfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) parsers.writeSettings(parsers.dictSettings(parsers.readSettings(ans,self.Message)),settingsFile,self.Message) self.Menu_Main() self.initSettings() self.Message.set("Settings are imported from "+ans) else: self.Message.set("Importing settings is cancelled.") def Plugins_Add(self): self.Message.set("Choosing plugin binary file to add.") if tkMessageBox.askyesno('Add Plugin...','Plug-ins are created by users and independent from the program. File paths of your images and file path of a mask file is passed as arguments to the plug-in binaries. If you have obtained the plug-in from somebody else, use it only of you trust it.\nDo you want to proceed?'): if os.path.sep == '/': pext = '' else: pext = '.exe' self.file_opt = options = {} if pext == '.exe': options['defaultextension'] = '.exe' options['filetypes'] = [ ('Binary files', '.exe'),('all files', '.*')] options['title'] = 'Choose plugin binary file to add...' ans = tkFileDialog.askopenfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) if os.path.splitext(ans)[1] != pext or not os.path.isfile(ans): tkMessageBox.showwarning('Error','Chosen file is not an executable binary file.') self.Message.set("Choose plugin binary file is cancelled.") return False else: incaux = False if tkMessageBox.askyesno('Add Plugin...','Does the executable need also the files in the same folder and subfolders with it, or is only the executable binary file enough?\nIf you answer \'Yes\', all files in the same directory and all subdirectories will be copied to the plugin directory! ('+PluginsDir+')'): incaux = True #test plugin self.Message.set("Testing plugin.|busy:True") for resolution in [(640,480),(1024,758),(2560,1440)]: self.Message.set("Testing for resolution: "+str(resolution)) mahotas.imsave(os.path.join(TmpDir,'plugintestimg.jpg'),np.random.randint(0,256,(resolution[1],resolution[0],3)).astype('uint8')) mask = np.random.randint(0,2,(resolution[1],resolution[0]))*255 mask = np.dstack((mask,mask,mask)).astype('uint8') mahotas.imsave(os.path.join(TmpDir,'plugintestmsk.jpg'),mask) try: pipe = subprocess.Popen([ans,os.path.join(TmpDir,'plugintestimg.jpg'),os.path.join(TmpDir,'plugintestmsk.jpg')], stdout=subprocess.PIPE) res = pipe.communicate() pipe.wait() (res, err) = (res[0],res[1]) if err is not None: self.Message.set('Error: '+err+': '+res) res = res.replace('\n','') outstr = res res = res.split(',') (res_title,res) = (res[0],res[1:]) if len(res) < 3 or len(res)%2!=0: res = False for j in range(len(res)/2): float(res[j*2+1]) self.Message.set("Testing passed. Output: "+outstr) except: self.Message.set("Testing failed. Plugin can not be added.\nPlugin output:\n"+outstr) tkMessageBox.showerror('Error',"Testing failed. Plugin can not be added.\nPlugin output:\n"+outstr) self.Message.set("Testing failed.|busy:False") return False self.Message.set("Testing complete.|busy:False") name = os.path.splitext(os.path.split(ans)[1])[0] try: if os.path.exists(os.path.join(PluginsDir,name)): shutil.rmtree(os.path.join(PluginsDir,name)) if not incaux: os.makedirs(os.path.join(PluginsDir,name)) if os.path.isfile(ans): shutil.copyfile(ans,os.path.join(PluginsDir,name,name)+pext) self.Message.set("Plugin is copied to the plugin directory.") else: shutil.copytree(os.path.split(ans)[0],os.path.join(PluginsDir,name)) self.Message.set("Plugin is copied to the plugin directory.") calculations.AddPlugin(name) if self.ActiveMenu.get() == "Analyses": self.Menu_Main_Calculations() except: tkMessageBox.showerror('Error','Problem in copying files. Check file/folder permissions.') self.Message.set('Problem in copying files.') else: self.Message.set("Choose plugin binary file is cancelled.") return False def Plugins_Remove(self): pluglist = [] for p in calcnames_en: if 'Plug-in: ' in p: pluglist.append(p.replace('Plug-in: ','')) if len(pluglist) == 0: self.Message.set('There is not any plugin to be removed.|dialog:info') return False self.plugintoremove = Tkinter.StringVar() self.plugintoremove.set(pluglist[0]) self.removeplugindialog = Tkinter.Toplevel(self,padx=10,pady=10) self.removeplugindialog.wm_title('Remove plugins') Tkinter.Label(self.removeplugindialog,text='Choose plugin to remove:').grid(sticky='w'+'e',row=1,column=1,columnspan=2) Tkinter.OptionMenu(self.removeplugindialog,self.plugintoremove,*pluglist).grid(sticky='w'+'e',row=2,column=1,columnspan=2) Tkinter.Button(self.removeplugindialog ,text='Cancel',command=self.removeplugindialog.destroy).grid(sticky='w'+'e',row=3,column=1,columnspan=1) Tkinter.Button(self.removeplugindialog ,text='OK',command=self.Plugins_Remove_Remove).grid(sticky='w'+'e',row=3,column=2,columnspan=1) self.centerWindow(self.removeplugindialog) self.removeplugindialog.grab_set() self.removeplugindialog.lift() self.removeplugindialog.wait_window() if self.ActiveMenu.get() == "Analyses": self.Menu_Main_Calculations() def Plugins_Remove_Remove(self): if os.path.exists(os.path.join(PluginsDir,self.plugintoremove.get())): try: shutil.rmtree(os.path.join(PluginsDir,self.plugintoremove.get())) self.Message.set('Files and directories that belongs to the Plug-in: '+self.plugintoremove.get()+' are removed.') except: self.Message.set('File operations problem: Files and directories that belongs to the Plug-in: '+self.plugintoremove.get()+' can not be removed. Check file/directory permissions.') tkMessageBox.showerror('Error','File operations problem: Files and directories that belongs to the Plug-in: '+self.plugintoremove.get()+' can not be removed. Check file/directory permissions.') self.removeplugindialog.lift() return False calculations.RemovePlugin(self.plugintoremove.get()) self.Message.set('Plug-in: '+self.plugintoremove.get()+' is removed from the plugin list.') tkMessageBox.showinfo('Remove plugin','Plug-in: '+self.plugintoremove.get()+' is removed.') self.removeplugindialog.destroy() self.grab_set() def Tools_Comparison(self): self.Win1 = Tkinter.Toplevel(self,padx=10,pady=10) self.Win1.grab_set() self.Win1.wm_title('Comparison tool') self.Win1.columnconfigure(2, minsize=150) self.Win1.columnconfigure(3, minsize=450) self.Win1.ProdName = Tkinter.StringVar() self.Win1.ProdName.set("FMIPROT Time series results - Snow Cover Fraction") Tkinter.Label(self.Win1,text="Product data",anchor='w').grid(sticky='w'+'e',row=1,column=2,columnspan=1) Tkinter.OptionMenu(self.Win1,self.Win1.ProdName,*auxnamelist).grid(sticky='w'+'e',row=1,column=3,columnspan=1) self.Win1.RefrName = Tkinter.StringVar() self.Win1.RefrName.set("MONIMET Visual observations - Snow Cover Fraction") Tkinter.Label(self.Win1,text="Reference data",anchor='w').grid(sticky='w'+'e',row=2,column=2,columnspan=1) Tkinter.OptionMenu(self.Win1,self.Win1.RefrName,*auxnamelist).grid(sticky='w'+'e',row=2,column=3,columnspan=1) self.Win1.ClsdName = Tkinter.StringVar() self.Win1.ClsdName.set("None") Tkinter.Label(self.Win1,text="Classification data",anchor='w').grid(sticky='w'+'e',row=3,column=2,columnspan=1) Tkinter.OptionMenu(self.Win1,self.Win1.ClsdName,*(["None"]+auxnamelist)).grid(sticky='w'+'e',row=3,column=3,columnspan=1) self.AuxSourcesComparisonType = Tkinter.StringVar() self.AuxSourcesComparisonType.set('Continuous statistics') Tkinter.Label(self.Win1,text="Comparison type:",anchor='w').grid(sticky='w'+'e',row=6,column=2,columnspan=1) Tkinter.OptionMenu(self.Win1,self.AuxSourcesComparisonType,'Binary statistics','Continuous statistics').grid(sticky='w'+'e',row=6,column=3,columnspan=1) #,'Multi-class statistics' Tkinter.Button(self.Win1 ,text='Cancel',command=self.CloseWin_1).grid(sticky='w'+'e',row=7,column=2,columnspan=1) Tkinter.Button(self.Win1 ,text='Next>',command=self.SetupComparison).grid(sticky='w'+'e',row=7,column=3,columnspan=1) self.centerWindow(self.Win1) self.Win1.wait_window() def SetupComparison(self): if auxlist[self.Win1.ProdName.get()]["metadata"]["temporal"] == "static" or auxlist[self.Win1.RefrName.get()]["metadata"]["temporal"] == "static": tkMessageBox.showerror('Comparison not applicable','Product and reference data should not be a static map.') return False if self.Win1.ClsdName.get() != "None" and auxlist[self.Win1.ClsdName.get()]["metadata"]["temporal"] != "static": tkMessageBox.showerror('Comparison not applicable','Classification data should be a static map.') return False if self.AuxSourcesComparisonType.get() == 'Binary statistics': if auxlist[self.Win1.ProdName.get()]["metadata"]["valuetype"] == "continuous" or auxlist[self.Win1.RefrName.get()]["metadata"]["valuetype"] == "continuous": tkMessageBox.showerror('Comparison not applicable','Selected data sources are not applicable for binary statistics. At least one of product and reference data should be binary.') self.Win1.lift() self.Win1.grab_set() return False if self.AuxSourcesComparisonType.get() == 'Continuous statistics': if auxlist[self.Win1.ProdName.get()]["metadata"]["valuetype"] == "binary": tkMessageBox.showerror('Comparison not applicable','Selected data sources are not applicable for continous statistics. Product data should be continous.') self.Win1.lift() self.Win1.grab_set() return False self.Win2 = Tkinter.Toplevel(self,padx=10,pady=10) self.Win2.grab_set() self.Win2.wm_title('Comparison setup') self.Win2.columnconfigure(1, minsize=100) self.Win2.columnconfigure(2, minsize=100) self.Win2.columnconfigure(3, minsize=100) self.Win2.columnconfigure(4, minsize=100) r = 1 Tkinter.Label(self.Win2,text="Choose the directory of the datasets. Default values for each data source can be set up in settings menu.",anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor).grid(sticky='w'+'e',row=r,column=1,columnspan=4) self.Win2.ProdDir = Tkinter.StringVar() self.Win2.RefrDir = Tkinter.StringVar() self.Win2.ClsdDir = Tkinter.StringVar() self.Win2.ProdDir.set(auxlist[self.Win1.ProdName.get()]["settings"]["datadir"]) self.Win2.RefrDir.set(auxlist[self.Win1.RefrName.get()]["settings"]["datadir"]) r += 1 Tkinter.Label(self.Win2,text="Product data",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ProdDir,justify="left").grid(sticky='w'+'e',row=r,column=2,columnspan=2) Tkinter.Button(self.Win2,text='Browse...',command=self.BrowseProdDir).grid(sticky='w'+'e',row=r,column=4) r += 1 Tkinter.Label(self.Win2,text="Reference data",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.RefrDir,justify="left").grid(sticky='w'+'e',row=r,column=2,columnspan=2) Tkinter.Button(self.Win2,text='Browse...',command=self.BrowseRefrDir).grid(sticky='w'+'e',row=r,column=4) if self.Win1.ClsdName.get() == "None": self.Win2.ClsdDir.set("") else: self.Win2.ClsdDir.set(auxlist[self.Win1.ClsdName.get()]["settings"]["datadir"]) r += 1 Tkinter.Label(self.Win2,text="Classification data",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ClsdDir,justify="left").grid(sticky='w'+'e',row=r,column=2,columnspan=2) Tkinter.Button(self.Win2,text='Browse...',command=self.BrowseClsdDir).grid(sticky='w'+'e',row=r,column=4) r += 1 Tkinter.Label(self.Win2,text="Choose values for comparison in the table. Use comma between multiple values and slash for value ranges as in the example.",anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor).grid(sticky='w'+'e',row=r,column=1,columnspan=4) r += 1 row_sep = deepcopy(r) Tkinter.Label(self.Win2,text="Product data",anchor='c').grid(sticky='w'+'e',row=r,column=1,columnspan=2) if auxlist[self.Win1.ProdName.get()]["metadata"]["valuetype"] == "binary": self.Win2.ValsProdTrue = Tkinter.StringVar() self.Win2.ValsProdFalse = Tkinter.StringVar() self.Win2.ValsProdTrue.set(auxlist[self.Win1.ProdName.get()]["metadata"]["truevalue"]) self.Win2.ValsProdFalse.set(auxlist[self.Win1.ProdName.get()]["metadata"]["falsevalue"]) r += 1 Tkinter.Label(self.Win2,text="True values",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsProdTrue,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="False values",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsProdFalse,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) if auxlist[self.Win1.ProdName.get()]["metadata"]["valuetype"] == "continuous": self.Win2.ValsProdRange = Tkinter.StringVar() self.Win2.ValsProdRange.set(auxlist[self.Win1.ProdName.get()]["metadata"]["valuerange"]) r += 1 Tkinter.Label(self.Win2,text="Value range",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsProdRange,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) if self.AuxSourcesComparisonType.get() == 'Binary statistics': self.Win2.ValsProdTrueMin = Tkinter.StringVar() self.Win2.ValsProdTrueMin.set((float(auxlist[self.Win1.ProdName.get()]["metadata"]["valuerange"].split('-')[1])-float(auxlist[self.Win1.ProdName.get()]["metadata"]["valuerange"].split('-')[0]))/2) self.Win2.ValsProdFalseMax = Tkinter.StringVar() self.Win2.ValsProdFalseMax.set((float(auxlist[self.Win1.ProdName.get()]["metadata"]["valuerange"].split('-')[1])-float(auxlist[self.Win1.ProdName.get()]["metadata"]["valuerange"].split('-')[0]))/2) r += 1 Tkinter.Label(self.Win2,text="True value threshold (>=)",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsProdTrueMin,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="False value threshold (>)",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsProdFalseMax,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) if self.AuxSourcesComparisonType.get() == 'Continuous statistics': self.Win2.ValsProdScale = Tkinter.StringVar() self.Win2.ValsProdScale.set(auxlist[self.Win1.ProdName.get()]["metadata"]["valuescale"]) self.Win2.ValsProdBias = Tkinter.StringVar() self.Win2.ValsProdBias.set(auxlist[self.Win1.ProdName.get()]["metadata"]["valuebias"]) r += 1 Tkinter.Label(self.Win2,text="Correction scale",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsProdScale,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="Correction bias",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsProdBias,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) r = row_sep Tkinter.Label(self.Win2,text="Reference data",anchor='c').grid(sticky='w'+'e',row=r,column=3,columnspan=2) if auxlist[self.Win1.RefrName.get()]["metadata"]["valuetype"] == "binary": self.Win2.ValsRefrTrue = Tkinter.StringVar() self.Win2.ValsRefrFalse = Tkinter.StringVar() self.Win2.ValsRefrTrue.set(auxlist[self.Win1.RefrName.get()]["metadata"]["truevalue"]) self.Win2.ValsRefrFalse.set(auxlist[self.Win1.RefrName.get()]["metadata"]["falsevalue"]) r += 1 Tkinter.Label(self.Win2,text="True values",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsRefrTrue,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="False values",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsRefrFalse,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) if auxlist[self.Win1.RefrName.get()]["metadata"]["valuetype"] == "continuous": self.Win2.ValsRefrRange = Tkinter.StringVar() self.Win2.ValsRefrRange.set(auxlist[self.Win1.RefrName.get()]["metadata"]["valuerange"]) r += 1 Tkinter.Label(self.Win2,text="Value range",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsRefrRange,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) if self.AuxSourcesComparisonType.get() == 'Binary statistics': self.Win2.ValsRefrTrueMin = Tkinter.StringVar() self.Win2.ValsRefrTrueMin.set((float(auxlist[self.Win1.RefrName.get()]["metadata"]["valuerange"].split('-')[1])-float(auxlist[self.Win1.RefrName.get()]["metadata"]["valuerange"].split('-')[0]))/2) self.Win2.ValsRefrFalseMax = Tkinter.StringVar() self.Win2.ValsRefrFalseMax.set((float(auxlist[self.Win1.RefrName.get()]["metadata"]["valuerange"].split('-')[1])-float(auxlist[self.Win1.RefrName.get()]["metadata"]["valuerange"].split('-')[0]))/2) r += 1 Tkinter.Label(self.Win2,text="True value threshold (>=)",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsRefrTrueMin,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="False value threshold (>)",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsRefrFalseMax,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) if self.AuxSourcesComparisonType.get() == 'Continuous statistics': self.Win2.ValsRefrScale = Tkinter.StringVar() self.Win2.ValsRefrScale.set(auxlist[self.Win1.RefrName.get()]["metadata"]["valuescale"]) self.Win2.ValsRefrBias = Tkinter.StringVar() self.Win2.ValsRefrBias.set(auxlist[self.Win1.RefrName.get()]["metadata"]["valuebias"]) r += 1 Tkinter.Label(self.Win2,text="Correction scale",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsRefrScale,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="Correction bias",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsRefrBias,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) self.Win2.ValsRefrInvs = Tkinter.StringVar() self.Win2.ValsRefrThrs = Tkinter.StringVar() self.Win2.ValsClsdThrs = Tkinter.StringVar() self.Win2.ValsContMatr = Tkinter.StringVar() self.Win2.ValsRefrInvs.set(auxlist[self.Win1.RefrName.get()]["metadata"]["invisvalue"]) self.Win2.ValsRefrThrs.set(auxlist[self.Win1.RefrName.get()]["metadata"]["invisthreshold"]) self.Win2.ValsContMatr.set('None') if self.Win1.ClsdName.get() != "None": self.Win2.ValsClsdThrs.set(auxlist[self.Win1.ClsdName.get()]["metadata"]["invisthreshold"]) r += 1 Tkinter.Label(self.Win2,text="Uncertain values",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsRefrInvs,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="Uncertain value threshold (>=)",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsRefrThrs,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="Choose values for the classes to be used in the contingency matrix (optional).",anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor).grid(sticky='w'+'e',row=r,column=1,columnspan=4) r += 1 Tkinter.Label(self.Win2,textvariable=self.Win2.ValsContMatr,anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=3) Tkinter.Button(self.Win2 ,text='Edit...',command=self.ContMatrEdit).grid(sticky='w'+'e',row=r,column=4,columnspan=1) if self.Win1.ClsdName.get() != "None": self.Win2.ValsClsdVals = Tkinter.StringVar() self.Win2.ValsClsdNams = Tkinter.StringVar() self.Win2.ValsClsdVals.set(auxlist[self.Win1.ClsdName.get()]["metadata"]["classvalues"]) self.Win2.ValsClsdNams.set(auxlist[self.Win1.ClsdName.get()]["metadata"]["classnames"]) r += 1 Tkinter.Label(self.Win2,text="Choose values for the classes to be used from the classification data. Use semicolon between classes, comma between multiple values and slash for value ranges as in the example.",anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor).grid(sticky='w'+'e',row=r,column=1,columnspan=4) r += 1 Tkinter.Label(self.Win2,text="Class names:",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsClsdNams,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=3) r += 1 Tkinter.Label(self.Win2,text="Class values:",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsClsdVals,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=3) r += 1 Tkinter.Label(self.Win2,text="Fraction threshold (>=)",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ValsClsdThrs,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=3) r += 1 Tkinter.Label(self.Win2,text="Choose values for resampling parameters. Resampling is done using Gaussian distribution.",anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor).grid(sticky='w'+'e',row=r,column=1,columnspan=4) self.Win2.ResampleRadiusRefr = Tkinter.StringVar() self.Win2.ResampleSigmaRefr = Tkinter.StringVar() self.Win2.ResampleRadiusRefr.set("Auto") self.Win2.ResampleSigmaRefr.set("Auto") self.Win2.ResampleRadiusClsd = Tkinter.StringVar() self.Win2.ResampleSigmaClsd = Tkinter.StringVar() self.Win2.ResampleRadiusClsd.set("Auto") self.Win2.ResampleSigmaClsd.set("Auto") self.Win2.ValsClsdOnto = Tkinter.StringVar() self.Win2.ValsClsdOnto.set('Reference data') if self.Win1.ClsdName.get() != "None": r+= 1 Tkinter.Label(self.Win2,text="Reference Data",anchor='w',justify="center").grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Label(self.Win2,text="Classification Data",anchor='w',justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="Radius of influence (m)",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=2) Tkinter.Entry(self.Win2,textvariable=self.Win2.ResampleRadiusRefr,justify="center").grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ResampleRadiusClsd,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="Sigma (See documentation) (m)",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=2) Tkinter.Entry(self.Win2,textvariable=self.Win2.ResampleSigmaRefr,justify="center").grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.ResampleSigmaClsd,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="Reproject onto",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=2) Tkinter.OptionMenu(self.Win2,self.Win2.ValsClsdOnto,*['Product data','Reference data']).grid(sticky='w'+'e',row=r,column=4,columnspan=2) else: r += 1 Tkinter.Label(self.Win2,text="Radius of influence (m)",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=2) Tkinter.Entry(self.Win2,textvariable=self.Win2.ResampleRadiusRefr,justify="center").grid(sticky='w'+'e',row=r,column=3,columnspan=2) r += 1 Tkinter.Label(self.Win2,text="Sigma (See documentation) (m)",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=2) Tkinter.Entry(self.Win2,textvariable=self.Win2.ResampleSigmaRefr,justify="center").grid(sticky='w'+'e',row=r,column=3,columnspan=2) r = 40 Tkinter.Label(self.Win2,text="Enter the spatial extent for the validation to be done in. Use slash for value ranges as in the example.",anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor).grid(sticky='w'+'e',row=r,column=1,columnspan=4) self.Win2.LatitudeRange = Tkinter.StringVar() self.Win2.LatitudeRange.set("-90/90") self.Win2.LongitudeRange = Tkinter.StringVar() self.Win2.LongitudeRange.set("-180/180") r += 1 Tkinter.Label(self.Win2,text="Latitude range (degrees)",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=2) Tkinter.Entry(self.Win2,textvariable=self.Win2.LatitudeRange,justify="center").grid(sticky='w'+'e',row=r,column=3,columnspan=2) r += 1 Tkinter.Label(self.Win2,text="Longitude range (degrees)",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=2) Tkinter.Entry(self.Win2,textvariable=self.Win2.LongitudeRange,justify="center").grid(sticky='w'+'e',row=r,column=3,columnspan=2) r += 1 self.Win2.TemporalRangeDays = Tkinter.IntVar() self.Win2.TemporalRangeHours = Tkinter.IntVar() self.Win2.TemporalRangeMinutes = Tkinter.IntVar() self.Win2.TemporalRangeSeconds = Tkinter.IntVar() self.Win2.TemporalRangeDays.set("0") self.Win2.TemporalRangeHours.set("11") self.Win2.TemporalRangeMinutes.set("59") self.Win2.TemporalRangeSeconds.set("59") Tkinter.Label(self.Win2,text="Enter maximum temporal difference for datasets to be compared.",anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor).grid(sticky='w'+'e',row=r,column=1,columnspan=4) r += 1 Tkinter.Label(self.Win2,text="Days",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.TemporalRangeDays,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) Tkinter.Label(self.Win2,text="Hours",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.TemporalRangeHours,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) r += 1 Tkinter.Label(self.Win2,text="Minutes",anchor='w').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.TemporalRangeMinutes,justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) Tkinter.Label(self.Win2,text="Seconds",anchor='w').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Entry(self.Win2,textvariable=self.Win2.TemporalRangeSeconds,justify="center").grid(sticky='w'+'e',row=r,column=4,columnspan=1) r += 1 Tkinter.Button(self.Win2 ,text='Cancel',command=self.CloseWin_2).grid(sticky='w'+'e',row=r,column=1,columnspan=2) if self.AuxSourcesComparisonType.get() == 'Binary statistics': Tkinter.Button(self.Win2 ,text='Run comparison',command=self.CompareBinary).grid(sticky='w'+'e',row=r,column=3,columnspan=2) if self.AuxSourcesComparisonType.get() == 'Continuous statistics': Tkinter.Button(self.Win2 ,text='Run comparison',command=self.CompareContinuous).grid(sticky='w'+'e',row=r,column=3,columnspan=2) self.centerWindow(self.Win2) self.Win2.wait_window() def BrowseProdDir(self): self.file_opt = options = {} options['title'] = 'Select data directory...' ans = str(os.path.normpath(tkFileDialog.askdirectory(**self.file_opt))) if ans != '' and ans != '.': self.Win2.ProdDir.set(ans) self.Win2.grab_set() self.Win2.lift() self.Win2.geometry("") def BrowseRefrDir(self): self.file_opt = options = {} options['title'] = 'Select data directory...' ans = str(os.path.normpath(tkFileDialog.askdirectory(**self.file_opt))) if ans != '' and ans != '.': self.Win2.RefrDir.set(ans) self.Win2.grab_set() self.Win2.lift() self.Win2.geometry("") def BrowseClsdDir(self): self.file_opt = options = {} options['title'] = 'Select data directory...' ans = str(os.path.normpath(tkFileDialog.askdirectory(**self.file_opt))) if ans != '' and ans != '.': self.Win2.ClsdDir.set(ans) self.Win2.grab_set() self.Win2.lift() self.Win2.geometry("") def ContMatrEdit(self): self.Win3 = Tkinter.Toplevel(self,padx=10,pady=10) self.Win3.grid_propagate(1) self.Win3.grab_set() self.Win3.wm_title('Comparison setup') self.Win3.columnconfigure(1, minsize=100) self.Win3.columnconfigure(2, minsize=30) self.Win3.columnconfigure(3, minsize=30) self.Win3.columnconfigure(4, minsize=40) self.Win3.columnconfigure(5, minsize=30) self.Win3.columnconfigure(6, minsize=30) self.Win3.columnconfigure(7, minsize=30) if self.Win2.ValsContMatr.get() == 'None': self.Win3.ValsMin = [] self.Win3.ValsMax = [] self.Win3.EqsMin = [] self.Win3.EqsMax = [] else: for cond in self.Win2.ValsContMatr.get().split(','): cond = cond.split() self.Win3.ValsMin.append(cond[0]) self.Win3.EqsMin.append(cond[1]) self.Win3.ValsMax.append(cond[4]) self.Win3.EqsMax.append(cond[3]) r = 0 r += 1 Tkinter.Button(self.Win3,text='Add',command=self.ContMatrAdd).grid(sticky='w'+'e',row=r,column=3) Tkinter.Button(self.Win3,text='OK',command=self.ContMatrOK).grid(sticky='w'+'e',row=r,column=4) Tkinter.Button(self.Win3,text='Cancel',command=self.CloseWin_3).grid(sticky='w'+'e',row=r,column=5) r += 1 Tkinter.Label(self.Win3,text="Class",anchor='c').grid(sticky='w'+'e',row=r,column=1,columnspan=1) Tkinter.Label(self.Win3,text="Min",anchor='c').grid(sticky='w'+'e',row=r,column=2,columnspan=1) Tkinter.Label(self.Win3,text="Eq.",anchor='c').grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Label(self.Win3,text="Eq.",anchor='c').grid(sticky='w'+'e',row=r,column=5,columnspan=1) Tkinter.Label(self.Win3,text="Max",anchor='c').grid(sticky='w'+'e',row=r,column=6,columnspan=1) for i in range(len(self.Win3.ValsMin)): r += 1 Tkinter.Label(self.Win3,text="Class "+str(i+1),anchor='c').grid(sticky='w'+'e',row=r,column=1,columnspan=1) exec("self.Win3.ValMin"+str(i)+" = Tkinter.StringVar()") exec("self.Win3.ValMin"+str(i)+".set(self.Win3.ValsMin["+str(i)+"])") Tkinter.Entry(self.Win3,textvariable=eval("self.Win3.ValMin"+str(i)),justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) exec("self.Win3.EqMin"+str(i)+" = Tkinter.StringVar()") exec("self.Win3.EqMin"+str(i)+".set(self.Win3.EqsMin["+str(i)+"])") Tkinter.OptionMenu(self.Win3,eval("self.Win3.EqMin"+str(i)),*['<','<=']).grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Label(self.Win3,text="Value",anchor='c').grid(sticky='w'+'e',row=r,column=4,columnspan=1) exec("self.Win3.EqMax"+str(i)+" = Tkinter.StringVar()") exec("self.Win3.EqMax"+str(i)+".set(self.Win3.EqsMax["+str(i)+"])") Tkinter.OptionMenu(self.Win3,eval("self.Win3.EqMax"+str(i)),*['>','>=']).grid(sticky='w'+'e',row=r,column=5,columnspan=1) exec("self.Win3.ValMax"+str(i)+" = Tkinter.StringVar()") exec("self.Win3.ValMax"+str(i)+".set(self.Win3.ValsMax["+str(i)+"])") Tkinter.Entry(self.Win3,textvariable=eval("self.Win3.ValMax"+str(i)),justify="center").grid(sticky='w'+'e',row=r,column=6,columnspan=1) Tkinter.Button(self.Win3,text='Del',command=self.BrowseProdDir).grid(sticky='w'+'e',row=r,column=7) self.centerWindow(self.Win3) self.Win3.wait_window() def ContMatrAdd(self): r = 3 + len(self.Win3.ValsMin) i = len(self.Win3.ValsMin) self.Win3.ValsMin.append('0') self.Win3.EqsMin.append('<') self.Win3.ValsMax.append('0') self.Win3.EqsMax.append('>') Tkinter.Label(self.Win3,text="Class "+str(i+1),anchor='c').grid(sticky='w'+'e',row=r,column=1,columnspan=1) exec("self.Win3.ValMin"+str(i)+" = Tkinter.StringVar()") exec("self.Win3.ValMin"+str(i)+".set(self.Win3.ValsMin["+str(i)+"])") Tkinter.Entry(self.Win3,textvariable=eval("self.Win3.ValMin"+str(i)),justify="center").grid(sticky='w'+'e',row=r,column=2,columnspan=1) exec("self.Win3.EqMin"+str(i)+" = Tkinter.StringVar()") exec("self.Win3.EqMin"+str(i)+".set(self.Win3.EqsMin["+str(i)+"])") Tkinter.OptionMenu(self.Win3,eval("self.Win3.EqMin"+str(i)),*['<','<=']).grid(sticky='w'+'e',row=r,column=3,columnspan=1) Tkinter.Label(self.Win3,text="Value",anchor='c').grid(sticky='w'+'e',row=r,column=4,columnspan=1) exec("self.Win3.EqMax"+str(i)+" = Tkinter.StringVar()") exec("self.Win3.EqMax"+str(i)+".set(self.Win3.EqsMax["+str(i)+"])") Tkinter.OptionMenu(self.Win3,eval("self.Win3.EqMax"+str(i)),*['>','>=']).grid(sticky='w'+'e',row=r,column=5,columnspan=1) exec("self.Win3.ValMax"+str(i)+" = Tkinter.StringVar()") exec("self.Win3.ValMax"+str(i)+".set(self.Win3.ValsMax["+str(i)+"])") Tkinter.Entry(self.Win3,textvariable=eval("self.Win3.ValMax"+str(i)),justify="center").grid(sticky='w'+'e',row=r,column=6,columnspan=1) Tkinter.Button(self.Win3,text='Del',command=self.BrowseProdDir).grid(sticky='w'+'e',row=r,column=7) def ContMatrOK(self): #update self.Win2.ValsContMatr return False def CompareBinary(self): if tkMessageBox.askyesno("Binary comparison","Depending on the amout of the data, binary comparison can take a long time to be completed. Do you want to proceed?"): resultspath = self.outputpath.get() if not os.path.exists(resultspath): os.makedirs(resultspath) if auxlist[self.Win1.ProdName.get()]["metadata"]["valuetype"] == "binary": ProdVals = (self.Win2.ValsProdTrue.get(),self.Win2.ValsProdFalse.get()) if auxlist[self.Win1.ProdName.get()]["metadata"]["valuetype"] == "continuous": ProdVals = (self.Win2.ValsProdRange.get(),self.Win2.ValsProdTrueMin.get(),self.Win2.ValsProdFalseMax.get()) if auxlist[self.Win1.RefrName.get()]["metadata"]["valuetype"] == "binary": RefrVals = (self.Win2.ValsRefrTrue.get(),self.Win2.ValsRefrFalse.get(),self.Win2.ValsRefrInvs.get(),self.Win2.ValsRefrThrs.get()) if auxlist[self.Win1.RefrName.get()]["metadata"]["valuetype"] == "continuous": RefrVals = (self.Win2.ValsRefrRange.get(),self.Win2.ValsRefrTrueMin.get(),self.Win2.ValsRefrFalseMax.get(),self.Win2.ValsRefrInvs.get(),self.Win2.ValsRefrThrs.get()) if self.Win1.ClsdName.get() == "None": self.Win2.ValsClsdVals = Tkinter.StringVar() self.Win2.ValsClsdNams = Tkinter.StringVar() self.Win2.ValsClsdVals.set("None") self.Win2.ValsClsdNams.set("None") ClsdVals = None else: ClsdVals = (self.Win2.ValsClsdVals.get(),self.Win2.ValsClsdThrs.get(),self.Win2.ValsClsdOnto.get()) extent = (self.Win2.LatitudeRange.get(),self.Win2.LongitudeRange.get(),self.Win2.TemporalRangeDays.get(),self.Win2.TemporalRangeHours.get(),self.Win2.TemporalRangeMinutes.get(),self.Win2.TemporalRangeSeconds.get()) output = comparators.compareBinary(self.Win1.ProdName.get(),self.Win2.ProdDir.get(),ProdVals,self.Win1.RefrName.get(),self.Win2.RefrDir.get(),RefrVals, self.Win1.ClsdName.get(),self.Win2.ClsdDir.get(),self.Win2.ValsClsdNams.get(), ClsdVals,self.Win2.ResampleRadiusRefr.get(),self.Win2.ResampleSigmaRefr.get(),self.Win2.ResampleRadiusClsd.get(),self.Win2.ResampleSigmaClsd.get(),extent,self.Message) analysis_captions = {'source': '', 'analysis': 'Binary statistics', 'scenario': self.Win1.ProdName.get()+' vs '+self.Win1.RefrName.get(), 'network': ''} if output: filelabel = os.path.join(resultspath,'Comparison') storeData(filelabel,analysis_captions,output,self.Message) self.CloseWin_2() self.CloseWin_1() self.Menu_Main_Results() self.ResultFolderNameVariable.set(resultspath) def CompareContinuous(self): if tkMessageBox.askyesno("Continuous comparison","Depending on the amout of the data, continuous comparison can take a long time to be completed. Do you want to proceed?"): resultspath = self.outputpath.get() if not os.path.exists(resultspath): os.makedirs(resultspath) if auxlist[self.Win1.ProdName.get()]["metadata"]["valuetype"] == "binary": ProdVals = (self.Win2.ValsProdTrue.get(),self.Win2.ValsProdFalse.get()) if auxlist[self.Win1.ProdName.get()]["metadata"]["valuetype"] == "continuous": ProdVals = (self.Win2.ValsProdRange.get(),self.Win2.ValsProdScale.get(),self.Win2.ValsProdBias.get()) if auxlist[self.Win1.RefrName.get()]["metadata"]["valuetype"] == "binary": RefrVals = (self.Win2.ValsRefrTrue.get(),self.Win2.ValsRefrFalse.get(),self.Win2.ValsRefrInvs.get(),self.Win2.ValsRefrThrs.get()) if auxlist[self.Win1.RefrName.get()]["metadata"]["valuetype"] == "continuous": RefrVals = (self.Win2.ValsRefrRange.get(),self.Win2.ValsRefrScale.get(),self.Win2.ValsRefrBias.get(),self.Win2.ValsRefrInvs.get(),self.Win2.ValsRefrThrs.get()) if self.Win1.ClsdName.get() == "None": self.Win2.ValsClsdVals = Tkinter.StringVar() self.Win2.ValsClsdNams = Tkinter.StringVar() self.Win2.ValsClsdVals.set("None") self.Win2.ValsClsdNams.set("None") ClsdVals = None else: ClsdVals = (self.Win2.ValsClsdVals.get(),self.Win2.ValsClsdThrs.get(),self.Win2.ValsClsdOnto.get()) extent = (self.Win2.LatitudeRange.get(),self.Win2.LongitudeRange.get(),self.Win2.TemporalRangeDays.get(),self.Win2.TemporalRangeHours.get(),self.Win2.TemporalRangeMinutes.get(),self.Win2.TemporalRangeSeconds.get()) output = comparators.compareContinuous(self.Win1.ProdName.get(),self.Win2.ProdDir.get(),ProdVals,self.Win1.RefrName.get(),self.Win2.RefrDir.get(),RefrVals,self.Win1.ClsdName.get(),self.Win2.ClsdDir.get(),self.Win2.ValsClsdNams.get(), ClsdVals ,self.Win2.ResampleRadiusRefr.get(),self.Win2.ResampleSigmaRefr.get(),self.Win2.ResampleRadiusClsd.get(),self.Win2.ResampleSigmaClsd.get(),extent,self.Message) analysis_captions = {'source': '', 'analysis': 'Continuous statistics', 'scenario': self.Win1.ProdName.get()+' vs '+self.Win1.RefrName.get(), 'network': ''} if output: filelabel = os.path.join(resultspath,'Comparison') storeData(filelabel,analysis_captions,output,self.Message) self.CloseWin_2() self.CloseWin_1() self.Menu_Main_Results() self.ResultFolderNameVariable.set(resultspath) def Tools_Georectification(self): self.UpdateSetup() from georectification import georectificationTool, transSingle, transExtent analysis = self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())] geoparams = paramnames[calcids.index('GEOREC001')] geoopts = paramopts[calcids.index('GEOREC001')] corrparams = paramnames[calcids.index('IMGCORR01')] message = '' message += 'This tool simulates the georectification using VTK and OpenGL libraries. The parameters are taken from the current analysis parameters in the current scenario. The preview image used is the one chosen in the Camera menu.\n' try: extent = analysis[geoparams[0]] extent_proj = analysis[geoparams[1]] res = float(analysis[geoparams[2]]) dem = analysis[geoparams[3]] C = analysis[geoparams[4]] C_proj = analysis[geoparams[5]] Cz = float(analysis[geoparams[6]]) hd = float(analysis[geoparams[7]]) td = float(analysis[geoparams[8]]) vd = float(analysis[geoparams[9]]) f = float(analysis[geoparams[10]])*0.001 s = float(analysis[geoparams[11]]) interpolate = analysis[geoparams[12]] flat = analysis[geoparams[13]] extent_proj = geoopts[1][int(extent_proj)] dem = geoopts[3][int(dem)] C_proj = geoopts[5][int(C_proj)] origin = analysis[corrparams[0]] ax = analysis[corrparams[1]] ay = analysis[corrparams[2]] except: message += '\nGeorectification parameters are not found in the current analysis or an unexpected error has occured. Check the analysis type and parameters and try again.\n' tkMessageBox.showwarning('Georectification preview',message) return 0 extent = map(float,extent.split(';')) C = map(float,C.split(';')) C = transSingle(C,C_proj) if extent != [0,0,0,0]: if extent_proj == "ETRS-TM35FIN(EPSG:3067) GEOID with Camera at Origin": extent[0] += C[0] extent[2] += C[0] extent[1] += C[1] extent[3] += C[1] extent_proj = "ETRS-TM35FIN(EPSG:3067)" extent = transExtent(extent,extent_proj) [x1,y1,x2,y2] = extent size = int(((y2-y1)/res)*((x2-x1)/res)) goodsize = 1000000. res = res*size/goodsize size = goodsize analysis[geoparams[2]] = res georectificationTool(self,self.Message,self.PictureFileName.get(),analysis,geoparams,geoopts,corrparams,self.memorylimit.get()) # message += '\nThere are over ' + str(size) + ' points in the real world to be simulated for the preview. It is adviced to keep the number of points under half million, otherwise the process may take too long.\n' # message += '\nThe spatial resolution or the spatial extent can be decreased to decrease number of points.\n' # message += '\nDo you wish the continue?' # # # if tkMessageBox.askyesno('Georectification preview',message): # georectificationTool(self,self.Message,self.PictureFileName.get(),analysis,geoparams,geoopts,corrparams,self.memorylimit.get()) def Menu_Base(self): greentexture = Tkinter.PhotoImage(file=os.path.join(ResourcesDir,'green_grad_inv.gif')) bluetexture = Tkinter.PhotoImage(file=os.path.join(ResourcesDir,'blue_grad_vert.gif')) #Previous and next analysis shadow Label = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="",anchor='w',bg="RoyalBlue4",relief=Tkinter.GROOVE) Label.photo = bluetexture Label.place(x=self.TableX+self.FolderX,y=0,height=self.PasAnaY,width=self.WindowX-2*self.TableX-2*self.FolderX) Label = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="",anchor='w',bg="RoyalBlue4",relief=Tkinter.GROOVE) Label.place(x=self.TableX+self.FolderX,y=2*self.TableY+3*self.FolderY+self.BannerY-self.PasAnaY+self.MenuY+self.LogY,height=self.PasAnaY,width=self.WindowX-2*self.TableX-2*self.FolderX) #Folder Label = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="",bg='DarkOrange4',anchor='w',relief=Tkinter.GROOVE) #Label.photo = greentexture #Label.place(width=1000,height=3000) Label.place(x=self.TableX,y=self.TableY,width=self.WindowX-2*self.TableX,height=self.WindowY-2*self.TableY-self.LogY) #Banner Label = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="<",command=self.AnalysisNoMinus,relief=Tkinter.GROOVE) Label.place(x=self.TableX+self.FolderX,y=self.TableY+self.FolderY,width=self.BannerX,height=self.BannerY) Label = Tkinter.Button(self,wraplength=self.MenuX*0.8,text=">",command=self.AnalysisNoPlus,relief=Tkinter.GROOVE) Label.place(x=self.WindowX-self.TableX-self.FolderX-self.BannerX,y=self.TableY+self.FolderY,width=self.BannerX,height=self.BannerY) Label = Tkinter.Entry(self,textvariable=self.ScenarioNameVariable,fg="white",bg="RoyalBlue4",relief=Tkinter.GROOVE,justify='center') Label.place(x=self.TableX+self.FolderX+self.BannerX,y=self.TableY+self.FolderY,width=self.WindowX-2*self.TableX-2*self.FolderX-2*self.BannerX,height=self.BannerY) #Passive Parchment #Passive Parchment #Label = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="",anchor='w',bg="white",image=greentexture,relief=Tkinter.GROOVE) #Label.photo = greentexture #Label.place(x=self.TableX+self.FolderX,y=self.TableY+2*self.FolderY+self.BannerY+self.PasParchIn,width=self.PasParchX,height=self.WindowY-2*self.TableY-3*self.FolderY-self.BannerY-2*self.PasParchIn-self.LogY) #Active Parchment Label = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="",anchor='w',bg="white",image=greentexture,relief=Tkinter.GROOVE) Label.photo = greentexture Label.place(x=self.TableX+self.FolderX+self.PasParchX,y=self.TableY+2*self.FolderY+self.BannerY,width=self.MenuX+self.MenuHeaderX,height=self.WindowY-2*self.TableY-3*self.FolderY-self.BannerY-self.LogY) #MenuHeader Label = Tkinter.Label(self,textvariable=self.ActiveMenu,anchor='c',bg="RoyalBlue4",fg="white",wraplength=1,relief=Tkinter.GROOVE) Label.place(x=self.TableX+self.FolderX+self.PasParchX,y=self.TableY+2*self.FolderY+self.BannerY,height=self.MenuY,width=self.MenuHeaderX) #Log Label = Tkinter.Label(self,textvariable=self.LogLL,wraplength=self.WindowX-2*self.TableX,relief=Tkinter.GROOVE,fg="white",bg="RoyalBlue4",anchor="c") Label.place(x=self.TableX,y=2*self.TableY+3*self.FolderY+self.BannerY-self.PasAnaY+self.MenuY,height=self.LogY,width=self.WindowX-2*self.TableX) #Menu self.MenuOSX = self.TableX+self.FolderX+self.PasParchX+self.MenuHeaderX self.MenuOSY = self.TableY+2*self.FolderY+self.BannerY def Menu_Main(self): self.ClearMenu() self.ActiveMenu.set("Main Menu") self.Menu_Prev("Main Menu","self.Menu_Main") self.MaskingPolygonPen.set(0) NItems = 8 space = 0.02 Item = 1 self.MenuItem1 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Camera",anchor="c",command=self.Menu_Main_Camera,activebackground='RoyalBlue4',activeforeground='white')#,image=photo,compound="center",fg="white") self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 2 self.MenuItem2 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Temporal",anchor="c",command=self.Menu_Main_Temporal,activebackground='RoyalBlue4',activeforeground='white') self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 3 self.MenuItem3 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Thresholds",anchor="c",command=self.Menu_Main_Thresholds,activebackground='RoyalBlue4',activeforeground='white') self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem4 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Masking/ROIs",anchor="c",command=self.Menu_Main_Masking_Polygonic,activebackground='RoyalBlue4',activeforeground='white') self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem6 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Analyses",anchor="c",command=self.Menu_Main_Calculations,activebackground='RoyalBlue4',activeforeground='white') self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem10 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text='Results',anchor="c",command=self.Menu_Main_Output,activebackground='RoyalBlue4',activeforeground='white') self.MenuItem10.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem9 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Run All",anchor="c",command=self.RunAnalyses,activebackground='RoyalBlue4',activeforeground='white') self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem8 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text='Result Viewer',anchor="c",command=self.Menu_Main_Results,activebackground='RoyalBlue4',activeforeground='white') self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Camera(self): self.ClearMenu() self.ActiveMenu.set("Camera") self.Menu_Prev("Main Menu","self.Menu_Main") self.callbackCameraName(0,0) NItems = 10 space = 0.02 Item = 2 self.MenuItem11 = Tkinter.Label(self,wraplength=self.MenuX*0.4,text="Camera Network",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem11.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 3 self.MenuItem10 = Tkinter.OptionMenu(self,self.NetworkNameVariable,*sources.listNetworks(self.Message,self.networklist)) self.MenuItem10.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem12 = Tkinter.Label(self,wraplength=self.MenuX*0.4,text="Camera",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem12.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem1 = Tkinter.OptionMenu(self,self.CameraNameVariable,*sources.listSources(self.Message,self.sourcelist,network=self.NetworkNameVariable.get())) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem2 = Tkinter.Checkbutton(self,variable=self.MenuItem2Switch,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text="Preview") self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem3 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Choose Picture for Preview",anchor="c",command=self.Menu_Main_Camera_Picture) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem5 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Open local image directory",anchor="c",command=self.Menu_Main_Camera_Open) self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 9 self.MenuItem4 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Camera metadata...",anchor="c",command=self.Menu_Main_Camera_Metadata) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuEnablerFunc.set("self.MenuEnabler([2,[3],['self.PreviewCanvasSwitch'],['0'],['self.PreviewCanvasSwitch.set(self.MenuItem2Switch.get())']])") exec(self.MenuEnablerFunc.get()) def Menu_Main_Camera_Open(self): source_ = self.setup[self.AnalysisNoVariable.get()-1]['source'] source = sources.getProxySource(self.Message,source_,self.proxylist) self.makeDirStorage() if source['protocol'] == 'LOCAL': if 'temporary' in source and source['temporary']: tkMessageBox.showwarning('No directory','Directory does not exist. This camera was temporarily added and the images of the camera refer to local directories and they do not exist. It probably means that the setup file loaded is saved in another computer with a camera network or camera which is not defined identically in this computer. To fix it, load the setup file again, confirm the permanent save of the camera/network and the open camera network manager and set up directories accordingly.') return False else: webbrowser.open('file:///'+source['path']) else: if 'temporary' in source and source['temporary']: webbrowser.open('file:///'+os.path.join(os.path.join(TmpDir,'tmp_images'),validateName(source['network'])+'-'+source['protocol']+'-'+source['host']+'-'+validateName(source['username'])+'-'+validateName(source['path']))) else: webbrowser.open('file:///'+os.path.join(self.imagespath.get(),source['networkid']+'-'+parsers.validateName(source['network']),parsers.validateName(source['name']))) def Menu_Main_Camera_Metadata(self): string = '' source = sources.getSource(self.Message,self.sourcelist,self.CameraNameVariable.get()) for key in source: if key not in source_metadata_hidden: if key in source_metadata_names: if 'time' in key: string += source_metadata_names[key] + ': ' + str(parsers.strptime2(source[key])[0]) +'\n' else: string += source_metadata_names[key] + ': ' + str(source[key]) +'\n' else: string += key + ': ' + str(source[key]) +'\n' source_ = sources.getSource(self.Message,self.sourcelist,self.CameraNameVariable.get()) source = sources.getProxySource(self.Message,source_,self.proxylist) if source == source_: string += 'Proxy metadata\n' for key in source: if key not in source_metadata_hidden: if key in source_metadata_names: if 'time' in key: string += source_metadata_names[key] + ': ' + str(parsers.strptime2(source[key])[0]) +'\n' else: string += source_metadata_names[key] + ': ' + str(source[key]) +'\n' else: string += key + ': ' + str(source[key]) +'\n' tkMessageBox.showwarning('Camera Metadata',string) def Menu_Main_Camera_Picture(self): source_ = self.setup[self.AnalysisNoVariable.get()-1]['source'] source = sources.getProxySource(self.Message,source_,self.proxylist) if source['protocol'] == 'LOCAL' and 'temporary' in source and source['temporary']: tkMessageBox.showwarning('No directory','Directory does not exist. This camera was temporarily added and the images of the camera refer to local directories and they do not exist. It probably means that the setup file loaded is saved in another computer with a camera network or camera which is not defined identically in this computer. To fix it, load the setup file again, confirm the permanent save of the camera/network and the open camera network manager and set up directories accordingly.') return False self.ClearMenu() self.ActiveMenu.set("Choose Picture for Preview") self.Menu_Prev("Camera","self.Menu_Main_Camera") self.Menu_Choose_Picture() def Menu_Choose_Picture(self): NItems = 10 space = 0.02 Item = 1 self.MenuItem2 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Double click to choose:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 2 self.MenuItem8 = Tkinter.Scrollbar(self) self.MenuItem8.place(x=self.MenuX*0.8-self.ScrollbarX+self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.ScrollbarX,height=space*6+7*self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem1 = Tkinter.Listbox(self,yscrollcommand=self.MenuItem8.set) self.MenuItem8.config(command=self.MenuItem1.yview) self.ChoosePictureKeywords = Tkinter.StringVar() self.ChoosePictureKeywords.set("Keywords") self.Menu_Main_Camera_Picture_Filter() self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8-self.ScrollbarX,height=space*6+7*self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem1.bind("<Double-Button-1>", self.ChangePictureFileName) Item = 8 self.MenuItem4 = Tkinter.Entry(self,textvariable=self.ChoosePictureKeywords,justify="center") self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 9 self.MenuItem5 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Filter by keywords",anchor="c",command=self.Menu_Main_Camera_Picture_Filter) self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 10 self.MenuItem3 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Download pictures...",anchor="c",command=self.FetchCurrentImages) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Camera_Picture_Filter(self): if self.ChoosePictureKeywords.get() == "Keywords": keys = "" else: keys = self.ChoosePictureKeywords.get().split() try: self.MenuItem1.delete(0,"end") source_ = self.setup[self.AnalysisNoVariable.get()-1]['source'] source = sources.getProxySource(self.Message,source_,self.proxylist) if source['protocol'] == 'LOCAL': if 'temporary' in source and source['temporary']: tkMessageBox.showwarning('No directory','Directory does not exist. This camera was temporarily added and the images of the camera refer to local directories and they do not exist. It probably means that the setup file loaded is saved in another computer with a camera network or camera which is not defined identically in this computer. To fix it, load the setup file again, confirm the permanent save of the camera/network and the open camera network manager and set up directories accordingly.') return False imglist = fetchers.fetchImages(self, self.Message, source, self.proxy, self.connection, self.imagespath.get(), [0,0,0,0, "All"], online=True, care_tz = self.TimeZoneConversion.get())[0] for i,v in enumerate(imglist): imglist[i] = os.path.split(v)[-1] else: if 'temporary' in source and source['temporary']: imglist = os.listdir(os.path.join(os.path.join(TmpDir,'tmp_images'),validateName(source['network'])+'-'+source['protocol']+'-'+source['host']+'-'+validateName(source['username'])+'-'+validateName(source['path']))) else: imglist = os.listdir(os.path.join(self.imagespath.get(),source['networkid']+'-'+parsers.validateName(source['network']),parsers.validateName(source['name']))) imglist.sort() for item in imglist: if keys == [] or keys=="": self.MenuItem1.insert("end",item) else: inc = True for key in keys: if key not in item: inc = False break if inc: self.MenuItem1.insert("end",item) except: pass def Menu_Main_Temporal(self): self.ClearMenu() self.ActiveMenu.set("Temporal") self.Menu_Prev("Main Menu","self.Menu_Main") NItems = 10 space = 0.02 Item = 4 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Temporal selection:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem2 = Tkinter.OptionMenu(self,self.TemporalModeVariable,*temporal_modes) self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem3 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Dates",anchor="c",command=self.Menu_Main_Temporal_Dates) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem4 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Time of the day",anchor="c",command=self.Menu_Main_Temporal_Times) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.callbackTemporalMode() def callbackTemporalMode(self,*args): if self.TemporalModeVariable.get() in ['All','Latest 1 hour','Latest image only','Latest 48 hours','Latest 24 hours','Last 48 hours','Last 24 hours']: self.DateStartVariable.set(scenario_def['temporal'][0]) self.DateEndVariable.set(scenario_def['temporal'][1]) self.TimeStartVariable.set(scenario_def['temporal'][2]) self.TimeEndVariable.set(scenario_def['temporal'][3]) if self.ActiveMenu.get() == "Temporal": self.MenuItem3.config(state='disabled') self.MenuItem4.config(state='disabled') if (self.ActiveMenu.get() == "Dates" or self.ActiveMenu.get() == "Time of the day"): self.Menu_Main_Temporal() if self.TemporalModeVariable.get() in ['Time of day','Yesterday only','Today only','Last one year','Last one week','Last one month','Latest one year','Latest one week','Latest one month']: self.DateStartVariable.set(scenario_def['temporal'][0]) self.DateEndVariable.set(scenario_def['temporal'][1]) if self.ActiveMenu.get() == "Temporal": self.MenuItem3.config(state='disabled') self.MenuItem4.config(state='normal') if self.ActiveMenu.get() == "Dates": self.Menu_Main_Temporal_Dates() if self.TemporalModeVariable.get() in ['Date and time intervals']: if self.ActiveMenu.get() == "Temporal": self.MenuItem3.config(state='normal') self.MenuItem4.config(state='normal') if self.TemporalModeVariable.get() in ['Earliest date and time intervals']: self.DateEndVariable.set(scenario_def['temporal'][1]) if self.ActiveMenu.get() == "Temporal": self.MenuItem3.config(state='normal') self.MenuItem4.config(state='normal') if self.TemporalModeVariable.get() in ['Latest date and time intervals']: self.DateStartVariable.set(scenario_def['temporal'][0]) if self.ActiveMenu.get() == "Temporal": self.MenuItem3.config(state='normal') self.MenuItem4.config(state='normal') def Menu_Main_Temporal_Dates(self): self.ClearMenu() self.ActiveMenu.set("Dates") self.Menu_Prev("Temporal","self.Menu_Main_Temporal") NItems = 10 space = 0.02 Item = 3 if self.TemporalModeVariable.get() != 'Latest date and time intervals': Item += 1 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Start:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem3 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.DateStartVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) if self.TemporalModeVariable.get() != 'Earliest date and time intervals': Item += 1 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="End:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem6 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.DateEndVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Temporal_Times(self): self.ClearMenu() self.ActiveMenu.set("Time of the day") self.Menu_Prev("Temporal","self.Menu_Main_Temporal") NItems = 10 space = 0.02 Item = 4 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Start:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem3 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.TimeStartVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="End:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.TimeEndVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds(self): self.ClearMenu() self.ActiveMenu.set("Thresholds") self.Menu_Prev("Main Menu","self.Menu_Main") NItems = 15 space = 0.02 Item = 1 self.MenuItem8 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Image thresholds",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem1 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Brightness",anchor="c",command=self.Menu_Main_Thresholds_Brightness,activebackground='seashell',activeforeground='black') self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem2 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Luminance",anchor="c",command=self.Menu_Main_Thresholds_Luminance,activebackground='beige',activeforeground='black') self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem13 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Red Fraction",anchor="c",command=self.Menu_Main_Thresholds_RedFI,activebackground='red3',activeforeground='white') self.MenuItem13.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem14 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Green Fraction",anchor="c",command=self.Menu_Main_Thresholds_GreenFI,activebackground='green4',activeforeground='white') self.MenuItem14.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem15 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Blue Fraction",anchor="c",command=self.Menu_Main_Thresholds_BlueFI,activebackground='blue2',activeforeground='white') self.MenuItem15.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem9 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="ROI thresholds",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem11 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Red Fraction",anchor="c",command=self.Menu_Main_Thresholds_RedF,activebackground='red3',activeforeground='white') self.MenuItem11.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem3 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Green Fraction",anchor="c",command=self.Menu_Main_Thresholds_GreenF,activebackground='green4',activeforeground='white') self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem4 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Blue Fraction",anchor="c",command=self.Menu_Main_Thresholds_BlueF,activebackground='blue2',activeforeground='white') self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem10 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Pixel thresholds",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem10.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem5 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Red Channel",anchor="c",command=self.Menu_Main_Thresholds_Red,activebackground='red3',activeforeground='white') self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem6 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Green Channel",anchor="c",command=self.Menu_Main_Thresholds_Green,activebackground='green4',activeforeground='white') self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem7 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Blue Channel",anchor="c",command=self.Menu_Main_Thresholds_Blue,activebackground='blue2',activeforeground='white') self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem12 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Grey Composite",anchor="c",command=self.Menu_Main_Thresholds_Grey,activebackground='seashell',activeforeground='black') self.MenuItem12.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_Brightness(self): self.ClearMenu() self.ActiveMenu.set("Brightness") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.BrightnessLTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.BrightnessUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_Luminance(self): self.ClearMenu() self.ActiveMenu.set("Luminance") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.LuminanceLTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.LuminanceUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_Red(self): self.ClearMenu() self.ActiveMenu.set("Red Channel") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=255,orient="horizontal",resolution=1, width=self.CheckButtonY, variable=self.RedLTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=255,orient="horizontal",resolution=1, width=self.CheckButtonY, variable=self.RedUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_Green(self): self.ClearMenu() self.ActiveMenu.set("Green Channel") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=255,orient="horizontal",resolution=1, width=self.CheckButtonY, variable=self.GreenLTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=255,orient="horizontal",resolution=1, width=self.CheckButtonY, variable=self.GreenUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_Blue(self): self.ClearMenu() self.ActiveMenu.set("Blue Channel") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=255,orient="horizontal",resolution=1, width=self.CheckButtonY, variable=self.BlueLTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=255,orient="horizontal",resolution=1, width=self.CheckButtonY, variable=self.BlueUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_Grey(self): self.ClearMenu() self.ActiveMenu.set("Grey Composite") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=255,orient="horizontal",resolution=1, width=self.CheckButtonY, variable=self.GreyLTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=255,orient="horizontal",resolution=1, width=self.CheckButtonY, variable=self.GreyUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_RedF(self): self.ClearMenu() self.ActiveMenu.set("Red Fraction") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.RedFLTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.RedFUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_GreenF(self): self.ClearMenu() self.ActiveMenu.set("Green Fraction") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.GreenFLTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.GreenFUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_BlueF(self): self.ClearMenu() self.ActiveMenu.set("Blue Fraction") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.BlueFLTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.BlueFUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_RedFI(self): self.ClearMenu() self.ActiveMenu.set("Red Fraction") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.RedFILTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.RedFIUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_GreenFI(self): self.ClearMenu() self.ActiveMenu.set("Green Fraction") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.GreenFILTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.GreenFIUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Thresholds_BlueFI(self): self.ClearMenu() self.ActiveMenu.set("Blue Fraction") self.Menu_Prev("Thresholds","self.Menu_Main_Thresholds") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Minimum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem3 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.BlueFILTVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem6 = Tkinter.Scale(self, from_=0, to=1,orient="horizontal",resolution=0.005, width=self.CheckButtonY,variable=self.BlueFIUTVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Masking(self): self.ClearMenu() self.ActiveMenu.set("Masking/ROIs") self.Menu_Prev("Main Menu","self.Menu_Main") NItems = 9 space = 0.02 Item = 5 self.MenuItem1 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Polygonic Masking",anchor="c",command=self.Menu_Main_Masking_Polygonic) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Masking_Polygonic(self): self.ClearMenu() self.ActiveMenu.set("Polygonic Masking") self.Menu_Prev("Main Menu","self.Menu_Main") NItems = 15 space = 0.02 Item = 1 self.PreviewCanvasSwitch.set(self.PreviewCanvasSwitch.get()) self.MenuItem1 = Tkinter.Checkbutton(self,variable=self.MenuItem1Switch,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text="Display preview with polygons") self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem2 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Pick Points",command=self.PolygonPick,activebackground='green4',activeforeground='white') self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) #Item = 6 self.MenuItem17 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Remove Points",command=self.PolygonRemove,activebackground='red3',activeforeground='white') self.MenuItem17.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem4 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Remove All",command=self.PolygonRemoveAll,activebackground='red3',activeforeground='white') self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem6 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Test Mask",command=self.ApplyMask,activebackground='gold',activeforeground='black') self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 9 self.MenuItem25 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text=" - ",command=self.SensMinus) self.MenuItem25.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem8 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Sensitivity",anchor='c',bg='RoyalBlue4',fg='white') self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.3,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem7 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text=" + ",command=self.SensPlus) self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.7,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 10 self.MenuItem9 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Coordinates:",anchor='c') self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 11 self.MenuItem10 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.PolygonCoordinatesVariable,state="readonly") self.MenuItem10.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 2 self.MenuItem11 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="<",command=self.PolygonNoPlus) self.MenuItem11.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.1,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem13 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Polygon ",anchor='e',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem13.place(x=self.MenuOSX+self.MenuX*0.2,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem14 = Tkinter.Label(self,textvariable=self.PolygonNoVariable,anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem14.place(x=self.MenuOSX+self.MenuX*0.6,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem12 = Tkinter.Button(self,wraplength=self.MenuX*0.9,text=">",command=self.PolygonNoMinus) self.MenuItem12.place(x=self.MenuOSX+self.MenuX*0.8,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.1,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 3 self.MenuItem15 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Add Polygon",command=self.PolygonNoNew,activebackground='green4',activeforeground='white') self.MenuItem15.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem16 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Delete Polygon",command=self.PolygonNoDelete,activebackground='red3',activeforeground='white') self.MenuItem16.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem26 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Copy polygons from other scenarios...",command=self.Menu_Main_Masking_Polygonic_Copy,activebackground='gold',activeforeground='black') self.MenuItem26.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem24 = Tkinter.Checkbutton(self,variable=self.PolygonMultiRoiVariable,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text="Run analyses also for each polygon (ROI) separately") self.MenuItem24.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(0.5*NItems+1)*space)/(0.5*NItems)) Item = 12 self.MenuItem3 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Choose Picture for Preview",command=self.Menu_Main_Masking_Polygonic_Picture) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 13 self.MenuItem18 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Selected Polygon's Color:",justify='left',anchor='c',bg=self.PolygonColor0.get()) self.MenuItem18.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.5,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 13 void = Tkinter.StringVar() void.set('Change') self.MenuItem19 = Tkinter.OptionMenu(self,void,*self.Colors) self.MenuItem19.place(x=self.MenuOSX+self.MenuX*0.6,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.3,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem19['menu'].delete(0,"end") for color in self.Colors: self.MenuItem19['menu'].add_command(label='Change',command=Tkinter._setit(self.PolygonColor0,color),background=color,foreground=color,activebackground=color,activeforeground=color) Item = 14 self.MenuItem20 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Polygon Color:",justify='left',anchor='c') self.MenuItem20.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.5,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 14 self.MenuItem21 = Tkinter.OptionMenu(self,void,*self.Colors) self.MenuItem21['menu'].delete(0,"end") for color in self.Colors: self.MenuItem21['menu'].add_command(label='Change',command=Tkinter._setit(self.PolygonColor1,color),background=color,foreground=color,activebackground=color,activeforeground=color) self.MenuItem21.place(x=self.MenuOSX+self.MenuX*0.6,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.3,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 15 self.MenuItem22 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Polygon Line Width: ",anchor='c') self.MenuItem22.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.6,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem23 = Tkinter.OptionMenu(self,self.PolygonWidth,*[1,2,3,4,5,6,7,8,9]) self.MenuItem23.place(x=self.MenuOSX+self.MenuX*0.7,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuEnablerFunc.set("self.MenuEnabler([1,[3,18,19,20,21,22,23],['self.PreviewCanvasSwitch'],['0'],['self.PreviewCanvasSwitch.set(self.MenuItem1Switch.get())']])") exec(self.MenuEnablerFunc.get()) def Menu_Main_Masking_Polygonic_Copy(self): self.copypolygonfiledialog = Tkinter.Toplevel(self,padx=10,pady=10) self.copypolygonfiledialog.wm_title('Copy polygons') Tkinter.Button(self.copypolygonfiledialog ,text='Copy polygons from other scenarios in the current setup',command=self.Menu_Main_Masking_Polygonic_Copy_CurSetup).grid(sticky='w'+'e',row=1,column=1,columnspan=1) Tkinter.Button(self.copypolygonfiledialog ,text='Copy polygons from other scenarios in a different setup file...',command=self.Menu_Main_Masking_Polygonic_Copy_OthSetup).grid(sticky='w'+'e',row=2,column=1,columnspan=1) self.centerWindow(self.copypolygonfiledialog) self.copypolygonfiledialog.grab_set() self.copypolygonfiledialog.lift() self.copypolygonfiledialog.wait_window() def Menu_Main_Masking_Polygonic_Copy_CurSetup(self): self.copypolygonfiledialog.destroy() self.Menu_Main_Masking_Polygonic_Copy_Choose(self.setup) def Menu_Main_Masking_Polygonic_Copy_OthSetup(self): self.file_opt = options = {} options['defaultextension'] = '.cfg' options['filetypes'] = [ ('FMIPROT setup files', '.cfg'),('FMIPROT configuration files', '.cfg'),('all files', '.*')] options['title'] = 'Choose setup file to copy polygons from...' ans = tkFileDialog.askopenfilename(**self.file_opt) try: if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) setup = parsers.readSetup(ans,self.sourcelist,self.Message) #fix polygons for i,scenario in enumerate(setup): if isinstance(scenario['polygonicmask'],dict): coordict = scenario['polygonicmask'] coordlist = [] for j in range(len(coordict)): coordlist.append(coordict[str(j)]) setup[i].update({'polygonicmask':coordlist}) self.copypolygonfiledialog.destroy() self.Menu_Main_Masking_Polygonic_Copy_Choose(setup) except: tkMessageBox.showwarning('Problem','Problem in reading setup file. It could not be loaded.') self.copypolygonfiledialog.grab_set() self.copypolygonfiledialog.lift() def Menu_Main_Masking_Polygonic_Copy_Choose(self,setup): poltocopy = False for s,scenario in enumerate(setup): if s != self.AnalysisNoVariable.get()-1: if np.array(scenario['polygonicmask']).sum() != 0: poltocopy = True break if not poltocopy: tkMessageBox.showwarning('Copy polygons','No polygons found in other scenarios.') else: self.copypolygondialog = Tkinter.Toplevel(self,padx=10,pady=10) self.copypolygondialog.grab_set() self.copypolygondialog.lift() self.copypolygondialog.wm_title('Copy polygons') Tkinter.Label(self.copypolygondialog ,anchor='w',wraplength=self.MenuX,text='Choose a scenario below to copy the polygons from. All the polygons from the scenario will be added to the current scenario.').grid(sticky='w'+'e',row=1,column=1,columnspan=2) sel_sce = Tkinter.StringVar() self.sel_pol = Tkinter.StringVar() for s,scenario in enumerate(setup): if s != self.AnalysisNoVariable.get()-1: sel_sce.set(scenario['name']) self.sel_pol.set(self.polygonicmask2PolygonCoordinatesVariable(scenario['polygonicmask'])) opts = Tkinter.OptionMenu(self.copypolygondialog , sel_sce,1,2) opts.grid(sticky='w'+'e',row=3,column=1,columnspan=2) opts['menu'].delete(0,'end') for s,scenario in enumerate(setup): if s != self.AnalysisNoVariable.get()-1: if np.array(scenario['polygonicmask']).sum() != 0: opts['menu'].add_command(label=scenario['name'], command=lambda caption=scenario['name']: self.sel_pol.set(self.polygonicmask2PolygonCoordinatesVariable(scenario['polygonicmask']))) Tkinter.Button(self.copypolygondialog ,text='OK',command=self.Menu_Main_Masking_Polygonic_Copy_Copy).grid(sticky='w'+'e',row=4,column=2,columnspan=1) Tkinter.Button(self.copypolygondialog ,text='Cancel',command=self.copypolygondialog.destroy).grid(sticky='w'+'e',row=4,column=1,columnspan=1) self.centerWindow(self.copypolygondialog) self.copypolygondialog.grab_set() self.copypolygondialog.lift() self.copypolygondialog.wait_window() def Menu_Main_Masking_Polygonic_Copy_Copy(self): pollist = self.PolygonCoordinatesVariable2polygonicmask(self.PolygonCoordinatesVariable.get()) if np.array(pollist).sum() == 0: pollist = [] else: if not isinstance(pollist[0],list): pollist = [pollist] addlist = self.PolygonCoordinatesVariable2polygonicmask(self.sel_pol.get()) if not isinstance(addlist[0],list): addlist = [addlist] for pol in addlist: if pol not in pollist: pollist.append(pol) self.PolygonCoordinatesVariable.set(self.polygonicmask2PolygonCoordinatesVariable(pollist)) self.copypolygondialog.destroy() self.Menu_Main_Masking_Polygonic() self.grab_set() def Menu_Main_Masking_Polygonic_Picture(self): source_ = self.setup[self.AnalysisNoVariable.get()-1]['source'] source = sources.getProxySource(self.Message,source_,self.proxylist) if source['protocol'] == 'LOCAL' and 'temporary' in source and source['temporary']: tkMessageBox.showwarning('No directory','Directory does not exist. This camera was temporarily added and the images of the camera refer to local directories and they do not exist. It probably means that the setup file loaded is saved in another computer with a camera network or camera which is not defined identically in this computer. To fix it, load the setup file again, confirm the permanent save of the camera/network and the open camera network manager and set up directories accordingly.') return False self.ClearMenu() self.ActiveMenu.set("Choose Picture ") self.Menu_Prev("Polygonic Masking","self.Menu_Main_Masking_Polygonic") self.Menu_Choose_Picture() def Menu_Main_Calculations(self): self.ClearMenu() self.ActiveMenu.set("Analyses") self.Menu_Prev("Main Menu","self.Menu_Main") NItems = 10 space = 0.02 Item = 1 self.MenuItem1 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="<",command=self.CalculationNoMinus) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.1,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem8 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Analysis ",anchor='e',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.2,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem9 = Tkinter.Label(self,textvariable=self.CalculationNoVariable,anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.6,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem2 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text=">",command=self.CalculationNoPlus) self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.8,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.1,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 9 self.MenuItem3 = Tkinter.Button(self,text=u"Add New",command=self.CalculationNoNew,activebackground='green4',activeforeground='white') self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem4 = Tkinter.Button(self,text=u"Delete",command=self.CalculationNoDelete,activebackground='red3',activeforeground='white') self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 2 self.MenuItem5 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Algorithm:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 3 self.MenuItem6 = Tkinter.OptionMenu(self,self.CalculationNameVariable,*calcnames_en) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 10 self.MenuItem7 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Set parameters",anchor="c",command=self.Menu_Main_Calculations_Parameters,activebackground='gold',activeforeground='black') self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem10 = Tkinter.Label(self,wraplength=self.MenuX*0.8,textvariable=self.CalculationDescriptionVariable,anchor='w',justify='left') self.MenuItem10.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(0.25*NItems+1)*space)/(0.25*NItems)) self.parampage = 1 def Menu_Main_Calculations_Parameters(self): self.ClearMenu() self.ActiveMenu.set("Set parameters") self.Menu_Prev("Analyses","self.Menu_Main_Calculations") calcindex = calcnames.index(self.CalculationNameVariable.get()) space = 0.02 if len(paramnames[calcindex]) == 0: NItems = 5 Item = 3 self.MenuItem5 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="No parameters to set for the selected analysis.",anchor='c') self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) else: NItems = self.MenuItemMax if len(paramnames[calcindex]) >= self.MenuItemMax/2: self.parampages = (len(paramnames[calcindex])+(len(paramnames[calcindex])%(self.MenuItemMax/2 - 1) != 0)*((self.MenuItemMax/2 - 1)-len(paramnames[calcindex])%(self.MenuItemMax/2 - 1))) / (self.MenuItemMax/2 - 1) self.geometry(str(self.WindowX+(len(paramnames[calcindex])/self.MenuItemMax/2)*self.MenuX)+"x"+str(self.WindowY)) try: self.PictureCanvas.destroy() except: pass Item = self.MenuItemMax self.MenuItem111 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="<",command=self.parampageMinus) self.MenuItem111.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem112 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text=">",command=self.parampagePlus) self.MenuItem112.place(x=self.MenuOSX+self.MenuX*0.7,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem113 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Page "+str(self.parampage),anchor='c') self.MenuItem113.place(x=self.MenuOSX+self.MenuX*0.3,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 0 else: self.parampages = 1 numbox = 0 NItems -= numbox % 2 Item = (NItems - len(paramnames[calcindex])*2 + numbox)/2 j = 3 for i in range(len(paramnames[calcindex])): paramname = paramnames[calcindex][i] paramhelp = paramhelps[calcindex][i] paramopt = paramopts[calcindex][i] i = str(i) exec("self.p"+i+"Var = Tkinter.StringVar()") exec("self.p"+i+"Var.set(self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())][paramname])") if int(i) / (self.MenuItemMax/2 - 1) + 1 != self.parampage: continue if isinstance(paramopt,list): exec("self.p"+i+"VarOpt = Tkinter.StringVar()") exec("self.p"+i+"VarOpt.set(paramopt[int(float(self.p"+i+"Var.get()))])") j += 1 Item += 1 exec("self.MenuItem"+str(j)+" = Tkinter.Label(self,wraplength=self.MenuX*0.8,text='"+paramname+"',anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor)") exec("self.MenuItem"+str(j)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.7,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") j += 1 exec("self.MenuItem"+str(j)+" = Tkinter.Button(self,wraplength=self.MenuX*0.8,text='?',anchor='c',command=lambda: tkMessageBox.showinfo('"+paramname+"','"+paramhelp+"'))") exec("self.MenuItem"+str(j)+".place(x=self.MenuOSX+self.MenuX*0.8,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.1,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") j += 1 Item += 1 exec("self.MenuItem"+str(j)+" = Tkinter.OptionMenu(self,self.p"+i+"VarOpt,*paramopt)") exec("self.MenuItem"+str(j)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") else: if paramopt == "Checkbox": exec("self.p"+i+"Var.set(int(float(self.p"+i+"Var.get())))") j += 1 Item += 1 exec("self.MenuItem"+str(j)+" = Tkinter.Label(self,wraplength=self.MenuX*0.8,text='"+paramname+"',anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor)") exec("self.MenuItem"+str(j)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.7,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") j += 1 exec("self.MenuItem"+str(j)+" = Tkinter.Button(self,wraplength=self.MenuX*0.8,text='?',anchor='c',command=lambda: tkMessageBox.showinfo('"+paramname+"','"+paramhelp+"'))") exec("self.MenuItem"+str(j)+".place(x=self.MenuOSX+self.MenuX*0.8,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.1,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") j += 1 Item += 1 exec("self.MenuItem"+str(j)+" = Tkinter.Checkbutton(self,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text='Enable/Include/Calculate',variable=self.p"+i+"Var)") exec("self.MenuItem"+str(j)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") else: j += 1 Item += 1 exec("self.MenuItem"+str(j)+" = Tkinter.Label(self,wraplength=self.MenuX*0.8,text='"+paramname+"',anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor)") exec("self.MenuItem"+str(j)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.7,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") j += 1 exec("self.MenuItem"+str(j)+" = Tkinter.Button(self,wraplength=self.MenuX*0.8,text='?',anchor='c',command=lambda: tkMessageBox.showinfo('"+paramname+"','"+paramhelp+"'))") exec("self.MenuItem"+str(j)+".place(x=self.MenuOSX+self.MenuX*0.8,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.1,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") j += 1 Item += 1 exec("self.MenuItem"+str(j)+" = Tkinter.Entry(self,justify='center',textvariable=self.p"+i+"Var)") exec("self.MenuItem"+str(j)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") def parampageMinus(self): self.UpdateSetup() if self.parampage == 1: self.parampage = self.parampages else: self.parampage -= 1 self.Menu_Main_Calculations_Parameters() def parampagePlus(self): self.UpdateSetup() if self.parampage == self.parampages: self.parampage = 1 else: self.parampage += 1 self.Menu_Main_Calculations_Parameters() def Menu_Main_Results(self): self.ClearMenu() if self.ActiveMenu.get() != "Customize Graph": self.ReadResults() self.ActiveMenu.set('Result Viewer') self.Menu_Prev("Main Menu","self.Menu_Main") NItems = 10 space = 0.02 flist = ['(Choose) Custom directory','Result Directory'] for f in os.listdir(self.resultspath.get()): if os.path.isdir(os.path.join(self.resultspath.get(),f)): flist.append(f) flist.sort() self.MenuItem9 = Tkinter.OptionMenu(self,self.ResultFolderNameVariable,*flist[::-1]) if self.NumResultsVariable.get() == 0: self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="No results in the directory",anchor="c") self.MenuItem8 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="No results in the directory",anchor="c") self.MenuItem5Switch.set(False) self.MenuItem5 = Tkinter.Checkbutton(self,variable=self.MenuItem5Switch,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text="Plot",state="disabled") self.MenuItem7 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Open File",anchor="c",command=self.Menu_Main_Results_Open,state="disabled") #self.MenuItem11 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Create Animation",anchor="c",command=self.Menu_Main_Results_Animate,state="disabled") else: self.MenuItem4 = Tkinter.OptionMenu(self,self.ResultNameVariable,1,2) self.LoadResultNameVariable() self.MenuItem8 = Tkinter.OptionMenu(self,self.ResultVariableNameVariable,1,2) self.LoadResultVariableNameVariable() self.MenuItem5 = Tkinter.Checkbutton(self,variable=self.MenuItem5Switch,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text="Plot") self.MenuItem7 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Open File",anchor="c",command=self.Menu_Main_Results_Open,state="normal") #self.MenuItem11 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Create Animation",anchor="c",command=self.Menu_Main_Results_Animate,state="normal") if self.PlotCanvasSwitch.get() == False: self.MenuItem6 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Customize Graph",anchor="c",command=self.Menu_Main_Results_Customize,state="disabled") self.MenuItem13 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="-",command=self.SensMinus,state="disabled") self.MenuItem14 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="+",command=self.SensPlus,state="disabled") else: self.MenuItem6 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Customize Graph",anchor="c",command=self.Menu_Main_Results_Customize,state="normal") self.MenuItem13 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="-",command=self.SensMinus,state="normal") self.MenuItem14 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="+",command=self.SensPlus,state="normal") Item = 1 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Directory:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 2 self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 3 self.MenuItem2 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="File:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem3 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Variable:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 9 self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 10 #self.MenuItem11.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) #Item = 11 self.MenuItem13.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem14.place(x=self.MenuOSX+self.MenuX*0.7,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem15 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Size") self.MenuItem15.place(x=self.MenuOSX+self.MenuX*0.3,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuEnablerFunc.set("self.MenuEnabler([5,[6,13,14],['self.PlotCanvasSwitch'],['0'],['self.PlotCanvasSwitch.set(self.MenuItem5Switch.get())']])") exec(self.MenuEnablerFunc.get()) def LoadResultVariableNameVariable(self,*args): try: self.MenuItem8['menu'].delete(0,'end') for caption in self.ResultsCaptions: if caption != 'Date' and caption != 'Time' and caption != 'Latitude' and caption != 'Longitude' and not (len(self.ResultsData[1][self.ResultsCaptions.index(caption)*2+1].shape) == 1 and self.ResultsCaptions.index(caption) == 0): self.MenuItem8['menu'].add_command(label=caption, command=lambda caption=caption: self.ResultVariableNameVariable.set(caption)) except: pass def LoadResultNameVariable(self,*args): try: self.MenuItem4['menu'].delete(0,'end') for i in range(self.NumResultsVariable.get()): caption = self.ResultsList[i][0] self.MenuItem4['menu'].add_command(label=caption, command=lambda caption=caption: self.ResultNameVariable.set(caption)) except: pass def Menu_Main_Results_Open(self): webbrowser.open(self.ResultsFileNameVariable.get(),new=2) def Menu_Main_Results_Animate(self): self.ClearMenu() self.ActiveMenu.set("Create Animation") self.Menu_Prev('Result Viewer',"self.Menu_Main_Results") NItems = 14 space = 0.02 Item = 1 self.ResultsAnimateTemporalMode = Tkinter.StringVar() self.ResultsAnimateTemporalMode.set('Range in the data') self.ResultsAnimateTemporalMode.trace_variable('w',self.callbackResultsAnimateTemporalMode) self.ResultsAnimateTemporalRange = [] self.ResultsAnimateTemporalThreshold = Tkinter.StringVar() self.ResultsAnimateTemporalThreshold.set('24.0') self.ResultsAnimateReplaceImages = Tkinter.StringVar() self.ResultsAnimateReplaceImages.set('Monochromatic Noise') self.ResultsAnimateBarWidth = Tkinter.StringVar() self.ResultsAnimateBarWidth.set('1.5') self.ResultsAnimateBarLocation = Tkinter.StringVar() self.ResultsAnimateBarLocation.set('Right') self.ResultsAnimateDuration = Tkinter.StringVar() self.ResultsAnimateDuration.set(paramdefs[calcids.index('ANIM001')][paramnames[calcids.index('ANIM001')].index('Duration')]) self.ResultsAnimateFPS = Tkinter.StringVar() self.ResultsAnimateFPS.set(paramdefs[calcids.index('ANIM001')][paramnames[calcids.index('ANIM001')].index('Frames per second')]) self.ResultsAnimateResolution = Tkinter.StringVar() self.ResultsAnimateResolution.set(paramopts[calcids.index('ANIM001')][paramnames[calcids.index('ANIM001')].index('Resolution')][int(paramdefs[calcids.index('ANIM001')][paramnames[calcids.index('ANIM001')].index('Resolution')])]) self.ResultsAnimateFormat = Tkinter.StringVar() self.ResultsAnimateFormat.set(paramopts[calcids.index('ANIM001')][paramnames[calcids.index('ANIM001')].index('Format')][int(paramdefs[calcids.index('ANIM001')][paramnames[calcids.index('ANIM001')].index('Format')])]) self.ResultsAnimateVarsToPlot = [] [fname,metadata] = self.ResultsList[zip(*self.ResultsList)[0].index(self.ResultNameVariable.get())][1:] if os.path.splitext(fname)[1] != '.dat': tkMessageBox.showerror('Data inconsistent','Data format is inconsistent. Can not create animation.') self.Menu_Main_Results() try: time_key_ok = False metadata['network'] metadata['source'] deftoplot = ['Snow Cover - Rectified','Snow Cover','Red Fraction','Green Fraction','Brightness'] deftocolor = [['#000000','#FFFFFF'],['#000000','#FF0000'],['#000000','#00FF00'],['#000000','#FFFFFF'],['#000000','#FFFFFF']] defminmax = [[0.0,1.0],[0.0,1.0],[0.0,1.0],[0.0,1.0],[0.0,1.0]] for i in range(9999): if 'var'+str(i) in metadata: if metadata['var'+str(i)] == 'Time': self.ResultsAnimateVarsToPlot.append([1,metadata['var'+str(i)],'#000000','#A37FFF','','']) time_key_ok = True else: if metadata['var'+str(i)] in deftoplot: self.ResultsAnimateVarsToPlot.append([1,metadata['var'+str(i)],deftocolor[deftoplot.index(metadata['var'+str(i)])][0],deftocolor[deftoplot.index(metadata['var'+str(i)])][1],defminmax[deftoplot.index(metadata['var'+str(i)])][0],defminmax[deftoplot.index(metadata['var'+str(i)])][1]]) else: self.ResultsAnimateVarsToPlot.append([0,metadata['var'+str(i)],'#000000','#FFFFFF','','']) del metadata['var'+str(i)] else: break if not time_key_ok: tkMessageBox.showerror('Metadata inconsistent','Time information for the images is not found in results file. Can not create animation.') self.Menu_Main_Results() except: tkMessageBox.showerror('Metadata not found','Metadata is not complete or inconsistent in the results. Can not create animation.') self.Menu_Main_Results() try: self.ResultsAnimateSource = sources.getSource(self.Message,sources.getSources(self.Message,self.sourcelist,metadata['network'],'network'),metadata['source']) del metadata['network'] del metadata['source'] except: tkMessageBox.showerror('Camera not found','The camera which the results are from can not be found in the camera list. Check the camera networks and camera. Camera network name: '+metadata['network']+', camera name: '+metadata['source']+'.') self.Menu_Main_Results() self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Temporal Selection",anchor='c') self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem2 = Tkinter.OptionMenu(self,self.ResultsAnimateTemporalMode,'Date interval','Range in the data') self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem21 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Maximum time difference (hours)",anchor='c') self.MenuItem21.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem22 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.ResultsAnimateTemporalThreshold) self.MenuItem22.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem3 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Replace missing images with",anchor='c') self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem4 = Tkinter.OptionMenu(self,self.ResultsAnimateReplaceImages,'Closest image','Blank (Black)','Blank (White)','Monochromatic Noise') self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem6 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Variables to plot as bars",command=self.Menu_Main_Results_Animate_Variables) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem7 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Bar thickness (% of image)",anchor='c') self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem8 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.ResultsAnimateBarWidth) self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem9 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Bar location",anchor='c') self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem10 = Tkinter.OptionMenu(self,self.ResultsAnimateBarLocation,'Right','Left','Top','Bottom') self.MenuItem10.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem11 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Duration",anchor='c') self.MenuItem11.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem12 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.ResultsAnimateDuration) self.MenuItem12.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem13 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Frame per second",anchor='c') self.MenuItem13.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem14 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.ResultsAnimateFPS) self.MenuItem14.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem15 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Resolution",anchor='c') self.MenuItem15.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem16 = Tkinter.OptionMenu(self,self.ResultsAnimateResolution,*paramopts[calcids.index('ANIM001')][paramnames[calcids.index('ANIM001')].index('Resolution')]) self.MenuItem16.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem17 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Format",anchor='c') self.MenuItem17.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) self.MenuItem18 = Tkinter.OptionMenu(self,self.ResultsAnimateFormat,*paramopts[calcids.index('ANIM001')][paramnames[calcids.index('ANIM001')].index('Format')]) self.MenuItem18.place(x=self.MenuOSX+self.MenuX*0.5,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.4,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item += 1 self.MenuItem20 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Create",command=self.Menu_Main_Results_Animate_Create) self.MenuItem20.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def callbackResultsAnimateTemporalMode(self,*args): if self.ResultsAnimateTemporalMode.get() == 'Range in the data': self.ResultsAnimateTemporalRange = [] if self.ResultsAnimateTemporalMode.get() == 'Date interval': d1 = Tkinter.StringVar() d2 = Tkinter.StringVar() if self.ResultsAnimateTemporalRange == []: d1.set('01.01.2016') d2.set('31.12.2016') else: d1.set(self.ResultsAnimateTemporalRange[0]) d2.set(self.ResultsAnimateTemporalRange[1]) self.Win1 = Tkinter.Toplevel(self,padx=10,pady=10) self.Win1.grab_set() self.Win1.wm_title('Date interval') Tkinter.Label(self.Win1,text="Date interval:",anchor='c').grid(sticky='w'+'e',row=1,column=1,columnspan=3) Tkinter.Entry(self.Win1,textvariable=d1,justify="center").grid(sticky='w'+'e',row=2,column=1,columnspan=1) Tkinter.Label(self.Win1,text=" - ",anchor='c').grid(sticky='w'+'e',row=2,column=2,columnspan=1) Tkinter.Entry(self.Win1,textvariable=d2,justify="center").grid(sticky='w'+'e',row=2,column=3,columnspan=1) Tkinter.Button(self.Win1 ,text='Cancel',command=self.CloseWin_1).grid(sticky='w'+'e',row=3,column=1,columnspan=1) Tkinter.Button(self.Win1 ,text='OK',command=self.Win1.destroy).grid(sticky='w'+'e',row=3,column=3,columnspan=1) self.centerWindow(self.Win1) self.Win1.wait_window() self.ResultsAnimateTemporalRange = [d1.get(),d2.get()] self.CloseWin_1() def Menu_Main_Results_Animate_Variables(self): self.Win1 = Tkinter.Toplevel(self,padx=10,pady=10) self.Win1.grab_set() self.Win1.wm_title('Choose Variables') Tkinter.Label(self.Win1,text="Plot",anchor='w').grid(sticky='w'+'e',row=1,column=1,columnspan=1) Tkinter.Label(self.Win1,text="Background Color",anchor='w').grid(sticky='w'+'e',row=1,column=2,columnspan=1) Tkinter.Label(self.Win1,text="Foreground Color",anchor='w').grid(sticky='w'+'e',row=1,column=3,columnspan=1) Tkinter.Label(self.Win1,text="Min. Value",anchor='w').grid(sticky='w'+'e',row=1,column=4,columnspan=1) Tkinter.Label(self.Win1,text="Max. Value",anchor='w').grid(sticky='w'+'e',row=1,column=5,columnspan=1) for i,v in enumerate(self.ResultsAnimateVarsToPlot): exec("self.p"+str(i)+"VarPlot = Tkinter.BooleanVar()") exec("self.p"+str(i)+"VarPlot.set(bool(int(v[0])))") exec("self.p"+str(i)+"VarBgColor = Tkinter.StringVar()") exec("self.p"+str(i)+"VarBgColor.set(v[2])") exec("self.p"+str(i)+"VarFgColor = Tkinter.StringVar()") exec("self.p"+str(i)+"VarFgColor.set(v[3])") exec("self.p"+str(i)+"VarMin = Tkinter.StringVar()") exec("self.p"+str(i)+"VarMin.set(v[4])") exec("self.p"+str(i)+"VarMax = Tkinter.StringVar()") exec("self.p"+str(i)+"VarMax.set(v[5])") exec("Tkinter.Checkbutton(self.Win1,height=self.CheckButtonY,width=self.CheckButtonX,variable=self.p"+str(i)+"VarPlot,text=v[1]).grid(sticky='w',row=2+i,column=1,columnspan=1)") exec("self.MenuItem"+str(i)+"1 = Tkinter.OptionMenu(self.Win1,self.p"+str(i)+"VarBgColor,*self.Colors)") exec("self.MenuItem"+str(i)+"1['menu'].delete(0,'end')") for color in self.Colors: exec("self.MenuItem"+str(i)+"1['menu'].add_command(label='Change',command=Tkinter._setit(self.p"+str(i)+"VarBgColor,color),background=color,foreground=color,activebackground=color,activeforeground=color)") exec("self.MenuItem"+str(i)+"1.grid(sticky='w'+'e',row=2+i,column=2,columnspan=1)") exec("self.MenuItem"+str(i)+"2 = Tkinter.OptionMenu(self.Win1,self.p"+str(i)+"VarFgColor,*self.Colors)") exec("self.MenuItem"+str(i)+"2['menu'].delete(0,'end')") for color in self.Colors: exec("self.MenuItem"+str(i)+"2['menu'].add_command(label='Change',command=Tkinter._setit(self.p"+str(i)+"VarFgColor,color),background=color,foreground=color,activebackground=color,activeforeground=color)") exec("self.MenuItem"+str(i)+"2.grid(sticky='w'+'e',row=2+i,column=3,columnspan=1)") exec("Tkinter.Entry(self.Win1,textvariable=self.p"+str(i)+"VarMin,).grid(sticky='w',row=2+i,column=4,columnspan=1)") exec("Tkinter.Entry(self.Win1,textvariable=self.p"+str(i)+"VarMax,).grid(sticky='w',row=2+i,column=5,columnspan=1)") Tkinter.Button(self.Win1,wraplength=self.MenuX*0.8,text="OK",command=self.Menu_Main_Results_Animate_Variables_OK).grid(sticky='w'+'e',row=2+len(self.ResultsAnimateVarsToPlot),column=5,columnspan=1) self.centerWindow(self.Win1) self.Win1.wait_window() def Menu_Main_Results_Animate_Variables_OK(self): for i,v in enumerate(self.ResultsAnimateVarsToPlot): exec("self.ResultsAnimateVarsToPlot[i][0] = int(self.p"+str(i)+"VarPlot.get())") exec("self.ResultsAnimateVarsToPlot[i][2] = self.p"+str(i)+"VarBgColor.get()") exec("self.ResultsAnimateVarsToPlot[i][3] = self.p"+str(i)+"VarFgColor.get()") exec("self.ResultsAnimateVarsToPlot[i][4] = self.p"+str(i)+"VarMin.get()") exec("self.ResultsAnimateVarsToPlot[i][5] = self.p"+str(i)+"VarMax.get()") self.CloseWin_1() def Menu_Main_Results_Animate_Create(self): fname = self.ResultsList[zip(*self.ResultsList)[0].index(self.ResultNameVariable.get())][1] [resname, resdata] = readers.readDAT(fname)[0] if 'Time' not in resdata: tkMessageBox.showerror('Metadata inconsistent','Time information for the images is not found in results file. Can not create animation.') return False self.Message.set('Creating animation...|busy:True') (imglist,datetimelist) = fetchers.fetchImages(self, self.Message, self.ResultsAnimateSource, self.proxy, self.connection, self.imagespath.get(), [0,0,0,0,'List',resdata[resdata.index('Time')*2+1]], online=self.imagesdownload.get()) mask = None fnames = calcfuncs.animateImagesFromResults(imglist, datetimelist, mask, settings,self.Message, self.ResultsAnimateTemporalMode.get(), self.ResultsAnimateTemporalRange, self.ResultsAnimateTemporalThreshold.get(), self.ResultsAnimateReplaceImages.get(), self.ResultsAnimateVarsToPlot, self.ResultsAnimateBarWidth.get(), self.ResultsAnimateBarLocation.get(), self.ResultsAnimateDuration.get(), self.ResultsAnimateFPS.get(), self.ResultsAnimateResolution.get(),self.ResultsAnimateFormat.get(), resdata) if fnames is not False: fnames = fnames[0][1][1] else: self.Message.set('Animation creation failed.|busy:False') tkMessageBox.showerror('Animation','Animation creation failed.') return False fnamet = os.path.splitext(fname)[0]+os.path.splitext(fnames)[1] if os.path.isfile(fnamet): os.remove(fnamet) shutil.copy(fnames,fnamet) if os.path.isfile(fnames): os.remove(fnames) self.Message.set('Animation is saved as '+fnamet+'|busy:False') tkMessageBox.showinfo('Animation','Animation is saved as '+fnamet+'.') def Menu_Main_Results_Customize(self): self.ClearMenu() self.ActiveMenu.set("Customize Graph") self.Menu_Prev('Result Viewer',"self.Menu_Main_Results") vars = False styles = True NItems = 9 if self.ResultVariableNameVariable.get() == "Merged Plot": #or self.ResultVariableNameVariable.get() == "Composite Image" vars = True if NItems == 10: Nitems = 9 else: NItems = 10 if self.ResultVariableNameVariable.get() == "Composite Image": styles = False if NItems == 10: Nitems = 9 else: NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Checkbutton(self,variable=self.LegendVar,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text="Legend/Color bar") self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) if vars: #Item = Item+int(vars) Item += 1 self.MenuItem2 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Variables",anchor="c",command=self.Menu_Main_Results_Customize_Variables) self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) #Item = 4+int(vars) Item += 1 self.MenuItem5 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Extent",anchor="c",command=self.Menu_Main_Results_Customize_Extent) self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) if styles: #Item = 4+int(vars)+int(styles) Item += 1 if len(self.ResultsData[1][self.ResultsCaptions.index(self.ResultVariableNameVariable.get())*2+1].shape) == 1: self.MenuItem7 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Axes",anchor="c",command=self.Menu_Main_Results_Customize_Axes) self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) #Item = 6+int(vars) Item += 1 self.MenuItem4 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Style",anchor="c",command=self.Menu_Main_Results_Customize_Style) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) #Item = 5+int(vars)+int(styles) Item += 1 self.MenuItem3 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Save plot as PNG Image",anchor="c",command=self.SavePlot) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) #Item = 6+int(vars)+int(styles) #self.MenuItem7 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Save data as PNG Image",anchor="c",command=self.SaveData) #self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Results_Customize_Axes(self): self.ClearMenu() self.ActiveMenu.set("Axes") self.Menu_Prev("Customize Graph","self.Menu_Main_Results_Customize") NItems = 10 space = 0.02 Item = 3 self.MenuItem1 = Tkinter.Checkbutton(self,variable=self.PlotVarLogXSwitch,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text='Logarithmic X') self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem2 = Tkinter.Checkbutton(self,variable=self.PlotVarLogYSwitch,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text='Logarithmic Y') self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem3 = Tkinter.Checkbutton(self,variable=self.PlotVarInvertXSwitch,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text='Invert X') self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem4 = Tkinter.Checkbutton(self,variable=self.PlotVarInvertYSwitch,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text='Invert Y') self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Results_Customize_Style(self): self.ClearMenu() self.ActiveMenu.set("Style") self.Menu_Prev("Customize Graph","self.Menu_Main_Results_Customize") NItems = 10 space = 0.02 if len(self.ResultsData[1][self.ResultsCaptions.index(self.ResultVariableNameVariable.get())*2+1].shape) == 2: for i,c in enumerate(cmaps): Item = i*2+2 exec("self.MenuItem"+str(i*2)+" = Tkinter.Label(self,wraplength=self.MenuX*0.8,text=c[0],anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor)") exec("self.MenuItem"+str(i*2)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") Item = i*2+3 exec("self.MenuItem"+str(i*2+1)+" = Tkinter.OptionMenu(self,self.PlotVarColormap,*c[1])") exec("self.MenuItem"+str(i*2+1)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") if len(self.ResultsData[1][self.ResultsCaptions.index(self.ResultVariableNameVariable.get())*2+1].shape) == 1: Item = 3 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Line",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem2 = Tkinter.OptionMenu(self,self.PlotVarStyle,'-','--','-.',':','None') self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem3 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Marker",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 markers = [] for m in matplotlib.lines.Line2D.markers: try: if len(m) == 1 and m != ' ': markers.append(m) except TypeError: pass markers += [r'$\lambda$',r'$\bowtie$',r'$\circlearrowleft$',r'$\clubsuit$',r'$\checkmark$'] self.MenuItem4 = Tkinter.OptionMenu(self,self.PlotVarMarker,*markers) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) if not self.ResultVariableNameVariable.get() == "Merged Plot": Item = 7 self.MenuItem5 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Color",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem6 = Tkinter.OptionMenu(self,self.PlotVarColor,'blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'black') self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def Menu_Main_Results_Customize_Variables(self): self.ClearMenu() self.ActiveMenu.set("Variables") self.Menu_Prev("Customize Graph","self.Menu_Main_Results_Customize") Results_Captions = [] if self.ResultVariableNameVariable.get() == "Composite Image": Results_Captions = ["R-Channel","G-Channel","B-Channel"] if self.ResultVariableNameVariable.get() == "Merged Plot": Results_Captions = deepcopy(self.ResultsCaptions[1:-1]) NItems = self.MenuItemMax-2+((len(Results_Captions))%2) space = 0.02 for i in range(len(Results_Captions)): Item = i + (NItems - len(Results_Captions))/2 lastitem = Item exec("self.MenuItem"+str(i)+" = Tkinter.Checkbutton(self,variable=self.PlotVar"+str(i)+"Switch,wraplength=self.MenuX*0.7,height=self.CheckButtonY,width=self.CheckButtonX,text='"+Results_Captions[int(i)]+"')") exec("self.MenuItem"+str(i)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") Item = lastitem + 1 exec("self.MenuItem"+str(self.MenuItemMax-2)+" = Tkinter.Button(self,text='Select All',wraplength=self.MenuX*0.8,command=self.Menu_Main_Results_Customize_Variables_All)") exec("self.MenuItem"+str(self.MenuItemMax-2)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") Item = lastitem + 2 exec("self.MenuItem"+str(self.MenuItemMax-1)+" = Tkinter.Button(self,text='Select None',wraplength=self.MenuX*0.8,command=self.Menu_Main_Results_Customize_Variables_None)") exec("self.MenuItem"+str(self.MenuItemMax-1)+".place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems)") def Menu_Main_Results_Customize_Variables_All(self): for i in range(self.MenuItemMax+1): exec("self.PlotVar"+str(i)+"Switch = Tkinter.BooleanVar()") exec("self.PlotVar"+str(i)+"Switch.set(True)") exec("self.PlotVar"+str(i)+"Switch.trace('w',self.callbackResultsVar)") self.callbackResultsVar() self.Menu_Main_Results_Customize_Variables() def Menu_Main_Results_Customize_Variables_None(self): for i in range(self.MenuItemMax+1): exec("self.PlotVar"+str(i)+"Switch = Tkinter.BooleanVar()") exec("self.PlotVar"+str(i)+"Switch.set(False)") exec("self.PlotVar"+str(i)+"Switch.trace('w',self.callbackResultsVar)") self.callbackResultsVar() self.Menu_Main_Results_Customize_Variables() def Menu_Main_Results_Customize_Extent(self): self.ClearMenu() self.ActiveMenu.set("Extent") self.Menu_Prev("Customize Graph","self.Menu_Main_Results_Customize") NItems = 10 space = 0.02 self.PlotExtentRead() Item = 1 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="X Axis Start:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 2 self.MenuItem3 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.PlotXStartVariable) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 3 self.MenuItem4 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="X Axis End:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem4.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem6 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.PlotXEndVariable) self.MenuItem6.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem5 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Y Axis Start:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem2 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.PlotYStartVariable) self.MenuItem2.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem7 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Y Axis End:",anchor='c',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem7.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 8 self.MenuItem8 = Tkinter.Entry(self,justify="center",width=10,textvariable=self.PlotYEndVariable) self.MenuItem8.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 9 self.MenuItem9 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Apply",anchor="c",command=self.PlotExtentWrite) self.MenuItem9.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 10 self.MenuItem10 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Defaults",anchor="c",command=self.PlotExtentDefault) self.MenuItem10.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) def PlotExtentDefault(self,*args): self.PlotXStartFactor.set(0) self.PlotXEndFactor.set(0) if "Merged Plot" in self.ResultsCaptions: self.PlotYStartFactor.set(-0.1) self.PlotYEndFactor.set(-0.1) else: self.PlotYStartFactor.set(0) self.PlotYEndFactor.set(0) self.PlotExtentRead() self.DrawResults() def PlotExtentRead(self,*args): if self.ResultsCaptions[0] == "Time" or self.ResultsCaptions[0] == "Date": if self.ResultsCaptions[0] == "Time": self.PlotXStartVariable.set(self.XMin + datetime.timedelta(seconds=self.PlotXStartFactor.get()*self.XDist)) self.PlotXEndVariable.set(self.XMax - datetime.timedelta(seconds=self.PlotXEndFactor.get()*self.XDist)) else: self.PlotXStartVariable.set(self.XMin + datetime.timedelta(seconds=self.PlotXStartFactor.get()*self.XDist)) self.PlotXEndVariable.set(self.XMax - datetime.timedelta(seconds=self.PlotXEndFactor.get()*self.XDist)) else: self.PlotXStartVariable.set(self.XMin + self.PlotXStartFactor.get()*self.XDist) self.PlotXEndVariable.set(self.XMax - self.PlotXEndFactor.get()*self.XDist) self.PlotYStartVariable.set(self.YMin + self.PlotYStartFactor.get()*self.YDist) self.PlotYEndVariable.set(self.YMax - self.PlotYEndFactor.get()*self.YDist) def PlotExtentWrite(self,*args): if self.ResultsCaptions[0] == "Time" or self.ResultsCaptions[0] == "Date": if self.ResultsCaptions[0] == "Time": dif = parsers.strptime2(self.PlotXStartVariable.get(),"%Y-%m-%d %H:%M:%S")[0]- self.XMin self.PlotXStartFactor.set(float(dif.seconds+dif.days*86400)/self.XDist) dif = self.XMax - parsers.strptime2(self.PlotXEndVariable.get(),"%Y-%m-%d %H:%M:%S")[0] self.PlotXEndFactor.set(float(dif.seconds+dif.days*86400)/self.XDist) else: dif = parsers.strptime2(self.PlotXStartVariable.get(),"%Y-%m-%d")[1] - self.XMin self.PlotXStartFactor.set(float(dif.seconds+dif.days*86400)/self.XDist) dif = self.XMax - parsers.strptime2(self.PlotXEndVariable.get(),"%Y-%m-%d")[1] self.PlotXEndFactor.set(float(dif.seconds+dif.days*86400)/self.XDist) else: self.PlotXStartFactor.set((- self.XMin + float(self.PlotXStartVariable.get()))/self.XDist) self.PlotXEndFactor.set((self.XMax - float(self.PlotXEndVariable.get()))/self.XDist) if self.YDist == 0: self.PlotYStartFactor.set(0) self.PlotYEndFactor.set(0) else: self.PlotYStartFactor.set((-self.YMin + float(self.PlotYStartVariable.get()))/self.YDist) self.PlotYEndFactor.set((self.YMax - float(self.PlotYEndVariable.get()))/self.YDist) if self.PlotXStartFactor.get() < 0 or self.PlotXStartFactor.get() > 1: self.PlotXStartFactor.set(0) tkMessageBox.showwarning('Incorrect Value','Extent is ouf of bounds for X Axis Start value. Value is returned to default.') if self.PlotXEndFactor.get() < 0 or self.PlotXEndFactor.get() > 1: self.PlotXEndFactor.set(0) tkMessageBox.showwarning('Incorrect Value','Extent is ouf of bounds for X Axis End value. Value is returned to default.') if "Merged Plot" in self.ResultsCaptions: if self.PlotYStartFactor.get() < -0.1 or self.PlotYStartFactor.get() > 1: self.PlotYStartFactor.set(-0.1) tkMessageBox.showwarning('Incorrect Value','Extent is ouf of bounds for Y Axis Start value. Value is returned to default.') if self.PlotYEndFactor.get() < -0.1 or self.PlotYEndFactor.get() > 1: self.PlotYEndFactor.set(-0.1) tkMessageBox.showwarning('Incorrect Value','Extent is ouf of bounds for Y Axis End value. Value is returned to default.') else: if self.PlotYStartFactor.get() < 0 or self.PlotYStartFactor.get() > 1: self.PlotYStartFactor.set(0) tkMessageBox.showwarning('Incorrect Value','Extent is ouf of bounds for Y Axis Start value. Value is returned to default.') if self.PlotYEndFactor.get() < 0 or self.PlotYEndFactor.get() > 1: self.PlotYEndFactor.set(0) tkMessageBox.showwarning('Incorrect Value','Extent is ouf of bounds for Y Axis End value. Value is returned to default.') self.PlotExtentRead() self.DrawResults() def Menu_Main_Output(self): self.ClearMenu() self.ActiveMenu.set('Results') self.Menu_Prev("Main Menu","self.Menu_Main") NItems = 9 space = 0.02 Item = 3 self.MenuItem13 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="These options will not be stored in setup files",anchor='c',bg='RoyalBlue4',fg='white') self.MenuItem13.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 4 self.MenuItem11 = Tkinter.Label(self,wraplength=self.MenuX*0.8,text="Where to store the analysis results:",anchor='w',bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem11.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 5 self.MenuItem10 = Tkinter.OptionMenu(self,self.outputmodevariable,*output_modes) self.MenuItem10.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem1 = Tkinter.Label(self,wraplength=self.MenuX*0.7,text="Directory to be stored in:",anchor="w",bg=self.MenuTitleBgColor,fg=self.MenuTitleTextColor) self.MenuItem1.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.6,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 6 self.MenuItem5 = Tkinter.Button(self,wraplength=self.MenuX*0.8,text="Browse...",anchor="c",command=self.selectoutputpath) self.MenuItem5.place(x=self.MenuOSX+self.MenuX*0.7,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.2,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) Item = 7 self.MenuItem3 = Tkinter.Label(self,textvariable=self.outputpath,justify="left",wraplength=self.MenuX*0.8) self.MenuItem3.place(x=self.MenuOSX+self.MenuX*0.1,y=self.MenuOSY+Item*space*self.MenuY+(Item-1)*self.MenuY*(1.0-(NItems+1)*space)/NItems,width=self.MenuX*0.8,height=self.MenuY*(1.0-(NItems+1)*space)/NItems) if self.outputmodevariable.get() == output_modes[0]: self.MenuItem5.config(state='disabled') def callbackoutputmode(self,*args): if self.outputmodevariable.get() == output_modes[0]: timelabel = parsers.dTime2fTime(datetime.datetime.now()) self.outputpath.set(os.path.join(self.resultspath.get(),timelabel)) if self.ActiveMenu.get() == 'Results': self.MenuItem5.config(state='disabled') else: if self.ActiveMenu.get() == 'Results': self.MenuItem5.config(state='normal') if not self.selectoutputpath(): self.outputmodevariable.set(output_modes[0]) self.MenuItem5.config(state='disabled') def selectoutputpath(self): self.file_opt = options = {} options['title'] = 'Choose path for results to be stored...' self.Message.set("Choosing path for results to be stored...") if self.outputmodevariable.get() == output_modes[2]: tkMessageBox.showwarning(output_modes[2],'This mode will work if only the setup in the selected directory is identical with your setup. It is designed to analyze new images or images from a different temporal interval with the same other scenario options.\nIf you have lost/did not save your setup, you can load the setup in the results directory which you would choose (Setup -> Load...) and then try this option again.') ask = True while ask: ask = False ans = tkFileDialog.askdirectory(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) self.outputpath.set(ans) if self.outputmodevariable.get() == output_modes[1]: if self.checkemptyoutput(): return True else: ask = True if self.outputmodevariable.get() == output_modes[2]: if self.checkoutputsetup() is False: ask = True else: return True self.Message.set("Selection of path for results to be stored is cancelled.") self.outputmodevariable.set(output_modes[0]) return False def checkemptyoutput(self,out=False): if os.listdir(self.outputpath.get()) == []: if not out: self.Message.set("Path for results to be stored is selected.") return True else: if out: tkMessageBox.showerror('Directory not empty','Chosen directory for the analysis results to be stored is not empty. Analyses have stopped.\nChoose an empty directory for the analysis results to be stored.') else: tkMessageBox.showwarning('Directory not empty','Chosen directory is not empty. Choose an empty directory for the analysis results to be stored.') return False def checkoutputsetup(self,out=False): self.Message.set('Checking consistency of the setup and the setup file in the output directory...') if os.path.isfile(os.path.join(self.outputpath.get(),'setup.cfg')): outputsetup = self.setupFileRead(os.path.join(self.outputpath.get(),'setup.cfg')) setup = deepcopy(self.setup) for s,scenario in enumerate(setup): outputscenario = outputsetup[s] if 'previewimagetime' in scenario and scenario['previewimagetime'] != '' and scenario['previewimagetime']: del scenario['previewimagetime'] if 'previewimagetime' in outputscenario and outputscenario['previewimagetime'] != '' and outputscenario['previewimagetime']: del outputscenario['previewimagetime'] if 'previewimagetime' in scenario['source'] and scenario['source']['previewimagetime'] != '' and scenario['source']['previewimagetime']: del scenario['source']['previewimagetime'] if 'previewimagetime' in outputscenario['source'] and outputscenario['source']['previewimagetime'] != '' and outputscenario['source']['previewimagetime']: del outputscenario['source']['previewimagetime'] if outputsetup == setup: if not out: tkMessageBox.showwarning('Setups consistent','Please read carefully!\nSetup found in the directory is identical with the current one. Results of the analysis will be merged with the ones in the directory.\nThe merging is done assuming that the files in the directory are not modified, which means the data files really belong to the setup file in the directory. If the data is modified, results can be inconsistent and incorrect.\nAlthough the setup file in the directory is checked, in case the current setup is changed before running the analysis, it will also be checked again before running the analyses. If they are inconsistent, analyses will not be run.\nOverlapping results will be skipped, only the images not analzed before will be analzed.') self.Message.set('Setups are consistent.') return outputsetup else: if not out: tkMessageBox.showwarning('Setups inconsistent','Setup found in the directory is not identical with the current one. Choose the correct directory, if there is one.') else: tkMessageBox.showerror('Setups inconsistent','Setup found in the directory for the results to be stored is not identical with the current one. Either current setup or the setup file in the directory is changed.') self.Message.set('Setups are inconsistent.') return False else: if not out: tkMessageBox.showwarning('No setup found','No setup file is found in the directory. Choose the correct directory, if there is one.') else: tkMessageBox.showwarning('No setup found','No setup file is found in the selected directory for the results to be stored.') self.Message.set('No setup file found.') return False def MenuEnabler(self,*args): #[sw,[menuitems],[varstoodef],[defs],func] if self.MenuEnablerFunc.get() != '': for arg in args: swi = arg[0] list = arg[1] exec("sw = self.MenuItem"+str(swi)+"Switch.get()") for item in list: if sw: exec("self.MenuItem"+str(item)+".config(state='normal')") else: exec("self.MenuItem"+str(item)+".config(state='disabled')") for i in range(len(arg[2])): exec("val = str(" + arg[2][i] + ".get())") defval = arg[3][i] if sw == 2: if val != defval: exec("self.MenuItem"+str(swi)+"Switch.set(1)") else: exec("self.MenuItem"+str(swi)+"Switch.set(0)") else: if sw == 0 and val != defval: exec(arg[2][i]+".set('"+defval+"')") for com in arg[4]: exec(com) def callbackActiveMenu(self,*args): if self.ActiveMenu.get() not in self.prevonlist: self.PreviewCanvasSwitch.set(False) if self.ActiveMenu.get() not in self.plotonlist: self.PlotCanvasSwitch.set(False) self.SensVariable.set(self.SensVariableDef) def callbackMenuItemSwitch(self,*args): exec(self.MenuEnablerFunc.get()) def callbackPreviewCanvasSwitch(self,event,*args): self.UpdatePictureFileName() self.UpdatePictures() if self.ActiveMenu.get() == "Polygonic Masking": try: self.MenuItem18.config(bg=self.PolygonColor0.get()) self.MenuItem20.config(bg=self.PolygonColor1.get()) except: pass def callbackPlotCanvasSwitch(self,event,*args): self.DrawResults() def ReadResults(self): if self.ResultFolderNameVariable.get() == 'Results Directory': ResultFolderNameVariable = '' elif self.ResultFolderNameVariable.get() == '(Choose) Custom directory': self.file_opt = options = {} options['title'] = 'Choose path to load results...' ans = tkFileDialog.askdirectory(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) ResultFolderNameVariable = ans self.ResultFolderNameVariable.set(ans) self.Message.set('Directory chosen for results viewer.') else: ResultFolderNameVariable = '' self.ResultFolderNameVariable.set('Results Directory') else: ResultFolderNameVariable = self.ResultFolderNameVariable.get() if os.path.split(ResultFolderNameVariable)[0] == '': resultfolderpath = os.path.join(self.resultspath.get(),ResultFolderNameVariable) else: resultfolderpath = ResultFolderNameVariable filelist = [] extlist = [".tsv",".dat",".h5",".png","jpg"] try: for fname in os.listdir(resultfolderpath): for ext in extlist: if ext == os.path.splitext(fname)[1]: filelist.append(fname) self.NumResultsVariable.set(len(filelist)) except: self.NumResultsVariable.set(0) self.ResultsList = [] for i in range(self.NumResultsVariable.get()): filename = os.path.join(self.resultspath.get(),ResultFolderNameVariable,filelist[i]) if not os.path.isfile(os.path.join(resultfolderpath,os.path.splitext(filelist[i])[0] + '.tsvx')) and not os.path.isfile(os.path.join(resultfolderpath,os.path.splitext(filelist[i])[0] + '.ini')): #v0.15.4 and before support name = os.path.splitext(filelist[i].replace('_',' '))[0] + " (no-metadata, "+os.path.splitext(filelist[i].replace('_',' '))[1]+")" metadata = {} else: if os.path.isfile(os.path.join(resultfolderpath,os.path.splitext(filelist[i])[0] + '.tsvx')): metadata = sources.readTSVx(os.path.join(resultfolderpath,os.path.splitext(filelist[i])[0] + '.tsvx'))[0] else: metadata = sources.readTSVx(os.path.join(resultfolderpath,os.path.splitext(filelist[i])[0] + '.ini'))[0] if '_S' in filename: name = os.path.split(filename)[1].split('_S')[0] + ' - ' else: name = '' name += metadata['scenario'] + ' - ' + metadata['network'] + ' - ' + metadata['source'] + ' - ' + metadata['analysis'] + ' - ' + metadata['result'] if 'variable' in metadata: name += ' - ' + metadata['variable'] self.ResultsList.append([name,filename,metadata]) self.ResultsList.sort() self.Message.set("Results are read and listed.") if len(self.ResultsList) != 0: self.ResultNameVariable.set(self.ResultsList[0][0]) def LoadResults(self): ext = os.path.splitext(self.ResultsFileNameVariable.get())[1] for res in self.ResultsList: if res[1] == self.ResultsFileNameVariable.get(): self.ResultsFileMetadata = deepcopy(res[2]) self.ResultsName = deepcopy(res[0]) break if ext == ".tsv" or ext == ".dat": #v0.15.4 and before support f = open(self.ResultsFileNameVariable.get(),'r') line = f.readline() line = line.replace('\n','') if line[0] == '!': line = line[1:].split('\t') else: line = line.split('\t') while '\t' in line: line.remove('\t') while '\n' in line: line.remove('\n') while '\r' in line: line.remove('\r') while '\r\n' in line: line.remove('\r\n') while '' in line: line.remove('') self.ResultsCaptions = line[:] if self.ResultsFileMetadata != {}: for i in range(len(self.ResultsCaptions)): self.ResultsCaptions[i] = self.ResultsFileMetadata[self.ResultsCaptions[i]] self.ResultsData = [] if self.ResultVariableNameVariable.get() != "": data = [] for line in f: line = line.split() dataline = [] for i,v in enumerate(line): if self.ResultsCaptions[i] != "Time" and self.ResultsCaptions[i] != "Date": v = float(v) else: if self.ResultsCaptions[i] == "Time": v = datetime.datetime(int(v[:4]),int(v[5:7]),int(v[8:10]),int(v[11:13]),int(v[14:16]),int(v[17:19])) else: v = datetime.date(int(v[:4]),int(v[5:7]),int(v[8:10])) dataline.append(v) data.append(dataline) data = np.copy(zip(*data[:])) for i in range(len(self.ResultsCaptions)): self.ResultsData.append(self.ResultsCaptions[i]) if self.ResultVariableNameVariable.get() == self.ResultsCaptions[i] or i == 0 or self.ResultVariableNameVariable.get() == "Merged Plot": self.ResultsData.append(data[i]) else: self.ResultsData.append(np.array([])) else: for i in range(len(self.ResultsCaptions)): self.ResultsData.append(self.ResultsCaptions[i]) self.ResultsData.append(np.array([])) self.ResultsCaptions.append("Merged Plot") self.ResultsData.append("Merged Plot") self.ResultsData.append(np.array([0])) self.ResultsData = [self.ResultNameVariable.get(),self.ResultsData] f.close() self.PlotXStartFactor.set(0.0) self.PlotXEndFactor.set(0.0) self.PlotYStartFactor.set(-0.1) self.PlotYEndFactor.set(-0.1) if ".png" == ext or ".jpg" == ext: dset = mahotas.imread(os.path.normpath(self.ResultsFileNameVariable.get().encode('ascii','replace'))).transpose(2,0,1) if dset.shape[0] == 4: dset = dset.transpose(1,2,0)[:,:,:3].transpose(2,0,1) if self.ResultVariableNameVariable.get() == "": tkMessageBox.showwarning("Transparency ignored","Selected image has alpha channel. The channel is ignored for drawing.") if self.ResultVariableNameVariable.get() == "": self.ResultsData = [self.ResultNameVariable.get(),["R-Channel",np.array([]),"G-Channel",np.array([]),"B-Channel",np.array([]),"Composite Image",np.array([])]] else: self.ResultsData = [] for i,v in enumerate(["R-Channel","G-Channel","B-Channel"]): self.ResultsData.append(v) if self.ResultVariableNameVariable.get() == v: self.ResultsData.append(dset[i]) else: self.ResultsData.append(np.array([])) self.ResultsData.append("Composite Image") if self.ResultVariableNameVariable.get() == "Composite Image": self.ResultsData.append(dset.transpose(1,2,0)) else: self.ResultsData.append(np.array([])) self.ResultsData = [self.ResultNameVariable.get(),self.ResultsData] self.ResultsCaptions = ["R-Channel","G-Channel","B-Channel","Composite Image"] self.PlotXStartFactor.set(0.0) self.PlotXEndFactor.set(0.0) self.PlotYStartFactor.set(0) self.PlotYEndFactor.set(0) if ".h5" in ext: hdf_f = h5py.File(self.ResultsFileNameVariable.get(),'r') self.ResultsData = [] self.ResultsCaptions = [] for dset in hdf_f: self.ResultsCaptions.append(str(dset)) for dset in hdf_f: self.ResultsData.append(str(dset)) if self.ResultVariableNameVariable.get() != "" and (self.ResultVariableNameVariable.get() == str(dset) or str(dset) == "Latitude" or str(dset) == "Longitude"): self.ResultsData.append(np.copy(hdf_f[dset])) else: self.ResultsData.append(np.array([])) hdf_f.close() self.ResultsData = [self.ResultNameVariable.get(),self.ResultsData] self.PlotXStartFactor.set(0.0) self.PlotXEndFactor.set(0.0) self.PlotYStartFactor.set(0) self.PlotYEndFactor.set(0) if self.ResultVariableNameVariable.get() != "": self.Message.set("Loaded variable: " + self.ResultVariableNameVariable.get() + " from results: " + self.ResultNameVariable.get()) else: self.Message.set("Variables listed from results: " + self.ResultNameVariable.get()) def callbackResultsFolder(self,*args): self.ReadResults() self.Menu_Main_Results() def callbackResultsName(self, *args): for res in self.ResultsList: if res[0] == self.ResultNameVariable.get(): self.ResultsFileNameVariable.set(os.path.normpath(res[1])) self.ResultVariableNameVariable.set("") for caption in self.ResultsCaptions: if caption != 'Date' and caption != 'Time' and caption != 'Latitude' and caption != 'Longitude' and not (".dat" in self.ResultsFileNameVariable.get()[-5:] and self.ResultsCaptions.index(caption) == 0): self.ResultVariableNameVariable.set(caption) break self.LoadResultVariableNameVariable() def callbackResultsVar(self,*args): self.DrawResults() def callbackResultVariable(self, *args): self.LoadResults() if self.ResultVariableNameVariable.get() != "": for i in range(self.MenuItemMax+1): exec("self.PlotVar"+str(i)+"Switch = Tkinter.BooleanVar()") exec("self.PlotVar"+str(i)+"Switch.set(True)") exec("self.PlotVar"+str(i)+"Switch.trace('w',self.callbackResultsVar)") self.PlotVarLogXSwitch = Tkinter.BooleanVar() self.PlotVarLogXSwitch.set(False) self.PlotVarLogXSwitch.trace('w',self.callbackResultsVar) self.PlotVarLogYSwitch = Tkinter.BooleanVar() self.PlotVarLogYSwitch.set(False) self.PlotVarLogYSwitch.trace('w',self.callbackResultsVar) self.PlotVarInvertXSwitch = Tkinter.BooleanVar() self.PlotVarInvertXSwitch.set(False) self.PlotVarInvertXSwitch.trace('w',self.callbackResultsVar) self.PlotVarInvertYSwitch = Tkinter.BooleanVar() self.PlotVarInvertYSwitch.set(False) self.PlotVarInvertYSwitch.trace('w',self.callbackResultsVar) self.PlotVarColormap = Tkinter.StringVar() self.PlotVarColormap.set("Paired") self.PlotVarColormap.trace('w',self.callbackResultsVar) self.PlotVarMarker = Tkinter.StringVar() self.PlotVarMarker.set('.') self.PlotVarMarker.trace('w',self.callbackResultsVar) self.PlotVarStyle = Tkinter.StringVar() self.PlotVarStyle.set('-') self.PlotVarStyle.trace('w',self.callbackResultsVar) self.PlotVarColor = Tkinter.StringVar() self.PlotVarColor.set('black') self.PlotVarColor.trace('w',self.callbackResultsVar) self.DrawResults() def DrawResults(self,*args): try: self.PlotCanvas.delete("all") self.PlotCanvas.get_tk_widget().destroy() except: pass try: self.PlotFigure.clf() except: pass try: self.ax.clear() except: pass if self.PlotCanvasSwitch.get() and self.ResultVariableNameVariable.get() != "": self.geometry(str(self.WindowX+self.SensVariable.get()*33*self.UnitSize)+"x"+str(self.SensVariable.get()*25*self.UnitSize)) drawable = True data_index = self.ResultsCaptions.index(self.ResultVariableNameVariable.get())*2+1 try: if not (len(self.ResultsData[1][data_index].shape) <= 2 and len(self.ResultsData[1][data_index].shape) > 0): if len(self.ResultsData[1][data_index].shape) == 3: if self.ResultsData[1][data_index].shape[2] != 3: drawable = False else: drawable = False except: pass if drawable: self.PlotFigure = matplotlib.figure.Figure() offset = 0 if len(self.ResultsData[1][data_index].shape) == 1: offset = 1 if len(self.ResultsData[1][data_index].shape) == 2: offset = 0 if "Latitude" in self.ResultsCaptions and "Longitude" in self.ResultsCaptions: offset = 2 lat_index = self.ResultsCaptions.index("Latitude")*2+1 lon_index = self.ResultsCaptions.index("Longitude")*2+1 matplotlib.rcParams.update({'font.size': 1*self.FontSize}) pgrid = [1,1] pindex = 1 if offset == 1: self.XMax = self.ResultsData[1][1].max() self.XMin = self.ResultsData[1][1].min() self.XDist = self.XMax - self.XMin self.YMax = np.nanmax(np.array(self.ResultsData[1][data_index],np.float)) self.YMin = np.nanmin(np.array(self.ResultsData[1][data_index],np.float)) if self.ResultVariableNameVariable.get() == "Merged Plot": ymins = [] ymaxs = [] emptyplot = True for i in range(1,len(self.ResultsCaptions[:-1])): exec("switch = self.PlotVar"+str(i-1)+"Switch.get()") if switch: emptyplot = False ymins = np.append(ymins,np.nanmin(self.ResultsData[1][i*2 +1])) ymaxs = np.append(ymaxs,np.nanmax(self.ResultsData[1][i*2 +1])) if emptyplot: self.YMax = 1.0 self.YMin = 0.0 else: self.YMax = np.nanmax(ymaxs) self.YMin = np.nanmin(ymins) self.YDist = self.YMax - self.YMin if self.ResultsCaptions[0] == "Time" or self.ResultsCaptions[0] == "Date": self.XDist = self.XDist.days*86400 + self.XDist.seconds self.ax = self.PlotFigure.add_subplot(pgrid[0],pgrid[1],pindex) self.ax.set_xlabel(self.ResultsCaptions[0]) if 'result' in self.ResultsFileMetadata: self.ax.set_title("\n".join(textwrap.wrap(self.ResultsFileMetadata['result'], 80/pgrid[1]))) else: self.ax.set_title("\n".join(textwrap.wrap(self.ResultsName.split()[-1], 80/pgrid[1]))) if self.ResultVariableNameVariable.get() == "Merged Plot": emptyplot = True for i in range(1,len(self.ResultsCaptions[:-1])): exec("switch = self.PlotVar"+str(i-1)+"Switch.get()") if switch: self.ax.plot_date(self.ResultsData[1][1],self.ResultsData[1][i*2 +1],label=self.ResultsCaptions[i],marker=self.PlotVarMarker.get(), linestyle=self.PlotVarStyle.get(),fmt='') self.ax.axis((self.XMin+datetime.timedelta(seconds=self.XDist*self.PlotXStartFactor.get()),self.XMax-datetime.timedelta(seconds=self.XDist*self.PlotXEndFactor.get()),self.YMin+self.YDist*self.PlotYStartFactor.get(),self.YMax-self.YDist*self.PlotYEndFactor.get())) else: self.ax.plot_date(self.ResultsData[1][1],self.ResultsData[1][data_index],label=self.ResultVariableNameVariable.get(),marker=self.PlotVarMarker.get(), linestyle=self.PlotVarStyle.get(), color=self.PlotVarColor.get()) self.ax.axis((self.XMin+datetime.timedelta(seconds=self.XDist*self.PlotXStartFactor.get()),self.XMax-datetime.timedelta(seconds=self.XDist*self.PlotXEndFactor.get()),self.YMin+self.YDist*self.PlotYStartFactor.get(),self.YMax-self.YDist*self.PlotYEndFactor.get())) else: self.ax = self.PlotFigure.add_subplot(pgrid[0],pgrid[1],pindex) self.ax.set_xlabel(self.ResultsCaptions[0]) self.ax.set_title("\n".join(textwrap.wrap(self.ResultVariableNameVariable.get(), 80/pgrid[1]))) if self.ResultVariableNameVariable.get() == "Merged Plot": for i in range(1,len(self.ResultsCaptions[:-1])): exec("switch = self.PlotVar"+str(i-1)+"Switch.get()") if switch: self.ax.plot(self.ResultsData[1][1],self.ResultsData[1][i*2 +1],label=self.ResultsCaptions[i],marker=self.PlotVarMarker.get(), linestyle=self.PlotVarStyle.get()) self.ax.axis((self.XMin+self.XDist*self.PlotXStartFactor.get(),self.XMax-self.XDist*self.PlotXEndFactor.get(),ymins.min()+(ymaxs.max()-ymins.min())*self.PlotYStartFactor.get(),ymaxs.max()-(ymaxs.max()-ymins.min())*self.PlotYEndFactor.get())) else: self.ax.plot(self.ResultsData[1][1],self.ResultsData[1][data_index],label=self.ResultVariableNameVariable.get(),marker=self.PlotVarMarker.get(), linestyle=self.PlotVarStyle.get(), color=self.PlotVarColor.get()) self.ax.axis((self.XMin+self.XDist*self.PlotXStartFactor.get(),self.XMax-self.XDist*self.PlotXEndFactor.get(),self.YMin+self.YDist*self.PlotYStartFactor.get(),self.YMax-self.YDist*self.PlotYEndFactor.get())) if self.LegendVar.get(): lgd = self.ax.legend(framealpha=0.8, prop={'size':1*self.FontSize}) if self.PlotVarLogXSwitch.get(): self.ax.set_xscale('log') if self.PlotVarLogYSwitch.get(): self.ax.set_yscale('log') if self.PlotVarInvertXSwitch.get(): self.ax.invert_xaxis() if self.PlotVarInvertYSwitch.get(): self.ax.invert_yaxis() else: self.ax = self.PlotFigure.add_subplot(pgrid[0],pgrid[1],pindex) self.ax.set_title("\n".join(textwrap.wrap(self.ResultVariableNameVariable.get(), 80/pgrid[1]))) if offset == 0: x = np.indices(self.ResultsData[1][data_index].shape[:2])[1] y = np.indices(self.ResultsData[1][data_index].shape[:2])[0] self.ax.set_xlabel("X") self.ax.set_ylabel("Y") if offset == 2: x = np.copy(self.ResultsData[1][lon_index]) y = np.copy(self.ResultsData[1][lat_index]) self.ax.set_xlabel("Longitude") self.ax.set_ylabel("Latitude") self.XMax = x.max() self.XMin = x.min() self.YMax = y.max() self.YMin = y.min() self.XDist = self.XMax - self.XMin self.YDist = self.YMax - self.YMin extent = [self.XMin+self.XDist*self.PlotXStartFactor.get(),self.XMax-self.XDist*self.PlotXEndFactor.get(),self.YMin+self.YDist*self.PlotYStartFactor.get(),self.YMax-self.YDist*self.PlotYEndFactor.get()] mask = (x>=extent[0])*(x<=extent[1])*(y>=extent[2])*(y<=extent[3]) extent_i = [0,x.shape[1],0,x.shape[0]] x = None y = None if False in mask: for row in mask: if True not in row: extent_i[2] += 1 else: break for i in range(mask.shape[0]): row = mask[mask.shape[0]-i-1] if True not in row: extent_i[3] -= 1 else: break for col in mask.transpose(1,0): if True not in col: extent_i[0] += 1 else: break for i in range(mask.shape[1]): col = mask.transpose(1,0)[mask.shape[1]-i-1] if True not in col: extent_i[1] -= 1 else: break mask = None if len(self.ResultsData[1][data_index].shape) == 3: exec("cax = self.ax.imshow(self.ResultsData[1][data_index][extent_i[2]:extent_i[3],extent_i[0]:extent_i[1]].transpose(0,2,1)[::-1].transpose(0,2,1), extent=(extent[0]-0.5,extent[1]+0.5,extent[2]-0.5,extent[3]+0.5),interpolation='none', cmap=matplotlib.cm."+self.PlotVarColormap.get()+")") else: exec("cax = self.ax.imshow(self.ResultsData[1][data_index][extent_i[2]:extent_i[3],extent_i[0]:extent_i[1]].transpose(0,1)[::-1].transpose(0,1), extent=(extent[0]-0.5,extent[1]+0.5,extent[2]-0.5,extent[3]+0.5),interpolation='none', cmap=matplotlib.cm."+self.PlotVarColormap.get()+")") if self.LegendVar.get() and len(self.ResultsData[1][data_index].shape) != 3: self.PlotFigure.colorbar(cax) if self.PlotVarLogXSwitch.get(): self.ax.set_xscale('log') if self.PlotVarLogYSwitch.get(): self.ax.set_yscale('log') if self.PlotVarInvertXSwitch.get(): self.ax.invert_xaxis() if self.PlotVarInvertYSwitch.get(): self.ax.invert_yaxis() grid = None self.PlotCanvas = FigureCanvasTkAgg(self.PlotFigure, master=self) self.PlotCanvas.get_tk_widget().place(x=self.WindowX,y=0,height=self.SensVariable.get()*25*self.UnitSize,width=self.SensVariable.get()*33*self.UnitSize) self.PlotCanvas.draw() self.PlotCanvas.mpl_connect('button_press_event', self.callbackPlotCanvas) else: tkMessageBox.showwarning("Unable to plot","Selected data is not suitable for plotting. It has more than 2 axis. 3D plotting is not available (yet?).") self.PlotCanvasSwitch.set(False) self.Message.set("Drawn/renewed variable: " + self.ResultVariableNameVariable.get() + " from results: " + self.ResultNameVariable.get()) elif not self.PreviewCanvasSwitch.get(): self.geometry(str(self.WindowX)+"x"+str(self.WindowY)) def SavePlot(self,*args): if self.PlotCanvasSwitch.get(): self.Message.set("Saving plot...") self.file_opt = options = {} options['defaultextension'] = '.png' options['filetypes'] = [ ('PNG', '.png'),('all files', '.*')] options['title'] = 'Set filename to save the image...' ans = tkFileDialog.asksaveasfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) self.PlotFigure.savefig(ans) self.Message.set("Plot is saved as " + ans ) else: self.Message.set("Saving the plot is cancelled.") else: self.Message.set("No plot to save. Plot the results first.") def SaveData(self,*args): if self.PlotCanvasSwitch.get(): self.Message.set("Saving data...") self.file_opt = options = {} options['defaultextension'] = '.png' options['filetypes'] = [ ('PNG', '.png'),('all files', '.*')] options['title'] = 'Set filename to save the data...' ans = tkFileDialog.asksaveasfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) mahotas.imread.imsave(ans,np.array(self.ResultsData[1][self.ResultsCaptions.index(self.ResultVariableNameVariable.get())*2+1])) self.Message.set("Plot is saved as " + ans ) else: self.Message.set("Saving the plot is cancelled.") else: self.Message.set("No plot to save. Plot the results first.") def callbackPlotCanvas(self,event,*args): x = event.xdata y = event.ydata data_index = self.ResultsCaptions.index(self.ResultVariableNameVariable.get())*2+1 try: if len(self.ResultsData[1][data_index].shape) == 1: if self.ResultsData[1][0] == 'Time' or self.ResultsData[1][0] == 'Date': ix = np.argmin(np.abs(self.ResultsData[1][1] - mdate.num2date(x).replace(tzinfo=None))) vx = mdate.num2date(x).replace(tzinfo=None) else: ix = np.argmin(np.abs(self.ResultsData[1][1] - x)) vx = x if self.ResultsData[1][data_index-1] == 'Merged Plot': v = '' for i in range(1,(len(self.ResultsData[1])/2)-1): v += ' -' + self.ResultsData[1][2*i] + ' is ' + str(self.ResultsData[1][2*i+1][ix]) + ' at ' + str(self.ResultsData[1][1][ix]) + '.\n' tkMessageBox.showinfo('Values','Values of the nearest to ' + str(vx) + ':\n'+ str(v)) else: v = self.ResultsData[1][data_index][ix] tkMessageBox.showinfo('Value','Value of the nearest to ' + str(vx) + ' is '+ str(v) + ' at ' + str(self.ResultsData[1][1][ix]) + '.') if len(self.ResultsData[1][data_index].shape) == 2: v = self.ResultsData[1][data_index][np.rint(y)][np.rint(x)] tkMessageBox.showinfo('Value','Value of the nearest to (' + str(x) + ', ' + str(y) + ') is '+str(v) + ' at (' + str(np.rint(x)) + ', ' + str(np.rint(y)) + ').' ) if len(self.ResultsData[1][data_index].shape) == 3: v = self.ResultsData[1][data_index][np.rint(y)][np.rint(x)] tkMessageBox.showinfo('Value','Value of the nearest to (' + str(x) + ', ' + str(y) + ') is '+str(v) + ' at (' + str(np.rint(x)) + ', ' + str(np.rint(y)) + ').' ) except: pass def callbackPictureCanvas(self,event,*args): if self.MaskingPolygonPen.get() != 0: self.UpdateSetup() if self.MaskingPolygonPen.get() == 1: if isinstance(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][0],list): if self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1] == [0,0,0,0,0,0,0,0]: self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1] = [] self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1].append(event.x/float(self.PictureSize[0]))#(int(event.x/self.PictureRatio)) #maskdebug self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1].append(event.y/float(self.PictureSize[1]))#(int(event.y/self.PictureRatio)) else: if self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] == [0,0,0,0,0,0,0,0]: self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] = [] self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'].append(event.x/float(self.PictureSize[0]))#(int(event.x/self.PictureRatio)) self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'].append(event.y/float(self.PictureSize[1]))#(int(event.y/self.PictureRatio)) if self.MaskingPolygonPen.get() == 2: distsq = [] if isinstance(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][0],list): for i in range(len(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1])/2): distsq.append(((event.x/float(self.PictureSize[0])) - self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1][i*2])**2+((event.y/float(self.PictureSize[1])) - self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1][i*2+1])**2) if len(distsq) != 1 or self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1] == scenario_def['polygonicmask'][:]: del self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1][distsq.index(min(distsq))*2] del self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1][distsq.index(min(distsq))*2] else: self.PolygonRemoveAll() else: for i in range(len(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'])/2): distsq.append(((event.x/float(self.PictureSize[0])) - self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][i*2])**2+((event.y/float(self.PictureSize[1])) - self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][i*2+1])**2) if len(distsq) != 1 or self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] == scenario_def['polygonicmask'][:]: del self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][distsq.index(min(distsq))*2] del self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][distsq.index(min(distsq))*2] else: self.PolygonRemoveAll() distsq = [] self.UpdatePictures() self.LoadValues() def callbackAnalysisNo(self,event,*args): self.ExceptionSwitches_ComingFromCallbackAnalysis.set(True) self.CalculationNoVariable.set(1) self.PolygonNoVariable.set(1) self.LoadValues() self.UpdatePictures() self.Message.set("Scenario no changed to " + str(self.AnalysisNoVariable.get()) + '( Scenario name: ' + self.ScenarioNameVariable.get()+')') def callbackNetworkName(self,event,*args): if len(sources.getSources(self.Message,self.sourcelist,self.NetworkNameVariable.get(),'network')) == 0: tkMessageBox.showwarning('No camera in the network','There is no camera in the network. Check the network from the camera manager.') self.NetworkNameVariable.set(self.networklist[0]['name']) else: self.Message.set("Camera network is changed to " + self.NetworkNameVariable.get()) if not bool(self.ExceptionSwitches_ComingFromCallbackAnalysis.get()) and (self.CameraNameVariable.get() not in sources.listSources(self.Message,self.sourcelist,network=self.NetworkNameVariable.get()) or self.NetworkNameVariable.get() != self.NetworkNameVariablePre.get()): self.CameraNameVariable.set(sources.getSource(self.Message,self.sourcelist,self.NetworkNameVariable.get(),'network')['name']) self.ExceptionSwitches_ComingFromCallbackAnalysis.set(False) if self.ActiveMenu.get() == 'Camera': self.MenuItem1['menu'].delete(0,"end") for source in sources.listSources(self.Message,self.sourcelist,network=self.NetworkNameVariable.get()): self.MenuItem1['menu'].add_command(label=source,command=Tkinter._setit(self.CameraNameVariable,source)) def callbackCameraName(self,event,*args): try: self.setup[self.AnalysisNoVariable.get()-1]['source'] = {} self.setup[self.AnalysisNoVariable.get()-1]['source'].update(sources.getSource(self.Message,sources.getSources(self.Message,self.sourcelist,self.NetworkNameVariable.get(),'network'),self.CameraNameVariable.get())) except: pass if self.PictureFileName.get() == '' or self.CameraNameVariable.get() != self.CameraNameVariablePre.get() or self.NetworkNameVariable.get() != self.NetworkNameVariablePre.get() or self.PictureFileName.get() == os.path.join(TmpDir,'testmask.jpg'): if not bool(self.ExceptionSwitches_ComingFromStartupSetupFileSetupReset.get()): self.setup[self.AnalysisNoVariable.get()-1]['source'],self.setup[self.AnalysisNoVariable.get()-1] = self.UpdatePreviewPictureFiles(sources.getProxySource(self.Message,self.setup[self.AnalysisNoVariable.get()-1]['source'],self.proxylist),self.setup[self.AnalysisNoVariable.get()-1]) self.UpdatePictureFileName() self.UpdatePictures() self.CameraNameVariablePre.set(self.CameraNameVariable.get()) self.NetworkNameVariablePre.set(self.NetworkNameVariable.get()) self.Message.set("Camera is changed to " + self.CameraNameVariable.get()) def callbackCalculationNo(self,event,*args): self.CalculationNameVariable.set(calcnames[calcids.index(self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())]['id'])]) self.Message.set("Analysis no changed to " + str(self.CalculationNoVariable.get())) def callbackCalculationName(self,event,*args): if not self.CalculationNameVariable.get() == calcnames[calcids.index(self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())]['id'])]: paramdef = paramdefs[calcnames.index(self.CalculationNameVariable.get())] paramname = paramnames[calcnames.index(self.CalculationNameVariable.get())] id = calcids[calcnames.index(self.CalculationNameVariable.get())] name = calcnames[calcnames.index(self.CalculationNameVariable.get())] param = {} param.update({'id':id}) param.update({'name':name}) self.setup[self.AnalysisNoVariable.get()-1].update({'analysis-'+str(self.CalculationNoVariable.get()):param}) for n,nn in enumerate(paramname): param.update({paramname[n]:paramdef[n]}) self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())].update(param) self.CalculationDescriptionVariable.set(calcdescs[calcnames.index(self.CalculationNameVariable.get())]) self.Message.set("Analysis is changed to " + self.CalculationNameVariable.get()) def LoadValues(self): self.ScenarioNameVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['name']) self.RedFLTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][0]) self.RedFUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][1]) self.GreenFLTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][2]) self.GreenFUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][3]) self.BlueFLTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][4]) self.BlueFUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][5]) self.RedFILTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][18]) self.RedFIUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][19]) self.GreenFILTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][20]) self.GreenFIUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][21]) self.BlueFILTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][22]) self.BlueFIUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][23]) self.RedLTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][8]) self.RedUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][9]) self.GreenLTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][10]) self.GreenUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][11]) self.BlueLTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][12]) self.BlueUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][13]) self.GreyLTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][16]) self.GreyUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][17]) self.BrightnessLTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][6]) self.BrightnessUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][7]) self.LuminanceLTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][14]) self.LuminanceUTVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][15]) self.DateStartVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['temporal'][0]) self.DateEndVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['temporal'][1]) self.TimeStartVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['temporal'][2]) self.TimeEndVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['temporal'][3]) self.TemporalModeVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['temporal'][4]) self.PolygonMultiRoiVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['multiplerois']) self.PolygonCoordinatesVariable.set('') if self.PolygonNoVariable.get() == 0: self.PolygonNoVariable.set(1) self.PolygonCoordinatesVariable.set(self.polygonicmask2PolygonCoordinatesVariable(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'])) if self.ActiveMenu.get() == "Set parameters": calcindex = calcnames.index(self.CalculationNameVariable.get()) for i in range(len(paramnames[calcindex])): paramname = paramnames[calcindex][i] paramhelp = paramhelps[calcindex][i] paramopt = paramopts[calcindex][i] i = str(i) exec("self.p"+i+"Var.set(self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())][paramname])") try: self.NetworkNameVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['source']['network']) except: pass self.CameraNameVariable.set(self.setup[self.AnalysisNoVariable.get()-1]['source']['name']) self.CalculationNameVariable.set(calcnames[calcids.index(self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())]['id'])]) self.Message.set("Switched to scenario " + str(self.AnalysisNoVariable.get())) def PolygonCoordinatesVariable2polygonicmask(self,var): line = var jlist = [] for j in line.split(): klist = [] for k in j.split(','): klist.append(float(k)) jlist.append(klist) if len(jlist) == 1: if len(klist) == 1: jlist = float(k) else: jlist = klist line = jlist return line def polygonicmask2PolygonCoordinatesVariable(self,tab): var = '' if isinstance(tab,dict): t = [] for k in tab: t.append(tab[k]) tab = t if isinstance(tab,list): for tab1_i, tab1 in enumerate(tab): if isinstance(tab1,list): for tab2_i, tab2 in enumerate(tab1): sep = ',' var += str(round(tab2,4)) if tab2_i != len(tab1) - 1: var += sep sep = ' ' else: sep = ',' var += str(round(tab1,4)) if tab1_i != len(tab) - 1: var += sep else: var += str(int(tab)) return var def checkSetupName(self): for s,scenario in enumerate(self.setup): if s+1 != self.AnalysisNoVariable.get() and scenario['name'] == self.ScenarioNameVariable.get(): return False return True def UpdateSetup(self): tmp = deepcopy(self.setup) while not self.checkSetupName(): tkt = Tkinter.Toplevel(self,padx=10,pady=10) tkt.grab_set() tkt.wm_title('Scenario name error') Tkinter.Label(tkt ,text='Scenario name you have is already used by another scenario. Enter a different name:').grid(sticky='w'+'e',row=1,column=1,columnspan=1) Tkinter.Entry(tkt ,textvariable=self.ScenarioNameVariable).grid(sticky='w'+'e',row=2,column=1,columnspan=1) Tkinter.Button(tkt ,text='OK',command=tkt.destroy).grid(sticky='w'+'e',row=3,column=1,columnspan=1) self.centerWindow(tkt) tkt.wait_window() self.setup[self.AnalysisNoVariable.get()-1]['name'] = self.ScenarioNameVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['source']['network'] = self.NetworkNameVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['source']['name'] = self.CameraNameVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][0] = self.RedFLTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][1] = self.RedFUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][2] = self.GreenFLTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][3] = self.GreenFUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][4] = self.BlueFLTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][5] = self.BlueFUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][18] = self.RedFILTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][19] = self.RedFIUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][20] = self.GreenFILTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][21] = self.GreenFIUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][22] = self.BlueFILTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][23] = self.BlueFIUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][8] = self.RedLTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][9] = self.RedUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][10] = self.GreenLTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][11] = self.GreenUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][12] = self.BlueLTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][13] = self.BlueUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][16] = self.GreyLTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][17] = self.GreyUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][6] = self.BrightnessLTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][7] = self.BrightnessUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][14] = self.LuminanceLTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['thresholds'][15] = self.LuminanceUTVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['temporal'][0] = self.DateStartVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['temporal'][1] = self.DateEndVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['temporal'][2] = self.TimeStartVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['temporal'][3] = self.TimeEndVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['temporal'][4] = self.TemporalModeVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['multiplerois'] = self.PolygonMultiRoiVariable.get() self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] = self.PolygonCoordinatesVariable2polygonicmask(self.PolygonCoordinatesVariable.get()) self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())]['id'] = calcids[calcnames.index(self.CalculationNameVariable.get())] if self.ActiveMenu.get() == "Set parameters": params = {} for i in range(9999): i = str(i) if int(i) < len(paramnames[calcids.index(self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())]['id'])]): try: if isinstance(paramopts[calcids.index(self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())]['id'])][int(i)],list): try: exec("self.p"+str(i)+"Var.set(paramopts[calcids.index(self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())]['id'])]["+str(i)+"].index(self.p"+str(i)+"VarOpt.get()))") except: pass exec("params.update({paramnames[calcids.index(self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())]['id'])]["+i+"]:self.p"+i+"Var.get()})") except: pass else: break self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())].update(params) if tmp != self.setup: self.Message.set("Setup is updated.") def UpdatePictures(self): if self.PreviewCanvasSwitch.get(): if self.WindowY < self.SensVariable.get()*25*self.UnitSize: self.geometry(str(self.WindowX+self.SensVariable.get()*33*self.UnitSize)+"x"+str(self.SensVariable.get()*25*self.UnitSize)) else: self.geometry(str(self.WindowX+self.SensVariable.get()*33*self.UnitSize)+"x"+str(self.WindowY)) self.PictureCanvas = Tkinter.Canvas(self,height=self.SensVariable.get()*33*self.UnitSize,width=self.SensVariable.get()*25*self.UnitSize) self.PictureCanvas.bind("<Button-1>",self.callbackPictureCanvas) self.PictureCanvas.place(x=self.WindowX,y=0,height=self.SensVariable.get()*25*self.UnitSize,width=self.SensVariable.get()*33*self.UnitSize) self.PictureImage = Image.open(self.PictureFileName.get()) if self.PictureImage.size[0] > self.PictureImage.size[1]: self.PictureSize = (self.SensVariable.get()*33*self.UnitSize,int(self.SensVariable.get()*33*self.UnitSize*(self.PictureImage.size[1]/float(self.PictureImage.size[0])))) self.PictureRatio = (self.SensVariable.get()*33*self.UnitSize)/float(self.PictureImage.size[0]) else: self.PictureSize = (int(self.SensVariable.get()*25*self.UnitSize*(self.PictureImage.size[0]/float(self.PictureImage.size[1]))),self.SensVariable.get()*25*self.UnitSize) self.PictureRatio = (self.SensVariable.get()*25*self.UnitSize)/float(self.PictureImage.size[1]) self.PictureImage = self.PictureImage.resize(self.PictureSize,Image.ANTIALIAS) self.PicturePhoto = ImageTk.PhotoImage(self.PictureImage) self.PictureCanvas.delete("all") self.PictureCanvas.create_image(0,0,image=self.PicturePhoto,anchor="nw") if self.ActiveMenu.get() == "Polygonic Masking" or "Choose Picture " == self.ActiveMenu.get(): coords = self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] if isinstance(coords,dict): coordss = [] for k in range(len(coords)): coordss.append(coords[str(k)]) coords = coordss if not isinstance(coords[0],list): coords_ = [coords[:]] else: coords_ = coords[:] for coords in coords_: tmp = coords[:] for i,t in enumerate(tmp): if i % 2 == 0: tmp[i] = round(t*self.PictureImage.size[0]) #maskdebug else: tmp[i] = round(t*self.PictureImage.size[1]) if tmp != [0,0,0,0,0,0,0,0]: self.PictureCanvas.create_polygon(*(tmp),outline=[self.PolygonColor0.get(),self.PolygonColor1.get()][int(float(self.PolygonNoVariable.get()-1!=coords_.index(coords)))],fill="",width=self.PolygonWidth.get()) else: try: self.PictureCanvas.destroy() if not self.PlotCanvasSwitch.get(): self.geometry(str(self.WindowX)+"x"+str(self.WindowY)) except: pass def FetchCurrentImages(self): self.DownloadArchive(camselect=False) if "Choose Picture for Preview" == self.ActiveMenu.get(): self.Menu_Main_Camera_Picture() if "Choose Picture " == self.ActiveMenu.get(): self.Menu_Main_Masking_Polygonic_Picture() self.Message.set("Images fetched.") def ChangePictureFileName(self,*args): fn = self.MenuItem1.get(self.MenuItem1.curselection()) source_ = self.setup[self.AnalysisNoVariable.get()-1]['source'] source = sources.getProxySource(self.Message,source_,self.proxylist) scenario = self.setup[self.AnalysisNoVariable.get()-1] pfn_ts = '-' + parsers.dTime2fTime(parsers.strptime2(fn,source['filenameformat'])[0]) if 'temporary' in source and source['temporary']: pfn = validateName(source['network'])+'-'+source['protocol']+'-'+source['host']+'-'+validateName(source['username'])+'-'+validateName(source['path'])+'-'+validateName(source['name']) + pfn_ts + os.path.splitext(source['filenameformat'])[1] pfn_prev = [validateName(source['network'])+'-'+source['protocol']+'-'+source['host']+'-'+validateName(source['username'])+'-'+validateName(source['path'])+'-'+validateName(source['name']), os.path.splitext(source['filenameformat'])[1]] else: pfn = source['networkid']+'-'+validateName(source['network'])+'-'+validateName(source['name']) + pfn_ts + os.path.splitext(source['filenameformat'])[1] pfn_prev = [source['networkid']+'-'+validateName(source['network'])+'-'+validateName(source['name']),os.path.splitext(source['filenameformat'])[1]] if source['protocol'] == 'LOCAL': self.PictureFileName.set(os.path.join(source['path'],fn)) else: if 'temporary' in source and source['temporary']: self.PictureFileName.set(os.path.join(os.path.join(TmpDir,'tmp_images'),validateName(source['network'])+'-'+source['protocol']+'-'+source['host']+'-'+validateName(source['username'])+'-'+validateName(source['path'])+'-'+validateName(source['name']),fn)) else: self.PictureFileName.set(os.path.join(self.imagespath.get(),source['networkid']+'-'+parsers.validateName(source['network']),parsers.validateName(source['name']),fn)) self.setup[self.AnalysisNoVariable.get()-1].update({'previewimagetime':parsers.strftime2(parsers.strptime2(fn,source['filenameformat'])[0])[0]}) self.Message.set("Preview image is changed.") try: shutil.copyfile(self.PictureFileName.get(),os.path.join(PreviewsDir,pfn)) self.Message.set('Preview image file is updated camera: '+source['network'] + ' - ' + source['name']) except: self.Message.set('Preview image file could not be updated for camera: '+source['network'] + ' - ' + source['name'] + '.') self.UpdatePictures() def UpdatePreviewPictureFilesAll(self): if tkMessageBox.askyesno('Preview images','Preview images will be checked and downloaded. This process can take a long time depending on the number of cameras and networks. If needed, passwords and usernames will also be asked.\nDo you want to proceed?'): for source in self.sourcelist: self.UpdatePreviewPictureFiles(source,[],noconfirm=True) def UpdatePreviewPictureFiles(self,source,scenario,noconfirm=False): self.Message.set('Checking preview image for '+source['name']+'...') pfn_ts = '' if 'previewimagetime' in scenario and scenario['previewimagetime'] != '' and scenario['previewimagetime'] is not None: pfn_ts = '-' + parsers.sTime2fTime(scenario['previewimagetime']) else: if 'previewimagetime' in source and source['previewimagetime'] != '' and source['previewimagetime'] is not None: pfn_ts = '-' + parsers.sTime2fTime(source['previewimagetime']) if 'temporary' in source and source['temporary']: pfn = validateName(source['network'])+'-'+source['protocol']+'-'+source['host']+'-'+validateName(source['username'])+'-'+validateName(source['path'])+'-'+validateName(source['name']) + pfn_ts + os.path.splitext(source['filenameformat'])[1] else: pfn = source['networkid']+'-'+validateName(source['network'])+'-'+validateName(source['name']) + pfn_ts + os.path.splitext(source['filenameformat'])[1] if pfn in os.listdir(PreviewsDir): return (source,scenario) else: if noconfirm or not sysargv['prompt'] or tkMessageBox.askyesno('Missing preview image','Preview image is missing for '+source['network']+' '+source['name']+'. Do you want to fetch one?'): self.Message.set('Updating preview image for camera: '+source['network'] + ' - ' + source['name']) img = [] if 'previewimagetime' in scenario and scenario['previewimagetime'] != '' and scenario['previewimagetime'] is not None: self.Message.set('Looking for the image for the ' + source_metadata_names['previewimagetime'] + ' provided by the setup file....' ) timec = [0,0,0,0] timec[0] = parsers.strftime2(parsers.strptime2(scenario['previewimagetime'],'%Y-%m-%dT%H:%M:%S')[0],conv="%d.%m.%Y %H:%M")[1] timec[1] = parsers.strftime2(parsers.strptime2(scenario['previewimagetime'],'%Y-%m-%dT%H:%M:%S')[0],conv="%d.%m.%Y %H:%M")[1] timec[2] = parsers.strftime2(parsers.strptime2(scenario['previewimagetime'],'%Y-%m-%dT%H:%M:%S')[0],conv="%d.%m.%Y %H:%M")[2] timec[3] = parsers.strftime2(parsers.strptime2(scenario['previewimagetime'],'%Y-%m-%dT%H:%M:%S')[0],conv="%d.%m.%Y %H:%M")[2] img, ts = fetchers.fetchImages(self, self.Message, source, self.proxy, self.connection, self.imagespath.get(), timec + ['Date and time intervals'], count=1, online=True, care_tz = self.TimeZoneConversion.get())[:2] if len(img) == 0: del scenario['previewimagetime'] self.Message.set('Can not find the image for the ' + source_metadata_names['previewimagetime'] + ' provided by the setup file. It is removed from the setup.' ) else: if 'previewimagetime' in source and source['previewimagetime'] != '' and source['previewimagetime'] is not None: self.Message.set('Looking for the image for the ' + source_metadata_names['previewimagetime'] + ' provided by CNIF....' ) timec = [0,0,0,0] timec[0] = parsers.strftime2(parsers.strptime2(source['previewimagetime'],'%Y-%m-%dT%H:%M:%S')[0],conv="%d.%m.%Y %H:%M")[1] timec[1] = parsers.strftime2(parsers.strptime2(source['previewimagetime'],'%Y-%m-%dT%H:%M:%S')[0],conv="%d.%m.%Y %H:%M")[1] timec[2] = parsers.strftime2(parsers.strptime2(source['previewimagetime'],'%Y-%m-%dT%H:%M:%S')[0],conv="%d.%m.%Y %H:%M")[2] timec[3] = parsers.strftime2(parsers.strptime2(source['previewimagetime'],'%Y-%m-%dT%H:%M:%S')[0],conv="%d.%m.%Y %H:%M")[2] img, ts = fetchers.fetchImages(self, self.Message, source, self.proxy, self.connection, self.imagespath.get(), timec + ['Date and time intervals'], count=1, online=True, care_tz = self.TimeZoneConversion.get())[:2] if len(img) == 0: self.Message.set('Can not find the image for the ' + source_metadata_names['previewimagetime'] + ' provided by CNIF.' ) else: self.Message.set(source_metadata_names['previewimagetime'] + ' is not supplied in CNIF file or the scenario.') if len(img) == 0: self.Message.set('Looking for a suitable image...') img, ts = fetchers.fetchImages(self, self.Message, source, self.proxy, self.connection, self.imagespath.get(), [0,0,'11:30','12:30','Date and time intervals'], count=1, online=True, care_tz = self.TimeZoneConversion.get())[:2] if len(img) == 0: img, ts = fetchers.fetchImages(self, self.Message, source, self.proxy, self.connection, self.imagespath.get(), [0,0,'00:00','23:59','All'], count=1, online=True, care_tz = self.TimeZoneConversion.get())[:2] if len(img) == 0: self.Message.set('No suitable file for preview image found for camera: '+source['network'] + ' - ' + source['name']) return (source,scenario) else: if ('previewimagetime' in scenario and scenario['previewimagetime'] != '' and scenario['previewimagetime'] is not None) or ('previewimagetime' in source and source['previewimagetime'] != '' and source['previewimagetime'] is not None): if len(pfn_ts) == 0: pfn = os.path.splitext(pfn)[0] + '-' + parsers.dTime2fTime(ts[0]) + os.path.splitext(pfn)[1] else: pfn = os.path.splitext(pfn)[0][:-len(pfn_ts)] + '-' + parsers.dTime2fTime(ts[0]) + os.path.splitext(pfn)[1] else: if len(pfn_ts) == 0: pfn = os.path.splitext(pfn)[0] + os.path.splitext(pfn)[1] else: pfn = os.path.splitext(pfn)[0][:-len(pfn_ts)] + os.path.splitext(pfn)[1] try: shutil.copyfile(img[0],os.path.join(PreviewsDir,pfn)) self.Message.set('Preview image downloaded/updated for camera: '+source['network'] + ' - ' + source['name']) self.PictureFileName.set(os.path.join(PreviewsDir,pfn)) except: self.Message.set('Preview image could not be downloaded/updated for camera: '+source['network'] + ' - ' + source['name']) return (source,scenario) self.Message.set('Checking complete.') def UpdatePictureFileName(self): source_ = self.setup[self.AnalysisNoVariable.get()-1]['source'] source = sources.getProxySource(self.Message,source_,self.proxylist) scenario = self.setup[self.AnalysisNoVariable.get()-1] pfn_ts = '' if 'previewimagetime' in scenario and scenario['previewimagetime'] != '' and scenario['previewimagetime'] is not None: pfn_ts = '-' + parsers.sTime2fTime(scenario['previewimagetime']) else: if 'previewimagetime' in source and source['previewimagetime'] != '' and source['previewimagetime'] is not None: pfn_ts = '-' + parsers.sTime2fTime(source['previewimagetime']) if 'temporary' in source and source['temporary']: pfn = validateName(source['network'])+'-'+source['protocol']+'-'+source['host']+'-'+validateName(source['username'])+'-'+validateName(source['path'])+'-'+validateName(source['name']) + pfn_ts + os.path.splitext(source['filenameformat'])[1] else: pfn = source['networkid']+'-'+validateName(source['network'])+'-'+validateName(source['name']) + pfn_ts + os.path.splitext(source['filenameformat'])[1] if pfn in os.listdir(PreviewsDir): self.PictureFileName.set(os.path.join(PreviewsDir,pfn)) else: self.PictureFileName.set(os.path.join(ResourcesDir,'preview_blank.jpg')) def setupFileLoad(self): if sysargv['setupfile'] is not None: ans = sysargv['setupfile'] else: self.file_opt = options = {} options['defaultextension'] = '.cfg' options['filetypes'] = [ ('FMIPROT setup files', '.cfg'),('FMIPROT configuration files', '.cfg'),('all files', '.*')] options['title'] = 'Choose setup file to load...' ans = tkFileDialog.askopenfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) setup = self.setupFileRead(ans) if sysargv['gui']: self.Menu_Main() self.setup = setup (self.networklist,self.sourcelist, self.setup) = sources.fixSourcesBySetup(self.Message,self.networklist,self.sourcelist, self.setup) self.setupFileVariable.set(ans) self.Message.set("Setup file is loaded.") if not sysargv['gui']: return False self.AnalysisNoVariable.set(1) self.Menu_Main() else: self.Message.set("Loading cancelled.") def setupFileRead(self,fname): setup = parsers.readSetup(fname,self.sourcelist,self.Message) #check analyses are valid: warning = "Analyses " showwarning = False for s,scenario in enumerate(setup): if not isinstance(scenario['analyses'],list): scenario.update({'analyses':[scenario['analyses']]}) discard = [] for analysis in scenario['analyses']: if analysis == '': discard.append(analysis) else: if scenario[analysis]['id'] not in calcids: discard.append(analysis) showwarning = True self.Message.set("Analysis "+ scenario[analysis]['name']+" in selected setup file is not supported anymore or plugin file is not detected if it is a plugin. The analysis is discarded.") warning += analysis + ' in selected setup file are not supported anymore or plugin file(s) are not detected if it is a plugin. The analyses are discarded. ' else: for p,param in enumerate(paramnames[calcids.index(scenario[analysis]['id'])]): if param not in scenario[analysis]: scenario[analysis].update({param:paramdefs[calcids.index(scenario[analysis]['id'])][p]}) self.Message.set("Analysis "+ scenario[analysis]['name']+" in selected setup file does not include the parameter "+ param+ ". It is set to default ("+str(paramdefs[calcids.index(scenario[analysis]['id'])][p])+").") analyses = [] for analysis in scenario['analyses']: if analysis not in discard: analyses.append(analysis) scenario.update({'analyses':analyses}) for analysis in discard: if analysis != '': del scenario[analysis] if len(discard)>0: if len(analyses) > 0: for i,d in enumerate(discard): d = int(discard[i].replace('analysis-','')) scenario.update({'analysis-'+str(d-i):scenario['analysis-'+str(d+1)]}) else: scenario.update({'analysis-1':deepcopy(scenario_def['analysis-1'])}) scenario.update({'analyses':['analysis-1']}) warning += 'It was the only analysis in the scenario, thus the default analysis is added to the scenario.' warning += '\n' setup[s] = scenario if showwarning: tkMessageBox.showwarning('Setup problem',warning) #fix polygons for i,scenario in enumerate(setup): if isinstance(scenario['polygonicmask'],dict): coordict = scenario['polygonicmask'] coordlist = [] for j in range(len(coordict)): coordlist.append(coordict[str(j)]) setup[i].update({'polygonicmask':coordlist}) #fix missing multiplerois for i,scenario in enumerate(setup): if 'multiplerois' not in scenario: setup[i].update({'multiplerois':0}) #fix temporal selection for i,scenario in enumerate(setup): if len(scenario['temporal']) < 5: setup[i]['temporal'].append(temporal_modes[1]) #fix timestamps from v0.15.4 and older for i,scenario in enumerate(setup): for key in ['previewimagetime','lastimagetime','firstimagetime']: if key in scenario and scenario[key] is not None: if scenario[key] == '': scenario[key] = None else: if 'T' not in scenario[key]: setup[i][key] = parsers.strftime2(parsers.strptime2(scenario[key],'%Y%m%d_%H%M%S')[0])[0] if key in scenario['source'] and scenario['source'][key] is not None: if scenario['source'][key] == '': scenario['source'][key] = None else: if 'T' not in scenario['source'][key]: setup[i]['source'][key] = parsers.strftime2(parsers.strptime2(scenario['source'][key],'%Y%m%d_%H%M%S')[0])[0] if 'timezone' in scenario['source'] and scenario['source']['timezone'] is not None: if ':' not in scenario['source']['timezone']: setup[i]['source']['timezone'] = scenario['source']['timezone'][:-2] + ':' + scenario['source']['timezone'][-2:] #fix Thresholds for i,scenario in enumerate(setup): if len(scenario['thresholds']) == 18: setup[i]['thresholds'] = scenario['thresholds'] + [0.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0] if len(scenario['thresholds']) == 8: setup[i]['thresholds'] = scenario['thresholds'] + [0.0,255.0,0.0,255.0,0.0,255.0,0.0,1.0,0.0,255.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0] return setup def setupFileSave(self): self.UpdateSetup() if self.setupFileVariable.get() == "Untitled.cfg": self.setupFileSaveas() else: parsers.writeTSVx(self.setupFileVariable.get(),self.setupToWrite(self.setup)) self.Message.set("Setup file saved as " + os.path.split(self.setupFileVariable.get())[1]) def setupFileSaveas(self): self.UpdateSetup() self.file_opt = options = {} options['defaultextension'] = '.cfg' options['filetypes'] = [ ('FMIPROT setup files', '.cfg'),('FMIPROT configuration files', '.cfg'),('all files', '.*')] options['title'] = 'Set setup file to save...' ans = tkFileDialog.asksaveasfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) self.setupFileVariable.set(ans) parsers.writeTSVx(self.setupFileVariable.get(),self.setupToWrite(self.setup)) self.Message.set("Setup file saved as " + os.path.split(self.setupFileVariable.get())[1]) else: self.Message.set("Saving cancelled.") def setupFileSaveasModified(self): self.UpdateSetup() self.file_opt = options = {} options['defaultextension'] = '.cfg' options['filetypes'] = [ ('FMIPROT setup files', '.cfg'),('FMIPROT configuration files', '.cfg'),('all files', '.*')] options['title'] = 'Set setup file to save...' ans = tkFileDialog.asksaveasfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) setup = deepcopy(self.setup) setup = self.modifySourcesInSetup(setup) parsers.writeTSVx(ans,self.setupToWrite(setup)) self.Message.set("Modified copy of setup file saved as " + os.path.split(ans)[1]) else: self.Message.set("Saving cancelled.") def setupToWrite(self,setup): setup_ = deepcopy(setup) setuptowrite = [] for i,scenario in enumerate(setup_): if 'temporary' not in scenario: setuptowrite.append(scenario) else: if scenario['temporary'] is False: del scenario['temporary'] setuptowrite.append(scenario) for i,scenario in enumerate(setuptowrite): if isinstance(scenario['polygonicmask'][0],list): coordlist = scenario['polygonicmask'] coordict = {} for j, coord in enumerate(coordlist): coordict.update({str(j):coord}) setuptowrite[i].update({'polygonicmask':coordict}) return setuptowrite def setupFileClear(self): self.setupFileVariable.set("Untitled.cfg") self.setup = [] if not sysargv['gui']: return False self.AnalysisNoNew() self.Menu_Main() self.Message.set("Setup is resetted.") def setupFileReport(self): self.UpdateSetup() self.file_opt = options = {} options['defaultextension'] = '.html' options['filetypes'] = [ ('HTML', '.html'),('all files', '.*')] options['title'] = 'Set file to save the report...' ans = tkFileDialog.asksaveasfilename(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) self.setupFileReportFunc(ans) else: self.Message.set('Report generation cancelled.') def setupFileReportFunc(self,ans,s=False): res_data = False if isinstance(ans,list): res_data = ans[1:] ans = ans[0] if ans != '' and ans != '.': setup = deepcopy(self.setup) maskdir = os.path.splitext(ans)[0]+"_files" if s is not False: setup = [deepcopy(self.setup[s])] for i,scenario in enumerate(setup): source_ = scenario['source'] source = sources.getProxySource(self.Message,source_,self.proxylist) (source,scenario) = self.UpdatePreviewPictureFiles(source,scenario) pfn_ts = '' if 'previewimagetime' in scenario and scenario['previewimagetime'] != '' and scenario['previewimagetime'] is not None: pfn_ts = '-' + parsers.sTime2fTime(scenario['previewimagetime']) else: if 'previewimagetime' in source and source['previewimagetime'] != '' and source['previewimagetime'] is not None: pfn_ts = '-' + parsers.sTime2fTime(source['previewimagetime']) if 'temporary' in source and source['temporary']: pfn = validateName(source['network'])+'-'+source['protocol']+'-'+source['host']+'-'+validateName(source['username'])+'-'+validateName(source['path']) +'-'+validateName(source['name']) + pfn_ts + os.path.splitext(source['filenameformat'])[1] else: pfn = source['networkid']+'-'+validateName(source['network'])+'-'+validateName(source['name']) + pfn_ts + os.path.splitext(source['filenameformat'])[1] if not os.path.exists(maskdir): os.makedirs(maskdir) maskfiles = [] maskfilet = [] maskfilet.append(os.path.join(maskdir,"Scenario_"+str(i+1)+"_Mask_Preview_0.jpg")) maskfilet.append(os.path.join(maskdir,"Scenario_"+str(i+1)+"_Mask_Preview_1.jpg")) maskfilet.append(os.path.join(maskdir,"Scenario_"+str(i+1)+"_Mask_Preview_2.jpg")) maskfilet.append(os.path.join(maskdir,"Scenario_"+str(i+1)+"_Mask_Preview_3.jpg")) maskfiles.append(os.path.join(TmpDir,"Scenario_"+str(i+1)+"_Mask_Preview_0.jpg")) maskfiles.append(os.path.join(TmpDir,"Scenario_"+str(i+1)+"_Mask_Preview_1.jpg")) maskfiles.append(os.path.join(TmpDir,"Scenario_"+str(i+1)+"_Mask_Preview_2.jpg")) maskfiles.append(os.path.join(TmpDir,"Scenario_"+str(i+1)+"_Mask_Preview_3.jpg")) aoic = deepcopy(scenario['polygonicmask']) if isinstance(aoic, dict): aoi = [] for k in aoic: aoi.append(aoic[k]) aoic = aoi if not isinstance(aoic[0], list): aoic = [aoic] if aoic != [[0,0,0,0,0,0,0,0]]: for p_i,p in enumerate(aoic): maskfilet.append(os.path.join(maskdir,"Scenario_"+str(i+1)+"_Mask_Preview_ROI"+str(p_i+1).zfill(3)+".jpg")) maskfiles.append(os.path.join(TmpDir,"Scenario_"+str(i+1)+"_Mask_Preview_ROI"+str(p_i+1).zfill(3)+".jpg")) for j in range(len(maskfiles)): if os.path.isfile(maskfilet[j]): os.remove(maskfilet[j]) if pfn not in os.listdir(PreviewsDir): self.Message.set("Preview image not found.") continue img = mahotas.imread(os.path.join(PreviewsDir,pfn)) rat = 160.0/img.shape[1] tshape = (int(img.shape[1]*rat),int(img.shape[0]*rat)) maskt = Image.new("RGB", tshape[0:2], "white") mask0b = Image.new("RGB", (img.shape[1], img.shape[0]), "white") mask0 = Image.new("RGB", (img.shape[1], img.shape[0]), "white") drawt = ImageDraw.Draw(maskt) draw0b = ImageDraw.Draw(mask0b) draw0 = ImageDraw.Draw(mask0) if img.shape[0]>480: linewidth=int(self.PolygonWidth.get()*img.shape[0]/float(480)) else: linewidth=self.PolygonWidth.get() if aoic != [[0,0,0,0,0,0,0,0]]: for p_i,p in enumerate(aoic): exec("mask"+str(p_i+1)+" = Image.new('RGB', (img.shape[1], img.shape[0]), 'white')") exec("draw"+str(p_i+1)+" = ImageDraw.Draw(mask"+str(p_i+1)+")") exec("maskb"+str(p_i+1)+" = Image.new('RGB', (img.shape[1], img.shape[0]), 'white')") exec("drawb"+str(p_i+1)+" = ImageDraw.Draw(maskb"+str(p_i+1)+")") textx = [] texty = [] for i_c,c in enumerate(p): if i_c%2==0: textx.append(p[i_c]*tshape[0]) p[i_c]*=img.shape[1] else: texty.append(p[i_c]*tshape[1]) p[i_c]*=img.shape[0] p.append(p[0]) p.append(p[1]) draw0b.line(tuple(map(int,p)), fill='black', width=linewidth) draw0.line(tuple(map(int,p)), fill=self.PolygonColor1.get(), width=linewidth) eval("drawb"+str(p_i+1)).line(tuple(map(int,p)), fill='black', width=linewidth) eval("draw"+str(p_i+1)).line(tuple(map(int,p)), fill=self.PolygonColor1.get(), width=linewidth) exec("maskb"+str(p_i+1)+" = np.array(list(maskb"+str(p_i+1)+".getdata())).reshape(img.shape)") #black polygon exec("mask"+str(p_i+1)+" = np.array(list(mask"+str(p_i+1)+".getdata())).reshape(img.shape)") #polycolor polygon mahotas.imsave(maskfiles[4+p_i],(eval("mask"+str(p_i+1))*(eval("maskb"+str(p_i+1))<100)+img*(eval("maskb"+str(p_i+1))>=100)).astype('uint8')) drawt.text(((np.array(textx).mean()).astype(int),(np.array(texty).mean()).astype(int)),str(p_i+1),'black',font=ImageFont.load_default()) maskt = maskt.resize(img.shape[0:2][::-1]) maskt = np.array(list(maskt.getdata())).reshape(img.shape) #black text mask0b = np.array(list(mask0b.getdata())).reshape(img.shape) #black polygons mask0 = np.array(list(mask0.getdata())).reshape(img.shape) #polycolor polygons mahotas.imsave(maskfiles[0],(mask0*(mask0b<100)+img*(mask0b>=100)).astype('uint8')) mahotas.imsave(maskfiles[1],(255-((255)*((mask0b<100)+(maskt<100)))).astype('uint8')) mahotas.imsave(maskfiles[2],img.astype('uint8')) mahotas.imsave(maskfiles[3],mask0b.astype('uint8')) for j in range(len(maskfiles)): if os.path.isfile(maskfiles[j]): shutil.copyfile(maskfiles[j],maskfilet[j]) if os.path.isfile(maskfiles[j]): os.remove(maskfiles[j]) shutil.copyfile(os.path.join(ResourcesDir,'style.css'),os.path.join(maskdir,'style.css')) shutil.copyfile(os.path.join(ResourcesDir,'dygraph.js'),os.path.join(maskdir,'dygraph.js')) shutil.copyfile(os.path.join(ResourcesDir,'dygraph.css'),os.path.join(maskdir,'dygraph.css')) shutil.copyfile(os.path.join(ResourcesDir,'interaction-api.js'),os.path.join(maskdir,'interaction-api.js')) if res_data: parsers.writeSetupReport([ans]+res_data,setup,self.Message) else: parsers.writeSetupReport(ans,setup,self.Message) if res_data is False: if tkMessageBox.askyesno("Report complete","Setup report completed. Do you want to open it in default browser?"): webbrowser.open(ans,new=2) else: if sysargv['gui'] and tkMessageBox.askyesno("Run complete","Analyses are completed and setup report with results are created. Do you want to open it in default browser?"): webbrowser.open(ans,new=2) else: self.Message.set("Report generation cancelled.") def LogWindowOn(self): self.LogWindow = Tkinter.Toplevel(self,padx=10,pady=10) self.LogWindow.wm_title('Log') self.LogScrollbar = Tkinter.Scrollbar(self.LogWindow,width=self.ScrollbarX) self.LogScrollbar.grid(sticky='w'+'e'+'n'+'s',row=2,column=2,columnspan=1) self.LogText = Tkinter.Text(self.LogWindow, yscrollcommand=self.LogScrollbar.set,wrap='word') self.LogText.grid(sticky='w'+'e',row=2,column=1,columnspan=1) self.LogScrollbar.config(command=self.LogText.yview) self.centerWindow(self.LogWindow,ontheside=True) def LogWindowOff(self): if self.LogWindow.winfo_exists(): self.LogWindow.destroy() self.grab_set() self.lift() def ReplaceOptMenuParams(self,scenario_in): scenario = deepcopy(scenario_in) for analysis in scenario['analyses']: c_i = calcids.index(scenario[analysis]['id']) for parameter in scenario[analysis]: if parameter == 'name' or parameter == 'id': continue p_i = paramnames[c_i].index(parameter) if isinstance(paramopts[c_i][p_i],list): scenario[analysis][parameter] = paramopts[c_i][p_i][int(scenario[analysis][parameter])] return scenario def RunAnalyses(self): self.Run() def RunAnalysis(self): self.Run(self.AnalysisNoVariable.get()-1) def Run(self,scn=None): logger = self.Message if sysargv['gui']: self.UpdateSetup() if scn == None: runq = ("Run all scenarios","FMIPROT will now run all the scenarios. Depending on the options selected, it may take a long time. It is adviced to check your input before runs. 'Generate Report' option is quite handy to check everything about your input.\nFMIPROT will save your setup under the your results directory ("+self.resultspath.get()+") for any case. If your runs fail, you may load the setup from that directory.\nDo you want to proceed?") else: runq = ("Run scenario","FMIPROT will now run the scenario. Depending on the options selected, it may take a long time. It is adviced to check your input before runs. 'Generate Report' option is quite handy to check everything about your input.\nFMIPROT will save your setup under the your results directory ("+self.resultspath.get()+") for any case. If your runs fail, you may load the setup from that directory.\nDo you want to proceed?") if not sysargv['prompt'] or tkMessageBox.askyesno(runq[0],runq[1]): settings = {'memory_limit':self.memorylimit.get()} if self.outputmodevariable.get() == output_modes[1]: if not self.checkemptyoutput(out=True): self.Menu_Main_Output() return False if self.outputmodevariable.get() == output_modes[2]: outputsetup = self.checkoutputsetup(out=True) if outputsetup is False: if self.checkemptyoutput(out=True): self.outputmodevariable.set(output_modes[1]) tkMessageBox.showwarning('Results can not be merged','No results in the directory, new results will be stored under it.') else: if not sysargv['prompt'] or tkMessageBox.askyesno('Results can not be merged','Results can not be merged. Do you want to continue the analysis and store results in a new directory under results directory?'): if not sysargv['prompt']: tkMessageBox.showwarning('Results can not be merged','Results can not be merged. Results will be stored in a new directory under results directory.') self.outputmodevariable.set(output_modes[0]) else: return False resultspath = self.outputpath.get() self.LogFileName[1] = os.path.join(resultspath,'log.txt') if not os.path.exists(resultspath): os.makedirs(resultspath) self.Message.set('Running all scenarios...|busy:True') parsers.writeTSVx(os.path.join(resultspath,'setup.cfg'),self.setupToWrite(self.setup)) self.Message.set("Setup file saved as " + os.path.split(self.setupFileVariable.get())[1] + " in results directory. ") csvlist = [] if scn == None: self.Message.set('Scenario: |progress:10|queue:0|total:'+str(len(self.setup))) for s,scenario in enumerate(self.setup): scenario = self.ReplaceOptMenuParams(scenario) csvlist.append([]) if scn == None or scn == s: source_ = sources.getSource(self.Message,sources.getSources(self.Message,self.sourcelist,scenario['source']['network'],prop='network'),scenario['source']['name']) source = sources.getProxySource(self.Message,source_,self.proxylist) self.Message.set('Analyzing ' + source['name'].replace('_',' ') + ' Camera images:') (imglist_uf,datetimelist_uf,pathlist_uf) = fetchers.fetchImages(self, self.Message, source, self.proxy, self.connection, self.imagespath.get(), scenario['temporal'], online=self.imagesdownload.get(),download=False, care_tz = self.TimeZoneConversion.get()) if imglist_uf == []: self.Message.set("No pictures found. Scenario is skipped.") self.Message.set('Scenario: |progress:10|queue:'+str(s+1)+'|total:'+str(len(self.setup))) continue self.Message.set('Analysis: |progress:8|queue:'+str(0)+'|total:'+str(len(scenario['analyses']))) for a,analysis in enumerate(scenario['analyses']): csvlist[s].append([]) analysis = scenario[analysis] filelabel = os.path.join(resultspath, 'S' + str(s+1).zfill(3) + 'A' + str(a+1).zfill(3)) if scn == None or scn == s: analysis_captions = {'scenario':scenario['name'],'analysis':str(a)+'-'+calcnames[calcids.index(analysis['id'])],'network':source['network'],'source':source['name']} self.Message.set('Running analysis ' + str(a+1) + ': ' + analysis['name'] + '...') commandstring = "output = calcfuncs." + calccommands[calcids.index(analysis['id'])] if "params" in commandstring: paramsstring = '' for i,param in enumerate(paramnames[calcids.index(analysis['id'])]): if isinstance(analysis[param],str): paramsstring += '\'' paramsstring += str(analysis[param]) if isinstance(analysis[param],str): paramsstring += '\'' if i != len(paramnames[calcids.index(analysis['id'])]) -1: paramsstring += ',' commandstring = commandstring.replace('params',paramsstring) else: for i,param in enumerate(paramnames[calcids.index(analysis['id'])]): exec("commandstring = commandstring.replace('p"+str(i)+"','"+str(analysis[param])+"')") if scenario['multiplerois'] and isinstance(scenario['polygonicmask'][0],list): self.Message.set('ROI: |progress:6|queue:'+str(0)+'|total:'+str(len(scenario['polygonicmask'])+1)) (imglist,datetimelist,pathlist) = (deepcopy(imglist_uf),deepcopy(datetimelist_uf),deepcopy(pathlist_uf)) if self.outputmodevariable.get() == output_modes[2]: self.Message.set('Reading results of image that are already processed...') (analysis_captionsv, outputtv) = readResultsData(filelabel,logger) if outputtv[0][1][0] == 'filename' and os.path.splitext(outputtv[0][1][1])[1] == '.mp4': outputtv = [] if outputtv == []: datetimelistp = [] else: datetimelistp = parsers.oTime2dTime(outputtv[0][1][1]) # one side has tzinfo one side does not. all aware results are utc. if datetimelistp != []: if datetimelistp[0].tzinfo is None or datetimelistp[0].tzinfo.utcoffset(datetimelistp[0]) is None: #old results are naive if not (datetimelist[0].tzinfo is None or datetimelist[0].tzinfo.utcoffset(datetimelist[0]) is None): #new results are not naive for i_dt,dt in enumerate(datetimelistp): datetimelistp[i_dt]=dt.replace(tzinfo=timezone('UTC')) outputtv[0][1][1][i_dt] = parsers.strftime2(datetimelistp[i_dt],"%Y-%m-%dT%H:%M:%S%z")[0][:-2] + ':' + parsers.strftime2(datetimelistp[i_dt],"%Y-%m-%d %H:%M:%S%z")[0][-2:] else: #old results are aware if datetimelist[0].tzinfo is None or datetimelist[0].tzinfo.utcoffset(datetimelist[0]) is None: #new results are naive for i_dt,dt in enumerate(datetimelistp): datetimelistp[i_dt]=dt.replace(tzinfo=None) outputtv[0][1][1][i_dt] = parsers.strftime2(datetimelistp[i_dt],"%Y-%m-%dT%H:%M:%S%z")[0] (imglista,datetimelista,pathlista) = (deepcopy(imglist),deepcopy(datetimelist),deepcopy(pathlist)) #all outputtvd = [] #out of temporal selection if outputtv != []: for i,v in enumerate(outputtv[0][1][1]): if parsers.oTime2dTime(v) not in datetimelista: outputtvd.append(i) for i in range(len(outputtv[0][1])/2)[::-1]: if isinstance(outputtv[0][1][2*i+1],list): for j in outputtvd[::-1]: del outputtv[0][1][2*i+1][j] else: outputtv[0][1][2*i+1] = np.delete(outputtv[0][1][2*i+1],outputtvd) imglist = [] #missing datetimelist = [] pathlist = [] for i,v in enumerate(datetimelista): if v not in datetimelistp: imglist.append(imglista[i]) datetimelist.append(v) pathlist.append(pathlista[i]) self.Message.set(str(len(datetimelistp))+' images are already processed. '+ str(len(imglist))+' images will be processed. Results of '+ str(len(outputtvd))+' images which do not fit the temporal selection will be deleted.') if analysis['id'] != 'TEMPO01': (imglist,datetimelist,pathlist) = fetchers.fetchImages(self, self.Message, source, self.proxy, self.connection, self.imagespath.get(), scenario['temporal'][:4]+['List',imglist,datetimelist,pathlist], online=self.imagesdownload.get(),download=True, care_tz = self.TimeZoneConversion.get()) outputValid = True if imglist == []: outputValid = False if analysis['id'] != 'TEMPO01' and scenario['multiplerois'] and isinstance(scenario['polygonicmask'][0],list): self.Message.set("No pictures are valid after filtering with thresholds. ROI is skipped.") self.Message.set('ROI: |progress:6|queue:'+str(0)+'|total:'+str(len(scenario['polygonicmask'])+1)) else: self.Message.set("No pictures are valid after filtering with thresholds. Scenario is skipped.") self.Message.set('Scenario: |progress:10|queue:'+str(s+1)+'|total:'+str(len(self.setup))) imglisto = [] if outputValid: if analysis['id'] == 'TEMPO01': mask = None else: mask = maskers.polymask(imglist,scenario['polygonicmask'],self.Message) if isinstance(mask,bool) and mask == False: outputValid = False if analysis['id'] != 'TEMPO01' and scenario['multiplerois'] and isinstance(scenario['polygonicmask'][0],list): self.Message.set("No valid images found. ROI is skipped.") self.Message.set('ROI: |progress:6|queue:'+str(0)+'|total:'+str(len(scenario['polygonicmask'])+1)) else: self.Message.set("No valid images found. Scenario is skipped.") self.Message.set('Scenario: |progress:10|queue:'+str(s+1)+'|total:'+str(len(self.setup))) mask = (mask,scenario['polygonicmask'],scenario['thresholds']) if mask[0] is False: outputValid = False else: (imglist,datetimelist,imglisto,datetimelisto) = calculations.filterThresholds(imglist,datetimelist, mask,logger) if imglist == []: outputValid = False if analysis['id'] != 'TEMPO01' and scenario['multiplerois'] and isinstance(scenario['polygonicmask'][0],list): self.Message.set("No pictures are valid after filtering with thresholds. ROI is skipped.") self.Message.set('ROI: |progress:6|queue:'+str(0)+'|total:'+str(len(scenario['polygonicmask'])+1)) else: self.Message.set("No pictures are valid after filtering with thresholds. Scenario is skipped.") self.Message.set('Scenario: |progress:10|queue:'+str(s+1)+'|total:'+str(len(self.setup))) if outputValid: exec(commandstring) else: output = False if self.outputmodevariable.get() == output_modes[2]: self.Message.set('Merging results...') if output is not False: if outputtv != []: for i in range(len(output[0][1])/2): if output[0][1][2*i] == outputtv[0][1][2*i]: output[0][1][2*i+1] = np.hstack((output[0][1][2*i+1] , outputtv[0][1][2*i+1])) else: output[0] = [outputtv[0]] break else: if outputtv != []: output = [outputtv[0]] if imglisto != [] and output is not False: for i in range(len(output[0][1])/2): if output[0][1][2*i] == "Time" or output[0][1][2*i] == "Date": output[0][1][2*i+1] = np.hstack((output[0][1][2*i+1] , map(str,datetimelisto))) else: output[0][1][2*i+1] = np.hstack((output[0][1][2*i+1] , [np.nan]*len(imglisto))) if self.outputmodevariable.get() == output_modes[2] or imglisto != []: if output is not False and output[0] != [] and not isinstance(output[0][1][1],str): isorted = np.argsort(output[0][1][1]) for i in range(len(output[0][1])/2)[::-1]: if isinstance(output[0][1][2*i+1],list): output[0][1][2*i+1] = np.array(output[0][1][2*i+1]) output[0][1][2*i+1] = output[0][1][2*i+1][isorted] if scenario['multiplerois'] and isinstance(scenario['polygonicmask'][0],list): self.Message.set('ROI: |progress:6|queue:'+str(1)+'|total:'+str(len(scenario['polygonicmask'])+1)) outputt = [] if output: outputt.append(output[0]) if analysis['id'] != 'TEMPO01' and scenario['multiplerois'] and isinstance(scenario['polygonicmask'][0],list): for r, roi in enumerate(scenario['polygonicmask']): self.Message.set("Running for ROI"+str(r+1).zfill(3)) (imglist,datetimelist,pathlist) = (deepcopy(imglist_uf),deepcopy(datetimelist_uf),deepcopy(pathlist_uf)) if self.outputmodevariable.get() == output_modes[2]: self.Message.set('Reading results of image that are already processed...') if outputtv == []: datetimelistp = [] else: datetimelistp = parsers.oTime2dTime(outputtv[r+1][1][1]) (imglista,datetimelista,pathlista) = (deepcopy(imglist),deepcopy(datetimelist),deepcopy(pathlist)) #all if outputtv != []: outputtvd = [] #out of temporal selection for i,v in enumerate(outputtv[r+1][1][1]): if parsers.oTime2dTime(v) not in datetimelista: outputtvd.append(i) for i in range(len(outputtv[r+1][1])/2)[::-1]: if isinstance(outputtv[r+1][1][2*i+1],list): for j in outputtvd[::-1]: del outputtv[r+1][1][2*i+1][j] else: np.delete(outputtv[r+1][1][2*i+1],outputtvd) imglist = [] #missing datetimelist = [] pathlist = [] for i,v in enumerate(datetimelista): if v not in datetimelistp: imglist.append(imglista[i]) datetimelist.append(v) pathlist.append(pathlista[i]) self.Message.set(str(len(datetimelistp))+' images are already processed. '+ str(len(imglist))+' images will be processed. Results of '+ str(len(outputtvd))+' images which do not fit the temporal selection will be deleted.') (imglist,datetimelist,pathlist) = fetchers.fetchImages(self, self.Message, source, self.proxy, self.connection, self.imagespath.get(), scenario['temporal'][:4]+['List',imglist,datetimelist,pathlist], online=self.imagesdownload.get(),download=True, care_tz = self.TimeZoneConversion.get()) outputValid = True if imglist == []: outputValid = False self.Message.set("No pictures are valid after filtering with thresholds. ROI is skipped.") self.Message.set('ROI: |progress:6|queue:'+str(r+2)+'|total:'+str(len(scenario['polygonicmask'])+1)) imglisto = [] if outputValid: mask = maskers.polymask(imglist,[roi],self.Message) if isinstance(mask,bool) and mask == False: outputValid = False self.Message.set("No valid images found. ROI is skipped.") self.Message.set('ROI: |progress:6|queue:'+str(r+2)+'|total:'+str(len(scenario['polygonicmask'])+1)) mask = (mask,[roi],scenario['thresholds']) if mask[0] is False: outputValid = False else: (imglist,datetimelist,imglisto,datetimelisto) = calculations.filterThresholds(imglist,datetimelist, mask,logger) if imglist == []: outputValid = False self.Message.set("No pictures are valid after filtering with thresholds. ROI is skipped.") self.Message.set('ROI: |progress:6|queue:'+str(r+2)+'|total:'+str(len(scenario['polygonicmask'])+1)) if outputValid: exec(commandstring) else: output = False if self.outputmodevariable.get() == output_modes[2]: self.Message.set('Merging results...') if output is not False: if outputtv != []: for i in range(len(output[0][1])/2): if output[0][1][2*i] == outputtv[r+1][1][2*i]: output[0][1][2*i+1] = np.hstack((output[0][1][2*i+1] , outputtv[r+1][1][2*i+1])) else: output[0] = outputtv[r+1] break else: output = [outputtv[r+1]] if imglisto != [] and output is not False: for i in range(len(output[0][1])/2): if output[0][1][2*i] == "Time" or output[0][1][2*i] == "Date": output[0][1][2*i+1] = np.hstack((output[0][1][2*i+1] , map(str,datetimelisto))) else: output[0][1][2*i+1] = np.hstack((output[0][1][2*i+1] , [np.nan]*len(imglisto))) if self.outputmodevariable.get() == output_modes[2] or imglisto != []: if output[0] != []: isorted = np.argsort(output[0][1][1]) for i in range(len(output[0][1])/2)[::-1]: if isinstance(output[0][1][2*i+1],list): output[0][1][2*i+1] = np.array(output[0][1][2*i+1]) output[0][1][2*i+1] = output[0][1][2*i+1][isorted] if output and output[0]: if ' - ROI' + str(r+1).zfill(3) not in output[0][0]: output[0][0] += ' - ROI' + str(r+1).zfill(3) outputt.append(output[0]) self.Message.set('ROI: |progress:6|queue:'+str(r+2)+'|total:'+str(len(scenario['polygonicmask'])+1)) if len(outputt)>0: if self.TimeZoneConversion.get() and self.TimeZone.get() != '+00:00': outputt = convertTZoutput(outputt,self.TimeZone.get()) csvf = storeData(filelabel, analysis_captions , outputt,self.Message,visout=True) csvlist[s][a].append(csvf) else: csvlist[s][a].append([False]) self.Message.set('Analysis: |progress:8|queue:'+str(a+1)+'|total:'+str(len(scenario['analyses']))) if scn != None and scn != s: csvf = filelabel + 'R' + str(0).zfill(3) + '.csv' if os.path.isfile(csvf): csvlist[s][a].append([csvf]) if scenario['multiplerois'] and isinstance(scenario['polygonicmask'][0],list): for r, roi in enumerate(scenario['polygonicmask']): csvf = filelabel + 'R' + str(r+1).zfill(3) + '.csv' if os.path.isfile(csvf): csvlist[s][a][0].append(csvf) else: csvlist[s][a][0].append(False) else: csvlist[s][a].append([False]) if scn == None: self.Message.set('Scenario: |progress:10|queue:'+str(s+1)+'|total:'+str(len(self.setup))) if self.outputreportvariable.get(): self.setupFileReportFunc([os.path.join(resultspath,'report.html')]+csvlist) if not sysargv['gui']: return False self.ResultFolderNameVariable.set(resultspath) self.Message.set("Running scenarios completed.|busy:False") self.LogFileName[1] = '' if self.outputmodevariable.get() == output_modes[0]: self.callbackoutputmode() self.Menu_Main_Results() self.FinishUp() def ApplyMask(self): if np.array(self.PolygonCoordinatesVariable2polygonicmask(self.PolygonCoordinatesVariable.get())).sum() != 0: if not self.PictureFile2.get(): tmp = self.PictureFileName.get() mask = maskers.polymask(self.PictureFileName.get(),self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'],self.Message) mahotas.imsave(os.path.join(TmpDir,'testmask.jpg'),mahotas.imread(self.PictureFileName.get())*mask) self.PictureFileName.set(os.path.join(TmpDir,'testmask.jpg')) self.UpdatePictures() self.PictureFileName.set(tmp) self.PictureFile2.set(True) self.Message.set("Mask applied.") else: self.UpdatePictures() self.PictureFile2.set(False) self.Message.set("Mask unapplied.") def MaskRefPlate(self): coords = maskers.findrefplate() if coords: if isinstance(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][0],list): self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'].append(coords) else: self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] = [self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'],coords] else: self.Message.set("Reference plate can not be detected.") coords = None def selectResultspath(self): self.PlotCanvasSwitch.set(False) self.file_opt = options = {} options['title'] = 'Choose path to save results...' self.Message.set("Choosing results path...") ans = tkFileDialog.askdirectory(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) self.resultspath.set(ans) else: self.Message.set("Selection of results path is cancelled.") self.Message.set("Results path is selected.") if self.ActiveMenu.get() == 'Result Viewer': self.Menu_Main_Results() def selectImagespath(self): self.file_opt = options = {} options['title'] = 'Choose path for local images...' self.Message.set("Choosing path for local images...") ans = tkFileDialog.askdirectory(**self.file_opt) if ans != '' and ans != '.' and ans != (): ans = os.path.normpath(ans) self.imagespath.set(ans) else: self.Message.set("Selection of images path is cancelled.") self.Message.set("Path for local images is selected.") def AnalysisNoNew(self): if len(self.setup)>0: self.UpdateSetup() self.setup.append(deepcopy(scenario_def)) for i in range(1,99999): name = 'Scenario-'+str(i) if len(self.setup) == 1 or len(sources.getSources(self.Message,self.setup,name,'name')) < 1: break self.setup[len(self.setup)-1].update({'name':name}) self.AnalysisNoVariable.set(len(self.setup)) self.Message.set("New scenario is added.") self.LoadValues() def AnalysisNoDelete(self): if len(self.setup) == 1: if len(self.setup)>0: self.UpdateSetup() self.setup.append(deepcopy(scenario_def)) self.AnalysisNoVariable.set(len(self.setup)) self.setup.remove(self.setup[0]) else: self.setup.remove(self.setup[self.AnalysisNoVariable.get()-1]) self.AnalysisNoVariable.set(len(self.setup)) self.Message.set("Selected scenario is deleted.") def AnalysisNoDuplicate(self): self.UpdateSetup() self.setup.append(deepcopy(self.setup[self.AnalysisNoVariable.get()-1])) self.AnalysisNoVariable.set(len(self.setup)) for i in range(1,99999): name = 'Scenario-'+str(i) if len(sources.getSources(self.Message,self.setup,name,'name')) < 1: break self.setup[self.AnalysisNoVariable.get()-1].update({'name':name}) self.UpdateSetup() self.Message.set("Selected scenario is duplicated.") def AnalysisNoDuplicateNoMask(self): self.UpdateSetup() self.setup.append(deepcopy(self.setup[self.AnalysisNoVariable.get()-1])) self.AnalysisNoVariable.set(len(self.setup)) self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] = deepcopy(scenario_def['polygonicmask']) for i in range(1,99999): name = 'Scenario-'+str(i) if len(sources.getSources(self.Message,self.setup,name,'name')) < 1: break self.setup[self.AnalysisNoVariable.get()-1].update({'name':name}) self.LoadValues() self.UpdatePictures() self.Message.set("Selected scenario is duplicated without masking.") def PolygonNoNew(self): self.UpdateSetup() if self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] != [0,0,0,0,0,0,0,0]: if isinstance(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][0],list): self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'].append(deepcopy(scenario_def['polygonicmask'])) else: self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] = [self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'],deepcopy(scenario_def['polygonicmask'])] if self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] != [0,0,0,0,0,0,0,0]: self.PolygonNoVariable.set(len(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'])) else: self.PolygonNoVariable.set(1) self.LoadValues() self.UpdatePictures() self.Message.set("New polygon is added.") else: self.Message.set("There are no points selected. No need to add polygons.") def PolygonNoDelete(self): self.UpdateSetup() if isinstance(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][0],list): self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'].remove(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1]) else: self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] = deepcopy(scenario_def['polygonicmask']) if self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] != [0,0,0,0,0,0,0,0]: self.PolygonNoVariable.set(len(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'])) else: self.PolygonNoVariable.set(1) self.LoadValues() self.UpdatePictures() self.Message.set("Selected polygon is deleted.") def CalculationNoNew(self): analyses = self.setup[self.AnalysisNoVariable.get()-1]['analyses'] i = 0 while True: i += 1 if 'analysis-'+str(i) not in analyses: break analyses.append('analysis-'+str(i)) self.setup[self.AnalysisNoVariable.get()-1].update({'analyses':analyses}) self.setup[self.AnalysisNoVariable.get()-1].update({'analysis-'+str(i):deepcopy(scenario_def['analysis-1'])}) self.Message.set("New analysis is added.") self.CalculationNoVariable.set(len(analyses)) def CalculationNoDelete(self): analyses = self.setup[self.AnalysisNoVariable.get()-1]['analyses'] analyses.remove('analysis-'+str(len(analyses))) self.setup[self.AnalysisNoVariable.get()-1].update({'analyses':analyses}) del self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(self.CalculationNoVariable.get())] if len(analyses) > 0: for i in range(self.CalculationNoVariable.get(),len(analyses)+1): self.setup[self.AnalysisNoVariable.get()-1].update({'analysis-'+str(i):self.setup[self.AnalysisNoVariable.get()-1]['analysis-'+str(i+1)]}) self.CalculationNoVariable.set(len(analyses)) else: self.setup[self.AnalysisNoVariable.get()-1].update({'analysis-1':deepcopy(scenario_def['analysis-1'])}) self.setup[self.AnalysisNoVariable.get()-1].update({'analyses':['analysis-1']}) self.CalculationNoVariable.set(1) self.Message.set("Selected analysis is deleted.") def PolygonPick(self): self.MaskingPolygonPen.set(1) self.Message.set("Polygon points can be picked now.") def PolygonRemove(self): self.MaskingPolygonPen.set(2) self.Message.set("Polygon points can be removed now.") def PolygonRemoveAll(self): if isinstance(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][0],list): self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][self.PolygonNoVariable.get()-1] = deepcopy(scenario_def['polygonicmask']) else: self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'] = deepcopy(scenario_def['polygonicmask']) self.Message.set("All polygon points are deleted.") self.LoadValues() self.UpdatePictures() def CalculationNoPlus(self): npol = len(self.setup[self.AnalysisNoVariable.get()-1]['analyses']) if self.CalculationNoVariable.get() == npol: self.CalculationNoVariable.set(1) else: self.CalculationNoVariable.set(self.CalculationNoVariable.get()+1) if self.CalculationNoVariable.get() <= 0 or self.CalculationNoVariable.get() > npol: self.CalculationNoVariable.set(1) def CalculationNoMinus(self): npol = len(self.setup[self.AnalysisNoVariable.get()-1]['analyses']) if self.CalculationNoVariable.get() == 1: self.CalculationNoVariable.set(npol) else: self.CalculationNoVariable.set(self.CalculationNoVariable.get()-1) if self.CalculationNoVariable.get() <= 0 or self.CalculationNoVariable.get() > npol: self.CalculationNoVariable.set(1) def PolygonNoMinus(self): if isinstance(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][0],list): npol = len(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask']) else: npol = 1 if self.PolygonNoVariable.get() == npol: self.PolygonNoVariable.set(1) else: self.PolygonNoVariable.set(self.PolygonNoVariable.get()+1) if self.PolygonNoVariable.get() <= 0 or self.PolygonNoVariable.get() > npol: self.PolygonNoVariable.set(1) self.UpdatePictures() def PolygonNoPlus(self): if isinstance(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask'][0],list): npol = len(self.setup[self.AnalysisNoVariable.get()-1]['polygonicmask']) else: npol = 1 if self.PolygonNoVariable.get() == 1: self.PolygonNoVariable.set(npol) else: self.PolygonNoVariable.set(self.PolygonNoVariable.get()-1) if self.PolygonNoVariable.get() <= 0 or self.PolygonNoVariable.get() > npol: self.PolygonNoVariable.set(1) self.UpdatePictures() def AnalysisNoPlus(self): self.UpdateSetup() nana = len(self.setup) if self.AnalysisNoVariable.get() == nana: self.AnalysisNoVariable.set(1) else: self.AnalysisNoVariable.set(self.AnalysisNoVariable.get()+1) if self.AnalysisNoVariable.get() <= 0 or self.AnalysisNoVariable.get() > nana: self.AnalysisNoVariable.set(1) def AnalysisNoMinus(self): self.UpdateSetup() nana = len(self.setup) if self.AnalysisNoVariable.get() == 1: self.AnalysisNoVariable.set(nana) else: self.AnalysisNoVariable.set(self.AnalysisNoVariable.get()-1) if self.AnalysisNoVariable.get() <= 0 or self.AnalysisNoVariable.get() > nana: self.AnalysisNoVariable.set(1) def SensPlus(self): if self.PreviewCanvasSwitch.get(): self.SensVariable.set(self.SensVariable.get()+1) self.UpdateWindowSize() def SensMinus(self): if self.PreviewCanvasSwitch.get(): if self.SensVariable.get() > self.SensVariableDef: self.SensVariable.set(self.SensVariable.get()-1) self.Message.set("Point selection sensitivity decreased.") else: self.SensVariable.set(self.SensVariableDef) self.Message.set("Point selection sensitivity/Plot Size is already minimum.") self.UpdateWindowSize() def UpdateWindowSize(self): self.geometry(str(self.WindowX+self.SensVariable.get()*33*self.UnitSize)+"x"+str(self.SensVariable.get()*25*self.UnitSize)) if self.ActiveMenu.get() == 'Result Viewer': self.PlotCanvas.get_tk_widget().place(x=self.WindowX,y=0,height=self.SensVariable.get()*25*self.UnitSize,width=self.SensVariable.get()*33*self.UnitSize) else: self.PictureCanvas.place(x=self.WindowX,y=0,height=self.SensVariable.get()*25*self.UnitSize,width=self.SensVariable.get()*33*self.UnitSize) self.UpdatePictures() self.Message.set("Window size updated.") def ResultPrev(self): if self.NumResultsVariable.get() != 0: if self.ResultNoVariable.get() == 0: self.ResultNoVariable.set(self.NumResultsVariable.get()-1) else: self.ResultNoVariable.set(self.ResultNoVariable.get() -1) def ResultNext(self): if self.NumResultsVariable.get() != 0: if self.ResultNoVariable.get() == (self.NumResultsVariable.get()-1): self.ResultNoVariable.set(0) else: self.ResultNoVariable.set(self.ResultNoVariable.get() +1) def CheckArchive(self, *args): (sourcelist,timec) = self.SelectSources() if sourcelist != False: if len(sourcelist) == 0: tkMessageBox.showinfo("Quantity Report",'None of the cameras is selected. Report cancelled.') else: if tkMessageBox.askyesno("Quantity Report","Depending on the number of images in the servers, quantity report can take a long time to be completed. Do you want to proceed?"): self.Message.set("Running quantity report...|busy:True") resultspath = self.outputpath.get() if not os.path.exists(resultspath): os.makedirs(resultspath) for n,network in enumerate(sources.listNetworks(self.Message,self.networklist)): slist = sources.getSources(self.Message,sourcelist,network,'network') for s,source_ in enumerate(slist): source = sources.getProxySource(self.Message,source_,self.proxylist) self.Message.set('Checking the images from the camera network: ' + network + ' and the camera: ' + source['name'] + '...') output = fetchers.checkQuantity(self,self.Message,source, self.proxy, self.connection, self.imagespath.get(), timec,30,15) analysis_captions = {'source': source['name'], 'analysis': 'Quantity Report', 'scenario': 'Quantity Report', 'network': network} if output: filelabel = os.path.join(resultspath,'N' + str(n+1).zfill(3) + 'S' + str(s+1).zfill(3)) storeData(filelabel,analysis_captions,output,self.Message) self.Message.set('Quantity Report completed.|busy:False') self.Menu_Main_Results() self.ResultFolderNameVariable.set(resultspath) def SelectSources(self, camselect = True, *args): self.SelectSources_sourcelist1 = deepcopy(self.sourcelist) self.SelectSources_sourcelist2 = [] d1=Tkinter.StringVar() d1.set(scenario_def['temporal'][0]) d2=Tkinter.StringVar() d2.set(scenario_def['temporal'][1]) t1=Tkinter.StringVar() t1.set(scenario_def['temporal'][2]) t2=Tkinter.StringVar() t2.set(scenario_def['temporal'][3]) self.tkt = Tkinter.Toplevel(self,padx=10,pady=10) self.tkt.grab_set() self.tkt.wm_title('Download images') if camselect: self.tkt.columnconfigure(1, minsize=500) self.tkt.columnconfigure(6, minsize=500) Tkinter.Label(self.tkt,text="Cameras to select",anchor='c').grid(sticky='w'+'e',row=1,column=1,columnspan=2) Tkinter.Label(self.tkt,text="Selected Cameras",anchor='c').grid(sticky='w'+'e',row=1,column=6,columnspan=2) listlen=21 scrollbar1 = Tkinter.Scrollbar(self.tkt) scrollbar2 = Tkinter.Scrollbar(self.tkt) self.SelectSources_list1 = Tkinter.Listbox(self.tkt,yscrollcommand=scrollbar1.set) scrollbar1.config(command=self.SelectSources_list1.yview) self.SelectSources_list2 = Tkinter.Listbox(self.tkt,yscrollcommand=scrollbar2.set) scrollbar2.config(command=self.SelectSources_list2.yview) self.SelectSourcesRefresh() scrollbar1.grid(sticky='n'+'s',row=2,column=2,columnspan=1,rowspan=listlen) scrollbar2.grid(sticky='n'+'s',row=2,column=7,columnspan=1,rowspan=listlen) self.SelectSources_list1.grid(sticky='n'+'s'+'w'+'e',row=2,column=1,columnspan=1,rowspan=listlen) self.SelectSources_list2.grid(sticky='n'+'s'+'w'+'e',row=2,column=6,columnspan=1,rowspan=listlen) Tkinter.Button(self.tkt ,text='<=',command=self.SelectSourcesUnselect).grid(sticky='w'+'e',row=1-1+(listlen+1)/2,column=4,columnspan=1) Tkinter.Button(self.tkt ,text='=>',command=self.SelectSourcesSelect).grid(sticky='w'+'e',row=1+1+(listlen+1)/2,column=4,columnspan=1) else: listlen = 0 self.SelectSources_sourcelist2 = [sources.getSource(self.Message,sources.getSources(self.Message,self.sourcelist,self.NetworkNameVariable.get(),'network'),self.CameraNameVariable.get())] Tkinter.Label(self.tkt,text="Date interval:",anchor='c').grid(sticky='w'+'e',row=2+listlen,column=1,columnspan=1) Tkinter.Label(self.tkt,text="Time of day:",anchor='c').grid(sticky='w'+'e',row=2+listlen,column=6,columnspan=1) Tkinter.Entry(self.tkt,textvariable=d1,justify="center").grid(sticky='w'+'e',row=3+listlen,column=1,columnspan=1) Tkinter.Entry(self.tkt,textvariable=t1,justify="center").grid(sticky='w'+'e',row=3+listlen,column=6,columnspan=1) Tkinter.Label(self.tkt,text=" - ",anchor='c').grid(sticky='w'+'e',row=4+listlen,column=1,columnspan=1) Tkinter.Label(self.tkt,text=" - ",anchor='c').grid(sticky='w'+'e',row=4+listlen,column=6,columnspan=1) Tkinter.Entry(self.tkt,textvariable=d2,justify="center").grid(sticky='w'+'e',row=5+listlen,column=1,columnspan=1) Tkinter.Entry(self.tkt,textvariable=t2,justify="center").grid(sticky='w'+'e',row=5+listlen,column=6,columnspan=1) Tkinter.Button(self.tkt ,text='OK',command=self.tkt.destroy).grid(sticky='w'+'e',row=6+listlen,column=1,columnspan=1) Tkinter.Button(self.tkt ,text='Cancel',command=self.SelectSourcesCancel).grid(sticky='w'+'e',row=6+listlen,column=6,columnspan=1) self.centerWindow(self.tkt) self.tkt.wait_window() return (self.SelectSources_sourcelist2,[d1.get(),d2.get(),t1.get(),t2.get(),temporal_modes[1]]) def SelectSourcesCancel(self,*arg): self.SelectSources_sourcelist2 = False self.tkt.destroy() self.lift() def SelectSourcesRefresh(self, *args): self.SelectSources_sourcelist1 = sources.sortSources(self.Message,self.SelectSources_sourcelist1) self.SelectSources_sourcelist2 = sources.sortSources(self.Message,self.SelectSources_sourcelist2) self.SelectSources_namelist1 = [] for source in self.SelectSources_sourcelist1: self.SelectSources_namelist1.append(source['network']+' - '+source['name']) self.SelectSources_namelist2 = [] for source in self.SelectSources_sourcelist2: self.SelectSources_namelist2.append(source['network']+' - '+source['name']) self.SelectSources_list1.delete(0,"end") for name in self.SelectSources_namelist1: self.SelectSources_list1.insert("end",name) self.SelectSources_list2.delete(0,"end") for name in self.SelectSources_namelist2: self.SelectSources_list2.insert("end",name) def SelectSourcesSelect(self,*arg): try: index = self.SelectSources_namelist1.index(self.SelectSources_list1.get(self.SelectSources_list1.curselection())) source = deepcopy(self.SelectSources_sourcelist1[index]) del self.SelectSources_sourcelist1[index] self.SelectSources_sourcelist2.append(source) self.SelectSourcesRefresh() except: pass def SelectSourcesUnselect(self,*arg): try: index = self.SelectSources_namelist2.index(self.SelectSources_list2.get(self.SelectSources_list2.curselection())) source = deepcopy(self.SelectSources_sourcelist2[index]) del self.SelectSources_sourcelist2[index] self.SelectSources_sourcelist1.append(source) self.SelectSourcesRefresh() except: pass def DownloadArchive(self, camselect=True, *args): (sourcelist,timec) = self.SelectSources(camselect) if sourcelist != False: if len(sourcelist) == 0: tkMessageBox.showinfo("Download images",'None of the cameras is selected. Download cancelled.') (sourcelist,timec) = self.SelectSources() return False else: if tkMessageBox.askyesno("Download images",str(len(sourcelist)) + " cameras are selected. Depending on the number of images in the server, downloading can take a long time to be completed. Do you want to proceed?"): self.Message.set('Downloading images...|busy:True') for source_ in sourcelist: source = sources.getProxySource(self.Message,source_,self.proxylist) self.Message.set('Downloading images of ' + source['network'] + ' - ' + source['name'] + ' camera...') fetchers.fetchImages(self, self.Message, source, self.proxy, self.connection, self.imagespath.get(), timec,online=True, care_tz = self.TimeZoneConversion.get()) self.Message.set("Downloading completed.|busy:False") return True def LogMessage(self,*args): now = datetime.datetime.now() time = parsers.strftime2(now)[0] meta = {} if '|' in self.Message.get(): for m in self.Message.get().split('|')[1:]: (k,v) = (m.split(':')[0],m.split(':')[1]) try: float(v) if '.' in v: v = float(v) else: v = int(v) except: pass if v == "True": v = True if v == "False": v = False meta.update({k:v}) message = self.Message.get().split('|')[0] else: message = self.Message.get() if "progress" not in meta: if not 'logtextonly' in meta: print time + ": " + message self.Log.set(self.Log.get() + " ~ " + time + ": " + message) self.LogLL.set(message) self.update() if "progress" in meta and meta['total'] != 1 and meta['total'] != 0: p_level = meta['progress'] p_fraction = float(10000*meta['queue']/meta['total'])/100 if meta['total'] != 0 and meta['queue'] != 0 and p_level in self.MessagePrev: try: p_remaining = datetime.timedelta(seconds=(100-p_fraction)*((now-self.MessagePrev[p_level]).total_seconds()/float(p_fraction))) except: p_remaining = '~' else: p_remaining = '~' if meta['total'] != 0 and meta['queue'] == 1: self.MessagePrev.update({p_level:now}) if meta['queue']==meta['total'] and p_level in self.MessagePrev: del self.MessagePrev[p_level] p_string = message + str(meta['queue'])+' of '+str(meta['total'])+' ('+(str(p_fraction))+'%) (' + str(p_remaining)[:7] + ')' print '\r',p_string, sys.stdout.flush() if meta['queue']==meta['total']: print '' if self.LogText.winfo_exists(): if "progress" in meta and meta['total'] != 1 and meta['total'] != 0: try: exec("self.LogProgressLabelLevel"+str(p_level)+".config(text=p_string)") exec("self.LogProgressBarLevel"+str(p_level)+"['value']=p_fraction") if meta['queue']==meta['total']: exec("self.LogProgressLabelLevel"+str(p_level)+".destroy()") exec("self.LogProgressBarLevel"+str(p_level)+".destroy()") except: exec("self.LogProgressLabelLevel"+str(p_level)+" = Tkinter.Label(self.LogWindow,anchor='c')") exec("self.LogProgressLabelLevel"+str(p_level)+".grid(sticky='w'+'e',row=1+2*p_level,column=1,columnspan=1)") exec("self.LogProgressBarLevel"+str(p_level)+" = ttk.Progressbar(self.LogWindow,orient='horizontal',length=100,mode='determinate')") exec("self.LogProgressBarLevel"+str(p_level)+".grid(sticky='w'+'e',row=2+2*p_level,column=1,columnspan=1)") exec("self.LogProgressLabelLevel"+str(p_level)+".config(text=p_string)") exec("self.LogProgressBarLevel"+str(p_level)+"['value']=p_fraction") if meta['queue']==meta['total']: exec("self.LogProgressLabelLevel"+str(p_level)+".destroy()") exec("self.LogProgressBarLevel"+str(p_level)+".destroy()") else: self.LogText.config(state='normal') self.LogText.tag_configure("hln", foreground="black") if 'color' in meta: tag = "hlc" self.LogText.tag_configure("hlc", foreground=meta['color']) else: tag = "hln" self.LogText.insert('end', time + ": " + message+'\n',tag) if "busy" in meta: self.LogText.tag_configure("hlr", foreground="red") self.LogText.tag_configure("hlg", foreground="green") if meta["busy"]: self.LogText.insert('end', "Program is busy, it will not respond until the process is complete.\n","hlr") message += "\n"+time+" Program is busy, it will not respond until the process is complete." self.LogWindow.grab_set() self.LogWindow.lift() self.BusyWindow = Tkinter.Toplevel(self,padx=10,pady=10) self.BusyWindow.grab_set() self.BusyWindow.lift() self.BusyWindow.wm_title('Program is busy') Tkinter.Label(self.BusyWindow,anchor='w',text='FMIPROT is busy, it will not respond until the process is complete...').grid(sticky='w'+'e',row=1,column=1) self.centerWindow(self.BusyWindow) else: self.LogText.insert('end', "Program is responsive again.\n","hlg") message += "\n"+time+" Program is responsive again." self.BusyWindow.destroy() self.grab_set() self.lift() self.LogText.config(state='disabled') self.LogText.see('end') self.LogWindow.update() self.LogWindow.geometry("") if 'dialog' in meta: if meta['dialog'] == 'error': tkMessageBox.showerror('Error',message) if meta['dialog'] == 'warning': tkMessageBox.showwarning('Warning',message) if meta['dialog'] == 'info': tkMessageBox.showinfo('Information',message) if not 'logtextonly' in meta and ("progress" not in meta or ( "progress" in meta and meta['total'] == 1)): for l,lfname in enumerate(self.LogFileName): if lfname == '': continue if l == 0: lf = open(os.path.join(LogDir,lfname),'a') else: if os.path.isfile(lfname): lf = open(lfname,'a') else: lf = open(lfname,'w') lf.write(time) lf.write(" ") lf.write(message) lf.write("\n") lf.close() def LogOpen(self): self.LogWindowOff() self.Message.set('Log window opened.') self.LogWindowOn() lf = open(os.path.join(LogDir,self.LogFileName[0]),'r') for line in lf: self.Message.set(line.replace('\n','')+'|logtextonly:True') lf.close() def License(self): if os.path.exists(os.path.join(BinDir,'LICENSE')): lic_f = open(os.path.join(BinDir,'LICENSE')) elif os.path.exists(os.path.join(BinDir,'..','LICENSE')): lic_f = open(os.path.join(BinDir,'..','LICENSE')) else: lic_f = None if lic_f is not None: if sysargv['gui']: LicenseWindow = Tkinter.Toplevel(self,padx=10,pady=10) LicenseWindow.wm_title('License agreement') scrollbar = Tkinter.Scrollbar(LicenseWindow,width=20) scrollbar.grid(sticky='w'+'e'+'n'+'s',row=2,column=3,columnspan=1) lictext = Tkinter.Text(LicenseWindow, yscrollcommand=scrollbar.set,wrap='word') lictext.insert('end', lic_f.read()) lic_f.close() lictext.config(state='disabled') lictext.grid(sticky='w'+'e',row=2,column=1,columnspan=2) scrollbar.config(command=lictext.yview) Tkinter.Button(LicenseWindow,text="Close",anchor="c",command=LicenseWindow.destroy).grid(sticky='w'+'e',row=3,column=1,columnspan=3) self.centerWindow(LicenseWindow) LicenseWindow.grab_set() LicenseWindow.wait_window() self.grab_set() else: print open(os.path.join(BinDir,'LICENSE')).read() else: if sysargv['gui']: tkMessageBox.showerror('Not found','License file not found.') else: print "License file not found." def LogFileOpen(self): webbrowser.open(os.path.join(LogDir,self.LogFileName[0]),new=2) def ManualFileOpen(self): if os.path.exists(os.path.join(BinDir,'usermanual.pdf')): webbrowser.open(os.path.join(BinDir,'usermanual.pdf'),new=2) elif os.path.exists(os.path.join(BinDir,'..','usermanual.pdf')): webbrowser.open(os.path.join(BinDir,'..','usermanual.pdf'),new=2) else: tkMessageBox.showerror('Not found','User manual not found.') def About(self): tkMessageBox.showinfo("About...", "FMIPROT (Finnish Meteorological Institute Image Processing Tool) is a toolbox to analyze the images from multiple camera networks and developed under the project MONIMET, funded by EU Life Programme.\nCurrent version is " + sysargv['version'] + ".\nFor more information, contact [email protected].") def WebMONIMET(self): webbrowser.open("http://monimet.fmi.fi",new=2) def WebFMIPROT(self): webbrowser.open("https://fmiprot.fmi.fi",new=2) def LogNew(self,*args): self.LogFileName[0] = str(datetime.datetime.now()).replace(":",".").replace(" ",".").replace("-",".") + ".log" def FinishUp(self): if os.path.exists(TmpDir): shutil.rmtree(TmpDir) os.makedirs(TmpDir) if __name__ == "__main__": app = monimet_gui(None) app.title('FMIPROT ' + sysargv['version']) if os.path.sep != "/": app.iconbitmap(os.path.join(ResourcesDir,'monimet.ico')) app.mainloop()
64.15625
917
0.714124
423,288
0.99604
0
0
0
0
0
0
85,433
0.201033
9a61264c94a41a473e6cc008dcf849ae78b0596c
898
py
Python
akamai/cache_buster/bust_cache.py
famartinrh/cloud-services-config
7dd4fe24fc09a62f360e3407629b1c2567a10260
[ "MIT" ]
11
2019-06-25T17:01:12.000Z
2022-01-21T18:53:13.000Z
akamai/cache_buster/bust_cache.py
famartinrh/cloud-services-config
7dd4fe24fc09a62f360e3407629b1c2567a10260
[ "MIT" ]
253
2019-05-24T12:48:32.000Z
2022-03-29T11:00:25.000Z
akamai/cache_buster/bust_cache.py
famartinrh/cloud-services-config
7dd4fe24fc09a62f360e3407629b1c2567a10260
[ "MIT" ]
93
2019-04-17T09:22:43.000Z
2022-03-21T18:53:28.000Z
import sys import subprocess def main(): edgeRcPath = sys.argv[1] branch = sys.argv[2] navlist = sys.argv[3:] domain = 'https://console.stage.redhat.com' if 'prod' in branch: domain = 'https://console.redhat.com' if 'beta' in branch: domain += '/beta' purgeAssets = ['fed-modules.json'] for nav in navlist: purgeAssets.append(f'{nav}-navigation.json') purgeUrls = [f'{domain}/config/main.yml'] for assetPath in purgeAssets: purgeUrls.append(f'{domain}/config/chrome/{assetPath}') for endpoint in purgeUrls: print(f'Purging endpoint cache: {endpoint}') try: subprocess.check_output(['akamai', 'purge', '--edgerc', edgeRcPath , 'invalidate', endpoint]) except subprocess.CalledProcessError as e: print(e.output) sys.exit(1) if __name__ == "__main__": main()
30.965517
105
0.615813
0
0
0
0
0
0
0
0
271
0.301782
9a61c54ca6366d9eef60d2491aa686f033543efd
3,261
py
Python
GAparsimony/util/config.py
misantam/GAparsimony
0241092dc5d7741b5546151ff829167588e4f703
[ "MIT" ]
null
null
null
GAparsimony/util/config.py
misantam/GAparsimony
0241092dc5d7741b5546151ff829167588e4f703
[ "MIT" ]
1
2021-12-05T10:24:55.000Z
2021-12-05T11:01:25.000Z
GAparsimony/util/config.py
misantam/GAparsimony
0241092dc5d7741b5546151ff829167588e4f703
[ "MIT" ]
null
null
null
################################################# #****************LINEAR MODELS******************# ################################################# CLASSIF_LOGISTIC_REGRESSION = {"C":{"range": (1., 100.), "type": 1}, "tol":{"range": (0.0001,0.9999), "type": 1}} CLASSIF_PERCEPTRON = {"tol":{"range": (0.0001,0.9999), "type": 1}, "alpha":{"range": (0.0001,0.9999), "type": 1}} REG_LASSO = {"tol":{"range": (0.0001,0.9999), "type": 1}, "alpha":{"range": (1., 100.), "type": 1}} REG_RIDGE = {"tol":{"range": (0.0001,0.9999), "type": 1}, "alpha":{"range": (1., 100.), "type": 1}} ################################################ #*****************SVM MODELS*******************# ################################################ CLASSIF_SVC = {"C":{"range": (1.,100.), "type": 1}, "alpha":{"range": (0.0001,0.9999), "type": 1}} REG_SVR = {"C":{"range": (1.,100.), "type": 1}, "alpha":{"range": (0.0001,0.9999), "type": 1}} ################################################## #******************KNN MODELS********************# ################################################## CLASSIF_KNEIGHBORSCLASSIFIER = {"n_neighbors":{"range": (2,11), "type": 0}, "p":{"range": (1, 3), "type": 0}} REG_KNEIGHBORSREGRESSOR = {"n_neighbors":{"range": (2,11), "type": 0}, "p":{"range": (1, 3), "type": 0}} ################################################## #******************MLP MODELS********************# ################################################## CLASSIF_MLPCLASSIFIER = {"tol":{"range": (0.0001,0.9999), "type": 1}, "alpha":{"range": (0.0001, 0.999), "type": 1}} REG_MLPREGRESSOR = {"tol":{"range": (0.0001,0.9999), "type": 1}, "alpha":{"range": (0.0001, 0.999), "type": 1}} ################################################## #*************Random Forest MODELS***************# ################################################## CLASSIF_RANDOMFORESTCLASSIFIER = {"n_estimators":{"range": (100,250), "type": 0}, "max_depth":{"range": (4, 20), "type": 0}, "min_samples_split":{"range": (2,25), "type": 0}} REG_RANDOMFORESTREGRESSOR = {"n_estimators":{"range": (100,250), "type": 0}, "max_depth":{"range": (4, 20), "type": 0}, "min_samples_split":{"range": (2,25), "type": 0}} ################################################## #*************Decision trees MODELS**************# ################################################## CLASSIF_DECISIONTREECLASSIFIER = {"min_weight_fraction_leaf":{"range": (0,20), "type": 0}, "max_depth":{"range": (4, 20), "type": 0}, "min_samples_split":{"range": (2,25), "type": 0}} REG_DECISIONTREEREGRESSOR = {"min_weight_fraction_leaf":{"range": (0,20), "type": 0}, "max_depth":{"range": (4, 20), "type": 0}, "min_samples_split":{"range": (2,25), "type": 0}}
40.259259
90
0.340693
0
0
0
0
0
0
0
0
1,739
0.533272
9a620af02d14a583cea144484597abc9077f8497
6,300
py
Python
gryphon/dashboards/handlers/status.py
qiquanzhijia/gryphon
7bb2c646e638212bd1352feb1b5d21536a5b918d
[ "Apache-2.0" ]
1,109
2019-06-20T19:23:27.000Z
2022-03-20T14:03:43.000Z
gryphon/dashboards/handlers/status.py
qiquanzhijia/gryphon
7bb2c646e638212bd1352feb1b5d21536a5b918d
[ "Apache-2.0" ]
63
2019-06-21T05:36:17.000Z
2021-05-26T21:08:15.000Z
gryphon/dashboards/handlers/status.py
qiquanzhijia/gryphon
7bb2c646e638212bd1352feb1b5d21536a5b918d
[ "Apache-2.0" ]
181
2019-06-20T19:42:05.000Z
2022-03-21T13:05:13.000Z
# -*- coding: utf-8 -*- from datetime import timedelta import logging from delorean import Delorean import tornado.web from gryphon.dashboards.handlers.admin_base import AdminBaseHandler from gryphon.lib.exchange import exchange_factory from gryphon.lib.models.order import Order from gryphon.lib.models.exchange import Exchange as ExchangeData from gryphon.lib.models.exchange import Balance from gryphon.lib.models.transaction import Transaction from gryphon.lib.money import Money logger = logging.getLogger(__name__) BANK_ACCOUNT_HIGHLIGHT_THRESHOLD = 30000 class GryphonStatusHandler(AdminBaseHandler): @tornado.web.authenticated def get(self): exchanges = exchange_factory.get_all_initialized_exchange_wrappers( self.trading_db, ) exchange_info = self.get_exchange_info(exchanges) system_balances, total_fiat = self.get_system_balances(exchanges) bank_accounts = self.get_trading_bank_accounts() in_transit_fiat_txs, in_transit_btc_txs = self.get_in_transit_transactions() recent_transactions = self.get_recent_transactions() net_flows = self.get_daily_net_transaction_flows(exchanges) self.render_template( 'status.html', args={ 'all_exchanges': exchange_info, 'system_balances': system_balances, 'bank_accounts': bank_accounts, 'total_fiat': total_fiat, 'in_transit_fiat_txs': in_transit_fiat_txs, 'in_transit_btc_txs': in_transit_btc_txs, 'recent_transactions': recent_transactions, 'net_flows': net_flows, }, ) def get_daily_net_transaction_flows(self, exchanges): flows = [] one_day_ago = Delorean().last_day(1).naive for exchange in exchanges: exchange_data = exchange.exchange_account_db_object(self.trading_db) exchange_txs = exchange_data.transactions\ .filter(Transaction._amount_currency == 'BTC')\ .filter(Transaction.time_created > one_day_ago)\ .filter(Transaction.transaction_status == 'COMPLETED')\ .order_by(Transaction.time_created.desc())\ .all() deposit_total = sum([ round(tx.amount.amount, 0) for tx in exchange_txs if tx.transaction_type == Transaction.DEPOSIT ]) withdrawal_total = sum([ round(tx.amount.amount, 0) for tx in exchange_txs if tx.transaction_type == Transaction.WITHDRAWL ]) flows.append({ 'exchange_name': exchange.name, 'withdrawals': withdrawal_total, 'deposits': deposit_total, }) flows = sorted( flows, key=lambda flow: flow.get('withdrawals') + flow.get('deposits'), reverse=True ) return flows def get_recent_transactions(self): five_hours_ago = Delorean().naive - timedelta(hours=5) txs = self.trading_db.query(Transaction)\ .filter(Transaction.time_created > five_hours_ago)\ .filter_by(transaction_status='COMPLETED')\ .order_by(Transaction.time_created.desc())\ .join(ExchangeData)\ .all() return txs def get_in_transit_transactions(self): """ Query all IN_TRANSIT transactions from the database. Returns the fiat tx results, and then the btc ones """ all_txs_query = self.trading_db.query(Transaction)\ .filter_by(transaction_status='IN_TRANSIT')\ .join(ExchangeData)\ .order_by(Transaction.time_created) fiat_txs = all_txs_query.filter(Transaction._amount_currency != "BTC").all() btc_txs = all_txs_query.filter(Transaction._amount_currency == "BTC").all() return fiat_txs, btc_txs def get_exchange_info(self, exchanges): up_exchanges = self.get_up_exchanges() exchange_info = [] for exchange in exchanges: exchange_data = exchange.exchange_account_db_object(self.trading_db) exchange_dict = { 'name': exchange.name, 'balance': exchange_data.balance, 'is_up': exchange.name in up_exchanges.keys(), 'up_since': up_exchanges.get(exchange.name), } exchange_info.append(exchange_dict) exchange_info = sorted(exchange_info, key=lambda e: e.get('is_up') is False) return exchange_info def get_system_balances(self, exchanges): system_balance = Balance() for e in exchanges: system_balance += e.exchange_account_db_object(self.trading_db).balance total_fiat = sum([ balance.to("USD") for currency, balance in system_balance.iteritems() if currency not in Money.CRYPTO_CURRENCIES ]) return system_balance, total_fiat def get_up_exchanges(self): now = Delorean().naive ten_minutes_ago = now - timedelta(minutes=10) orders = self.trading_db\ .query(Order)\ .filter(Order.time_created > ten_minutes_ago)\ .order_by(Order.time_created.asc())\ .all() up_exchanges = {} for order in orders: up_exchanges[order._exchange_name] = order.time_created # TODO: convert these into "minutes ago". for key in up_exchanges.keys(): up_exchanges[key] = now - up_exchanges[key] return up_exchanges def get_trading_bank_accounts(self): trading_bank_acount_keys = ['BMO_USD', 'BMO_CAD'] bank_account_infos = [] for key in trading_bank_acount_keys: account = exchange_factory.make_exchange_data_from_key( key, self.trading_db, ) account_info = { 'name': account.name, 'balance': account.balance.fiat(), 'highlight': account.balance.fiat() > BANK_ACCOUNT_HIGHLIGHT_THRESHOLD, } bank_account_infos.append(account_info) return bank_account_infos
33.157895
87
0.623968
5,729
0.909365
0
0
1,074
0.170476
0
0
543
0.08619
9a63239cdeadf5547e515d79f10a494c6c3288e7
4,897
py
Python
setup.py
Hydar-Zartash/TF_regression
ac7cef4c1f248664b57139ae40c582ec80b2355f
[ "MIT" ]
null
null
null
setup.py
Hydar-Zartash/TF_regression
ac7cef4c1f248664b57139ae40c582ec80b2355f
[ "MIT" ]
null
null
null
setup.py
Hydar-Zartash/TF_regression
ac7cef4c1f248664b57139ae40c582ec80b2355f
[ "MIT" ]
null
null
null
import yfinance as yf import numpy as np import pandas as pd class StockSetup(): """ The object of this class includes a dataframe, a classifier trained on it and some associated test and prediction stats """ def __init__(self, ticker: str, target:int) -> None: """Initialize the object by downloading stock data and performing several methods Args: ticker (string): the ticker to be downloaded and used target (int): the required next month growth percentage """ self.data = yf.download(ticker, period="max") self.target = target/100 + 1 #returns decimal value of int input (8% -> 1.08) self.RSI14() self.STOCHRSI() self.MACD() self.AROON() self.Williams() self.BULL() self.data = self.setup() self.data = self.data.dropna() def RSI14(self) -> None: """The formula for relative strength index is as follows RSI = 100 - 100/(1- avg gain/avg loss) in general practice, > 70 indicates a selling oppurtunity and < 30 indicates a buy all averages used are simple moving averages """ self.data['pct_change'] = 100*(self.data['Close']-self.data['Open'])/self.data['Open'] #daily perent change self.data['day_gain'] = self.data['pct_change'].where(self.data['pct_change'] > 0, other = 0) #filters the percent changes for only the gains self.data['avg_gain'] = self.data['day_gain'].rolling(window=14).mean() #take rolling avg of the gains self.data['day_loss'] = self.data['pct_change'].where(self.data['pct_change'] < 0,other = 0) #filters only precent changes of a loss self.data['avg_loss'] = self.data['day_loss'].rolling(window=14).mean() #takes rolling avg self.data['RSI-14'] = 100 -(100/ (1 - (self.data['avg_gain']/self.data['avg_loss']))) #unsmoothed RSI self.data def STOCHRSI(self) -> None: """stochastic RSI calculate a stochastic oscillation for the RSI 14 stoch = (current - recent min) / (recent max - recent min) """ self.data['STOCH-RSI'] = (self.data['RSI-14'] - self.data['RSI-14'].rolling(window=14).min())/(self.data['RSI-14'].rolling(window=14).max() - self.data['RSI-14'].rolling(window=14).min()) def MACD(self) -> None: """moving average convergence divergence is another indicator calculated by short term EMA - long term EMA EMA is provided by the pandas.ewm().mean() method """ self.data['MACD'] = self.data['Close'].ewm(span = 12, adjust=False).mean() - self.data['Close'].ewm(span = 24, adjust=False).mean() def AROON(self) -> None: """the aroon oscillator is arron up - aroon down and measures the momentum Aroon up = 100*(interval length - days since rolling max on interval)/interval Aroon up = 100*(interval length - days since rolling min on interval)/interval we will be doing a 25 day interval """ self.data['AROON'] = (100 * (25 - self.data['Close'].rolling(window=25).apply(np.argmax)) / 25) - (100 * (25 - self.data['Close'].rolling(window=25).apply(np.argmin)) / 25) def Williams(self) -> None: """Williams R% is the (Highest high - Current close)/(Highest High - Lowest low)*-100% for any given range (14 in this case) """ self.data['R%'] = (self.data['High'].rolling(window=14).max() - self.data['Close']) / (self.data['High'].rolling(window=14).max() - self.data['Low'].rolling(window=14).min()) *-100 def BULL(self) -> None: """Bull power is the formula of high - exponential weight average of the close """ self.data['Bull'] = self.data['High'] - self.data['Close'].ewm(span = 14, adjust=False).mean() def setup(self) -> pd.DataFrame: """ Adds a column to see if stock goes up by 8% in 30 days (1 for True, 0 for false) Returns: pd.DataFrame: returns df of cols: Close Values RSI 14 Stochastic oscillator of RSI 14 MACD AROON Williams R% Bull-Bear indicator boolean whether stock grew X% in the next thirty days """ self.data['Shift'] = self.data['Adj Close'].shift(-30) self.data['Shift'] = self.data['Shift'].rolling(window=30).max() self.data['Growth X%'] = self.data['Adj Close']*self.target <= self.data['Shift'] self.data['Growth X%'] = np.where(self.data['Growth X%']==True, 1, 0) final = self.data[['Adj Close', 'RSI-14', 'STOCH-RSI', 'MACD', 'AROON', 'R%', "Bull", 'Growth X%']] return final if __name__ == "__main__": stock = StockSetup('SPY', 3) print(stock.data.tail()) print(stock.data.isna().sum())
44.926606
195
0.596488
4,708
0.961405
0
0
0
0
0
0
2,615
0.534
9a636c8c285701e4e227ff48aaa2926973c39b10
1,893
py
Python
netsuitesdk/api/custom_records.py
wolever/netsuite-sdk-py
1b1c21e2a8a532fdbf54915e7e9d30b8b5fc2d08
[ "MIT" ]
47
2019-08-15T21:36:36.000Z
2022-03-18T23:44:59.000Z
netsuitesdk/api/custom_records.py
wolever/netsuite-sdk-py
1b1c21e2a8a532fdbf54915e7e9d30b8b5fc2d08
[ "MIT" ]
52
2019-06-17T09:43:04.000Z
2022-03-22T05:00:53.000Z
netsuitesdk/api/custom_records.py
wolever/netsuite-sdk-py
1b1c21e2a8a532fdbf54915e7e9d30b8b5fc2d08
[ "MIT" ]
55
2019-06-02T22:18:01.000Z
2022-03-29T07:20:31.000Z
from collections import OrderedDict from .base import ApiBase import logging logger = logging.getLogger(__name__) class CustomRecords(ApiBase): SIMPLE_FIELDS = [ 'allowAttachments', 'allowInlineEditing', 'allowNumberingOverride', 'allowQuickSearch', 'altName', 'autoName', 'created', 'customFieldList', 'customRecordId', 'description', 'disclaimer', 'enablEmailMerge', 'enableNumbering', 'includeName', 'internalId', 'isAvailableOffline', 'isInactive', 'isNumberingUpdateable', 'isOrdered', 'lastModified', 'name', 'numberingCurrentNumber', 'numberingInit', 'numberingMinDigits', 'numberingPrefix', 'numberingSuffix', 'recordName', 'scriptId', 'showCreationDate', 'showCreationDateOnList', 'showId', 'showLastModified', 'showLastModifiedOnList', 'showNotes', 'showOwner', 'showOwnerAllowChange', 'showOwnerOnList', 'translationsList', 'usePermissions', 'nullFieldList', ] RECORD_REF_FIELDS = [ 'customForm', 'owner', 'parent', 'recType', ] def __init__(self, ns_client): ApiBase.__init__(self, ns_client=ns_client, type_name='CustomRecord') def post(self, data) -> OrderedDict: assert data['externalId'], 'missing external id' record = self.ns_client.CustomRecord(externalId=data['externalId']) self.build_simple_fields(self.SIMPLE_FIELDS, data, record) self.build_record_ref_fields(self.RECORD_REF_FIELDS, data, record) logger.debug('able to create custom record = %s', record) res = self.ns_client.upsert(record) return self._serialize(res)
25.581081
77
0.59588
1,774
0.937137
0
0
0
0
0
0
758
0.400423
9a64215513cbe7b2b8f68643b42ce0ea2da19bba
147
py
Python
api/schema/__init__.py
wepickheroes/wepickheroes.github.io
032c2a75ef058aaceb795ce552c52fbcc4cdbba3
[ "MIT" ]
3
2018-02-15T20:04:23.000Z
2018-09-29T18:13:55.000Z
api/schema/__init__.py
wepickheroes/wepickheroes.github.io
032c2a75ef058aaceb795ce552c52fbcc4cdbba3
[ "MIT" ]
5
2018-01-31T02:01:15.000Z
2018-05-11T04:07:32.000Z
api/schema/__init__.py
prattl/wepickheroes
032c2a75ef058aaceb795ce552c52fbcc4cdbba3
[ "MIT" ]
null
null
null
import graphene from schema.queries import Query from schema.mutations import Mutations schema = graphene.Schema(query=Query, mutation=Mutations)
24.5
57
0.836735
0
0
0
0
0
0
0
0
0
0
9a6446896e65dc764ddad3e136039fc438fa2758
1,710
py
Python
airbox/commands/__init__.py
lewisjared/airbox
56bfdeb3e81bac47c80fbf249d9ead31c94a2139
[ "MIT" ]
null
null
null
airbox/commands/__init__.py
lewisjared/airbox
56bfdeb3e81bac47c80fbf249d9ead31c94a2139
[ "MIT" ]
null
null
null
airbox/commands/__init__.py
lewisjared/airbox
56bfdeb3e81bac47c80fbf249d9ead31c94a2139
[ "MIT" ]
null
null
null
""" This module contains a number of other commands that can be run via the cli. All classes in this submodule which inherit the baseclass `airbox.commands.base.Command` are automatically included in the possible commands to execute via the commandline. The commands can be called using their `name` property. """ from logging import getLogger from .backup import BackupCommand from .backup_sync import BackupSyncCommand from .basic_plot import BasicPlotCommand from .create_mounts import CreateMountsCommand from .install import InstallCommand from .print_fstab import PrintFstabCommand from .run_schedule import RunScheduleCommand from .spectronus_subset import SpectronusSubsetCommand from .subset import SubsetCommand logger = getLogger(__name__) # Commands are registered below _commands = [ BackupCommand(), BackupSyncCommand(), BasicPlotCommand(), CreateMountsCommand(), InstallCommand(), PrintFstabCommand(), RunScheduleCommand(), SpectronusSubsetCommand(), SubsetCommand() ] def find_commands(): """ Finds all the Commands in this package :return: List of Classes within """ # TODO: Make this actually do that. For now commands are manually registered pass def initialise_commands(parser): """ Initialise the parser with the commandline arguments for each parser :param parser: :return: """ find_commands() for c in _commands: p = parser.add_parser(c.name, help=c.help) c.initialise_parser(p) def run_command(cmd_name): """ Attempts to run a command :param config: Configuration data """ for c in _commands: if cmd_name == c.name: return c.run()
26.307692
118
0.729825
0
0
0
0
0
0
0
0
706
0.412865
9a67bbeeb8843ddedf058092d195c66fcbe342a3
1,881
py
Python
waveguide/waveguide_test.py
DentonGentry/gfiber-platform
2ba5266103aad0b7b676555eebd3c2061ddb8333
[ "Apache-2.0" ]
8
2017-09-24T03:11:46.000Z
2021-08-24T04:29:14.000Z
waveguide/waveguide_test.py
DentonGentry/gfiber-platform
2ba5266103aad0b7b676555eebd3c2061ddb8333
[ "Apache-2.0" ]
null
null
null
waveguide/waveguide_test.py
DentonGentry/gfiber-platform
2ba5266103aad0b7b676555eebd3c2061ddb8333
[ "Apache-2.0" ]
1
2017-10-05T23:04:10.000Z
2017-10-05T23:04:10.000Z
#!/usr/bin/python # Copyright 2015 Google Inc. All Rights Reserved. # # 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. import os import waveguide from wvtest import wvtest class FakeOptDict(object): """A fake options.OptDict containing default values.""" def __init__(self): self.status_dir = '/tmp/waveguide' @wvtest.wvtest def IwTimeoutTest(): old_timeout = waveguide.IW_TIMEOUT_SECS waveguide.IW_TIMEOUT_SECS = 1 old_path = os.environ['PATH'] os.environ['PATH'] = 'fake:' + os.environ['PATH'] waveguide.RunProc(lambda e, so, se: wvtest.WVPASSEQ(e, -9), ['iw', 'sleepn', str(waveguide.IW_TIMEOUT_SECS + 1)]) os.environ['PATH'] = old_path waveguide.IW_TIMEOUT_SECS = old_timeout @wvtest.wvtest def ParseDevListTest(): waveguide.opt = FakeOptDict() old_path = os.environ['PATH'] os.environ['PATH'] = 'fake:' + os.environ['PATH'] managers = [] waveguide.CreateManagers(managers, False, False, None) got_manager_summary = set((m.phyname, m.vdevname, m.primary) for m in managers) want_manager_summary = set(( ('phy1', 'wlan1', True), ('phy1', 'wlan1_portal', False), ('phy0', 'wlan0', True), ('phy0', 'wlan0_portal', False))) wvtest.WVPASSEQ(got_manager_summary, want_manager_summary) os.environ['PATH'] = old_path if __name__ == '__main__': wvtest.wvtest_main()
28.938462
74
0.696438
146
0.077618
0
0
1,009
0.536417
0
0
817
0.434343
9a67d0c9f6bb396b9d590ca653e1ee83e64bff97
3,421
py
Python
ava/actives/shell_injection.py
indeedsecurity/ava-ce
4483b301034a096b716646a470a6642b3df8ce61
[ "Apache-2.0" ]
2
2019-03-26T15:37:48.000Z
2020-01-03T03:47:30.000Z
ava/actives/shell_injection.py
indeedsecurity/ava-ce
4483b301034a096b716646a470a6642b3df8ce61
[ "Apache-2.0" ]
2
2021-03-25T21:27:09.000Z
2021-06-01T21:20:04.000Z
ava/actives/shell_injection.py
indeedsecurity/ava-ce
4483b301034a096b716646a470a6642b3df8ce61
[ "Apache-2.0" ]
null
null
null
import re from ava.common.check import _ValueCheck, _TimingCheck from ava.common.exception import InvalidFormatException # metadata name = __name__ description = "checks for shell injection" class ShellInjectionCheck(_ValueCheck): """ Checks for Shell Injection by executing the 'id' command. The payload uses shell separators to inject 'id', such as ;, &&, ||, \n, and backticks. """ key = "shell.value.command" name = "Shell Injection" description = "checks for shell injection by executing commands" example = "; id #" def __init__(self): """Define static payloads""" self._payloads = [ # no quotes '; id #', '| id #', '&& id #', '|| id #', # single quotes "' ; id #", "' | id #", "' && id #", "' || id #", # double quotes '" ; id #', '" | id #', '" && id #', '" || id #', # inside quotes '`id`', '$(id)' ] def check(self, response, payload): """ Checks for Shell Injection by looking for the output of 'id' in the response's body. :param response: response object from server :param payload: payload value :return: true if vulnerable, false otherwise """ # check response body if not response.text: return False # check for output # uid=user gid=group groups=groups regex = r"(uid=\d+[\(\)\w\-]+)(\s+gid=\d+[\(\)\w\-]+)(\s+groups=\d+[\(\)\w\-,]+)?" if re.search(regex, response.text): return True else: return False def _check_payloads(self, payloads): """ Checks if the payloads are adoptable for this class and modify the payloads to adjust to check function. InvalidFormatException is raised, if a payload is not adoptable. Children can override. :param payloads: list of payloads :return: list of modified payloads """ for i, payload in enumerate(payloads): if 'id' not in payload: raise InvalidFormatException("Payload of {} must include 'id'".format(self.key)) return payloads class ShellInjectionTimingCheck(_TimingCheck): """ Checks for Shell Injection by executing the 'sleep' command. The payload uses shell separators to inject 'sleep', such as ;, &&, ||, \n, and backticks. """ key = "shell.timing.sleep" name = "Shell Injection Timing" description = "checks for shell injection by executing delays" example = "; sleep 9 #" def __init__(self): """Define static payloads""" self._payloads = [ # no quotes ('; sleep 9 #', 9.00), ('| sleep 9 #', 9.00), ('&& sleep 9 #', 9.00), ('|| sleep 9 #', 9.00), # single quotes ("' ; sleep 9 #", 9.00), ("' | sleep 9 #", 9.00), ("' && sleep 9 #", 9.00), ("' || sleep 9 #", 9.00), # double quotes ('" ; sleep 9 #', 9.00), ('" | sleep 9 #', 9.00), ('" && sleep 9 #', 9.00), ('" || sleep 9 #', 9.00), # inside quotes ('`sleep 9`', 9.00), ('$(sleep 9)', 9.00) ]
31.385321
117
0.501315
3,222
0.94183
0
0
0
0
0
0
1,828
0.534347
7bd4127115e5637b5b3d7a956f2d5a45c70e9ad5
5,536
py
Python
matlab/FRCNN/For_LOC/python/Generate_Trecvid_Data.py
xyt2008/frcnn
32a559e881cceeba09a90ff45ad4aae1dabf92a1
[ "BSD-2-Clause" ]
198
2018-01-07T13:44:29.000Z
2022-03-21T12:06:16.000Z
matlab/FRCNN/For_LOC/python/Generate_Trecvid_Data.py
xyt2008/frcnn
32a559e881cceeba09a90ff45ad4aae1dabf92a1
[ "BSD-2-Clause" ]
18
2018-02-01T13:24:53.000Z
2021-04-26T10:51:47.000Z
matlab/FRCNN/For_LOC/python/Generate_Trecvid_Data.py
xyt2008/frcnn
32a559e881cceeba09a90ff45ad4aae1dabf92a1
[ "BSD-2-Clause" ]
82
2018-01-06T14:21:43.000Z
2022-02-16T09:39:58.000Z
import os import xml.etree.ElementTree as ET import numpy as np import scipy.sparse import scipy.io as sio import cPickle import subprocess import uuid def Get_Class_Ind(Class_INT): concepts = [] concepts.append(('Animal', [ 'n01443537', 'n01503061', 'n01639765', 'n01662784', 'n01674464', 'n01726692', 'n01770393', 'n01784675', 'n01882714', 'n01910747', 'n01944390', 'n01990800', 'n02062744', 'n02076196', 'n02084071', 'n02118333', 'n02129165', 'n02129604', 'n02131653', 'n02165456', 'n02206856', 'n02219486', 'n02268443', 'n02274259', 'n02317335', 'n02324045', 'n02342885', 'n02346627', 'n02355227', 'n02374451', 'n02391049', 'n02395003', 'n02398521', 'n02402425', 'n02411705', 'n02419796', 'n02437136', 'n02444819', 'n02445715', 'n02454379', 'n02484322', 'n02503517', 'n02509815', 'n02510455', 'Animal'])) concepts.append(('Music', [ 'n02672831', 'n02787622', 'n02803934', 'n02804123', 'n03249569', 'n03372029', 'n03467517', 'n03800933', 'n03838899', 'n03928116', 'n04141076', 'n04536866', 'Music'])) ####### concepts.append(('Bike', ['Bike', 'n02834778', 'n02835271', 'n03792782', 'n04126066'])) concepts.append(('Baby', ['Baby', 'n10353016'])) concepts.append(('Boy', ['Boy', 'n09871229', 'n09871867', 'n10078719'])) concepts.append(('Fire', ['n03343560', 'Fire', 'FIre', 'n03346135', 'n10091450', 'n10091564', 'n10091861', 'n14891255'])) concepts.append(('Skier', ['Skier', 'n04228054'])) concepts.append(('Running', ['Running'])) concepts.append(('Dancing', ['Dancing'])) concepts.append(('Sit', ['Sit'])) if (Class_INT == 2): concepts = concepts[:2] elif (Class_INT == 5): concepts = concepts[2:7] elif (Class_INT == 8): concepts = concepts[2:10] elif (Class_INT == 10): concepts = concepts[:] else: assert False _wind_to_ind = {} _class_to_ind = {} _classes = ('__background__',) for synset in concepts: _classes = _classes + (synset[0],) class_ind = len(_classes) - 1 _class_to_ind[ synset[0] ] = class_ind print ('%9s [Label]: %d' % (synset[0], class_ind)) for wnid in synset[1]: _wind_to_ind[ wnid ] = class_ind #print ('--------> : {}'.format(wnid)) return _wind_to_ind, _class_to_ind def load_annotation(filename, _class_to_ind): #filename = os.path.join(self._data_path, 'Annotations', index + '.xml') tree = ET.parse(filename) objs = tree.findall('object') num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.int32) gt_classes = np.zeros((num_objs), dtype=np.int32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): bbox = obj.find('bndbox') # Make pixel indexes 0-based x1 = float(bbox.find('xmin').text) y1 = float(bbox.find('ymin').text) x2 = float(bbox.find('xmax').text) y2 = float(bbox.find('ymax').text) cls = _class_to_ind[obj.find('name').text.strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls return {'boxes' : boxes, 'gt_classes': gt_classes} if __name__ == '__main__': #Save_Name = './dataset/8.train_val' ImageSets = ['../LOC/LOC_Split/trecvid_val_8.txt', '../LOC/LOC_Split/trecvid_train_8.txt'] ImageSets = ['../LOC/LOC_Split/trecvid_train_Animal_Music.txt', '../LOC/LOC_Split/trecvid_val_Animal_Music.txt'] ImageSets = ['../LOC/LOC_Split/trecvid_5_manual_train.txt'] ImageSets = ['../LOC/LOC_Split/trecvid_train_8.txt', '../LOC/LOC_Split/trecvid_val_8.txt', '../LOC/LOC_Split/trecvid_train_Animal_Music.txt', '../LOC/LOC_Split/trecvid_val_Animal_Music.txt'] num_cls = 10 Save_Name = '../dataset/{}.train_val'.format(num_cls) _wind_to_ind, _class_to_ind = Get_Class_Ind(num_cls) for ImageSet in ImageSets: if not os.path.isfile(ImageSet): print 'File({}) does not exist'.format(ImageSet) sys.exit(1) else: print 'Open File : {} '.format(ImageSet) print 'Save into : {} '.format(Save_Name) out_file = open(Save_Name, 'w') ids = 0 count_cls = np.zeros((num_cls+1), dtype=np.int32) assert count_cls.shape[0]-1 == len(_class_to_ind) for ImageSet in ImageSets: file = open(ImageSet, 'r') while True: line = file.readline() if line == '': break line = line.strip('\n') xml_path = '../LOC/BBOX/{}.xml'.format(line) rec = load_annotation(xml_path, _wind_to_ind) out_file.write('# {}\n'.format(ids)) ids = ids + 1 out_file.write('{}.JPEG\n'.format(line)) boxes = rec['boxes'] gt_classes = rec['gt_classes'] assert boxes.shape[0] == gt_classes.shape[0] out_file.write('{}\n'.format(boxes.shape[0])) for j in range(boxes.shape[0]): out_file.write('{} {} {} {} {} 0\n'.format(int(gt_classes[j]),int(boxes[j,0]),int(boxes[j,1]),int(boxes[j,2]),int(boxes[j,3]))) count_cls[ int(gt_classes[j]) ] = count_cls[ int(gt_classes[j]) ] + 1 if ids % 2000 == 0: print 'print {} image with recs into {}'.format(ids, Save_Name) file.close() for i in range(count_cls.shape[0]): print ('%2d th : %4d' % (i, count_cls[i])) i = i + 1 out_file.close()
37.659864
194
0.588873
0
0
0
0
0
0
0
0
1,872
0.33815
7bd4c7d5599bd575e062c27d1c3e19928097f821
5,967
py
Python
train.py
ProfessorHuang/2D-UNet-Pytorch
b3941e8dc0ac3e76b6eedb656f943f1bd66fa799
[ "MIT" ]
11
2020-12-09T10:38:47.000Z
2022-03-07T13:12:48.000Z
train.py
lllllllllllll-llll/2D-UNet-Pytorch
b3941e8dc0ac3e76b6eedb656f943f1bd66fa799
[ "MIT" ]
3
2020-11-24T02:23:02.000Z
2021-04-18T15:31:51.000Z
train.py
ProfessorHuang/2D-UNet-Pytorch
b3941e8dc0ac3e76b6eedb656f943f1bd66fa799
[ "MIT" ]
2
2021-04-07T06:17:46.000Z
2021-11-11T07:41:46.000Z
import argparse import logging import os import sys import numpy as np from tqdm import tqdm import time import torch import torch.nn as nn from torch import optim from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader from models.unet import UNet from models.nested_unet import NestedUNet from datasets.promise12 import Promise12 from datasets.chaos import Chaos from dice_loss import DiceBCELoss, dice_coeff from eval import eval_net torch.manual_seed(2020) def train_net(net, trainset, valset, device, epochs, batch_size, lr, weight_decay, log_save_path): train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2, pin_memory=True) val_loader = DataLoader(valset, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=True, drop_last=True) writer = SummaryWriter(log_dir=log_save_path) optimizer = optim.Adam(net.parameters(), lr=lr, weight_decay=weight_decay) scheduler = optim.lr_scheduler.ExponentialLR(optimizer=optimizer, gamma=0.95) criterion = DiceBCELoss() best_DSC = 0.0 for epoch in range(epochs): logging.info(f'Epoch {epoch + 1}') epoch_loss = 0 epoch_dice = 0 with tqdm(total=len(trainset), desc=f'Epoch {epoch + 1}/{epochs}', unit='img') as pbar: for batch in train_loader: net.train() imgs = batch['image'] true_masks = batch['mask'] imgs = imgs.to(device=device, dtype=torch.float32) true_masks = true_masks.to(device=device, dtype=torch.float32) masks_pred = net(imgs) pred = torch.sigmoid(masks_pred) pred = (pred>0.5).float() loss = criterion(masks_pred, true_masks) epoch_loss += loss.item() epoch_dice += dice_coeff(pred, true_masks).item() optimizer.zero_grad() loss.backward() nn.utils.clip_grad_value_(net.parameters(), 5) optimizer.step() pbar.set_postfix(**{'loss (batch)': loss.item()}) pbar.update(imgs.shape[0]) scheduler.step() logging.info('Training loss: {}'.format(epoch_loss/len(train_loader))) writer.add_scalar('Train/loss', epoch_loss/len(train_loader), epoch) logging.info('Training DSC: {}'.format(epoch_dice/len(train_loader))) writer.add_scalar('Train/dice', epoch_dice/len(train_loader), epoch) val_dice, val_loss = eval_net(net, val_loader, device, criterion) logging.info('Validation Loss: {}'.format(val_loss)) writer.add_scalar('Val/loss', val_loss, epoch) logging.info('Validation DSC: {}'.format(val_dice)) writer.add_scalar('Val/dice', val_dice, epoch) writer.add_scalar('learning_rate', optimizer.param_groups[0]['lr'], epoch) # writer.add_images('images', imgs, epoch) writer.add_images('masks/true', true_masks, epoch) writer.add_images('masks/pred', torch.sigmoid(masks_pred) > 0.5, epoch) writer.close() def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--epochs', type=int, default=100, help='Number of epochs') parser.add_argument('--batch_size', metavar='B', type=int, nargs='?', default=8, help='Batch size') parser.add_argument('--lr', metavar='LR', type=float, nargs='?', default=1e-3, help='Learning rate') parser.add_argument('--weight_decay', type=float, nargs='?', default=1e-5, help='Weight decay') parser.add_argument('--model', type=str, default='unet', help='Model name') parser.add_argument('--dataset', type=str, default='promise12', help='Dataset name') parser.add_argument('--gpu', type=int, default='0', help='GPU number') parser.add_argument('--save', type=str, default='EXP', help='Experiment name') return parser.parse_args() if __name__ == '__main__': args = get_args() args.save = 'logs_train/{}-{}-{}'.format(args.model, args.dataset, time.strftime("%Y%m%d-%H%M%S")) if not os.path.exists(args.save): os.makedirs(args.save) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(args.save, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) logging.info(f''' Model: {args.model} Dataset: {args.dataset} Total Epochs: {args.epochs} Batch size: {args.batch_size} Learning rate: {args.lr} Weight decay: {args.weight_decay} Device: GPU{args.gpu} Log name: {args.save} ''') torch.cuda.set_device(args.gpu) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # choose a model if args.model == 'unet': net = UNet() elif args.model == 'nestedunet': net = NestedUNet() net.to(device=device) # choose a dataset if args.dataset == 'promise12': dir_data = '../data/promise12' trainset = Promise12(dir_data, mode='train') valset = Promise12(dir_data, mode='val') elif args.dataset == 'chaos': dir_data = '../data/chaos' trainset = Chaos(dir_data, mode='train') valset = Chaos(dir_data, mode='val') try: train_net(net=net, trainset=trainset, valset=valset, epochs=args.epochs, batch_size=args.batch_size, lr=args.lr, weight_decay=args.weight_decay, device=device, log_save_path=args.save) except KeyboardInterrupt: try: sys.exit(0) except SystemExit: os._exit(0)
37.062112
121
0.622256
0
0
0
0
0
0
0
0
1,113
0.186526
7bd5134da373e6ab71f1575fcac61884fd8fa7f9
41
py
Python
bot/run.py
anhhanuman/python-selenium
6dbb169282c44c50189447a1c9a303ae1a790a8b
[ "Apache-2.0" ]
null
null
null
bot/run.py
anhhanuman/python-selenium
6dbb169282c44c50189447a1c9a303ae1a790a8b
[ "Apache-2.0" ]
5
2021-09-02T13:02:25.000Z
2021-09-20T04:58:37.000Z
bot/run.py
anhhanuman/python-selenium
6dbb169282c44c50189447a1c9a303ae1a790a8b
[ "Apache-2.0" ]
null
null
null
from booking.constants import myConstant
20.5
40
0.878049
0
0
0
0
0
0
0
0
0
0
7bd7021be4efb1d2b67a9ea0b8c76a83b68b38ed
411
py
Python
geoxml.py
ssubramanian90/UMich-Python-coursera
35aa6b7d939852e7e9f1751d6a7b369910c5a572
[ "bzip2-1.0.6" ]
null
null
null
geoxml.py
ssubramanian90/UMich-Python-coursera
35aa6b7d939852e7e9f1751d6a7b369910c5a572
[ "bzip2-1.0.6" ]
null
null
null
geoxml.py
ssubramanian90/UMich-Python-coursera
35aa6b7d939852e7e9f1751d6a7b369910c5a572
[ "bzip2-1.0.6" ]
null
null
null
import urllib import xml.etree.ElementTree as ET address = raw_input('Enter location: ') url = address print 'Retrieving', url uh = urllib.urlopen(url) data = uh.read() print 'Retrieved',len(data),'characters' tree = ET.fromstring(data) sumcount=count=0 counts = tree.findall('.//count') for i in counts: count+=1 sumcount+= int(i.text) print 'Count: '+str(count) print 'Sum: '+str(sumcount)
17.125
40
0.690998
0
0
0
0
0
0
0
0
79
0.192214
7bd7513f32c35775cd41faee3dba10cf9bfca50a
882
py
Python
app/mod_tweepy/controllers.py
cbll/SocialDigger
177a7b5bb1b295722e8d281a8f33678a02bd5ab0
[ "Apache-2.0" ]
3
2016-01-28T20:35:46.000Z
2020-03-08T08:49:07.000Z
app/mod_tweepy/controllers.py
cbll/SocialDigger
177a7b5bb1b295722e8d281a8f33678a02bd5ab0
[ "Apache-2.0" ]
null
null
null
app/mod_tweepy/controllers.py
cbll/SocialDigger
177a7b5bb1b295722e8d281a8f33678a02bd5ab0
[ "Apache-2.0" ]
null
null
null
from flask import Flask from flask.ext.tweepy import Tweepy app = Flask(__name__) app.config.setdefault('TWEEPY_CONSUMER_KEY', 'sve32G2LtUhvgyj64J0aaEPNk') app.config.setdefault('TWEEPY_CONSUMER_SECRET', '0z4NmfjET4BrLiOGsspTkVKxzDK1Qv6Yb2oiHpZC9Vi0T9cY2X') app.config.setdefault('TWEEPY_ACCESS_TOKEN_KEY', '1425531373-dvjiA55ApSFEnTAWPzzZAZLRoGDo3OTTtt4ER1W') app.config.setdefault('TWEEPY_ACCESS_TOKEN_SECRET', '357nVGYtynDtDBmqAZw2vxeXE3F8GbqBSqWInwStDluDX') tweepy = Tweepy(app) @app.route('/tweets') def show_tweets(): tweets = tweepy.api.public_timeline() return render_template('tweets.html', tweets=tweets) @app.route('/say-something') def say_something(): status = tweepy.api.update_status('Hello, world!') status_link = 'http://twitter.com/#!/YourUserName/status/%s' % status.id return render_template('what_i_said.html', status_link=status_link)
38.347826
102
0.794785
0
0
0
0
392
0.444444
0
0
393
0.445578
7bd7c0bcead87f462866473027496b7fc3302170
128
py
Python
sftp_sync/__init__.py
bluec0re/python-sftpsync
f68a8cb47ff38cdf883d93c448cf1bcc9df7f532
[ "MIT" ]
3
2017-06-09T09:23:03.000Z
2021-12-10T00:52:27.000Z
sftp_sync/__init__.py
bluec0re/python-sftpsync
f68a8cb47ff38cdf883d93c448cf1bcc9df7f532
[ "MIT" ]
null
null
null
sftp_sync/__init__.py
bluec0re/python-sftpsync
f68a8cb47ff38cdf883d93c448cf1bcc9df7f532
[ "MIT" ]
null
null
null
from __future__ import absolute_import from .__main__ import main from .sftp import * from .sync import * __version__ = '0.6'
16
38
0.765625
0
0
0
0
0
0
0
0
5
0.039063
7bd8ac16582450f85a23c7ef200dbfd91aa09837
2,636
py
Python
core/predictor/RF/rf_predict.py
LouisYZK/dds-avec2019
9a0ee86bddf6c23460a689bde8d75302f1d5aa45
[ "BSD-2-Clause" ]
8
2020-02-28T04:04:30.000Z
2021-12-28T07:06:06.000Z
core/predictor/RF/rf_predict.py
LouisYZK/dds-avec2019
9a0ee86bddf6c23460a689bde8d75302f1d5aa45
[ "BSD-2-Clause" ]
1
2021-04-18T09:35:13.000Z
2021-04-18T09:35:13.000Z
core/predictor/RF/rf_predict.py
LouisYZK/dds-avec2019
9a0ee86bddf6c23460a689bde8d75302f1d5aa45
[ "BSD-2-Clause" ]
2
2020-03-26T21:42:15.000Z
2021-09-09T12:50:41.000Z
"""Simple predictor using random forest """ import pandas as pd import numpy as np import math from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import RandomForestClassifier from sklearn import preprocessing from sklearn.metrics import mean_absolute_error from sklearn.metrics import f1_score from sklearn.model_selection import cross_val_score from sklearn import metrics from core.predictor.predictor import Predictor from common.sql_handler import SqlHandler from common.metric import ccc_score import config from global_values import * from common.log_handler import get_logger logger = get_logger() def pre_data(df): df[np.isnan(df)] = 0.0 df[np.isinf(df)] = 0.0 return df class RfPredictor(Predictor): def __init__(self, train, dev, features=None): """ Input: train and dev are ndarray-like data features are the freature name in tran and dev """ self.train_set = pre_data(train) self.dev_set = pre_data(dev) self.feature_list = features def train(self): self.rf = RandomForestRegressor(n_estimators=100, criterion='mse', n_jobs=-1) X = self.train_set.loc[:, 'F0_mean':].values y = self.train_set['PHQ8_Score'].values.ravel() self.rf.fit(X, y) def predict(self, X): y = self.rf.predict(X) return y def eval(self): X = self.dev_set.loc[:, 'F0_mean':].values y = self.dev_set['PHQ8_Score'].values scores = cross_val_score(self.rf, X, y, cv=10, scoring='neg_mean_absolute_error') mae = abs(scores.mean()) scores = cross_val_score(self.rf, X, y, cv=10, scoring='neg_mean_squared_error') rmse = math.sqrt(abs(scores.mean())) y_pred = self.predict(X) ccc = ccc_score(y, y_pred) fea_importance = self.rf.feature_importances_ fea_imp_dct = {fea:val for fea, val in zip(self.feature_list, fea_importance)} top = sorted(fea_imp_dct, key=lambda x: fea_imp_dct[x], reverse=True)[:5] top_fea = {fea: fea_imp_dct[fea] for fea in top} return {'MAE': mae, 'RMSE': rmse, 'CCC':ccc, 'feature_importaces': top_fea} class MultiModalRandomForest(Predictor): def __init__(self, data, features): """ data and features is a dictionary that conatines data we need. """ self.data = data self.features = features def train(self): pass def predict(self): pass def eval(self): pass
30.651163
90
0.638088
1,916
0.726859
0
0
0
0
0
0
398
0.150986
7bd8f52d214214860defef756924562c2d718956
2,135
py
Python
speed/__init__.py
Astrochamp/speed
e17b2d1de6590d08e5cfddf875b4445f20c1e08a
[ "MIT" ]
1
2022-02-12T18:43:43.000Z
2022-02-12T18:43:43.000Z
speed/__init__.py
Astrochamp/speed
e17b2d1de6590d08e5cfddf875b4445f20c1e08a
[ "MIT" ]
null
null
null
speed/__init__.py
Astrochamp/speed
e17b2d1de6590d08e5cfddf875b4445f20c1e08a
[ "MIT" ]
null
null
null
def showSpeed(func, r, *args): '''Usage: showSpeed(function, runs) You can also pass arguments into <function> like so: showSpeed(function, runs, <other>, <args>, <here> ...) showSpeed() prints the average execution time of <function> over <runs> runs ''' def formatted(f): import re s = str(f) m = re.fullmatch(r'(-?)(\d)(?:\.(\d+))?e([+-]\d+)', s) if not m: return s sign, intpart, fractpart, exponent = m.groups('') exponent = int(exponent) + 1 digits = intpart + fractpart if exponent < 0: return sign + '0.' + '0'*(-exponent) + digits exponent -= len(digits) return sign + digits + '0'*exponent + '.0' import os, sys, gc class noPrint: def __enter__(self): self._original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout.close() sys.stdout = self._original_stdout from time import perf_counter as pf garbage = gc.isenabled() gc.disable() start = pf() with noPrint(): for _ in range(r): func(*args) end = pf() if garbage: gc.enable() print(f'{formatted((end-start)/r)}') def getSpeed(func, r, *args): '''Usage: getSpeed(function, runs) You can also pass arguments into <function> like so: getSpeed(function, runs, <other>, <args>, <here> ...) getSpeed() returns the average execution time of <function> over <runs> runs, as a float ''' import os, sys, gc class noPrint: def __enter__(self): self._original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout.close() sys.stdout = self._original_stdout from time import perf_counter as pf garbage = gc.isenabled() gc.disable() start = pf() with noPrint(): for _ in range(r): func(*args) end = pf() if garbage: gc.enable() return (end-start)/r
31.865672
92
0.562061
540
0.252927
0
0
0
0
0
0
576
0.269789
7bd9a84e5c6f84dbd90d1bc72cc33fccf0f2c06c
9,106
py
Python
polygonize.py
yaramohajerani/GL_learning
aa8d644024e48ba3e68398050f259b61d0660a2e
[ "MIT" ]
7
2021-03-04T15:43:21.000Z
2021-07-08T08:42:23.000Z
polygonize.py
yaramohajerani/GL_learning
aa8d644024e48ba3e68398050f259b61d0660a2e
[ "MIT" ]
null
null
null
polygonize.py
yaramohajerani/GL_learning
aa8d644024e48ba3e68398050f259b61d0660a2e
[ "MIT" ]
2
2021-03-11T12:04:42.000Z
2021-04-20T16:33:31.000Z
#!/usr/bin/env python u""" polygonize.py Yara Mohajerani (Last update 09/2020) Read output predictions and convert to shapefile lines """ import os import sys import rasterio import numpy as np import getopt import shapefile from skimage.measure import find_contours from shapely.geometry import Polygon,LineString,Point #-- main function def main(): #-- Read the system arguments listed after the program long_options=['DIR=','FILTER=','OUT_BASE=','CODE_BASE=','IN_BASE=','noMASK'] optlist,arglist = getopt.getopt(sys.argv[1:],'D:F:O:C:I:M',long_options) #-- Set default settings subdir = os.path.join('geocoded_v1','stitched.dir',\ 'atrous_32init_drop0.2_customLossR727.dir') FILTER = 0. code_base = '/DFS-L/DATA/isabella/ymohajer/GL_learning' out_base = '/DFS-L/DATA/gl_ml' make_mask = True in_base = os.path.expanduser('~/GL_learning_data') for opt, arg in optlist: if opt in ("-D","--DIR"): subdir = arg elif opt in ("-F","--FILTER"): if arg not in ['NONE','none','None','N','n',0]: FILTER = float(arg) elif opt in ("O","--OUT_BASE"): out_base = os.path.expanduser(arg) elif opt in ("I","--IN_BASE"): in_base = os.path.expanduser(arg) elif opt in ("C","--CODE_BASE"): code_base = os.path.expanduser(arg) elif opt in ("M","--noMASK"): make_mask = False flt_str = '_%.1fkm'%(FILTER/1000) #-- make sure out directory doesn't end with '\' so we can get parent directory if out_base.endswith('/'): out_base = out_base[:-1] indir = os.path.join(in_base,subdir) #-- Get list of files fileList = os.listdir(indir) pred_list = [f for f in fileList if (f.endswith('.tif') and ('mask' not in f))] #-- LOCAL output directory local_output_dir = os.path.join(indir,'shapefiles.dir') #-- make output directory if it doesn't exist if not os.path.exists(local_output_dir): os.mkdir(local_output_dir) #-- slurm directory slurm_dir = os.path.join(indir,'slurm.dir') #-- make slurm directory if it doesn't exist if not os.path.exists(slurm_dir): os.mkdir(slurm_dir) print('# of files: ', len(pred_list)) #-- threshold for getting contours and centerlines eps = 0.3 #-- open file for list of polygons to run through centerline routine list_fid = open(os.path.join(slurm_dir,'total_job_list%s.sh'%flt_str),'w') #-- loop through prediction files #-- get contours and save each as a line in shapefile format for pcount,f in enumerate(pred_list): #-- open job list for this file sub_list_fid = open(os.path.join(slurm_dir,f.replace('.tif','%s.sh'%flt_str)),'w') #-- read file raster = rasterio.open(os.path.join(indir,f),'r') im = raster.read(1) #-- get transformation matrix trans = raster.transform if make_mask: #-- also read the corresponding mask file mask_file = os.path.join(indir,f.replace('.tif','_mask.tif')) mask_raster = rasterio.open(mask_file,'r') mask = mask_raster.read(1) mask_raster.close() #-- get contours of prediction #-- close contour ends to make polygons im[np.nonzero(im[:,0] > eps),0] = eps im[np.nonzero(im[:,-1] > eps),-1] = eps im[0,np.nonzero(im[0,:] > eps)] = eps im[-1,np.nonzero(im[-1,:] > eps)] = eps contours = find_contours(im, eps) #-- make contours into closed polyons to find pinning points #-- also apply noise filter and append to noise list x = {} y = {} noise = [] none_list = [] pols = [None]*len(contours) pol_type = [None]*len(contours) for n,contour in enumerate(contours): #-- convert to coordinates x[n],y[n] = rasterio.transform.xy(trans, contour[:,0], contour[:,1]) if len(x[n]) < 3: pols[n] = None none_list.append(n) else: pols[n] = Polygon(zip(x[n],y[n])) if make_mask: #-- get elements of mask the contour is on submask = mask[np.round(contour[:, 0]).astype('int'), np.round(contour[:, 1]).astype('int')] #-- if more than half of the elements are from test tile, count contour as test type if np.count_nonzero(submask) > submask.size/2.: pol_type[n] = 'Test' else: pol_type[n] = 'Train' else: pol_type[n] = 'Test' #-- loop through remaining polygons and determine which ones are #-- pinning points based on the width and length of the bounding box pin_list = [] box_ll = [None]*len(contours) box_ww = [None]*len(contours) for n in range(len(pols)): if n not in none_list: box_ll[n] = pols[n].length box_ww[n] = pols[n].area/box_ll[n] #-- if the with is larger than 1/25 of the length, it's a pinning point if box_ww[n] > box_ll[n]/25: pin_list.append(n) #-- Loop through all the polygons and take any overlapping areas out #-- of the enclosing polygon and ignore the inside polygon ignore_list = [] for i in range(len(pols)): for j in range(len(pols)): if (i != j) and (i not in none_list) and (j not in none_list) and pols[i].contains(pols[j]): # pols[i] = pols[i].difference(pols[j]) if (i in pin_list) and (j in pin_list): #-- if it's a pinning point, ignore outer loop ignore_list.append(i) else: #-- if not, add inner loop to ignore list ignore_list.append(j) #-- get rid of duplicates in ignore list ignore_list = list(set(ignore_list)) #-- loop through and apply noise filter for n in range(len(contours)): #-- apply filter if (n not in none_list) and (n not in ignore_list) and (len(x[n]) < 2 or LineString(zip(x[n],y[n])).length <= FILTER): noise.append(n) #-- find overlap between ignore list nad noise list if len(list(set(noise) & set(ignore_list))) != 0: sys.exit('Overlap not empty: ', list(set(noise) & set(ignore_list))) #-- find overlap between ignore list nad none list if len(list(set(none_list) & set(ignore_list))) != 0: sys.exit('Overlap not empty: ', list(set(none_list) & set(ignore_list))) #-- initialize list of contour linestrings er = [None]*len(contours) n = 0 # total center line counter er_type = [None]*len(er) er_class = [None]*len(er) er_lbl = [None]*len(er) count = 1 #-- file count pc = 1 # pinning point counter lc = 1 # line counter #-- loop through polygons and save to separate files for idx,p in enumerate(pols): er[idx] = [list(a) for a in zip(x[idx],y[idx])] er_type[idx] = pol_type[idx] if (idx in noise) or (idx in none_list): er_class[idx] = 'Noise' elif idx in ignore_list: er_class[idx] = 'Ignored Contour' else: if idx in pin_list: er_class[idx] = 'Pinning Contour' er_lbl[idx] = 'pin_err%i'%pc pc += 1 #- incremenet pinning point counter else: er_class[idx] = 'GL Uncertainty' #-- set label er_lbl[idx] = 'err%i'%lc lc += 1 #- incremenet line counter #-- write individual polygon to file out_name = f.replace('.tif','%s_ERR_%i'%(flt_str,count)) er_file = os.path.join(local_output_dir,'%s.shp'%out_name) w = shapefile.Writer(er_file) w.field('ID', 'C') w.field('Type','C') w.field('Class','C') w.field('Length','C') w.field('Width','C') w.line([er[idx]]) w.record(er_lbl[idx] , er_type[idx], er_class[idx], box_ll[idx], box_ww[idx]) w.close() # create the .prj file prj = open(er_file.replace('.shp','.prj'), "w") prj.write(raster.crs.to_wkt()) prj.close() #-- write corresponding slurm file #-- calculate run time run_time = int(p.length/300)+10 outfile = os.path.join(slurm_dir,'%s.sh'%out_name) fid = open(outfile,'w') fid.write("#!/bin/bash\n") fid.write("#SBATCH -N1\n") fid.write("#SBATCH -n1\n") fid.write("#SBATCH --mem=10G\n") fid.write("#SBATCH -t %i\n"%run_time) fid.write("#SBATCH -p sib2.9,nes2.8,has2.5,brd2.4,ilg2.3\n") fid.write("#SBATCH --job-name=gl_%i_%i_%i\n"%(pcount,idx,count)) fid.write("#SBATCH [email protected]\n") fid.write("#SBATCH --mail-type=FAIL\n\n") fid.write('source ~/miniconda3/bin/activate gl_env\n') fid.write('python %s %s\n'%\ (os.path.join(code_base,'run_centerline.py'),\ os.path.join(out_base,subdir,'shapefiles.dir','%s.shp'%out_name))) fid.close() #-- add job to list sub_list_fid.write('nohup sbatch %s\n'%os.path.join(out_base,subdir,'slurm.dir','%s.sh'%out_name)) count += 1 sub_list_fid.close() #-- add sub list fid to total job list list_fid.write('sh %s\n'%os.path.join(out_base,subdir,'slurm.dir',f.replace('.tif','%s.sh'%flt_str))) #-- save all contours to file er_file = os.path.join(local_output_dir,f.replace('.tif','%s_ERR.shp'%flt_str)) w = shapefile.Writer(er_file) w.field('ID', 'C') w.field('Type','C') w.field('Class','C') w.field('Length','C') w.field('Width','C') #-- loop over contours and write them for n in range(len(er)): w.line([er[n]]) w.record(er_lbl[n] , er_type[n], er_class[n], box_ll[n], box_ww[n]) w.close() # create the .prj file prj = open(er_file.replace('.shp','.prj'), "w") prj.write(raster.crs.to_wkt()) prj.close() #-- close input file raster.close() #-- close master list fid list_fid.close() #-- run main program if __name__ == '__main__': main()
32.992754
121
0.647595
0
0
0
0
0
0
0
0
3,544
0.389194
7bdb2f5c5a190e7161ceacb56d31dd8753fd3925
4,573
py
Python
test_autofit/graphical/regression/test_linear_regression.py
rhayes777/AutoFit
f5d769755b85a6188ec1736d0d754f27321c2f06
[ "MIT" ]
null
null
null
test_autofit/graphical/regression/test_linear_regression.py
rhayes777/AutoFit
f5d769755b85a6188ec1736d0d754f27321c2f06
[ "MIT" ]
null
null
null
test_autofit/graphical/regression/test_linear_regression.py
rhayes777/AutoFit
f5d769755b85a6188ec1736d0d754f27321c2f06
[ "MIT" ]
null
null
null
import numpy as np import pytest from autofit.graphical import ( EPMeanField, LaplaceOptimiser, EPOptimiser, Factor, ) from autofit.messages import FixedMessage, NormalMessage np.random.seed(1) prior_std = 10. error_std = 1. a = np.array([[-1.3], [0.7]]) b = np.array([-0.5]) n_obs = 100 n_features, n_dims = a.shape x = 5 * np.random.randn(n_obs, n_features) y = x.dot(a) + b + np.random.randn(n_obs, n_dims) @pytest.fixture(name="likelihood") def make_likelihood(norm): def likelihood(z, y): return norm.logpdf(z - y).sum() return likelihood @pytest.fixture(name="model") def make_model(likelihood_factor, linear_factor, prior_a, prior_b): return likelihood_factor * linear_factor * prior_a * prior_b @pytest.fixture(name="approx0") def make_approx0(a_, b_, z_, x_, y_): return { a_: NormalMessage.from_mode(np.zeros((n_features, n_dims)), 100), b_: NormalMessage.from_mode(np.zeros(n_dims), 100), z_: NormalMessage.from_mode(np.zeros((n_obs, n_dims)), 100), x_: FixedMessage(x), y_: FixedMessage(y), } @pytest.fixture(name="model_approx") def make_model_approx(model, approx0): return EPMeanField.from_approx_dists(model, approx0) def check_model_approx(mean_field, a_, b_, z_, x_, y_): X = np.c_[x, np.ones(len(x))] XTX = X.T.dot(X) + np.eye(3) * (error_std / prior_std)**2 cov = np.linalg.inv(XTX) * error_std**2 cov_a = cov[:2, :] cov_b = cov[2, :] # Analytic results mean_a = cov_a.dot(X.T.dot(y)) mean_b = cov_b.dot(X.T.dot(y)) a_std = cov_a.diagonal()[:, None] ** 0.5 b_std = cov_b[[-1]] ** 0.5 assert mean_field[a_].mean == pytest.approx(mean_a, rel=1e-2) assert mean_field[b_].mean == pytest.approx(mean_b, rel=1e-2) assert mean_field[a_].sigma == pytest.approx(a_std, rel=0.5) assert mean_field[b_].sigma == pytest.approx(b_std, rel=0.5) @pytest.fixture(name="model_jac_approx") def make_model_jac_approx( model, approx0, likelihood_factor, linear_factor_jac, prior_a, prior_b ): model = likelihood_factor * linear_factor_jac * prior_a * prior_b model_jac_approx = EPMeanField.from_approx_dists(model, approx0) return model_jac_approx def test_jacobian( a_, b_, x_, z_, linear_factor, linear_factor_jac, ): n, m, d = 5, 4, 3 x = np.random.rand(n, d) a = np.random.rand(d, m) b = np.random.rand(m) values = {x_: x, a_: a, b_: b} g0 = {z_: np.random.rand(n, m)} fval0, fjac0 = linear_factor.func_jacobian(values) fval1, fjac1 = linear_factor_jac.func_jacobian(values) fgrad0 = fjac0.grad(g0) fgrad1 = fjac1.grad(g0) assert fval0 == fval1 assert (fgrad0 - fgrad1).norm() < 1e-6 assert (fval0.deterministic_values - fval1.deterministic_values).norm() < 1e-6 def test_laplace( model_approx, a_, b_, x_, y_, z_, ): laplace = LaplaceOptimiser() opt = EPOptimiser(model_approx.factor_graph, default_optimiser=laplace) model_approx = opt.run(model_approx) mean_field = model_approx.mean_field check_model_approx(mean_field, a_, b_, z_, x_, y_) def _test_laplace_jac( model_jac_approx, a_, b_, x_, y_, z_, ): laplace = LaplaceOptimiser() opt = EPOptimiser(model_jac_approx.factor_graph, default_optimiser=laplace) model_approx = opt.run(model_jac_approx) mean_field = model_approx.mean_field check_model_approx(mean_field, a_, b_, z_, x_, y_) @pytest.fixture(name="normal_model_approx") def make_normal_model_approx( model_approx, approx0, linear_factor, a_, b_, y_, z_, ): y = model_approx.mean_field[y_].mean normal_factor = NormalMessage(y, np.full_like(y, error_std)).as_factor(z_) prior_a = NormalMessage( np.zeros_like(a), np.full_like(a, prior_std) ).as_factor(a_, 'prior_a') prior_b = NormalMessage( np.zeros_like(b), np.full_like(b, prior_std) ).as_factor(b_, 'prior_b') new_model = normal_factor * linear_factor * prior_a * prior_b return EPMeanField.from_approx_dists(new_model, approx0) def test_exact_updates( normal_model_approx, a_, b_, x_, y_, z_, ): laplace = LaplaceOptimiser() opt = EPOptimiser.from_meanfield(normal_model_approx, default_optimiser=laplace) new_approx = opt.run(normal_model_approx) mean_field = new_approx.mean_field check_model_approx(mean_field, a_, b_, z_, x_, y_)
26.9
84
0.659086
0
0
0
0
1,726
0.377433
0
0
117
0.025585
7bdbfbdb118df696ee04cd30b0904cea6a77354a
1,716
py
Python
src/linear/linear.py
RaulMurillo/cpp-torch
30d0ee38c20f389e4b996d821952a48cccc70789
[ "MIT" ]
null
null
null
src/linear/linear.py
RaulMurillo/cpp-torch
30d0ee38c20f389e4b996d821952a48cccc70789
[ "MIT" ]
null
null
null
src/linear/linear.py
RaulMurillo/cpp-torch
30d0ee38c20f389e4b996d821952a48cccc70789
[ "MIT" ]
null
null
null
import math from torch import nn import torch import torch.nn.functional as F import linear_cpu as linear class LinearFunction(torch.autograd.Function): @staticmethod def forward(ctx, input, weights, bias, params): is_bias = int(params[0]) outputs = linear.forward(input, weights, bias, is_bias)[0] variables = [input, weights, bias, params] ctx.save_for_backward(*variables) return outputs @staticmethod def backward(ctx, gradOutput): _ = torch.autograd.Variable(torch.zeros(5)) input, weights, bias, params = ctx.saved_tensors is_bias = int(params[0]) gradInput, gradWeight, gradBias = linear.backward( input, gradOutput, weights, is_bias) return gradInput, gradWeight, gradBias, _ class Linear(nn.Module): def __init__(self, in_features, out_features, is_bias=True): super(Linear, self).__init__() self.in_features = in_features self.out_features = out_features self.is_bias = is_bias self.params = torch.autograd.Variable(torch.Tensor([is_bias])) self.weight = nn.Parameter(torch.empty(out_features, in_features)) self.bias = nn.Parameter(torch.empty(out_features)) self._initialize_weights() def _initialize_weights(self): nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.is_bias: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0 nn.init.uniform_(self.bias, -bound, bound) def forward(self, input): return LinearFunction.apply(input, self.weight, self.bias, self.params)
29.586207
79
0.666084
1,604
0.934732
0
0
636
0.370629
0
0
0
0
7bdf6ec04e7754ae150125e027e057b6d43b24d9
11,907
py
Python
object_files_api/files_api.py
ndlib/mellon-manifest-pipeline
aa90494e73fbc30ce701771ac653d28d533217db
[ "Apache-2.0" ]
1
2021-06-27T15:16:13.000Z
2021-06-27T15:16:13.000Z
object_files_api/files_api.py
ndlib/marble-manifest-pipeline
abc036e4c81a8a5e938373a43153e2492a17cbf8
[ "Apache-2.0" ]
8
2019-11-05T18:58:23.000Z
2021-09-03T14:54:42.000Z
object_files_api/files_api.py
ndlib/mellon-manifest-pipeline
aa90494e73fbc30ce701771ac653d28d533217db
[ "Apache-2.0" ]
null
null
null
""" Files API """ import boto3 import os import io from datetime import datetime, timedelta import json import time from s3_helpers import write_s3_json, read_s3_json, delete_s3_key from api_helpers import json_serial from search_files import crawl_available_files, update_pdf_fields from dynamo_helpers import add_file_to_process_keys, add_file_group_keys, get_iso_date_as_string, add_image_group_keys, add_media_group_keys, add_media_keys, add_image_keys from dynamo_save_functions import save_file_system_record from add_files_to_json_object import change_file_extensions_to_tif from pipelineutilities.dynamo_query_functions import get_all_file_to_process_records_by_storage_system class FilesApi(): def __init__(self, event, config): self.event = event self.event['local'] = self.event.get('local', False) self.config = config self.local_folder = os.path.dirname(os.path.realpath(__file__)) + "/" self.time_to_break = datetime.now() + timedelta(seconds=config['seconds-to-allow-for-processing']) if self.config.get('test', False): self.directory = os.path.join(os.path.dirname(__file__), 'test') else: self.directory = os.path.join(os.path.dirname(__file__), 'cache') self.start_time = time.time() self.table_name = self.config.get('website-metadata-tablename', '') self.resumption_filename = 'file_objects_list_partially_processed.json' if not self.event['local']: save_file_system_record(self.table_name, 'S3', 'Marble content bucket') save_file_system_record(self.table_name, 'S3', 'Multimedia bucket') self.file_to_process_records_in_dynamo = {} if not self.config.get('local', True): print("pulling file_to_process_records from dynamo") self.file_to_process_records_in_dynamo = get_all_file_to_process_records_by_storage_system(self.config.get('website-metadata-tablename', ''), 'S3') self.table = boto3.resource('dynamodb').Table(self.table_name) self.config['forceSaveCrawlAvailableFiles'] = False def save_files_details(self): """ This will crawl available files, then loop through the file listing, saving each to dynamo """ if self.event['objectFilesApi_execution_count'] == 1: marble_files = self._crawl_available_files_from_s3_or_cache(self.config['marble-content-bucket'], True) # rbsc_files = self._crawl_available_files_from_s3_or_cache(self.config['rbsc-image-bucket'], True) # save in case we need to crawl the RBSC bucket ever again # all_files_listing = {**rbsc_files, **marble_files} all_files_listing = {**marble_files} else: all_files_listing = self._resume_execution() file_objects = [] processing_complete = True for key, value in all_files_listing.items(): if not value.get('recordProcessedFlag', False): file_objects.extend(self._save_file_objects_per_collection(value)) value['recordProcessedFlag'] = True print("saved", len(value.get('files', [])), "files for collection: ", key, int(time.time() - self.start_time), 'seconds.') if datetime.now() >= self.time_to_break: self._save_progress(all_files_listing) processing_complete = False break if processing_complete: self._clean_up_when_done() self.event['objectFilesApiComplete'] = True if self.event['local']: self._cache_s3_call(os.path.join(self.directory, "file_objects.json"), file_objects) else: write_s3_json(self.config['manifest-server-bucket'], 'objectFiles/all/index.json', file_objects) return file_objects def _save_progress(self, all_files_listing: dict): """ This is used to save progress in order to resume execution later """ if self.event['local']: cache_file_name = os.path.join(self.directory, self.resumption_filename) self._cache_s3_call(self, cache_file_name, all_files_listing) else: s3_key = os.path.join(self.config['pipeline-control-folder'], self.resumption_filename) write_s3_json(self.config['process-bucket'], s3_key, all_files_listing) def _resume_execution(self) -> list: """ This re-loads the all_files_listing saved as part of _save_progress in order to resume execution """ all_files_listing = [] if self.event['local']: cache_file_name = os.path.join(self.directory, self.resumption_filename) if os.path.exists(cache_file_name): with io.open(cache_file_name, 'r', encoding='utf-8') as json_file: all_files_listing = json.load(json_file) else: s3_key = os.path.join(self.config['pipeline-control-folder'], self.resumption_filename) all_files_listing = read_s3_json(self.config['process-bucket'], s3_key) return all_files_listing def _clean_up_when_done(self): """ This deletes work-in-progress files """ if self.event['local']: cache_file_name = os.path.join(self.directory, self.resumption_filename) if os.path.exists(cache_file_name): os.remove(cache_file_name) else: s3_key = os.path.join(self.config['pipeline-control-folder'], self.resumption_filename) delete_s3_key(self.config['process-bucket'], s3_key) def _save_file_objects_per_collection(self, collection_json: dict) -> list: # noqa: C901 """ Loop through every file in a collection and save each record into dynamo """ i = 0 collection_list = [] object_group_ids = [] image_group_ids = [] media_group_ids = [] for file_info in collection_json.get('files', []): i += 1 my_json = dict(file_info) my_json['sequence'] = i my_json['id'] = my_json.get('key', '') my_json['copyrightStatus'] = "Public domain" if 'copyright' in my_json.get('key', '').lower(): # If the word "copyright" exists in the folder structure, this file is Copyrighted my_json['copyrightStatus'] = "Copyright" if 'mediaGroupId' not in my_json and 'imageGroupId' not in my_json: continue # We must have either mediaGroupId or imageGroupId or we can't process this record. if 'mediaGroupId' in my_json: # is_media_file(self.config.get('media-file-extensions', []), my_json.get('id')): my_json = add_media_keys(my_json, self.config.get('media-server-base-url', '')) else: update_pdf_fields(my_json) my_json = change_file_extensions_to_tif(my_json, self.config.get("file-extensions-to-protect-from-changing-to-tif", [])) my_json = add_image_keys(my_json, self.config.get('image-server-base-url', '')) my_json['typeOfData'] = my_json.get('typeOfData', 'Marble content bucket') collection_list.append(my_json) my_json['storageSystem'] = my_json.get('storageSystem', 'S3') if 'sourceFilePath' not in my_json: my_json['sourceFilePath'] = my_json.get('path', '') # only add if this does not already exist if not self.config.get('local', False): with self.table.batch_writer() as batch: batch.put_item(Item=my_json) item_id = my_json.get('id') if self.config.get('folder_exposed_through_cdn') not in my_json.get('id'): # nothing in the folder exposed through cdn should have image processing done for it. if self.event.get('exportAllFilesFlag', False) or item_id not in self.file_to_process_records_in_dynamo or my_json.get('modifiedDate', '') > self.file_to_process_records_in_dynamo[item_id].get('dateModifiedInDynamo', ''): # noqa: #501 file_to_process_json = dict(my_json) file_to_process_json = add_file_to_process_keys(file_to_process_json) batch.put_item(Item=file_to_process_json) collection_list.append(file_to_process_json) # Only insert Group records once object_group_id = my_json.get('objectFileGroupId') if object_group_id and object_group_id not in object_group_ids: # This will be removed once we transition to imageGroupId and mediaGroupId file_group_record = {'objectFileGroupId': object_group_id} file_group_record['storageSystem'] = my_json.get('storageSystem') file_group_record['typeOfData'] = my_json.get('typeOfData') file_group_record['dateAddedToDynamo'] = get_iso_date_as_string() file_group_record = add_file_group_keys(file_group_record) batch.put_item(Item=file_group_record) collection_list.append(file_group_record) object_group_ids.append(object_group_id) image_group_id = my_json.get('imageGroupId') if image_group_id and image_group_id not in image_group_ids: image_group_record = {'imageGroupId': image_group_id} image_group_record['storageSystem'] = my_json.get('storageSystem') image_group_record['typeOfData'] = my_json.get('typeOfData') image_group_record['dateAddedToDynamo'] = get_iso_date_as_string() image_group_record = add_image_group_keys(image_group_record) batch.put_item(Item=image_group_record) collection_list.append(image_group_record) image_group_ids.append(image_group_id) media_group_id = my_json.get('mediaGroupId') if media_group_id and media_group_id not in media_group_ids: media_group_record = {'mediaGroupId': media_group_id} media_group_record['storageSystem'] = my_json.get('storageSystem') media_group_record['typeOfData'] = my_json.get('typeOfData') media_group_record['dateAddedToDynamo'] = get_iso_date_as_string() media_group_record = add_media_group_keys(media_group_record) batch.put_item(Item=media_group_record) collection_list.append(media_group_record) media_group_ids.append(media_group_id) return collection_list def _cache_s3_call(self, file_name: str, objects: dict): """ Save json file locally """ with open(file_name, 'w') as outfile: json.dump(objects, outfile, default=json_serial, sort_keys=True, indent=2) def _crawl_available_files_from_s3_or_cache(self, bucket: str, force_use_s3: bool = False) -> dict: """ Find all related files, whether from querying S3 or loading from a local json file. """ cache_file = os.path.join(self.directory, 'crawl_available_files_cache.json') if force_use_s3 or (not self.config.get("test", False) and not self.config.get('local', False)): objects = crawl_available_files(self.config, bucket) if self.config.get('local', False) or self.config.get('forceSaveCrawlAvailableFiles', False): self._cache_s3_call(cache_file, objects) return objects elif os.path.exists(cache_file): with io.open(cache_file, 'r', encoding='utf-8') as json_file: return json.load(json_file) else: return {}
62.340314
259
0.646342
11,219
0.942219
0
0
0
0
0
0
2,857
0.239943
7be095f1c9c4b3f5f33d92d1c96cc497d62846c5
40,240
py
Python
sampledb/frontend/projects.py
NicolasCARPi/sampledb
d6fd0f4d28d05010d7e0c022fbf2576e25435077
[ "MIT" ]
null
null
null
sampledb/frontend/projects.py
NicolasCARPi/sampledb
d6fd0f4d28d05010d7e0c022fbf2576e25435077
[ "MIT" ]
null
null
null
sampledb/frontend/projects.py
NicolasCARPi/sampledb
d6fd0f4d28d05010d7e0c022fbf2576e25435077
[ "MIT" ]
null
null
null
# coding: utf-8 """ """ import flask import flask_login import json from flask_babel import _ from . import frontend from .. import logic from ..logic.object_permissions import Permissions from ..logic.security_tokens import verify_token from ..logic.languages import get_languages, get_language, get_language_by_lang_code from ..models.languages import Language from .projects_forms import CreateProjectForm, EditProjectForm, LeaveProjectForm, InviteUserToProjectForm, InviteGroupToProjectForm, AddSubprojectForm, RemoveSubprojectForm, DeleteProjectForm, RemoveProjectMemberForm, RemoveProjectGroupForm, ObjectLinkForm from .permission_forms import PermissionsForm from .utils import check_current_user_is_not_readonly from ..logic.utils import get_translated_text @frontend.route('/projects/<int:project_id>', methods=['GET', 'POST']) @flask_login.login_required def project(project_id): if 'token' in flask.request.args: token = flask.request.args.get('token') expiration_time_limit = flask.current_app.config['INVITATION_TIME_LIMIT'] token_data = verify_token(token, salt='invite_to_project', secret_key=flask.current_app.config['SECRET_KEY'], expiration=expiration_time_limit) if token_data is None: flask.flash(_('Invalid project group invitation token. Please request a new invitation.'), 'error') return flask.abort(403) if 'invitation_id' in token_data: if logic.projects.get_project_invitation(token_data['invitation_id']).accepted: flask.flash(_('This invitation token has already been used. Please request a new invitation.'), 'error') return flask.abort(403) if token_data.get('project_id', None) != project_id: return flask.abort(403) permissions = Permissions.from_value(token_data.get('permissions', Permissions.READ.value)) if permissions == Permissions.NONE: flask.flash(_('Invalid permissions in project group invitation token. Please request a new invitation.'), 'error') return flask.abort(403) user_id = token_data.get('user_id', None) if user_id != flask_login.current_user.id: if user_id is not None: try: invited_user = logic.users.get_user(user_id) flask.flash(_('Please sign in as user "%(user_name)s" to accept this invitation.', user_name=invited_user.name), 'error') except logic.errors.UserDoesNotExistError: pass return flask.abort(403) if not flask.current_app.config['DISABLE_SUBPROJECTS']: other_project_ids = token_data.get('other_project_ids', []) for notification in logic.notifications.get_notifications(user_id, unread_only=True): if notification.type == logic.notifications.NotificationType.INVITED_TO_PROJECT: if notification.data['project_id'] == project_id: logic.notifications.mark_notification_as_read(notification.id) else: other_project_ids = [] try: logic.projects.add_user_to_project(project_id, user_id, permissions, other_project_ids=other_project_ids) except logic.errors.UserAlreadyMemberOfProjectError: flask.flash(_('You are already a member of this project group.'), 'error') except logic.errors.ProjectDoesNotExistError: pass allowed_language_ids = [ language.id for language in get_languages(only_enabled_for_input=True) ] user_id = flask_login.current_user.id try: project = logic.projects.get_project(project_id) except logic.errors.ProjectDoesNotExistError: return flask.abort(404) user_permissions = logic.projects.get_user_project_permissions(project_id=project_id, user_id=user_id, include_groups=True) if Permissions.READ in user_permissions: show_objects_link = True else: show_objects_link = False if Permissions.READ in user_permissions: leave_project_form = LeaveProjectForm() else: leave_project_form = None translations = [] name_language_ids = [] description_language_ids = [] if Permissions.WRITE in user_permissions: edit_project_form = EditProjectForm() for name in project.name.items(): lang_id = get_language_by_lang_code(name[0]).id name_language_ids.append(lang_id) item = { 'language_id': lang_id, 'lang_name': get_translated_text(get_language(lang_id).names), 'name': name[1], 'description': '' } translations.append(item) for description in project.description.items(): if description[0] == '': continue lang_id = get_language_by_lang_code(description[0]).id description_language_ids.append(lang_id) for translation in translations: if lang_id == translation['language_id']: translation['description'] = description[1] break else: item = { 'language_id': lang_id, 'lang_name': get_translated_text(get_language(lang_id).names), 'name': '', 'description': description[1] } translations.append(item) else: edit_project_form = None show_edit_form = False english = get_language(Language.ENGLISH) project_member_user_ids_and_permissions = logic.projects.get_project_member_user_ids_and_permissions(project_id=project_id, include_groups=False) project_member_group_ids_and_permissions = logic.projects.get_project_member_group_ids_and_permissions(project_id=project_id) project_member_user_ids = list(project_member_user_ids_and_permissions.keys()) project_member_user_ids.sort(key=lambda user_id: logic.users.get_user(user_id).name.lower()) project_member_group_ids = list(project_member_group_ids_and_permissions.keys()) project_member_group_ids.sort(key=lambda group_id: get_translated_text(logic.groups.get_group(group_id).name).lower()) if Permissions.GRANT in user_permissions: invitable_user_list = [] for user in logic.users.get_users(exclude_hidden=True, exclude_fed=True): if user.id not in project_member_user_ids_and_permissions: invitable_user_list.append(user) parent_projects_with_add_permissions = logic.projects.get_ancestor_project_ids(project_id, only_if_child_can_add_users_to_ancestor=True) else: invitable_user_list = [] parent_projects_with_add_permissions = [] if invitable_user_list: other_project_ids_data = [] for parent_project_id in parent_projects_with_add_permissions: other_project_ids_data.append({'project_id': parent_project_id}) invite_user_form = InviteUserToProjectForm(other_project_ids=other_project_ids_data) else: invite_user_form = None if Permissions.GRANT in user_permissions: invitable_group_list = [] for group in logic.groups.get_user_groups(user_id): if group.id not in project_member_group_ids_and_permissions: invitable_group_list.append(group) else: invitable_group_list = [] if invitable_group_list: other_project_ids_data = [] for parent_project_id in parent_projects_with_add_permissions: other_project_ids_data.append({'project_id': parent_project_id}) invite_group_form = InviteGroupToProjectForm(other_project_ids=other_project_ids_data) else: invite_group_form = None child_project_ids = logic.projects.get_child_project_ids(project_id) child_project_ids_can_add_to_parent = {child_project_id: logic.projects.can_child_add_users_to_parent_project(parent_project_id=project_id, child_project_id=child_project_id) for child_project_id in child_project_ids} parent_project_ids = logic.projects.get_parent_project_ids(project_id) add_subproject_form = None remove_subproject_form = None delete_project_form = None remove_project_member_form = None remove_project_group_form = None addable_projects = [] addable_project_ids = [] if Permissions.GRANT in user_permissions: for other_project in logic.projects.get_user_projects(flask_login.current_user.id, include_groups=True): if other_project.id == project.id: continue if Permissions.GRANT in logic.projects.get_user_project_permissions(other_project.id, flask_login.current_user.id, include_groups=True): addable_projects.append(other_project) addable_project_ids = logic.projects.filter_child_project_candidates(project_id, [child_project.id for child_project in addable_projects]) addable_projects = [logic.projects.get_project(child_project_id) for child_project_id in addable_project_ids] if addable_projects: add_subproject_form = AddSubprojectForm() if child_project_ids: remove_subproject_form = RemoveSubprojectForm() delete_project_form = DeleteProjectForm() remove_project_member_form = RemoveProjectMemberForm() remove_project_group_form = RemoveProjectGroupForm() project_invitations = None show_invitation_log = flask_login.current_user.is_admin and logic.settings.get_user_settings(flask_login.current_user.id)['SHOW_INVITATION_LOG'] if Permissions.GRANT in user_permissions or flask_login.current_user.is_admin: project_invitations = logic.projects.get_project_invitations( project_id=project_id, include_accepted_invitations=show_invitation_log, include_expired_invitations=show_invitation_log ) object = logic.projects.get_object_linked_to_project(project_id) if 'leave' in flask.request.form and Permissions.READ in user_permissions: if leave_project_form.validate_on_submit(): try: logic.projects.remove_user_from_project(project_id=project_id, user_id=user_id) except logic.errors.ProjectDoesNotExistError: flask.flash(_('This project group does not exist.'), 'error') return flask.redirect(flask.url_for('.projects')) except logic.errors.UserDoesNotExistError: return flask.abort(500) except logic.errors.UserNotMemberOfProjectError: flask.flash(_('You have already left the project group.'), 'error') return flask.redirect(flask.url_for('.projects')) except logic.errors.NoMemberWithGrantPermissionsForProjectError: flask.flash(_('You cannot leave this project group, because your are the only user with GRANT permissions.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) else: flask.flash(_('You have successfully left the project group.'), 'success') # create object log entry if this caused the deletion of a project linked to an object try: logic.projects.get_project(project_id) except logic.errors.ProjectDoesNotExistError: if object is not None: logic.object_log.unlink_project( flask_login.current_user.id, object.id, project_id, project_deleted=True ) return flask.redirect(flask.url_for('.projects')) if 'delete' in flask.request.form and Permissions.GRANT in user_permissions: if delete_project_form.validate_on_submit(): check_current_user_is_not_readonly() # create object log entry if deleting a project linked to an object if object is not None: logic.object_log.unlink_project( flask_login.current_user.id, object.id, project_id, project_deleted=True ) try: logic.projects.delete_project(project_id=project_id) except logic.errors.ProjectDoesNotExistError: flask.flash(_('This project group has already been deleted.'), 'success') return flask.redirect(flask.url_for('.projects')) else: flask.flash(_('You have successfully deleted the project group.'), 'success') return flask.redirect(flask.url_for('.projects')) if 'remove_member' in flask.request.form and Permissions.GRANT in user_permissions: if remove_project_member_form.validate_on_submit(): check_current_user_is_not_readonly() member_id_str = flask.request.form['remove_member'] try: member_id = int(member_id_str) except ValueError: flask.flash(_('The member ID was invalid. Please contact an administrator.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) if member_id == flask_login.current_user.id: flask.flash(_('You cannot remove yourself from a project group. Please press "Leave Project Group" instead.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) try: logic.projects.remove_user_from_project(project_id=project_id, user_id=member_id) except logic.errors.ProjectDoesNotExistError: flask.flash(_('This project group does not exist.'), 'error') return flask.redirect(flask.url_for('.projects')) except logic.errors.UserDoesNotExistError: flask.flash(_('This user does not exist.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) except logic.errors.UserNotMemberOfProjectError: flask.flash(_('This user is not a member of this project group.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) except logic.errors.NoMemberWithGrantPermissionsForProjectError: flask.flash(_('You cannot remove this user from this project group, because they are the only user with GRANT permissions.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) else: flask.flash(_('You have successfully removed this user from the project group.'), 'success') return flask.redirect(flask.url_for('.project', project_id=project_id)) if 'remove_group' in flask.request.form and Permissions.GRANT in user_permissions: if remove_project_group_form.validate_on_submit(): check_current_user_is_not_readonly() group_id_str = flask.request.form['remove_group'] try: group_id = int(group_id_str) except ValueError: flask.flash(_('The basic group ID was invalid. Please contact an administrator.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) try: logic.projects.remove_group_from_project(project_id=project_id, group_id=group_id) except logic.errors.ProjectDoesNotExistError: flask.flash(_('This project group does not exist.'), 'error') return flask.redirect(flask.url_for('.projects')) except logic.errors.GroupDoesNotExistError: flask.flash(_('This basic group does not exist.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) except logic.errors.GroupNotMemberOfProjectError: flask.flash(_('This basic group is not a member of this project group.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) except logic.errors.NoMemberWithGrantPermissionsForProjectError: flask.flash(_('You cannot remove this basic group from this project group, because they are the only basic group with GRANT permissions.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) else: flask.flash(_('You have successfully removed this basic group from the project group.'), 'success') return flask.redirect(flask.url_for('.project', project_id=project_id)) if 'edit' in flask.request.form and Permissions.WRITE in user_permissions: show_edit_form = True if edit_project_form.validate_on_submit(): check_current_user_is_not_readonly() try: translations = json.loads(edit_project_form.translations.data) if not translations: raise ValueError(_('Please enter at least an english name.')) names = {} descriptions = {} for translation in translations: name = translation['name'].strip() description = translation['description'].strip() language_id = int(translation['language_id']) if language_id not in allowed_language_ids: continue if language_id == Language.ENGLISH: if name == '': raise ValueError(_('Please enter at least an english name.')) elif name == '' and description == '': continue lang_code = get_language(language_id).lang_code names[lang_code] = name if description != '': descriptions[lang_code] = description else: descriptions[lang_code] = '' logic.projects.update_project(project_id, names, descriptions) except ValueError as e: flask.flash(str(e), 'error') edit_project_form.translations.errors.append(str(e)) except logic.errors.ProjectDoesNotExistError: flask.flash(_('This project group does not exist.'), 'error') return flask.redirect(flask.url_for('.projects')) except logic.errors.ProjectAlreadyExistsError: edit_project_form.name.errors.append(_('A project group with this name already exists.')) except logic.errors.InvalidProjectNameError: edit_project_form.name.errors.append(_('This project group name is invalid.')) else: flask.flash(_('Project group information updated successfully.'), 'success') return flask.redirect(flask.url_for('.project', project_id=project_id)) if 'add_user' in flask.request.form and Permissions.GRANT in user_permissions: if invite_user_form.validate_on_submit(): check_current_user_is_not_readonly() if not any(user.id == invite_user_form.user_id.data for user in invitable_user_list): flask.flash(_('You cannot add this user.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) permissions = Permissions.from_value(invite_user_form.permissions.data) if Permissions.READ not in permissions: flask.flash(_('Please select read permissions (or higher) for the invitation.'), 'error') return flask.redirect(flask.url_for('.projects')) try: other_project_ids = [] for other_project_id_form in invite_user_form.other_project_ids: try: if other_project_id_form.add_user.data: other_project_ids.append(int(other_project_id_form.project_id.data)) except (KeyError, ValueError): pass logic.projects.invite_user_to_project(project_id, invite_user_form.user_id.data, flask_login.current_user.id, other_project_ids, permissions) except logic.errors.ProjectDoesNotExistError: flask.flash(_('This project group does not exist.'), 'error') return flask.redirect(flask.url_for('.projects')) except logic.errors.UserDoesNotExistError: flask.flash(_('This user does not exist.'), 'error') except logic.errors.UserAlreadyMemberOfProjectError: flask.flash(_('This user is already a member of this project group.'), 'error') else: flask.flash(_('The user was successfully invited to the project group.'), 'success') return flask.redirect(flask.url_for('.project', project_id=project_id)) if 'add_group' in flask.request.form and Permissions.GRANT in user_permissions: if invite_group_form.validate_on_submit(): check_current_user_is_not_readonly() if not any(group.id == invite_group_form.group_id.data for group in invitable_group_list): flask.flash(_('You cannot add this basic group.'), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) try: logic.projects.add_group_to_project(project_id, invite_group_form.group_id.data, permissions=Permissions.READ) except logic.errors.ProjectDoesNotExistError: flask.flash(_('This project group does not exist.'), 'error') return flask.redirect(flask.url_for('.projects')) except logic.errors.GroupDoesNotExistError: flask.flash(_('This basic group does not exist.'), 'error') except logic.errors.GroupAlreadyMemberOfProjectError: flask.flash(_('This basic group is already a member of this project group.'), 'error') else: flask.flash(_('The basic group was successfully added to the project group.'), 'success') return flask.redirect(flask.url_for('.project', project_id=project_id)) if not flask.current_app.config['DISABLE_SUBPROJECTS']: if 'remove_subproject' in flask.request.form and Permissions.GRANT in user_permissions: if remove_subproject_form is not None and remove_subproject_form.validate_on_submit(): check_current_user_is_not_readonly() child_project_id = remove_subproject_form.child_project_id.data if child_project_id not in child_project_ids: flask.flash(_('Project group #%(child_project_id)s is not a child of this project group.', child_project_id=int(child_project_id)), 'error') else: logic.projects.delete_subproject_relationship(project_id, child_project_id) flask.flash(_('The child project group was successfully removed from this project group.'), 'success') return flask.redirect(flask.url_for('.project', project_id=project_id)) if 'add_subproject' in flask.request.form and Permissions.GRANT in user_permissions: if add_subproject_form is not None and add_subproject_form.validate_on_submit(): check_current_user_is_not_readonly() child_project_id = add_subproject_form.child_project_id.data if child_project_id not in addable_project_ids: flask.flash(_('Project group #%(child_project_id)s cannot become a child of this project group.', child_project_id=int(child_project_id)), 'error') else: logic.projects.create_subproject_relationship(project_id, child_project_id, child_can_add_users_to_parent=add_subproject_form.child_can_add_users_to_parent.data) flask.flash(_('The child project group was successfully added to this project group.'), 'success') return flask.redirect(flask.url_for('.project', project_id=project_id)) object_id = object.id if object is not None else None object_action = None object_link_form = None linkable_objects = [] linkable_action_ids = [] already_linked_object_ids = [] if Permissions.GRANT in user_permissions and not flask_login.current_user.is_readonly: object_link_form = ObjectLinkForm() if object is None: already_linked_object_ids = [link[1] for link in logic.projects.get_project_object_links()] for action_type in logic.actions.get_action_types(): if action_type.enable_project_link: linkable_action_ids.extend([ action.id for action in logic.actions.get_actions(action_type.id) ]) if not flask.current_app.config['LOAD_OBJECTS_IN_BACKGROUND']: for object_info in logic.object_permissions.get_object_info_with_permissions(user_id, Permissions.GRANT, action_type_id=action_type.id): if object_info.object_id not in already_linked_object_ids: linkable_objects.append((object_info.object_id, get_translated_text(object_info.name_json))) if object is not None: object_permissions = logic.object_permissions.get_user_object_permissions(object.object_id, flask_login.current_user.id) if Permissions.READ in object_permissions: object_action = logic.actions.get_action(object.action_id) else: object = None return flask.render_template( 'projects/project.html', ENGLISH=english, translations=translations, languages=get_languages(only_enabled_for_input=True), name_language_ids=name_language_ids, description_language_ids=description_language_ids, get_user=logic.users.get_user, get_group=logic.groups.get_group, get_project=logic.projects.get_project, project=project, project_member_user_ids=project_member_user_ids, project_member_group_ids=project_member_group_ids, project_member_user_ids_and_permissions=project_member_user_ids_and_permissions, project_member_group_ids_and_permissions=project_member_group_ids_and_permissions, project_invitations=project_invitations, show_invitation_log=show_invitation_log, object=object, object_id=object_id, object_link_form=object_link_form, linkable_action_ids=linkable_action_ids, already_linked_object_ids=already_linked_object_ids, linkable_objects=linkable_objects, object_action=object_action, leave_project_form=leave_project_form, delete_project_form=delete_project_form, remove_project_member_form=remove_project_member_form, remove_project_group_form=remove_project_group_form, edit_project_form=edit_project_form, show_edit_form=show_edit_form, invite_user_form=invite_user_form, invitable_user_list=invitable_user_list, invite_group_form=invite_group_form, invitable_group_list=invitable_group_list, show_objects_link=show_objects_link, child_project_ids=child_project_ids, child_project_ids_can_add_to_parent=child_project_ids_can_add_to_parent, parent_project_ids=parent_project_ids, add_subproject_form=add_subproject_form, addable_projects=addable_projects, remove_subproject_form=remove_subproject_form, user_may_edit_permissions=Permissions.GRANT in user_permissions, ) @frontend.route('/projects/', methods=['GET', 'POST']) @flask_login.login_required def projects(): user_id = None if 'user_id' in flask.request.args: try: user_id = int(flask.request.args['user_id']) except ValueError: pass if user_id is not None: if user_id != flask_login.current_user.id and not flask_login.current_user.is_admin: return flask.abort(403) projects = logic.projects.get_user_projects(user_id) else: projects = logic.projects.get_projects() for project in projects: project.permissions = logic.projects.get_user_project_permissions(project_id=project.id, user_id=flask_login.current_user.id, include_groups=True) create_project_form = CreateProjectForm() show_create_form = False if 'create' in flask.request.form: allowed_language_ids = [ language.id for language in get_languages(only_enabled_for_input=True) ] show_create_form = True if create_project_form.validate_on_submit(): check_current_user_is_not_readonly() if flask_login.current_user.is_admin or not flask.current_app.config['ONLY_ADMINS_CAN_CREATE_PROJECTS']: try: translations = json.loads(create_project_form.translations.data) if not translations: raise ValueError(_('Please enter at least an english name.')) names = {} descriptions = {} for translation in translations: name = translation['name'].strip() description = translation['description'].strip() language_id = int(translation['language_id']) if language_id not in allowed_language_ids: continue if language_id == Language.ENGLISH: if name == '': raise ValueError(_('Please enter at least an english name.')) lang_code = get_language(language_id).lang_code names[lang_code] = name if description != '': descriptions[lang_code] = description else: descriptions[lang_code] = '' project_id = logic.projects.create_project(names, descriptions, flask_login.current_user.id).id except ValueError as e: flask.flash(str(e), 'error') create_project_form.translations.errors.append(str(e)) except logic.errors.ProjectAlreadyExistsError: create_project_form.translations.errors.append(_('A project group with this name already exists.')) except logic.errors.InvalidProjectNameError: create_project_form.translations.errors.append(_('This project group name is invalid.')) else: flask.flash(_('The project group has been created successfully.'), 'success') return flask.redirect(flask.url_for('.project', project_id=project_id)) else: create_project_form.translations.errors.append(_('Only administrators can create project groups.')) projects_by_id = { project.id: project for project in projects } project_id_hierarchy_list = logic.projects.get_project_id_hierarchy_list(list(projects_by_id)) english = get_language(Language.ENGLISH) return flask.render_template( "projects/projects.html", create_project_form=create_project_form, show_create_form=show_create_form, Permissions=logic.projects.Permissions, projects_by_id=projects_by_id, project_id_hierarchy_list=project_id_hierarchy_list, languages=get_languages(only_enabled_for_input=True), ENGLISH=english ) @frontend.route('/projects/<int:project_id>/permissions') @flask_login.login_required def project_permissions(project_id): try: project = logic.projects.get_project(project_id) except logic.errors.ProjectDoesNotExistError: return flask.abort(404) user_permissions = logic.projects.get_project_member_user_ids_and_permissions(project_id, include_groups=False) group_permissions = logic.projects.get_project_member_group_ids_and_permissions(project_id) if Permissions.GRANT in logic.projects.get_user_project_permissions(project_id=project_id, user_id=flask_login.current_user.id, include_groups=True): delete_project_form = DeleteProjectForm() user_permission_form_data = [] for user_id, permissions in sorted(user_permissions.items()): if user_id is None: continue user_permission_form_data.append({'user_id': user_id, 'permissions': permissions.name.lower()}) group_permission_form_data = [] for group_id, permissions in sorted(group_permissions.items()): if group_id is None: continue group_permission_form_data.append({'group_id': group_id, 'permissions': permissions.name.lower()}) permissions_form = PermissionsForm(user_permissions=user_permission_form_data, group_permissions=group_permission_form_data) # disable permissions for all users and other projects permissions_form.all_user_permissions.choices = [('none', Permissions.NONE)] permissions_form.project_permissions.max_entries = 0 else: delete_project_form = None permissions_form = None return flask.render_template( 'projects/project_permissions.html', project=project, delete_project_form=delete_project_form, user_permissions=user_permissions, group_permissions=group_permissions, get_user=logic.users.get_user, get_group=logic.groups.get_group, Permissions=Permissions, permissions_form=permissions_form ) @frontend.route('/projects/<int:project_id>/permissions', methods=['POST']) @flask_login.login_required def update_project_permissions(project_id): check_current_user_is_not_readonly() try: if Permissions.GRANT not in logic.projects.get_user_project_permissions(project_id, flask_login.current_user.id, include_groups=True): return flask.abort(403) except logic.errors.ProjectDoesNotExistError: return flask.abort(404) permissions_form = PermissionsForm() # disable permissions for all users and other projects permissions_form.all_user_permissions.choices = [('none', Permissions.NONE)] permissions_form.project_permissions.max_entries = 0 if 'edit_permissions' in flask.request.form and permissions_form.validate_on_submit(): # First handle GRANT updates, then others (to prevent temporarily not having a GRANT user) for user_permissions_data in sorted(permissions_form.user_permissions.data, key=lambda upd: upd['permissions'] != 'grant'): user_id = user_permissions_data['user_id'] try: logic.users.get_user(user_id) except logic.errors.UserDoesNotExistError: continue permissions = Permissions.from_name(user_permissions_data['permissions']) try: logic.projects.update_user_project_permissions(project_id=project_id, user_id=user_id, permissions=permissions) except logic.errors.NoMemberWithGrantPermissionsForProjectError: continue for group_permissions_data in permissions_form.group_permissions.data: group_id = group_permissions_data['group_id'] try: logic.groups.get_group(group_id) except logic.errors.GroupDoesNotExistError: continue permissions = Permissions.from_name(group_permissions_data['permissions']) logic.projects.update_group_project_permissions(project_id=project_id, group_id=group_id, permissions=permissions) flask.flash(_("Successfully updated project group permissions."), 'success') else: flask.flash(_("A problem occurred while changing the project group permissions. Please try again."), 'error') try: logic.projects.get_project(project_id) except logic.errors.ProjectDoesNotExistError: return flask.redirect(flask.url_for('.projects')) return flask.redirect(flask.url_for('.project_permissions', project_id=project_id)) @frontend.route('/projects/<int:project_id>/object_link', methods=['POST']) @flask_login.login_required def link_object(project_id): check_current_user_is_not_readonly() object_link_form = ObjectLinkForm() if not object_link_form.validate_on_submit(): flask.flash(_("Missing or invalid object ID."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) object_id = object_link_form.object_id.data try: if Permissions.GRANT not in logic.projects.get_user_project_permissions(project_id, flask_login.current_user.id, True): flask.flash(_("You do not have GRANT permissions for this project group."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) if Permissions.GRANT not in logic.object_permissions.get_user_object_permissions(object_id, flask_login.current_user.id): flask.flash(_("You do not have GRANT permissions for this object."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) logic.projects.link_project_and_object(project_id, object_id, flask_login.current_user.id) except logic.errors.ProjectObjectLinkAlreadyExistsError: flask.flash(_("Project group is already linked to an object or object is already linked to a project group."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) except logic.errors.ProjectDoesNotExistError: flask.flash(_("Project group does not exist."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) except logic.errors.ObjectDoesNotExistError: flask.flash(_("Object does not exist."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) flask.flash(_("Successfully linked the object to a project group."), 'success') return flask.redirect(flask.url_for('.project', project_id=project_id)) @frontend.route('/projects/<int:project_id>/object_unlink', methods=['POST']) @flask_login.login_required def unlink_object(project_id): check_current_user_is_not_readonly() object_link_form = ObjectLinkForm() if not object_link_form.validate_on_submit(): flask.flash(_("Missing or invalid object ID."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) object_id = object_link_form.object_id.data try: if Permissions.GRANT not in logic.projects.get_user_project_permissions(project_id, flask_login.current_user.id, True): flask.flash(_("You do not have GRANT permissions for this project group."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) logic.projects.unlink_project_and_object(project_id, object_id, flask_login.current_user.id) except logic.errors.ProjectObjectLinkDoesNotExistsError: flask.flash(_("No link exists between this object and project group."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) except logic.errors.ProjectDoesNotExistError: flask.flash(_("Project group does not exist."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) except logic.errors.ObjectDoesNotExistError: flask.flash(_("Object does not exist."), 'error') return flask.redirect(flask.url_for('.project', project_id=project_id)) flask.flash(_("Successfully unlinked the object and project group."), 'success') return flask.redirect(flask.url_for('.project', project_id=project_id))
56.437588
256
0.675149
0
0
0
0
39,453
0.980442
0
0
5,972
0.14841
7be58215b629ccdaed1b12b4ee8ac016d5bf374b
1,474
py
Python
setup.py
caalle/caaalle
3653155338fefde73579508ee83905a8ad8e3924
[ "Apache-2.0" ]
null
null
null
setup.py
caalle/caaalle
3653155338fefde73579508ee83905a8ad8e3924
[ "Apache-2.0" ]
4
2021-04-26T18:42:38.000Z
2021-04-26T18:42:41.000Z
setup.py
caalle/caaalle
3653155338fefde73579508ee83905a8ad8e3924
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 import codecs import os import re from setuptools import setup with open('README.md', 'r') as f: readme = f.read() here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") _title = 'caaalle' _description = 'caaalle' _author = 'Carl Larsson' _author_email = '[email protected]' _license = 'Apache 2.0' _url = 'https://github.com/caalle/caaalle' setup( name=_title, description=_description, long_description=readme, long_description_content_type='text/markdown', version=find_version("caaalle", "__init__.py"), author=_author, author_email=_author_email, url=_url, packages=['caaalle'], include_package_data=True, python_requires=">=3.5.*", install_requires=[], license=_license, zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.5' ], keywords='caaalle' )
26.321429
68
0.643148
0
0
0
0
0
0
0
0
459
0.311398
7be7ae3f178cdb0ca2b090e6df4678e140e34e75
311
py
Python
Assets/Code/Python/src/python.py
Ross-Morgan/Logic-Gate-Visualisation
01976248ef66837ec2009f18533fd0aab090a8b9
[ "BSD-3-Clause" ]
null
null
null
Assets/Code/Python/src/python.py
Ross-Morgan/Logic-Gate-Visualisation
01976248ef66837ec2009f18533fd0aab090a8b9
[ "BSD-3-Clause" ]
null
null
null
Assets/Code/Python/src/python.py
Ross-Morgan/Logic-Gate-Visualisation
01976248ef66837ec2009f18533fd0aab090a8b9
[ "BSD-3-Clause" ]
null
null
null
def or_gate(a:int, b:int): return a | b def and_gate(a:int, b:int): return a & b def nor_gate(a:int, b:int): return 1 - (a | b) def nand_gate(a:int, b:int): return 1 - (a | b) def xor_gate(a:int, b:int): return a ^ b def xnor_gate(a:int, b:int): return 1 - (a ^ b)
17.277778
29
0.533762
0
0
0
0
0
0
0
0
0
0
7be827f0693117abffb3e3ef853dcd8e6d5807a0
10,522
py
Python
kevlar/tests/test_novel.py
johnsmith2077/kevlar
3ed06dae62479e89ccd200391728c416d4df8052
[ "MIT" ]
24
2016-12-07T07:59:09.000Z
2019-03-11T02:05:36.000Z
kevlar/tests/test_novel.py
johnsmith2077/kevlar
3ed06dae62479e89ccd200391728c416d4df8052
[ "MIT" ]
325
2016-12-07T07:37:17.000Z
2019-03-12T19:01:40.000Z
kevlar/tests/test_novel.py
standage/kevlar
622d1869266550422e91a60119ddc7261eea434a
[ "MIT" ]
8
2017-08-17T01:37:39.000Z
2019-03-01T16:17:44.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # # ----------------------------------------------------------------------------- # Copyright (c) 2016 The Regents of the University of California # # This file is part of kevlar (http://github.com/dib-lab/kevlar) and is # licensed under the MIT license: see LICENSE. # ----------------------------------------------------------------------------- import filecmp import glob import json import pytest import re from tempfile import NamedTemporaryFile, mkdtemp import screed from shutil import rmtree import sys import kevlar from kevlar.tests import data_file, data_glob from khmer import Counttable def test_novel_banding_args(): errormsg = r'Must specify `numbands` and `band` together' with pytest.raises(ValueError, match=errormsg): reads = list(kevlar.novel.novel(None, [], [], numbands=4)) with pytest.raises(ValueError, match=errormsg): reads = list(kevlar.novel.novel(None, [], [], band=0)) errormsg = r'`band` must be a value between 0 and 3' with pytest.raises(ValueError, match=errormsg): reads = list(kevlar.novel.novel(None, [], [], numbands=4, band=-1)) def test_cli(): args = kevlar.cli.parser().parse_args([ 'novel', '--case', 'case1.fq', '--control', 'cntl1.fq', '--control', 'cntl2.fq', '-k', '17', ]) assert args.ksize == 17 assert args.case_min == 6 assert args.ctrl_max == 1 assert args.num_bands is None assert args.band is None args = kevlar.cli.parser().parse_args([ 'novel', '--num-bands', '8', '--band', '1', '--case', 'case1.fq', '--control', 'cntl1.fq', '--control', 'cntl2.fq', ]) assert args.ksize == 31 assert args.case_min == 6 assert args.ctrl_max == 1 assert args.num_bands == 8 assert args.band == 1 errormsg = r'Must specify --num-bands and --band together' with pytest.raises(ValueError, match=errormsg): args = kevlar.cli.parser().parse_args([ 'novel', '--case', 'case1.fq', '--control', 'cntl1.fq', '--band', '1' ]) kevlar.novel.main(args) @pytest.mark.parametrize('kmer', [ ('ACCGTACAA' * 3), ('TTATAATAG' * 3), ('CGAAAAATT' * 3), ]) def test_assumptions(kmer): ct = Counttable(27, 1e5, 2) kmer_rc = kevlar.revcom(kmer) assert ct.hash(kmer) == ct.hash(kmer_rc) assert ct.get_kmer_hashes(kmer)[0] == ct.get_kmer_hashes(kmer_rc)[0] @pytest.mark.parametrize('case,ctrl', [ ('microtrios/trio-li-proband.fq.gz', 'microtrios/trio-li-??ther.fq.gz'), ('microtrios/trio-na-proband.fq.gz', 'microtrios/trio-na-??ther.fq.gz'), ('microtrios/trio-k-proband.fq.gz', 'microtrios/trio-k-??ther.fq.gz'), ]) def test_novel_single_mutation(case, ctrl, capsys): casestr = data_file(case) ctrls = kevlar.tests.data_glob(ctrl) arglist = ['novel', '--case', casestr, '--ksize', '25', '--case-min', '7', '--control', ctrls[0], '--control', ctrls[1], '--num-bands', '2', '--band', '2', '--ctrl-max', '0', '--memory', '500K'] args = kevlar.cli.parser().parse_args(arglist) kevlar.novel.main(args) out, err = capsys.readouterr() for line in out.split('\n'): if not line.endswith('#') or line.startswith('#mateseq'): continue abundmatch = re.search(r'(\d+) (\d+) (\d+)#$', line) assert abundmatch, line case = int(abundmatch.group(1)) ctl1 = int(abundmatch.group(2)) ctl2 = int(abundmatch.group(3)) assert case >= 7, line assert ctl1 == 0 and ctl2 == 0, line def test_novel_two_cases(capsys): cases = kevlar.tests.data_glob('trio1/case6*.fq') controls = kevlar.tests.data_glob('trio1/ctrl[5,6].fq') with NamedTemporaryFile(suffix='.ct') as case1ct, \ NamedTemporaryFile(suffix='.ct') as case2ct, \ NamedTemporaryFile(suffix='.ct') as ctrl1ct, \ NamedTemporaryFile(suffix='.ct') as ctrl2ct: counttables = [case1ct, case2ct, ctrl1ct, ctrl2ct] seqfiles = cases + controls for ct, seqfile in zip(counttables, seqfiles): arglist = ['count', '--ksize', '19', '--memory', '1e7', ct.name, seqfile] print(arglist) args = kevlar.cli.parser().parse_args(arglist) kevlar.count.main(args) arglist = ['novel', '--ksize', '19', '--memory', '1e7', '--ctrl-max', '1', '--case-min', '7', '--case', cases[0], '--case', cases[1], '--case-counts', case1ct.name, case2ct.name, '--control-counts', ctrl1ct.name, ctrl2ct.name] args = kevlar.cli.parser().parse_args(arglist) kevlar.novel.main(args) out, err = capsys.readouterr() assert out.strip() != '' for line in out.split('\n'): if not line.endswith('#') or line.startswith('#mateseq'): continue abundmatch = re.search(r'(\d+) (\d+) (\d+) (\d+)#$', line) assert abundmatch, line case1 = int(abundmatch.group(1)) case2 = int(abundmatch.group(2)) ctl1 = int(abundmatch.group(3)) ctl2 = int(abundmatch.group(4)) assert case1 >= 7 and case2 >= 7 assert ctl1 <= 1 and ctl2 <= 1 def test_kmer_rep_in_read(capsys): from sys import stdout read = ('AGGATGAGGATGAGGATGAGGATGAGGATGAGGATGAGGATGAGGATGAGGATGAGGATGAGGAT' 'GAGGATGAGGATGAGGAT') record = kevlar.sequence.Record(name='reqseq', sequence=read) record.annotate('GATGAGGATGAGGATGAGGATGAGG', 2, (11, 1, 0)) record.annotate('GATGAGGATGAGGATGAGGATGAGG', 8, (11, 1, 0)) kevlar.print_augmented_fastx(record, stdout) out, err = capsys.readouterr() assert read in out def test_iter_read_multi_file(): infiles = kevlar.tests.data_glob('bogus-genome/mask-chr[1,2].fa') print(infiles) records = [r for r in kevlar.multi_file_iter_khmer(infiles)] assert len(records) == 4 def test_novel_abund_screen(capsys): case = data_file('screen-case.fa') ctrl = data_file('screen-ctrl.fa') arglist = ['novel', '--ksize', '25', '--ctrl-max', '1', '--case-min', '8', '--case', case, '--control', ctrl, '--abund-screen', '3'] args = kevlar.cli.parser().parse_args(arglist) kevlar.novel.main(args) out, err = capsys.readouterr() assert '>seq_error' not in out def test_skip_until(capsys): readname = 'bogus-genome-chr1_115_449_0:0:0_0:0:0_1f4/1' case = data_file('trio1/case1.fq') ctrls = kevlar.tests.data_glob('trio1/ctrl[1,2].fq') arglist = [ 'novel', '--ctrl-max', '0', '--case-min', '6', '--case', case, '--control', ctrls[0], '--control', ctrls[1], '--skip-until', readname ] args = kevlar.cli.parser().parse_args(arglist) kevlar.logstream, logstream = sys.stderr, kevlar.logstream kevlar.novel.main(args) out, err = capsys.readouterr() message = ('Found read bogus-genome-chr1_115_449_0:0:0_0:0:0_1f4/1 ' '(skipped 1001 reads)') assert message in err assert '29 unique novel kmers in 14 reads' in err readname = 'BOGUSREADNAME' arglist = [ 'novel', '--ctrl-max', '0', '--case-min', '6', '--case', case, '--control', ctrls[0], '--control', ctrls[1], '--skip-until', readname ] args = kevlar.cli.parser().parse_args(arglist) kevlar.novel.main(args) kevlar.logstream = logstream out, err = capsys.readouterr() assert 'Found read' not in err assert '(skipped ' not in err assert 'Found 0 instances of 0 unique novel kmers in 0 reads' in err def test_novel_save_counts(): outdir = mkdtemp() try: for ind in ('father', 'mother', 'proband'): outfile = '{:s}/{:s}.ct'.format(outdir, ind) infile = data_file('microtrios/trio-na-{:s}.fq.gz'.format(ind)) arglist = ['count', '--ksize', '27', '--memory', '500K', outfile, infile] args = kevlar.cli.parser().parse_args(arglist) kevlar.count.main(args) arglist = [ 'novel', '--ksize', '27', '--out', outdir + '/novel.augfastq.gz', '--save-case-counts', outdir + '/kid.ct', '--save-ctrl-counts', outdir + '/mom.ct', outdir + '/dad.ct', '--case', data_file('microtrios/trio-na-proband.fq.gz'), '--control', data_file('microtrios/trio-na-mother.fq.gz'), '--control', data_file('microtrios/trio-na-father.fq.gz'), '--memory', '500K' ] args = kevlar.cli.parser().parse_args(arglist) kevlar.novel.main(args) counts = ('father', 'mother', 'proband') testcounts = ('dad', 'mom', 'kid') for c1, c2 in zip(counts, testcounts): f1 = '{:s}/{:s}.ct'.format(outdir, c1) f2 = '{:s}/{:s}.ct'.format(outdir, c2) assert filecmp.cmp(f1, f2) finally: rmtree(outdir) def test_novel_save_counts_mismatch(capsys): outdir = mkdtemp() try: arglist = [ 'novel', '--ksize', '27', '--out', outdir + '/novel.augfastq.gz', '--save-case-counts', outdir + '/kid.ct', '--save-ctrl-counts', outdir + '/mom.ct', outdir + '/dad.ct', outdir + '/sibling.ct', '--case', data_file('microtrios/trio-k-proband.fq.gz'), '--control', data_file('microtrios/trio-k-mother.fq.gz'), '--control', data_file('microtrios/trio-k-father.fq.gz'), '--memory', '500K' ] args = kevlar.cli.parser().parse_args(arglist) kevlar.logstream, logstream = sys.stderr, kevlar.logstream kevlar.novel.main(args) kevlar.logstream = logstream finally: rmtree(outdir) out, err = capsys.readouterr() assert 'stubbornly refusing to save k-mer counts' in err def test_novel_load_counts(capsys): file1 = data_file('simple-genome-case-reads.fa.gz') file2 = data_file('ambig.fasta') file3 = data_file('simple-genome-case.ct') file4, file5 = data_glob('simple-genome-ctrl?.ct') arglist = [ 'novel', '-k', '25', '--case', file1, file2, '--case-counts', file3, '--control-counts', file4, file5 ] args = kevlar.cli.parser().parse_args(arglist) kevlar.logstream, logstream = sys.stderr, kevlar.logstream kevlar.novel.main(args) kevlar.logstream = logstream out, err = capsys.readouterr() assert 'counttables for 2 sample(s) provided' in err
37.180212
79
0.585535
0
0
0
0
1,481
0.140753
0
0
3,102
0.294811
7be972ac4586def48187bfcf50e95c9e16542c4d
361
py
Python
Python Advanced Retake Exam - 16 Dec 2020/Problem 3- Magic triangle - Pascal.py
DiyanKalaydzhiev23/Advanced---Python
ed2c60bb887c49e5a87624719633e2b8432f6f6b
[ "MIT" ]
null
null
null
Python Advanced Retake Exam - 16 Dec 2020/Problem 3- Magic triangle - Pascal.py
DiyanKalaydzhiev23/Advanced---Python
ed2c60bb887c49e5a87624719633e2b8432f6f6b
[ "MIT" ]
null
null
null
Python Advanced Retake Exam - 16 Dec 2020/Problem 3- Magic triangle - Pascal.py
DiyanKalaydzhiev23/Advanced---Python
ed2c60bb887c49e5a87624719633e2b8432f6f6b
[ "MIT" ]
null
null
null
def get_magic_triangle(n): triangle = [[1], [1, 1]] for _ in range(2, n): row = [1] last_row = triangle[-1] for i in range(1, len(last_row)): num = last_row[i-1] + last_row[i] row.append(num) row.append(1) triangle.append(row) return triangle get_magic_triangle(5)
21.235294
46
0.509695
0
0
0
0
0
0
0
0
0
0
7bea7db6a9ed79dea66853c2fd9ed8df8241cc8b
1,353
py
Python
bot.py
egor5q/pvp-combat
42d0f9df14e35c408deb7a360a9f7544ceae7dd7
[ "MIT" ]
null
null
null
bot.py
egor5q/pvp-combat
42d0f9df14e35c408deb7a360a9f7544ceae7dd7
[ "MIT" ]
null
null
null
bot.py
egor5q/pvp-combat
42d0f9df14e35c408deb7a360a9f7544ceae7dd7
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import os import telebot import time import random import threading from emoji import emojize from telebot import types from pymongo import MongoClient import traceback token = os.environ['TELEGRAM_TOKEN'] bot = telebot.TeleBot(token) #client=MongoClient(os.environ['database']) #db=client. #users=db.users def battle(game): if game['started']==False: game['started']=True for ids in game['players']: sendkb(game['players'][ids], game) def sendkb(player, game): if player['die']!=1 and player['stun']<=0: kb=types.ReplyKeyboardMarkup() kb.add(types.KeyboardButton('Атаковать'), types.KeyboardButton('Блокировать')) gamestats=stats(game) bot.send_message(player['id'], gamestats, reply_markup=kb) def createplayer(user): return {user.id:{ 'hp':1000, 'stamina':15, 'stun':0, 'status':'rest', 'action':None } } def medit(message_text,chat_id, message_id,reply_markup=None,parse_mode=None): return bot.edit_message_text(chat_id=chat_id,message_id=message_id,text=message_text,reply_markup=reply_markup, parse_mode=parse_mode) print('7777') bot.polling(none_stop=True,timeout=600)
22.932203
115
0.625277
0
0
0
0
0
0
0
0
250
0.182083
7beab3658ca8052cfa8c2cfea3b8cd3bd3c9a157
262
py
Python
py4mc/__init__.py
capslock321/py4mc
aad43d33f2ab1d264f0b86a84c80823309677994
[ "MIT" ]
null
null
null
py4mc/__init__.py
capslock321/py4mc
aad43d33f2ab1d264f0b86a84c80823309677994
[ "MIT" ]
null
null
null
py4mc/__init__.py
capslock321/py4mc
aad43d33f2ab1d264f0b86a84c80823309677994
[ "MIT" ]
null
null
null
from .api import MojangApi from .dispatcher import Dispatch from .exceptions import ( ApiException, ResourceNotFound, InternalServerException, UserNotFound, ) __version__ = "0.0.1a" __license__ = "MIT" __author__ = "capslock321"
17.466667
33
0.698473
0
0
0
0
0
0
0
0
26
0.099237
7bed1d2243d33ac3902ca09a4b56c1ae1c77465e
553
py
Python
server/players/query.py
kfields/django-arcade
24df3d43dde2d69df333529d8790507fb1f5fcf1
[ "MIT" ]
1
2021-10-03T05:44:32.000Z
2021-10-03T05:44:32.000Z
server/players/query.py
kfields/django-arcade
24df3d43dde2d69df333529d8790507fb1f5fcf1
[ "MIT" ]
null
null
null
server/players/query.py
kfields/django-arcade
24df3d43dde2d69df333529d8790507fb1f5fcf1
[ "MIT" ]
null
null
null
from loguru import logger from channels.db import database_sync_to_async from schema.base import query from .models import Player from .schemata import PlayerConnection @query.field("allPlayers") @database_sync_to_async def resolve_all_players(root, info, after='', before='', first=0, last=0): players = [p for p in Player.objects.all()] connection = PlayerConnection(players) result = connection.wire() return result @query.field("player") @database_sync_to_async def resolve_player(*_, id): return Player.objects.get(id=id)
24.043478
74
0.755877
0
0
0
0
376
0.679928
0
0
24
0.0434
7bee6b98a8502317f53e2986edd1dc16f78c2ac7
50,039
py
Python
simleague/simleague.py
Kuro-Rui/flare-cogs
f739e3a4a8c65bf0e10945d242ba0b82f96c6d3d
[ "MIT" ]
38
2021-03-07T17:13:10.000Z
2022-02-28T19:50:00.000Z
simleague/simleague.py
Kuro-Rui/flare-cogs
f739e3a4a8c65bf0e10945d242ba0b82f96c6d3d
[ "MIT" ]
44
2021-03-12T19:13:32.000Z
2022-03-18T10:20:52.000Z
simleague/simleague.py
Kuro-Rui/flare-cogs
f739e3a4a8c65bf0e10945d242ba0b82f96c6d3d
[ "MIT" ]
33
2021-03-08T18:59:59.000Z
2022-03-23T10:57:46.000Z
import asyncio import logging import random import time from abc import ABC from typing import Literal, Optional import aiohttp import discord from redbot.core import Config, bank, checks, commands from redbot.core.utils.chat_formatting import box from redbot.core.utils.menus import DEFAULT_CONTROLS, menu from tabulate import tabulate from .core import SimHelper from .functions import WEATHER from .simset import SimsetMixin from .stats import StatsMixin from .teamset import TeamsetMixin # THANKS TO https://code.sololearn.com/ci42wd5h0UQX/#py FOR THE SIMULATION AND FIXATOR/AIKATERNA/STEVY FOR THE PILLOW HELP/LEVELER class CompositeMetaClass(type(commands.Cog), type(ABC)): """This allows the metaclass used for proper type detection to coexist with discord.py's metaclass.""" class SimLeague( SimHelper, TeamsetMixin, StatsMixin, SimsetMixin, commands.Cog, metaclass=CompositeMetaClass ): """SimLeague""" __version__ = "3.1.0" def format_help_for_context(self, ctx): """Thanks Sinbad.""" pre_processed = super().format_help_for_context(ctx) return f"{pre_processed}\nCog Version: {self.__version__}" def __init__(self, bot): self.log = logging.getLogger("red.flarecogs.SimLeague") defaults = { "levels": {}, "teams": {}, "fixtures": [], "standings": {}, "stats": { "goals": {}, "yellows": {}, "reds": {}, "penalties": {}, "assists": {}, "motm": {}, "cleansheets": {}, }, "users": [], "resultchannel": [], "gametime": 1, "bettime": 180, "htbreak": 5, "bettoggle": True, "betmax": 10000, "betmin": 10, "mentions": True, "redcardmodifier": 22, "probability": { "goalchance": 96, "yellowchance": 98, "redchance": 398, "penaltychance": 249, "penaltyblock": 0.6, }, "maxplayers": 4, "active": False, "started": False, "betteams": [], "transferwindow": False, "cupmode": False, } defaults_user = {"notify": True} self.config = Config.get_conf(self, identifier=4268355870, force_registration=True) self.config.register_guild(**defaults) self.config.register_user(**defaults_user) self.bot = bot self.bets = {} self.cache = time.time() self.session = aiohttp.ClientSession() async def red_delete_data_for_user( self, *, requester: Literal["discord_deleted_user", "owner", "user", "user_strict"], user_id: int, ): await self.config.user_from_id(user_id).clear() def cog_unload(self): self.bot.loop.create_task(self.session.close()) @commands.command() async def notify(self, ctx, toggle: bool): """Set wheter to recieve notifications of matches and results.""" await self.config.user(ctx.author).notify.set(toggle) if toggle: await ctx.send("You will recieve a notification on matches and results.") else: await ctx.send("You will no longer recieve a notification on matches and results.") @checks.admin_or_permissions(manage_guild=True) @commands.command() async def register( self, ctx, teamname: str, members: commands.Greedy[discord.Member], logo: Optional[str] = None, *, role: discord.Role = None, ): """Register a team. Try keep team names to one word if possible.""" maxplayers = await self.config.guild(ctx.guild).maxplayers() if len(members) != maxplayers: return await ctx.send(f"You must provide {maxplayers} members.") names = {str(x.id): x.name for x in members} memids = await self.config.guild(ctx.guild).users() a = [uid for uid in names if uid in memids] if a: b = [] for ids in a: user = self.bot.get_user(ids) if user is None: user = await self.bot.fetch_user(ids) b.append(user.name) return await ctx.send(", ".join(b) + " is/are on a team.") async with self.config.guild(ctx.guild).teams() as teams: if teamname in teams: return await ctx.send("{} is already a team!".format(teamname)) a = [] teams[teamname] = { "members": names, "captain": {str(members[0].id): members[0].name}, "logo": logo, "role": role.name if role is not None else None, "cachedlevel": 0, "fullname": None, "kits": {"home": None, "away": None, "third": None}, "stadium": None, "bonus": 0, } async with self.config.guild(ctx.guild).standings() as standings: standings[teamname] = { "played": 0, "wins": 0, "losses": 0, "points": 0, "gd": 0, "gf": 0, "ga": 0, "draws": 0, } await self.config.guild(ctx.guild).users.set(memids + list(names.keys())) for uid in list(names.keys()): await self.addrole(ctx, uid, role) await ctx.tick() @commands.command(name="teams") async def _list(self, ctx, updatecache: bool = False, mobilefriendly: bool = True): """List current teams.""" if updatecache: await self.updatecacheall(ctx.guild) teams = await self.config.guild(ctx.guild).teams() if not teams: return await ctx.send("No teams have been registered.") if mobilefriendly: embed = discord.Embed(colour=ctx.author.colour) msg = await ctx.send( "This may take some time depending on the amount of teams currently registered." ) if time.time() - self.cache >= 86400: await msg.edit( content="Updating the level cache, please wait. This may take some time." ) await self.updatecacheall(ctx.guild) self.cache = time.time() async with ctx.typing(): for team in teams: mems = list(teams[team]["members"].values()) lvl = teams[team]["cachedlevel"] embed.add_field( name="Team {}".format(team), value="{}**Members**:\n{}\n**Captain**: {}\n**Team Level**: ~{}{}{}".format( "**Full Name**:\n{}\n".format(teams[team]["fullname"]) if teams[team]["fullname"] is not None else "", "\n".join(mems), list(teams[team]["captain"].values())[0], lvl, "\n**Role**: {}".format( ctx.guild.get_role(teams[team]["role"]).mention ) if teams[team]["role"] is not None else "", "\n**Stadium**: {}".format(teams[team]["stadium"]) if teams[team]["stadium"] is not None else "", ), inline=True, ) await msg.edit(embed=embed, content=None) else: teamlen = max(*[len(str(i)) for i in teams], 5) + 3 rolelen = max(*[len(str(teams[i]["role"])) for i in teams], 5) + 3 caplen = max(*[len(list(teams[i]["captain"].values())[0]) for i in teams], 5) + 3 lvllen = 6 msg = f'{"Team":{teamlen}} {"Level":{lvllen}} {"Captain":{caplen}} {"Role":{rolelen}} Members\n' non = "None" for team in teams: lvl = teams[team]["cachedlevel"] captain = list(teams[team]["captain"].values())[0] role = teams[team]["role"] msg += f'{team} {lvl} {captain} {role.name if role is not None else non}{", ".join(list(teams[team]["members"].values()))} \n' msg = await ctx.send(box(msg, lang="ini")) @commands.command() async def team(self, ctx, *, team: str): """List a team.""" teams = await self.config.guild(ctx.guild).teams() if not teams: return await ctx.send("No teams have been registered.") if team not in teams: return await ctx.send("Team does not exist, ensure that it is correctly capitilized.") async with ctx.typing(): embeds = [] embed = discord.Embed( title="{} {}".format( team, "- {}".format(teams[team]["fullname"]) if teams[team]["fullname"] is not None else "", ), colour=ctx.author.colour, ) embed.add_field( name="Members:", value="\n".join(list(teams[team]["members"].values())), inline=True, ) embed.add_field(name="Captain:", value=list(teams[team]["captain"].values())[0]) embed.add_field(name="Level:", value=teams[team]["cachedlevel"], inline=True) embed.add_field(name="Bonus %:", value=f"{teams[team]['bonus'] * 15}%", inline=True) if teams[team]["role"] is not None: embed.add_field( name="Role:", value=ctx.guild.get_role(teams[team]["role"]).mention, inline=True, ) if teams[team]["stadium"] is not None: embed.add_field(name="Stadium:", value=teams[team]["stadium"], inline=True) if teams[team]["logo"] is not None: embed.set_thumbnail(url=teams[team]["logo"]) embeds.append(embed) for kit in teams[team]["kits"]: if teams[team]["kits"][kit] is not None: embed = discord.Embed(title=f"{kit.title()} Kit", colour=ctx.author.colour) embed.set_image(url=teams[team]["kits"][kit]) embeds.append(embed) await menu(ctx, embeds, DEFAULT_CONTROLS) @commands.command() async def fixtures(self, ctx, week: Optional[int] = None): """Show all fixtures.""" fixtures = await self.config.guild(ctx.guild).fixtures() if not fixtures: return await ctx.send("No fixtures have been made.") if week is None: embed = discord.Embed(color=0xFF0000) for i, fixture in enumerate(fixtures[:25]): a = [f"{game[0]} vs {game[1]}" for game in fixture] embed.add_field(name="Week {}".format(i + 1), value="\n".join(a)) await ctx.send(embed=embed) if len(fixtures) > 25: embed = discord.Embed(color=0xFF0000) for i, fixture in enumerate(fixtures[25:], 25): a = [f"{game[0]} vs {game[1]}" for game in fixture] embed.add_field(name="Week {}".format(i + 1), value="\n".join(a)) await ctx.send(embed=embed) else: if week == 0: return await ctx.send("Try starting with week 1.") try: games = fixtures games.reverse() games.append("None") games.reverse() games = games[week] except IndexError: return await ctx.send("Invalid gameweek.") a = [f"{fixture[0]} vs {fixture[1]}" for fixture in games] await ctx.maybe_send_embed("\n".join(a)) @commands.command() async def standings(self, ctx, verbose: bool = False): """Current sim standings.""" if await self.config.guild(ctx.guild).cupmode(): return await ctx.send( "This simulation league is in cup mode, contact the maintainer of the league for the current standings." ) standings = await self.config.guild(ctx.guild).standings() if standings is None: return await ctx.send("The table is empty.") t = [] # PrettyTable(["Team", "W", "L", "D", "PL", "PO"]) if not verbose: for x in sorted( standings, key=lambda x: (standings[x]["points"], standings[x]["gd"], standings[x]["gf"]), reverse=True, ): t.append( [ x, standings[x]["wins"], standings[x]["losses"], standings[x]["draws"], standings[x]["played"], standings[x]["points"], ] ) tab = tabulate(t, headers=["Team", "Wins", "Losses", "Draws", "Played", "Points"]) else: for x in sorted( standings, key=lambda x: (standings[x]["points"], standings[x]["gd"], standings[x]["gf"]), reverse=True, ): t.append( [ x, standings[x]["wins"], standings[x]["losses"], standings[x]["draws"], standings[x]["played"], standings[x]["points"], standings[x]["gd"], standings[x]["gf"], standings[x]["ga"], ] ) tab = tabulate( t, headers=["Team", "Wins", "Losses", "Draws", "Played", "Points", "GD", "GF", "GA"], ) await ctx.send(box(tab)) @checks.admin_or_permissions(manage_guild=True) @commands.cooldown(rate=1, per=30, type=commands.BucketType.guild) @commands.max_concurrency(1, per=commands.BucketType.guild) @commands.command(aliases=["playsim", "simulate"]) async def sim(self, ctx, team1: str, team2: str): """Simulate a game between two teams.""" teams = await self.config.guild(ctx.guild).teams() if team1 not in teams or team2 not in teams: return await ctx.send("One of those teams do not exist.") if team1 == team2: return await ctx.send("You can't sim two of the same teams silly.") msg = await ctx.send("Updating cached levels...") await self.updatecachegame(ctx.guild, team1, team2) await msg.delete() await asyncio.sleep(2) teams = await self.config.guild(ctx.guild).teams() lvl1 = teams[team1]["cachedlevel"] lvl2 = teams[team2]["cachedlevel"] bonuslvl1 = teams[team1]["bonus"] bonuslvl2 = teams[team2]["bonus"] homewin = lvl2 / lvl1 awaywin = lvl1 / lvl2 try: draw = homewin / awaywin except ZeroDivisionError: draw = 0.5 await self.config.guild(ctx.guild).active.set(True) await self.config.guild(ctx.guild).betteams.set([team1, team2]) goals = {} assists = {} reds = {team1: 0, team2: 0} bettime = await self.config.guild(ctx.guild).bettime() stadium = teams[team1]["stadium"] if teams[team1]["stadium"] is not None else None weather = random.choice(WEATHER) im = await self.matchinfo(ctx, [team1, team2], weather, stadium, homewin, awaywin, draw) await ctx.send(file=im) await self.matchnotif(ctx, team1, team2) bet = await ctx.send( "Betting is now open, game will commence in {} seconds.\nUsage: {}bet <amount> <team>".format( bettime, ctx.prefix ) ) for i in range(1, bettime): if i % 5 == 0: await bet.edit( content="Betting is now open, game will commence in {} seconds.\nUsage: {}bet <amount> <team>".format( bettime - i, ctx.prefix ) ) await asyncio.sleep(1) await bet.delete() probability = await self.config.guild(ctx.guild).probability() await self.config.guild(ctx.guild).started.set(True) redcardmodifier = await self.config.guild(ctx.guild).redcardmodifier() team1players = list(teams[team1]["members"].keys()) team2players = list(teams[team2]["members"].keys()) logos = ["sky", "bt", "bein", "bbc"] yellowcards = [] logo = random.choice(logos) motm = {} events = False # Team 1 stuff yC_team1 = [] rC_team1 = [] injury_team1 = [] sub_in_team1 = [] sub_out_team1 = [] sub_count1 = 0 rc_count1 = 0 score_count1 = 0 injury_count1 = 0 team1Stats = [ team1, yC_team1, rC_team1, injury_team1, sub_in_team1, sub_out_team1, sub_count1, rc_count1, score_count1, injury_count1, ] # Team 2 stuff yC_team2 = [] rC_team2 = [] injury_team2 = [] sub_in_team2 = [] sub_out_team2 = [] sub_count2 = 0 rc_count2 = 0 score_count2 = 0 injury_count2 = 0 team2Stats = [ team2, yC_team2, rC_team2, injury_team2, sub_in_team2, sub_out_team2, sub_count2, rc_count2, score_count2, injury_count2, ] async def TeamWeightChance( ctx, t1totalxp, t2totalxp, reds1: int, reds2: int, team1bonus: int, team2bonus: int ): if t1totalxp < 2: t1totalxp = 1 if t2totalxp < 2: t2totalxp = 1 team1bonus *= 15 team2bonus *= 15 t1totalxp = t1totalxp * float(f"1.{team1bonus}") t2totalxp = t2totalxp * float(f"1.{team2bonus}") self.log.debug(f"Team 1: {t1totalxp} - Team 2: {t2totalxp}") redst1 = float(f"0.{reds1 * redcardmodifier}") redst2 = float(f"0.{reds2 * redcardmodifier}") total = ["A"] * int(((1 - redst1) * 100) * t1totalxp) + ["B"] * int( ((1 - redst2) * 100) * t2totalxp ) rdmint = random.choice(total) if rdmint == "A": return team1Stats else: return team2Stats async def TeamChance(): rndint = random.randint(1, 10) if rndint >= 5: return team1Stats else: return team2Stats async def PlayerGenerator(event, team, yc, rc): random.shuffle(team1players) random.shuffle(team2players) output = [] if team == team1: fs_players = team1players yc = yC_team1 rc = rC_team1 elif team == team2: fs_players = team2players yc = yC_team2 rc = rC_team2 if event == 0: rosterUpdate = [i for i in fs_players if i not in rc] if not rosterUpdate: return await ctx.send( "Game abandoned, no score recorded due to no players remaining." ) isassist = False assist = random.randint(0, 100) if assist > 20: isassist = True if len(rosterUpdate) < 3: isassist = False player = random.choice(rosterUpdate) if not isassist: return [team, player] rosterUpdate.remove(player) assister = random.choice(rosterUpdate) return [team, player, assister] elif event == 1: rosterUpdate = [i for i in fs_players if i not in rc] if len(rosterUpdate) == 1: return None player = random.choice(rosterUpdate) if player in yc or player in yellowcards: return [team, player, 2] else: return [team, player] elif event in [2, 3]: rosterUpdate = [i for i in fs_players if i not in rc] if len(rosterUpdate) == 1 and event == 2: return None player_out = random.choice(rosterUpdate) output = [team, player_out] return output # Start of Simulation! im = await self.walkout(ctx, team1, "home") im2 = await self.walkout(ctx, team2, "away") await ctx.send("Teams:", file=im) await ctx.send(file=im2) timemsg = await ctx.send("Kickoff!") gametime = await self.config.guild(ctx.guild).gametime() for min in range(1, 91): await asyncio.sleep(gametime) if min % 5 == 0: await timemsg.edit(content="Minute: {}".format(min)) if events is False: gC = await self.goalChance(ctx.guild, probability) if gC is True: teamStats = await TeamWeightChance( ctx, lvl1, lvl2, reds[team1], reds[team2], bonuslvl1, bonuslvl2 ) playerGoal = await PlayerGenerator(0, teamStats[0], teamStats[1], teamStats[2]) teamStats[8] += 1 async with self.config.guild(ctx.guild).stats() as stats: if playerGoal[1] not in stats["goals"]: stats["goals"][playerGoal[1]] = 1 else: stats["goals"][playerGoal[1]] += 1 if len(playerGoal) == 3: if playerGoal[2] not in stats["assists"]: stats["assists"][playerGoal[2]] = 1 else: stats["assists"][playerGoal[2]] += 1 events = True if len(playerGoal) == 3: user2 = self.bot.get_user(int(playerGoal[2])) if user2 is None: user2 = await self.bot.fetch_user(int(playerGoal[2])) if user2 not in motm: motm[user2] = 1 else: motm[user2] += 1 if user2.id not in assists: assists[user2.id] = 1 else: assists[user2.id] += 1 user = self.bot.get_user(int(playerGoal[1])) if user is None: user = await self.bot.fetch_user(int(playerGoal[1])) if user not in motm: motm[user] = 2 else: motm[user] += 2 if user.id not in goals: goals[user.id] = 1 else: goals[user.id] += 1 if len(playerGoal) == 3: image = await self.simpic( ctx, str(min), "goal", user, team1, team2, str(playerGoal[0]), str(team1Stats[8]), str(team2Stats[8]), user2, ) else: image = await self.simpic( ctx, str(min), "goal", user, team1, team2, str(playerGoal[0]), str(team1Stats[8]), str(team2Stats[8]), ) await ctx.send(file=image) if events is False: pC = await self.penaltyChance(ctx.guild, probability) if pC is True: teamStats = await TeamWeightChance( ctx, lvl1, lvl2, reds[team1], reds[team2], bonuslvl1, bonuslvl2 ) playerPenalty = await PlayerGenerator( 3, teamStats[0], teamStats[1], teamStats[2] ) user = self.bot.get_user(int(playerPenalty[1])) if user is None: user = await self.bot.fetch_user(int(playerPenalty[1])) image = await self.penaltyimg(ctx, str(playerPenalty[0]), str(min), user) await ctx.send(file=image) pB = await self.penaltyBlock(ctx.guild, probability) if pB is True: events = True async with self.config.guild(ctx.guild).stats() as stats: if playerPenalty[1] not in stats["penalties"]: stats["penalties"][playerPenalty[1]] = {"scored": 0, "missed": 1} else: stats["penalties"][playerPenalty[1]]["missed"] += 1 user = self.bot.get_user(int(playerPenalty[1])) if user is None: user = await self.bot.fetch_user(int(playerPenalty[1])) image = await self.simpic( ctx, str(min), "penmiss", user, team1, team2, str(playerPenalty[0]), str(team1Stats[8]), str(team2Stats[8]), ) await ctx.send(file=image) else: teamStats[8] += 1 async with self.config.guild(ctx.guild).stats() as stats: if playerPenalty[1] not in stats["goals"]: stats["goals"][playerPenalty[1]] = 1 else: stats["goals"][playerPenalty[1]] += 1 if playerPenalty[1] not in stats["penalties"]: stats["penalties"][playerPenalty[1]] = {"scored": 1, "missed": 0} else: stats["penalties"][playerPenalty[1]]["scored"] += 1 events = True user = self.bot.get_user(int(playerPenalty[1])) if user is None: user = await self.bot.fetch_user(int(playerPenalty[1])) if user not in motm: motm[user] = 2 else: motm[user] += 2 if user.id not in goals: goals[user.id] = 1 else: goals[user.id] += 1 image = await self.simpic( ctx, str(min), "penscore", user, team1, team2, str(playerPenalty[0]), str(team1Stats[8]), str(team2Stats[8]), ) await ctx.send(file=image) if events is False: yC = await self.yCardChance(ctx.guild, probability) if yC is True: teamStats = await TeamChance() playerYellow = await PlayerGenerator( 1, teamStats[0], teamStats[1], teamStats[2] ) if playerYellow is not None: if len(playerYellow) == 3: teamStats[7] += 1 teamStats[2].append(playerYellow[1]) async with self.config.guild(ctx.guild).stats() as stats: reds[str(playerYellow[0])] += 1 if playerYellow[1] not in stats["reds"]: stats["reds"][playerYellow[1]] = 1 stats["yellows"][playerYellow[1]] += 1 else: stats["yellows"][playerYellow[1]] += 1 stats["reds"][playerYellow[1]] += 1 events = True user = self.bot.get_user(int(playerYellow[1])) if user is None: user = await self.bot.fetch_user(int(playerYellow[1])) if user not in motm: motm[user] = -2 else: motm[user] += -2 image = await self.simpic( ctx, str(min), "2yellow", user, team1, team2, str(playerYellow[0]), str(team1Stats[8]), str(team2Stats[8]), None, str( len(teams[str(str(playerYellow[0]))]["members"]) - (int(teamStats[7])) ), ) await ctx.send(file=image) else: teamStats[1].append(playerYellow[1]) yellowcards.append(str(playerYellow[1])) async with self.config.guild(ctx.guild).stats() as stats: if playerYellow[1] not in stats["yellows"]: stats["yellows"][playerYellow[1]] = 1 else: stats["yellows"][playerYellow[1]] += 1 events = True user = self.bot.get_user(int(playerYellow[1])) if user is None: user = await self.bot.fetch_user(int(playerYellow[1])) if user not in motm: motm[user] = -1 else: motm[user] += -1 image = await self.simpic( ctx, str(min), "yellow", user, team1, team2, str(playerYellow[0]), str(team1Stats[8]), str(team2Stats[8]), ) await ctx.send(file=image) if events is False: rC = await self.rCardChance(ctx.guild, probability) if rC is True: teamStats = await TeamChance() playerRed = await PlayerGenerator(2, teamStats[0], teamStats[1], teamStats[2]) if playerRed is not None: teamStats[7] += 1 async with self.config.guild(ctx.guild).stats() as stats: if playerRed[1] not in stats["reds"]: stats["reds"][playerRed[1]] = 1 else: stats["reds"][playerRed[1]] += 1 reds[str(playerRed[0])] += 1 teamStats[2].append(playerRed[1]) events = True user = self.bot.get_user(int(playerRed[1])) if user is None: user = await self.bot.fetch_user(int(playerRed[1])) if user not in motm: motm[user] = -2 else: motm[user] += -2 image = await self.simpic( ctx, str(min), "red", user, team1, team2, str(playerRed[0]), str(team1Stats[8]), str(team2Stats[8]), None, str( len(teams[str(str(playerRed[0]))]["members"]) - (int(teamStats[7])) ), ) await ctx.send(file=image) if events is False: pass events = False if min == 45: added = random.randint(1, 5) im = await self.extratime(ctx, added) await ctx.send(file=im) s = 45 for i in range(added): s += 1 gC = await self.goalChance(ctx.guild, probability) if gC is True: teamStats = await TeamWeightChance( ctx, lvl1, lvl2, reds[team1], reds[team2], bonuslvl1, bonuslvl2 ) playerGoal = await PlayerGenerator( 0, teamStats[0], teamStats[1], teamStats[2] ) teamStats[8] += 1 async with self.config.guild(ctx.guild).stats() as stats: if playerGoal[1] not in stats["goals"]: stats["goals"][playerGoal[1]] = 1 else: stats["goals"][playerGoal[1]] += 1 if len(playerGoal) == 3: if playerGoal[2] not in stats["assists"]: stats["assists"][playerGoal[2]] = 1 else: stats["assists"][playerGoal[2]] += 1 if len(playerGoal) == 3: user2 = self.bot.get_user(int(playerGoal[2])) if user2 is None: user2 = await self.bot.fetch_user(int(playerGoal[2])) if user2 not in motm: motm[user2] = 1 else: motm[user2] += 1 if user2.id not in assists: assists[user2.id] = 1 else: assists[user2.id] += 1 events = True user = self.bot.get_user(int(playerGoal[1])) if user is None: user = await self.bot.fetch_user(int(playerGoal[1])) if user not in motm: motm[user] = 2 else: motm[user] += 2 if user.id not in goals: goals[user.id] = 1 else: goals[user.id] += 1 if len(playerGoal) == 3: image = await self.simpic( ctx, str(min) + "+" + str(i + 1), "goal", user, team1, team2, str(playerGoal[0]), str(team1Stats[8]), str(team2Stats[8]), user2, ) else: image = await self.simpic( ctx, str(min) + "+" + str(i + 1), "goal", user, team1, team2, str(playerGoal[0]), str(team1Stats[8]), str(team2Stats[8]), ) await ctx.send(file=image) await asyncio.sleep(gametime) events = False ht = await self.config.guild(ctx.guild).htbreak() im = await self.timepic( ctx, team1, team2, str(team1Stats[8]), str(team2Stats[8]), "HT", logo ) await ctx.send(file=im) await asyncio.sleep(ht) await timemsg.delete() timemsg = await ctx.send("Second Half!") if min == 90: added = random.randint(1, 5) im = await self.extratime(ctx, added) await ctx.send(file=im) s = 90 for i in range(added): s += 1 gC = await self.goalChance(ctx.guild, probability) if gC is True: teamStats = await TeamWeightChance( ctx, lvl1, lvl2, reds[team1], reds[team2], bonuslvl1, bonuslvl2 ) playerGoal = await PlayerGenerator( 0, teamStats[0], teamStats[1], teamStats[2] ) teamStats[8] += 1 async with self.config.guild(ctx.guild).stats() as stats: if playerGoal[1] not in stats["goals"]: stats["goals"][playerGoal[1]] = 1 else: stats["goals"][playerGoal[1]] += 1 if len(playerGoal) == 3: if playerGoal[2] not in stats["assists"]: stats["assists"][playerGoal[2]] = 1 else: stats["assists"][playerGoal[2]] += 1 if len(playerGoal) == 3: user2 = self.bot.get_user(int(playerGoal[2])) if user2 is None: user2 = await self.bot.fetch_user(int(playerGoal[2])) if user2 not in motm: motm[user2] = 1 else: motm[user2] += 1 if user2.id not in assists: assists[user2.id] = 1 else: assists[user2.id] += 1 events = True user = self.bot.get_user(int(playerGoal[1])) if user is None: user = await self.bot.fetch_user(int(playerGoal[1])) if user not in motm: motm[user] = 2 else: motm[user] += 2 if user.id not in goals: goals[user.id] = 1 else: goals[user.id] += 1 if len(playerGoal) == 3: image = await self.simpic( ctx, str(min) + "+" + str(i + 1), "goal", user, team1, team2, str(playerGoal[0]), str(team1Stats[8]), str(team2Stats[8]), user2, ) else: image = await self.simpic( ctx, str(min) + "+" + str(i + 1), "goal", user, team1, team2, str(playerGoal[0]), str(team1Stats[8]), str(team2Stats[8]), ) await ctx.send(file=image) await asyncio.sleep(gametime) events = False im = await self.timepic( ctx, team1, team2, str(team1Stats[8]), str(team2Stats[8]), "FT", logo ) await timemsg.delete() await ctx.send(file=im) if team1Stats[8] > team2Stats[8]: async with self.config.guild(ctx.guild).standings() as standings: standings[team1]["wins"] += 1 standings[team1]["points"] += 3 standings[team1]["played"] += 1 standings[team2]["losses"] += 1 standings[team2]["played"] += 1 t = await self.payout(ctx.guild, team1, homewin) if team1Stats[8] < team2Stats[8]: async with self.config.guild(ctx.guild).standings() as standings: standings[team2]["points"] += 3 standings[team2]["wins"] += 1 standings[team2]["played"] += 1 standings[team1]["losses"] += 1 standings[team1]["played"] += 1 t = await self.payout(ctx.guild, team2, awaywin) if team1Stats[8] == team2Stats[8]: async with self.config.guild(ctx.guild).standings() as standings: standings[team1]["played"] += 1 standings[team2]["played"] += 1 standings[team1]["points"] += 1 standings[team2]["points"] += 1 standings[team2]["draws"] += 1 standings[team1]["draws"] += 1 t = await self.payout(ctx.guild, "draw", draw) await self.cleansheets(ctx, team1, team2, team1Stats[8], team2Stats[8]) team1gd = team1Stats[8] - team2Stats[8] team2gd = team2Stats[8] - team1Stats[8] async with self.config.guild(ctx.guild).standings() as standings: if team1gd != 0: standings[team1]["gd"] += team1gd if team2gd != 0: standings[team2]["gd"] += team2gd if team2Stats[8] != 0: standings[team2]["gf"] += team2Stats[8] standings[team1]["ga"] += team2Stats[8] if team1Stats[8] != 0: standings[team1]["gf"] += team1Stats[8] standings[team2]["ga"] += team1Stats[8] await self.postresults(ctx, team1, team2, team1Stats[8], team2Stats[8]) await self.config.guild(ctx.guild).active.set(False) await self.config.guild(ctx.guild).started.set(False) await self.config.guild(ctx.guild).betteams.set([]) if ctx.guild.id in self.bets: self.bets[ctx.guild.id] = {} if motm: motmwinner = sorted(motm, key=motm.get, reverse=True)[0] if motmwinner.id in goals: motmgoals = goals[motmwinner.id] else: motmgoals = 0 if motmwinner.id in assists: motmassists = assists[motmwinner.id] else: motmassists = 0 try: await bank.deposit_credits( self.bot.get_user(motmwinner.id), (75 * motmgoals) + (30 * motmassists) ) except AttributeError: pass im = await self.motmpic( ctx, motmwinner, team1 if str(motmwinner.id) in teams[team1]["members"].keys() else team2, motmgoals, motmassists, ) async with self.config.guild(ctx.guild).stats() as stats: if str(motmwinner.id) not in stats["motm"]: stats["motm"][str(motmwinner.id)] = 1 else: stats["motm"][str(motmwinner.id)] += 1 await ctx.send(file=im) if t is not None: await ctx.send("Bet Winners:\n" + t) async def bet_conditions(self, ctx, bet, team): bettoggle = await self.config.guild(ctx.guild).bettoggle() active = await self.config.guild(ctx.guild).active() started = await self.config.guild(ctx.guild).started() if not bettoggle: return await ctx.send("Betting is currently disabled.") if not active: await ctx.send("There isn't a game onright now.") return False elif started: try: await ctx.author.send("You can't place a bet after the game has started.") except discord.HTTPException: await ctx.send( "Maybe you should unblock me or turn off privacy settings if you want to bet ¯\\_(ツ)_/¯. {}".format( ctx.author.mention ) ) return False if ctx.guild.id not in self.bets: self.bets[ctx.guild.id] = {} elif ctx.author.id in self.bets[ctx.guild.id]: await ctx.send("You have already entered a bet for the game.") return False teams = await self.config.guild(ctx.guild).teams() if team not in teams and team != "draw": await ctx.send("That team isn't currently playing.") return False minbet = await self.config.guild(ctx.guild).betmin() if bet < minbet: await ctx.send("The minimum bet is {}".format(minbet)) return False maxbet = await self.config.guild(ctx.guild).betmax() if bet > maxbet: await ctx.send("The maximum bet is {}".format(maxbet)) return False if await bank.can_spend(ctx.author, bet): return True await ctx.send("You do not have enough money to cover the bet.") return False @commands.command(name="bet") async def _bet(self, ctx, bet: int, *, team: str): """Bet on a team or a draw.""" if await self.bet_conditions(ctx, bet, team): self.bets[ctx.guild.id][ctx.author] = {"Bets": [(team, bet)]} currency = await bank.get_currency_name(ctx.guild) await bank.withdraw_credits(ctx.author, bet) await ctx.send(f"{ctx.author.mention} placed a {bet} {currency} bet on {team}.") async def payout(self, guild, winner, odds): if winner is None: return None bet_winners = [] if guild.id not in self.bets: return None for better in self.bets[guild.id]: for team, bet in self.bets[guild.id][better]["Bets"]: if team == winner: bet_winners.append(f"{better.mention} - Winnings: {int(bet + (bet * odds))}") await bank.deposit_credits(better, int(bet + (bet * odds))) return "\n".join(bet_winners) if bet_winners else None async def cleansheets(self, ctx, team1, team2, team1score, team2score): if team1score == 0 and team2score > 0: async with self.config.guild(ctx.guild).stats() as stats: if team2 in stats["cleansheets"]: stats["cleansheets"][team2] += 1 else: stats["cleansheets"][team2] = 1 elif team2score == 0 and team1score > 0: async with self.config.guild(ctx.guild).stats() as stats: if team2 in stats["cleansheets"]: stats["cleansheets"][team1] += 1 else: stats["cleansheets"][team1] = 1
43.85539
142
0.428846
49,411
0.987371
0
0
43,885
0.876946
46,701
0.933217
4,994
0.099794
7befce5f0d88c105c0447661c3338248d03f3ae9
2,118
py
Python
7_neural_networks/4_DeepLearning2.py
edrmonteiro/DataSciencePython
0a35fb085bc0b98b33e083d0e1b113a04caa3aac
[ "MIT" ]
null
null
null
7_neural_networks/4_DeepLearning2.py
edrmonteiro/DataSciencePython
0a35fb085bc0b98b33e083d0e1b113a04caa3aac
[ "MIT" ]
null
null
null
7_neural_networks/4_DeepLearning2.py
edrmonteiro/DataSciencePython
0a35fb085bc0b98b33e083d0e1b113a04caa3aac
[ "MIT" ]
null
null
null
""" Deep Learning """ import pandas as pd from keras.models import Sequential from keras.layers import Dense from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.preprocessing import StandardScaler from sklearn.compose import make_column_transformer import os path = os.path.abspath(os.getcwd()) + r"/0_dataset/" dataset = pd.read_csv(path + "Credit2.csv", sep=";") dataset #separação dos variáveis, ignoro primeira pois não tem valor semântico X = dataset.iloc[:,1:10].values y = dataset.iloc[:, 10].values #temos um arry e não mais um data frame X #label encoder coluna checking_status #atribui valores de zero a 3 labelencoder = LabelEncoder() X[:,0] = labelencoder.fit_transform(X[:,0]) X #one hot encoder coluna credit_history #deve adicionar 5 colunas onehotencoder = make_column_transformer((OneHotEncoder(categories='auto', sparse=False), [1]), remainder="passthrough") X = onehotencoder.fit_transform(X) X #Excluimos a variável para evitar a dummy variable trap X = X:,1: X #Laber encoder com a classe labelencoder_Y = LabelEncoder() y = labelencoder_Y.fit_transform(y) y #separação em treino e teste X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) print(len(X_train),len(X_test),len(y_train),len(y_test)) #Feature Scalling, Padronização z-score sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) X_test classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 12)) classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) classifier.fit(X_train, y_train, batch_size = 10, epochs = 100) y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5) y_pred #matriz de confusão cm = confusion_matrix(y_test, y_pred) cm
29.830986
119
0.767705
0
0
0
0
0
0
0
0
584
0.274178
7bf26d67b6d552692974b4958df2a46110802ae6
1,529
py
Python
src/python_settings/python_settings.py
tomatze/opendihu-webapp
0f08bdeb82348a1e30fa44db1ac3b9b1606f1da1
[ "MIT" ]
17
2018-11-25T19:29:34.000Z
2021-09-20T04:46:22.000Z
src/python_settings/python_settings.py
tomatze/opendihu-webapp
0f08bdeb82348a1e30fa44db1ac3b9b1606f1da1
[ "MIT" ]
1
2020-11-12T15:15:58.000Z
2020-12-29T15:29:24.000Z
src/python_settings/python_settings.py
tomatze/opendihu-webapp
0f08bdeb82348a1e30fa44db1ac3b9b1606f1da1
[ "MIT" ]
4
2018-10-17T12:18:10.000Z
2021-05-28T13:24:20.000Z
import re # import all settings-modules here, so we can only import this module to get them all from python_settings.settings_activatable import * from python_settings.settings_child_placeholder import * from python_settings.settings_choice import * from python_settings.settings_comment import * from python_settings.settings_conditional import * from python_settings.settings_container import * from python_settings.settings_dict_entry import * from python_settings.settings_empty_line import * from python_settings.settings_list_entry import * # this holds a complete settings.py by parsing its config-dict and storing the rest of the file in prefix and postfix class PythonSettings(): prefix = '' config_dict = None postfix = '' # takes a string of a settings.py and parses it def __init__(self, settings=None): if settings: # isolate content of config{} to settings and save the rest of the file settings_prefix and settings_postfix split1 = settings.split('config = {') self.prefix = split1[0][:-1] settings = split1[1] split2 = re.compile(r'(?m)^}').split(settings, 1) settings = split2[0] settings = '{' + settings + '}' self.postfix = split2[1][1:] # iterate over tokens to create SettingsDict self.config_dict = SettingsDict(settings) return None def __repr__(self): return self.prefix + '\nconfig = ' + str(self.config_dict) + self.postfix
39.205128
120
0.695226
860
0.562459
0
0
0
0
0
0
445
0.29104
7bf3d0583faad7a302993fc30d577771cb1e654a
460
py
Python
titan/abstracts/decorator.py
DeSireFire/titans
9194950694084a7cbc6434dfec0ecb2e755f0cdf
[ "Apache-2.0" ]
17
2020-03-14T01:08:07.000Z
2020-12-26T08:20:14.000Z
titan/abstracts/decorator.py
DeSireFire/titans
9194950694084a7cbc6434dfec0ecb2e755f0cdf
[ "Apache-2.0" ]
4
2020-12-05T08:50:55.000Z
2022-02-27T06:48:21.000Z
titan/abstracts/decorator.py
DeSireFire/titans
9194950694084a7cbc6434dfec0ecb2e755f0cdf
[ "Apache-2.0" ]
1
2020-05-24T06:57:03.000Z
2020-05-24T06:57:03.000Z
# -*- coding: utf-8 -*- import timeit from functools import wraps from titan.manages.global_manager import GlobalManager def run_time_sum(func): @wraps(func) def wrapper(*args, **kwargs): start = timeit.default_timer() __func = func(*args, **kwargs) end = timeit.default_timer() if GlobalManager().debug: print('run time: {} s'.format(str(round(end - start, 4)))) return __func return wrapper
25.555556
70
0.630435
0
0
0
0
288
0.626087
0
0
39
0.084783
7bf5036dc7b11f3015385fa7ebed58f2c40e9c71
262
py
Python
src/cs2mako/patterns.py
eventbrite/cs2mako
163affcc764a574b4af543c3520b7f345992973a
[ "MIT" ]
null
null
null
src/cs2mako/patterns.py
eventbrite/cs2mako
163affcc764a574b4af543c3520b7f345992973a
[ "MIT" ]
null
null
null
src/cs2mako/patterns.py
eventbrite/cs2mako
163affcc764a574b4af543c3520b7f345992973a
[ "MIT" ]
2
2015-04-03T05:35:36.000Z
2021-09-08T11:48:27.000Z
# Copyright (c) 2014 Eventbrite, Inc. All rights reserved. # See "LICENSE" file for license. import re open_r_str = r'\<\?cs\s*([a-zA-Z]+)([:]|\s)' close_r_str = r'\<\?cs\s*/([a-zA-Z]+)\s*\?\>' open_r = re.compile(open_r_str) close_r = re.compile(close_r_str)
26.2
58
0.637405
0
0
0
0
0
0
0
0
153
0.583969
7bf5401a73cd65b2b3dab4a303b9fc867d22f877
3,142
py
Python
presta_connect.py
subteno-it/presta_connect
7cc8f2f915b28ada40a03573651a3558e6503004
[ "MIT" ]
null
null
null
presta_connect.py
subteno-it/presta_connect
7cc8f2f915b28ada40a03573651a3558e6503004
[ "MIT" ]
null
null
null
presta_connect.py
subteno-it/presta_connect
7cc8f2f915b28ada40a03573651a3558e6503004
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2019 Subteno IT # License MIT License import requests import xmltodict import string import random import io class PrestaConnectError(RuntimeError): pass class PrestaConnect: _BOUNDARY_CHARS = string.digits + string.ascii_letters _STATUSES = (200, 201) def __init__(self, api, key): self.api = api self.key = key def _get_url(self, path): return self.api + '/' + path def _check_response(self, res, ret): if res.status_code not in self._STATUSES: raise PrestaConnectError('Status %s, %s' % (res.status_code, ret)) return ret def _encode_multipart_formdata(self, files): """Encode files to an http multipart/form-data. :param files: a sequence of (type, filename, value) elements for data to be uploaded as files. :return: headers and body. """ BOUNDARY = (''.join(random.choice(self._BOUNDARY_CHARS) for i in range(30))) CRLF = b'\r\n' L = [] for (key, filename, value) in files: L.append(bytes(('--' + BOUNDARY).encode('utf8'))) L.append( bytes(('Content-Disposition: form-data; \ name="%s"; filename="%s"' % (key, filename)).encode('utf8'))) L.append(bytes(('Content-Type: %s' % self._get_content_type(filename)).encode('utf8'))) L.append(b'') L.append(value) L.append(bytes(('--' + BOUNDARY + '--').encode('utf8'))) L.append(b'') body = CRLF.join(L) headers = { 'Content-Type': 'multipart/form-data; boundary=%s' % BOUNDARY } return headers, body def add(self, path, data): return self._request('POST', path, data=data) def _load_image(self, file_name): """loads image to upload""" fd = io.open(file_name, "rb") content = fd.read() fd.close() return content, file_name def _request(self, method, path, params=None, data=None, files=None): if data is not None: data = xmltodict.unparse({'prestashop': data}).encode('utf-8') res = requests.request(method, self._get_url(path), auth=(self._api_token(), ''), params=params, data=data, files=files) return self._check_response(res, xmltodict.parse(res.text)['prestashop'] if not files and res.text else None) def add_image(self, path, file_name, exists=False): content, file_name = self._load_image(file_name) files = [('image', file_name, content)] headers, data = self._encode_multipart_formdata(files) return self._request('POST', 'images/' + path, params={'ps_method': 'PUT'} if exists else None, data=data, headers=headers) def get(self, path, params=None): return self._request('GET', path, params) def edit(self, path, data): return self._request('PUT', path, data=data) def delete(self, path): return self._request('DELETE', path)
34.911111
131
0.579885
2,991
0.951941
0
0
0
0
0
0
621
0.197645
7bf8224c1d14572f51a3d9141d24b9fbd1be25c1
2,884
py
Python
blender/SCAFFOLDER_settings.py
nodtem66/Scaffolder
c2b89e981192f61b028e1e8780a01894b1e34494
[ "MIT" ]
8
2019-12-24T17:28:03.000Z
2022-03-23T02:49:28.000Z
blender/SCAFFOLDER_settings.py
nodtem66/Scaffolder
c2b89e981192f61b028e1e8780a01894b1e34494
[ "MIT" ]
9
2019-12-27T18:10:05.000Z
2021-08-04T15:18:47.000Z
blender/SCAFFOLDER_settings.py
nodtem66/Scaffolder
c2b89e981192f61b028e1e8780a01894b1e34494
[ "MIT" ]
null
null
null
import bpy from bpy.types import Panel from bpy.props import * import math default_surface_names = [ ("bcc", "bcc", "", 1), ("schwarzp", "schwarzp", "", 2), ("schwarzd", "schwarzd", "", 3), ("gyroid", "gyroid", "", 4), ("double-p", "double-p", "", 5), ("double-d", "double-d", "", 6), ("double-gyroid", "double-gyroid", "", 7), ("lidinoid", "lidinoid", "", 8), ("schoen_iwp", "schoen_iwp", "", 9), ("neovius", "neovius", "", 10), ("tubular_g_ab", "tubular_g_ab", "", 11), ("tubular_g_c", "tubular_g_c", "", 12) ] default_direction = [ ("X", "X", "", 0), ("Y", "Y", "", 1), ("Z", "Z", "", 2), ("All", "All", "", 3) ] class SCAFFOLDER_settings(bpy.types.PropertyGroup): def set_coff(self, context): if self.target1 is not None: if self.target1.dimensions is not None: L = min(self.target1.dimensions) N = self.unit_cell self.coff = 2*math.pi*N/L target1: PointerProperty(name="target MESH", type=bpy.types.Object, update=set_coff) target2: PointerProperty(name="target MESH", type=bpy.types.Object) is_intersect: BoolProperty(name="Intersection", default=True) is_build_inverse: BoolProperty(name="Build inverse", default=False) grid_size: IntProperty(name="Grid size", default=100, min=10) grid_offset: IntProperty(name="Grid offset", default=3, min=0) smooth_step: IntProperty(name="smooth step", default=0, min=0) k_slice: IntProperty(name="k slice", default=100, min=1) k_polygon: IntProperty(name="k polygon", default=4, min=1) coff: FloatProperty(name="coff", default=math.pi) unit_cell: FloatProperty(name="unit_cell", default=1, min=0, update=set_coff) isolevel: FloatProperty(name="isolevel", default=0.0) qsim_percent: FloatProperty(name="qsim", default=0.0, min=0, max=1.0, subtype="FACTOR") minimum_diameter: FloatProperty(name="minimum diameter", default=0.25, min=0, max=1, subtype="FACTOR") lua_file: StringProperty(name="Lua file", default="", subtype="FILE_PATH") surface_name: EnumProperty(name="Surface name", items=default_surface_names) direction: EnumProperty(name="slice direction", items=default_direction) progress1: IntProperty(name="progress1", default=0, min=0, max=100) progress2: IntProperty(name="progress2", default=0, min=0, max=100) result1: StringProperty(name="result1") result2: StringProperty(name="result2") def get_progress1(self): return self.progress1 def get_progress2(self): return self.progress2 def null_set(self, value): pass readonly_progress1: IntProperty(min=0, max=100, subtype="PERCENTAGE", get=get_progress1, set=null_set) readonly_progress2: IntProperty(min=0, max=100, subtype="PERCENTAGE", get=get_progress2, set=null_set)
40.055556
106
0.645631
2,201
0.763176
0
0
0
0
0
0
609
0.211165
7bf8ba88150b609b31fa7978009e2b6cda410d96
1,702
py
Python
examples/run_burgers.py
s274001/PINA
beb33f0da20581338c46f0c525775904b35a1130
[ "MIT" ]
4
2022-02-16T14:52:55.000Z
2022-03-17T13:31:42.000Z
examples/run_burgers.py
s274001/PINA
beb33f0da20581338c46f0c525775904b35a1130
[ "MIT" ]
3
2022-02-17T08:57:42.000Z
2022-03-28T08:41:53.000Z
examples/run_burgers.py
s274001/PINA
beb33f0da20581338c46f0c525775904b35a1130
[ "MIT" ]
7
2022-02-13T14:35:00.000Z
2022-03-28T08:51:11.000Z
import argparse import torch from torch.nn import Softplus from pina import PINN, Plotter from pina.model import FeedForward from problems.burgers import Burgers1D class myFeature(torch.nn.Module): """ Feature: sin(pi*x) """ def __init__(self, idx): super(myFeature, self).__init__() self.idx = idx def forward(self, x): return torch.sin(torch.pi * x[:, self.idx]) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run PINA") group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-s", "-save", action="store_true") group.add_argument("-l", "-load", action="store_true") parser.add_argument("id_run", help="number of run", type=int) parser.add_argument("features", help="extra features", type=int) args = parser.parse_args() feat = [myFeature(0)] if args.features else [] burgers_problem = Burgers1D() model = FeedForward( layers=[30, 20, 10, 5], output_variables=burgers_problem.output_variables, input_variables=burgers_problem.input_variables, func=Softplus, extra_features=feat, ) pinn = PINN( burgers_problem, model, lr=0.006, error_norm='mse', regularizer=0, lr_accelerate=None) if args.s: pinn.span_pts(2000, 'latin', ['D']) pinn.span_pts(150, 'random', ['gamma1', 'gamma2', 't0']) pinn.train(5000, 100) pinn.save_state('pina.burger.{}.{}'.format(args.id_run, args.features)) else: pinn.load_state('pina.burger.{}.{}'.format(args.id_run, args.features)) plotter = Plotter() plotter.plot(pinn)
28.366667
79
0.636898
245
0.143948
0
0
0
0
0
0
230
0.135135
7bf92b8ac984ff1d4af8bc11028ce720f6dccb7d
2,072
py
Python
questions/cousins-in-binary-tree/Solution.py
marcus-aurelianus/leetcode-solutions
8b43e72fe1f51c84abc3e89b181ca51f09dc7ca6
[ "MIT" ]
141
2017-12-12T21:45:53.000Z
2022-03-25T07:03:39.000Z
questions/cousins-in-binary-tree/Solution.py
marcus-aurelianus/leetcode-solutions
8b43e72fe1f51c84abc3e89b181ca51f09dc7ca6
[ "MIT" ]
32
2015-10-05T14:09:52.000Z
2021-05-30T10:28:41.000Z
questions/cousins-in-binary-tree/Solution.py
marcus-aurelianus/leetcode-solutions
8b43e72fe1f51c84abc3e89b181ca51f09dc7ca6
[ "MIT" ]
56
2015-09-30T05:23:28.000Z
2022-03-08T07:57:11.000Z
""" In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. Two nodes of a binary tree are cousins if they have the same depth, but have different parents. We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree. Return true if and only if the nodes corresponding to the values x and y are cousins.   Example 1: Input: root = [1,2,3,4], x = 4, y = 3 Output: false Example 2: Input: root = [1,2,3,null,4,null,5], x = 5, y = 4 Output: true Example 3: Input: root = [1,2,3,null,4], x = 2, y = 3 Output: false   Constraints: The number of nodes in the tree will be between 2 and 100. Each node has a unique integer value from 1 to 100. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isCousins(self, root: TreeNode, x: int, y: int) -> bool: def find_vals(node, x, y, lvl, pos1, pos2): if node.left is not None: if node.left.val == x: pos1[0] = lvl + 1 pos1[1] = node if node.left.val == y: pos2[0] = lvl + 1 pos2[1] = node find_vals(node.left, x, y, lvl + 1, pos1, pos2) if node.right is not None: if node.right.val == x: pos1[0] = lvl + 1 pos1[1] = node if node.right.val == y: pos2[0] = lvl + 1 pos2[1] = node find_vals(node.right, x, y, lvl + 1, pos1, pos2) if root is None: return False if root.val == x or root.val == y: return False pos1, pos2 = [-1, None], [-1, None] find_vals(root, x, y, 0, pos1, pos2) if pos1[0] == pos2[0] and pos1[0] != -1 and pos1[1] != pos2[1]: return True return False
28
117
0.531853
1,121
0.539461
0
0
0
0
0
0
948
0.456208
7bfad01ae563f31b06389bcaffa8bf4fb786658a
456
py
Python
utility_ai/models/action.py
TomasMaciulis/Utility-AI-API
29144e4b5dc038854335bd11ed3b072ba1231ebc
[ "MIT" ]
null
null
null
utility_ai/models/action.py
TomasMaciulis/Utility-AI-API
29144e4b5dc038854335bd11ed3b072ba1231ebc
[ "MIT" ]
null
null
null
utility_ai/models/action.py
TomasMaciulis/Utility-AI-API
29144e4b5dc038854335bd11ed3b072ba1231ebc
[ "MIT" ]
null
null
null
from .configuration_entry import ConfigurationEntry from utility_ai.traits.utility_score_trait import UtilityScoreTrait class Action(ConfigurationEntry, UtilityScoreTrait): def __init__(self, name: str, description: dict): ConfigurationEntry.__init__(self, name, description) UtilityScoreTrait.__init__( self, description['utility_score_formula'], super().weight_value, name )
30.4
67
0.699561
333
0.730263
0
0
0
0
0
0
23
0.050439
7bfb0d85a9d2727156196fca82066ec05a53a3a0
1,119
py
Python
widdy/styles.py
ubunatic/widdy
1e5923d90010f27e352ad3eebb670c09752dd86b
[ "MIT" ]
2
2018-05-30T17:23:46.000Z
2019-08-29T20:32:27.000Z
widdy/styles.py
ubunatic/widdy
1e5923d90010f27e352ad3eebb670c09752dd86b
[ "MIT" ]
null
null
null
widdy/styles.py
ubunatic/widdy
1e5923d90010f27e352ad3eebb670c09752dd86b
[ "MIT" ]
null
null
null
from collections import namedtuple Style = namedtuple('Style', 'name fg bg') default_pal = { Style('inv-black', 'black', 'light gray'), Style('green-bold', 'dark green,bold', ''), Style('red-bold', 'dark red,bold', ''), Style('blue-bold', 'dark blue,bold', ''), Style('yellow-bold', 'yellow,bold', ''), Style('magenta-bold', 'dark magenta,bold', ''), Style('cyan-bold', 'dark cyan,bold', ''), Style('green', 'dark green', ''), Style('red', 'dark red', ''), Style('blue', 'dark blue', ''), Style('cyan', 'dark cyan', ''), Style('magenta', 'dark magenta', ''), Style('yellow', 'yellow', ''), } INV_BLACK = 'inv-black' RED_BOLD = 'red-bold' GREEN_BOLD = 'green-bold' BLUE_BOLD = 'blue-bold' MAGENTA_BOLD = 'magenta-bold' CYAN_BOLD = 'cyan-bold' YELLOW_BOLD = 'yellow-bold' BLUE = 'blue' GREEN = 'green' RED = 'red' MAGENTA = 'magenta' CYAN = 'cyan' YELLOW = 'yellow'
29.447368
61
0.489723
0
0
0
0
0
0
0
0
470
0.420018
7bfb8c398b66afff9f9537190851684dffe009d8
189
py
Python
basics.py
c25l/longmont_data_science_tensorflow
78302ab5b76a1e4632deda164615b4861c21f534
[ "MIT" ]
null
null
null
basics.py
c25l/longmont_data_science_tensorflow
78302ab5b76a1e4632deda164615b4861c21f534
[ "MIT" ]
null
null
null
basics.py
c25l/longmont_data_science_tensorflow
78302ab5b76a1e4632deda164615b4861c21f534
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import tensorflow as tf x=tf.Variable(0.5) y = x*x sess = tf.Session() sess.run(tf.global_variables_initializer()) print("x =",sess.run(x)) print("y =",sess.run(y))
18.9
43
0.687831
0
0
0
0
0
0
0
0
32
0.169312
7bfc0a90c6e361e602b8b4fb5d3bb23952ab70e8
3,468
py
Python
nist_tools/combine_images.py
Nepherhotep/roboarchive-broom
a60c6038a5506c19edc6b74dbb47de525b246d2a
[ "MIT" ]
null
null
null
nist_tools/combine_images.py
Nepherhotep/roboarchive-broom
a60c6038a5506c19edc6b74dbb47de525b246d2a
[ "MIT" ]
null
null
null
nist_tools/combine_images.py
Nepherhotep/roboarchive-broom
a60c6038a5506c19edc6b74dbb47de525b246d2a
[ "MIT" ]
null
null
null
import os import random import cv2 import numpy as np from gen_textures import add_noise, texture, blank_image from nist_tools.extract_nist_text import BaseMain, parse_args, display class CombineMain(BaseMain): SRC_DIR = 'blurred' DST_DIR = 'combined_raw' BG_DIR = 'backgrounds' SMPL_DIR = 'combined_clean' def __init__(self): self.backgrounds = os.listdir(os.path.join(args.data_dir, self.BG_DIR)) self.backgrounds.sort() def get_random_bg(self): filename = random.choice(self.backgrounds) return os.path.join(args.data_dir, self.BG_DIR, filename) def main(self, args): lst = self.get_sorted_files(args) a = lst[::3] b = lst[1::3] c = lst[2::3] text_files = list(zip(a, b, c)) if args.index: text_files = text_files[args.index:args.index + 1] for i, chunk in enumerate(text_files): paths = [os.path.join(args.data_dir, self.SRC_DIR, p) for p in chunk] fname = 'combined-{}.png'.format(i) smpl_path = os.path.join(args.data_dir, self.SMPL_DIR, fname) bg_path = self.get_random_bg() output_path = os.path.join(args.data_dir, self.DST_DIR, fname) print('Processing {}/{}'.format(i, len(text_files))) self.combine_file(args, bg_path, output_path, smpl_path, *paths) def random_bool(self): return random.choice([True, False]) def load_text_image(self, shape, path, vert_offset, hor_offset): layer = np.full(shape, 255) sub_image = cv2.imread(path, cv2.IMREAD_GRAYSCALE) h, w = sub_image.shape layer[vert_offset:vert_offset + h, hor_offset:hor_offset + w] = sub_image return layer def merge_with_text(self, img, text_file_path, density, vert_offset, hor_offset=200): a_img = 255 - self.load_text_image(img.shape, text_file_path, vert_offset, hor_offset) img = img - (density * a_img).astype('int') return img.clip(0, 255) def combine_file(self, args, bg_path, output_path, smpl_path, *text_paths): # open files and invert text raw_image = cv2.imread(bg_path, cv2.IMREAD_GRAYSCALE).astype('int') h, w = raw_image.shape # generate random noise noise = 160 - add_noise(texture(blank_image(background=125, height=4096, width=4096), sigma=4), sigma=10).astype('float')[:h, :w] noise = (random.random() * noise).astype('int') raw_image = raw_image + noise raw_image = raw_image.clip(0, 255) # random horizontal flip if self.random_bool(): raw_image = cv2.flip(raw_image, 0) # random vertical flip if self.random_bool(): raw_image = cv2.flip(raw_image, 1) # create a clean training image clean_image = np.full(raw_image.shape, 255) # save reference to raw image for i, path in enumerate(text_paths): v_offset = 100 + i * 1250 density = 0.2 + random.random() * 0.3 raw_image = self.merge_with_text(raw_image, path, density, v_offset) clean_image = self.merge_with_text(clean_image, path, 1, v_offset) cv2.imwrite(output_path, raw_image) cv2.imwrite(smpl_path, clean_image) if __name__ == '__main__': random.seed(123) args = parse_args() CombineMain().main(args) print('done')
31.527273
94
0.625144
3,160
0.911188
0
0
0
0
0
0
282
0.081315
7bfe07fff56233f17c17498061812fd747efa684
1,205
py
Python
auto_funcs/look_for_date.py
rhysrushton/testauto
9c32f40640f58703a0d063afbb647855fb680a61
[ "MIT" ]
null
null
null
auto_funcs/look_for_date.py
rhysrushton/testauto
9c32f40640f58703a0d063afbb647855fb680a61
[ "MIT" ]
null
null
null
auto_funcs/look_for_date.py
rhysrushton/testauto
9c32f40640f58703a0d063afbb647855fb680a61
[ "MIT" ]
null
null
null
# this function looks for either the encounter date or the patient's date of birth # so that we can avoid duplicate encounters. import time def look_for_date (date_string, driver): print('looking for date') date_present = False for div in driver.find_elements_by_class_name('card.my-4.patient-card.assessment-reg-patient'): if date_string in div.get_attribute('innerHTML'): print('date here') date_present = True #print(div.get_attribute('innerHTML')) break return date_present #this will select element in div with relement div. def find_date_click (date_string, driver): print('getting div to add encounter to.') for div in driver.find_elements_by_class_name('card.my-4.patient-card.assessment-reg-patient'): if date_string in div.get_attribute('innerHTML'): #print("We here" ) #print(div.get_attribute('innerHTML')) #time.sleep(20) new_encounter_button = div.find_element_by_class_name('btn.btn-primary.mr-4') new_encounter_button.click() #break return print('hey')
30.125
99
0.637344
0
0
0
0
0
0
0
0
501
0.415768
7bfefe9a585dfb51817f970316b20305a606310a
1,047
py
Python
app/api/apis/token_api.py
boceckts/ideahub
fbd48c53a5aaf7252a5461d0c0d2fe9d4eef9aed
[ "BSD-3-Clause" ]
null
null
null
app/api/apis/token_api.py
boceckts/ideahub
fbd48c53a5aaf7252a5461d0c0d2fe9d4eef9aed
[ "BSD-3-Clause" ]
null
null
null
app/api/apis/token_api.py
boceckts/ideahub
fbd48c53a5aaf7252a5461d0c0d2fe9d4eef9aed
[ "BSD-3-Clause" ]
null
null
null
from flask import g from flask_restplus import Resource, marshal from app import db from app.api.namespaces.token_namespace import token_ns, token from app.api.security.authentication import basic_auth, token_auth @token_ns.route('', strict_slashes=False) @token_ns.response(401, 'Unauthenticated') @token_ns.response(500, 'Internal Server Error') class TokensResource(Resource): @token_ns.response(200, 'Token successfully generated') @token_ns.doc(security='Basic Auth') @basic_auth.login_required def post(self): """Generate a new bearer token""" g.current_user.generate_auth_token() db.session.commit() token_obj = {'token': g.current_user.token, 'expires_on': g.current_user.token_expiration} return marshal(token_obj, token), 200 @token_ns.response(204, 'Token successfully revoked') @token_auth.login_required def delete(self): """Revoke a token""" g.current_user.revoke_token() db.session.commit() return '', 204
32.71875
67
0.700096
695
0.663801
0
0
829
0.791786
0
0
186
0.17765
7bff9b4a9c838befc20c601a3d326698664e8b5d
1,025
py
Python
quickSort.py
pflun/learningAlgorithms
3101e989488dfc8a56f1bf256a1c03a837fe7d97
[ "MIT" ]
null
null
null
quickSort.py
pflun/learningAlgorithms
3101e989488dfc8a56f1bf256a1c03a837fe7d97
[ "MIT" ]
null
null
null
quickSort.py
pflun/learningAlgorithms
3101e989488dfc8a56f1bf256a1c03a837fe7d97
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # low --> Starting index, high --> Ending index class Solution(object): def quickSort(self, arr, low, high): if low < high: pi = self.partition(arr, low, high) self.quickSort(arr, low, pi - 1) self.quickSort(arr, pi + 1, high) return arr def partition(self, arr, low, high): # pivot (Element to be placed at right position) pivot = arr[high] # Index of smaller element i = low - 1 for j in range(low, high): # If current element is smaller than or equal to pivot # 这个双指针就像moveZeros, 小于pivot挪前面,大的挪后面 if arr[j] <= pivot: i += 1 # swap arr[i], arr[j] = arr[j], arr[i] # pivot挪到小于组的下一个(和大于组第一个交换) arr[i + 1], arr[high] = arr[high], arr[i + 1] # 返回pivot位置,下次partition就这个分(pi - 1组 和 pi + 1组) return i + 1 test = Solution() print test.quickSort([10, 80, 30, 90, 40, 50, 70], 0, 6)
29.285714
66
0.520976
982
0.866726
0
0
0
0
0
0
424
0.374228
d0003ec058228de9777e23294e4fbffc93d7d212
4,816
py
Python
docker_multiarch/tool.py
CynthiaProtector/helo
ad9e22363a92389b3fa519ecae9061c6ead28b05
[ "Apache-2.0" ]
399
2017-05-30T05:12:48.000Z
2022-01-29T05:53:08.000Z
docker_multiarch/tool.py
greenpea0104/incubator-mxnet
fc9e70bf2d349ad4c6cb65ff3f0958e23a7410bf
[ "Apache-2.0" ]
58
2017-05-30T23:25:32.000Z
2019-11-18T09:30:54.000Z
docker_multiarch/tool.py
greenpea0104/incubator-mxnet
fc9e70bf2d349ad4c6cb65ff3f0958e23a7410bf
[ "Apache-2.0" ]
107
2017-05-30T05:53:22.000Z
2021-06-24T02:43:31.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """Multi arch dockerized build tool. """ __author__ = 'Pedro Larroy' __version__ = '0.1' import os import sys import subprocess import logging import argparse from subprocess import check_call import glob import re class CmdResult(object): def __init__(self, std_out, std_err, status_code): self.std_out = std_out self.std_err = std_err self.status_code = status_code if status_code is not None else 0 def __str__(self): return "%s, %s, %s" % (self.std_out, self.std_err, self.status_code) def run(cmd, fail_on_error=True): logging.debug("executing shell command:\n" + cmd) proc = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) std_out, std_err = proc.communicate() if fail_on_error: if proc.returncode != 0: logging.warn('Error running command: {}'.format(cmd)) assert proc.returncode == 0, std_err res = CmdResult(std_out.decode('utf-8'), std_err.decode('utf-8'), proc.returncode) return res def mkdir_p(d): rev_path_list = list() head = d while len(head) and head != os.sep: rev_path_list.append(head) (head, tail) = os.path.split(head) rev_path_list.reverse() for p in rev_path_list: try: os.mkdir(p) except OSError as e: if e.errno != 17: raise def get_arches(): """Get a list of architectures given our dockerfiles""" dockerfiles = glob.glob("Dockerfile.build.*") dockerfiles = list(filter(lambda x: x[-1] != '~', dockerfiles)) arches = list(map(lambda x: re.sub(r"Dockerfile.build.(.*)", r"\1", x), dockerfiles)) arches.sort() return arches def sync_source(): logging.info("Copying sources") check_call(["rsync","-a","--delete","--exclude=\".git/\"",'--exclude=/docker_multiarch/',"../","mxnet"]) def get_docker_tag(arch): return "mxnet.build.{0}".format(arch) def get_dockerfile(arch): return "Dockerfile.build.{0}".format(arch) def build(arch): """Build the given architecture in the container""" assert arch in get_arches(), "No such architecture {0}, Dockerfile.build.{0} not found".format(arch) logging.info("Building for target platform {0}".format(arch)) check_call(["docker", "build", "-f", get_dockerfile(arch), "-t", get_docker_tag(arch), "."]) def collect_artifacts(arch): """Collects the artifacts built inside the docker container to the local fs""" def artifact_path(arch): return "{}/build/{}".format(os.getcwd(), arch) logging.info("Collect artifacts from build in {0}".format(artifact_path(arch))) mkdir_p("build/{}".format(arch)) # Mount artifact_path on /$arch inside the container and copy the build output so we can access # locally from the host fs check_call(["docker","run", "-v", "{}:/{}".format(artifact_path(arch), arch), get_docker_tag(arch), "bash", "-c", "cp -r /work/build/* /{}".format(arch)]) def main(): logging.getLogger().setLevel(logging.INFO) logging.basicConfig(format='%(asctime)-15s %(message)s') parser = argparse.ArgumentParser() parser.add_argument("-a", "--arch", help="Architecture", type=str) parser.add_argument("-l", "--list_arch", help="List architectures", action='store_true') args = parser.parse_args() if args.list_arch: arches = get_arches() print(arches) elif args.arch: sync_source() build(args.arch) collect_artifacts(args.arch) else: arches = get_arches() logging.info("Building for all architectures: {}".format(arches)) logging.info("Artifacts will be produced in the build/ directory.") sync_source() for arch in arches: build(arch) collect_artifacts(arch) return 0 if __name__ == '__main__': sys.exit(main())
30.871795
108
0.65054
315
0.065407
0
0
0
0
0
0
1,892
0.392857
d001b6743e397b1ed7c3a5a49549452902031c2c
150
py
Python
integrate/test/test_samples/sample_norun.py
Requirement-Engineers/default-coding-Bo2
f51e4e17af4fff077aebe2f3611c363da9ed9871
[ "Unlicense" ]
null
null
null
integrate/test/test_samples/sample_norun.py
Requirement-Engineers/default-coding-Bo2
f51e4e17af4fff077aebe2f3611c363da9ed9871
[ "Unlicense" ]
null
null
null
integrate/test/test_samples/sample_norun.py
Requirement-Engineers/default-coding-Bo2
f51e4e17af4fff077aebe2f3611c363da9ed9871
[ "Unlicense" ]
null
null
null
import json def dummy_function(): return [] def test_norun(): this shall not run if __name__ == '__main__': test_norun()
11.538462
27
0.593333
0
0
0
0
0
0
0
0
10
0.066667
d003fb1f6605d874e72c3a666281e62431d7b2a8
3,283
py
Python
02module/module_containers.py
mayi140611/szzy_pytorch
81978d75513bc9a1b85aec05023d14fa6f748674
[ "Apache-2.0" ]
null
null
null
02module/module_containers.py
mayi140611/szzy_pytorch
81978d75513bc9a1b85aec05023d14fa6f748674
[ "Apache-2.0" ]
null
null
null
02module/module_containers.py
mayi140611/szzy_pytorch
81978d75513bc9a1b85aec05023d14fa6f748674
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ # @file name : module_containers.py # @author : tingsongyu # @date : 2019-09-20 10:08:00 # @brief : 模型容器——Sequential, ModuleList, ModuleDict """ import torch import torchvision import torch.nn as nn from collections import OrderedDict # ============================ Sequential class LeNetSequential(nn.Module): def __init__(self, classes): super(LeNetSequential, self).__init__() self.features = nn.Sequential( nn.Conv2d(3, 6, 5), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(6, 16, 5), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2),) self.classifier = nn.Sequential( nn.Linear(16*5*5, 120), nn.ReLU(), nn.Linear(120, 84), nn.ReLU(), nn.Linear(84, classes),) def forward(self, x): x = self.features(x) x = x.view(x.size()[0], -1) x = self.classifier(x) return x class LeNetSequentialOrderDict(nn.Module): def __init__(self, classes): super(LeNetSequentialOrderDict, self).__init__() self.features = nn.Sequential(OrderedDict({ 'conv1': nn.Conv2d(3, 6, 5), 'relu1': nn.ReLU(inplace=True), 'pool1': nn.MaxPool2d(kernel_size=2, stride=2), 'conv2': nn.Conv2d(6, 16, 5), 'relu2': nn.ReLU(inplace=True), 'pool2': nn.MaxPool2d(kernel_size=2, stride=2), })) self.classifier = nn.Sequential(OrderedDict({ 'fc1': nn.Linear(16*5*5, 120), 'relu3': nn.ReLU(), 'fc2': nn.Linear(120, 84), 'relu4': nn.ReLU(inplace=True), 'fc3': nn.Linear(84, classes), })) def forward(self, x): x = self.features(x) x = x.view(x.size()[0], -1) x = self.classifier(x) return x # net = LeNetSequential(classes=2) # net = LeNetSequentialOrderDict(classes=2) # # fake_img = torch.randn((4, 3, 32, 32), dtype=torch.float32) # # output = net(fake_img) # # print(net) # print(output) # ============================ ModuleList class ModuleList(nn.Module): def __init__(self): super(ModuleList, self).__init__() self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(20)]) def forward(self, x): for i, linear in enumerate(self.linears): x = linear(x) return x # net = ModuleList() # # print(net) # # fake_data = torch.ones((10, 10)) # # output = net(fake_data) # # print(output) # ============================ ModuleDict class ModuleDict(nn.Module): def __init__(self): super(ModuleDict, self).__init__() self.choices = nn.ModuleDict({ 'conv': nn.Conv2d(10, 10, 3), 'pool': nn.MaxPool2d(3) }) self.activations = nn.ModuleDict({ 'relu': nn.ReLU(), 'prelu': nn.PReLU() }) def forward(self, x, choice, act): x = self.choices[choice](x) x = self.activations[act](x) return x net = ModuleDict() fake_img = torch.randn((4, 10, 32, 32)) output = net(fake_img, 'conv', 'relu') print(output) # 4 AlexNet alexnet = torchvision.models.AlexNet()
22.486301
76
0.540664
2,362
0.716844
0
0
0
0
0
0
743
0.225493
d00408e74248e82eceb28ea83155d9b67a8bad9f
2,124
py
Python
tests/test_sample_images.py
olavosamp/semiauto-video-annotation
b1a46f9c0ad3bdcedab76b4cd730747ee2afd2fd
[ "MIT" ]
null
null
null
tests/test_sample_images.py
olavosamp/semiauto-video-annotation
b1a46f9c0ad3bdcedab76b4cd730747ee2afd2fd
[ "MIT" ]
20
2019-07-15T21:49:29.000Z
2020-01-09T14:35:03.000Z
tests/test_sample_images.py
olavosamp/semiauto-video-annotation
b1a46f9c0ad3bdcedab76b4cd730747ee2afd2fd
[ "MIT" ]
null
null
null
import pytest import shutil as sh import pandas as pd from pathlib import Path from glob import glob import libs.dirs as dirs from libs.iteration_manager import SampleImages from libs.utils import copy_files, replace_symbols class Test_SampleImages(): def test_setup_SampleImages(self): # Metatest if test assets are in place sourceFolder = Path(dirs.test_assets) / "dataset_test" setupImageList = glob(str(sourceFolder) + "/**.jpg", recursive=True) assert len(setupImageList) == 2666 def setup_sample_from_folder(self): self.sourceFolder = Path(dirs.test_assets) / "dataset_test" self.sampleImagesFolder = Path(dirs.test) / "test_sample_images" self.destFolderSFF = self.sampleImagesFolder / "test_sample_from_folder" # Guarantee that the destination folder was created for this test only if self.destFolderSFF.is_dir(): self.teardown_sample_from_folder() dirs.create_folder(self.destFolderSFF) def teardown_sample_from_folder(self): sh.rmtree(self.destFolderSFF) def test_sample_from_folder(self): self.setup_sample_from_folder() assert self.destFolderSFF.is_dir() self.sampler = SampleImages(self.sourceFolder, self.destFolderSFF) # Test image sampling and copying self.sampler.sample(percentage=0.01) globString = str(self.sampler.imageFolder) + "/**.jpg" globString = replace_symbols(globString) imageList = glob(globString, recursive=True) assert len(imageList) == 26 # Test saving samples to index self.outIndexPathSFF = self.sampler.imageFolder / "test_index_sample_from_file.csv" print("Saving index to\n", self.outIndexPathSFF) self.sampler.save_to_index(indexPath=self.outIndexPathSFF) self.outIndexSFF = pd.read_csv(self.outIndexPathSFF) assert self.outIndexPathSFF.is_file() assert self.outIndexSFF.shape[0] == 26 self.teardown_sample_from_folder()
34.819672
91
0.677966
1,812
0.853107
0
0
0
0
0
0
314
0.147834
d0056587271ff8ce0d2628ab99ab1c7bc8e2f7e9
558
py
Python
data/Carp.py
shebang-sh/npb-ouenka-bot
6fc6f7c1717632c3845496c309560233a9c73d8e
[ "MIT" ]
null
null
null
data/Carp.py
shebang-sh/npb-ouenka-bot
6fc6f7c1717632c3845496c309560233a9c73d8e
[ "MIT" ]
14
2022-03-29T09:07:31.000Z
2022-03-30T02:37:07.000Z
data/Carp.py
shebang-sh/npb-ouenka-bot
6fc6f7c1717632c3845496c309560233a9c73d8e
[ "MIT" ]
null
null
null
data={ "田中広輔":"赤く燃え上がる 夢見たこの世界で 研ぎ澄ませそのセンス 打てよ広輔", "長野久義":"歓声を背に受け 頂をみつめて 紅一筋に 突き進め長野", "安部友裕":"新しい時代に 今手を伸ばせ 終わらぬ夢の先に 導いてくれ", "堂林翔太":"光り輝く その道を 翔けぬけて魅せろ 堂林SHOW TIME!", "會澤翼":"いざ大空へ翔ばたけ 熱い想い乗せ 勝利へ導く一打 決めろよ翼", "菊池涼介":"【前奏:始まりの鐘が鳴る 広島伝説】\n光を追い越して メーター振りきり駆け抜けろ 止まらないぜ 韋駄天菊池", "野間峻祥":"鋭い打球飛ばせ 自慢の俊足魅せろ 赤い流星のように 走れ峻祥", "磯村嘉孝":"【前奏:当たると痛えぞ! 磯村パンチ】\n解き放てよこの瞬間 エンジン全開さあスパーク いざ満タンフルパワーで 撃て磯村パンチ", "小園海斗":"新たな息吹を 注ぎ込め 世代のトップを走れ ぶっちぎれ", "松山竜平":"闘志を燃やし 鋭く振り抜け さあかっとばせ さあ打ちまくれ 我等の松山", "西川龍馬":"気高きその勇姿 比ぶ者は無いさ 我等に希望の光 見せてくれ", }
42.923077
77
0.691756
0
0
0
0
0
0
0
0
1,229
0.935312
d0057db4b4f167cbdeebfbc062e049713a913fcb
42
py
Python
source/constants.py
sideround/predict-revenue-new-releases
b6b597cfed328d6b7981917477ceb6f0630aee49
[ "MIT" ]
null
null
null
source/constants.py
sideround/predict-revenue-new-releases
b6b597cfed328d6b7981917477ceb6f0630aee49
[ "MIT" ]
11
2020-05-21T17:52:04.000Z
2020-06-08T03:33:28.000Z
source/constants.py
sideround/predict-revenue-new-releases
b6b597cfed328d6b7981917477ceb6f0630aee49
[ "MIT" ]
2
2020-06-02T13:14:16.000Z
2020-06-11T17:46:05.000Z
BASE_URL = 'https://api.themoviedb.org/3'
21
41
0.714286
0
0
0
0
0
0
0
0
30
0.714286
d00676794b322b39517d8082c8b83c61f4836359
284
py
Python
Unit 2/2.16/2.16.5 Black and White Squares.py
shashwat73/cse
60e49307e57105cf9916c7329f53f891c5e81fdb
[ "MIT" ]
1
2021-04-08T14:02:49.000Z
2021-04-08T14:02:49.000Z
Unit 2/2.16/2.16.5 Black and White Squares.py
shashwat73/cse
60e49307e57105cf9916c7329f53f891c5e81fdb
[ "MIT" ]
null
null
null
Unit 2/2.16/2.16.5 Black and White Squares.py
shashwat73/cse
60e49307e57105cf9916c7329f53f891c5e81fdb
[ "MIT" ]
null
null
null
speed(0) def make_square(i): if i % 2 == 0: begin_fill() for i in range(4): forward(25) left(90) end_fill() penup() setposition(-100, 0) pendown() for i in range (6): pendown() make_square(i) penup() forward(35)
14.947368
23
0.503521
0
0
0
0
0
0
0
0
0
0
d0075df444476cd69e92bd3d5f61f5eff5a35b08
771
py
Python
Q1/read.py
arpanmangal/Regression
06969286d7db65a537e89ac37905310592542ca9
[ "MIT" ]
null
null
null
Q1/read.py
arpanmangal/Regression
06969286d7db65a537e89ac37905310592542ca9
[ "MIT" ]
null
null
null
Q1/read.py
arpanmangal/Regression
06969286d7db65a537e89ac37905310592542ca9
[ "MIT" ]
null
null
null
""" Module for reading data from 'linearX.csv' and 'linearY.csv' """ import numpy as np def loadData (x_file="ass1_data/linearX.csv", y_file="ass1_data/linearY.csv"): """ Loads the X, Y matrices. Splits into training, validation and test sets """ X = np.genfromtxt(x_file) Y = np.genfromtxt(y_file) Z = [X, Y] Z = np.c_[X.reshape(len(X), -1), Y.reshape(len(Y), -1)] np.random.shuffle(Z) # Partition the data into three sets size = len(Z) training_size = int(0.8 * size) validation_size = int(0.1 * size) test_size = int(0.1 * size) training_Z = Z[0:training_size] validation_Z = Z[training_size:training_size+validation_size] test_Z = Z[training_size+validation_size:] return (Z[:,0], Z[:,1])
25.7
78
0.639429
0
0
0
0
0
0
0
0
241
0.312581
d00814276e589d5ea8bb86b5cdc709673c74e2be
331
py
Python
apps/experiments/forms.py
Intellia-SME/OptiPLANT
1d40b62f00b3fff940499fa27d0c2d59e7e6dd4c
[ "Apache-2.0" ]
1
2022-01-26T18:07:22.000Z
2022-01-26T18:07:22.000Z
apps/experiments/forms.py
Intellia-SME/OptiPLANT
1d40b62f00b3fff940499fa27d0c2d59e7e6dd4c
[ "Apache-2.0" ]
null
null
null
apps/experiments/forms.py
Intellia-SME/OptiPLANT
1d40b62f00b3fff940499fa27d0c2d59e7e6dd4c
[ "Apache-2.0" ]
1
2022-01-26T18:07:26.000Z
2022-01-26T18:07:26.000Z
from django import forms from .models import Experiment class CreateExperimentForm(forms.ModelForm): class Meta: model = Experiment fields = ['name', 'description', 'dataset'] def save(self, commit=True): self.instance.experimenter = self.request.user return super().save(commit=commit)
23.642857
54
0.679758
271
0.818731
0
0
0
0
0
0
28
0.084592
d0089b5c467aacb771cc69018d2b7e9da7c6f7d7
3,377
py
Python
Giveme5W1H/extractor/tools/timex.py
bkrrr/Giveme5W
657738781fe387d76e6e0da35ed009ccf81f4290
[ "Apache-2.0" ]
410
2018-05-02T12:53:02.000Z
2022-03-28T16:11:34.000Z
Giveme5W1H/extractor/tools/timex.py
bkrrr/Giveme5W
657738781fe387d76e6e0da35ed009ccf81f4290
[ "Apache-2.0" ]
51
2018-05-02T13:53:19.000Z
2022-03-22T00:16:39.000Z
Giveme5W1H/extractor/tools/timex.py
TU-Berlin/Giveme5W1H
b1586328393a50acde86015d22f78a4c15bf2f34
[ "Apache-2.0" ]
81
2018-05-29T14:03:27.000Z
2022-02-08T08:59:38.000Z
from datetime import datetime from dateutil.relativedelta import relativedelta class Timex: """ Simply represents a Timex object. Main reason for this class is that the datetime class (and other Python equivalents) do not allow to reflect a month or a day but only a single point in time. """ _date_format_month = '%Y-%m' _date_format_week = '%Y-W%W' + '-%w' _date_format_day = '%Y-%m-%d' _date_format_time_nosecs = '%Y-%m-%dT%H:%M' # _log = logging.getLogger('GiveMe5W') def __init__(self, start_datetime, end_datetime): self._start_date = start_datetime self._end_date = end_datetime def __str__(self): return 'Timex(' + str(self._start_date) + ', ' + str(self._end_date) + ')' @staticmethod def _get_date_distance_in_seconds(date1, date2): return abs((date2 - date1).total_seconds()) def get_start_date(self): return self._start_date def get_end_date(self): return self._end_date def get_duration(self): return self._end_date - self._start_date def is_entailed_in(self, other_timex): return other_timex.get_start_date() <= self._start_date and self.get_end_date() <= other_timex._end_date def get_min_distance_in_seconds_to_datetime(self, other_datetime): return min(Timex._get_date_distance_in_seconds(self._start_date, other_datetime), Timex._get_date_distance_in_seconds(self._end_date, other_datetime)) def get_json(self): """ return a serializable representation of this object. :return: """ return { 'start_date': self._start_date.isoformat(), 'end_date': self._end_date.isoformat() } @staticmethod def from_timex_text(text): # month (2017-11) try: start_date = datetime.strptime(text, Timex._date_format_month) end_date = start_date + relativedelta(months=1) - relativedelta(seconds=1) return Timex(start_date, end_date) except ValueError as verr: pass # week (2017-W45) try: default_day = '-0' # https://stackoverflow.com/a/17087427/1455800 start_date = datetime.strptime(text + default_day, Timex._date_format_week) end_date = start_date + relativedelta(weeks=1) - relativedelta(seconds=1) return Timex(start_date, end_date) except ValueError as verr: pass # day (2017-11-01) try: start_date = datetime.strptime(text, Timex._date_format_day) end_date = start_date + relativedelta(days=1) - relativedelta(seconds=1) return Timex(start_date, end_date) except ValueError as verr: pass # datetime without seconds (2017-02-04T13:55) try: start_date = datetime.strptime(text, Timex._date_format_time_nosecs) end_date = start_date + relativedelta(minutes=1) - relativedelta(seconds=1) return Timex(start_date, end_date) except ValueError as verr: pass # Timex._log.error('could not parse "' + text + '" to Timex') # print('could not parse "' + text + '" to Timex') # we cannot parse the following things # could not parse "2017-SU" to Timex: This summer return None
35.547368
112
0.638733
3,294
0.975422
0
0
1,743
0.516139
0
0
771
0.228309
d008c5731d8fedc349d8c20f7b0bc4f197dfbb75
1,172
py
Python
utils/get_dic_question_id.py
Pxtri2156/M4C_inforgraphicsVQA
8846ea01a9be726de03e8944c746203936334bc9
[ "BSD-3-Clause" ]
1
2022-02-15T14:46:15.000Z
2022-02-15T14:46:15.000Z
utils/get_dic_question_id.py
Pxtri2156/M4C_inforgraphicsVQA
8846ea01a9be726de03e8944c746203936334bc9
[ "BSD-3-Clause" ]
null
null
null
utils/get_dic_question_id.py
Pxtri2156/M4C_inforgraphicsVQA
8846ea01a9be726de03e8944c746203936334bc9
[ "BSD-3-Clause" ]
1
2022-02-13T11:15:11.000Z
2022-02-13T11:15:11.000Z
import argparse import json from os import openpty def create_dic_question_id(path): set_name = ['train', 'val', 'test'] dic_qid = {} for i in range(len(set_name)): print("Processing, ", set_name[i]) annot_path = path.replace("change", set_name[i]) annot_fi = open(annot_path) data = json.load(annot_fi) data = data['data'] for sample in data: questionId = sample['questionId'] img_id = sample['image'].split('/')[-1].split('.')[0] new_id = int(str(i+1) + img_id + '00') while new_id in dic_qid.keys(): new_id += 1 dic_qid[questionId] = new_id dic_qid[new_id] = questionId annot_fi.close() return dic_qid def main(args): dic_qid = create_dic_question_id(args.path) print(dic_qid) def get_parser(): parser = argparse.ArgumentParser() parser.add_argument( "--path", default="/mlcv/Databases/VN_InfographicVQA/change/VietInfographicVQA_change_v1.0.json", type=str, ) return parser.parse_args() if __name__ == "__main__": args = get_parser() main(args)
29.3
96
0.595563
0
0
0
0
0
0
0
0
171
0.145904