# -*- coding: utf-8 -*-

"""
Module implementing MaterialListWindow.
"""

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtSql import *
from PyQt5.QtGui import QIcon
from .newMaterial import *
from .modifyMaterial import *
from .seeMaterial import *
from .material_files import Dialog_files
from .Ui_materialview import Ui_MaterialListWindow
from .piclabel import picLabel
import sys
sys.path.append("..\..")
from config import *

class MaterialListWindow(QMainWindow, Ui_MaterialListWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor

        @param parent reference to the parent widget
        @type QWidget
        """

        QMainWindow.__init__(self, parent)
        self.currentIndex=None
        self.parent=parent
        self.showDataFlag=u'成品'
        self.searchkey=None
        self.curmtype='成品'
        self.curmdtype=None

        self.selectdata={}
        connectdb()
        self.setupUi(self)

        self.setmaterialviewtoolbar()
        self.setPicLabel()
        self.setviewmodel(viewflag=self.curmtype)

        self.setlefttreeview()

        self.search.textChanged.connect(self.searchItem)

        self.closeview.triggered.connect(self.viewclose)
        self.new.triggered.connect(self.newItem)
        self.copynew.triggered.connect(self.copyNewItem)
        self.modify.triggered.connect(self.modifyItem)
        self.delete.triggered.connect(self.deleteItem)
        self.picture.triggered.connect(self.pictureshow)
        self.tableView.customContextMenuRequested[QPoint].connect(self.setPopMenu)

    def setPicLabel(self):
        self.label_pic = picLabel(self.centralWidget)
        self.gridLayout.addWidget(self.label_pic, 1, 0, 1, 1, Qt.AlignHCenter|Qt.AlignVCenter)

    def setmaterialviewtoolbar(self):
        self.search=QLineEdit()
        self.search.setFixedWidth(120)
        self.new=QAction(QIcon(u'./Icons/new.png'), u'新增', self)
        self.copynew=QAction(QIcon(u'./Icons/new.png'), u'复制新增', self)
        self.modify=QAction(QIcon(u'./Icons/modify.png'), u'修改', self)
        self.delete=QAction(QIcon(u'./Icons/delete.gif'), u'删除', self)
        self.picture=QAction(QIcon(u'./Icons/picture.png'), u'产品资料', self)
        self.closeview=QAction(QIcon(u'./Icons/关闭.gif'), u'关闭', self)
        self.toolBar.addWidget(self.search)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.new)
        self.toolBar.addAction(self.copynew)
        self.toolBar.addAction(self.modify)
        self.toolBar.addAction(self.delete)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.picture)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.closeview)
        self.toolBar.setMovable(False)

    def setviewmodel(self, viewflag=None, searchkey=None, detailtype=None):
        mtype='%%' if viewflag==None else '%'+viewflag+'%'
        mdtype='%%' if detailtype==None else '%'+detailtype+'%'
        searchkey='%%' if searchkey==None else '%'+searchkey+'%'

        query=QSqlQuery()
        qstr="SELECT `物料编号`,`物料名称`,`内玉`,`规格尺寸`,`基本单位`,\
        `材质`,`颜色`,`产品类别`,`产品细分类`,`创建日期`,`采购单位`,`基数采购单位`,\
        `基数基本单位`,`最近修改日期` FROM material\
        where `产品类别` like '{maintype}' and `产品细分类` like '{detailtype}' and (`物料名称` like '{skey}' or `物料编号` like '{skey}') ORDER BY `物料编号` DESC LIMIT 300".format(maintype=mtype, skey=searchkey, detailtype=mdtype)

#        query.prepare(u"SELECT `物料编号`,`物料名称`,`内玉`,`规格尺寸`,`基本单位`,\
#        `材质`,`颜色`,`产品类别`,`产品细分类`,`创建日期`,`采购单位`,`基数采购单位`,\
#        `基数基本单位`,`最近修改日期` FROM material\
#        where `产品类别`= ? and (`物料名称` like ? or `物料编号` like ?) ORDER BY `物料编号` DESC LIMIT 200")
        query.prepare(qstr)
#        query.bindValue(0, viewflag)
#        query.bindValue(1, searchkey)
#        query.bindValue(2, searchkey)
        query.exec_()

        querymodel=QSqlQueryModel()
        querymodel.setQuery(query)
        self.tableView.setModel(querymodel)
        if viewflag==u'原材料':
            self.tableView.setColumnHidden(2, True)
            self.tableView.setColumnHidden(5, True)
            self.tableView.setColumnHidden(9, True)
            self.tableView.setColumnHidden(13, True)

            self.tableView.setColumnHidden(10, False)
            self.tableView.setColumnHidden(11, False)
            self.tableView.setColumnHidden(12, False)
        else:
            self.tableView.setColumnHidden(9, True)
            self.tableView.setColumnHidden(10, True)
            self.tableView.setColumnHidden(11, True)
            self.tableView.setColumnHidden(12, True)
            self.tableView.setColumnHidden(13, True)

            self.tableView.setColumnHidden(2, False)
            self.tableView.setColumnHidden(5, False)
        self.tableView.resizeColumnsToContents()
        self.tableView.verticalHeader().setVisible(False)

        self.currentIndex=None
    def setlefttreeview(self):
        title=['商品分类']
        query=QSqlQuery()
        model=QStandardItemModel()
        model.setHorizontalHeaderLabels(title)
        query.prepare("select distinct 产品类别 from material")
        query.exec_()
        row=0
        while query.next():
            maintype=query.value(0)
            item=QStandardItem(str(maintype))
            brush=QBrush(QColor(130, 170, 255))
            item.setBackground(brush)
            model.setItem(row, 0, item)
            dquery=QSqlQuery()
            dquery.prepare("select distinct 产品细分类 from material where 产品类别=:mtype")
            dquery.bindValue(":mtype", maintype)
            dquery.exec_()
            drow=0
            while dquery.next():
                detailtype=dquery.value(0)
                ditem=QStandardItem(detailtype)
                brush=(QBrush(QColor(220, 230, 255)) if row%2 else QBrush(QColor(210, 220, 255)))
                ditem.setBackground(brush)
                item.setChild(drow, 0, ditem)
                drow+=1
            row+=1
        self.treeView_left.setModel(model)
        self.treeView_left.expandAll()

    def checkDataBeUsed(self):
        query=QSqlQuery()
        #检查BOM表中是否使用
        data=self.currentIndex.data(Qt.DisplayRole)
        query.prepare("select count(物料编号) from bomheader where 物料编号=:maid")
        query.bindValue(":maid", self.currentIndex.data(Qt.DisplayRole))
        query.exec_()
        query.next()
        if query.value(0)>0:
            return True
        #检查BOM表
        query.prepare("select count(物料编号) from bomdetail where 物料编号=:maid")
        query.bindValue(":maid", self.currentIndex.data(Qt.DisplayRole))
        query.exec_()
        query.next()
        if query.value(0)>0:
            return True
        #检查是否有单价
        query.prepare("select 单价名称 fro material where 物料编号=:maid")
        query.bindValue(":maid", self.currentIndex.data(Qt.DisplayRole))
        query.exec_()
        query.next()
        if query.value(0)!=None:
            if len(query.value(0))!=0:
                return True

    def getCurrentData(self):
        if self.currentIndex==None:
            QMessageBox.warning(None, u"警告：", u"请选择要修改的物料", QMessageBox.Ok)
            return False
        else:
            self.currentdata={}
            self.currentdata[u'物料编号']=self.currentIndex.data(Qt.DisplayRole)
            self.currentdata[u'物料名称']=self.currentIndex.sibling(self.currentIndex.row(), 1).data(Qt.DisplayRole)
            self.currentdata[u'内玉']=self.currentIndex.sibling(self.currentIndex.row(), 2).data(Qt.DisplayRole)
            self.currentdata[u'规格尺寸']=self.currentIndex.sibling(self.currentIndex.row(), 3).data(Qt.DisplayRole)
            self.currentdata[u'基本单位']=self.currentIndex.sibling(self.currentIndex.row(), 4).data(Qt.DisplayRole)
            self.currentdata[u'材质']=self.currentIndex.sibling(self.currentIndex.row(), 5).data(Qt.DisplayRole)
            self.currentdata[u'颜色']=self.currentIndex.sibling(self.currentIndex.row(), 6).data(Qt.DisplayRole)
            self.currentdata[u'采购单位']=self.currentIndex.sibling(self.currentIndex.row(), 10).data(Qt.DisplayRole)
            self.currentdata[u'基数采购单位']=self.currentIndex.sibling(self.currentIndex.row(), 11).data(Qt.DisplayRole)
            self.currentdata[u'基数基本单位']=self.currentIndex.sibling(self.currentIndex.row(), 12).data(Qt.DisplayRole)
            self.currentdata[u'最近修改日期']=self.currentIndex.sibling(self.currentIndex.row(), 14).data(Qt.DisplayRole)
            self.currentdata[u'产品类别']=self.currentIndex.sibling(self.currentIndex.row(), 7).data(Qt.DisplayRole)
            self.currentdata[u'产品细分类']=self.currentIndex.sibling(self.currentIndex.row(), 8).data(Qt.DisplayRole)

    @pyqtSlot()
    def pictureshow(self):
        try:
            filekey=self.currentIndex.data(Qt.DisplayRole)
#            print ('filekey is', filekey)
        except:
            QMessageBox.warning(self, u'警告', u'请选择物料')
            return
        dialog=Dialog_files(None, filekey)
        dialog.exec_()

    @pyqtSlot(str)
    def searchItem(self, p0):
        self.searchkey='%'+p0+'%'
        self.setviewmodel(viewflag=self.curmtype, searchkey=self.searchkey, detailtype=self.curmdtype)

    @pyqtSlot()
    def newItem(self):
        newMaterialDialog=Dialog_newMaterial()
        if newMaterialDialog.exec_()==QDialog.Accepted:

            self.setviewmodel(self.curmtype, self.searchkey, self.curmdtype)

    @pyqtSlot()
    def copyNewItem(self):
        if self.currentIndex==None:
            QMessageBox.warning(self, "提示", "请选择需要复制的物料")
            return
        newMaterialDialog=Dialog_newMaterial(None, self.selectdata)
        if newMaterialDialog.exec_()==QDialog.Accepted:
            self.setviewmodel(self.curmtype, self.searchkey, self.curmdtype)
            self.setlefttreeview()

    @pyqtSlot()
    def deleteItem(self):
        text, ok=QInputDialog.getText(self, "密码输入", "请输入权限密码:", QLineEdit.Password,'')
        if ok:
            if text!='88*':
                QMessageBox.warning(self, "错误", "权限密码不正确！")
                return
        else:
            return
        if self.checkDataBeUsed()==True:
            QMessageBox.warning(None, u"警告：", u"该物料已经被使用，不可删除", QMessageBox.Ok)
            return
        elif self.currentIndex==None:
            QMessageBox.warning(None, u"警告：", u"请选择要删除的物料", QMessageBox.Ok)
            return
        else:
            if QMessageBox.question(None, u"删除确认", u"请确定是否真的要删除当前物料", QMessageBox.Ok, QMessageBox.Cancel)==QMessageBox.Cancel:
                return

            query=QSqlQuery()
            query.prepare(u"DELETE FROM material WHERE `物料编号`=?")
            query.bindValue(0, self.currentIndex.data(Qt.DisplayRole))
            if query.exec_()==True:
                self.setviewmodel(self.curmtype, self.searchkey, self.curmdtype)
    @pyqtSlot()
    def modifyItem(self):

        if self.getCurrentData()==False:
            return

        modifydialog=Dialog_modifyMaterial(self, self.currentdata)
        if modifydialog.exec_()==QDialog.Accepted:

            self.setviewmodel(self.curmtype, self.searchkey, self.curmdtype)
            self.setlefttreeview()

    @pyqtSlot()
    def viewclose(self):
        self.parent.tabnavigator.removeTab(self.parent.tabnavigator.currentIndex())
        self.parent.basicSTMaterilWidget=False
        self.close()

    @pyqtSlot(QModelIndex)
    def on_tableView_clicked(self, index):
        """
        Slot documentation goes here.

        @param index DESCRIPTION
        @type QModelIndex
        """
        self.currentIndex=index.sibling(index.row(), 0)
        self.index=index
        model=self.tableView.model()
        colcount=model.columnCount()
        for section in range(colcount):
            name=model.headerData(section, Qt.Horizontal, Qt.DisplayRole)
#            print("current name is ", name)
            self.selectdata[name]=model.data(index.sibling(index.row(), section), Qt.DisplayRole)
        self.maid=self.tableView.model().record(index.row()).value('物料编号')
        query=QSqlQuery()
        query.prepare("select 图片 from material where 物料编号=:maid ")
        query.bindValue(":maid", self.maid)
        query.exec_()
        query.next()
        self.scaledimagedata=query.value(0)
        image=QImage().fromData(self.scaledimagedata)
        scalx=image.width()/400.0
        scaly=image.height()/300.0
        self.scaledimage= image.scaledToWidth(200, Qt.SmoothTransformation) if scalx>scaly else image.scaledToHeight(200, Qt.SmoothTransformation)

#        print(scaledimage.size())
        self.label_pic.setPixmap(QPixmap(self.scaledimage))
        self.label_pic.setimage(image)
#        print 'index nowis ', self.currentIndex.data(Qt.DisplayRole).toString()

    @pyqtSlot(QModelIndex)
    def on_tableView_doubleClicked(self, index):
        """
        Slot documentation goes here.

        @param index DESCRIPTION
        @type QModelIndex
        """
        # TODO: not implemented yet
        self.currentIndex=index.sibling(index.row(), 0)
        self.getCurrentData()

        modifydialog=Dialog_seeMaterial(self, self.currentdata)
        modifydialog.exec_()

    @pyqtSlot(QModelIndex)
    def on_treeView_left_clicked(self, index):
        """
        Slot documentation goes here.

        @param index DESCRIPTION
        @type QModelIndex
        """
        # TODO: not implemented yet
        item=self.treeView_left.model().itemFromIndex(index)
        if item.hasChildren()==True:
            self.curmtype=index.data(Qt.DisplayRole)
            self.curmdtype=None
        else:
            self.curmtype=item.parent().data(Qt.DisplayRole)
            self.curmdtype=index.data(Qt.DisplayRole)

        self.setviewmodel(viewflag=self.curmtype, searchkey=self.searchkey, detailtype=self.curmdtype)

    def setPopMenu(self, index):
        self.index=self.tableView.indexAt(index)
        if self.index.row()==-1:
            return
        popmenu=QMenu()
        upload=popmenu.addAction(u"上传简图")
        upload.triggered.connect(self.upload)
        popmenu.addSeparator()
        delete=popmenu.addAction(u"删除简图")
        delete.triggered.connect(self.deleteImage)
        popmenu.exec_(QCursor.pos())

    def upload(self):
        filename=QFileDialog.getOpenFileName(self,"载入图片", "", "图档文件(*.bmp *.jpg *.jpeg *.png)")
        if len(filename[0])==0:
            self.bytearray=None
            return

        image=QImage(filename[0])

        scalx=image.width()/400.0
        scaly=image.height()/300.0

        self.scaledimage= image.scaledToWidth(200, Qt.SmoothTransformation) if scalx>scaly else image.scaledToHeight(200, Qt.SmoothTransformation)
        self.savedscaledimage= image.scaledToWidth(800, Qt.SmoothTransformation) if scalx>scaly else image.scaledToHeight(600, Qt.SmoothTransformation)
        self.label_pic.setPixmap(QPixmap(self.scaledimage))
        self.label_pic.setimage(self.savedscaledimage)
        self.bytearray=QByteArray()
        buffer=QBuffer(self.bytearray)
        buffer.open(QIODevice.WriteOnly)
        ok=self.savedscaledimage.save(buffer, 'PNG')
        if ok==False:
            self.bytearray=None
        query=QSqlQuery()
        query.prepare("update material set 图片=:pic where 物料编号=:maid")
        query.bindValue(":pic", self.bytearray)
        query.bindValue(":maid", self.tableView.model().record(self.index.row()).value('物料编号'))
        query.exec_()
        if query.lastError().type()!=QSqlError.NoError:
                QMessageBox.warning(self, u"警告", u"写入图片数据错误")

    def deleteImage(self):
        self.bytearray=None
        self.label_pic.clear()
        query=QSqlQuery()
        query.prepare("update material set 图片=null where 物料编号=:maid")
        query.bindValue(":maid", self.tableView.model().record(self.index.row()).value('物料编号'))
        query.exec_()
        if query.lastError().type()!=QSqlError.NoError:
                QMessageBox.warning(self, u"警告", u"删除图片数据错误")
        #开始删除数据库中数据


#!/usr/bin/python3
import argparse
import torchvision.transforms as transforms
import torch.utils.data
from neural_compression_correction.models import load_dn4, load_dn9, load_dn10_sharpen, load_dn13na, load_dn14na

from tqdm import tqdm

from PIL import Image
import os

def mirror_directory_structure(original_base, new_base):
    original_base = original_base.rstrip(os.sep) + os.sep
    new_base = new_base.rstrip(os.sep) + os.sep

    if not os.path.exists(new_base):
        os.makedirs(new_base)
    for root, dirs, _ in os.walk(original_base):
        for dr in dirs:
            p = os.path.join(root.replace(original_base, new_base), dr)
            try:
                os.makedirs(p)
            except Exception as e:
                print(e)

def list_file_paths(base_path):
    paths = []
    for root, dirs, fns in os.walk(base_path):
        if ".ipynb_checkpoints" in root:
            continue
        for fn in fns:
            if fn.lower().split(".")[-1] in {"jpg", "jpeg", "png"}:
                print(os.path.join(root, fn))
                paths.append(os.path.join(root, fn))
    return paths

class RawPathedImageDataset(torch.utils.data.Dataset):
    def __init__(self, image_paths, super_resolution=False):
        self.image_paths = list(image_paths)
        self.length = len(self.image_paths)
        self.to_tensor = transforms.ToTensor()
        self.super_resolution = super_resolution

    def __len__(self):
        return self.length

    def __getitem__(self, idx):
        path, new_path = self.image_paths[idx]
        img = Image.open(path).convert("RGB")
        if self.super_resolution:
            img = img.resize((img.size[0] * 2, img.size[1] * 2))
        oimage = self.to_tensor(img)

        return (new_path, oimage)

def main():
    # Training settings
    parser = argparse.ArgumentParser(description='PyTorch Neural Compression Correction')
    parser.add_argument('--batch-size', type=int, default=1, metavar='N',
                        help='input batch size for inference (default: 1)')
    parser.add_argument('-w', '--workers', type=int, default=1, metavar='N',
                        help='Number of input workers (default: 1)')
    parser.add_argument('--no-cuda', action='store_true', default=False,
                        help='disables CUDA training')
    parser.add_argument('-i', '--input', type=str, required=True, help="Path to file or directory of images to process")
    parser.add_argument('-o', '--output', type=str, required=True, help="Path to file or directory to output results to")
    parser.add_argument('-s', '--super', action='store_true', default=False, help="Doubles image resolution")

    args = parser.parse_args()

    batch_size = args.batch_size
    super_resolution = args.super
    single_file = os.path.isfile(args.input)
    if not single_file:
        paths = list_file_paths(args.input)
        output_path = args.output.rstrip(os.sep) + os.sep
        mirror_directory_structure(args.input, args.output)
        paths = [
            (path, os.path.join(path.replace(args.input, output_path))) for path in paths
        ]
    else:
        paths = [(args.input, args.output)]
        batch_size = 1

    use_cuda = not args.no_cuda and torch.cuda.is_available()

    device = torch.device("cuda" if use_cuda else "cpu")

    loader = torch.utils.data.DataLoader(
        RawPathedImageDataset(paths, super_resolution=super_resolution),
        batch_size=batch_size,
        shuffle=False,
        drop_last=False,
        num_workers=args.workers,
    )

    model = load_dn4(device=device)
    #model = load_dn14na(device=device)
    unloader = transforms.ToPILImage()

    with torch.no_grad():

        for new_paths, image_batch in tqdm(loader):
            try:
                preds = model(image_batch.to(device)).cpu()
                for i, np in enumerate(new_paths):
                    img = unloader(preds[i, :, :, :])
                    img.save(np)
                    del img
                del preds
                del image_batch
            except RuntimeError as rte:
                preds = model.cpu()(image_batch.to("cpu")).cpu()
                for i, np in enumerate(new_paths):
                    img = unloader(preds[i, :, :, :])
                    img.save(np)
                    del img
                model.to(device)
                del preds
                del image_batch

if __name__ == '__main__':
    main()


def color(x,y):
    x2 = str(x)
    y2 = str(y)
    if y2 in x2:
        rstr = "true"
    if y2 not in x2:
        rstr = "false"
    return rstr

x2 = "My favorite color: red."
print(x2)

y2 = input("red.")
print(y2)

ans = color(y2, x2)
print("color, ans")

print("rstr")


from django.shortcuts import render, redirect
import requests
from .models import City
from .forms import CityForm

def index(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=9c232263729a5d8323c4c23d763742c7'

    errorMsg = ''
    message = ''                #message the user will see
    message_class = ''          #the color the message will be

    if request.method == 'POST':
        form = CityForm(request.POST)

        if form.is_valid():
            new_city = form.cleaned_data['name']
            #filter out cities that have already been added
            exisiting_city = City.objects.filter(name=new_city).count()

            if exisiting_city == 0:
                r = requests.get(url.format(new_city)).json()
                #find city code to determine if city exists
                #print(r)
                if r['cod'] == 200:
                    form.save()
                else:
                    errorMsg = 'City does not exist!'
            else:
                errorMsg = "City already exists!"
        if errorMsg:
            message = errorMsg
        else:
            message = 'City added successfully!'

    #restart the form after submission
    form = CityForm()

    cities = City.objects.all()

    weather_data = []

    #loop thru each city in the database
    for city in cities:
        #call the requests to add the city to the url
        #call the json method to convert information to a json object
        r = requests.get(url.format(city)).json()

        #print was used to gather the neccessary information on the command line
        #print(r.text)

        #create a dictionary that holds the information needed to display the weather
        city_weather = {
            'city': city.name,                  #pass the name of the object not the object itself
            'temperature': r['main']['temp'],
            'description': r['weather'][0]['description'],
            'icon': r['weather'][0]['icon'],
        }

        #append the weather data to each city
        weather_data.append(city_weather)

    print(weather_data)

    context = {'weather_data': weather_data,
                'form': form,
                'message': message,
                }
    return render(request, 'weather/weather.html', context)

def delete_city(request, city_name):
    #query the city and delete it
    City.objects.get(name=city_name).delete()
    return redirect('home')


from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
from align_dataset import normal_align
from create_svm import create_svm

import tkinter
import cv2
import PIL.Image, PIL.ImageTk

from torchvision import datasets, transforms

import numpy as np
import os
import sys
import torch
import pickle
import cv2
import time
import argparse
import math
from Model.MobileFacenet import MobileFaceNet

sys.path.insert(1, "MTCNN")

from mtcnn import MTCNN
from detect_face import extract_face
from mtcnn import MTCNN, detect_face

from threading import Thread

window = Tk()
window.title('Face Recognition Terminal')

photo = None
switch = 0

FONT = cv2.FONT_HERSHEY_SIMPLEX

MAX_IMGS = 100
NROF_IMGS = 0

SVM_MODEL =  "../PretrainedModel/classifier.pkl"

device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
detector = MTCNN(image_size=112, device=device)

model = MobileFaceNet(512).to(torch.device("cuda:0"))
model.load_state_dict(torch.load('../PretrainedModel/model.pth'))

with open(SVM_MODEL, 'rb') as infile:
	(class_name, svm_model) = pickle.load(infile)

transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])

cap = cv2.VideoCapture(0)

def handleswitch():

	global switch
	switch = 1 - switch

def handleaddid():

	global switch
	global class_name, svm_model

	switch = 0
	SVM_MODEL =  "../PretrainedModel/classifier.pkl"

	if text_input.get() != '':

		add(text_input.get())
		normal_align()
		create_svm()

		with open(SVM_MODEL, 'rb') as infile:
			(class_name, svm_model) = pickle.load(infile)
		print('load done')

		return

	else:
		label.configure(text='Must Add Name of Identify')
		return

def save_face(img, save_dir):
	global NROF_IMGS, detector
	boxes, proba, points = detector.detect(img, select_largest=True, landmarks=True, proba=True)
	if boxes is not None:
		for box, point in zip(boxes, points):
			if NROF_IMGS < MAX_IMGS and proba > 0.99:
				NROF_IMGS+=1
				face = detect_face.extract_face(img, box, image_size=160)
				os.makedirs(os.path.dirname(save_dir + "%d.jpg"%(NROF_IMGS)) + "/", exist_ok=True)
				cv2.imwrite(save_dir + "%d.jpg"%(NROF_IMGS), face)
				print("Image Saved: "+ os.path.expanduser(save_dir + "%d.jpg"%(NROF_IMGS)))
	return

def add(name):
	nrof_lines = 256
	SAVE_DIR = "../Dataset/Processed/" + name + '/'

	if not cap.isOpened:
		raise RuntimeError("Cannot Open Video")

	add = 0

	start = time.time()
	while(add == 0):
		ret, frame = cap.read()
		img = cv2.flip(frame, 1)
		if frame is None:
			break
		(h, w) = img.shape[:2]
		radius = min(h, w)/2 - 50
		cv2.circle(img, (w//2, h//2), min(h,w), (0, 0, 0), min(h,w)+150)
		for i in range(np.int32(nrof_lines)):
			angle = 2 * math.pi * i / nrof_lines
			x, y = w//2 + math.sin(angle)*radius, h//2 + math.cos(angle)*radius
			pt1 = x, y
			pt2 = x + math.sin(angle)*10, y + math.cos(angle)*10
			cv2.line(img, tuple(np.int32(pt1)), tuple(np.int32(pt2)), (255, 255, 255), 1)

		percent = NROF_IMGS/MAX_IMGS
		nrof_big_lines = nrof_lines * percent
		n = 0
		while n < nrof_big_lines :
			angle = 2 * math.pi * n / nrof_lines
			x, y = w//2 + math.sin(angle)*radius, h//2 + math.cos(angle)*radius
			pt1 = x, y
			pt2 = x + math.sin(angle)*15, y + math.cos(angle)*15
			cv2.line(img, tuple(np.int32(pt1)), tuple(np.int32(pt2)), (255, 255, 255), 2)
			n += 1

		thread = Thread(target=save_face, args=(img, SAVE_DIR,))
		thread.start()
		start = time.time()

		boxes = detector.detect(img, select_largest=True, landmarks=False, proba=False)
		if boxes is not None:
			for box in boxes:
				cv2.putText(img, "Turn Head Around!", (10, 50), FONT, 1, (255, 255, 255), 2, cv2.LINE_AA)
				cv2.rectangle(img, tuple((np.int32(box[0]), np.int32(box[1]))), tuple((np.int32(box[2]), np.int32(box[3]))), (255, 255, 255), 1)
		if NROF_IMGS == MAX_IMGS:
			done_logo = cv2.imread("../Dataset/done.jpg")
			done_logo = cv2.resize(done_logo, (200, 200))
			done_logo = cv2.addWeighted(img[h//2-100:h//2+100,w//2-100:w//2+100,:],0.1,done_logo[0:200,0:200,:],0.9,0)
			img[h//2-100:h//2+100,w//2-100:w//2+100,:] = done_logo
			cv2.putText(img, "Press ""Q"" to Exit.", (h//2-100, w//2-100), FONT, 1, (255, 255, 255), 2, cv2.LINE_AA)
		cv2.imshow('preview', np.uint8(img))
		if cv2.waitKey(1) & 0xFF == ord('q'):
			break

	# cap.release()
	cv2.destroyAllWindows()

def Recognition(img):
	start = time.time()
	boxes, points = detector.detect(img, select_largest=True, proba=False, landmarks=True)

	if boxes is not None:
		for box in boxes:
			cv2.rectangle(img, tuple((np.int32(box[0]), np.int32(box[1]))), tuple((np.int32(box[2]), np.int32(box[3]))), (255, 255, 255), 1)
			face = extract_face(img, box, image_size=160)
			face = cv2.resize(face,(112,112))
			face = transform(face)
			face = face.type(torch.FloatTensor)
			face = torch.unsqueeze(face, 0)
			model.eval()
			with torch.no_grad():
			  face = face.to(torch.device("cuda:0"))
			  emb_buff = model(face).cpu()
			buff = emb_buff.numpy().reshape(1, -1)
			predictions = svm_model.predict_proba(buff).ravel()
			best_class_idxs = np.argmax(predictions)
			confidence = predictions[best_class_idxs]*100
			name = class_name.inverse_transform([best_class_idxs])
			predict_str = '%s: %.3f'%(name, confidence)
			print(predict_str)
			pos = tuple((np.int32(box[0]), np.int32(box[1])))
			cv2.putText(img, predict_str, pos, FONT, 0.5, (255, 255, 255), 1, cv2.LINE_AA)
	fps_str = 'fps: %d'%(1/(time.time() - start))
	cv2.putText(img, fps_str, (10, 50), FONT, 1, (255, 0, 0), 2, cv2.LINE_AA)
	return img

def Processing():

	global canvas, photo, switch

	if switch == 1:

		ret, frame = cap.read()

		frame = Recognition(frame)
		frame = cv2.resize(frame, (800,450))

		frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

		photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame))

		canvas.create_image(0,0, image = photo, anchor=tkinter.NW)

	elif switch == 0:

		frame = cv2.imread('nope.jpg')
		frame = cv2.resize(frame, (800,450))
		frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
		photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame))

		canvas.create_image(0,0, image = photo, anchor=tkinter.NW)

	window.after(15, Processing)

canvas = Canvas(window, width = 800, height= 450 , bg= "gray")
canvas.pack()

label = tkinter.Label(window, text='Add Id', font=('Times New Roman', 20))
label.pack()

text_input = Entry(window, width=10)
text_input.pack()

function = Button(window,text = "Add one more Identify", command=handleaddid)
function.pack()

start = Button(window,text = "Start/Stop Get Frame", command=handleswitch)
start.pack()

Processing()

window.mainloop()


import numpy as np
import matplotlib.pyplot as pl
import scipy.special as ss

def WishartDistribution(X, Cov, n):
    p = Cov.shape[0]
    A = 1 / ((n * np.sqrt(np.diag(Cov))) *
            ((n * p) * np.sqrt(2)) *
            np.sum(ss.gamma(n / 2)))
    B = np.sqrt(np.diag(X)) ** (n - p - 1)
    C = np.exp(-0.5 * np.trace(np.linalg.inv(Cov) * X))

    return A * B * C


######################################################################
## Imports
######################################################################

import matplotlib, DatasetFactory, Plotter, PlotWindow
matplotlib.use('TkAgg')

from tkinter import filedialog
import Filters

import sys
if sys.version_info[0] < 3:
    from Tkinter import *
else:
    from tkinter import *

######################################################################
## Core
######################################################################

class Core(Tk):
    """
    The core class is a container for the plotting class.

    """

    def __init__(self):
        """
        Constructor sets the wm_title and wm_geometry and initiates
        the main window.

        @return
        """
        Tk.__init__(self)

        self.wm_title("eCLAM")
        self.wm_geometry("480x400")

        self.dataset = None
        self.plotter = None
        self.lastSelectedPlot = 0

        self._init_window()
        self.base.lift()

    def _init_window(self):
        """
        Init_Window is called by the Core Constructor and initializes
        the variables needed to display the main window used for
        displaying plots.

        @return null
        """

        self.base = Frame(self)
        self.base.pack(fill=BOTH, expand=1)

        loadOptions = LabelFrame(self.base, text="Load options")
        loadOptions.pack(fill=X, padx=10, pady=5)

        self.label = Label(loadOptions, text="")
        self.selectedDir = self.label
        self.selectedDir.pack(side=LEFT)

        self.browse = Button(loadOptions, text="Load Data", command=self._setDirectory)
        self.browse.pack(side=LEFT)

        viewOptions = LabelFrame(self.base, text="View")
        viewOptions.pack(fill=X, padx=10)

        self.btnViewSpectro = Button(viewOptions, text="Spectrogram", command=lambda :self._showPlot(0))
        self.btnViewSpectro.pack(side=LEFT)

        self.btnViewPoint = Button(viewOptions, text="Point", command=lambda :self._showPlot(1))
        self.btnViewPoint.pack(side=LEFT)

        self.btnViewCycle = Button(viewOptions, text="Cycle", command=lambda :self._showPlot(2))
        self.btnViewCycle.pack(side=LEFT)

        controls = LabelFrame(self.base, text="General Controls")
        controls.pack(fill=X, padx=10)

        self.plotWindow = Frame(self.base)

        self.voltagePoint = IntVar()
        self.cyclePoint = IntVar()
        self.filterSetAppy = IntVar()

        self.chkApplyFilterSet = Checkbutton(controls, text="Apply Filter Set", variable=self.filterSetAppy, command=lambda : self.updatePlots(1))
        self.chkApplyFilterSet.pack(side=LEFT)

        self.sldVoltagePoint = Scale(controls, orient=HORIZONTAL, label="Voltage Point", from_=0, to=1600, variable=self.voltagePoint, command=self.updatePlots)
        self.sldTest1 = Scale(controls, orient=HORIZONTAL, label="test1", from_=0, to=1600, variable=self.test1, command=self.updatePlots)
        self.sldVoltagePoint.pack(side=LEFT, fill=X, pady=5, expand=True)

        self.sldCyclePoint = Scale(controls, orient=HORIZONTAL, label="Cycle Number", from_=0, to=102, variable=self.cyclePoint, command=self.updatePlots)
        self.sldTest2 = Scale(controls, orient=HORIZONTAL, label="test2", from_=0, to=1600, variable=self.test2, command=self.updatePlots)
        self.sldCyclePoint.pack(side=LEFT, fill=X, pady=5, expand=True)

        self.plotWindow.config(bg="black")
        self.plotWindow.pack()

    def _setDirectory(self):
        """

        @return
        """
        selected = filedialog.askdirectory()
        self.selectedDir.configure(text=selected)
        self.dataset = DatasetFactory.buildDataset(selected + '/')
        self.plotter = Plotter.Plotter(self.dataset)
        self._plotDataset()

    def updatePlots(self, event):
        """

        @param event:
        @return
        """
        if self.plotter == None:
            return
        if self.filterSetAppy.get():
            self.plotter.updateData(Filters.BackgroundSubtraction(self.dataset))
        else:
            self.plotter.updateData(self.dataset)
        self.spectra = PlotWindow.PlotWindow(self.plotWindow, self.plotter.createSpectra())
        self.lineHoriz = PlotWindow.PlotWindow(self.plotWindow, self.plotter.createYPointPlot(self.voltagePoint.get()))
        self.lineVert = PlotWindow.PlotWindow(self.plotWindow, self.plotter.createXPointPlot(self.cyclePoint.get()))
        self.plot = self._showPlot(self.lastSelectedPlot)

    def _showPlot(self, event):
        """
        ShowPlot takes an event as a parameter
        @param event:
        @return
        """
        self.lastSelectedPlot = event
        if (event == 0):
            self.spectra.grid(row=0, column=0)
            self.spectra.tkraise()
        elif(event == 1):
            self.lineHoriz.grid(row=0, column=0)
            self.lineHoriz.tkraise()
        elif(event == 2):
            self.lineVert.grid(row=0, column=0)
            self.lineVert.tkraise()
        else:
            raise Exception("Unknown Event code " +  str(event))

    def _plotDataset(self):
        """
        PlotDataset plots all three graphs from the dataset.
        @return
        """
        self.spectra = PlotWindow.PlotWindow(self.plotWindow, self.plotter.createSpectra())
        self.lineHoriz = PlotWindow.PlotWindow(self.plotWindow, self.plotter.createYPointPlot(self.cyclePoint.get()))
        self.lineVert = PlotWindow.PlotWindow(self.plotWindow, self.plotter.createXPointPlot(self.voltagePoint.get()))

######################################################################
## Main
######################################################################

app = Core()
app.mainloop()


# Course: ECE 3822
# Lab: 3
# Date: 9/11/2019
# Username: kuang
# Name: Kuang Jiang
# Description: Lab3 file
# File Name: lab3.py

##############################################################
#   Libraries
##############################################################
import os
import sys
import random
import numpy as np
from lab3_bsearch_Jiang import *
from lab3_cardsearch_Jiang import *

##############################################################
#   Variable Definition
##############################################################

##############################################################
#   Function Prototype
##############################################################
# Loop Function
# Loop calcualition for 1000 times and record the result
# Input: max_loop_number
# Output: result[result1, result2]
def circling(max_loop_number):
    for loop in range(0, max_loop_number):
        # print(loop)
        if loop == 0:
            # Start No.1
            data_set1 = set_generation(length=26, data_range=52)
            # print(data_set1)
            result1 = np.asarray(binary_search(data=data_set1, target=random.randint(1, 52)))

            # Start No.2
            data_set2 = start()
            target = [random.randint(1, 4), random.randint(1, 13)]
            result2 = np.asarray(card_search(data=data_set2, target=target))
        else:
            data_set1 = set_generation(length=26, data_range=52)
            result1 = np.row_stack((result1, np.asarray(binary_search(data=data_set1, target=random.randint(1, 52)))))
            data_set2 = start()
            target = [random.randint(1, 4), random.randint(1, 13)]
            result2 = np.row_stack((result2, np.asarray(card_search(data=data_set2, target=target))))

    sum1 = 0
    sum2 = 0
    for loop in range(0, result1.shape[0]):
        sum1 += result1[loop][1]
        sum2 += result2[loop][1]

    avg1 = sum1 / result1.shape[0]
    avg2 = sum2 / result2.shape[0]

    return[avg1, avg2]

##############################################################
#   Main Function
##############################################################
def main():
    print("Hello World!")
    [avg1, avg2] = circling(10000)
    print("Average Check Rate for BSearch is ", avg1)
    print("Average Check Rate for CSearch is ", avg2)

##############################################################
#    Main Function Runner
##############################################################
if __name__ == "__main__":
    main()


#!/usr/bin/python3

from pyrob.api import *

@task(delay=0.02)
def task_7_5():
    h = 0
    c = 1
    move_right()
    fill_cell()
    while not wall_is_on_the_right():
        move_right()
        h = h + 1
        if wall_is_on_the_right():
            break
        if (h % c) == 0:
            fill_cell()
            c = c + 1
            h = 0

if __name__ == '__main__':
    run_tasks()


import asyncio
import websockets
import functools
import json
import time
import base64
import requests

async def hello(websocket, path, i, newFile):
    try:
        async for message in  websocket:
            #print(message)
            #greeting = f"Hello {message}!"
            data = json.loads(message)

            if data["bk_telkom"]["type"] == "authDevice" :
                item = {"data":{
                        "status":200
                    }}
                data["bk_telkom"].update(item)
                res = json.dumps(data)
                i=0
                await websocket.send(res)
            elif data["bk_telkom"]["type"] == "audioConn" :

                newFile = open("audio.raw", "wb")
                item = {"data":{
                        "status":200
                    }}
                data["bk_telkom"].update(item)
                i=0
                res = json.dumps(data)
                await websocket.send(res)

            elif i > 10 :
                newFile.close()
                del data["bk_telkom"]["data"]
                item ={"data" :{"endpoint":True}
                }
                data["bk_telkom"].update(item)
                res = json.dumps(data)
                await websocket.send(res)
                time.sleep(2);
                del data["bk_telkom"]["data"]
                #item ={"data" :{"endpoint":False,"url":"test","intent":"ask_ganti_channel","entity":"102"}}
                print("set data")
                item = {"data": { "endpoint": False, "intent":{"name":"naikvolume", "confidence": 0.950077 }, "entity": { "start": 18, "end": 22, "value": "50", "entity": "channel_name", "confidence": 0.956165, "extractor":"ner_crf" }}}
                i=0
                data["bk_telkom"].update(item)

                link_tts = "http://dcganfrontend-loadbalancer-53387530.ap-southeast-1.elb.amazonaws.com/api/alpha2/synth"
                body = {
                    "text" : "channel di antara. .",
                    "key"  : "kunciuntuktelkom",
                    "audiotype":"ogg"
                }
                r = requests.post(link_tts, json=body, timeout=120)
                body = json.loads(r.text)
                print(body)
                body['url'] = body.pop('list')
                data["bk_telkom"]["data"].update(body)
                res = json.dumps(data)
                print(res)
                await websocket.send(res)
            else :
                baudio = data["bk_telkom"]["data"]["audio"]
                #print(baudio)
                #print(len(baudio))
                bytesaudio = base64.b64decode(baudio)
                #print(len(bytesaudio))

                try:
                    newFile.write(bytesaudio)
                except :
                    print("closed")
            i=i +1
    except:
        print("connection closed")
bound_handler = functools.partial(hello,i=0, newFile = None)

start_server = websockets.serve(bound_handler, '192.168.0.2', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


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

from setuptools import setup

with open("README.md", "r") as fh:
    long_description = fh.read()

requires = [
    'jsonschema>=2.6.0,<2.7.0',
    'pandas>=0.23.0,<0.24.0',
    'boto3>=1.9.0, <1.10.0',
    'requests>=2.20.0, <=2.21.0'
]

packages = ['ops_helpers']

setup(
    name="ops-lambda-python-helpers",
    version="0.0.41",
    author="David Fort",
    author_email="ptiger10@gmail.com",
    description="Helper functions for use with ops lambda functions",
    long_description=long_description,
    long_description_content_type="text/markdown",
    packages=packages,
    incude_package_data=True,
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires=">=3.6",
    install_requires=requires,
)


# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

'''
#선형회귀 :  변수들간의 관계를 분석하는데 필요한 통계학적 방법
# 독립변수 x, 상수항 b, 종속변수 y사이의 관계를 모델화
# x,y 두 변수만의 관계일 경우 단순회귀분석이라고 하고
# 여러개의 변수를 다룰 경우 다중회귀분석이라고 함.
'''

# y = W*x + b의 모델을 만들어보고 확인
num_points = 1000
vectors_set = []

for i in xrange(num_points):
	#x1을 0~0.55사이의 random값으로 set.
	x1 = np.random.normal(0.0, 0.55)
	#x,y(독립변수,종속변수)의 관계 정의
	y1 = x1*0.1 + 0.3 + np.random.normal(0.0, 0.03)
	#총 1000개의 좌표(독립,종속변수 쌍이)가vectors_set에 들어가게 된다.
	vectors_set.append([x1, y1])
#x좌표를 가져옴.
x_data = [v[0] for v in vectors_set]
#y좌표를 자져옴.
y_data = [v[1] for v in vectors_set]

plt.plot(x_data, y_data, 'ro', label='Original data')
plt.legend()
plt.show()


# -*- coding: utf-8 -*-
#
# Archéo Lex – Pure Histoire de la Loi française
# – crée un dépôt Git des lois françaises écrites en syntaxe Markdown
# – ce module assemble les textes et fait l’export final
#
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# the LICENSE file for more details.

# Imports
import datetime
import time
from marcheolex.utilitaires import comp_infini_large
from marcheolex.exports import *

class FabriqueArticle:

    def __init__( self, db, stockage, syntaxe, cache = None ):

        """
        :param db:
            Base de donnée.
        :param stockage:
            (Stockage) Classe modélisant le stockage.
        :param syntaxe:
            (Syntaxes) Classe modélisant la syntaxe.
        :param cache:
            boolean Utilisation d’un cache mémoire
        """

        self.db = db
        self.stockage = stockage
        self.syntaxe = syntaxe
        self.cache = cache

        self.articles = {}
        self.erreurs = []

    def effacer_cache(self):

        self.articles = {}

    def obtenir_texte_article( self, id, hierarchie, debut_vigueur_texte, fin_vigueur_texte ):

        """
        Obtenir le texte d’un article donné par un id.

        :param id:
            string - ID de l’article.
        :param hierarchie:
            [(str, str)] - Liste de couples (id, titre_ta) donnant le contexte dans la hiérarchie des titres.
        :param debut_vigueur_texte:
            datetime.date - date de début de vigueur demandée.
        :param fin_vigueur_texte:
            datetime.date - date de fin de vigueur autorisée par la requête.
        :returns:
            (string, string, datetime.date, datetime.date) - (num, texte, debut_vigueur, fin_vigueur) Numéro et texte de l’article, dates de début et fin de vigueur.
        """

        if id not in self.articles:

            article = self.db.one("""
                SELECT num, date_debut, date_fin, bloc_textuel, cid
                FROM articles
                WHERE id = '{0}'
            """.format(id))
            if not article:
                article = self.db.one("""
                    SELECT num, debut, fin
                    FROM sommaires
                    WHERE element = '{0}'
                """.format(id))
                if not article:
                    self._cache_article( id, 'INCONNU', None, None, '(article manquant)' )
                    self.erreurs.append( 'Article {0} inconnu (métadonnées inconnues)'.format(id) )
                else:
                    num, date_debut, date_fin = article
                    self._cache_article( id, num, date_debut, date_fin, '(article manquant)' )
                    self.articles[id] = (num, '(article manquant)', None, None )
                    self.erreurs.append( 'Article {0} inconnu (métadonnées connues : numéro={1}, date_debut={2}, date_fin={3})'.format(id, num, date_debut, date_fin) )
            else:
                num, date_debut, date_fin, bloc_textuel, cid = article

                articles = self.db.all("""
                    SELECT id, num, date_debut, date_fin, bloc_textuel
                    FROM articles
                    WHERE cid = '{0}'
                """.format(cid))

                for article in articles:

                    aid, num, date_debut, date_fin, bloc_textuel = article

                    self._cache_article( aid, num, date_debut, date_fin, bloc_textuel )

        num, texte_article, date_debut, date_fin = self.articles[id]

        # La période de vigueur de cet article est expiré ou expire : ne pas l’ajouter au texte (date_fin <= debut_vigueur_texte)
        # Le cas quasi-erroné où le texte n’a pas de début de vigueur est écarté ici, mais devrait probablement renvoyer une erreur ailleurs
        if debut_vigueur_texte and comp_infini_large( date_fin, debut_vigueur_texte ):
            return (num, None, date_debut, date_fin)

        # La période de vigueur de cet article n’est pas encore commencé (fin_vigueur_texte <= date_debut)
        # Les articles intemporels (= sans date de début de vigueur (et normalement sans date de fin de vigueur)) sont considérés comme toujours en vigueur
        if date_debut and comp_infini_large( fin_vigueur_texte, date_debut ):
            return (num, None, date_debut, date_fin)

        if not self.cache:
            self.effacer_cache()

        # Assemblage du texte
        num = num.strip() if num else ''
        texte_article = texte_article.strip()
        titre = 'Article ' + num if num else 'Article (non-numéroté)'
        hierarchie[-1] = (hierarchie[-1][0], id, titre)
        titre_formate = self.syntaxe.obtenir_titre( hierarchie, titre )
        texte_retourne = titre_formate + texte_article + '\n\n'

        # Enregistrement
        self.stockage.ecrire_ressource( id, hierarchie, num, '', texte_article )

        return (num, texte_retourne, date_debut, date_fin)

    def _cache_article( self, id, num, date_debut, date_fin, bloc_textuel ):

        """
        Fonction interne d’enregistrement dans le cache d’un article issu de la base de données.

        :param id:
            (str) ID de l’article.
        :param num:
            (str) Numéro de l’article.
        :param date_debut:
            (str) Date de début de vigueur demandée.
        :param date_fin:
            (str) Date de fin de vigueur autorisée par la requête.
        :param bloc_textuel:
            (str) Corps de l’article (en HTML).
        :returns:
            (None)
        """

        num = num.strip() if isinstance( num, str ) else ''

        date_debut = datetime.date(*(time.strptime(date_debut, '%Y-%m-%d')[0:3])) if date_debut != '2999-01-01' else None
        date_fin = datetime.date(*(time.strptime(date_fin, '%Y-%m-%d')[0:3])) if date_fin != '2999-01-01' else None

        texte_article = self.syntaxe.transformer_depuis_html( bloc_textuel )

        self.articles[id] = (num, texte_article, date_debut, date_fin)

# vim: set ts=4 sw=4 sts=4 et:


import media
import revs_movie_week

"""This file includes all of the information for the movie tiles."""

title_int = "Interstellar"  # Movie's Title Name
tagline_int = "Go Further"  # Movie's tag line
poster_int = "https://upload.wikimedia.org/wikipedia/en/b/bc/Interstellar_film_poster.jpg"  # URL link to poster
trailer_int = "https://youtu.be/Lm8p5rlrSkY"  # URL to youtube.com trailer
duration_int = "2h 49m"  # Length of the movie
rating_int = "PG-13"  # Movie's MPAA Rating
interstellar = media.Movie(title_int,  # Creates a class object for the film
                           tagline_int,
                           poster_int,
                           trailer_int,
                           duration_int,
                           rating_int)

title_mad = "Mad Max Fury Road"
tagline_mad = "The Future Belongs to the Mad"
poster_mad = "https://upload.wikimedia.org/wikipedia/en/6/6e/Mad_Max_Fury_Road.jpg"
trailer_mad = "https://youtu.be/hEJnMQG9ev8"
duration_mad = "2h"
rating_mad = "PG-13"
mad_max = media.Movie(title_mad,
                      tagline_mad,
                      poster_mad,
                      trailer_mad,
                      duration_mad,
                      rating_mad)

title_t2 = "Terminator 2: Judgement Day"
tagline_t2 = "It's Nothing Personal."
poster_t2 = "https://upload.wikimedia.org/wikipedia/en/8/85/Terminator2poster.jpg"
trailer_t2 = "https://youtu.be/7QXDPzx71jQ"
duration_t2 = "2h 36m"
rating_t2 = "R"
terminator2 = media.Movie(
                          title_t2,
                          tagline_t2,
                          poster_t2,
                          trailer_t2,
                          duration_t2,
                          rating_t2)

title_lego = "The Lego Movie"
tagline_lego = "The Story of a Nobody who Saved Everybody"
poster_lego = "https://upload.wikimedia.org/wikipedia/en/1/10/The_Lego_Movie_poster.jpg"
trailer_lego = "https://youtu.be/fZ_JOBCLF-I"
duration_lego = "1h 41m"
rating_lego = "PG"
lego_movie = media.Movie(
                         title_lego,
                         tagline_lego,
                         poster_lego,
                         trailer_lego,
                         duration_lego,
                         rating_lego)

title_tdk = "The Dark Knight"
tagline_tdk = "Welcome to a  World Without Rules"
poster_tdk = "https://upload.wikimedia.org/wikipedia/en/8/8a/Dark_Knight.jpg"
trailer_tdk = "https://youtu.be/EXeTwQWrcwY"
duration_tdk = "2h 32m"
rating_tdk = "PG-13"
the_dark_knight = media.Movie(
                              title_tdk,
                              tagline_tdk,
                              poster_tdk,
                              trailer_tdk,
                              duration_tdk,
                              rating_tdk)

title_tm = "Transformers Movie"
tagline_tm = "Beyond Good, Beyond Evil, Beyond your Wildest Imagination."
poster_tm = "https://upload.wikimedia.org/wikipedia/en/9/91/Transformers-movieposter-west.jpg"
trailer_tm = "https://youtu.be/Sh3HW3mZAoQ"
duration_tm = "1h 30m"
rating_tm = "PG"
transformers_the_movie = media.Movie(
                                     title_tm,
                                     tagline_tm,
                                     poster_tm,
                                     trailer_tm,
                                     duration_tm,
                                     rating_tm)

movies = [interstellar,
          mad_max,
          terminator2,
          lego_movie,
          the_dark_knight,
          transformers_the_movie]

# Calls the function inside the .py file that creates the HTML and passes
# the movie instances.
revs_movie_week.open_movies_page(movies)


import random
def main():

    lines = []
    temp_list = []
    humidity_list=[]
    pressure_list =[]
    number_of_sensors = 25
    #mean and standard deviation
    mu = 0
    sigma = 1
    with open('scenario2_output.txt') as f:
        lines = f.readlines()

        for line in lines:
            line = line.strip("\n")
            if not(line.find("Main") != -1 or line.find("reachable") != -1 or line.find("collected") != -1):
                data = line.split("#")
                data = data[1].split(",")
                listtostring = ' '.join([str(element) for (element) in data])
                listtostring = listtostring.split(" ")

                temp     = float(listtostring[2])
                humidity = float(listtostring[5])
                pressure = float(listtostring[8])

                temp_list.append(abs(25.0 - ((temp/number_of_sensors)+random.gauss(mu, sigma))))
                humidity_list.append(abs(40.0-((humidity/number_of_sensors)+random.gauss(mu, sigma))))
                pressure_list.append(abs(101000.0 - ((pressure/number_of_sensors)+random.gauss(mu, sigma))))

        smallest_Temp_error = min(temp_list)
        largest_Temp_error  = max(temp_list)
        average_Temp_error  = round(sum(temp_list)/len(temp_list),2)

        smallest_humidity_error = min(humidity_list)
        largest_humidity_error  = max(humidity_list)
        average_humidity_error  = round(sum(humidity_list)/len(humidity_list),2)

        smallest_pressure_error =  min(pressure_list)
        largest_pressure_error  = max(pressure_list)
        average_pressure_error  = round(sum(pressure_list)/len(pressure_list),2)

        print(f"smallest_Temp_error     = {smallest_Temp_error}, largest_Temp_error = {largest_Temp_error}, average_Temp_error = {average_Temp_error}\n")
        print(f"smallest_humidity_error = {smallest_humidity_error}, largest_humidity_error = {largest_humidity_error}, average_humidity_error = {average_humidity_error}\n")
        print(f"smallest_pressure_error = {smallest_pressure_error}, largest_pressure_error = {largest_pressure_error}, average_pressure_error = {average_pressure_error}\n")

main()


path="C:/Users/akshat.gupta/Downloads/amazon-reviews-analysis-master/amazon-reviews-analysis-master/data/"
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
import json
import gzip
import logging
import re
import cPickle
import pyLDAvis.gensim
from os.path import isfile
from sklearn.feature_extraction.text import CountVectorizer
from gensim.corpora import Dictionary
from gensim.models.lsimodel import LsiModel
from gensim.models.ldamodel import LdaModel
from gensim.models.tfidfmodel import TfidfModel
import pandas as pd
from atlas.config import dbConfig

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', \
                    level=logging.INFO)

def id2word(dictionary):
    id2word = {}
    for word in dictionary.token2id:
        id2word[dictionary.token2id[word]] = word
    return id2word

def train_lda_model(corpus, dictionary, num_topics):
    lda = LdaModel(corpus=corpus, num_topics=num_topics, id2word=id2word(dictionary), \
                    alpha=0.2, update_every=5, chunksize=10000, passes=10, iterations=50)
    return lda

def train_lsi_model(corpus, dictionary):
    lsi = LsiModel(corpus=corpus, id2word=id2word(dictionary), num_topics=20, chunksize=10000,\
                   onepass=True)
    return lsi

def get_tokeniser(ngram_range=(1, 1), stop_words='english'):
    vect = CountVectorizer(ngram_range=ngram_range, stop_words=stop_words,max_df=0.8, max_features=5000,
                                   min_df=0.2)
    return vect.build_analyzer()

def prettify(topics):
    return map(lambda ts: re.sub("\\s\+", ",", ts), map(lambda t: re.sub("(\d*\.\d*\*)", "", t), topics))

def save(data, file):
    fo = open(file, 'wb')
    cPickle.dump(data, fo, protocol=2)
    fo.close()

def load(file):
    fo = open(file, 'rb')
    data = cPickle.load(fo)
    fo.close()
    return data

def valid(chunks, product):
    for chunk in chunks:
        mask = (chunk['pCategory'] == product)
        if mask.all():
            yield chunk
        else:
            yield chunk.loc[mask]
            break

def main(request, num_topics):
    dataset_name = request
    tfidf_corpus_path = dbConfig.dict['topicModels'] + '%s_tfidf_corpus.pkl' % dataset_name
    tfidf_corpus = None
    #logging.info("inside main")

    #Reading only required rows
    status_code = 200
    #if not isfile(tfidf_corpus_path):
    try:
        if True:
            logging.warn("No saved models available. Generating corpus. This might take a while...")

            #logging.info("Loading data from text file")
            filename = dbConfig.dict['outputUrl']
            chunksize = 10 ** 5
            chunks = pd.read_csv(filename, chunksize=chunksize)
            df = pd.concat(valid(chunks, request))

            #lines = open(r'C:/Users/akshat.gupta/Downloads/amazon-reviews-analysis-master/amazon-reviews-analysis-master/data/data.csv').readlines()
            lines = df['rText'].tolist()

            #logging.info("Tokenising data")
            tokeniser = get_tokeniser()
            texts = map(lambda s: tokeniser(s), lines)

            #logging.info("Saving corpus texts")
            #save(texts, 'data/models/%s_texts.pkl' % dataset_name)
            save(texts, dbConfig.dict['topicModels'] + '%s_texts.pkl' % dataset_name)

            #logging.info("Generating bag of words")
            dictionary = Dictionary(texts)
            #save(dictionary, 'data/models/%s_dict.pkl' % dataset_name)
            save(texts, dbConfig.dict['topicModels'] + '%s_dict.pkl' % dataset_name)

            corpus = [dictionary.doc2bow(text) for text in texts]

            #logging.info("Saving bag of words")
            #save(corpus, 'data/models/%s_corpus.pkl' % dataset_name)
            save(texts, dbConfig.dict['topicModels'] + '%s_corpus.pkl' % dataset_name)

            #logging.info("Applying Tfidf model to corpus")
            tfidf = TfidfModel(corpus)
            tfidf_corpus = [tfidf[c] for c in corpus]

            #logging.info("Saving TF-IDF transformed corpus")
            save(tfidf_corpus, tfidf_corpus_path)
            #pyLDAvis.enable_notebook()

        else:
            #logging.info("Loading saved TF-IDF dictionary")
            dictionary = load(dbConfig.dict['topicModels'] + '%s_dict.pkl' % dataset_name)
            #corpus = load('C:/Users/akshat.gupta/Downloads/amazon-reviews-analysis-master/amazon-reviews-analysis-master/data/models/%s_corpus.pkl' % dataset_name)
            #logging.info("Loading saved TF-IDF corpus")
            tfidf_corpus = load(tfidf_corpus_path)

        # #logging.info("Training LSI model")
        # lsi = train_lsi_model(tfidf_corpus, dictionary)
        # lsi_topics = prettify(lsi.show_topics(-1))
        # lsi_topic_distribution = [l for l in lsi[tfidf_corpus]]

        #logging.info("Training LDA model")
        lda = train_lda_model(tfidf_corpus, dictionary, num_topics)

        p = pyLDAvis.gensim.prepare(lda, tfidf_corpus, dictionary)
        pyLDAvis.save_html(p, dbConfig.dict['topicViz'] + request + ".html")
        #lda_raw_topics = lda.show_topics(-1)
        #lda_pretty_topics = prettify(lda.show_topics(-1))
        #lda_topic_distribution = [l for l in lda[tfidf_corpus]]

    except:
        status_code = 500

    return status_code


"""
Date: Feb 17th, 2020
Dev: franco@sustemaggency.com

bot_actions/views/data.py
"""

import json
import datetime
import urllib.parse
from time import gmtime, strftime

from flask_cors import CORS, cross_origin
from flask import session, request, jsonify, make_response
from flask import Blueprint, render_template, redirect, url_for

from utils.auth import auth
from utils.utilities import utils
from utils.dynamo_client import dynamoInterface

data = Blueprint('data', __name__)

# Grant access on CORS
CORS(data)

# Init the class container for methods to use
utils = utils()

# Init the decorator for authentication
auth = auth()

# Starting the DynamoDB interface
dynamo = dynamoInterface(table_name='ma_bot_actions'); dynamo.connect()

@data.route('/createItem', methods=['POST'])
@auth.restricted(dynamo)
def create(actual_user):

    _item, item = request.args.to_dict(), {}
    item['gsidataportion'] = _item.pop('gsidataportion')
    item.update(_item)

    if item['gsidataportion'] in ['ig_bio', 'ig_followings']:
        _ig = utils.check_ig_format(ig=item['pkurl'])
        item['pkurl'] = 'https://www.instagram.com/{}/'.format(_ig)

    elif item['gsidataportion'] == 'sa_signature':

        item['phone'] = '+' + item['phone'][1:]

        if item['phone_two']:
            item['phone_two'] = '+' + item['phone_two'][1:]

        if (type(item['select_for_msg']) == str ):
            item['select_for_msg'] = item['select_for_msg'] == 'true' # bool

        # TODO: Create the signature
        s3_info = utils.signature_maker(data=item, output=True)
        item['s3_file'] = s3_info['s3_file']

        print("Create signature member")
        print(item); print('\n\n')

    for _ in list(item.keys()):
        if item['gsidataportion'] == 'sa_signature' and item[_] == "":
            item.pop(_)
        elif item['gsidataportion'] != 'sa_signature' and not item[_]:
            item.pop(_)

    dynamo.insert(item=item)

    # Element inserted: 201
    return jsonify({'Message': 'Element created'}), 201

@data.route('/queryItems', methods=['GET'])
@auth.restricted(dynamo)
def query(actual_user):
    """The Read section for the CRUD.

    Will read the params from the url and converted into a dictionary.

    The first element of the dictionary will be GSI, it is a requirement
    hold the GSI at the first position of the dictionary.

    :param actual_user dict, will contain the elements returned by
    the autentication

    :output dict, hold the results of the query.
    """

    _args, args, output = {}, {}, None
    _args = request.args.to_dict()
    # print('\n\n'); print('_args', _args)
    args['gsidataportion'] = _args.pop('gsidataportion')
    args.update(_args)

    if len(args.keys()) > 1:
        for _ in list(args.keys()):
            if not args[_]: args.pop(_)

    output = dynamo.query_items(arguments=args, debug_query=False)

    return jsonify(output["Items"]), 200

@data.route('/updateItem', methods=['PUT'])
@auth.restricted(dynamo)
def update(actual_user):
    del_attrs = ""
    gsi = ""

    key = {
        'pkurl': request.args.get('pkurl')
    }

    args = {
        'date_in': utils.date_formating(),
        'progress': request.args.get('progress')
    }

    if request.args.get('gsidataportion') == 'agency':
        args.update({
            'country': request.args.get('country'),
            'url_name': request.args.get('url_name')
        })

    elif request.args.get('gsidataportion') == 'sa_signature':
        args = request.args.to_dict()

        gsi = args.pop('gsidataportion')
        args.pop('pkurl')

        if (type(args['select_for_msg']) == str ):
            args['select_for_msg'] = (args['select_for_msg'] == 'true') # bool

        try:
            # Deleting not important attrs.
            del_attrs = args.pop('delete_item').split(',')
            dynamo.update_big(
                {'pkurl': key['pkurl'], 'deletes': del_attrs}, debug_query=False)
        except KeyError:
            pass

        args['phone'] = '+' + args['phone'][1:]
        try:
            if args['phone_two']:
                args['phone_two'] = '+' + args['phone_two'][1:]
        except KeyError:
            pass

    for _ in list(args.keys()):
        if gsi == 'sa_signature' and args[_] == "":
            args.pop(_)
        elif gsi != 'sa_signature' and not args[_]:
            args.pop(_)

    return dynamo.update(args, key, debug=True)

@data.route('/deleteItem', methods=['DELETE'])
@auth.restricted(dynamo)
def delete(actual_user):
    key = {
        "pkurl": request.args.get('pkurl')
    }

    return dynamo.delete(key=key)


from Case import Case
from Type import Type
from Deplacement import Deplacement

class Labyrinthe:
    def __init__(self, taille):
        self.labyrinthe = []
        self.arrive = 0
        self.depart = 0
        self.taille = taille

    def chargerLabyrinthe(self,lab_txt):
        #Creation manuel du labyrinthe pour avancer rapidement
        for i in range(self.taille):
            self.labyrinthe.append([])
            for j in range(self.taille):
                if (lab_txt[i][j] == 'v'):
                    self.labyrinthe[i].append(Case(Type.Libre, i,j))
                if (lab_txt[i][j] == 'm'):
                    self.labyrinthe[i].append(Case(Type.Mur, i,j))
                if (lab_txt[i][j] == 's'):
                    self.labyrinthe[i].append(Case(Type.Sortie, i,j))
                    self.arrive = (i,j)
                if (lab_txt[i][j] == 'e'):
                    self.labyrinthe[i].append(Case(Type.Entree, i,j))
                    self.depart = (i,j)
                if (lab_txt[i][j] == 'p'):
                    self.labyrinthe[i].append(Case(Type.Piege, i,j))

    def deplacement_possible(self, case):
        deplacement_possible = []
        for i in range(case.x-1 ,case.x+2 ):
            if i>=0 and i<self.taille :
                if self.labyrinthe[i][case.y].type.name != 'Mur' :
                    if i-case.x==1 :
                        deplacement_possible.append(Deplacement.SUD)
                    elif i-case.x == -1:
                        deplacement_possible.append(Deplacement.NORD)
        for j in range(case.y-1, case.y+2):
            if j>=0 and j<self.taille :
                if self.labyrinthe[case.x][j].type.name != 'Mur' :
                    if j-case.y == 1 :
                        deplacement_possible.append(Deplacement.EST)
                    elif j-case.y == -1 :
                        deplacement_possible.append(Deplacement.OUEST)
        return deplacement_possible

    def se_deplacer(self, case, deplacement):
        renfort = 0
        if deplacement == Deplacement.NORD or deplacement == Deplacement.SUD:
            case_arriver = self.labyrinthe[int(case.x+deplacement.value/abs(deplacement.value))][case.y]
        else:
            case_arriver = self.labyrinthe[case.x][case.y+deplacement.value]
        renfort = case_arriver.type.value
        return (renfort, case_arriver)

    def getArrive(self):
        return self.arrive

    def getDepart(self):
        return self.depart

    def afficherLab(self):
        for i in range(self.taille):
            for j in range(self.taille):
                print(str(self.labyrinthe[i][j].type.name) + ' ', end='')
            print()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File    : code_03_InsertSort.py
# @Author  : yunch
# @Time    : 2018/8/11 20:22
# @IDE     : PyCharm 2018

import checker.sort_checker

def insert_sort(lyst):
    if lyst == None or len(lyst) < 2:
        return

    length = len(lyst)
    for i in range(1, length):  # i从第二个元素开始遍历所有元素
        j = i - 1  # j取初始值0，初始有序序列只有一个元素，为第一个
        while j >= 0:  # 从后向前遍历这个有序序列
            # 相当于基准值与原序列构成一个新的序列，进行顺序微调。
            if lyst[j + 1] < lyst[j]:  # 从基准值开始与有序序列的最后一个元素进行比较
                lyst[j + 1], lyst[j] = lyst[j], lyst[j + 1]  # 满足条件时进行交换
                j -= 1  # 索引序号-1，向前一个元素
            else:
                break
    return lyst

if __name__ == "__main__":
    checker.sort_checker.algorithm_checker(insert_sort)


from fastapi import Depends, APIRouter, HTTPException
from typing import List
from sqlalchemy.orm import Session
from app.schemas import user_schema
from app.deliveries import user_delivery
from app.middlewares import deps

router = APIRouter()

@router.get("/")
async def read_main():
    return {"msg": "Hello World"}

@router.post("/users/", response_model=user_schema.User)
def create_user(user: user_schema.UserCreate, db: Session = Depends(deps.get_db)):
    db_user = user_delivery.get_user_by_email(db, email=user.email)
    if db_user:
        raise HTTPException(status_code=400, detail="Email already registered")
    return user_delivery.create_user(db=db, user=user)

@router.get("/users/", response_model=List[user_schema.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(deps.get_db)):
    users = user_delivery.get_users(db, skip=skip, limit=limit)
    return users

@router.get("/users/{user_id}", response_model=user_schema.User)
def read_user(user_id: int, db: Session = Depends(deps.get_db)):
    db_user = user_delivery.get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user


"""
Jos Hens (5737222), Luka van der Plas (4119142), Andrea Scorza (6649173)
Methods in AI Research
Assignment 1c

This file matches keywords to input strings.
"""

from restaurantinfo import restaurantInfo
import Levenshtein

def findMatch(string, input):
    distancelist = []
    for word in input.split():
        distance = Levenshtein.distance(word, string)
        distancelist.append(distance)

    return min(distancelist)

def extractpreferences (input, editdistance=0):
    user_preferences = {'food': None, 'area': None, 'pricerange': None}

    #extract food preferences based on Levenshtein (when applicable)
    food_distances = dict()
    for food in foods:
        distance = findMatch(food, input)
        food_distances[food] = distance
    bestFmatch = min(food_distances, key=food_distances.get)
    if food_distances[bestFmatch] <= editdistance:
        user_preferences['food'] = bestFmatch

    #extract area preferences based on Levenshtein (when applicable)
    area_distances = dict()
    for area in areas:
        distance = findMatch(area, input)
        area_distances[area] = distance
    bestAmatch = min(area_distances, key=area_distances.get)
    if area_distances[bestAmatch] <= editdistance:
        user_preferences['area'] = bestAmatch

    #extract pricerange preferences based on Levenshtein (when applicable)
    price_distances = dict()
    for price in priceranges:
        distance = findMatch(price, input)
        price_distances[price] = distance
    bestPmatch = min(price_distances, key=price_distances.get)
    if price_distances[bestPmatch] <= editdistance:
        user_preferences['pricerange'] = bestPmatch

    return user_preferences

#import restaurant data
rdata = restaurantInfo('./restaurantinfo.csv')

#extract known preference options
priceranges = set()
areas = set()
foods = set()

for restaurant in rdata:
    priceranges.add(rdata[restaurant]['pricerange'])
    areas.add(rdata[restaurant]['area'])
    foods.add(rdata[restaurant]['food'])

areas.remove('') #some restaurants have blank area field

priceranges = list(priceranges)
areas = list(areas)
foods = list(foods)

# extractpreferences('i want moderately priced moroccan food in the center area of town')
# testing
"""
trainfile = open('./trainData.txt', 'r')
data = trainfile.readlines()
trainfile.close()

errors = 0
total = 0
for line in data:
    words = line.split()
    true_tag = words[0]
    sentence = " ".join(words[1:])
    estimated_tag = rulebaseline(sentence)
    total += 1
    if estimated_tag != true_tag:
        errors += 1
        #print(sentence)
        #print('Real tag:', true_tag)
        #print('Estimated tag:', estimated_tag)
        #print()

print('errors:', errors)
print('error rate:', errors / total)
"""


#!/usr/bin/python
# -*- coding: UTF-8 -*-
###############################################################################
# Module:   WeatherMiniChallenge.py    Autor: Felipe Almeida                  #
# Start:    29-Jul-2019                Last Update: 29-Jul-2019  Version: 1.0 #
###############################################################################

import sys
import requests
import json
from datetime import datetime, timezone
import calendar

OWM_ApiKey = '11111111111111111111111111111111'
OWM_EndPoint = 'api.openweathermap.org'
OWM_Version = '2.5'
OWM_GlobalUrl = 'https://'+OWM_EndPoint+'/data/'+OWM_Version+'/'

def GetWeatherForecast(v_CityId=-1):
    global OWM_ApiKey, OWM_GlobalUrl

    StrReturn = ''
    PrevWeekDay = ''

    if v_CityId == -1:
        return -1
    else:
        Url = OWM_GlobalUrl + 'forecast'
        QueryString = {
            'APPID': OWM_ApiKey,
            'id': v_CityId,
            'cnt': 40  # 5 days, 3 Hours Interval
        }
        Headers = {
            'User-Agent': "Mozilla/5.0",
            'Accept': "*/*",
            'Cache-Control': "no-cache",
            'Host': "openweathermap.org",
            'accept-encoding': "gzip, deflate",
            'Connection': "keep-alive",
            'cache-control': "no-cache"
        }
        Response = requests.request("GET", Url, headers=Headers,
                                    params=QueryString)
        jResponse = json.loads(Response.text)
        # print(json.dumps(jResponse, indent=4, sort_keys=True))
        CityName = jResponse['city']['name']+', '+jResponse['city']['country']
        for jDay in jResponse['list']:
            UnixTSDate = jDay['dt']
            Humidity = jDay['main']['humidity']
            dtDataDate = datetime.fromtimestamp(UnixTSDate, timezone.utc)
            StrWeekDay = calendar.day_name[dtDataDate.weekday()]
            StrDataHour = dtDataDate.strftime("%H")

            if (Humidity > 70):
                if (StrWeekDay == PrevWeekDay):
                    StrReturn = StrReturn+StrDataHour+','
                else:
                    StrReturn = (StrReturn[:-1] + '), ' + StrWeekDay +
                                 ' @('+StrDataHour+',')
                PrevWeekDay = StrWeekDay

    StrReturn = StrReturn[2:-1].strip() + ')'
    print('You should take an umbrella in "' + CityName +
          '" in these days/hours: ' + StrReturn)
    return 0

def GetCityId(v_CityName='São Paulo'):
    global OWM_ApiKey, OWM_GlobalUrl

    CityCode = 0
    Url = OWM_GlobalUrl + 'weather'
    QueryString = {
        'APPID': OWM_ApiKey,
        'q': v_CityName
    }
    Headers = {
        'User-Agent': "Mozilla/5.0",
        'Accept': "*/*",
        'Cache-Control': "no-cache",
        'Host': "openweathermap.org",
        'accept-encoding': "gzip, deflate",
        'Connection': "keep-alive",
        'cache-control': "no-cache"
    }
    Response = requests.request("GET", Url, headers=Headers,
                                params=QueryString)
    jResponse = json.loads(Response.text)
    try:
        if v_CityName == jResponse['name']:
            CityCode = jResponse['id']
    except:
        CityCode = -1

    return CityCode

def MainProcess():
    CityName = 'Ribeirão Preto'

    if (GetWeatherForecast(GetCityId(CityName)) == -1):
        print('Invalid City Name')
        sys.exit(1)

def main():
    try:
        MainProcess()
        sys.exit(0)
    except KeyboardInterrupt:
        print("Weather Mini Challenge Interrupted!")
        sys.exit(1)

if __name__ == "__main__":
    main()


"""Flask app for Cupcakes"""
from flask import Flask, request, redirect, render_template, flash, jsonify
from flask_debugtoolbar import DebugToolbarExtension
from models import db, connect_db, Cupcake

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///cupcakes'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
app.config['SECRET_KEY'] = "SECRET!"
debug = DebugToolbarExtension(app)

connect_db(app)

@app.route("/")
def show_home_page():
    return render_template("index.html")

def serialize_cupcake(cupcake):
    """Serialize a Cupcake SQLAlchemy obj to dictionary."""

    return {
        "id": cupcake.id,
        "flavor": cupcake.flavor,
        "size": cupcake.size,
        "rating": cupcake.rating,
        "image": cupcake.image
    }

@app.route('/api/cupcakes')
def get_all_cupcakes():
    """Returns JSON data for all cupcakes"""
    cupcakes = Cupcake.query.all()
    serialized = [serialize_cupcake(c) for c in cupcakes]
    return jsonify(cupcakes=serialized)

@app.route('/api/cupcakes/<int:cupcake_id>')
def get_single_cupcake(cupcake_id):
    """Returns JSON data for single cupcake"""
    cupcake = Cupcake.query.get_or_404(cupcake_id)
    serialized = serialize_cupcake(cupcake)
    return jsonify(cupcake=serialized)

@app.route('/api/cupcakes', methods=['POST'])
def create_cupcake():
    """Creates cupcake object from data in request.
    Responds with JSON data of new cupcake."""
    flavor = request.json["flavor"]
    size = request.json["size"]
    rating = float(request.json["rating"])
    if request.json["image"]:
        image = request.json["image"]
    else:
        image = None
    new_cupcake = Cupcake(flavor=flavor, size=size, rating=rating, image=image)
    db.session.add(new_cupcake)
    db.session.commit()
    serialized = serialize_cupcake(new_cupcake)
    return ( jsonify(cupcake=serialized), 201 )

@app.route('/api/cupcakes/<int:cupcake_id>', methods=['PATCH'])
def update_cupcake(cupcake_id):
    cupcake = Cupcake.query.get_or_404(cupcake_id)
    cupcake.flavor = request.json.get("flavor") if request.json.get("flavor") else cupcake.flavor
    cupcake.size = request.json.get("size") if request.json.get("size") else cupcake.size
    cupcake.rating = float(request.json.get("rating")) if request.json.get("rating") else cupcake.rating
    cupcake.image = request.json.get("image") if request.json.get("image") else cupcake.image
    db.session.add(cupcake)
    db.session.commit()
    serialized = serialize_cupcake(cupcake)
    return jsonify(cupcake=serialized)

@app.route('/api/cupcakes/<int:cupcake_id>', methods=['DELETE'])
def delete_cupcake(cupcake_id):
    """Delete a single cupcake"""
    cupcake = Cupcake.query.get_or_404(cupcake_id)
    Cupcake.query.filter_by(id=cupcake.id).delete()
    db.session.commit()
    return jsonify({"message": "Cupcake deleted."})


from model import common
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
import model.arch_util as mutil
def make_model(args, parent=False):
    return MARDN(args)

# branch fusion with channel-wise sub-network attention
class FusionLayer(nn.Module):
    def __init__(self, channel, reduction=16):
        super(FusionLayer, self).__init__()
        self.avg_pool1 = nn.AdaptiveAvgPool2d(1)
        self.avg_pool2 = nn.AdaptiveAvgPool2d(1)
        self.avg_pool3 = nn.AdaptiveAvgPool2d(1)
        # Squeeze and excitation
        self.se_x1 = nn.Sequential(
            nn.Conv2d(channel, channel // reduction, 1, padding=0, bias=True),
            nn.ReLU(inplace=True),
            nn.Conv2d(channel // reduction, channel, 1, padding=0, bias=True),
        )
        self.se_x2 = nn.Sequential(
            nn.Conv2d(channel, channel // reduction, 1, padding=0, bias=True),
            nn.ReLU(inplace=True),
            nn.Conv2d(channel // reduction, channel, 1, padding=0, bias=True),
        )
        self.se_x3 = nn.Sequential(
            nn.Conv2d(channel, channel // reduction, 1, padding=0, bias=True),
            nn.ReLU(inplace=True),
            nn.Conv2d(channel // reduction, channel, 1, padding=0, bias=True),
        )
        self.softmax = nn.Softmax(dim=2)
    def forward(self, x):
        if len(x) == 2:
            avg_x1 = self.se_x1(self.avg_pool1(x[0]))
            avg_x2 = self.se_x2(self.avg_pool2(x[1]))
            attens = self.softmax(torch.cat([avg_x1, avg_x2], 2))
            y = attens[:, :, 0, :].unsqueeze(2) * x[0] + attens[:, :, 1, :].unsqueeze(2) * x[1]
        elif len(x) == 3:
            avg_x1 = self.se_x1(self.avg_pool1(x[0]))
            avg_x2 = self.se_x2(self.avg_pool2(x[1]))
            avg_x3 = self.se_x3(self.avg_pool3(x[2]))
            attens = self.softmax(torch.cat([avg_x1, avg_x2, avg_x3], 2))

            y = attens[:, :, 0, :].unsqueeze(2) * x[0] + attens[:, :, 1, :].unsqueeze(2) * x[1] + \
                attens[:, :, 2, :].unsqueeze(2) * x[2]
        return y

class SpatialAttention(nn.Module):
    def __init__(self, n_feas):
        super(SpatialAttention, self).__init__()
        self.con1x1_pool = nn.Conv2d(n_feas, 1, 1)
        self.con1 = nn.Conv2d(3, 1, 1, bias=False)
        self.sig = nn.Sigmoid()

    def forward(self, x):
        avg_out = torch.mean(x, dim=1, keepdim=True)
        max_out, _ = torch.max(x, dim=1, keepdim=True)
        con_out = self.con1x1_pool(x)
        y = self.sig(self.con1(torch.cat([avg_out, max_out, con_out], 1)))

        return x*y

class ARDU(nn.Module):
    def __init__(self, nf=64, gc=32, bias=True):
        super(ARDU, self).__init__()
        # gc: growth channel, i.e. intermediate channels
        self.conv1 = nn.Conv2d(nf, gc, 3, 1, 1, bias=bias)
        self.conv2 = nn.Conv2d(nf + gc, gc, 3, 1, 1, bias=bias)
        self.conv3 = nn.Conv2d(nf + 2 * gc, gc, 3, 1, 1, bias=bias)
        self.conv4 = nn.Conv2d(nf + 3 * gc, gc, 3, 1, 1, bias=bias)
        self.conv5 = nn.Conv2d(nf + 4 * gc, nf, 3, 1, 1, bias=bias)
        self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
        self.spatialAttention = SpatialAttention(nf)
        # initialization
        mutil.initialize_weights([self.conv1, self.conv2, self.conv3, self.conv4, self.conv5], 0.1)

    def forward(self, x):
        x1 = self.lrelu(self.conv1(x))
        x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))
        x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))
        x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))
        x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
        x5 = self.spatialAttention(x5)
        return x5 + x

class ARDB(nn.Module):
    '''Space-attended Residual Dense Block'''

    def __init__(self, nf, gc=32):
        super(ARDB, self).__init__()
        self.RDB1 = ARDU(nf, gc)
        self.RDB2 = ARDU(nf, gc)
        self.RDB3 = ARDU(nf, gc)
    def forward(self, x):
        out = self.RDB1(x)
        out = self.RDB2(out)
        out = self.RDB3(out)
        return out * 0.2 + x

class MARDN(nn.Module):
    def __init__(self, args, conv=common.default_conv):
        super(MARDN, self).__init__()
        n_rrdb_b1 = args.n_level1
        n_rrdb_b2 = args.n_level2
        n_rrdb_b3 = args.n_level3
        n_feats = args.n_feats
        kernel_size = 3
        self.scale = args.scale[0]

        # RGB mean for DIV2K
        self.sub_mean = common.MeanShift(args.rgb_range)
        modules_head = [conv(args.n_colors, n_feats, kernel_size)]
        # module body
        # Each branch represents a sub-network
        ARDB_block_f = functools.partial(ARDB, nf=n_feats)
        # branch I
        modules_b1s1 = []
        modules_b1s2 = []
        modules_b1s3 = []
        for _ in range(n_rrdb_b1):
            modules_b1s1.append(ARDB_block_f())
            modules_b1s2.append(ARDB_block_f())
            modules_b1s3.append(ARDB_block_f())
        # branch II
        modules_b2s2 = []
        modules_b2s3 = []
        for _ in range(n_rrdb_b2):
            modules_b2s2.append(ARDB_block_f())
            modules_b2s3.append(ARDB_block_f())
        # branch III
        modules_b3s3 = []
        for _ in range(n_rrdb_b3):
            modules_b3s3.append(ARDB_block_f())

        # fusion layer
        self.furLayerb1s3 = FusionLayer(n_feats)
        self.furLayerb2s2 = FusionLayer(n_feats)
        self.furLayerb2s3 = FusionLayer(n_feats)
        self.furLayerb3s3 = FusionLayer(n_feats)
        self.furLayerFin = FusionLayer(n_feats)
        modules_tail = [
            conv(n_feats, args.n_colors, kernel_size)]
        modules_tail_1dot5 = [
            conv(n_feats, n_feats, kernel_size),
            conv(n_feats, args.n_colors, kernel_size)]
        modules_tailx2 = [
            common.Upsampler(conv, 2, n_feats, act=False),
            conv(n_feats, args.n_colors, kernel_size)]
        modules_tailx4 = [
            common.Upsampler(conv, 4, n_feats, act=False),
            conv(n_feats, args.n_colors, kernel_size)]
        self.conv_1x1 = nn.Sequential(
            nn.Conv2d(n_feats*2, n_feats, 1, padding=0, bias=True),
            nn.ReLU(inplace=True)
        )
        self.conv_1x1_3 = nn.Sequential(
            nn.Conv2d(n_feats * 3, n_feats, 1, padding=0, bias=True),
            nn.ReLU(inplace=True)
        )
        self.head = nn.Sequential(*modules_head)
        self.modules_b1s1 = nn.Sequential(*modules_b1s1)
        self.modules_b1s2 = nn.Sequential(*modules_b1s2)
        self.modules_b1s3 = nn.Sequential(*modules_b1s3)
        self.modules_b2s2 = nn.Sequential(*modules_b2s2)
        self.modules_b2s3 = nn.Sequential(*modules_b2s3)
        self.modules_b3s3 = nn.Sequential(*modules_b3s3)
        self.add_mean = common.MeanShift(args.rgb_range, sign=1)
        # Upsample modules
        self.tail = nn.Sequential(*modules_tail)
        self.tail_1dot5 = nn.Sequential(*modules_tail_1dot5)
        self.tailx2 = nn.Sequential(*modules_tailx2)
        self.tailx4 = nn.Sequential(*modules_tailx4)
    def forward(self, x):
        x = self.sub_mean(x)
        # shallow feature extraction module
        x = self.head(x)
        # deep feature extraction module
        xh, xw = x.size(2), x.size(3)
        x_res = F.interpolate(x, size=(xh * 2, xw * 2), mode='bilinear', align_corners=False)  # bilinear
        # Stage I
        x_b1 = F.interpolate(x, size=(xh//2, xw//2), mode='bilinear', align_corners=False)   # bilinear
        x_b1 = self.modules_b1s1(x_b1)
        # Stage II
        x_b2 = self.furLayerb2s2([F.interpolate(x_b1, size=(xh, xw), mode='bilinear', align_corners=False), x])
        x_b2 = self.modules_b2s2(x_b2)
        x_b1 = self.modules_b1s2(x_b1)
        # Stage III
        x_b3 = self.furLayerb3s3([F.interpolate(x_b1, size=(xh*2, xw*2), mode='bilinear', align_corners=False),\
                                  F.interpolate(x_b2, size=(xh*2, xw*2), mode='bilinear', align_corners=False)])
        x_temp = self.furLayerb1s3([x_b1, F.interpolate(x_b2, size=(xh//2, xw//2), mode='bilinear', align_corners=False)])
        x_b2 = self.furLayerb2s3([F.interpolate(x_b1, size=(xh, xw), mode='bilinear', align_corners=False), x_b2])
        x_b1 = x_temp
        x_b3 = self.modules_b3s3(x_b3)
        x_b2 = self.modules_b2s3(x_b2)
        x_b1 = self.modules_b1s3(x_b1)

        res = self.furLayerFin([F.interpolate(x_b1, size=(2*xh, 2*xw), mode='bilinear', align_corners=False),\
                                F.interpolate(x_b2, size=(2*xh, 2*xw), mode='bilinear', align_corners=False), x_b3])
        res = res + x_res
        # Upscaling and reconstruct module
        if self.scale == 2:
            x = self.tail(res)
        elif self.scale == 3:
            x = F.interpolate(res, size=(3*xh, 3*xw), mode='bilinear', align_corners=False)
            x = self.tail_1dot5(x)
        elif self.scale == 4:
            x = self.tailx2(res)
        elif self.scale == 8:
            x = self.tailx4(res)
        x = self.add_mean(x)

        return x