#!/usr/bin/env python
# coding: utf-8

# In[133]:

import numpy as np
import pandas as pd
from numpy.linalg import eig
import math
from collections import Counter
import random as rd
from collections import Counter
import matplotlib.pyplot as plt
import copy
import csv

# In[80]:

def der_tanh(z):
    return (1 - (np.tanh(z)**2))

# In[30]:

def sigmoid(z):
    return 1.0 / (1.0 + np.exp(-z))

# In[5]:

def sigmoidPrime(z):
    return np.exp(-z) / ((1 + np.exp(-z)) ** 2)

# In[6]:

def softMax(Z):
    E = np.exp(Z - np.max(Z, axis = 1, keepdims=True))
    S = np.sum(E, axis = 1, keepdims= True)
    A = E/S
#     print(A)
    return A

# In[86]:

def reLu(z):
    z1 = copy.deepcopy(z)
    z1[z1 < 0] = 0
    return z1

# In[88]:

def der_reLu(z):
    z1 = copy.deepcopy(z)
    z1[z1 <= 0] = 0
    z1[z1 > 0] = 1
    return z1

# In[97]:

def createBatch(epoch):
    for i  in range(epoch):
        batchSize = 100
        start = 0
        end = batchSize
        while(end < len(training_data)):
            batch = training_data.iloc[start:end]
            output = neuralNet.forwardPropagation(batch)
            neuralNet.backwardPropagation(batch, modifiedTrainLabel[start:end,:])
            start = start + batchSize
            end = end + batchSize

# In[8]:

def modifyLabelVector(x, trainLabel):
    columns = len(np.unique(trainLabel))
    rows = x.shape[0]
    modifiedLabels = np.zeros((rows, columns))

    for i in range(rows):
        modifiedLabels[i, trainLabel[i]] = 1

    return modifiedLabels

# In[127]:

class NeuralNet:
    def __init__(self, x, y, hiddenLayers):
        self.initialLayerSize = x.shape[1]
        self.outputLayerSize = len(y.unique())

        self.hiddenLayersCount = len(hiddenLayers)

        self.Weights = [0] * (self.hiddenLayersCount + 1)
        self.Z = [0] * (self.hiddenLayersCount + 1)
        self.ActivateFunc = [0] * (self.hiddenLayersCount + 1)

        for i in range(len(hiddenLayers) + 1):
            if i == 0:
                self.Weights[i] = np.random.randn(self.initialLayerSize, hiddenLayers[0])
            elif i == self.hiddenLayersCount:
                self.Weights[i] = np.random.randn(hiddenLayers[self.hiddenLayersCount - 1], self.outputLayerSize)
            else:
                self.Weights[i] = np.random.randn(hiddenLayers[i - 1], hiddenLayers[i])

#             print("Weight ", i, " ", self.Weights[i].shape)

    def forwardPropagation(self, X):
        self.Z[0] = np.dot(X, self.Weights[0])
        self.ActivateFunc[0] = np.tanh(self.Z[0])

        for i in range(1, self.hiddenLayersCount + 1):
            self.Z[i] = np.dot(self.ActivateFunc[i - 1], self.Weights[i])
            self.ActivateFunc[i] = np.tanh(self.Z[i])

        self.sm = softMax(self.Z[self.hiddenLayersCount])
        return self.sm

    def backwardPropagation(self, X, Y):

        delta = [None] * (self.hiddenLayersCount + 1)
        dJdW = [None] * (self.hiddenLayersCount + 1)

#         print("Active Func Shape: ", self.ActivateFunc[self.hiddenLayersCount - 1].shape)
        delta[self.hiddenLayersCount] = -(Y - self.sm) * der_tanh(self.ActivateFunc[-1])
        dJdW[self.hiddenLayersCount] = np.dot(self.ActivateFunc[self.hiddenLayersCount - 1].T, delta[self.hiddenLayersCount])

#         print("dj/dw: ", self.hiddenLayersCount, " ", dJdW[self.hiddenLayersCount])

        i = self.hiddenLayersCount - 1

        while i >= 0:
            if i == 0:
                delta[i] = np.dot(delta[i + 1], self.Weights[i + 1].T) * der_tanh(self.ActivateFunc[i])
                dJdW[i] = np.dot(X.T, delta[i])
            else:
                delta[i] = np.dot(delta[i + 1], self.Weights[i + 1].T) * der_tanh(self.ActivateFunc[i])
                dJdW[i] = np.dot(self.ActivateFunc[i - 1].T, delta[i])

            i -= 1

        i = self.hiddenLayersCount
        while i >= 0 :
            self.Weights[i] = self.Weights[i] - 0.01 * dJdW[i]

#             print(self.Weights[i])
            i -= 1

    def predict(self, data):
        return self.forwardPropagation(data)

# In[10]:

data = pd.read_csv('Apparel/apparel-trainval.csv')

training_data, test_data = np.split(data, [int(0.8*len(data))])

trainLabel = training_data['label']
testLabel = test_data['label']

training_data = training_data.drop(columns='label')
test_data = test_data.drop(columns='label')

# In[11]:

training_data=training_data.astype('float64')
means = np.mean(training_data, axis = 0)
stdDev = np.std(training_data, axis = 0)
training_data = (training_data - means) / stdDev

# In[12]:

test_data=test_data.astype('float64')
testMeans = np.mean(test_data, axis = 0)
testStdDev = np.std(test_data, axis = 0)
test_data = (test_data - testMeans) / testStdDev

# In[13]:

trainLabelValues = trainLabel.values
modifiedTrainLabel = modifyLabelVector(training_data, trainLabelValues)

# In[14]:

testLabelValues = testLabel.values
modifiedTestLabel = modifyLabelVector(test_data, testLabelValues)

# In[128]:

neuralNet = NeuralNet(training_data, trainLabel, [128])
epoch = 20
epochs.append(epoch)
createBatch(epoch)

# In[77]:

activAccuracy = []

# In[129]:

prediction = neuralNet.forwardPropagation(test_data)
print(len(prediction))
correct_cnt = 0
for i in range(len(prediction)):
    temp1 = np.argmax(modifiedTestLabel[i])
    temp2 = np.argmax(prediction[i])
    if(temp1 == temp2):
        correct_cnt += 1
# accuracies.append(correct_cnt * 1.0 / len(prediction))
# epochAcc.append(correct_cnt * 1.0 / len(prediction))
print("Accuracy:", correct_cnt * 1.0 / len(prediction))

# In[85]:

activAccuracy

# # Accuracy vs Number of Hidden Layers

# In[40]:

accuracies = []
layers = []

# In[72]:

layers.append(neuralNet.hiddenLayersCount)

# In[74]:

plt.figure()
plt.plot(layers, accuracies)
plt.show()

# # Accuracy vs No. of Epochs

# In[103]:

epochs = []
epochAcc = []

# In[124]:

epochAcc

# In[125]:

plt.figure()
plt.plot(epochs, epochAcc)
plt.show()

# In[144]:

test = pd.read_csv('apparel-test.csv')

test = test.astype('float64')
means = np.mean(test, axis = 0)
stdDev = np.std(test, axis = 0)
test = (test - means) / stdDev

result = []

prediction = neuralNet.forwardPropagation(test)
for i in range(len(prediction)):
    result.append(np.argmax(prediction[i]))

np.savetxt('2018202021_prediction.csv', result, delimiter=",")


import os
import sys
import clr
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import OpenOptions, DetachFromCentralOption, FilePath, ModelPathUtils
from Autodesk.Revit.DB import WorksetConfiguration, WorksetConfigurationOption
from Autodesk.Revit.DB import SaveAsOptions, WorksharingSaveAsOptions, TransmissionData

app = __revit__.Application

print(os.path.basename(__file__))

if not os.environ.get("RVT_QC_PATH"):
    print("no model specified - exiting.")
    sys.exit()

model_path = os.environ["RVT_QC_PATH"]

upgrade_dir = os.path.dirname(os.environ["RVT_QC_PATH"])
dir_files = os.listdir(upgrade_dir)

rvt_models = set()
upgrade_suffix = "_upgraded_to_{}_.rvt".format(app.VersionNumber)

skip_counter = {}
skip_models = {
}

for model in dir_files:
    if not model.endswith(".rvt"):
        skip_counter[model] = "not_a_rvt_model"
        continue
    elif model in skip_models:
        skip_counter[model] = "model_in_skip_list"
        continue
    elif model.endswith(upgrade_suffix):
        skip_counter[model] = "model_is_upgraded_already"
        continue
    elif model.endswith("0001.rvt"):
        skip_counter[model] = "model_is_a_backup_file"
        continue
    elif model + upgrade_suffix in dir_files:
        skip_counter[model] = "model_is_upgraded_already"
        continue
    rvt_models.add(os.path.join(upgrade_dir, model))

for model_name, reason in skip_counter.items():
    print("{}:{}".format(reason.ljust(25), model_name))

print("following {} models found for upgrade:".format(len(rvt_models)))
for model_path in sorted(rvt_models):
    print(model_path)

for model_path in sorted(rvt_models):
    new_target_path = model_path + upgrade_suffix
    rvt_path = FilePath(model_path)
    rvt_model_path = ModelPathUtils.ConvertUserVisiblePathToModelPath(model_path)
    print("currently processing: {}".format(model_path))

    ws_conf = WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets)
    open_opt = OpenOptions()
    open_opt.Audit = True
    open_opt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets
    open_opt.SetOpenWorksetsConfiguration(ws_conf)

    save_opt = SaveAsOptions()
    if os.path.exists(new_target_path):
        print("warning! overwriting: {}".format(new_target_path))
        save_opt.OverwriteExistingFile = True

    model_doc = app.OpenDocumentFile(rvt_path, open_opt)
    if model_doc.IsWorkshared:
        ws_opt = WorksharingSaveAsOptions()
        ws_opt.SaveAsCentral = True
        if TransmissionData.IsDocumentTransmitted(rvt_model_path):
            print("removing transmit   : {}".format(model_path))
            ws_opt.ClearTransmitted = True
        save_opt.SetWorksharingOptions(ws_opt)

    print("opened              : {}".format(model_path))
    model_doc.SaveAs(new_target_path, save_opt)
    print("saved as            : {}".format(new_target_path))
    model_doc.Close()
    print("closed")

sys.exit()


# -*- coding: utf-8 -*-
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_wx import _load_bitmap
from matplotlib.backends.backend_wxagg import \
    FigureCanvasWxAgg as FigureCanvas
from matplotlib.ticker import MaxNLocator
from mpl_toolkits.axes_grid1 import make_axes_locatable
import h5py
import numpy as np
import os
import sys
import rttov
import rview
from rview import util
from rview.util import MyCustomToolbar
import wx
import rmodel
from rview import myunits
from pubsub import pub

# constants
chnx = 50
# all images will be interpolated on levx
levx = 101
# tick positions for y axes (change it if you change levx)
ticky_positions = [100, 75, 50, 25, 0]
wix = 783
wnx = 400.0
spl = 29979245800.0  # en cm
gaslist = ['CH4', 'CO', 'CO2', 'N2O', 'O3', 'SO2']

obsoleteFrameMessage = (
    "kP invalid function:" +
    "\n- use the last k Matrix Viewer to display the K profile" +
    "\n- or run RTTOV K if necessary to display a new k Matrix Viewer")
kProfViewTitle = "run K profile channel "

class figPlot(plt.Figure):

    def __init__(self):
        plt.Figure.__init__(self)

class KMatrixFrame(util.GenericView):

    helpTitle = "Help"
    helpMessage = """Run K"""
    helpPage = os.environ["RTTOV_GUI_PREFIX"] + "/doc/helpKMatrixFrame.html"

    def __init__(self, parent, title, fname, runNumber=1, project=None):
        super().__init__(parent, title)
        self.title = title
        plt.rcParams['figure.autolayout'] = True
        self.myParent = parent
        self.myProject = project
        self.CreateMenuBar()
        self.runNumber = runNumber
        self.mykProfileView = None
        self.SetSize((900, 650))
        self.SetMinSize((900, 650))
        self.SetPosition((10, 10))
        self.sbgen = self.CreateStatusBar()
        self.sbgen.SetBackgroundColour('WHITE')
        txt = 'KMatrix file = %s' % fname
        self.sbgen.SetStatusText(txt)

        """  timer affichage StatusBar """
        self.txtsb = ''
        self.timer = wx.Timer(self)

        """ read kmat.h5 file """
        self.fh5 = fname
        self.kmat = rttov.kmatrix.Kmatrix()
        self.kmat101 = rttov.kmatrix.Kmatrix()

        """ read profile in kmat.h5 """
        self.baseProfile = rmodel.project.OpenAProfile(self.fh5, 1)

        frad = h5py.File(self.fh5, 'r')
        h5 = frad['/']
        self.kmat.loadh5(h5)
        frad.close()

        txt = 'lecture fichier %s' % (self.fh5)
        self.sat = self.kmat.misc['SATELLITE']
        self.ins = self.kmat.misc['INSTRUMENT']

        self.lev = self.kmat.profile['NLEVELS']
        self.tabP = self.kmat.profile['P']
        self.txtsb = '%s / %s' % (self.sat.replace(
            ' ', '').upper(), self.ins.upper())

        """ growth the levels  < 101 and map them """

        self.tabilevels = np.zeros(levx, int)
        for ilev in range(0, levx):
            self.tabilevels[ilev] = round(ilev * self.lev // levx)

        if self.lev < levx:
            tabNP = np.zeros(levx)
            for ilev in range(0, levx):
                tabNP[ilev] = self.tabP[self.tabilevels[ilev]]
            self.tabP = tabNP
        self.tabW = self.kmat.misc['WAVENUMBERS']
        self.tabY = {}

        self.chn = self.kmat.kmatrix['T'].shape[1]
        self.barwidth = max(1, int(wix / self.chn))
        self.yMax = self.lev
        if self.chn >= chnx:
            self.xMax = self.chn
        else:
            self.xMax = self.barwidth * self.chn
        self.tcomm = {}
        self.tunit = {}
        self.tcbar = {}
        self.gasplot = []
        for gas in ['T', 'Q'] + gaslist:
            if self.kmat.kmatrix[gas] is None:
                continue
            kmin = np.amin(self.kmat.kmatrix[gas])
            kmax = np.amax(self.kmat.kmatrix[gas])
            self.tcbar[gas] = 1
            if kmin == 0.0 and kmax == 0.0:
                self.tcbar[gas] = 0

            attr = '%s_ATTRIBUTE' % gas
            self.tcomm[gas] = u"{}".format((
                self.kmat.kmatrix[attr]['COMMENT']).decode("utf-8"))
            self.tunit[gas] = myunits.makePretty(
                gas,
                self.kmat.kmatrix[attr]['UNITS'],
                self.kmat.kmatrix['GAS_UNITS'])

            if not gas == 'T' and not gas == 'Q':
                self.gasplot.append(gas)

        """ extract gas """
        self.tabY['T'] = self.extract_kgas('T')
        self.tabY['Q'] = self.extract_kgas('Q')
        if self.gasplot:
            for gas in self.gasplot:
                self.tabY[gas] = self.extract_kgas(gas)
        self.init_canvas()
        self.chosen_gas = None
        if self.gasplot:
            self.chosen_gas = self.gasplot[0]
        """ plot references """
        self.sub_orig_P = None
        self.sub_scaled_P = None
        self.create_plots(self.sub_orig_P)
        self.create_toolbar()
        """ canvas and toolbar in sizer """
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.tlb, 0, wx.GROW)
        sizer.Add(self.cnv, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(sizer)
        self.Fit()
        pub.subscribe(self.ClosekProfViewListener, "CLOSE")
        self.myViews = {}
        self.MakeBinds()
        self.Show()

    def MakeBinds(self):
        self.Bind(wx.EVT_TIMER, self.refreshSB, self.timer)

    def ClosekProfViewListener(self, msg):
        viewTitle = msg
        if viewTitle == self.title:
            pub.unsubscribe(self.ClosekProfViewListener, "CLOSE")
        if viewTitle in self.myViews:
            print("remove reference to Window " + msg)
            self.myViews[viewTitle] = None

    def init_canvas(self):
        """ init figure """
        self.fig = figPlot()
        self.cnv = FigureCanvas(self, -1, self.fig)
        self.cnv.mpl_connect('motion_notify_event', self.onMMotion)
        self.cnv.mpl_connect('key_press_event', self.onkeypress)

    def create_plots(self, plot_refs):
        """ create the sublpots """

        #
        self.kprof = None
        # plot references
        plot_refs = {}
        self.cax = {}
        self.cb = {}
        #
        # subplots T and Q
        #
        plot_refs['T'] = self.fig.add_subplot(3, 1, 1)
        tt = u'%s : %s' % ('T', self.tcomm['T'])
        plot_refs['T'].set_title(tt)
        img = plot_refs['T'].imshow(self.tabY['T'], origin='upper')
        plot_refs['T'].set_ylabel('P levels')
        divider = make_axes_locatable(plot_refs['T'])
        self.cax['T'] = divider.append_axes(
            "right", size="1%", pad=0.05)
        self.cb['T'] = self.fig.colorbar(img, cax=self.cax['T'])
        plot_refs['T'].set_xlim([0, min(self.xMax, wix)])
        self.draw_plot('T', 'T', self.tcomm['T'], plot_refs)

        plot_refs['Q'] = self.fig.add_subplot(
            3, 1, 2, sharex=plot_refs['T'], sharey=plot_refs['T'])
        tt = u'%s : %s' % ('Q', self.tcomm['Q'])
        plot_refs['Q'].set_title(tt)
        img = plot_refs['Q'].imshow(self.tabY['Q'], origin='upper')
        plot_refs['Q'].set_ylabel('P levels')
        divider = make_axes_locatable(plot_refs['Q'])
        self.cax['Q'] = divider.append_axes(
            "right", size="1%", pad=0.05)
        self.cb['Q'] = self.fig.colorbar(img, cax=self.cax['Q'])
        plot_refs['Q'].set_xlim([0, min(self.xMax, wix)])
        self.draw_plot('Q', 'Q', self.tcomm['Q'], plot_refs)

#
# subplot other gases if exist
#
        if self.gasplot:
            gas = self.chosen_gas
            plot_refs['G'] = self.fig.add_subplot(
                3, 1, 3, sharex=plot_refs['T'],
                sharey=plot_refs['T'])
            tt = u'%s : %s' % (gas, self.tcomm[gas])
            plot_refs['G'].set_title(tt)
            img = plot_refs['G'].imshow(
                self.tabY[gas], origin='upper')
            plot_refs['G'].set_ylabel('P levels')

            divider = make_axes_locatable(plot_refs['G'])
            self.cax['G'] = divider.append_axes(
                "right", size="1%", pad=0.05)
            self.cb['G'] = self.fig.colorbar(img, cax=self.cax['G'])

            plot_refs['G'].set_xlim([0, min(self.xMax, wix)])
            self.draw_plot(
                'G', gas, self.tcomm[gas], plot_refs)

        self.make_yticks()
        # self.fig.tight_layout()
        self.fig.canvas.draw()
        self.plot_refs = plot_refs

    def create_toolbar(self):
        """ toolbar : custom buttons """
        self.tlb = MyCustomToolbar(self.cnv)
        iconsdir = os.environ["RTTOV_GUI_PREFIX"] + '/icons/'
        self.glabel = {}
        self.gasID = {}

        if len(self.gasplot) > 1:
            for ig in self.gasplot:
                self.gasID[ig] = wx.Window.NewControlId()
                self.glabel[self.gasID[ig]] = ig
                ico = iconsdir + '%s.png' % ig
                self.tlb.AddSimpleTool(
                    self.gasID[ig], _load_bitmap(ico), ig, '')
                wx.EvtHandler.Bind(self,
                                   event=wx.EVT_TOOL,
                                   handler=self.gaschoice,
                                   id=self.gasID[ig])
        self.LEFTLEFT_ID = wx.Window.NewControlId()
        self.tlb.AddSimpleTool(self.LEFTLEFT_ID, _load_bitmap(
            iconsdir + 'hand.xpm'), 'One screen left', '')
        wx.EvtHandler.Bind(self,
                           event=wx.EVT_TOOL,
                           handler=self.onleftleft,
                           id=self.LEFTLEFT_ID)

        self.LEFT_ID = wx.Window.NewControlId()
        self.tlb.AddSimpleTool(self.LEFT_ID, _load_bitmap(
            iconsdir + 'stock_left.xpm'), 'left', '')
        wx.EvtHandler.Bind(self,
                           event=wx.EVT_TOOL,
                           handler=self.onleft,
                           id=self.LEFT_ID)

        self.RIGHT_ID = wx.Window.NewControlId()
        self.tlb.AddSimpleTool(self.RIGHT_ID, _load_bitmap(
            iconsdir + 'stock_right.xpm'), 'right', '')
        wx.EvtHandler.Bind(self,
                           event=wx.EVT_TOOL,
                           handler=self.onright,
                           id=self.RIGHT_ID)

        self.RIGHTRIGHT_ID = wx.Window.NewControlId()
        self.tlb.AddSimpleTool(self.RIGHTRIGHT_ID, _load_bitmap(
            iconsdir + 'hand.xpm'), 'One screen right', '')
        wx.EvtHandler.Bind(self,
                           event=wx.EVT_TOOL,
                           handler=self.onrightright,
                           id=self.RIGHTRIGHT_ID)

        self.UP_ID = wx.Window.NewControlId()
        self.tlb.AddSimpleTool(self.UP_ID, _load_bitmap(
            iconsdir + 'stock_up.xpm'), 'scroll up', '')
        wx.EvtHandler.Bind(self,
                           event=wx.EVT_TOOL,
                           handler=self.onup,
                           id=self.UP_ID)

        self.DOWN_ID = wx.Window.NewControlId()
        self.tlb.AddSimpleTool(self.DOWN_ID, _load_bitmap(
            iconsdir + 'stock_down.xpm'), 'scroll down', '')
        wx.EvtHandler.Bind(self,
                           event=wx.EVT_TOOL,
                           handler=self.ondown,
                           id=self.DOWN_ID)
#
# add kscale icon : K / K%
#
        self.scalek = 0
        self.SCALE10K_ID = wx.Window.NewControlId()
        self.tlb.AddSimpleTool(self.SCALE10K_ID, _load_bitmap(
            iconsdir + 'k10.png'),
            'scale Kx10%', '')
        wx.EvtHandler.Bind(self,
                           event=wx.EVT_TOOL,
                           handler=self.onscale10k,
                           id=self.SCALE10K_ID)

        self.RESETK_ID = wx.Window.NewControlId()
        self.tlb.AddSimpleTool(self.RESETK_ID, _load_bitmap(
            iconsdir + 'reset.png'),
            'reset K', '')
        wx.EvtHandler.Bind(self,
                           event=wx.EVT_TOOL,
                           handler=self.onresetk,
                           id=self.RESETK_ID)

#
# add box : select channel
#
        self.SELCHAN_ID = wx.Window.NewControlId()
        self.tlb.AddSimpleTool(self.SELCHAN_ID, _load_bitmap(
            iconsdir + 'kP.png'),
            'select channnel', '')
        wx.EvtHandler.Bind(self,
                           event=wx.EVT_TOOL,
                           handler=self.onselchan,
                           id=self.SELCHAN_ID)

        self.tlb.Realize()

    def zoomp(self, evt, plot_refs):
        zp = int(self.szp.val)
        print("z :", zp)
        axes = plot_refs['T']
        y1, y2 = axes.get_ylim()
        ym = (y1 - y2) / 2
        print('avant :', y1, y2, ym)
        yy1 = ym + 50 / zp
        yy2 = ym - 50 / zp
        axes.set_ylim(yy1, yy2)
        print('apres :', yy1, yy2)
        self.make_yticks()

    def gaschoice(self, evt):
        gas = self.glabel[evt.GetId()]
        self.chosen_gas = gas
        plot_refs = self.plot_refs
        plot_refs['G'].clear()
        self.cb['G'].remove()
        plot_refs['G'] = self.fig.add_subplot(
            3, 1, 3, sharex=plot_refs['T'],
            sharey=plot_refs['T'])
        tt = u'%s : %s' % (gas, self.tcomm[gas])
        print(tt)
        plot_refs['G'].set_title(tt)
        img = plot_refs['G'].imshow(
            self.tabY[gas], origin='upper')
        plot_refs['G'].set_ylabel('P levels')

        divider = make_axes_locatable(plot_refs['G'])
        self.cax['G'] = divider.append_axes(
            "right", size="1%", pad=0.05)
        self.cb['G'] = self.fig.colorbar(img, cax=self.cax['G'])

        plot_refs['G'].set_xlim([0, min(self.xMax, wix)])
        self.draw_plot('G', gas, self.tcomm[gas], plot_refs)
        self.fig.canvas.draw_idle()
        self.make_yticks()

    def canDisplayKprofile(self):
        if self.myProject is None:
            return True
        if len(self.myProject.aKmats.aKmat) > 0:
            return self.runNumber == self.myProject.aKmats.aKmat[-1].runNumber
        else:
            return False

    def onkeypress(self, evt):
        if evt.key not in ['p', 'P'] or not evt.inaxes:
            return
        if not self.canDisplayKprofile():
            self.WarmError(obsoleteFrameMessage)
            return
        if self.chn > chnx:
            c = int(round(evt.xdata)) + 1
        else:
            c = int(round(evt.xdata) / self.barwidth) + 1
        if c < 0 or c > self.chn:
            return
        self.showkprof(c)

    def showkprof(self, c):
        """ show the kprofile frame """
        txt = 'display profile channel : %d from %s' % (c, self.fh5)
        self.writeSB(txt, 'green', 5, 1)
        pchan = self.kmat.getchanprof(c - 1)
        parent = self.myParent if self.myParent is not None else self
        mykProfViewTitle = kProfViewTitle + str(c)
        self.myViews[mykProfViewTitle] = rview.kprofileframe.KProfileView(
            parent, mykProfViewTitle, channel=c, runNumber=self.runNumber,
            kProfile=pchan,
            baseProfile=self.baseProfile,
            project=self.myProject)

    def extract_kgas(self, gas):
        # levels : put all profils on 101 levels

        tab101 = np.zeros((levx, self.chn))
        for ilev in range(levx):
            tab101[ilev][:] = self.kmat.kmatrix[gas][self.tabilevels[ilev]][:]

        self.kmat101.kmatrix[gas] = tab101

        if self.chn >= chnx:
            return self.kmat101.kmatrix[gas]
        tY = np.zeros(shape=((self.barwidth) * self.chn, levx))

        kmin = np.amin(self.kmat101.kmatrix[gas])
        kmax = np.amax(self.kmat101.kmatrix[gas])
        kmoy = (kmax + kmin) / 2
        pc = 0
        for ic in range(self.chn):

            for _ in range(self.barwidth - 1):
                tY[pc] = np.transpose(self.kmat101.kmatrix[gas])[ic]
                pc += 1
            #
            # bands separation
            #
            tY[pc] = kmoy
            pc += 1

        return np.transpose(tY)

    def onleftleft(self, evt):
        """ pan the graph to the left """
        if evt.GetId() == self.LEFTLEFT_ID:
            axes = self.cnv.figure.axes[0]
            x1, x2 = axes.get_xlim()
            shift = x2 - x1
            if x1 - shift <= 0:
                axes.set_xlim(0, shift)
            else:
                axes.set_xlim(x1 - shift, x2 - shift)
            self.make_yticks()

    def onleft(self, evt):
        if evt.GetId() == self.LEFT_ID:
            axes = self.cnv.figure.axes[0]
            x1, x2 = axes.get_xlim()
            shift = (x2 - x1) / 10
            axes.set_xlim(x1 - shift, x2 - shift)
            self.make_yticks()

    def onrightright(self, evt):
        if evt.GetId() == self.RIGHTRIGHT_ID:
            axes = self.cnv.figure.axes[0]
            x1, x2 = axes.get_xlim()
            shift = x2 - x1
            if x2 + shift >= self.xMax:
                axes.set_xlim(self.xMax - shift, self.xMax)
            else:
                axes.set_xlim(x1 + shift, x2 + shift)
            self.make_yticks()

    def onright(self, evt):
        if evt.GetId() == self.RIGHT_ID:
            axes = self.cnv.figure.axes[0]
            x1, x2 = axes.get_xlim()
            shift = (x2 - x1) / 10
            axes.set_xlim(x1 + shift, x2 + shift)
            self.make_yticks()

    def onup(self, evt):
        if evt.GetId() == self.UP_ID:
            axes = self.cnv.figure.axes[0]
            y1, y2 = axes.get_ylim()
            axes.set_ylim(y1 - 1, y2 - 1)
            self.make_yticks()

    def ondown(self, evt):
        if evt.GetId() == self.DOWN_ID:
            axes = self.cnv.figure.axes[0]
            y1, y2 = axes.get_ylim()
            axes.set_ylim(y1 + 1, y2 + 1)
            self.make_yticks()

    def redraw_y(self):
        axes = self.cnv.figure.axes[0]
        y1, y2 = axes.get_ylim()
        axes.set_ylim(y1, y2)

    # scale K-K%
    def onscale5k(self, evt):
        if evt.GetId() == self.SCALE5K_ID:
            self.scalexk(0.05)

    def onscale10k(self, evt):
        if evt.GetId() == self.SCALE10K_ID:
            self.scalexk(0.1)

    def onscale20k(self, evt):
        if evt.GetId() == self.SCALE20K_ID:
            self.scalexk(0.2)

    def scalexk(self, coeff):
        """ scale gas and plot """
        if self.scalek == 1:
            return

        self.scalek = 1
        text = 'init kmatrix scale'
        self.writeSB(text, 'yellow', 5, 1)
        self.kmat.kscale(coeff)
        text1 = u'end k scale'
        self.writeSB(text, 'green', 5, 1)
#
# update for all present gases
#
        for ig in ['Q'] + self.gasplot:
            self.tabY[ig] = self.extract_kgas(ig)
            self.tcomm[ig] = u'%s scaled by %3.2f input profile' % (
                self.tcomm[ig], coeff)

        for item in self.cax.keys():
            for axis in ['top', 'bottom', 'left', 'right']:
                self.cax[item].spines[axis].set_linewidth(0)
                self.cax[item].set_xticks([])
                self.cax[item].set_yticks([])
        for a in self.cnv.figure.axes:
            a.clear()
        for item in self.cax.keys():
            self.cax[item].clear()
        for item in self.cb.keys():
            self.cb[item].remove()
        self.create_plots(self.sub_scaled_P)
        text2 = u' / update graph '
        self.writeSB(text1 + text2, 'green', 5, 1)

    def onresetk(self, evt):
        """ reread kmat,  clear all axes and recreate plots """
        if self.scalek == 0:
            return
        self.scalek = 0
        text = 'init kmatix reset'
        self.writeSB(text, 'yellow', 5, 1)
        frad = h5py.File(self.fh5, 'r')
        h5 = frad['/']
        self.kmat.loadh5(h5)
        frad.close()
        text1 = 'end k reset'
        for ig in ['Q'] + self.gasplot:
            self.tabY[ig] = self.extract_kgas(ig)
            attr = '%s_ATTRIBUTE' % ig
            self.tcomm[ig] = str(self.kmat.kmatrix[attr]['COMMENT'])

        for a in self.cnv.figure.axes:
            a.clear()
        for item in self.cax.keys():
            self.cax[item].clear()
        for item in self.cb.keys():
            self.cb[item].remove()
        self.create_plots(self.sub_orig_P)

        text2 = ' / update graph '
        self.writeSB(text1 + text2, 'green', 5, 1)

    def onselchan(self, evt):
        if evt.GetId() != self.SELCHAN_ID:
            return
        if not self.canDisplayKprofile():
            self.WarmError(obsoleteFrameMessage)
            return
        txtbox = 'Select a channel number [%01d..%d] : ' % (1, self.chn)
        chnbox = util.SimpleFSDialogBox(
            self, -1, "Select channel", text=txtbox, text2="Channel",
            minval=1, maxval=self.chn, increment=1)
        chnbox.CenterOnParent()
        if (chnbox.ShowModal() == wx.ID_OK):
            c = chnbox.GetSelections()
            self.showkprof(c)
            chnbox.DeletePendingEvents()
            wx.CallAfter(chnbox.Destroy)

    def draw_plot(self, plot, gas, comment, plot_refs):
        """ draw the plot """
        tt = u'%s : %s' % (gas, comment)
        plot_refs[plot].set_title(tt)
        plot_refs[plot].imshow(self.tabY[gas], origin='upper')

        # x ticks = channel number
        if self.chn <= chnx:
            if self.chn <= 10:
                xtl = []
                xtp = []
                if gas == "T":
                    for i in range(0, self.chn + 1):
                        xtl.append(i + 1)
                        xtp.append((xtl[i] - 1) *
                                   self.barwidth + int(self.barwidth) // 2)

                    plot_refs[gas].set_xticks(xtp)
                    plot_refs[gas].set_xticklabels(xtl)
            else:
                xtl = []
                xtp = []
                if gas == "T":
                    for i in range(0, (self.chn + 1) // 2):
                        xtl.append(2 * i + 1)
                        xtp.append(int(self.barwidth // 2) +
                                   (xtl[i] - 1) * self.barwidth)

                    plot_refs[gas].set_xticks(xtp)
                    plot_refs[gas].set_xticklabels(
                        xtl, horizontalalignment='center')

        else:

            xa = plot_refs[plot].get_xaxis()
            xa.set_major_locator(MaxNLocator(nbins=10, integer=True))

    def make_yticks(self):
        """ for each axes compute and set yticklables """
        taxes = self.fig.get_axes()
        ytickslabels = []
        for pos in ticky_positions:
            ytickslabels.append(str(self.tabilevels[pos] + 1))
        for ax in range(0, len(taxes)):
            if taxes[ax].get_title():
                taxes[ax].set_yticks(ticky_positions)
                taxes[ax].set_yticklabels(ytickslabels)
        # self.fig.tight_layout()
        self.fig.canvas.draw_idle()
        return

    def MenuData(self):
        return (
            ("&File",  # File Menu
                ('&Quit', 'Quit', self.OnQuit, "quit", True)),
            ("&Help",  # Help Menu
                ("About", "About screen", self.OnAbout, "about", True),
                ("&Help", "Help", self.OnHelpHTML, "help", True)))

    def onMMotion(self, evt):
        if evt.inaxes:
            gas = evt.inaxes.title.get_text().split(' :')[0]

            if self.chn > chnx:
                c = int(round(evt.xdata)) + 1
            else:
                c = int(round(evt.xdata) / self.barwidth) + 1

            # print 'x=', evt.xdata ,' c=',c, 'xmax=', self.xMax
            if c < 0 or c > self.xMax:
                return

            y = int(evt.ydata)
# separation canaux
            if (
                    c > 1 and self.barwidth > 1 and
                    round(evt.xdata) % self.barwidth == 0.0):
                self.writeSB('channel separator', 'grey', 5, 0)
                return
#
# pression, canal, k
#
            try:
                tabwc = self.tabW[c - 1]
            except Exception:
                tabwc = self.tabW

            try:
                k = self.tabY[gas][y][int(round(evt.xdata))]

                if tabwc >= wnx:
                    txt0 = ' %s=%.3f %sm]' % (
                        u'\u03BB', (10000 / tabwc), u'\u03BC')
                else:
                    txt0 = ' %s=%.4f GHz]' % (
                        u'\u03BD', (spl * tabwc / 1000000000))
                mylevel = self.tabilevels[y] + 1
                text = u"%s : C=#%d P(%d)=%.3f hPa k=%g %s [wn=%.3f cm%s" % (
                    gas, c, mylevel, self.tabP[y], k,
                    self.tunit[gas], tabwc, myunits.exponentMinus1) + txt0
#
# ecriture message dans status bar
#
                self.writeSB(text, 'grey', 15, 0)
            except Exception:
                return

if __name__ == "__main__":
    print("******************************************************************")
    print("*******   KMatrixFrame environment   *****************************")
    print("******************************************************************")
    print('Executing on', os.uname())
    print('Python version', sys.version)
    print('wxPython version', wx.__version__)
    print('matplotlib version', matplotlib.__version__)
    print("******************************************************************")

    fh5 = []

    for i in range(len(sys.argv)):
        fh5.append(sys.argv[i])

    print("f=", fh5)

    app = wx.App(0)
    if len(fh5) < 2:
        from util import rttov_gui_data_test_dir
        data_test_dir = rttov_gui_data_test_dir()
        kmatrixfile = os.path.join(data_test_dir, "kmat.h5")
    else:
        kmatrixfile = fh5[1]
    print("kmatrixfile:", kmatrixfile)
    frame = KMatrixFrame(None, "K Matrix Viewer", kmatrixfile)

    app.MainLoop()


from fiware_ngsi_api.api_client import NgsiApiClient
from fiware_ngsi_api.configuration import NgsiConfiguration
from fiware_ngsi_api.api.entities import NgsiEntities

import json

if __name__ == "__main__":
    config = NgsiConfiguration("../conf/settings.conf")
    client = NgsiApiClient(configuration=config)

    nsgi_entities = NgsiEntities(api_client=client)

    body = {
        "id": "urn:ngsi-ld:Store:001",
        "type": "Store",
        "address": {
            "type": "PostalAddress",
                "value": {
                    "streetAddress": "Bornholmer Straße 65",
                    "addressRegion": "Berlin",
                    "addressLocality": "Prenzlauer Berg",
                    "postalCode": "10439"
                },
            "metadata": {
                    "verified": {
                        "value": True,
                        "type": "Boolean"
                    }
                }
        },
        "location": {
            "type": "geo:json",
            "value": {
                "type": "Point",
                "coordinates": [13.3986, 52.5547]
            }
        },
        "name": {
            "type": "Text",
            "value": "Bösebrücke Einkauf"
        }
    }

    # Create Entity
    response = nsgi_entities.create_entity(body)
    print("Creating an entity! \n", response.data.decode('utf-8'), response.status)

    # List all entities
    response = nsgi_entities.list_entities(
        options="keyValues", type="Store", q="address.addressLocality==Prenzlauer Berg")

    result = json.loads(response.data)
    print("Listing all current entities! \n", result)

    # Replace all entities attributes
    new_attr = {
        "address": {
            "type": "PostalAddress",
            "value": {
                    "streetAddress": "Nikou Akritidi 13",
                    "addressRegion": "Thessaloniki",
                    "addressLocality": "Kentro",
                    "postalCode": "54635"
            },
            "metadata": {
                "verified": {
                    "value": True,
                    "type": "Boolean"
                }
            }
        },
        "location": {
            "type": "geo:json",
            "value": {
                "type": "Point",
                "coordinates": [15, 16]
            }
        },
        "name": {
            "type": "Text",
            "value": "Giorgos"
        }
    }

    response = nsgi_entities.replace_all_entity_attributes(
        entity_id="urn:ngsi-ld:Store:001", body=new_attr
    )

    print("Replace entities attributes! \n", response.data, response.status)

    # List entity
    response = nsgi_entities.retrieve_entity(
        entity_id="urn:ngsi-ld:Store:001", options="keyValues")

    result = json.loads(response.data)
    print("List specific entity! \n", result)

    # Add attribute to entity
    extra_attribute = {
        "temperature": {
            "type": "Number",
            "value": 27.5
        }
    }

    response = nsgi_entities.update_or_append_entity_attributs(
        entity_id="urn:ngsi-ld:Store:001", body=extra_attribute, options="append"
    )

    print("Append an attribute to an entity\n", response.data, response.status)

    # Update existing entity attribute
    updated_attribute = {
        "temperature": {
            "type": "Number",
            "value": 30.0
        }
    }

    response = nsgi_entities.update_existing_entity_attributes(
        entity_id="urn:ngsi-ld:Store:001", body=updated_attribute
    )

    print("Update an existing attribute of that entity!\n",
          response.data, response.status)

    # List entity's attribute
    response = nsgi_entities.retrieve_entity_attributes(
        entity_id="urn:ngsi-ld:Store:001")

    result = json.loads(response.data)
    print("List attributes of the specified enitity\n", result)

    # Remove Entity
    response = nsgi_entities.remove_entity(entity_id="urn:ngsi-ld:Store:001")
    print("Removing an existing entity!\n",
          response.data.decode('utf-8'), response.status)


#!/usr/bin/python3
from pyftdi.ftdi import Ftdi
import pyftdi.serialext
import binascii

class USB_PD_DECODE_9K:
	# fixed widths
	HEADER_NUM_NIBBLES  = 4
	CRC_NUM_NIBBLES     = 8
	DATA_NUM_NIBBLES    = 8
	# ascii symbols from logger (selected by me, not USB spec)
	sync_1              = 'S'
	sync_2              = 'T'
	eop                 = '\r'
	beginning_of_packet = '\n'

	def __init__(self, dev='/dev/ttyUSB1', baudrate=1000000, debug=False):
		self.dev           = dev
		self.baudrate      = baudrate
		self.debug         = debug
		self.uart          = pyftdi.serialext.serial_for_url('ftdi://ftdi:2232:1/2', baudrate=1000000, bytesize=8, parity='N', stopbits=1, timeout=1)
                # use Ftdi.show_devices() to get URL

	def get_packet_nibble_list(self):
		self.uart.flushInput()
		self.uart.flushOutput()
		while (1):
			byte_list = []
			packet = self.uart.read_until()
			packet_nibble_list = list(packet.decode('UTF-8'))
			for char_to_strip in ['S', 'T', 'X', '\r', '\n']:
				try:
					while True: # remove all occurance in the whole list, not just the first
						packet_nibble_list.remove(char_to_strip)
				except:
					pass
			for index in range(0,len(packet_nibble_list)):
				if (packet_nibble_list[index] in ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']):
					packet_nibble_list[index] = int(packet_nibble_list[index],16)
			if (packet_nibble_list):
				self.check_num_nibbles(packet_nibble_list)
				print('[{}]'.format(', '.join(hex(x) for x in packet_nibble_list))) # print list as hex values

	def check_num_nibbles(self, packet_nibble_list):
		actual_num_nibbles = len(packet_nibble_list)
		expected_data_items = packet_nibble_list[3]
		expected_num_nibbles = self.HEADER_NUM_NIBBLES + expected_data_items * self.DATA_NUM_NIBBLES + self.CRC_NUM_NIBBLES
		if (actual_num_nibbles != expected_num_nibbles):
			print("ERROR, packet number of nibbles is {:d} and expected bumber of nibbles is {:d}".format(actual_num_nibbles,expected_num_nibbles))


#    Hitsuki (A telegram bot project)

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.

import re
from enum import IntEnum, unique

from hitsuki.modules.helper_funcs.string_handler import message_parser

from telethon import utils

NOTE_REGEX = re.compile(r"(^\S+|^\".*\")(?: |$)")

@unique
class Types(IntEnum):
    TEXT = 0
    BUTTON_TEXT = 1
    FILE = 2

async def get_note_type(message):
    data_type = None
    content = None
    text = ""
    split = message.text[len("/save "):]
    splitter = re.match(NOTE_REGEX, split)
    note_name = splitter.group(1).strip('"')

    reply = await message.get_reply_message()

    buttons = []
    # determine what the contents of the filter are - text, image, sticker, etc
    if not reply:
        note = re.sub(NOTE_REGEX, "", split)
        text, buttons = message_parser(note)
        if buttons:
            data_type = Types.BUTTON_TEXT
        else:
            if len(text) != 0:
                data_type = Types.TEXT

    elif reply and reply.text:
        text, buttons = message_parser(reply.text)
        if buttons:
            data_type = Types.BUTTON_TEXT
        else:
            data_type = Types.TEXT

    elif reply and reply.media:
        content = utils.pack_bot_file_id(reply.media)
        text = reply.text
        data_type = Types.FILE

    string = re.sub(' +', ' ', text).strip()
    return note_name, string, data_type, content, buttons

async def get_message_type(message, split: None):
    data_type = None
    content = None
    text = ""
    reply = await message.get_reply_message()

    buttons = []
    # determine what the contents of the filter are - text, image, sticker, etc
    if split:
        text, buttons = message_parser(split)
        if buttons:
            data_type = Types.BUTTON_TEXT
        else:
            data_type = Types.TEXT

    elif reply and reply.media:
        content = utils.pack_bot_file_id(reply.media)
        text = reply.text
        data_type = Types.FILE

    string = re.sub(' +', ' ', text).strip()
    return string, data_type, content, buttons


from rest_framework import status
from rest_framework.response import Response
from rest_framework.generics import RetrieveUpdateDestroyAPIView, ListCreateAPIView
from .models import Router
#from .permissions import IsOwnerOrReadOnly, IsAuthenticated
from .serializers import RouterSerializer
from .pagination import CustomPagination

class get_delete_update_movie(RetrieveUpdateDestroyAPIView):
    serializer_class = RouterSerializer
    #permission_classes = (IsAuthenticated, IsOwnerOrReadOnly,)

    def get_queryset(self, pk):
        try:
            router = Router.objects.get(pk=pk)
        except Router.DoesNotExist:
            content = {
                'status': 'Not Found'
            }
            return Response(content, status=status.HTTP_404_NOT_FOUND)
        return router

    # Get a movie
    def get(self, request, pk):

        router = self.get_queryset(pk)
        serializer = RouterSerializer(router)
        return Response(serializer.data, status=status.HTTP_200_OK)

    # Update a movie
    def put(self, request, pk):

        router = self.get_queryset(pk)

        if(request.user == router.creator): # If creator is who makes request
            serializer = RouterSerializer(router, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            content = {
                'status': 'UNAUTHORIZED'
            }
            return Response(content, status=status.HTTP_401_UNAUTHORIZED)

    # Delete a movie
    def delete(self, request, pk):

        router = self.get_queryset(pk)

        if(request.user == router.creator): # If creator is who makes request
            router.delete()
            content = {
                'status': 'NO CONTENT'
            }
            return Response(content, status=status.HTTP_204_NO_CONTENT)
        else:
            content = {
                'status': 'UNAUTHORIZED'
            }
            return Response(content, status=status.HTTP_401_UNAUTHORIZED)

class get_post_movies(ListCreateAPIView):
    serializer_class = RouterSerializer
    #permission_classes = (IsAuthenticated,)
    pagination_class = CustomPagination

    def get_queryset(self):
       routers = Router.objects.all()
       return routers

    # Get all movies
    def get(self, request):
        routers = self.get_queryset()
        paginate_queryset = self.paginate_queryset(routers)
        serializer = self.serializer_class(paginate_queryset, many=True)
        return self.get_paginated_response(serializer.data)

    # Create a new movie
    def post(self, request):
        serializer = RouterSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(creator=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


import functools
import json
from datetime import datetime, timedelta

from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from django.db.models import Max, Min, Prefetch
from django.forms import DateField
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.utils.formats import date_format
from django.utils.timezone import get_current_timezone, make_aware
from django.utils.translation import gettext as _
from django.views import View
from django.views.generic import (
    CreateView,
    DeleteView,
    DetailView,
    FormView,
    ListView,
    TemplateView,
    UpdateView,
)
from django.views.generic.detail import SingleObjectMixin
from guardian.shortcuts import assign_perm, get_objects_for_user, get_users_with_perms
from recurrence.forms import RecurrenceField

from ephios.core.forms.events import EventDuplicationForm, EventForm
from ephios.core.models import Event, EventType, Shift
from ephios.core.signals import event_forms
from ephios.extra.mixins import CanonicalSlugDetailMixin, CustomPermissionRequiredMixin
from ephios.extra.permissions import get_groups_with_perms

class EventListView(LoginRequiredMixin, ListView):
    model = Event

    def get_queryset(self):
        return (
            get_objects_for_user(self.request.user, "core.view_event")
            .annotate(
                start_time=Min("shifts__start_time"),
                end_time=Max("shifts__end_time"),
            )
            .filter(end_time__gte=timezone.now())
            .select_related("type")
            .prefetch_related("shifts")
            .prefetch_related(Prefetch("shifts__participations"))
            .order_by("start_time")
        )

    def get_context_data(self, *, object_list=None, **kwargs):
        kwargs.setdefault("eventtypes", EventType.objects.all())
        return super().get_context_data(**kwargs)

class EventDetailView(CustomPermissionRequiredMixin, CanonicalSlugDetailMixin, DetailView):
    model = Event
    permission_required = "core.view_event"

    def get_queryset(self):
        if self.request.user.has_perm("core.add_event"):
            return Event.all_objects.all()
        return Event.objects.all()

class EventEditMixin:
    @functools.cached_property
    def plugin_forms(self):
        forms = []
        for __, resp in event_forms.send(sender=None, event=self.object, request=self.request):
            forms.extend(resp)
        return forms

    def get_context_data(self, **kwargs):
        kwargs["plugin_forms"] = self.plugin_forms
        return super().get_context_data(**kwargs)

    def is_valid(self, form):
        return form.is_valid() and all(plugin_form.is_valid() for plugin_form in self.plugin_forms)

    def form_valid(self, form):
        response = super().form_valid(form)
        for plugin_form in self.plugin_forms:
            plugin_form.save()
        return response

class EventUpdateView(CustomPermissionRequiredMixin, EventEditMixin, UpdateView):
    model = Event
    queryset = Event.all_objects.all()
    permission_required = "core.change_event"

    def get_form(self, form_class=None):
        return EventForm(
            data=self.request.POST or None, user=self.request.user, instance=self.object
        )

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()
        if self.is_valid(form):
            return self.form_valid(form)
        return self.form_invalid(form)

class EventCreateView(CustomPermissionRequiredMixin, EventEditMixin, CreateView):
    template_name = "core/event_form.html"
    permission_required = "core.add_event"
    accept_object_perms = False
    model = EventType

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        self.object = form.instance
        if self.is_valid(form):
            return self.form_valid(form)
        return self.form_invalid(form)

    def dispatch(self, request, *args, **kwargs):
        self.eventtype = get_object_or_404(EventType, pk=self.kwargs.get("type"))
        return super().dispatch(request, *args, **kwargs)

    def get_form(self, form_class=None):
        return EventForm(
            data=self.request.POST or None,
            user=self.request.user,
            eventtype=self.eventtype,
        )

    def get_context_data(self, **kwargs):
        inactive_events = Event.all_objects.filter(active=False)
        kwargs.setdefault("inactive_events", inactive_events)
        kwargs.setdefault("eventtype", self.eventtype)
        return super().get_context_data(**kwargs)

    def get_success_url(self):
        return reverse("core:event_createshift", kwargs={"pk": self.object.pk})

class EventActivateView(CustomPermissionRequiredMixin, SingleObjectMixin, View):
    permission_required = "core.add_event"
    queryset = Event.all_objects.all()

    def post(self, request, *args, **kwargs):
        event = self.get_object()
        try:
            event.activate()
            messages.success(
                request,
                _("The event {title} has been saved.").format(title=event.title),
            )
        except ValidationError as e:
            messages.error(request, e)
        return redirect(event.get_absolute_url())

class EventDeleteView(CustomPermissionRequiredMixin, DeleteView):
    queryset = Event.all_objects.all()
    permission_required = "core.delete_event"
    success_url = reverse_lazy("core:event_list")

class EventArchiveView(CustomPermissionRequiredMixin, ListView):
    permission_required = "core.view_past_event"
    model = Event
    template_name = "core/event_archive.html"

    def get_queryset(self):
        return (
            get_objects_for_user(self.request.user, "core.view_event")
            .annotate(
                start_time=Min("shifts__start_time"),
                end_time=Max("shifts__end_time"),
            )
            .filter(end_time__lt=timezone.now())
            .select_related("type")
            .order_by("-start_time")
        )

class EventCopyView(CustomPermissionRequiredMixin, SingleObjectMixin, FormView):
    permission_required = "core.add_event"
    model = Event
    template_name = "core/event_copy.html"
    form_class = EventDuplicationForm

    def setup(self, request, *args, **kwargs):
        super().setup(request, *args, **kwargs)
        self.object = self.get_object()

    def form_valid(self, form):
        occurrences = form.cleaned_data["recurrence"].between(
            datetime.now() - timedelta(days=1),
            datetime.now() + timedelta(days=730),  # allow dates up to two years in the future
            inc=True,
            dtstart=datetime.combine(
                DateField().to_python(self.request.POST["start_date"]), datetime.min.time()
            ),
        )
        for date in occurrences:
            event = self.get_object()
            start_date = event.get_start_time().date()
            shifts = event.shifts.all()
            event.pk = None
            event.save()
            assign_perm(
                "view_event", get_groups_with_perms(self.get_object(), ["view_event"]), event
            )
            assign_perm(
                "change_event", get_groups_with_perms(self.get_object(), ["change_event"]), event
            )
            assign_perm(
                "change_event",
                get_users_with_perms(
                    self.get_object(), only_with_perms_in=["change_event"], with_group_users=False
                ),
                event,
            )

            shifts_to_create = []
            for shift in shifts:
                shift.pk = None
                # shifts on following days should have the same offset from the new date
                offset = shift.start_time.date() - start_date
                # shifts ending on the next day should end on the next day to the new date
                end_offset = shift.end_time.date() - shift.start_time.date()
                current_tz = get_current_timezone()
                shift.end_time = make_aware(
                    datetime.combine(
                        date.date() + offset + end_offset,
                        shift.end_time.astimezone(current_tz).time(),
                    )
                )
                shift.meeting_time = make_aware(
                    datetime.combine(
                        date.date() + offset, shift.meeting_time.astimezone(current_tz).time()
                    )
                )
                shift.start_time = make_aware(
                    datetime.combine(
                        date.date() + offset, shift.start_time.astimezone(current_tz).time()
                    )
                )
                shift.event = event
                shifts_to_create.append(shift)
            Shift.objects.bulk_create(shifts_to_create)

        messages.success(self.request, _("Event copied successfully."))
        return redirect(reverse("core:event_list"))

class RRuleOccurrenceView(CustomPermissionRequiredMixin, View):
    permission_required = "core.add_event"

    def post(self, *args, **kwargs):
        try:
            recurrence = RecurrenceField().clean(self.request.POST["recurrence_string"])
            return HttpResponse(
                json.dumps(
                    recurrence.between(
                        datetime.now() - timedelta(days=1),
                        datetime.now()
                        + timedelta(days=730),  # allow dates up to two years in the future
                        inc=True,
                        dtstart=datetime.combine(
                            DateField().to_python(self.request.POST["dtstart"]), datetime.min.time()
                        ),
                    ),
                    default=lambda obj: date_format(obj, format="SHORT_DATE_FORMAT"),
                )
            )
        except (TypeError, KeyError, ValidationError):
            return HttpResponse()

class HomeView(LoginRequiredMixin, TemplateView):
    template_name = "core/home.html"


import pygame

pygame.init()
winsize = 90
winmultiplier = 6
height = winsize * winmultiplier
width = height + winsize * 2
solvedBoard = []
buttonOffset = (winsize * 2) // 3
run = True
pressed = False
numberString = ''
N = 0
page = 0
solved = False

WHITE = (255,255,255)
BLACK  = (0,0,0)
LIGHTGRAY = (100,100,100)
LIGHTBLUE = (0,111,255)

window = pygame.display.set_mode((width,height))
pygame.display.set_caption('N-queens solver')

myfont = pygame.font.SysFont('arial', 30)
instructionFont = pygame.font.SysFont('arial', 20)

solverButton = pygame.Rect(0,0, 100, 50)
solverButton.center = (width // 2, height // 2 + height // 6)

previousPage = pygame.Rect(0, 0, 75, 50)
nextPage = pygame.Rect(0, 0, 75, 50)

previousPage.center = (height + buttonOffset - 10, 100)
nextPage.center = (height + buttonOffset * 2 + 10 ,100)

clearButton = pygame.Rect(0, 0, 75, 50)
clearButton.center = (height + (width - height) // 2, height // 2)

def left_diagonal_check(arr, row, col):
    x1, y1 = (0, 0)
    if row > col:
        x1, y1 = (row - col, 0)
    elif col > row:
        x1, y1 = (0, col - row)
    while ((x1 != len(arr)) and (y1 != len(arr[0]))):
        if arr[x1][y1] == 1:
            return False
        x1 = x1 + 1
        y1 = y1 + 1
    return True

def right_diagonal_check(arr, row, col):
    x1, y1 = (row, col)
    while x1 != 0 and y1 != len(arr) - 1:
        x1 = x1 - 1
        y1 = y1 + 1
    while x1 != len(arr) and y1 >= 0:
        if arr[x1][y1] == 1:
            return False
        x1 = x1 + 1
        y1 = y1 - 1
    return True

def is_valid_move(arr, row, col):
    for i in range(len(arr[0])):# no other 1 in row
        if arr[row][i]:
            return False
    for i in range(len(arr[col])):  # no other 1 in column
        if arr[i][col]:
            return False

    if not (right_diagonal_check(arr, row, col) and left_diagonal_check(arr, row, col)):
        return False

    return True

def array_copier(arr,N):
    array = initalize_array(N)
    for i in range(len(arr)):
        for j in range(len(arr[0])):
            array[i][j] = arr[i][j]
    return array

def solveNQueens(arr,col):
    global solvedBoard
    result = False
    if col >= len(arr[0]) :
        solvedBoard.append(array_copier(arr,len(arr)))
        return True
    for row in range(len(arr[0])):
        if is_valid_move(arr,row,col):
            arr[row][col] = 1
            result = solveNQueens(arr,col + 1) or result
            arr[row][col] = 0

    return result

def draw_chessboard(N):
    cellsize = height // N
    for x in range(N):
        for y in range(N):
            if x % 2 == 0 and y % 2 != 0:
                pygame.draw.rect(window,LIGHTGRAY, (cellsize * x, cellsize * y, cellsize,cellsize ))
            elif x % 2 != 0 and y % 2 == 0:
                pygame.draw.rect(window, LIGHTGRAY, (cellsize * x, cellsize * y , cellsize, cellsize))
    pygame.draw.line(window, BLACK, (0, 0), (cellsize * N, 0))
    pygame.draw.line(window,BLACK,(cellsize * N,0),(cellsize * N,cellsize * N))

def number_of_solutions(page, arr):
    string = '{} / {}'
    instructions = instructionFont.render(string.format(str(page + 1), str(len(arr))), 1, BLACK)
    instructionsRect = instructions.get_rect()
    instructionsRect.center = (height + (width - height) // 2, 50)
    window.blit(instructions,instructionsRect)

    pygame.draw.rect(window, LIGHTGRAY, previousPage)
    pygame.draw.rect(window, LIGHTGRAY, nextPage)
    pygame.draw.rect(window, LIGHTGRAY, clearButton)

    previous = instructionFont.render('Previous', 1, BLACK)
    previousRect = previous.get_rect()
    previousRect.center = previousPage.center
    window.blit(previous,previousRect)

    next = instructionFont.render('Next', 1, BLACK)
    nextRect = next.get_rect()
    nextRect.center = nextPage.center
    window.blit(next,nextRect)

    clear = instructionFont.render('Clear', 1, BLACK)
    clearRect = clear.get_rect()
    clearRect.center = clearButton.center
    window.blit(clear, clearRect)

def populate_cells(arr, N):
    cellsize = height // N
    queensize = cellsize // 1.5
    queenoffset = (cellsize - queensize) // 2
    for row in range(len(arr)):
        for col in range(len(arr[0])):
            if arr[row][col]:

                pygame.draw.rect(window, LIGHTBLUE, (col * cellsize + queenoffset, row * cellsize + queenoffset, queensize,queensize))

def initalize_array(N):
    return [[0 for i in range(N)] for j in range(N)]

def main_menu():
    #Heading
    text = myfont.render('Input number of Queens wanted (4 minimum):',1,BLACK)
    textRect = text.get_rect()
    textRect.center = (width //2 , height // 2 - height // 6)
    window.blit(text,textRect)

    #draws solve button
    pygame.draw.rect(window, LIGHTGRAY, solverButton)

    solvetext = myfont.render('Solve', 1, BLACK)
    solvetextRect = solvetext.get_rect()
    solvetextRect.center = (width // 2, height // 2 + height // 6)
    window.blit(solvetext, solvetextRect)

def input_number(numberString):
    inputText = myfont.render(numberString,1,BLACK)
    inputTextRect = inputText.get_rect()
    inputTextRect.center = (width //2 , height // 2)
    window.blit(inputText, inputTextRect)

def main():
    global run, pressed, numberString, solved, solvedBoard, page
    while run:
        window.fill(WHITE)
        if not pressed or N <= 3:
            main_menu()
            input_number(numberString)
            pressed = False
        elif N > 3:
            arr = initalize_array(N)
            draw_chessboard(N)
            # check if solved so program doesnt solve everytime user changes page
            if solved:
                solveNQueens(arr, 0)
                solved = False
            populate_cells(solvedBoard[page],N)
            number_of_solutions(page,solvedBoard)

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.unicode.isdigit():
                    numberString += event.unicode
                if event.key == pygame.K_BACKSPACE or event.key == pygame.K_DELETE:
                    numberString = numberString[:-1]
            elif event.type == pygame.MOUSEBUTTONDOWN:
                position = pygame.mouse.get_pos()
                x = position[0]
                y = position[1]
                if solverButton.collidepoint(x,y) and not pressed:
                    if numberString != '':
                        N = int(numberString)
                        numberString = ''
                        pressed = True
                        solved  = True
                elif previousPage.collidepoint(x,y) and page > 0:
                    page = page - 1
                elif nextPage.collidepoint(x,y) and page < len(solvedBoard) - 1:
                    page = page + 1
                elif clearButton.collidepoint(x,y):
                    pressed = False
                    solved = False
                    solvedBoard = []
                    page = 0
            elif event.type == pygame.QUIT:
                run = False
        pygame.display.update()

main()
pygame.quit()


from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def home(request):
    return render(request, "home.html")

def counter(request):
    words = request.POST["words"]
    # print(words)
    temp = words
    word_count = len(temp.split())

    return render(
        request,
        "counter.html",
        {
            "words": words,
            "word_count": word_count,
        },
    )


# !/usr/bin/env python
# -*- coding: utf-8 -*-
# forpylib - A Python library for forest simulation & optimization
# Licensed under GNU GPL, version 3
# UXFS Statistics & Operations Research Team (UXFSort)

"""
simulation
==========
Contains two classes, one to specify forest management prescriptions
(a itemized time schedule for operations, such as harvesting, planting, thinning)
and other to simulate stand tables based on dynamic growth models for
single-species, eveng-aged stands

    Example:

        >>> from growth_models.galicia import Betula_pendula
        >>> from simulation import PrescriptionWriter, Simulator
        >>> my_stand = Betula_pendula(stand_name="12A", t=10.0, H0=16.0, N=1000.0)
        >>> my_prescription = PrescriptionWriter(interval=3, periods=10)
        >>> my_prescription.add_thin(period=3, ti=50, rr=1)
        True
        >>> my_prescription.add_thin(period=6, ti=50, rr=0.6)
        True
        >>> my_prescription.add_final_harvest(period=10)
        True
        >>> my_simulation = Simulator(prescription=my_prescription, stand=my_stand)
        >>> my_simulation._to_string()
"""

import pandas
import numpy as np
import matplotlib.pyplot as plt
from tools.tabulate import *
import time

class PrescriptionWriter(object):
    """ A class to specify forest management prescriptions (sequence of
        operations) at stand level

    :Parameters:

        periods : int,
                  number of projection periods

        interval : int,
                   period length in years

    :Example:

        Creates a new stand forest management prescription object for 10 periods
        of 5 years length

        >>> my_prescription = PrescriptionWriter(stand=my_stand, periods=10, interval=5)
    """
    def __init__(self,  periods=1, interval=1):
        self.interval = float(interval)
        self.periods = float (periods)
        self.p = np.arange(1, self.periods + 1, dtype=np.int)
        self.actions = pandas.DataFrame({'p': self.p, 'ti': 0., 'rr': 0.},
                                        index=pandas.Index(self.p, name='period'))

    def add_final_harvest(self, period):
        """Adds a final harvest to the prescription

        :Parameters:

            period : int,
                     final harvest period in the range [1..self.periods]

        :Returns:

            Bool,
                  True if the action has been succesfully added to the presciption,
                  False otherwise

        :Examples:

            Final harvest at period 9

            >>> my_prescription.add_final_harvest(period=9)
            True
        """
        return self.add_thin(period=period, ti=100.0, rr=1.0)

    def add_thin(self, period, ti=0.0, rr=1.0):
        """Adds a thinning to the prescription

        :Parameters:

            period :  int, in the range [1..self.periods]
                      thinning period

            ti : float,
                 thinning intensity (the percentage of trees to remove)

            rr : float,
                 stand basal area removal ratio (the ratio of stand basal area
                 to remove to stand basal area before thinning times the ratio of
                 number of trees before thinning to number of trees to remove)
                 in the range [0.5..1.5]

        :Returns:

            bool,
                  True if the action has been succesfully added to the presciption,
                  False otherwise

        :Examples:

            Thinning at period 4 in which 30% of trees are removed
            with a stand basal area removal ratio of 1.0 (sistematic thinning)

            >>> my_prescription.add_thin(period=4, ti=30, rr=1.0)
            True
        """

        if (0 < period <= self.periods) and (0 < ti <= 100) and (0.5 <= rr <= 1.5):
            self.actions.ti[period] = ti
            self.actions.rr[period] = rr
            return True
        else:
            return False

    def delete_prescription(self):
        """
        Deletes all previously defined actions in the current prescription
        """
        self.actions.ti = 0.0
        self.actions.re = 0.0

    def get_actions(self, columns= ['p', 'ti', 'rr']):
        """
        Generates a list of the specified actions in the current prescription

        :Returns:
                pandas.dataset, actions in the current prescription
        """
        return self.actions.reindex(columns=columns)

class Simulator(object):
    """
    A class to generate stand tables on the basis of the initial state of
    the stands and the specified management prescriptions

    :Parameters:

        prescription : simulation.PrescriptionWriter
                       a instance of class to specify forest management
                       prescriptions (sequence of operations) at stand leve

        stand : growth_models.generic,
                the initial state of a stand of a given species for which
                there exists a dynamic stand growth modell

        relative : bool,
                   if True, the prescription is applied from the year: stand.t
                   if False, the prescription is applied from the year: zero

    :Example:

        Creates a new stand table on the basis of the initital state of the
        stand and the specified prescription

        >>> my_simulation = Simulator(prescription=my_prescription, stand=my_stand)
    """
    def __init__(self, prescription,stand, relative = False):
        self.prescription = prescription
        self.stand = stand
        if relative:
            self.inc = 0
            self.p = np.arange(1, 1 + self.prescription.periods - self.inc , dtype=np.int)
            self.t = (self.p - 1) * self.prescription.interval + self.stand.t  + \
                                                self.prescription.interval / 2
            self.prescription.actions['t'] = ((self.p - 1) * self.prescription.interval
                                        + self.stand.t + self.prescription.interval / 2)
        else:
            self.inc = (np.floor(((self.prescription.interval / 2.0) +
                            self.stand.t) / self.prescription.interval))
            self.p = np.arange(1, 1 + self.prescription.periods - self.inc , dtype=np.int)
            self.t = (self.inc * self.prescription.interval ) +  ((self.p-1)
                      * self.prescription.interval + self.prescription.interval / 2)
            self.prescription.actions['t'] = ((self.prescription.actions.p - 1) *
                                               self.prescription.interval  +
                                               self.prescription.interval / 2)
        self.t2 = self.t + self.prescription.interval
        self.simulation = self.get_simulation()

    def get_simulation(self, columns = (['t', 'H0', 'Dg', 'Dm', 'HBIb',
                                        'Nb', 'Gb', 'Vb', 'Nr', 'Gr', 'Vr', 'Na',
                                        'Ga', 'Va', 'HBIa', 'MAI', 'PAI'])):
        """Generates a dataset with the simulated stand table

        :Parameters:

            colums : array,
                name of stand variables to include in the dataset

        :Returns:

            ds : pandas.dataset,
        """

        ds = pandas.DataFrame({'p': self.p,
                               't': self.t,
                               't2': self.t2,
                               'mortality':True,
                               'Nb': 0., 'Gb': 0., 'Vb': 0., 'H0': 0., 'Dg': 0.,
                               'Dm': 0., 'HBIb': 0., 'tst': -1.0, 'Nr': 0.,
                               'Gr': 0., 'Vr': 0., 'Na': 0., 'Ga': 0.,
                               'Va': 0., 'HBIa': 0.,'Vra': 0.,'PAI': 0.,'MAI': 0.,
                                'interval':self.prescription.interval},
                              index=pandas.Index(self.p,
                                                 name='period'))

        ds0 = {'t': self.stand.t,'tst': self.stand.t-self.prescription.interval/2.0,
               't2': self.stand.t + self.prescription.interval/2.0,
               'mortality':self.stand.mortality,'Va': self.stand.V, 'Vra': 0.0,
               'H0': self.stand.H0, 'Na': self.stand.N, 'Ga': self.stand.G,
               'interval':self.prescription.interval/2.0}

        for i in ds.index:
            ds.H0[i] = self.stand.fH0(**ds0)
            ds.Gb[i] = self.stand.fGp(**ds0)
            ds.tst[i] =  ds0['tst'] + self.prescription.interval
            ds.mortality[i]= (ds0['tst'] > 0 and ds0['Na'] > 100
                              and self.stand.mortality)
            ds.Nb[i] = self.stand.fN(**ds0)
            ds.Dg[i] = self.stand.fDg(ds.Nb[i], ds.Gb[i])
            ds.Dm[i] = self.stand.fDm(**ds.loc[i])
            ds.HBIb[i] = (100 * np.sqrt(10000 / ds.Nb[i]) / ds.H0[i])
            ds.Vb[i] = self.stand.fV(**ds.loc[i])
            ds.Nr[i] = ds.Nb[i] * self.prescription.actions.ti[i+self.inc]/100
            if (ds.Nr[i] > 0): ds.tst[i] = 0
            ds.Gr[i] = (self.prescription.actions.rr[i+self.inc] * ds.Gb[i]
                        * ds.Nr[i] / ds.Nb[i])
            ds.Na[i] = ds.Nb[i] - ds.Nr[i]
            ds.Ga[i] = ds.Gb[i] - ds.Gr[i]
            if ds.Na[i] > 0:
                ds.Va[i] = self.stand.fV(after=ds.Nr[i] > 0, **ds.loc[i])
            ds.Vr[i] = ds.Vb[i] - ds.Va[i]
            ds.HBIa[i] = (100 * np.sqrt(10000 / ds.Na[i]) / ds.H0[i])
            ds.Vra[i] += ds.Vr[i] + ds0['Vra']
            ds.PAI[i] = (((ds.Vra[i] + ds.Va[i])-(ds0['Vra'] + ds0['Va'])) /
                                 ds0['interval'])
            ds.MAI[i] = (ds.Vra[i] + ds.Va[i]) / ds.t[i]
            if (ds.Na[i] < 25): break
            ds0 = ds.loc[i]
        return ds.reindex(columns=columns)

    def _to_string(self):

        summary = [('Generated by:', "forpylib"),
                   ('Date:', time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())),
                   ("Growth Model:", self.stand.model_specie + " - " +
                                     self.stand.model_region + " - " +
                                     self.stand.model_autor + " - " +
                                     self.stand.model_year)]
        prescription = self.prescription.get_actions(columns= ['p', 't','ti', 'rr'])
        txt = (
               "\n"
            +   "SUMMARY:\n"
            +  "========\n"
            +  tabulate(summary, tablefmt="grid")
            +  "\n"
            +  "\nSTAND:\n"
            +  "======\n"
            +  tabulate(self.stand.get_parametres(), headers="firstrow", tablefmt="orgtbl")
            +  "\n"
            +  "\nPRESCRIPTION:\n"
            +  "=============\n"
            +  tabulate(prescription[prescription.ti>0], headers="keys", tablefmt="orgtbl")
            +  "\n"
            +  "\nSIMULATION:\n"
            +  "===========\n"
            +  tabulate(self.simulation[self.simulation.H0>0], headers="keys", tablefmt="orgtbl"))

        return txt

    def plot(self,vars=['N','G','V','HBI']):

        ds = self.simulation
        columns =  ['t','N','G','V','H0','HBI', 'Nr', 'Gr']
        d1=ds[['t','Nb','Gb','Vb','H0','HBIb','Nr', 'Gr']]
        d1.columns = columns
        d2=ds[['t','Na','Ga','Va','H0','HBIa','Nr', 'Gr']]
        d2.columns = columns
        dt = pandas.concat([d1,d2], ignore_index=True).sort(['t','N'], ascending=[1, 0])

        dr = ds[ds.Nr>0]
        de=dr[['t','Nb','Gb','Vb','H0','HBIb','Nr', 'Gr']]
        de.columns = columns

        pos = len(vars)* 100 + 10
        plt.figure(figsize=(10,10))
        plt.rcParams.update({'font.size': 10})
        n = 0
        for var in vars:
            n += 1
            pos += 1
            ax = plt.subplot(pos)
            plt.plot(dt.t,dt[var],lw=2,color="black")
            plt.subplots_adjust(hspace =0)
            plt.grid(True)
            ax.set_xticklabels(())
            ax.margins(0.1,0.2)
            ax.set_ylabel(var,fontsize=13)
            ax.yaxis.set_label_position("right")
            if n == 1: plt.title("stand: " + self.stand.stand_name,fontsize=13 )
            y_min,y_max = ax.get_ylim()
            for i in de.index:
                plt.text(de.t[i], y_min,"thin(%.0f;%.2f)"% ((100*de.Nr[i]/
                         de.N[i]),(de.Gr[i]*de.N[i] /(de.G[i]* de.Nr[i] ))),
                         verticalalignment='top', horizontalalignment='center',
                         fontsize=9,backgroundcolor='0.95')
                plt.plot([de.t[i],de.t[i]],[y_min,de[var][i]],":",color="red")
            plt.plot(dt.t,dt[var],lw=2,color="black")
            plt.plot(de.t,de[var],'o',color="red")

        ax.set_xticklabels(ax.get_xticks())
        ax.set_xlabel(u"Time (years)")
        #plt.savefig("grafica.png",dpi=300)
        return plt


import torch
import torch.nn as nn
import torch.nn.functional as F
from models.StyleGAN2.model import EqualLinear

class FaceTexture(nn.Module):
    def __init__(self, in_channels, out_channels, volume_size):
        super().__init__()
        self.in_channels = in_channels
        self.face_texture_channels = out_channels
        self.volume_size = volume_size

        # pose encoder
        self.pose_encoder = nn.Sequential(
            EqualLinear(12, 32, lr_mul=0.01, activation="fused_lrelu"),
            EqualLinear(32, in_channels, lr_mul=0.01),
        )

        # last layer
        self.last = nn.Sequential(
            nn.LeakyReLU(0.2),
            nn.Conv2d(in_channels, out_channels+1, kernel_size=3, stride=1, padding=1)  # rgb featrue + sigma
        )

    def forward(self, face_texture, uv, c2w=None):
        if c2w is not None:
            # pose condition to texture
            pose = c2w.reshape(-1, 12)
            pose = self.pose_encoder(pose)
            face_texture = self.last(face_texture + pose.view(-1, self.in_channels, 1, 1))
        else:
            face_texture = self.last(face_texture)

        self.texture = face_texture

        sampled_texture = F.grid_sample(face_texture, uv.permute(0, 2, 3, 1),  # uv:(B, H, W, 2)
                                        mode='bilinear',
                                        align_corners=True)  # (B, feature_dim, H, W)

        feat = sampled_texture[:, :self.face_texture_channels, :, :]
        alpha = sampled_texture[:, self.face_texture_channels:, :, :]

        # sampled_texture = sampled_texture * mask
        alpha = torch.sigmoid(alpha)

        feat = F.interpolate(feat, (self.volume_size, self.volume_size), mode='bilinear')
        alpha = F.interpolate(alpha, (self.volume_size, self.volume_size), mode='bilinear')

        mask = (uv != 0).all(1, keepdim=True).float()
        mask = F.interpolate(mask, size=(self.volume_size, self.volume_size), mode='nearest')
        mask = (mask > 0.99).all(1, keepdim=True)

        feat = feat * mask
        alpha = alpha * mask

        return feat, alpha, mask


from .common import *

from django.db.models import Count

from apps.kanban.models import BoardCell, WorkflowStep, CellMovement
import apps.kanban.tasks as kanban_tasks
import apps.kanban.managers as kanban_manager
from apps.projects.models import Story
import apps.projects.tasks as projects_tasks

class IterationCellCounts(BaseHandler):
    allowed_methods = ('GET', )

    @throttle(READ_THROTTLE_REQUESTS, THROTTLE_TIME, 'user_reads')
    def read(self, request, organization_slug, project_slug, iteration_id):
        org, project = checkOrgProject(request, organization_slug, project_slug)

        return Story.objects.filter(project=project, iteration=iteration_id).values('cell_id').annotate(Count("id"))

class BoardCellHandler(BaseHandler):
    allowed_methods = ('GET', 'PUT', 'POST', "DELETE")
    fields = ("id",
              "project_id",
              "steps",
              "cell_type",
              "order",
              "label",
              "full_label",
              "x",
              "y",
              "width",
              "height",
              "headerColor",
              "backgroundColor",
              "wip_policy_id",
              "wipLimit",
              "pointLimit",
              "layout",
              "policy_text",
              "policy_html",
              "time_type",
              "leadTime",
              "minWipLimit",
              "minPointLimit",
              )

    write_fields = ("cell_type",
                    "order",
                    "label",
                    "x",
                    "y",
                    "width",
                    "height",
                    "headerColor",
                    "backgroundColor",
                    "wip",
                    "wip_policy_id",
                    "wipLimit",
                    "pointLimit",
                    "layout",
                    "policy_text",
                    "time_type",
                    "leadTime",
                    "minWipLimit",
                    "minPointLimit",
                    )

    model = BoardCell

    @staticmethod
    def policy_html(cell):
        try:
            if cell.policy_text != "":
                return htmlify(cell.policy_text, cell.project)
        finally:
            return ""

    @staticmethod
    def steps(cell):
        return [s.id for s in cell.steps.all()]

    @staticmethod
    def cell_type(cell):
        return cell.cellType

    def setSteps(self, cell, steps):
        result = []
        for stepId in steps:
            step = WorkflowStep.objects.get(id=stepId)
            if step.workflow.project_id != cell.project_id:
                raise ValidationError("Step %d not part of this project." % stepId)
            result.append(step)
        if cell.id is None:
            cell.save()

        before = set(cell.steps.all())
        after = set(result)

        added = after.difference(before)
        removed = before.difference(after)

        kanban_manager.handleStepsRemovedFromCell(removed, cell)
        kanban_manager.handleStepsAddedToCell(added, cell)

        cell.steps = result

    @throttle(WRITE_THROTTLE_REQUESTS, THROTTLE_TIME, 'user_writes')
    def create(self, request, organization_slug, project_slug):
        data = request.data
        org, project = checkOrgProject(request, organization_slug, project_slug, True)

        cell = BoardCell( project=project )
        self._update(cell, data)
        kanban_manager.setFullCellName(project, cell)
        cell.save()

        if "steps" in data:
            self.setSteps(cell, data["steps"])

        kanban_tasks.scheduleRebuildStepMovements(project, request.user)
        return cell

    def _update(self, cell, data):
        for field in BoardCellHandler.write_fields:
            if field in data:
                setattr(cell, field, data[field])

        if "steps" in data:
            self.setSteps(cell, data["steps"])

    @throttle(WRITE_THROTTLE_REQUESTS, THROTTLE_TIME, 'user_writes')
    def delete(self, request, organization_slug, project_slug, cell_id):
        org, project = checkOrgProject(request, organization_slug, project_slug, True)
        cell = project.boardCells.get(id=cell_id)

        tcid = request.GET.get("target_cell_id", None)
        targetCell = None
        if tcid is not None:
            targetCell = project.boardCells.get(id=tcid)
            updated = CellMovement.objects.filter(cell_to=cell).update(cell_to=targetCell)
            logger.info("Updated %d movements" % updated)

        for story in cell.stories.all():
            story.cell = targetCell
            story.save()

        cell.delete()
        kanban_tasks.scheduleRebuildStepMovements(project, request.user)
        projects_tasks.rebuildCellHeaderRisks.apply_async((project, ), countdown=10)
        return "deleted"

    @throttle(WRITE_THROTTLE_REQUESTS, THROTTLE_TIME, 'user_writes')
    def update(self, request, organization_slug, project_slug, cell_id):
        data = request.data
        org, project = checkOrgProject(request, organization_slug, project_slug, True)

        cell = project.boardCells.get(id=cell_id)
        self._update(cell, data)
        kanban_manager.setFullCellName(project, cell)
        cell.save()

        kanban_tasks.scheduleRebuildStepMovements(project, request.user)
        projects_tasks.rebuildCellHeaderRisks.apply_async((project, ), countdown=10)
        return cell

    @throttle(READ_THROTTLE_REQUESTS, THROTTLE_TIME, 'user_reads')
    def read(self, request, organization_slug, project_slug, cell_id=None ):
        org, project = checkOrgProject(request, organization_slug, project_slug)
        if cell_id is None:
            return project.boardCells.prefetch_related("steps").all()
        else:
            return project.boardCells.get(id=cell_id)


#!/usr/bin/env python

# This is a quickly hacked script to turn the ccc.media.de's podcast.xml,
# released for each Chaos Communication Congress, into XBMC *.nfo files.
#
# To find these files go to http://media.ccc.de/browse/congress/<INSERT YEAR HERE>/podcast.xml
#
# (c) 2014 by Florian Franzen

# ToDo: Scrap 'Fahrplan' info and add it to nfo (e.g. pictures of speaker)
# ToDo: Allow diffrent ending. Right now only '_h264-hq.mp4' is supported

import argparse

import xml.etree.ElementTree as ET
import urllib
import re
import codecs
import os
from collections import namedtuple

Talk = namedtuple("Talk", "title subtitle description speakers category prefix")

parser = argparse.ArgumentParser(description='Creates NFO files for each entry in a podcast.xml file.')

parser.add_argument('-x', '--xml-file', help='Path to the xml file. (Default: downloaded automatically)')

parser.add_argument('CONF_NUM', type=int, help='The conference the podcast.xml is from e.g. 30 if you run this for the 30c3.')
config = parser.parse_args()

# Parse XML file
if config.xml_file is not None:
    tree = ET.parse(config.xml_file)
    root = tree.getroot()
else:
    podcast_xml = urllib.urlopen("http://media.ccc.de/browse/congress/%d/podcast.xml" % (1983 + config.CONF_NUM)).read()
    root = ET.fromstring(podcast_xml)

# Make sure directory exist
directory = 'S%02d/' % config.CONF_NUM

if not os.path.exists(directory):
    os.makedirs(directory)
os.chdir(directory)

# Parse all talks
all_talks = dict()

for item in root[0].findall('item'):
    title = item.find('title').text[6:]

    subtitle = item.find('{http://www.itunes.com/dtds/podcast-1.0.dtd}subtitle')
    if subtitle is not None:
        subtitle = subtitle.text

    category = item.find('{http://www.itunes.com/dtds/podcast-1.0.dtd}keywords').text

    speakers = item.find('{http://www.itunes.com/dtds/podcast-1.0.dtd}author')
    if speakers is not None:
        speakers = speakers.text.split(",")
    else:
        speakers = []

    description = item.find('description').text
    description = re.split('event on media: |about this event: ', description)[0].strip()

    # Extract prefix from link
    link = item.find('link').text
    match = re.search(r'(?<=/)[^/]*(?=(_webm\.webm|_h264(-hq|-iprod)?\.mp4))', link)
    if match is not None:
        prefix = match.group(0)
    else:
        print("Can not extract prefix from following link: ", link)
        continue

    # Extract id from prefix
    match = re.search(r'(?<=\d{2}c3-)\d{4}(?=-)', prefix)
    if match is not None:
        id_num = int(match.group(0))
    else:
        print("Can not extract ID from prefix: ", prefix)
        continue

    all_talks[id_num] = Talk(title, subtitle, description, speakers, category, prefix)

# Compute length of zero padding
num_talks = len(all_talks)
num_digit = 0
while num_talks != 0:
    num_digit += 1
    num_talks //= 10

# For each talk...
rename_file = "#!/bin/sh\n"
episode = 1
for id_num in sorted(all_talks):
    talk = all_talks[id_num]

    # ... create NFO files
    xml_file = r"""<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    <episodedetails>
        <showtitle>Chaos Communication Congress</showtitle>
        <season>%d</season>
        <episode>%d</episode>
        <title>%s</title>""" % (config.CONF_NUM, episode, talk.title)

    if talk.subtitle is not None:
        xml_file += """
        <outline>%s</outline>""" % talk.subtitle

    xml_file += """
        <year>%s</year>
        <id>%s</id>
        <plot>
            %s
        </plot>
        <genre>Talk</genre>
        <tag>%s</tag>
    """ % (1983 + config.CONF_NUM, id_num, talk.description, talk.category)

    for speaker in talk.speakers:
        xml_file += r"""    <actor>
            <name>%s</name>
            <role></role>
        </actor>
    """ % speaker.strip()

    xml_file += r"</episodedetails>"

    file_pointer = codecs.open(talk.prefix + "_h264-hq.s%02de%0*d.nfo" % (config.CONF_NUM, num_digit, episode), "w", "utf-8-sig")
    file_pointer.write(xml_file)

    # ... collect the file names for the renaming script
    rename_file += "mv '%s' '%s'\n" % (talk.prefix + "_h264-hq.mp4", talk.prefix + "_h264-hq.s%02de%0*d.mp4" % (config.CONF_NUM, num_digit, episode))

    episode += 1

# Save rename script
f = open("rename.sh", "w")
f.write(rename_file)
f.close()

print("Finished parsing all %d talks of %dc3." % (episode - 1, config.CONF_NUM))


import os
import argparse
from tqdm import tqdm
import torch
import torch.nn as nn
from dataloader import MyDataset
from config import test_cfg
import pandas as pd
from net import networks
import numpy

def main(args):

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model=networks(num_class=test_cfg.num_class, pretrained = False).to(device)
    test_loader = torch.utils.data.DataLoader(
        MyDataset(test_cfg,train_mode=2),
        batch_size=test_cfg.batch_size, shuffle=False,
        num_workers=args.workers, pin_memory=True)

    predict_np=[]
    checkpoint_file = os.path.join(test_cfg.checkpoint_path,args.checkpoint +'.pth.tar')
    checkpoint = torch.load(checkpoint_file)
    model.load_state_dict(checkpoint['state_dict'])
    print('successful loaded checkpoint:{} (epoch{})'.format(checkpoint_file,checkpoint['epoch']))

    model.eval()

    print('testing.........')
    for i, inputs in tqdm(enumerate(test_loader)):
        with torch.no_grad():
            input_var = torch.autograd.Variable(inputs)
            out = model(input_var)
            _, prediction = torch.max(out.data, 1)
            pre = prediction.numpy()
            predict_np.append(pre)

    csv_path = os.path.join(test_cfg.img_folder,'..',test_cfg.csv_name)
    data = pd.read_csv(csv_path)
    predict_np=numpy.concatenate(predict_np)
    data['labels'] = pd.DataFrame(predict_np)
    data.to_csv(csv_path,index=False)
    print('successful write the predict results!')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='PyTorch Testing')
    parser.add_argument('-j', '--workers', default=12, type=int, metavar='N',
                        help='number of data loading workers (default: 12)')
    parser.add_argument('-c', '--checkpoint', default='epoch1checkpoint', type=str, metavar='PATH',
                        help='checkpoint filename (default: epoch1checkpoint)')
    main(parser.parse_args())


import argparse

def spider_parser(argv=None) -> argparse.Namespace:
    """
    Implement a command line parser for `nurs_reference_spider`.
    Returns
    -------
    argparse.Namespace
    """
    parser = argparse.ArgumentParser(argv, description='List the content of a folder')

    parser.add_argument('Path', metavar='path', type=str, help='the path to list')

    parser.add_argument(
        "-dp", '--description_path',
        default=None, required=False,
        metavar='description_path', type=str,
        help='path to description doc'
    )

    parser.add_argument(
        "-md", '--markdown_path',
        default="spider", required=False,
        metavar='markdown_path', type=str,
        help='path to write markdown output to'
    )

    parser.add_argument(
        "-new_dp", '--new_description_path',
        default="description", required=False,
        metavar='new_description_path', type=str,
        help='the path to list'
    )

    return parser.parse_args(argv)


import json

import requests as re

import streamlit as st

st.title("Sentiment Analyzer App using WordsAI")

st.image("./images/logo.png")

st.write("""
## About
This sentiment analyzer app uses the WordsAI API to get the sentiments of a text
""")

texts = st.text_input("Input text: ")
# make a post request to the fastapi server

if st.button ("Get sentiment"):
    response = re.post("http://wordsai-api.herokuapp.com/sentiment"+"?text="+texts)
    response_json = response.json()
    st.write(response_json)