-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuARG.py
More file actions
executable file
·7808 lines (6487 loc) · 292 KB
/
QuARG.py
File metadata and controls
executable file
·7808 lines (6487 loc) · 292 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
:copyright:
IRIS Data Management Center
:license:
This file is part of QuARG.
QuARG is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuARG is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuARG. If not, see <https://www.gnu.org/licenses/>.
"""
version = "1.2.0"
print("QuARG version %s" % version)
# TODO: Need to include MS Gothic.ttf when packaging the scripts
import kivy
kivy.require("1.11.0")
from kivy.config import Config
Config.set("graphics", "width", "1200")
Config.set("graphics", "height", "700")
Config.set("graphics", "resizable", 0)
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.scrollview import ScrollView
from kivy.properties import ObjectProperty # , StringProperty
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition, NoTransition
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.recycleview.views import (
_cached_views,
_view_base_cache,
) # supresses Original exception was:/Error in sys.excepthook: recycleview messages
from kivy.properties import BooleanProperty
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.clock import Clock
from kivy.uix.dropdown import DropDown
from kivy.graphics import Color, Rectangle
import os
import datetime
import shutil # used to remove directories
import webbrowser
import pandas as pd
import logging
logging.getLogger("matplotlib").setLevel(logging.WARNING)
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import sqlite3
from sqlite3 import Error
import subprocess
import urllib.request
import urllib.error
import requests # used for getting empty transfer_function returns
import reportUtils
Config.set("input", "mouse", "mouse,disable_multitouch")
# Explicit adapters and converters for datetime
sqlite3.register_adapter(datetime.datetime, lambda dt: dt.isoformat(" "))
sqlite3.register_converter(
"timestamp", lambda s: datetime.datetime.fromisoformat(s.decode())
)
# PREFERENCE FILE TODOS #
# OVERALL PROGRAM TODOS #
# TODO: status bar at bottom of gui for output that's normally displayed on the command line?
# TODO: add a targets list as an option?
# TODO: If I call on the ObjectProperty version of the properties, do I even need the get_*_inputs() function at all? Or will those update as soon as the field updates in the gui?
# THRESHOLDS #
# TODO: Change the thresholds list popup (all defined thresholds) in the Thresholds Page to be text input so that user can select them, just like in the Examine Issues page)
# FIND ISSUES TODOS#
# EXAMINE TAB TO-DOS #
# TODO: have the 'metrics' populate as the ones involved with the selected threshold(s)?
# TODO: put a "See Tickets" button to pull up all tickets related to the specified target
# TODO: add link to Mustangular in the resources column
# TODO: hold onto polarity_check's snql2 and display in the examine issues screen?
# TICKETING TODOS #
# TODO: put button on the "create ticket" screen that looks for existing tickets related to the selected target
# Seeing the list of related tickets would be available from both the Examine screen and the Create Ticket screen
# TODO: popup to select which description to import, if multiple
# GENERATE TAB TO-DOS #
# REPORT UTILS TODOS #
#### POP UPS and DROP DOWNS ####
class ExitDialog(FloatLayout):
exit = ObjectProperty(None)
cancel = ObjectProperty(None)
def do_exit(self):
# first, remove any figures that may be in quarg_plots/, as they are temporary
try:
for filename in os.listdir(masterDict["imageDir"]):
if filename.startswith("tmp."):
file_path = os.path.join(masterDict["imageDir"], filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print("Failed to delete %s. Reason: %s" % (file_path, e))
except:
pass
# Then exit the application
App.get_running_app().stop()
class DeleteDialog(FloatLayout):
deleteit = ObjectProperty(None)
cancel = ObjectProperty(None)
class LoadDialog(FloatLayout):
load = ObjectProperty(None)
cancel = ObjectProperty(None)
class LoadDialog2(FloatLayout):
load = ObjectProperty(None)
cancel = ObjectProperty(None)
class OverwriteDialog(FloatLayout):
dontDoIt = ObjectProperty(None)
doIt = ObjectProperty(None)
class ReportDialog(FloatLayout):
a = ObjectProperty(None)
b = ObjectProperty(None)
class notifyPopup(FloatLayout):
closePopup = ObjectProperty(None)
class TrackerDropDown(DropDown):
pass
#####################
### SCREEN CLASSES ###
class MainScreen(Screen):
startDate = ObjectProperty()
endDate = ObjectProperty()
find_pref = ObjectProperty()
find_directory = ObjectProperty()
find_file = ObjectProperty()
find_net = ObjectProperty()
find_sta = ObjectProperty()
find_loc = ObjectProperty()
find_cha = ObjectProperty()
examine_pref = ObjectProperty()
examine_directory = ObjectProperty()
examine_file = ObjectProperty()
query_pref = ObjectProperty()
query_net = ObjectProperty()
query_sta = ObjectProperty()
query_loc = ObjectProperty()
query_cha = ObjectProperty()
query_updated = ObjectProperty()
query_start = ObjectProperty()
query_end = ObjectProperty()
query_start_before = ObjectProperty()
query_end_before = ObjectProperty()
query_status_btn2 = ObjectProperty()
query_tracker_btn2 = ObjectProperty()
query_category_btn2 = ObjectProperty()
query_updated_before = ObjectProperty()
generate_pref = ObjectProperty()
generate_directory = ObjectProperty()
generate_file = ObjectProperty()
generate_net = ObjectProperty()
generate_sta = ObjectProperty()
generate_loc = ObjectProperty()
generate_cha = ObjectProperty()
generate_startDay = ObjectProperty()
generate_endDay = ObjectProperty()
start = ""
end = ""
query_options = list()
fileType = ""
def warning_popup(self, txt):
popupContent = BoxLayout(orientation="vertical", spacing=10)
popupContent.bind(minimum_height=popupContent.setter("height"))
scrvw = ScrollView(size_hint_y=6)
threshLabel = Label(text=txt, size_hint_y=None)
threshLabel.bind(texture_size=threshLabel.setter("size"))
scrvw.add_widget(threshLabel)
returnButton = Button(text="Return")
returnButton.bind(on_release=self.dismiss_warning_popup)
popupContent.add_widget(Label(size_hint_y=1.5))
popupContent.add_widget(scrvw)
popupContent.add_widget(Label(size_hint_y=1.5))
popupContent.add_widget(returnButton)
masterDict["warning_popup"] = Popup(
title="Warning", content=popupContent, size_hint=(0.66, 0.66)
)
masterDict["warning_popup"].open()
def get_default_dates(self):
today = datetime.date.today()
first = today.replace(day=1)
lastMonthEnd = first - datetime.timedelta(days=1)
lastMonthStart = lastMonthEnd.replace(day=1)
if not MainScreen.start:
self.start = str(lastMonthStart)
if not MainScreen.end:
self.end = str(first)
def set_default_start(self):
self.get_default_dates()
return self.start
def set_default_end(self):
self.get_default_dates()
return self.end
def get_dates(self):
ExamineIssuesScreen.start = self.start
ExamineIssuesScreen.end = self.end
def set_directory(self, whichToUse):
if whichToUse == "Find":
self.examine_directory.text = self.find_directory.text
self.generate_directory.text = self.find_directory.text
if whichToUse == "Examine":
self.find_directory.text = self.examine_directory.text
self.generate_directory.text = self.examine_directory.text
if whichToUse == "Generate":
self.find_directory.text = self.generate_directory.text
self.find_directory.text = self.generate_directory.text
def get_find_inputs(self):
self.start = self.startDate.text
self.end = self.endDate.text
self.preference = self.find_pref.text
masterDict["preference_file"] = self.preference
self.network = self.find_net.text
self.stations = self.find_sta.text
self.channels = self.find_cha.text
self.locations = self.find_loc.text
self.directory = self.find_directory.text
self.filename = self.find_file.text
self.csv = self.generate_file.text
def go_to_examine(self):
ExamineIssuesScreen.issueFile = (
self.examine_directory.text + "/" + self.examine_file.text
)
ExamineIssuesScreen.start = self.start
ExamineIssuesScreen.end = self.end
ExamineIssuesScreen.initiate_screen(ExamineIssuesScreen)
def get_examine_inputs(self):
main_screen = screen_manager.get_screen("mainScreen")
ExamineIssuesScreen.directory = main_screen.examine_directory.text
ExamineIssuesScreen.issueFile = main_screen.examine_file.text
ExamineIssuesScreen.start = self.start
ExamineIssuesScreen.end = self.end
def get_generate_inputs(self):
main_screen = screen_manager.get_screen("mainScreen")
self.preference = main_screen.generate_pref.text
masterDict["preference_file"] = self.preference
self.directory = main_screen.generate_directory.text
self.csv = main_screen.generate_file.text
# These are the dates at the top of the screen
self.start = main_screen.startDate.text
self.end = main_screen.endDate.text
# These are the dates for creating a csv file internally
self.generate_start = main_screen.generate_startDay.text
self.generate_end = main_screen.generate_endDay.text
self.generate_start_after = self.ids.generate_start_after_id.state
self.generate_end_before = self.ids.generate_end_before_id.state
# These are the target constraings for creating a csv internally
self.generate_network = ",".join(
[x.strip() for x in main_screen.generate_net.text.split(",")]
)
self.generate_station = main_screen.generate_sta.text
self.generate_location = main_screen.generate_loc.text
self.generate_channel = main_screen.generate_cha.text
# Do we need to generate a CSV file first? Yes if using internal ticketing system:
self.generate_csv_state = self.ids.generate_internal_id.active
def go_to_thresholds(self):
ThresholdsScreen.go_to_thresholdsLayout(ThresholdsScreen)
def go_to_preferences(self):
PreferencesScreen.go_to_preferencesLayout(PreferencesScreen)
def autofill_pref(self, preferenceFile):
if os.path.isfile(preferenceFile):
try:
with open(preferenceFile) as f:
local_dict = locals()
exec(
compile(f.read(), preferenceFile, "exec"), globals(), local_dict
)
self.startDate.text = local_dict["startday"]
self.endDate.text = local_dict["endday"]
self.find_file.text = os.path.basename(local_dict["outfile"])
self.examine_file.text = os.path.basename(local_dict["outfile"])
file_directory = os.path.dirname(local_dict["outfile"]).replace(
os.getcwd(), "./"
)
self.find_directory.text = file_directory
self.examine_directory.text = file_directory
self.generate_directory.text = file_directory
# self.examine_file.text = local_dict["outfile"]
self.find_net.text = local_dict["network"]
self.query_net.text = local_dict["network"]
self.find_sta.text = local_dict["station"]
self.query_sta.text = local_dict["station"]
self.find_loc.text = local_dict["location"]
self.query_loc.text = local_dict["location"]
self.find_cha.text = local_dict["channels"]
self.query_cha.text = local_dict["channels"]
# full_csv = os.path.basename(local_dict["csvfile"])
self.generate_file.text = os.path.basename(local_dict["csvfile"])
except:
self.warning_popup("WARNING: Could not read selected Preference File")
else:
self.warning_popup("WARNING: Preference File not found")
def dismiss_popup(self, *kwargs):
masterDict["_popup"].dismiss()
def dismiss_warning_popup(self, *kwargs):
masterDict["warning_popup"].dismiss()
def dismiss_csv_popup(self, *kwargs):
masterDict["_popup"].dismiss()
self.generate_report_pt2()
def dismiss_html_popup(self, *kwargs):
masterDict["_html_popup"].dismiss()
def pref_load(self):
content = LoadDialog(load=self.load_pref, cancel=self.dismiss_popup)
masterDict["_popup"] = Popup(
title="Load file", content=content, size_hint=(0.9, 0.9)
)
masterDict["_popup"].open()
def file_load(self):
content = LoadDialog(load=self.load_file, cancel=self.dismiss_popup)
masterDict["_popup"] = Popup(
title="Load file", content=content, size_hint=(0.9, 0.9)
)
masterDict["_popup"].open()
def load_pref(self, path, filename):
try:
filename = filename[0].replace(os.getcwd(), ".")
self.find_pref.text = filename
self.examine_pref.text = filename
self.query_pref.text = filename
self.generate_pref.text = filename
masterDict["preference_file"] = filename
except:
self.warning_popup("WARNING: No file selected")
self.dismiss_popup()
def load_file(self, path, filename):
try:
file_directory = os.path.dirname(filename[0].replace(os.getcwd(), "."))
self.find_directory.text = file_directory
self.examine_directory.text = file_directory
self.generate_directory.text = file_directory
self.find_file.text = os.path.basename(filename[0])
self.examine_file.text = os.path.basename(filename[0])
ExamineIssuesScreen.issueFile = self.examine_file.text
except Exception as e:
self.warning_popup("WARNING: %s" % e)
self.dismiss_popup()
def csv_load(self):
content = LoadDialog(load=self.load_csv, cancel=self.dismiss_popup)
masterDict["_popup"] = Popup(
title="Load file", content=content, size_hint=(0.9, 0.9)
)
masterDict["_popup"].open()
def load_csv(self, path, filename):
try:
file_directory = os.path.dirname(filename[0].replace(os.getcwd(), "."))
self.find_directory.text = file_directory
self.examine_directory.text = file_directory
self.generate_directory.text = file_directory
self.ids.csv_id.text = os.path.basename(filename[0])
except Exception as e:
self.warning_popup("WARNING: %s" % e)
self.dismiss_popup()
def find_issues(self):
self.get_find_inputs()
if self.start == "" or self.end == "":
self.warning_popup("WARNING: Start and End times required")
elif self.preference == "":
self.warning_popup("WARNING: Preference File required")
elif self.directory == "":
self.warning_popup("WARNING: Directory required")
elif self.filename == "":
self.warning_popup("WARNING: Issue File required")
elif self.network == "":
self.warning_popup("WARNING: Network required")
else:
if os.path.isfile(self.directory + "/" + self.filename):
self.fileType = self.directory + "/" + self.filename
content = OverwriteDialog(
dontDoIt=self.dismiss_popup, doIt=self.remove_file
)
masterDict["_popup"] = Popup(
title=self.filename, content=content, size_hint=(0.9, 0.9)
)
masterDict["_popup"].open()
else:
self.do_find()
def remove_file(self):
masterDict["_popup"].dismiss()
file = self.fileType
os.remove(file)
try:
if file == self.directory + "/" + self.filename:
self.do_find()
except:
pass
try:
if file == self.directory + "/" + self.csv:
doGenerate = self.generate_csv()
if doGenerate == 1:
self.generate_report_pt2()
except Exception as e:
self.warning_popup("Warning: could not generate final report")
def do_find(self):
self.get_find_inputs()
if not os.path.isfile(masterDict["metrics_file"]):
self.warning_popup(
"WARNING: Could not find file of EarthScope metrics: %s\nIf connected to the internet, this file can be generated by entering the Thresholds Editor"
% masterDict["metrics_file"]
)
return
if not os.path.isfile(masterDict["metadata_file"]):
self.warning_popup(
"WARNING: Could not find file of EarthScope metadata fields: %s\nIf connected to the internet, this file can be generated by entering the Thresholds Editor"
% masterDict["metadata_file"]
)
return
command = "python findIssues.py --start=" + self.start + " --end=" + self.end
if self.preference:
command = command + " --preference_file=" + self.preference
if self.network:
command = command + " --network=" + self.network
if self.stations:
command = command + " --stations=" + self.stations
if self.channels:
command = command + " --channels=" + self.channels
if self.locations:
command = command + " --locations=" + self.locations
if self.filename:
command = command + " --outfile=" + self.directory + "/" + self.filename
# pass along the metric files so that they don't have to be hardcoded elsewhere
command = command + " --thresholds_file=" + masterDict["thresholds_file"]
command = command + " --metrics_file=" + masterDict["metrics_file"]
command = command + " --metadata_file=" + masterDict["metadata_file"]
print(command)
os.system(command)
# Check file for any failed metrics
try:
with open("failedMetrics.txt", "r") as f:
self.failedMetrics = f.read().splitlines()
os.remove("failedMetrics.txt")
if len(self.failedMetrics) > 0:
failedMetricsList = list()
failedThresholdsList = list()
for line in self.failedMetrics:
if line.split(":")[0] == "threshold":
failedThresholdsList.append(line.split()[1])
elif line.split(":")[0] == "metric":
failedMetricsList.append(line.split()[1])
warningText = "WARNING: There were errors Finding Issues.\n\n"
if len(failedThresholdsList) > 0:
warningText = (
warningText
+ "THRESHOLDS\nThese thresholds were not found - this is likely because the threshold has been deleted (through the Edit Thresholds form)\nbut not removed from this Preference File (in the Threshold Groups):\n %s\n\n"
% "\n ".join(failedThresholdsList)
)
if len(failedMetricsList) > 0:
warningText = (
warningText
+ "METRICS\nThese metrics were unable to be retrieved: \n %s"
% "\n ".join(failedMetricsList)
)
self.warning_popup(warningText)
except:
self.warning_popup(
"WARNING: There was an error running FindIssues.py. Check the command line for more information."
)
def exit_confirmation(self, *kwargs):
content = ExitDialog(exit=ExitDialog.do_exit, cancel=self.dismiss_popup)
masterDict["_popup"] = Popup(
title="Confirm Exit", content=content, size_hint=(0.9, 0.9)
)
masterDict["_popup"].open()
def remove_dir(self):
masterDict["_html_popup"].dismiss()
if os.path.isfile(self.report_fullPath):
os.remove(self.report_fullPath)
if os.path.isdir(self.zipDir):
shutil.rmtree(self.zipDir)
print("Previous copy removed, generating new Report")
self.do_generate()
def get_ticket_inputs(self, *kwargs):
main_screen = screen_manager.get_screen("mainScreen")
masterDict["query_nets"] = main_screen.query_net.text
masterDict["query_stas"] = main_screen.query_sta.text
masterDict["query_locs"] = main_screen.query_loc.text
masterDict["query_chans"] = main_screen.query_cha.text
masterDict["query_start"] = main_screen.query_start.text
masterDict["query_start_before"] = main_screen.query_start_before.state
masterDict["query_end"] = main_screen.query_end.text
masterDict["query_end_before"] = main_screen.query_end_before.state
masterDict["query_status"] = main_screen.query_status_btn2.text
masterDict["query_tracker"] = main_screen.query_tracker_btn2.text
masterDict["query_cat"] = main_screen.query_category_btn2.text
masterDict["query_updated"] = main_screen.query_updated.text
masterDict["query_updated_before"] = main_screen.query_updated_before.state
def find_tickets(self):
self.get_ticket_inputs(self)
self.grab_tickets(self)
try:
if not masterDict["query_start"] == "":
datetime.datetime.strptime(masterDict["query_start"], "%Y-%m-%d")
if not masterDict["query_end"] == "":
datetime.datetime.strptime(masterDict["query_end"], "%Y-%m-%d")
if not masterDict["query_updated"] == "":
datetime.datetime.strptime(masterDict["query_updated"], "%Y-%m-%d")
except:
self.warning_popup(
"WARNING: Dates must be formatted YYYY-mm-dd - improper dates have been ignored"
)
SelectedTicketsScreen.go_to_selectedTickets(SelectedTicketsScreen)
def grab_tickets(self, *kwargs):
# Decided it would be easier to be nimble with the querying if it pulls back all tickets
# and then subsets from there, rather than building a complex sql query that accounts for
# all of the different ways that channels (in particular) may be listed/grouped
# Pull back tickets, subsetting here for status, category, tracker, and dates (if applicable)
SQL = "SELECT * FROM tickets WHERE "
if not masterDict["query_status"] == "-":
SQL = SQL + "AND status = '" + masterDict["query_status"] + "' "
if not masterDict["query_tracker"] == "-":
SQL = SQL + "AND tracker = '" + masterDict["query_tracker"] + "' "
if not masterDict["query_cat"] == "-":
SQL = SQL + "AND category = '" + masterDict["query_cat"] + "' "
if not masterDict["query_start"] == "":
if masterDict["query_start_before"] == "down":
SQL = (
SQL
+ "AND (start_date <= '"
+ masterDict["query_start"]
+ "' OR start_date ='') "
)
else:
SQL = (
SQL
+ "AND (start_date >= '"
+ masterDict["query_start"]
+ "' OR start_date ='') "
)
if not masterDict["query_end"] == "":
if masterDict["query_end_before"] == "down":
SQL = (
SQL
+ "AND (end_date <= '"
+ masterDict["query_end"]
+ "' OR end_date ='') "
)
else:
SQL = (
SQL
+ "AND (end_date >= '"
+ masterDict["query_end"]
+ "' OR end_date ='') "
)
if not masterDict["query_updated"] == "":
if masterDict["query_updated_before"] == "down":
SQL = (
SQL
+ "AND (updated <= '"
+ masterDict["query_updated"]
+ "' OR updated ='') "
)
else:
SQL = (
SQL
+ "AND (updated >= '"
+ masterDict["query_updated"]
+ "' OR updated ='') "
)
if SQL.endswith("WHERE "):
SQL = SQL.replace("WHERE", "")
else:
SQL = SQL.replace("WHERE AND", "WHERE")
try:
conn = NewTicketScreen.create_connection(NewTicketScreen, database)
if not conn == None:
allTickets = pd.read_sql_query(SQL, conn)
conn.close()
else:
self.warning_popup("WARNING: Could not retrieve tickets")
allTickets = ""
masterDict["tickets"] = ""
return
except:
self.warning_popup("WARNING: Could not retrieve tickets")
masterDict["tickets"] = ""
return
try:
# convert any cases of BH[EHZ] (for example) to lists
for ind, row in allTickets.iterrows():
# network(s)
networks = reportUtils.expandCodes(row["network"])
allTickets.at[ind, "networks"] = networks
# station(s)
stations = reportUtils.expandCodes(row["station"])
allTickets.at[ind, "stations"] = stations
# location(s)
locations = reportUtils.expandCodes(row["location"])
allTickets.at[ind, "locations"] = locations
# channel(s)
channels = reportUtils.expandCodes(row["channel"])
allTickets.at[ind, "channels"] = channels
# Now start subsetting
subsettedTickets = pd.DataFrame(columns=allTickets.columns)
# Subset for networks
frames_to_concat = [] # list to hold all DataFrames to concatenate
for net in masterDict["query_nets"].split(","):
if net in ["", "*", "%", "???"]:
frames_to_concat.append(allTickets)
else:
filtered_all = allTickets[
allTickets["networks"].str.contains(
",%s," % net.replace("?", ".?").replace("*", ".*")
)
]
frames_to_concat.append(filtered_all)
filtered_subset = subsettedTickets[
subsettedTickets["networks"].str.match(r",\*,")
]
frames_to_concat.append(filtered_subset)
subsettedTickets = pd.concat(frames_to_concat, ignore_index=True)
# Subset for stations
frames_to_concat = []
for sta in masterDict["query_stas"].split(","):
if sta in ["", "*", "%", "???"]:
frames_to_concat.append(subsettedTickets)
else:
filtered_stas = subsettedTickets[
subsettedTickets["stations"].str.contains(
",%s," % sta.replace("?", ".?").replace("*", ".*")
)
]
frames_to_concat.append(filtered_stas)
star_stas = subsettedTickets[
subsettedTickets["stations"].str.match(r",\*,")
]
frames_to_concat.append(star_stas)
subsettedTickets = pd.concat(frames_to_concat, ignore_index=True)
# Subset for locations
frames_to_concat = []
for loc in masterDict["query_locs"].split(","):
if loc in ["", "*", "%", "???"]:
frames_to_concat.append(subsettedTickets)
else:
filtered_locs = subsettedTickets[
subsettedTickets["locations"].str.contains(
",%s," % loc.replace("?", ".?").replace("*", ".*")
)
]
frames_to_concat.append(filtered_locs)
star_locs = subsettedTickets[
subsettedTickets["locations"].str.match(r",\*,")
]
frames_to_concat.append(star_locs)
subsettedTickets = pd.concat(frames_to_concat, ignore_index=True)
# Subset for channels
frames_to_concat = []
for chan in masterDict["query_chans"].split(","):
if chan in ["", "*", "%", "???"]:
frames_to_concat.append(subsettedTickets)
else:
filtered_chans = subsettedTickets[
subsettedTickets["channels"].str.contains(
",%s," % chan.replace("?", ".?").replace("*", ".*")
)
]
frames_to_concat.append(filtered_chans)
star_chans = subsettedTickets[
subsettedTickets["channels"].str.match(r",\*,")
]
frames_to_concat.append(star_chans)
subsettedTickets = pd.concat(frames_to_concat, ignore_index=True)
subsettedTickets.drop_duplicates(inplace=True)
try:
masterDict["tickets"] = subsettedTickets.drop(
["networks", "stations", "locations", "channels"], axis=1
).sort_index(axis=0)
except:
try:
masterDict["tickets"] = pd.DataFrame(
columns=allTickets.columns
).drop(["networks", "stations", "locations", "channels"], axis=1)
except:
masterDict["tickets"] = ""
except Exception as e:
masterDict["tickets"] = ""
def go_To_NewTickets(self, *kwargs):
NewTicketScreen.go_to_newTicketsScreen(NewTicketScreen)
def generate_csv(self):
self.get_generate_inputs()
if self.csv == "":
self.warning_popup("WARNING: CSV File required")
return 0
if self.generate_directory == "":
self.warning_popup("WARNING: CSV Directory required")
return 0
with open(self.preference) as f:
local_dict = locals()
exec(compile(f.read(), self.preference, "exec"), globals(), local_dict)
try:
if not self.generate_start == "":
datetime.datetime.strptime(self.generate_start, "%Y-%m-%d")
if not self.generate_end == "":
datetime.datetime.strptime(self.generate_end, "%Y-%m-%d")
except:
self.warning_popup("WARNING: Dates must be formatted YYYY-mm-dd")
return
# Do we need to generate a CSV file first? Yes if using internal ticketing system:
self.generate_csv_state = self.ids.generate_internal_id.active
# Pull back tickets, subsetting here for status, category, tracker, and dates (if applicable)
SQL = "SELECT * FROM tickets WHERE "
statusList = list()
for status in ["New", "In Progress", "Resolved", "Closed", "Rejected"]:
if (
self.ids["generate_%s_id" % status.replace(" ", "_").lower()].state
== "down"
):
statusList.append(status)
statusList = "' OR status = '".join(statusList)
if statusList:
SQL = SQL + "(status = '" + statusList + "') AND "
trackerList = list()
for tracker in ["Data Problems", "Support"]:
if (
self.ids["generate_%s_id" % tracker.replace(" ", "_").lower()].state
== "down"
):
trackerList.append(tracker)
trackerList = "' OR tracker = '".join(trackerList)
if trackerList:
SQL = SQL + "(tracker = '" + trackerList + "') "
if not self.generate_start == "":
if self.generate_start_after == "down":
SQL = (
SQL
+ "AND (start_date >= '"
+ self.generate_start
+ "' OR start_date ='') "
)
else:
SQL = (
SQL
+ "AND (start_date <= '"
+ self.generate_start
+ "' OR start_date ='') "
)
if not self.generate_end == "":
if self.generate_end_before == "down":
SQL = (
SQL
+ "AND (end_date <= '"
+ self.generate_end
+ "' OR end_date ='') "
)
else:
SQL = (
SQL
+ "AND (end_date >= '"
+ self.generate_end
+ "' OR end_date ='') "
)
if SQL.endswith("WHERE "):
SQL = SQL.replace("WHERE", "")
else:
SQL = SQL.replace("WHERE AND", "WHERE")
try:
conn = NewTicketScreen.create_connection(NewTicketScreen, database)
if not conn == None:
allTickets = pd.read_sql_query(SQL, conn)
conn.close()
else:
self.warning_popup("WARNING: Could not retrieve tickets")
return
except:
self.warning_popup("WARNING: Could not retrieve tickets")
return
try:
# convert any cases of BH[EHZ] (for example) to lists
for ind, row in allTickets.iterrows():
# network(s)
networks = reportUtils.expandCodes(row["network"])
allTickets.at[ind, "networks"] = networks
# station(s)
stations = reportUtils.expandCodes(row["station"])
allTickets.at[ind, "stations"] = stations
# location(s)
locations = reportUtils.expandCodes(row["location"])
allTickets.at[ind, "locations"] = locations
# channel(s)
channels = reportUtils.expandCodes(row["channel"])
allTickets.at[ind, "channels"] = channels
# Now start subsetting
subsettedTickets = pd.DataFrame(columns=allTickets.columns)
frames_to_concat = []
for net in self.generate_network.split(","):
if net in ["", "*", "%", "???"]:
frames_to_concat.append(allTickets)
else:
filtered_all = allTickets[
allTickets["networks"].str.contains(
",%s," % net.replace("?", ".?").replace("*", ".*")
)
]
frames_to_concat.append(filtered_all)
filtered_subset = subsettedTickets[