files = (os.path.join(path, x) for x in os.listdir(path))
    return (f for f in files if os.path.isfile(f))

"""
This script is modified in this PR (http://example.com)
to set the corresponding `has_bibliography` flag to `False` for all citation formats whose CSL file do not
include a bibliography section. As a result, all such citation formats would not show up in OSF
citation widgets for users to choose.

NOTE:
As of August 25th, 2017, there are however THREE EXCEPTIONS:
"Bluebook Law Review", "Bluebook Law Review(2)" and "Bluebook Inline" shares a
special CSL file ('website/static/bluebook.cls'), in which a bibliography section is defined,
for rendering bibliographies even though their official CSL files (located in assets folder)
do not contain a bibliography section.
The side effect is that, upon parsing all the CSL files in the assets folder, these three citation
formats are marked as `has_bibliography=False`, preventing them from user selection on the front end.
Therefore, intervention is needed to manually "turn on" their 'has_bibliography' flag for them to show
on the citation widget.
"""

import os

from lxml import etree

from website import settings
from website.app import setup_django
setup_django()
from osf.models.citation import CitationStyle

def main():

    # drop all styles
    CitationStyle.objects.all().delete()

    total = 0

    for style_file in get_style_files(settings.CITATION_STYLES_PATH):
        with open(style_file, 'r') as f:
            try:
                root = etree.parse(f).getroot()
            except etree.XMLSyntaxError:
                continue
            total += 1
            namespace = root.nsmap.get(None)
            selector = '{{{ns}}}info/{{{ns}}}'.format(ns=namespace)

            # Required
            fields = {
                '_id': os.path.splitext(os.path.basename(style_file))[0],
                'title': root.find(selector + 'title').text,
                'has_bibliography': True if root.find(
                    '{{{ns}}}{tag}'.format(ns=namespace, tag='bibliography')) is not None else False
            }

            # Optional
            try:
                fields['short_title'] = root.find(selector + 'title-short').text
            except AttributeError:
                pass

            try:
                fields['summary'] = root.find(selector + 'summary').text
            except AttributeError:
                pass

            style = CitationStyle(**fields)
            style.save()

    return total

def get_style_files(path):

if __name__ == '__main__':
    total = main()
    print('Parsed {} styles'.format(total))


try:
                root = etree.parse(f).getroot()
            except etree.XMLSyntaxError:
                continue

"""
This script is modified in this PR (http://example.com)
to set the corresponding `has_bibliography` flag to `False` for all citation formats whose CSL file do not
include a bibliography section. As a result, all such citation formats would not show up in OSF
citation widgets for users to choose.

NOTE:
As of August 25th, 2017, there are however THREE EXCEPTIONS:
"Bluebook Law Review", "Bluebook Law Review(2)" and "Bluebook Inline" shares a
special CSL file ('website/static/bluebook.cls'), in which a bibliography section is defined,
for rendering bibliographies even though their official CSL files (located in assets folder)
do not contain a bibliography section.
The side effect is that, upon parsing all the CSL files in the assets folder, these three citation
formats are marked as `has_bibliography=False`, preventing them from user selection on the front end.
Therefore, intervention is needed to manually "turn on" their 'has_bibliography' flag for them to show
on the citation widget.
"""

import os

from lxml import etree

from website import settings
from website.app import setup_django
setup_django()
from osf.models.citation import CitationStyle

def main():

    # drop all styles
    CitationStyle.objects.all().delete()

    total = 0

    for style_file in get_style_files(settings.CITATION_STYLES_PATH):
        with open(style_file, 'r') as f:

            total += 1
            namespace = root.nsmap.get(None)
            selector = '{{{ns}}}info/{{{ns}}}'.format(ns=namespace)

            # Required
            fields = {
                '_id': os.path.splitext(os.path.basename(style_file))[0],
                'title': root.find(selector + 'title').text,
                'has_bibliography': True if root.find(
                    '{{{ns}}}{tag}'.format(ns=namespace, tag='bibliography')) is not None else False
            }

            # Optional
            try:
                fields['short_title'] = root.find(selector + 'title-short').text
            except AttributeError:
                pass

            try:
                fields['summary'] = root.find(selector + 'summary').text
            except AttributeError:
                pass

            style = CitationStyle(**fields)
            style.save()

    return total

def get_style_files(path):
    files = (os.path.join(path, x) for x in os.listdir(path))
    return (f for f in files if os.path.isfile(f))

if __name__ == '__main__':
    total = main()
    print('Parsed {} styles'.format(total))


from costar_task_plan.abstract import *

'''
GMM policy:
  - fit to training data of some sort
  - execution takes the current set of features
'''

class GmmPolicy(AbstractPolicy):

    def __init__(self, dataset):
        # TODO(cpaxton): fit to dataset

    '''
  Compute features if actor id is nonzero; use world
  '''

    def __call__(self, world, state, actor):
        pass


return float(slide_value /light_interval_dic[name] * (light_gap_dic[name]) + light_min_dic[name])

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from functools import partial
import glob
import copy
import os
from ui.mouse_event import ReferenceDialog

Lb_width = 100
Lb_height = 40
Lb_row_shift = 25
Lb_col_shift = 20
Lb_x = 110
Lb_y = 700

Tb_width = 150
Tb_height = 60
Tb_row_shift = 50
Tb_col_shift = 5
Tb_x = 150
Tb_y = 63

square_size = 100

attr_degree_list = [1.5, 2.5, 1., 1., 2, 1.7,0.93, 1.]

min_dic = {'Gender': 0, 'Glasses': 0, 'Yaw': -20, 'Pitch': -20, 'Baldness': 0, 'Beard': 0.0, 'Age': 0, 'Expression': 0}
max_dic = {'Gender': 1, 'Glasses': 1, 'Yaw': 20, 'Pitch': 20, 'Baldness': 1, 'Beard': 1, 'Age': 65, 'Expression': 1}
attr_interval = 80
interval_dic = {'Gender': attr_interval, 'Glasses': attr_interval, 'Yaw': attr_interval, 'Pitch': attr_interval,
                'Baldness': attr_interval, 'Beard': attr_interval, 'Age': attr_interval, 'Expression': attr_interval}
set_values_dic = {i: int(interval_dic[i]/2) for i in interval_dic}
gap_dic = {i: max_dic[i] - min_dic[i] for i in max_dic}

light_degree = 1.
light_min_dic = {'Left->Right': 0, 'Right->Left': 0, 'Down->Up': 0, 'Up->Down': 0, 'No light': 0, 'Front light': 0}
light_max_dic = {'Left->Right': light_degree, 'Right->Left': light_degree, 'Down->Up': light_degree, 'Up->Down': light_degree, 'No light': light_degree, 'Front light': light_degree}

light_interval = 80
light_interval_dic = {'Left->Right': light_interval, 'Right->Left': light_interval, 'Down->Up': light_interval,
                      'Up->Down': light_interval, 'No light': light_interval, 'Front light': light_interval}
light_set_values_dic = {i: 0 for i in light_interval_dic}
light_gap_dic = {i: light_max_dic[i] - light_min_dic[i] for i in light_max_dic}

def transfer_real_to_slide(name, real_value):
    return int((real_value - min_dic[name]) / (gap_dic[name]) * interval_dic[name])

def invert_slide_to_real(name, slide_value):
    return float(slide_value /interval_dic[name] * (gap_dic[name]) + min_dic[name])

def light_transfer_real_to_slide(name, real_value):
    return int((real_value - light_min_dic[name]) / (light_gap_dic[name]) * light_interval_dic[name])

def light_invert_slide_to_real(name, slide_value):

class Ui_Form(QWidget):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.setWindowTitle("Let's Party StyleFlow")
        Form.resize(2784, 1566)

        self.graphicsView = QtWidgets.QGraphicsView(self)
        self.graphicsView.setGeometry(QtCore.QRect(150, 150, 1028, 1028))
        self.graphicsView.setObjectName("graphicsView")

        self.lockView = QtWidgets.QGraphicsView(self)
        self.lockView.setGeometry(QtCore.QRect(150, 150, 1028, 1028))
        self.lockView.setObjectName("lockView")

        self.resultView = QtWidgets.QGraphicsView(self)
        self.resultView.setGeometry(QtCore.QRect(1324 - 50, 150, 1028, 1028))
        self.resultView.setObjectName("blendingView")

        self.referDialog = ReferenceDialog(self)
        self.referDialog.setObjectName('Reference Dialog')
        self.referDialog.setWindowTitle('Reference Image')
        self.referDialogImage = QtWidgets.QLabel(self.referDialog)
        self.referDialogImage.setFixedSize(1024, 1024)

        self.add_tool_buttons(Form)
        self.add_intermediate_results_button(Form)
        self.add_Parameters_widgets(Form)
        self.add_lighting_widgets(Form)

        QtCore.QMetaObject.connectSlotsByName(self)

    def add_tool_buttons(self, Form):
        KaustLogo = QtWidgets.QLabel(self)
        KaustLogo.setPixmap(QPixmap('icons/1999780_200.png').scaled(90, 90))
        KaustLogo.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 25, 110, 110))

        self.newButton = QtWidgets.QPushButton(Form)
        self.newButton.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 150, square_size, square_size))
        self.newButton.setObjectName("openButton")
        self.newButton.setIcon(QIcon('icons/add_new_document.png'))
        self.newButton.setIconSize(QSize(square_size, square_size))

        self.openButton = QtWidgets.QPushButton(Form)
        self.openButton.setGeometry(
            QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 150 + square_size * 1 + 25 * 1, square_size, square_size))
        self.openButton.setObjectName("openButton")
        self.openButton.setIcon(QIcon('icons/open.png'))
        self.openButton.setIconSize(QSize(square_size, square_size))

        self.fillButton = QtWidgets.QPushButton(Form)
        self.fillButton.setGeometry(
            QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 150 + square_size * 2 + 25 * 2, square_size, square_size))
        self.fillButton.setObjectName("fillButton")
        self.fillButton.setIcon(QIcon('icons/paint_can.png'))
        self.fillButton.setIconSize(QSize(square_size, square_size))

        self.brushButton = QtWidgets.QPushButton(Form)
        self.brushButton.setGeometry(
            QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 150 + square_size * 3 + 25 * 3, square_size, square_size))
        self.brushButton.setObjectName("brushButton")
        self.brushButton.setIcon(QIcon('icons/foot2.png'))
        self.brushButton.setIconSize(QSize(square_size, square_size))
        self.brushButton.clicked.connect(Form.lock_switch)
        self.brushButton.setStyleSheet("background-color: #85adad")

        self.undoButton = QtWidgets.QPushButton(Form)
        self.undoButton.setGeometry(
            QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 150 + square_size * 4 + 25 * 4, square_size, square_size))
        self.undoButton.setObjectName("undolButton")
        self.undoButton.setIcon(QIcon('icons/undo.png'))
        self.undoButton.setIconSize(QSize(square_size, square_size))

        self.saveButton = QtWidgets.QPushButton(Form)
        self.saveButton.setGeometry(
            QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 150 + square_size * 5 + 25 * 5, square_size, square_size))
        self.saveButton.setObjectName("saveButton")
        self.saveButton.setIcon(QIcon('icons/reset1.png'))
        self.saveButton.setIconSize(QSize(square_size, square_size))
        self.saveButton.clicked.connect(Form.reset_Wspace)

    def add_intermediate_results_button(self, Form):

        self.reset_snapshot_button = QtWidgets.QPushButton(Form)
        self.reset_snapshot_button.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60), 1211 + 100, 100, 100))
        self.reset_snapshot_button.setIcon(QIcon('icons/save.png'))
        self.reset_snapshot_button.setIconSize(QSize(100, 100))
        self.reset_snapshot_button.clicked.connect(Form.update_lock_scene)

        self.scrollArea = QtWidgets.QScrollArea(Form)
        self.scrollArea.setGeometry(QtCore.QRect(150 - 10, 1200 + 100, 2152 + 10, 155))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollArea.setAlignment(Qt.AlignCenter)
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 2250, 128))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)
        self.horizontalLayout.setSpacing(27)
        self.horizontalLayout.setAlignment(Qt.AlignLeft)

        self.style_button_list = []
        for i in range(Form.opt.max_result_snapshots):
            style_button = QtWidgets.QPushButton()
            style_button.setFixedSize(128, 128)
            style_button.setIcon(QIcon())
            style_button.setIconSize(QSize(128, 128))
            style_button.clicked.connect(partial(Form.show_his_image, i))
            style_button.snap_shot_name = None
            style_button.setStyleSheet("background-color: transparent")
            self.style_button_list.append(style_button)
            self.horizontalLayout.addWidget(style_button)

        self.scrollArea.setWidget(self.scrollAreaWidgetContents)

    def add_Parameters_widgets(self,Form):

        self.formGroupBox1 = QtWidgets.QGroupBox("Attributes", Form)
        self.formGroupBox1.setGeometry(QtCore.QRect(2350-4, 130 +2, 400, 550))
        formlayout1 = QtWidgets.QFormLayout()

        formlayout1.setFormAlignment(Qt.AlignCenter)
        formlayout1.setVerticalSpacing(20)

        self.slider_list = []

        for j, i in enumerate(self.attr_order):
            slider = QtWidgets.QSlider(Form)
            slider.setOrientation(QtCore.Qt.Horizontal)
            slider.setMinimum(0)
            slider.setObjectName(i)
            slider.setMaximum(interval_dic[i])
            slider.setValue(set_values_dic[i])

            slider.valueChanged.connect(partial(Form.real_time_editing_thread, j))

            slider_vbox = QtWidgets.QVBoxLayout()
            slider_hbox = QtWidgets.QHBoxLayout()
            slider_vbox.setSpacing(0)
            label_minimum = QtWidgets.QLabel()
            label_minimum.setAlignment(Qt.AlignLeft)
            label_minimum.setText(str(min_dic[i]))
            label_maximum = QtWidgets.QLabel()
            label_maximum.setAlignment(Qt.AlignRight)
            label_maximum.setText(str(max_dic[i]))

            slider_vbox.addWidget(slider)
            slider_vbox.addLayout(slider_hbox)
            slider_hbox.addWidget(label_minimum)
            slider_hbox.addWidget(label_maximum)
            slider_vbox.addStretch()

            self.slider_list.append(slider)
            label = QtWidgets.QLabel(i + ':')
            font = label.font()
            font.setPointSize(12)
            label.setFont(font)

            formlayout1.addRow(label, slider_vbox)

        self.formGroupBox1.setLayout(formlayout1)

    def add_lighting_widgets(self,Form):

        self.formGroupBox2 = QtWidgets.QGroupBox("Lighting", Form)
        self.formGroupBox2.setGeometry(QtCore.QRect(2350-4, 800 + 20 + 4, 400, 350))
        formlayout2 = QtWidgets.QFormLayout()

        formlayout2.setFormAlignment(Qt.AlignCenter)
        formlayout2.setVerticalSpacing(23)

        self.lighting_slider_list = []

        for j, i in enumerate(self.lighting_order):
            slider = QtWidgets.QSlider(Form)
            slider.setOrientation(QtCore.Qt.Horizontal)
            slider.setMinimum(0)
            slider.setObjectName(i)
            slider.setMaximum(light_interval_dic[i])
            slider.setValue(0)

            slider.valueChanged.connect(partial(Form.real_time_light_thread, j))

            self.lighting_slider_list.append(slider)
            label = QtWidgets.QLabel(i + ':')
            font = label.font()
            font.setPointSize(12)
            label.setFont(font)

            formlayout2.addRow(label, slider)

        self.formGroupBox2.setLayout(formlayout2)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())


data_dir="data"
    fnames = (os.path.join(data_dir, "cifar10_train.rec"),
              os.path.join(data_dir, "cifar10_val.rec"))
    download_file('http://example.com', fnames[1])
    download_file('http://example.com', fnames[0])
    return fnames

import os
import argparse
import logging
logging.basicConfig(level=logging.DEBUG)
from common import find_mxnet, data, fit
from common.util import download_file
import mxnet as mx
from symbols import sparse_softmax,mixup
def download_cifar10():

if __name__ == '__main__':
    # download data
    (train_fname, val_fname) = download_cifar10()

    # parse args
    parser = argparse.ArgumentParser(description="train cifar10",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    fit.add_fit_args(parser)
    data.add_data_args(parser)
    data.add_data_aug_args(parser)
    data.set_data_aug_level(parser, 2)
    parser.set_defaults(
        # network
        network        = 'resnet_mixup',
        num_layers     = 50,
        # data
        data_train     = train_fname,
        data_val       = val_fname,
        num_classes    = 10,
        num_examples  = 50000,
        image_shape    = '3,28,28',
        pad_size       = 4,
        # train
        batch_size     = 128,
        num_epochs     = 300,
        lr             = 0.7,
        lr_step_epochs = '10,100,200',
        is_train = True
    )
    args = parser.parse_args()

    # load network
    from importlib import import_module
    net = import_module('symbols.'+args.network)
    sym = net.get_symbol(**vars(args))

    # train
    fit.fit(args, sym, data.get_rec_iter,is_train = True)


ASTNode.__init__(self, line, column)
        self.decList = []
        if initialObj:
            self.decList.append(initialObj)
        self.graph_ref = graph_ref

from parse.ast_node import ASTNode
from TAC.quadruple import *
from TAC.tac_enum import *
from parse.symbol_table import *

'''declaration  :     ID ID PORCENTAJE ROWTYPE PUNTOCOMA
                    | ID ID PUNTO ID PORCENTAJE TYPE PUNTOCOMA
                    | ID RECORD PUNTOCOMA
                    | ID constant_opt type collate_opt not_null_opt expression_opt PUNTOCOMA
                    | ID ALIAS FOR DOLLAR ENTERO PUNTOCOMA'''
class Declaration(ASTNode):
    # Var declaration for plpgsql
    def __init__(self, name, is_constant, type_, allow_null, exp, aliasfor, line, column, graph_ref):
        ASTNode.__init__(self, line, column)
        self.name = name
        self.exp = exp
        self.alias = aliasfor #index of parameter alias
        self.type_ = type_
        self.graph_ref = graph_ref
        self.default = None
        #set the dafult values by type:
        if self.type_ in ['SMALLINT','INTEGER', 'BIGINT']:
            self.default = 0
        if self.type_ in ['DECIMAL', 'NUMERIC', 'REAL', 'DOUBLE', 'MONEY']:
            self.default = 0.0
        if self.type_ in ['CARACTER', 'VARCHAR', 'CHARACTER', 'CHAR', 'TEXT']:
            self.default = ''
        if self.type_ in ['BOOLEAN']:
            self.default = False

    def execute(self, table, tree):# this execute must return tac list
        super().execute(table, tree)
    #for this test tree will contains the thre address code list
    #pay atention in the order to call genrate function for each childnode because it will affect the TAC list (order of eleents)
    def generate(self, table, tree):
        this_tac = None
        if self.alias is None:
            #TODO:validate tacs len
            if self.exp is None:
                this_tac = Quadruple(None, str(self.default), None, self.name, OpTAC.ASSIGNMENT) #I put the word 'None' for TA python syntax to print the word None
            else:
                exp_tacs = self.exp.generate(table, tree)#should return the last quadruple generated
                this_tac = Quadruple(None,exp_tacs.res if isinstance(exp_tacs, Quadruple) else exp_tacs,None, self.name, OpTAC.ASSIGNMENT)
        else:
            this_tac = Quadruple(None, f'{getParamNameFormat()}{self.alias}', None, self.name, OpTAC.ASSIGNMENT)
        #now add this new TAC to the list
        tree.append(this_tac)
        return this_tac

class DeclarationList(ASTNode):
    def __init__(self, initialObj, line, column, graph_ref):

    def execute(self, table, tree):# this execute must return tac list
        super().execute(table, tree)
        self.generate(table, tree)
        return f'TAC genrated'

    def append(self, obj: Declaration):
        self.decList.append(obj)

    def generate(self, table, tree):
        tacs = []
        for i in self.decList:
            i.generate(table, tacs)
        print('***********This is the thre address code generated:*********')
        printL(tacs)
        #Do the optimization...
        print('*****************Optimization code generated:***************')
        optimi = DoOptimization(tacs)
        printL(optimi[0])
        print("RemovedItems:")
        printL(optimi[1])
        print('***************************TAC END**************************')
        #Do python code...

        return tree


if service == "skytech":
        return True, arg

def audit(arg):
    url = arg
    payload = 'admin/sysconfig_reg_page.aspx'
    verify_url = url +  payload
    code, head, res, errcode, _ = curl.curl2(verify_url)
    if code == 200 and 'txtUserRights' in res and "txtTitle" in res:
        security_info(verify_url)
        security_info(url + payload)

if __name__ == '__main__':

    audit(assign('skytech','http://example.com')[1])


DistributedElevatorExt.setupElevator(self)
        self.elevatorSphereNodePath.setY(-1.0)
        self.elevatorSphereNodePath.setZ(1.5)

from toontown.building.DistributedElevatorExt import DistributedElevatorExt

class DistributedCogdoElevatorExt(DistributedElevatorExt):

    def setupElevator(self):

    def getElevatorModel(self):
        return self.bldg.getCogdoElevatorNodePath()

    def getBldgDoorOrigin(self):
        return self.bldg.getCogdoDoorOrigin()

    def _getDoorsClosedInfo(self):
        return ('cogdoInterior', 'cogdoInterior')


# Created by: Prof. Valdecy Pereira, D.Sc.
# UFF - Universidade Federal Fluminense (Brazil)
# email:  example@nnthink.com
# Course: Metaheuristics
# Lesson: Improved Whale Optimization Algorithm

# Required Libraries
import numpy  as np
import math
import random
import os

# Function
def target_function():

# Function: Initialize Variables
def initial_position(hunting_party = 5, min_values = [-5,-5], max_values = [5,5], target_function = target_function):
    position = np.zeros((hunting_party, len(min_values)+1))
    for i in range(0, hunting_party):
        for j in range(0, len(min_values)):
             position[i,j] = random.uniform(min_values[j], max_values[j])
        position[i,-1] = target_function(position[i,0:position.shape[1]-1])
    return position

# Function: Initialize Alpha
def leader_position(dimension = 2, target_function = target_function):
    leader = np.zeros((1, dimension+1))
    for j in range(0, dimension):
        leader[0,j] = 0.0
    leader[0,-1] = target_function(leader[0,0:leader.shape[1]-1])
    return leader

# Function: Updtade Leader by Fitness
def update_leader(position, leader):
    for i in range(0, position.shape[0]):
        if (leader[0,-1] > position[i,-1]):
            for j in range(0, position.shape[1]):
                leader[0,j] = position[i,j]
    return leader

# Function: Updtade Position
def update_position(position, leader, a_linear_component = 2, b_linear_component = 1,  spiral_param = 1, min_values = [-5,-5], max_values = [5,5], target_function = target_function):
    for i in range(0, position.shape[0]):
            r1_leader = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
            r2_leader = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
            a_leader  = 2*a_linear_component*r1_leader - a_linear_component
            c_leader  = 2*r2_leader
            p         = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
            for j in range (0, len(min_values)):
                if (p < 0.5):
                    if (abs(a_leader) >= 1):
                        rand              = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
                        rand_leader_index = math.floor(position.shape[0]*rand);
                        x_rand            = position[rand_leader_index, :]
                        distance_x_rand   = abs(c_leader*x_rand[j] - position[i,j])
                        position[i,j]     = np.clip( x_rand[j] - a_leader*distance_x_rand, min_values[j],  max_values[j])
                    elif (abs(a_leader) < 1):
                        distance_leader   = abs(c_leader*leader[0,j] - position[i,j])
                        position[i,j]     = np.clip(leader[0,j] - a_leader*distance_leader, min_values[j],  max_values[j])
                elif (p >= 0.5):
                    distance_Leader       = abs(leader[0,j] - position[i,j])
                    rand                  = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
                    m_param               = (b_linear_component - 1)*rand + 1
                    position[i,j]         = np.clip( (distance_Leader*math.exp(spiral_param*m_param)*math.cos(m_param*2*math.pi) + leader[0,j]), min_values[j],  max_values[j])
            position[i,-1] = target_function(position[i,0:position.shape[1]-1])
    return position

# Function: Fitness
def fitness_function(position):
    fitness = np.zeros((position.shape[0], 2))
    for i in range(0, fitness.shape[0]):
        fitness[i,0] = 1/(1+ position[i,-1] + abs(position[:,-1].min()))
    fit_sum = fitness[:,0].sum()
    fitness[0,1] = fitness[0,0]
    for i in range(1, fitness.shape[0]):
        fitness[i,1] = (fitness[i,0] + fitness[i-1,1])
    for i in range(0, fitness.shape[0]):
        fitness[i,1] = fitness[i,1]/fit_sum
    return fitness

# Function: Selection
def roulette_wheel(fitness):
    ix = 0
    random = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
    for i in range(0, fitness.shape[0]):
        if (random <= fitness[i, 1]):
          ix = i
          break
    return ix

# Function: Offspring
def breeding(position, fitness, min_values = [-5,-5], max_values = [5,5], mu = 1, target_function = target_function):
    offspring = np.copy(position)
    for i in range (0, offspring.shape[0]):
        parent_1, parent_2 = roulette_wheel(fitness), roulette_wheel(fitness)
        while parent_1 == parent_2:
            parent_2 = random.sample(range(0, len(position) - 1), 1)[0]
        for j in range(0, offspring.shape[1] - 1):
            rand = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
            rand_b = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
            if (rand <= 0.5):
                b_offspring = 2*(rand_b)
                b_offspring = b_offspring**(1/(mu + 1))
            elif (rand > 0.5):
                b_offspring = 1/(2*(1 - rand_b))
                b_offspring = b_offspring**(1/(mu + 1))
            offspring[i,j] = np.clip(((1 + b_offspring)*position[parent_1, j] + (1 - b_offspring)*position[parent_2, j])/2, min_values[j], max_values[j])
            if(i < position.shape[0] - 1):
                offspring[i+1,j] = np.clip(((1 - b_offspring)*position[parent_1, j] + (1 + b_offspring)*position[parent_2, j])/2, min_values[j], max_values[j])
        offspring[i,-1] = target_function(offspring[i,0:offspring.shape[1]-1])
    return offspring

# iWOA Function
def improved_whale_optimization_algorithm(hunting_party = 5, spiral_param = 1,  mu = 1, min_values = [-5,-5], max_values = [5,5], iterations = 50, target_function = target_function):
    count    = 0
    position = initial_position(hunting_party = hunting_party, min_values = min_values, max_values = max_values, target_function = target_function)
    leader   = leader_position(dimension = len(min_values), target_function = target_function)
    while (count <= iterations):
        print('Iteration = ', count, ' f(x) = ', leader[0,-1])
        a_linear_component =  2 - count*( 2/iterations)
        b_linear_component = -1 + count*(-1/iterations)
        leader             = update_leader(position, leader)
        position           = update_position(position, leader, a_linear_component, b_linear_component, spiral_param, min_values, max_values, target_function)
        fitness            = fitness_function(position)
        position           = breeding(position, fitness, min_values, max_values, mu, target_function)
        leader             = update_leader(position, leader)
        count              = count + 1
    return leader


while parent_1 == parent_2:
            parent_2 = random.sample(range(0, len(position) - 1), 1)[0]

# Created by: Prof. Valdecy Pereira, D.Sc.
# UFF - Universidade Federal Fluminense (Brazil)
# email:  example@nnthink.com
# Course: Metaheuristics
# Lesson: Improved Whale Optimization Algorithm

# Required Libraries
import numpy  as np
import math
import random
import os

# Function
def target_function():
    return

# Function: Initialize Variables
def initial_position(hunting_party = 5, min_values = [-5,-5], max_values = [5,5], target_function = target_function):
    position = np.zeros((hunting_party, len(min_values)+1))
    for i in range(0, hunting_party):
        for j in range(0, len(min_values)):
             position[i,j] = random.uniform(min_values[j], max_values[j])
        position[i,-1] = target_function(position[i,0:position.shape[1]-1])
    return position

# Function: Initialize Alpha
def leader_position(dimension = 2, target_function = target_function):
    leader = np.zeros((1, dimension+1))
    for j in range(0, dimension):
        leader[0,j] = 0.0
    leader[0,-1] = target_function(leader[0,0:leader.shape[1]-1])
    return leader

# Function: Updtade Leader by Fitness
def update_leader(position, leader):
    for i in range(0, position.shape[0]):
        if (leader[0,-1] > position[i,-1]):
            for j in range(0, position.shape[1]):
                leader[0,j] = position[i,j]
    return leader

# Function: Updtade Position
def update_position(position, leader, a_linear_component = 2, b_linear_component = 1,  spiral_param = 1, min_values = [-5,-5], max_values = [5,5], target_function = target_function):
    for i in range(0, position.shape[0]):
            r1_leader = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
            r2_leader = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
            a_leader  = 2*a_linear_component*r1_leader - a_linear_component
            c_leader  = 2*r2_leader
            p         = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
            for j in range (0, len(min_values)):
                if (p < 0.5):
                    if (abs(a_leader) >= 1):
                        rand              = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
                        rand_leader_index = math.floor(position.shape[0]*rand);
                        x_rand            = position[rand_leader_index, :]
                        distance_x_rand   = abs(c_leader*x_rand[j] - position[i,j])
                        position[i,j]     = np.clip( x_rand[j] - a_leader*distance_x_rand, min_values[j],  max_values[j])
                    elif (abs(a_leader) < 1):
                        distance_leader   = abs(c_leader*leader[0,j] - position[i,j])
                        position[i,j]     = np.clip(leader[0,j] - a_leader*distance_leader, min_values[j],  max_values[j])
                elif (p >= 0.5):
                    distance_Leader       = abs(leader[0,j] - position[i,j])
                    rand                  = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
                    m_param               = (b_linear_component - 1)*rand + 1
                    position[i,j]         = np.clip( (distance_Leader*math.exp(spiral_param*m_param)*math.cos(m_param*2*math.pi) + leader[0,j]), min_values[j],  max_values[j])
            position[i,-1] = target_function(position[i,0:position.shape[1]-1])
    return position

# Function: Fitness
def fitness_function(position):
    fitness = np.zeros((position.shape[0], 2))
    for i in range(0, fitness.shape[0]):
        fitness[i,0] = 1/(1+ position[i,-1] + abs(position[:,-1].min()))
    fit_sum = fitness[:,0].sum()
    fitness[0,1] = fitness[0,0]
    for i in range(1, fitness.shape[0]):
        fitness[i,1] = (fitness[i,0] + fitness[i-1,1])
    for i in range(0, fitness.shape[0]):
        fitness[i,1] = fitness[i,1]/fit_sum
    return fitness

# Function: Selection
def roulette_wheel(fitness):
    ix = 0
    random = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
    for i in range(0, fitness.shape[0]):
        if (random <= fitness[i, 1]):
          ix = i
          break
    return ix

# Function: Offspring
def breeding(position, fitness, min_values = [-5,-5], max_values = [5,5], mu = 1, target_function = target_function):
    offspring = np.copy(position)
    for i in range (0, offspring.shape[0]):
        parent_1, parent_2 = roulette_wheel(fitness), roulette_wheel(fitness)

        for j in range(0, offspring.shape[1] - 1):
            rand = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
            rand_b = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1)
            if (rand <= 0.5):
                b_offspring = 2*(rand_b)
                b_offspring = b_offspring**(1/(mu + 1))
            elif (rand > 0.5):
                b_offspring = 1/(2*(1 - rand_b))
                b_offspring = b_offspring**(1/(mu + 1))
            offspring[i,j] = np.clip(((1 + b_offspring)*position[parent_1, j] + (1 - b_offspring)*position[parent_2, j])/2, min_values[j], max_values[j])
            if(i < position.shape[0] - 1):
                offspring[i+1,j] = np.clip(((1 - b_offspring)*position[parent_1, j] + (1 + b_offspring)*position[parent_2, j])/2, min_values[j], max_values[j])
        offspring[i,-1] = target_function(offspring[i,0:offspring.shape[1]-1])
    return offspring

# iWOA Function
def improved_whale_optimization_algorithm(hunting_party = 5, spiral_param = 1,  mu = 1, min_values = [-5,-5], max_values = [5,5], iterations = 50, target_function = target_function):
    count    = 0
    position = initial_position(hunting_party = hunting_party, min_values = min_values, max_values = max_values, target_function = target_function)
    leader   = leader_position(dimension = len(min_values), target_function = target_function)
    while (count <= iterations):
        print('Iteration = ', count, ' f(x) = ', leader[0,-1])
        a_linear_component =  2 - count*( 2/iterations)
        b_linear_component = -1 + count*(-1/iterations)
        leader             = update_leader(position, leader)
        position           = update_position(position, leader, a_linear_component, b_linear_component, spiral_param, min_values, max_values, target_function)
        fitness            = fitness_function(position)
        position           = breeding(position, fitness, min_values, max_values, mu, target_function)
        leader             = update_leader(position, leader)
        count              = count + 1
    return leader


today = fields.Date.context_today(self)
        for partner in self:
            partner.stop_count = len(partner.stop_ids.filtered(
                lambda p: ((p.start_date and (p.start_date <= today)) or
                           not p.start_date) and
                ((p.end_date and (p.end_date >= today)) or not p.end_date)
            ))

from odoo import api, fields, models
from odoo.models import expression
from odoo.tools.safe_eval import safe_eval

class ResPartner(models.Model):
    _inherit = 'res.partner'

    stop_ids = fields.One2many(
        comodel_name="fleet.route.stop.passenger", inverse_name="partner_id",
        string="Route Stop")
    stop_count = fields.Integer(
        compute='_compute_stop_count', string="# Route Stop",
        compute_sudo=True)

    @api.multi
    def write(self, values):
        result = super(ResPartner, self).write(values)
        if values.get("bus_passenger") == "no":
            self.stop_ids.filtered(lambda s: not s.end_date).write({
                "end_date": fields.Date.context_today(self),
            })
        return result

    @api.multi
    @api.depends("stop_ids")
    def _compute_stop_count(self):

    @api.multi
    def button_open_partner_stops(self):
        self.ensure_one()
        action = self.env.ref(
            'fleet_route_school.action_fleet_route_stop_passenger')
        action_dict = action.read()[0] if action else {}
        passenger_stops = self.env['fleet.route.stop.passenger'].search([
            ('partner_id', 'in', self.ids)])
        domain = expression.AND([
            [('id', 'in', passenger_stops.ids)],
            safe_eval(action.domain or '[]')])
        action_dict['context'] = safe_eval(
            action_dict.get('context', '{}'))
        action_dict['context'].update({
            'search_default_partner_id': self.id,
            'default_partner_id': self.id,
        })
        action_dict.update({
            'domain': domain,
        })
        return action_dict


x, y, _ = data_binary_classification
    basis = Identity().fit(x)
    model_prefit = SSPOC(basis=basis)
    model_prefit.fit(x, y, prefit_basis=True, quiet=True)

    model_standard = SSPOC().fit(x, y, quiet=True)

    np.testing.assert_allclose(model_prefit.sensor_coef_, model_standard.sensor_coef_)

"""Tests for SSPOC class."""
import numpy as np
import pytest
from sklearn.datasets import make_classification
from sklearn.exceptions import NotFittedError
from sklearn.metrics import accuracy_score
from sklearn.utils.validation import check_is_fitted

from pysensors.basis import Identity
from pysensors.basis import RandomProjection
from pysensors.basis import SVD
from pysensors.classification import SSPOC

SEED = 15

@pytest.fixture
def data_binary_classification():
    x, y = make_classification(n_classes=2, random_state=SEED)
    l1_penalty = 1
    return x, y, l1_penalty

@pytest.fixture
def data_multiclass_classification():
    x, y = make_classification(n_classes=5, n_informative=5, random_state=SEED)
    l1_penalty = 0.03
    return x, y, l1_penalty

def test_not_fitted(data_binary_classification):
    x, y, _ = data_binary_classification
    model = SSPOC()

    # Shouldn't be able to call any of these methods before fitting
    with pytest.raises(NotFittedError):
        model.predict(x)
    with pytest.raises(NotFittedError):
        model.update_sensors(n_sensors=5)
    with pytest.raises(NotFittedError):
        model.selected_sensors

def test_prefit_basis(data_binary_classification):

@pytest.mark.parametrize(
    "data",
    [
        pytest.lazy_fixture("data_binary_classification"),
        pytest.lazy_fixture("data_multiclass_classification"),
    ],
)
def test_initialize_with_n_sensors(data):
    x, y, l1_penalty = data
    n_sensors = 3
    model = SSPOC(n_sensors=n_sensors, l1_penalty=l1_penalty).fit(x, y, quiet=True)

    assert len(model.selected_sensors) == n_sensors
    assert model.n_sensors == n_sensors

@pytest.mark.parametrize(
    "data",
    [
        pytest.lazy_fixture("data_binary_classification"),
        pytest.lazy_fixture("data_multiclass_classification"),
    ],
)
def test_initialize_with_threshold(data):
    x, y, l1_penalty = data
    max_sensors = x.shape[1]
    model = SSPOC(threshold=0, l1_penalty=l1_penalty).fit(x, y, quiet=True)

    assert len(model.selected_sensors) == max_sensors
    assert model.n_sensors == max_sensors

@pytest.mark.parametrize("n_sensors", [3, 0])
@pytest.mark.parametrize(
    "data",
    [
        pytest.lazy_fixture("data_binary_classification"),
        pytest.lazy_fixture("data_multiclass_classification"),
    ],
)
def test_update_n_sensors(data, n_sensors):
    x, y, l1_penalty = data
    model = SSPOC(l1_penalty=l1_penalty).fit(x, y, quiet=True)

    model.update_sensors(n_sensors=n_sensors, quiet=True)
    assert len(model.selected_sensors) == n_sensors
    assert model.n_sensors == n_sensors

@pytest.mark.parametrize(
    "data",
    [
        pytest.lazy_fixture("data_binary_classification"),
        pytest.lazy_fixture("data_multiclass_classification"),
    ],
)
def test_update_threshold(data):
    x, y, l1_penalty = data

    model = SSPOC(threshold=0.01, l1_penalty=l1_penalty).fit(x, y, quiet=True)
    nnz = len(model.selected_sensors)

    # Larger threshold should result in fewer sensors
    model.update_sensors(threshold=1, quiet=True)
    assert len(model.selected_sensors) < nnz

@pytest.mark.parametrize(
    "data",
    [
        pytest.lazy_fixture("data_binary_classification"),
        pytest.lazy_fixture("data_multiclass_classification"),
    ],
)
def test_large_threshold(data):
    x, y, l1_penalty = data
    model = SSPOC(l1_penalty=l1_penalty).fit(x, y, quiet=True)

    model.update_sensors(threshold=10, quiet=True)
    assert len(model.selected_sensors) == 0
    assert model.n_sensors == 0

def test_bad_update_sensors_input(data_binary_classification):
    x, y, _ = data_binary_classification
    model = SSPOC().fit(x, y, quiet=True)

    with pytest.raises(ValueError):
        model.update_sensors()

@pytest.mark.parametrize(
    "data, baseline_accuracy",
    [
        (pytest.lazy_fixture("data_binary_classification"), 0.55),
        (pytest.lazy_fixture("data_multiclass_classification"), 0.25),
    ],
)
def test_predict_accuracy(data, baseline_accuracy):
    x, y, l1_penalty = data
    model = SSPOC(threshold=0, l1_penalty=l1_penalty).fit(x, y, quiet=True)

    assert (
        accuracy_score(y, model.predict(x[:, model.selected_sensors]))
        > baseline_accuracy
    )

@pytest.mark.parametrize(
    "data",
    [
        pytest.lazy_fixture("data_binary_classification"),
        pytest.lazy_fixture("data_multiclass_classification"),
    ],
)
def test_dummy_predict(data):
    x, y, l1_penalty = data

    model = SSPOC(l1_penalty=l1_penalty).fit(x, y, quiet=True)
    model.update_sensors(n_sensors=0, xy=(x, y), quiet=True)

    assert model.n_sensors == 0
    # Test that model can still make predictions, albeit random ones
    # when it has no sensors to work with
    y_pred = model.predict(x)
    assert len(y_pred) == len(y)

@pytest.mark.parametrize(
    "data",
    [
        pytest.lazy_fixture("data_binary_classification"),
        pytest.lazy_fixture("data_multiclass_classification"),
    ],
)
@pytest.mark.parametrize(
    "basis", [Identity(), SVD(), RandomProjection(n_basis_modes=5)]
)
def test_basis_integration(basis, data):
    x, y, _ = data
    model = SSPOC(basis=basis, n_sensors=5)
    model.fit(x, y, quiet=True)

    check_is_fitted(model)

@pytest.mark.parametrize(
    "data, shape",
    [
        (pytest.lazy_fixture("data_binary_classification"), (20,)),
        (pytest.lazy_fixture("data_multiclass_classification"), (20, 5)),
    ],
)
def test_coefficient_shape(data, shape):
    x, y, _ = data
    model = SSPOC().fit(x, y, quiet=True)

    assert model.sensor_coef_.shape == shape

@pytest.mark.parametrize("basis", [SVD, RandomProjection])
def test_update_n_basis_modes_errors(basis, data_binary_classification):
    x, y, _ = data_binary_classification
    n_basis_modes = 5
    model = SSPOC(basis=basis(n_basis_modes=n_basis_modes))

    model.fit(x, y, quiet=True)

    with pytest.raises(ValueError):
        model.update_n_basis_modes(0, xy=(x, y))
    with pytest.raises(ValueError):
        model.update_n_basis_modes("5", xy=(x, y))
    with pytest.raises(ValueError):
        model.update_n_basis_modes(x.shape[0] + 1, xy=(x, y))

@pytest.mark.parametrize("basis", [SVD, RandomProjection])
def test_update_n_basis_modes_shape(basis, data_binary_classification):
    x, y, _ = data_binary_classification
    n_basis_modes_init = 10
    model = SSPOC(basis=basis(n_basis_modes=n_basis_modes_init))
    model.fit(x, y, quiet=True)
    assert model.basis.n_basis_modes == n_basis_modes_init
    assert model.basis_matrix_inverse_.shape[0] == n_basis_modes_init

    n_basis_modes = 5
    model.update_n_basis_modes(n_basis_modes, xy=(x, y), quiet=True)
    assert model.basis.n_basis_modes == n_basis_modes_init
    assert model.basis_matrix_inverse_.shape[0] == n_basis_modes

@pytest.mark.parametrize("basis", [SVD, RandomProjection])
def test_update_n_basis_modes_refit(basis, data_binary_classification):
    x, y, _ = data_binary_classification
    n_basis_modes = 5
    model = SSPOC(basis=basis(n_basis_modes=n_basis_modes))
    model.fit(x, y, quiet=True)
    assert model.basis_matrix_inverse_.shape[0] == n_basis_modes

    model.update_n_basis_modes(n_basis_modes + 1, (x, y), quiet=True)
    assert model.basis_matrix_inverse_.shape[0] == n_basis_modes + 1

@pytest.mark.parametrize("basis", [SVD, RandomProjection])
def test_update_n_basis_modes_unfit_basis(basis, data_binary_classification):
    x, y, _ = data_binary_classification
    n_basis_modes = 5
    model = SSPOC(basis=basis())
    model.update_n_basis_modes(n_basis_modes, (x, y), quiet=True)

    assert model.basis_matrix_inverse_.shape[0] == n_basis_modes

def test_sspoc_selector_equivalence(data_multiclass_classification):
    x, y, _ = data_multiclass_classification

    model = SSPOC().fit(x, y)

    np.testing.assert_array_equal(model.get_selected_sensors(), model.selected_sensors)


"""
    Convert base58 encoded string to bytes.
    """
    return base58.decode(string, alphabet=_ripple_alphabet)

from trezor.crypto import base58

# Ripple uses different 58 character alphabet than traditional base58
_ripple_alphabet = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"

def encode(data: bytes) -> str:
    """
    Convert bytes to base58 encoded string.
    """
    return base58.encode(data, alphabet=_ripple_alphabet)

def decode(string: str) -> bytes:

def encode_check(data: bytes, digestfunc=base58.sha256d_32) -> str:
    """
    Convert bytes to base58 encoded string, append checksum.
    """
    return encode(data + digestfunc(data))

def decode_check(string: str, digestfunc=base58.sha256d_32) -> bytes:
    """
    Convert base58 encoded string to bytes and verify checksum.
    """
    data = decode(string)
    return base58.verify_checksum(data, digestfunc)


from trezor.crypto import base58

# Ripple uses different 58 character alphabet than traditional base58
_ripple_alphabet = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"

def encode(data: bytes) -> str:
    """
    Convert bytes to base58 encoded string.
    """
    return base58.encode(data, alphabet=_ripple_alphabet)

def decode(string: str) -> bytes:
    """
    Convert base58 encoded string to bytes.
    """
    return base58.decode(string, alphabet=_ripple_alphabet)

def encode_check(data: bytes, digestfunc=base58.sha256d_32) -> str:
    """
    Convert bytes to base58 encoded string, append checksum.
    """

def decode_check(string: str, digestfunc=base58.sha256d_32) -> bytes:
    """
    Convert base58 encoded string to bytes and verify checksum.
    """
    data = decode(string)
    return base58.verify_checksum(data, digestfunc)


self.runT = Thread(target=self.methodInAThread, args=[num])
        self.runT.setDaemon(True)
        self.runT.start()
        print(self.runT)
        print('createThread():', self.runT.isAlive())

        # textBoxes are the Consumers of Queue data
        writeT = Thread(target=self.useQueues, daemon=True)
        writeT.start()

'''
Created on Jun 9, 2019
Ch08
@author: Burkhard
'''
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import Spinbox
from Ch08_Code.ToolTip import ToolTip
from threading import Thread
from time import sleep
from queue import Queue
from tkinter import filedialog as fd
from os import path
from tkinter import messagebox as mBox
from Ch08_Code.LanguageResources import I18N
from datetime import datetime
from pytz import all_timezones, timezone

# Module level GLOBALS
GLOBAL_CONST = 42

class OOP():
    def __init__(self):
        # Create instance
        self.win = tk.Tk()

        self.i18n = I18N('en')              # use English
        self.i18n = I18N('de')              # use German

        # Add a title
        self.win.title(self.i18n.title)
#         self.win.title("Python Graphical User Interface")    # w/out importing I18N

        # Disable resizing the window
        self.win.resizable(0,0)

        # Create a Queue
        self.guiQueue = Queue()

        self.createWidgets()

        # populate Tab 2 Entries
        self.defaultFileEntries()

        # create MySQL instance

    def defaultFileEntries(self):
        self.fileEntry.delete(0, tk.END)
        self.fileEntry.insert(0, 'Z:\\')        # bogus path
        self.fileEntry.config(state='readonly')

        self.netwEntry.delete(0, tk.END)
        self.netwEntry.insert(0, 'Z:\\Backup')  # bogus path

    # Combobox callback
    def _combo(self, val=0):
        value = self.combo.get()
        self.scr.insert(tk.INSERT, value + '\n')

    # Spinbox callback
    def _spin(self):
        value = self.spin.get()
        self.scr.insert(tk.INSERT, value + '\n')

    # Checkbox callback
    def checkCallback(self, *ignoredArgs):
        # only enable one checkbutton
        if self.chVarUn.get(): self.check3.configure(state='disabled')
        else:                  self.check3.configure(state='normal')
        if self.chVarEn.get(): self.check2.configure(state='disabled')
        else:                  self.check2.configure(state='normal')

    # Radiobutton callback function
    def radCall(self):
        radSel=self.radVar.get()
        if   radSel == 0: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[0])
        elif radSel == 1: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[1])
        elif radSel == 2: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[2])

    # Exit GUI cleanly
    def _quit(self):
        self.win.quit()
        self.win.destroy()
        exit()

    def methodInAThread(self, numOfLoops=10):
        for idx in range(numOfLoops):
            sleep(1)
            self.scr.insert(tk.INSERT, str(idx) + '\n')
        sleep(1)
        print('methodInAThread():', self.runT.isAlive())

    # Running methods in Threads
    def createThread(self, num):

    # Create Queue instance
    def useQueues(self):
        # Now using a class member Queue
        while True:
            qItem = self.guiQueue.get()
            print(qItem)
            self.scr.insert(tk.INSERT, qItem + '\n')

    # Button callback
    def insertQuote(self):
        title = self.bookTitle.get()
        page = self.pageNumber.get()
        quote = self.quote.get(1.0, tk.END)
        print(title)
        print(quote)
        self.mySQL.insertBooks(title, page, quote)

    # Button callback
    def getQuote(self):
        allBooks = self.mySQL.showBooks()
        print(allBooks)
        self.quote.insert(tk.INSERT, allBooks)

    # Button callback
    def modifyQuote(self):
        raise NotImplementedError("This still needs to be implemented for the SQL command.")

    # TZ Button callback
    def allTimeZones(self):
        for tz in all_timezones:
            self.scr.insert(tk.INSERT, tz + '\n')

    # TZ Local Button callback
    def localZone(self):
        from tzlocal import get_localzone
        self.scr.insert(tk.INSERT, get_localzone())

    # Format local US time with TimeZone info
    def getDateTime(self):
        fmtStrZone = "%Y-%m-%d %H:%M:%S %Z%z"
        # Get Coordinated Universal Time
        utc = datetime.now(timezone('UTC'))
        print(utc.strftime(fmtStrZone))

        # Convert UTC datetime object to Los Angeles TimeZone
        la = utc.astimezone(timezone('America/Los_Angeles'))
        print(la.strftime(fmtStrZone))

        # Convert UTC datetime object to New York TimeZone
        ny = utc.astimezone(timezone('America/New_York'))
        print(ny.strftime(fmtStrZone))

        # update GUI label with local Time and Zone

        # update GUI label with NY Time and Zone
        self.lbl2.set(ny.strftime(fmtStrZone))

    def createWidgets(self):
        tabControl = ttk.Notebook(self.win)     # Create Tab Control

        tab1 = ttk.Frame(tabControl)            # Create a tab
#         tabControl.add(tab1, text='MySQL')    # Add the tab -- COMMENTED OUT FOR CH08

        tab2 = ttk.Frame(tabControl)            # Add a second tab
        tabControl.add(tab2, text='Widgets')    # Make second tab visible

        tabControl.pack(expand=1, fill="both")  # Pack to make visible

        # We are creating a container frame to hold all other widgets
        self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ')
        self.mySQL.grid(column=0, row=0, padx=8, pady=4)

        # Creating a Label
        ttk.Label(self.mySQL, text="Book Title:").grid(column=0, row=0, sticky='W')

        # Adding a Textbox Entry widget
        book = tk.StringVar()
        self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book)
        self.bookTitle.grid(column=0, row=1, sticky='W')

        # Adding a Textbox Entry widget
        book1 = tk.StringVar()
        self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1)
        self.bookTitle1.grid(column=0, row=2, sticky='W')

        # Adding a Textbox Entry widget
        book2 = tk.StringVar()
        self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2)
        self.bookTitle2.grid(column=0, row=3, sticky='W')

        # Creating a Label
        ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber.grid(column=1, row=1, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber1.grid(column=1, row=2, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber2.grid(column=1, row=3, sticky='W')

        # Adding a Button
        self.action = ttk.Button(self.mySQL, text="Insert Quote", command=self.insertQuote)
        self.action.grid(column=2, row=1)

        # Adding a Button
        self.action1 = ttk.Button(self.mySQL, text="Get Quotes", command=self.getQuote)
        self.action1.grid(column=2, row=2)

        # Adding a Button
        self.action2 = ttk.Button(self.mySQL, text="Mody Quote", command=self.modifyQuote)
        self.action2.grid(column=2, row=3)

        # Add some space around each widget
        for child in self.mySQL.winfo_children():
            child.grid_configure(padx=2, pady=4)

        quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ')
        quoteFrame.grid(column=0, row=1, padx=8, pady=4)

        # Using a scrolled Text control
        quoteW  = 40; quoteH = 6
        self.quote = scrolledtext.ScrolledText(quoteFrame, width=quoteW, height=quoteH, wrap=tk.WORD)
        self.quote.grid(column=0, row=8, sticky='WE', columnspan=3)

        # Add some space around each widget
        for child in quoteFrame.winfo_children():
            child.grid_configure(padx=2, pady=4)

        # Tab Control 2
        # We are creating a container frame to hold all other widgets -- Tab2
        self.widgetFrame = ttk.LabelFrame(tab2, text=self.i18n.WIDGET_LABEL)
        self.widgetFrame.grid(column=0, row=0, padx=8, pady=4)

        # Creating three checkbuttons
        self.chVarDis = tk.IntVar()
        self.check1 = tk.Checkbutton(self.widgetFrame, text=self.i18n.disabled, variable=self.chVarDis, state='disabled')
        self.check1.select()
        self.check1.grid(column=0, row=0, sticky=tk.W)

        self.chVarUn = tk.IntVar()
        self.check2 = tk.Checkbutton(self.widgetFrame, text=self.i18n.unChecked, variable=self.chVarUn)
        self.check2.deselect()
        self.check2.grid(column=1, row=0, sticky=tk.W )

        self.chVarEn = tk.IntVar()
        self.check3 = tk.Checkbutton(self.widgetFrame, text=self.i18n.toggle, variable=self.chVarEn)
        self.check3.deselect()
        self.check3.grid(column=2, row=0, sticky=tk.W)

        # trace the state of the two checkbuttons
        self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())
        self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())

        # Radiobutton list
        colors = self.i18n.colors

        self.radVar = tk.IntVar()

        # Selecting a non-existing index value for radVar
        self.radVar.set(99)

        # Creating all three Radiobutton widgets within one loop
        for col in range(3):
            curRad = 'rad' + str(col)
            curRad = tk.Radiobutton(self.widgetFrame, text=colors[col], variable=self.radVar, value=col, command=self.radCall)
            curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3)
            # And now adding tooltips
            ToolTip(curRad, 'This is a Radiobutton control.')

        # Create a container to hold labels
        labelsFrame = ttk.LabelFrame(self.widgetFrame, text=self.i18n.labelsFrame)
        labelsFrame.grid(column=0, row=7, pady=6)

        # Place labels into the container element - vertically
        ttk.Label(labelsFrame, text=self.i18n.chooseNumber).grid(column=0, row=0)
        self.lbl2 = tk.StringVar()
        self.lbl2.set(self.i18n.label2)
        ttk.Label(labelsFrame, textvariable=self.lbl2).grid(column=0, row=1)

        # Add some space around each label
        for child in labelsFrame.winfo_children():
            child.grid_configure(padx=6, pady=1)

        number = tk.StringVar()
        self.combo = ttk.Combobox(self.widgetFrame, width=12, textvariable=number)
        self.combo['values'] = (1, 2, 4, 42, 100)
        self.combo.grid(column=1, row=7, sticky=tk.W)
        self.combo.current(0)
        self.combo.bind('<<ComboboxSelected>>', self._combo)

        # Adding a Spinbox widget using a set of values
        self.spin = Spinbox(self.widgetFrame, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin)
        self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1)

        # Using a scrolled Text control
        scrolW  = 40; scrolH = 1
        self.scr = scrolledtext.ScrolledText(self.widgetFrame, width=scrolW, height=scrolH, wrap=tk.WORD)
        self.scr.grid(column=0, row=8, sticky='WE', columnspan=3)

        # Adding a TZ Button
        self.allTZs = ttk.Button(self.widgetFrame,
                                 text=self.i18n.timeZones,
                                 command=self.allTimeZones)
        self.allTZs.grid(column=0, row=9, sticky='WE')

        # Adding local TZ Button
        self.localTZ = ttk.Button(self.widgetFrame,
                                  text=self.i18n.localZone,
                                  command=self.localZone)
        self.localTZ.grid(column=1, row=9, sticky='WE')

        # Adding getTime TZ Button
        self.dt = ttk.Button(self.widgetFrame,
                             text=self.i18n.getTime,
                             command=self.getDateTime)
        self.dt.grid(column=2, row=9, sticky='WE')

        # Create Manage Files Frame ------------------------------------------------
        mngFilesFrame = ttk.LabelFrame(tab2, text=self.i18n.mgrFiles)
        mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5)

        # Button Callback
        def getFileName():
            print('hello from getFileName')
            fDir  = path.dirname(__file__)
            fName = fd.askopenfilename(parent=self.win, initialdir=fDir)
            print(fName)
            self.fileEntry.config(state='enabled')
            self.fileEntry.delete(0, tk.END)
            self.fileEntry.insert(0, fName)

            if len(fName) > self.entryLen:
                self.fileEntry.config(width=len(fName) + 3)

        # Add Widgets to Manage Files Frame
        lb = ttk.Button(mngFilesFrame, text=self.i18n.browseTo, command=getFileName)
        lb.grid(column=0, row=0, sticky=tk.W)

        file = tk.StringVar()
        self.entryLen = scrolW - 4
        self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file)
        self.fileEntry.grid(column=1, row=0, sticky=tk.W)

        logDir = tk.StringVar()
        self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir)
        self.netwEntry.grid(column=1, row=1, sticky=tk.W)

        def copyFile():
            import shutil
            src = self.fileEntry.get()
            file = src.split('/')[-1]
            dst = self.netwEntry.get() + '\\'+ file
            try:
                shutil.copy(src, dst)
                mBox.showinfo('Copy File to Network', 'Succes: File copied.')
            except FileNotFoundError as err:
                mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err))
            except Exception as ex:
                mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex))

        cb = ttk.Button(mngFilesFrame, text=self.i18n.copyTo, command=copyFile)
        cb.grid(column=0, row=1, sticky=tk.E)

        # Add some space around each label
        for child in mngFilesFrame.winfo_children():
            child.grid_configure(padx=6, pady=6)

        # Creating a Menu Bar ==========================================================
        menuBar = Menu(tab1)
        self.win.config(menu=menuBar)

        # Add menu items
        fileMenu = Menu(menuBar, tearoff=0)
        fileMenu.add_command(label=self.i18n.new)
        fileMenu.add_separator()
        fileMenu.add_command(label=self.i18n.exit, command=self._quit)
        menuBar.add_cascade(label=self.i18n.file, menu=fileMenu)

        # Add another Menu to the Menu Bar and an item
        helpMenu = Menu(menuBar, tearoff=0)
        helpMenu.add_command(label=self.i18n.about)
        menuBar.add_cascade(label=self.i18n.help, menu=helpMenu)

        # Change the main windows icon
        self.win.iconbitmap('pyc.ico')

        # Using tkinter Variable Classes
        strData = tk.StringVar()
        strData.set('Hello StringVar')

        # It is not necessary to create a tk.StringVar()
        strData = tk.StringVar()
        strData = self.spin.get()

        # Place cursor into name Entry
        self.bookTitle.focus()

        # Add a Tooltip to the Spinbox
        ToolTip(self.spin, 'This is a Spin control.')

        # Add Tooltips to more widgets
        ToolTip(self.bookTitle, 'This is an Entry control.')
        ToolTip(self.action, 'This is a Button control.')
        ToolTip(self.scr,    'This is a ScrolledText control.')

# Start GUI
oop = OOP()
oop.win.mainloop()


while True:
            qItem = self.guiQueue.get()
            print(qItem)
            self.scr.insert(tk.INSERT, qItem + '\n')

'''
Created on Jun 9, 2019
Ch08
@author: Burkhard
'''
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import Spinbox
from Ch08_Code.ToolTip import ToolTip
from threading import Thread
from time import sleep
from queue import Queue
from tkinter import filedialog as fd
from os import path
from tkinter import messagebox as mBox
from Ch08_Code.LanguageResources import I18N
from datetime import datetime
from pytz import all_timezones, timezone

# Module level GLOBALS
GLOBAL_CONST = 42

class OOP():
    def __init__(self):
        # Create instance
        self.win = tk.Tk()

        self.i18n = I18N('en')              # use English
        self.i18n = I18N('de')              # use German

        # Add a title
        self.win.title(self.i18n.title)
#         self.win.title("Python Graphical User Interface")    # w/out importing I18N

        # Disable resizing the window
        self.win.resizable(0,0)

        # Create a Queue
        self.guiQueue = Queue()

        self.createWidgets()

        # populate Tab 2 Entries
        self.defaultFileEntries()

        # create MySQL instance

    def defaultFileEntries(self):
        self.fileEntry.delete(0, tk.END)
        self.fileEntry.insert(0, 'Z:\\')        # bogus path
        self.fileEntry.config(state='readonly')

        self.netwEntry.delete(0, tk.END)
        self.netwEntry.insert(0, 'Z:\\Backup')  # bogus path

    # Combobox callback
    def _combo(self, val=0):
        value = self.combo.get()
        self.scr.insert(tk.INSERT, value + '\n')

    # Spinbox callback
    def _spin(self):
        value = self.spin.get()
        self.scr.insert(tk.INSERT, value + '\n')

    # Checkbox callback
    def checkCallback(self, *ignoredArgs):
        # only enable one checkbutton
        if self.chVarUn.get(): self.check3.configure(state='disabled')
        else:                  self.check3.configure(state='normal')
        if self.chVarEn.get(): self.check2.configure(state='disabled')
        else:                  self.check2.configure(state='normal')

    # Radiobutton callback function
    def radCall(self):
        radSel=self.radVar.get()
        if   radSel == 0: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[0])
        elif radSel == 1: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[1])
        elif radSel == 2: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[2])

    # Exit GUI cleanly
    def _quit(self):
        self.win.quit()
        self.win.destroy()
        exit()

    def methodInAThread(self, numOfLoops=10):
        for idx in range(numOfLoops):
            sleep(1)
            self.scr.insert(tk.INSERT, str(idx) + '\n')
        sleep(1)
        print('methodInAThread():', self.runT.isAlive())

    # Running methods in Threads
    def createThread(self, num):
        self.runT = Thread(target=self.methodInAThread, args=[num])
        self.runT.setDaemon(True)
        self.runT.start()
        print(self.runT)
        print('createThread():', self.runT.isAlive())

        # textBoxes are the Consumers of Queue data
        writeT = Thread(target=self.useQueues, daemon=True)
        writeT.start()

    # Create Queue instance
    def useQueues(self):
        # Now using a class member Queue

    # Button callback
    def insertQuote(self):
        title = self.bookTitle.get()
        page = self.pageNumber.get()
        quote = self.quote.get(1.0, tk.END)
        print(title)
        print(quote)
        self.mySQL.insertBooks(title, page, quote)

    # Button callback
    def getQuote(self):
        allBooks = self.mySQL.showBooks()
        print(allBooks)
        self.quote.insert(tk.INSERT, allBooks)

    # Button callback
    def modifyQuote(self):
        raise NotImplementedError("This still needs to be implemented for the SQL command.")

    # TZ Button callback
    def allTimeZones(self):
        for tz in all_timezones:
            self.scr.insert(tk.INSERT, tz + '\n')

    # TZ Local Button callback
    def localZone(self):
        from tzlocal import get_localzone
        self.scr.insert(tk.INSERT, get_localzone())

    # Format local US time with TimeZone info
    def getDateTime(self):
        fmtStrZone = "%Y-%m-%d %H:%M:%S %Z%z"
        # Get Coordinated Universal Time
        utc = datetime.now(timezone('UTC'))
        print(utc.strftime(fmtStrZone))

        # Convert UTC datetime object to Los Angeles TimeZone
        la = utc.astimezone(timezone('America/Los_Angeles'))
        print(la.strftime(fmtStrZone))

        # Convert UTC datetime object to New York TimeZone
        ny = utc.astimezone(timezone('America/New_York'))
        print(ny.strftime(fmtStrZone))

        # update GUI label with local Time and Zone

        # update GUI label with NY Time and Zone
        self.lbl2.set(ny.strftime(fmtStrZone))

    def createWidgets(self):
        tabControl = ttk.Notebook(self.win)     # Create Tab Control

        tab1 = ttk.Frame(tabControl)            # Create a tab
#         tabControl.add(tab1, text='MySQL')    # Add the tab -- COMMENTED OUT FOR CH08

        tab2 = ttk.Frame(tabControl)            # Add a second tab
        tabControl.add(tab2, text='Widgets')    # Make second tab visible

        tabControl.pack(expand=1, fill="both")  # Pack to make visible

        # We are creating a container frame to hold all other widgets
        self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ')
        self.mySQL.grid(column=0, row=0, padx=8, pady=4)

        # Creating a Label
        ttk.Label(self.mySQL, text="Book Title:").grid(column=0, row=0, sticky='W')

        # Adding a Textbox Entry widget
        book = tk.StringVar()
        self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book)
        self.bookTitle.grid(column=0, row=1, sticky='W')

        # Adding a Textbox Entry widget
        book1 = tk.StringVar()
        self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1)
        self.bookTitle1.grid(column=0, row=2, sticky='W')

        # Adding a Textbox Entry widget
        book2 = tk.StringVar()
        self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2)
        self.bookTitle2.grid(column=0, row=3, sticky='W')

        # Creating a Label
        ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber.grid(column=1, row=1, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber1.grid(column=1, row=2, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber2.grid(column=1, row=3, sticky='W')

        # Adding a Button
        self.action = ttk.Button(self.mySQL, text="Insert Quote", command=self.insertQuote)
        self.action.grid(column=2, row=1)

        # Adding a Button
        self.action1 = ttk.Button(self.mySQL, text="Get Quotes", command=self.getQuote)
        self.action1.grid(column=2, row=2)

        # Adding a Button
        self.action2 = ttk.Button(self.mySQL, text="Mody Quote", command=self.modifyQuote)
        self.action2.grid(column=2, row=3)

        # Add some space around each widget
        for child in self.mySQL.winfo_children():
            child.grid_configure(padx=2, pady=4)

        quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ')
        quoteFrame.grid(column=0, row=1, padx=8, pady=4)

        # Using a scrolled Text control
        quoteW  = 40; quoteH = 6
        self.quote = scrolledtext.ScrolledText(quoteFrame, width=quoteW, height=quoteH, wrap=tk.WORD)
        self.quote.grid(column=0, row=8, sticky='WE', columnspan=3)

        # Add some space around each widget
        for child in quoteFrame.winfo_children():
            child.grid_configure(padx=2, pady=4)

        # Tab Control 2
        # We are creating a container frame to hold all other widgets -- Tab2
        self.widgetFrame = ttk.LabelFrame(tab2, text=self.i18n.WIDGET_LABEL)
        self.widgetFrame.grid(column=0, row=0, padx=8, pady=4)

        # Creating three checkbuttons
        self.chVarDis = tk.IntVar()
        self.check1 = tk.Checkbutton(self.widgetFrame, text=self.i18n.disabled, variable=self.chVarDis, state='disabled')
        self.check1.select()
        self.check1.grid(column=0, row=0, sticky=tk.W)

        self.chVarUn = tk.IntVar()
        self.check2 = tk.Checkbutton(self.widgetFrame, text=self.i18n.unChecked, variable=self.chVarUn)
        self.check2.deselect()
        self.check2.grid(column=1, row=0, sticky=tk.W )

        self.chVarEn = tk.IntVar()
        self.check3 = tk.Checkbutton(self.widgetFrame, text=self.i18n.toggle, variable=self.chVarEn)
        self.check3.deselect()
        self.check3.grid(column=2, row=0, sticky=tk.W)

        # trace the state of the two checkbuttons
        self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())
        self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())

        # Radiobutton list
        colors = self.i18n.colors

        self.radVar = tk.IntVar()

        # Selecting a non-existing index value for radVar
        self.radVar.set(99)

        # Creating all three Radiobutton widgets within one loop
        for col in range(3):
            curRad = 'rad' + str(col)
            curRad = tk.Radiobutton(self.widgetFrame, text=colors[col], variable=self.radVar, value=col, command=self.radCall)
            curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3)
            # And now adding tooltips
            ToolTip(curRad, 'This is a Radiobutton control.')

        # Create a container to hold labels
        labelsFrame = ttk.LabelFrame(self.widgetFrame, text=self.i18n.labelsFrame)
        labelsFrame.grid(column=0, row=7, pady=6)

        # Place labels into the container element - vertically
        ttk.Label(labelsFrame, text=self.i18n.chooseNumber).grid(column=0, row=0)
        self.lbl2 = tk.StringVar()
        self.lbl2.set(self.i18n.label2)
        ttk.Label(labelsFrame, textvariable=self.lbl2).grid(column=0, row=1)

        # Add some space around each label
        for child in labelsFrame.winfo_children():
            child.grid_configure(padx=6, pady=1)

        number = tk.StringVar()
        self.combo = ttk.Combobox(self.widgetFrame, width=12, textvariable=number)
        self.combo['values'] = (1, 2, 4, 42, 100)
        self.combo.grid(column=1, row=7, sticky=tk.W)
        self.combo.current(0)
        self.combo.bind('<<ComboboxSelected>>', self._combo)

        # Adding a Spinbox widget using a set of values
        self.spin = Spinbox(self.widgetFrame, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin)
        self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1)

        # Using a scrolled Text control
        scrolW  = 40; scrolH = 1
        self.scr = scrolledtext.ScrolledText(self.widgetFrame, width=scrolW, height=scrolH, wrap=tk.WORD)
        self.scr.grid(column=0, row=8, sticky='WE', columnspan=3)

        # Adding a TZ Button
        self.allTZs = ttk.Button(self.widgetFrame,
                                 text=self.i18n.timeZones,
                                 command=self.allTimeZones)
        self.allTZs.grid(column=0, row=9, sticky='WE')

        # Adding local TZ Button
        self.localTZ = ttk.Button(self.widgetFrame,
                                  text=self.i18n.localZone,
                                  command=self.localZone)
        self.localTZ.grid(column=1, row=9, sticky='WE')

        # Adding getTime TZ Button
        self.dt = ttk.Button(self.widgetFrame,
                             text=self.i18n.getTime,
                             command=self.getDateTime)
        self.dt.grid(column=2, row=9, sticky='WE')

        # Create Manage Files Frame ------------------------------------------------
        mngFilesFrame = ttk.LabelFrame(tab2, text=self.i18n.mgrFiles)
        mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5)

        # Button Callback
        def getFileName():
            print('hello from getFileName')
            fDir  = path.dirname(__file__)
            fName = fd.askopenfilename(parent=self.win, initialdir=fDir)
            print(fName)
            self.fileEntry.config(state='enabled')
            self.fileEntry.delete(0, tk.END)
            self.fileEntry.insert(0, fName)

            if len(fName) > self.entryLen:
                self.fileEntry.config(width=len(fName) + 3)

        # Add Widgets to Manage Files Frame
        lb = ttk.Button(mngFilesFrame, text=self.i18n.browseTo, command=getFileName)
        lb.grid(column=0, row=0, sticky=tk.W)

        file = tk.StringVar()
        self.entryLen = scrolW - 4
        self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file)
        self.fileEntry.grid(column=1, row=0, sticky=tk.W)

        logDir = tk.StringVar()
        self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir)
        self.netwEntry.grid(column=1, row=1, sticky=tk.W)

        def copyFile():
            import shutil
            src = self.fileEntry.get()
            file = src.split('/')[-1]
            dst = self.netwEntry.get() + '\\'+ file
            try:
                shutil.copy(src, dst)
                mBox.showinfo('Copy File to Network', 'Succes: File copied.')
            except FileNotFoundError as err:
                mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err))
            except Exception as ex:
                mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex))

        cb = ttk.Button(mngFilesFrame, text=self.i18n.copyTo, command=copyFile)
        cb.grid(column=0, row=1, sticky=tk.E)

        # Add some space around each label
        for child in mngFilesFrame.winfo_children():
            child.grid_configure(padx=6, pady=6)

        # Creating a Menu Bar ==========================================================
        menuBar = Menu(tab1)
        self.win.config(menu=menuBar)

        # Add menu items
        fileMenu = Menu(menuBar, tearoff=0)
        fileMenu.add_command(label=self.i18n.new)
        fileMenu.add_separator()
        fileMenu.add_command(label=self.i18n.exit, command=self._quit)
        menuBar.add_cascade(label=self.i18n.file, menu=fileMenu)

        # Add another Menu to the Menu Bar and an item
        helpMenu = Menu(menuBar, tearoff=0)
        helpMenu.add_command(label=self.i18n.about)
        menuBar.add_cascade(label=self.i18n.help, menu=helpMenu)

        # Change the main windows icon
        self.win.iconbitmap('pyc.ico')

        # Using tkinter Variable Classes
        strData = tk.StringVar()
        strData.set('Hello StringVar')

        # It is not necessary to create a tk.StringVar()
        strData = tk.StringVar()
        strData = self.spin.get()

        # Place cursor into name Entry
        self.bookTitle.focus()

        # Add a Tooltip to the Spinbox
        ToolTip(self.spin, 'This is a Spin control.')

        # Add Tooltips to more widgets
        ToolTip(self.bookTitle, 'This is an Entry control.')
        ToolTip(self.action, 'This is a Button control.')
        ToolTip(self.scr,    'This is a ScrolledText control.')

# Start GUI
oop = OOP()
oop.win.mainloop()


try:
                shutil.copy(src, dst)
                mBox.showinfo('Copy File to Network', 'Succes: File copied.')
            except FileNotFoundError as err:
                mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err))
            except Exception as ex:
                mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex))

'''
Created on Jun 9, 2019
Ch08
@author: Burkhard
'''
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import Spinbox
from Ch08_Code.ToolTip import ToolTip
from threading import Thread
from time import sleep
from queue import Queue
from tkinter import filedialog as fd
from os import path
from tkinter import messagebox as mBox
from Ch08_Code.LanguageResources import I18N
from datetime import datetime
from pytz import all_timezones, timezone

# Module level GLOBALS
GLOBAL_CONST = 42

class OOP():
    def __init__(self):
        # Create instance
        self.win = tk.Tk()

        self.i18n = I18N('en')              # use English
        self.i18n = I18N('de')              # use German

        # Add a title
        self.win.title(self.i18n.title)
#         self.win.title("Python Graphical User Interface")    # w/out importing I18N

        # Disable resizing the window
        self.win.resizable(0,0)

        # Create a Queue
        self.guiQueue = Queue()

        self.createWidgets()

        # populate Tab 2 Entries
        self.defaultFileEntries()

        # create MySQL instance

    def defaultFileEntries(self):
        self.fileEntry.delete(0, tk.END)
        self.fileEntry.insert(0, 'Z:\\')        # bogus path
        self.fileEntry.config(state='readonly')

        self.netwEntry.delete(0, tk.END)
        self.netwEntry.insert(0, 'Z:\\Backup')  # bogus path

    # Combobox callback
    def _combo(self, val=0):
        value = self.combo.get()
        self.scr.insert(tk.INSERT, value + '\n')

    # Spinbox callback
    def _spin(self):
        value = self.spin.get()
        self.scr.insert(tk.INSERT, value + '\n')

    # Checkbox callback
    def checkCallback(self, *ignoredArgs):
        # only enable one checkbutton
        if self.chVarUn.get(): self.check3.configure(state='disabled')
        else:                  self.check3.configure(state='normal')
        if self.chVarEn.get(): self.check2.configure(state='disabled')
        else:                  self.check2.configure(state='normal')

    # Radiobutton callback function
    def radCall(self):
        radSel=self.radVar.get()
        if   radSel == 0: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[0])
        elif radSel == 1: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[1])
        elif radSel == 2: self.widgetFrame.configure(text=self.i18n.WIDGET_LABEL + self.i18n.colorsIn[2])

    # Exit GUI cleanly
    def _quit(self):
        self.win.quit()
        self.win.destroy()
        exit()

    def methodInAThread(self, numOfLoops=10):
        for idx in range(numOfLoops):
            sleep(1)
            self.scr.insert(tk.INSERT, str(idx) + '\n')
        sleep(1)
        print('methodInAThread():', self.runT.isAlive())

    # Running methods in Threads
    def createThread(self, num):
        self.runT = Thread(target=self.methodInAThread, args=[num])
        self.runT.setDaemon(True)
        self.runT.start()
        print(self.runT)
        print('createThread():', self.runT.isAlive())

        # textBoxes are the Consumers of Queue data
        writeT = Thread(target=self.useQueues, daemon=True)
        writeT.start()

    # Create Queue instance
    def useQueues(self):
        # Now using a class member Queue
        while True:
            qItem = self.guiQueue.get()
            print(qItem)
            self.scr.insert(tk.INSERT, qItem + '\n')

    # Button callback
    def insertQuote(self):
        title = self.bookTitle.get()
        page = self.pageNumber.get()
        quote = self.quote.get(1.0, tk.END)
        print(title)
        print(quote)
        self.mySQL.insertBooks(title, page, quote)

    # Button callback
    def getQuote(self):
        allBooks = self.mySQL.showBooks()
        print(allBooks)
        self.quote.insert(tk.INSERT, allBooks)

    # Button callback
    def modifyQuote(self):
        raise NotImplementedError("This still needs to be implemented for the SQL command.")

    # TZ Button callback
    def allTimeZones(self):
        for tz in all_timezones:
            self.scr.insert(tk.INSERT, tz + '\n')

    # TZ Local Button callback
    def localZone(self):
        from tzlocal import get_localzone
        self.scr.insert(tk.INSERT, get_localzone())

    # Format local US time with TimeZone info
    def getDateTime(self):
        fmtStrZone = "%Y-%m-%d %H:%M:%S %Z%z"
        # Get Coordinated Universal Time
        utc = datetime.now(timezone('UTC'))
        print(utc.strftime(fmtStrZone))

        # Convert UTC datetime object to Los Angeles TimeZone
        la = utc.astimezone(timezone('America/Los_Angeles'))
        print(la.strftime(fmtStrZone))

        # Convert UTC datetime object to New York TimeZone
        ny = utc.astimezone(timezone('America/New_York'))
        print(ny.strftime(fmtStrZone))

        # update GUI label with local Time and Zone

        # update GUI label with NY Time and Zone
        self.lbl2.set(ny.strftime(fmtStrZone))

    def createWidgets(self):
        tabControl = ttk.Notebook(self.win)     # Create Tab Control

        tab1 = ttk.Frame(tabControl)            # Create a tab
#         tabControl.add(tab1, text='MySQL')    # Add the tab -- COMMENTED OUT FOR CH08

        tab2 = ttk.Frame(tabControl)            # Add a second tab
        tabControl.add(tab2, text='Widgets')    # Make second tab visible

        tabControl.pack(expand=1, fill="both")  # Pack to make visible

        # We are creating a container frame to hold all other widgets
        self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ')
        self.mySQL.grid(column=0, row=0, padx=8, pady=4)

        # Creating a Label
        ttk.Label(self.mySQL, text="Book Title:").grid(column=0, row=0, sticky='W')

        # Adding a Textbox Entry widget
        book = tk.StringVar()
        self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book)
        self.bookTitle.grid(column=0, row=1, sticky='W')

        # Adding a Textbox Entry widget
        book1 = tk.StringVar()
        self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1)
        self.bookTitle1.grid(column=0, row=2, sticky='W')

        # Adding a Textbox Entry widget
        book2 = tk.StringVar()
        self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2)
        self.bookTitle2.grid(column=0, row=3, sticky='W')

        # Creating a Label
        ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber.grid(column=1, row=1, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber1.grid(column=1, row=2, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber2.grid(column=1, row=3, sticky='W')

        # Adding a Button
        self.action = ttk.Button(self.mySQL, text="Insert Quote", command=self.insertQuote)
        self.action.grid(column=2, row=1)

        # Adding a Button
        self.action1 = ttk.Button(self.mySQL, text="Get Quotes", command=self.getQuote)
        self.action1.grid(column=2, row=2)

        # Adding a Button
        self.action2 = ttk.Button(self.mySQL, text="Mody Quote", command=self.modifyQuote)
        self.action2.grid(column=2, row=3)

        # Add some space around each widget
        for child in self.mySQL.winfo_children():
            child.grid_configure(padx=2, pady=4)

        quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ')
        quoteFrame.grid(column=0, row=1, padx=8, pady=4)

        # Using a scrolled Text control
        quoteW  = 40; quoteH = 6
        self.quote = scrolledtext.ScrolledText(quoteFrame, width=quoteW, height=quoteH, wrap=tk.WORD)
        self.quote.grid(column=0, row=8, sticky='WE', columnspan=3)

        # Add some space around each widget
        for child in quoteFrame.winfo_children():
            child.grid_configure(padx=2, pady=4)

        # Tab Control 2
        # We are creating a container frame to hold all other widgets -- Tab2
        self.widgetFrame = ttk.LabelFrame(tab2, text=self.i18n.WIDGET_LABEL)
        self.widgetFrame.grid(column=0, row=0, padx=8, pady=4)

        # Creating three checkbuttons
        self.chVarDis = tk.IntVar()
        self.check1 = tk.Checkbutton(self.widgetFrame, text=self.i18n.disabled, variable=self.chVarDis, state='disabled')
        self.check1.select()
        self.check1.grid(column=0, row=0, sticky=tk.W)

        self.chVarUn = tk.IntVar()
        self.check2 = tk.Checkbutton(self.widgetFrame, text=self.i18n.unChecked, variable=self.chVarUn)
        self.check2.deselect()
        self.check2.grid(column=1, row=0, sticky=tk.W )

        self.chVarEn = tk.IntVar()
        self.check3 = tk.Checkbutton(self.widgetFrame, text=self.i18n.toggle, variable=self.chVarEn)
        self.check3.deselect()
        self.check3.grid(column=2, row=0, sticky=tk.W)

        # trace the state of the two checkbuttons
        self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())
        self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())

        # Radiobutton list
        colors = self.i18n.colors

        self.radVar = tk.IntVar()

        # Selecting a non-existing index value for radVar
        self.radVar.set(99)

        # Creating all three Radiobutton widgets within one loop
        for col in range(3):
            curRad = 'rad' + str(col)
            curRad = tk.Radiobutton(self.widgetFrame, text=colors[col], variable=self.radVar, value=col, command=self.radCall)
            curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3)
            # And now adding tooltips
            ToolTip(curRad, 'This is a Radiobutton control.')

        # Create a container to hold labels
        labelsFrame = ttk.LabelFrame(self.widgetFrame, text=self.i18n.labelsFrame)
        labelsFrame.grid(column=0, row=7, pady=6)

        # Place labels into the container element - vertically
        ttk.Label(labelsFrame, text=self.i18n.chooseNumber).grid(column=0, row=0)
        self.lbl2 = tk.StringVar()
        self.lbl2.set(self.i18n.label2)
        ttk.Label(labelsFrame, textvariable=self.lbl2).grid(column=0, row=1)

        # Add some space around each label
        for child in labelsFrame.winfo_children():
            child.grid_configure(padx=6, pady=1)

        number = tk.StringVar()
        self.combo = ttk.Combobox(self.widgetFrame, width=12, textvariable=number)
        self.combo['values'] = (1, 2, 4, 42, 100)
        self.combo.grid(column=1, row=7, sticky=tk.W)
        self.combo.current(0)
        self.combo.bind('<<ComboboxSelected>>', self._combo)

        # Adding a Spinbox widget using a set of values
        self.spin = Spinbox(self.widgetFrame, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin)
        self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1)

        # Using a scrolled Text control
        scrolW  = 40; scrolH = 1
        self.scr = scrolledtext.ScrolledText(self.widgetFrame, width=scrolW, height=scrolH, wrap=tk.WORD)
        self.scr.grid(column=0, row=8, sticky='WE', columnspan=3)

        # Adding a TZ Button
        self.allTZs = ttk.Button(self.widgetFrame,
                                 text=self.i18n.timeZones,
                                 command=self.allTimeZones)
        self.allTZs.grid(column=0, row=9, sticky='WE')

        # Adding local TZ Button
        self.localTZ = ttk.Button(self.widgetFrame,
                                  text=self.i18n.localZone,
                                  command=self.localZone)
        self.localTZ.grid(column=1, row=9, sticky='WE')

        # Adding getTime TZ Button
        self.dt = ttk.Button(self.widgetFrame,
                             text=self.i18n.getTime,
                             command=self.getDateTime)
        self.dt.grid(column=2, row=9, sticky='WE')

        # Create Manage Files Frame ------------------------------------------------
        mngFilesFrame = ttk.LabelFrame(tab2, text=self.i18n.mgrFiles)
        mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5)

        # Button Callback
        def getFileName():
            print('hello from getFileName')
            fDir  = path.dirname(__file__)
            fName = fd.askopenfilename(parent=self.win, initialdir=fDir)
            print(fName)
            self.fileEntry.config(state='enabled')
            self.fileEntry.delete(0, tk.END)
            self.fileEntry.insert(0, fName)

            if len(fName) > self.entryLen:
                self.fileEntry.config(width=len(fName) + 3)

        # Add Widgets to Manage Files Frame
        lb = ttk.Button(mngFilesFrame, text=self.i18n.browseTo, command=getFileName)
        lb.grid(column=0, row=0, sticky=tk.W)

        file = tk.StringVar()
        self.entryLen = scrolW - 4
        self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file)
        self.fileEntry.grid(column=1, row=0, sticky=tk.W)

        logDir = tk.StringVar()
        self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir)
        self.netwEntry.grid(column=1, row=1, sticky=tk.W)

        def copyFile():
            import shutil
            src = self.fileEntry.get()
            file = src.split('/')[-1]
            dst = self.netwEntry.get() + '\\'+ file

        cb = ttk.Button(mngFilesFrame, text=self.i18n.copyTo, command=copyFile)
        cb.grid(column=0, row=1, sticky=tk.E)

        # Add some space around each label
        for child in mngFilesFrame.winfo_children():
            child.grid_configure(padx=6, pady=6)

        # Creating a Menu Bar ==========================================================
        menuBar = Menu(tab1)
        self.win.config(menu=menuBar)

        # Add menu items
        fileMenu = Menu(menuBar, tearoff=0)
        fileMenu.add_command(label=self.i18n.new)
        fileMenu.add_separator()
        fileMenu.add_command(label=self.i18n.exit, command=self._quit)
        menuBar.add_cascade(label=self.i18n.file, menu=fileMenu)

        # Add another Menu to the Menu Bar and an item
        helpMenu = Menu(menuBar, tearoff=0)
        helpMenu.add_command(label=self.i18n.about)
        menuBar.add_cascade(label=self.i18n.help, menu=helpMenu)

        # Change the main windows icon
        self.win.iconbitmap('pyc.ico')

        # Using tkinter Variable Classes
        strData = tk.StringVar()
        strData.set('Hello StringVar')

        # It is not necessary to create a tk.StringVar()
        strData = tk.StringVar()
        strData = self.spin.get()

        # Place cursor into name Entry
        self.bookTitle.focus()

        # Add a Tooltip to the Spinbox
        ToolTip(self.spin, 'This is a Spin control.')

        # Add Tooltips to more widgets
        ToolTip(self.bookTitle, 'This is an Entry control.')
        ToolTip(self.action, 'This is a Button control.')
        ToolTip(self.scr,    'This is a ScrolledText control.')

# Start GUI
oop = OOP()
oop.win.mainloop()


try:
        return KylinType[_convert_type(_type)](s) if s else s
    except KeyError:
        logger.error(
            'CONVERT ERROR, type: {}, raw string: {}'.format(_type, s))
        raise KylinUnsupportedType(_type)

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from datetime import datetime
import re

from kylinpy.exceptions import KylinUnsupportedType
from kylinpy.logger import logger
from kylinpy.utils.compat import text_type

true_pattern = re.compile(r'^true$', flags=re.IGNORECASE)

KylinType = dict(
    CHAR=text_type,
    VARCHAR=text_type,
    STRING=text_type,
    DECIMAL=float,
    DOUBLE=float,
    FLOAT=float,
    BIGINT=int,
    LONG=int,
    INTEGER=int,
    INT=int,
    TINYINT=int,
    SMALLINT=int,
    INT4=int,
    LONG8=int,
    BOOLEAN=lambda x: bool(re.search(true_pattern, x)),
    DATE=lambda x: datetime.strptime(x, '%Y-%m-%d').date(),
    DATETIME=lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S'),
    TIMESTAMP=lambda x: datetime.strptime(x.split('.')[0], '%Y-%m-%d %H:%M:%S'),
)

def _convert_type(_type):
    _type = re.sub(r'\(.*\)', '', _type)
    # remove some decorator in type string, such as 'BIGINT NOT NULL'
    _type = re.sub(r'\s.*', '', _type)
    return str(_type).upper()

def kylin_to_python(_type, s):