def on_button_pressed_a():
    global master
    master = not (master)
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_received_value(name, value):
    global temperature, light_level, light_angle, temperature_angle
    if master:
        if name == "temp":
            temperature = value
        elif name == "light":
            light_level = value
        light_angle = Math.floor(Math.map(light_level, 0, 255, 0, 180))
        temperature_angle = Math.floor(Math.map(temperature, -5, 50, 0, 180))
        serial.write_numbers([light_angle, temperature_angle])
        servos.P0.set_angle(temperature_angle)
        servos.P1.set_angle(light_angle)
    basic.pause(1000)
radio.on_received_value(on_received_value)

temperature_angle = 0
light_angle = 0
light_level = 0
temperature = 0
master = False
serial.redirect_to_usb()
master = False
radio.set_group(42)
temperature = 0
light_level = 0

def on_forever():
    global temperature, light_level
    if not (master):
        servos.P0.set_angle(0)
        servos.P1.set_angle(0)
        temperature = input.temperature()
        light_level = input.light_level()
        radio.send_value("temp", temperature)
        radio.send_value("light", light_level)
        basic.pause(2000)
    basic.pause(1000)
basic.forever(on_forever)

def on_forever2():
    if master:
        whaleysans.show_number(abs(temperature))
        basic.pause(2000)
        whaleysans.show_number(Math.floor(Math.map(light_level, 0, 255, 0, 99)))
    basic.pause(2000)
basic.forever(on_forever2)


import numpy as np
import matplotlib.pyplot as plt

def visualize(path, fitness, best_params_history, x_label="x", y_label="x",
            z_label="fitness", num_points=1000, x_min=0.0, x_max=20.0,
            y_min=0.0, y_max=20.0, color="red", azim=20.0, elev=230.0):
    """
    Produces a 3D visualization of the fitness landscape with points
    indicating the history of the best set of parameters. Only works
    if there are two parameters per individual.

    Parameters
    ----------
    path : string
            Output file path for the visualization.
    fitness : Callable
            The fitness function.
    best_params_history : np.ndarray
            A 2D array of parameters.
    x_label : string (default "x")
            The x-axis label (parameter 0).
    y_label : string (default "y")
            The y-axis label (parameter 1).
    z_label : string (default "fitness")
            The z-axis label (fitness value).
    num_points : int (default 1000)
            Number of points to fit across the x and y axes.
            Determines the precision of the fitness landscape.
    x_min : float (default 0.0)
            Minimum value for the x-axis.
    x_max : float (default 20.0)
            Maximum value for the x-axis.
    y_min : float (default 0.0)
            Minimum value for the y-axis.
    y_max : float (default 20.0)
            Maximum value for the y-axis.
    color : string (default "red")
            Color of the parameter points.
    azim : float (default 20.0)
            Plot azimuth angle in degrees.
    elev : float (default 230.0)
            Plot elevation angle in degrees.
    """
    # create a contour map of possible parameter values and
    # the corresponding fitness function values
    x = np.linspace(x_min, x_max, num_points)
    y = np.linspace(y_min, y_max, num_points)
    z = []
    for j in range(num_points):
        for i in range(num_points):
            z.append(fitness([x[i], y[j]]))
    Z = np.array(z).reshape((num_points, num_points))

    X, Y = np.meshgrid(x, y)

    fig = plt.figure()
    ax = plt.axes(projection='3d')
    ax.view_init(azim, elev)

    ax.contour3D(X, Y, Z, 50)

    # set labels
    ax.set_xlabel(x_label)
    ax.axes.set_xlim(x_min, x_max)
    ax.set_ylabel(y_label)
    ax.axes.set_ylim(y_min, y_max)
    ax.set_zlabel(z_label)

    # add points representing the history of best parameters
    ax.scatter3D(best_params_history[:,0], best_params_history[:,1],
        np.apply_along_axis(fitness, 1, best_params_history),
        color=color, depthshade=0)

    # save figure
    plt.savefig(path)


# first steps:
# start a new xml data object
from xml.etree.ElementTree import Element, SubElement, ElementTree
import csv

def drawingsubsubChild(x, y):
	if x != "":
		print("ok")
		childElement = SubElement(subChild, y)
#problem here: need x here to be the variable name. can't put "x" or just get text "x" in my element tags.
#don't like it, but below created additional name variable.
		childElement.text = x
	elif x == "":
		pass

def drawingsubsubsubChild(x, y):
	if x != "":
		print("ok")
		childElement = SubElement(subsubChild, y)
#problem here: need x here to be the variable name. can't put "x" or just get text "x" in my element tags.
#don't like it, but below created additional name variable.
		childElement.text = x
	elif x == "":
		pass

root = Element('berenson')
drawing_record = 0
BB_1903 = 0
BB_1903_recto = 0
BB_1903_verso = 0
FlorentineDrawingsProject = 0

# import the massive CSV

# parse the rows and loop
with open('FlorentineDrawings_PageNumbers - MasterList.csv', 'r', encoding="UTF-8") as f:
	reader = csv.reader(f)
	next(reader)
	for row in reader:

		FlorentineDrawings_IdentifierBB1961 = row[0]
		FlorentineDrawings_IdentifierBB1961_name = "FlorentineDrawings_IdentifierBB1961"

		PageNumber_1903 = row[10]
		PageNumber_1903_name = "PageNumber_1903"

		IIIF_Page_URL = row[12]
		IIIF_Page_URL_name = "IIIF_Page_URL"

		AWS_PageImage_URL = row[13]
		AWS_PageImage_URL_name = "AWS_PageImage_URL"

		AWS_PageThumbnail_URL = row[14]
		AWS_PageThumbnail_URL_name = "AWS_PageThumbnail_URL"

#wrapper for entire drawing
		child = SubElement(root, 'drawing_record')
		child.text = drawing_record

#data from the project.
		subChild = SubElement(child, 'FlorentineDrawingsProject')
		subChild.text = FlorentineDrawingsProject

		drawingsubsubChild(FlorentineDrawings_IdentifierBB1961, FlorentineDrawings_IdentifierBB1961_name)

# #data from the 1903 edition
		subChild = SubElement (child, 'BB_1903')
		subChild.text = BB_1903

		drawingsubsubChild(PageNumber_1903, PageNumber_1903_name)
		drawingsubsubChild(IIIF_Page_URL, IIIF_Page_URL_name)
		drawingsubsubChild(AWS_PageImage_URL, AWS_PageImage_URL_name)
		drawingsubsubChild(AWS_PageThumbnail_URL, AWS_PageThumbnail_URL_name)

# write XML file
ElementTree(root).write("xml_1903pagenumbers_30August.xml", encoding="UTF-8", xml_declaration=True, default_namespace=None)


"""
APIs of downloading pVol data from the Minio server

Author: @jiqicn
"""
import ipywidgets as widgets
import minio
import pandas as pd
from pathlib import Path
import os
import io

class Minio(object):
    """
    APIs for navigating and downloading data from the UvA-TCE Minio file server
    """
    def __init__(self):
        self.mc = None  # minio client
        self.bucket = ""  # current bucket
        self.prefix = ""  # current folder
        self.selection = []  # selection of the file paths

    def login(self, endpoint, user_name, password):
        """
        login to the UvA-TCE ninio server
        """
        self.mc = minio.Minio(
            endpoint=endpoint,
            access_key=user_name,
            secret_key=password,
            region="nl",
            secure=True
        )

        # check if successfully login
        try:
            self.mc.list_buckets()
        except Exception as e:
            print("! %s" % e.message)
            return
        print("* Login successfully!")

    def get_bucket_list(self):
        """
        get list of buckets that is accessable with the current permission
        """
        buckets = self.mc.list_buckets()
        bucket_names = []
        for b in buckets:
            bucket_names.append(b.name)
        return bucket_names

    def select_bucket(self, bucket):
        """
        select a bucket for further tasks
        """
        self.bucket = bucket

    def navigate(self, next_step=None):
        """
        navigate within the

        next_step[str or None]:
            if str, must be in format of "XXX/", where "XXX" is the directory name;
            if None, go back to a previous step;
        """
        if next_step is None:
            temp = self.prefix.split("/")
            temp = temp[:len(temp)-2]
            self.prefix = "/".join(temp) + "/"
        else:
            if next_step in self.get_object_list():
                self.prefix += next_step
            else:
                print("! Target directory not exists.")

        if self.prefix == "/":
            self.prefix = ""

    def get_object_list(self):
        """
        get list of objects in a specific bucket and under a given directory

        -parameters-
        bucket[str]
        prefix[str]: path to target directory
        """
        if self.bucket == "":
            return []
        objects = self.mc.list_objects(
            bucket_name=self.bucket,
            prefix=self.prefix
        )
        object_names = []
        for obj in objects:
            if obj.is_dir:
                obj_name = obj.object_name.split("/")[-2] + "/"
            else:
                obj_name = obj.object_name.split("/")[-1]
            object_names.append(obj_name)
        return object_names

    def save_selection(self, object_names):
        """
        accumulate the current selection

        -parameters-
        object_names[list]: list of file names for downloading
        """
        for obj_name in object_names:
            self.selection.append(self.prefix + obj_name)
        print("%d files saved to selection!" % len(object_names))

    def download_to_files(self, target_dir):
        """
        download the selected objects to a user selected folder

        -parameters-
        bucket[str]: name of the target bucket
        target_dir[str]
        """
        if target_dir is None:
            print("! Please choose the folder to keep your files.")
            return

        print("* Start downloading...")
        for obj in self.selection:
            fpath = os.path.join(target_dir, obj.split('/')[-1])
            try:
                self.mc.fget_object(
                    bucket_name=self.bucket,
                    object_name=obj,
                    file_path=fpath
                )
            except:
                print("! Fail to download %s." % obj)
                return

        print("* Download successfully to %s" % target_dir)


# Dividindo valores em vãrias listas
num = list()
pares = list()
impares = list()
while True:
    num.append(int(input('Digite um número: ')))
    resp = str(input('Quer continuar [S/n] '))
    if resp in 'Nn':
        break
for i, v in enumerate(num):
    if v %  2 == 0:
        pares.append(v)
    elif v % 2 == 1:
        impares.append(v)
print('=-'* 30 )
print(f'A lista completa é {num}')
print(f'A lista dos numeros pares é {pares}')
print(f'A lista de números impares é {impares}')


import time
import datetime
import requests
from io import StringIO

# must be exported VehicleParsedOutput Records filtered to the corresponding vehicle
EXPORT_IDS = [
    {
        "platform_id": "SV3-245",
        #"wgms_record_id": 74383,
        "wgms_record_id": 74446,
    },
    {
        "platform_id": "SV3-247",
        #"wgms_record_id": 74297,
        "wgms_record_id": 74445,
    },
]

LOGINSOAP="""<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap=
"http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <CreateLoginSession xmlns="http://gliders.liquidr.com/webservicesWebServices">
      <login>{login}</login>
      <password>{password}</password>
      <orgName>{org}</orgName>
    </CreateLoginSession>
  </soap:Body>
</soap:Envelope>
"""

# AVAILABLE FIELS:
#
# TimeStamp
# Structure ID
# Ground Speed(kt)
# Target
# Desired Heading (deg)
# Sub Heading
# POG (deg)
# Float Temp(degC)
# Pressure Sensor Float(kPa)
# Battery (Wh)
# Signal Strength
# User Name
# Lat (deg)
# Lon (deg)
# Distance Over Ground(m)
# Water Speed (kt/1000) WS
# Water Direction
# Current Speed (kt)
# Current Heading (deg)
# Created On

def parse_time(s):
    if len(s) == 0:
        return float("nan")
    return datetime.datetime.strptime(s, "%m/%d/%Y %H:%M:%S")

def parse_knots(s):
    if len(s) == 0:
        return float("nan")
    return float(s) * 1.852 / 3.6 # knots to m/s (exact)

def parse_milliknots(s):
    if len(s) == 0:
        return float("nan")
    return float(s) * 1.852 / 3.6 / 1000. # milliknots to m/s (exact)

def parse_degrees(s):
    if len(s) == 0:
        return float("nan")
    return float(s)

def parse_celsius(s):
    if len(s) == 0:
        return float("nan")
    return float(s)

def parse_kilopascal(s):
    if len(s) == 0:
        return float("nan")
    return float(s) * 1000. # kPa to Pa

def parse_watt_hours(s):
    if len(s) == 0:
        return float("nan")
    return float(s)

def parse_lat(s):
    if len(s) == 0:
        return float("nan")
    return float(s)

def parse_lon(s):
    if len(s) == 0:
        return float("nan")
    return float(s)

FIELDMAP = {
        "TimeStamp": {
            "name": "time",
            "parser": parse_time,
        },
        "Ground Speed(kt)": {
            "name": "speed_over_ground",
            "parser": parse_knots,
        },
        "Desired Heading (deg)": {
            "name": "desired_heading",
            "parser": parse_degrees,
        },
        "Float Temp(degC)": {
            "name": "device_temperature",
            "parser": parse_celsius,
        },
        "Pressure Sensor Float(kPa)": {
            "name": "pressure",
            "parser": parse_kilopascal,
        },
        "Battery (Wh)": {
            "name": "battery_charge",
            "parser": parse_watt_hours,
        },
        "Lat (deg)": {
            "name": "lat",
            "parser": parse_lat,
        },
        "Lon (deg)": {
            "name": "lon",
            "parser": parse_lon,
        },
        "Water Speed (kt/1000) WS": {
            "name": "water_speed",
            "parser": parse_milliknots,
        },
        "Water Direction": {
            "name": "water_direction",
            "parser": parse_degrees,
        },
        "Current Speed (kt)": {
            "name": "speed_in_water",
            "parser": parse_knots,
        },
        "Current Heading (deg)": {
            "name": "heading",
            "parser": parse_degrees,
        },
        "Created On": {
            "name": "dataset_time",
            "parser": parse_time,
        },
}

class GliderApi(object):
    def __init__(self, authinfo, base_url="https://apl-uw.wgms.com"):
        self._base_url = base_url
        #curl -k -H "Content-Type: text/xml; charset=utf-8" --dump-header headers -H "SOAPAction:" -d @loginsoap.xml -X POST https://gliders.wgms.com/webservices/entityapi.asmx
        loginsoap = LOGINSOAP.format(**authinfo)
        headers = {
            "Content-Type": "text/xml; charset=utf-8",
            "SOAPAction": None,
        }
        self._session = requests.Session()
        res = self._session.post(
            self._base_url + "/webservices/entityapi.asmx",
            data=loginsoap,
            headers=headers)
        res.raise_for_status()

    def get_export(self, view, entity):
        #http://apl-uw.wgms.com/pages/exportPage.aspx?viewid=74297&entitytype=42
        res = self._session.get(
                self._base_url + "/pages/exportPage.aspx",
                params={
                    "viewid": view,
                    "entitytype": entity
                })
        lines = iter(StringIO(res.text))
        header = next(lines).strip().split(",")
        for line in lines:
            parts = line.strip().split(",")
            data = {}
            for col, part in zip(header, parts):
                try:
                    colinfo = FIELDMAP[col]
                except KeyError:
                    continue
                data[colinfo["name"]] = colinfo["parser"](part.strip())
            yield data

def _main():
    from mqtt_utils import get_config_dir, EUREC4AMqttPublisher
    import os
    import json
    with open(os.path.join(get_config_dir(), "liquidr_gliders.json")) as configfile:
        config = json.load(configfile)

    api = GliderApi(config)

    with EUREC4AMqttPublisher() as publisher:
        while True:
            for vehicle in EXPORT_IDS:
                entries = list(sorted(api.get_export(vehicle["wgms_record_id"], 42),
                                      key=lambda x: x["time"]))
                latest = entries[-1]
                publisher.publish("platform/{}/location".format(vehicle["platform_id"]),
                    {"time": latest["time"], "lat": latest["lat"], "lon": latest["lon"]},
                    retain=True)
            time.sleep(30)

if __name__ == "__main__":
    _main()


## 스택을 클래스로 만들기
class Stack:

    def __init__(self):
        self.stack = []

    def push(self, item):
        self.stack.append(item)

    def pop(self):
        if not len(self.stack):
            return None
        else:
            returns = self.stack[len(self.stack) - 1]
            self.stack = self.stack[:len(self.stack) - 1]
            return returns

    def is_empty(self):
        if self.stack:
            return 0
        else:
            print("스택 비어있음")
            return 1

print('hello world')

stack1 = Stack()
print(stack1.stack)
stack1.push(13)
print(stack1.stack)

print('-----------------')

stack2 = Stack()
print(stack2.stack)
stack2.push(19)
print(stack2.stack)
stack2.pop()
print(stack2.stack)

print('----------------')

print(stack1.is_empty())
print(stack2.is_empty())


from firebase_admin import auth, initialize_app
import os
import pathlib

fb_admin_config_path = os.path.join(pathlib.Path(__file__).parent, 'key/fb_admin_config.json')

if not os.path.exists(fb_admin_config_path):
    print(f"Please provide firebase admin config file in the path: {fb_admin_config_path}")
    exit(1)

# we have to set this field before any admin stuff, as it will set firebase admin
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = fb_admin_config_path

app = initialize_app() # initialize firebase admin app

def create_user(email, user_id):
    try:
        # if user is there, return that
        return auth.get_user_by_email(email=email)
    except:
        # else create the user
        return auth.create_user(email=email, uid=user_id) if user_id else auth.create_user(email=email)


# -*- coding: utf-8 -*-
# @Time    : 2022/1/15 23:42
# @Author  : zhangweiqi
#! -*- coding: utf-8 -*-

import json
import re
from jieba import analyse
from zhon.hanzi import punctuation as p1
from zhon.pinyin import punctuation as p2
import re
import random
from tqdm import tqdm

re_puncs='['+re.escape(p1+p2+" \r\n")+']'

def cutTextToSent(text:str):
    split_text=re.sub(re_puncs,' ',text).split()#每个句子按标点符号分句
    return split_text

# 此处处理停用词
def getStopWords():
    return set(' ')

def readFromJsonFile(path: str):
    with open(path, "r", encoding="utf-8") as f:
        return json.loads(f.read())

def writeToJsonFile(path: str, obj, indent=None):
    with open(path, "w", encoding="utf-8") as f:
        f.write(json.dumps(obj, ensure_ascii=False, indent=indent))

#有些大型json文件，是每一行自成json格式，按行写入的
def readFromJsonFileForLine(path: str,max_line=float('inf')):
    with open(path, "r", encoding="utf-8") as f:
        res=[]
        for i in tqdm(f,ncols=80):
            data=i.strip()
            if len(data)!=0:
                res.append(json.loads(data))
            if len(res)>=max_line:
                return res
        return res

#适用于需要不断追加写入的json文件，f为a+模式打开
#每写一次都打开关闭文件一次，可确保能基本实时保存，但效率低
def appendJsonLine(path: str, obj):
    with open(path, "a+", encoding="utf-8") as f:
        f.write(json.dumps(obj,ensure_ascii=False)+'\n')

def writeToJsonFileForLine(path: str, ls:list):
    with open(path, "a+", encoding="utf-8") as f:
        for i in ls:
            f.write(json.dumps(i,ensure_ascii=False)+'\n')

#根据百分位间隔计算长度分布
def cal_Len_distribution(Lens,begin=0,end=100,step=5):
    Lens=list(Lens)
    Lens.sort()
    total_len=len(Lens)
    for i in range(begin,end+1,step):
        idx=int(total_len*i*0.01)
        idx=min(idx,total_len-1)
        print(f"百分位：{i}%，\tindex：{idx}，\t长度：{Lens[idx]}")

#删除多余空白符。对文本保留自然段（换行），其他空白符替换成空格且只保留一个
def delSpace(st:str):
    ls=st.split('\n')#只有换行特殊处理
    ls=list(filter(lambda x:len(x)>0,ls))
    for i in range(len(ls)):
        ls[i]=" ".join(ls[i].split())#若有多个分割，统一用空格替代
    return "\n".join(ls)


def exibe():
    i=0
    x=100
    y=200

    cont_dia = 0
    cont_tarde = 0
    cont_noite = 0
    while i<x:
        print('Bom dia')
        cont_dia +=1
        j=0
        while j<y:
            print('boa tarde')
            cont_tarde +=1
            j+=1
        i +=1
    print('boa noite')
    cont_noite += 1

    print('Quantidades de Bom dia', cont_dia)
    print('Quanidade de boa tarde', cont_tarde)
    print('Quantidade de boa noite', cont_noite)

exibe()


def isInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False
def restart():
    time.sleep(1)
    print("""
    =======+++=======
          ERROR:
     ENTER A CORRECT
          VALUE!
      RESTARTING...
    =======+++=======
        """)
    time.sleep(3)
    restart = 1

while True:
    import time, random
    print("""
    =======+++=======
        WELCOME TO
        PERSIMMON
    =======+++=======
    """)
    time.sleep(2)
    difficulty = input("SELECT YOUR DIFFICULTY: TYPE 'EASY' OR 'HARD', or 'HELP' for more options ")
    time.sleep(2)
    if difficulty == "EASY":
        maxn = 5
    elif difficulty == "HARD":
        maxn = 10
    elif difficulty == "HELP":
        what = input("""Welcome to the help menu.
1. Rules
2. Highscore""")
        if what == "1":
            print("""RULES:
A number will be randomly selected each round.
Guess the number correctly to get 10 points.
If you don't guess correctly, not to worry, but you will lose 1 point.
Good luck!""")
            time.sleep(6)
            continue
        elif what == "2":
            hisc = open("highscore.txt")
            print("HIGHSCORE =",hisc.read())
            time.sleep(5)

        else:
            restart()
            continue

    rounds = input("How many rounds would you like to play? ")

    if isInt(rounds) == True:
        rounds = int(rounds)
        if rounds <= 0:
            restart()
            continue
    else:
        restart()
        continue

    score = 0

    for x in range(rounds):
        time.sleep(0.5)
        randint = random.randint(1,maxn)
        guess = int(input("TIME TO GUESS! GUESS A NUMBER BETWEEN 1 AND " + str(maxn) + "! "))
        if guess == randint:
            score += 10
            print("CORRECT! YOUR SCORE IS NOW",str(score) + "!")
        else:
            score += -1
            print("INCORRECT! YOUR SCORE IS NOW",str(score) + ".")

    time.sleep(2)
    print("GAME OVER! You scored",str(score) + "!")

    highscore = 0

with open("highscore.txt", "r+") as hisc:
    hi = hisc.read()
    if not hi:
        hi = '0'
    if score > int(hi):
        print("NEW HIGHSCORE!")
        hisc.seek(0)
        hisc.write(str(score))
    else:
        print("HIGHSCORE =%s" % hi)

    time.sleep(3)


# BitCity Studios:
# Cameron O'Leary <coleary9@jhu.edu>
# Steve Griffin  <sgriff27@jhu.edu>
# Jeremey Dolinko <j.dolinko@gmail.com>
# Jonathan Rivera <jriver21@jhu.edu>
# Michael Shavit  <shavitmichael@gmail.com>

import glob
import pygame
from pygame import Color, time
import math

HEALTH_COLOR = (198, 73, 65, 0)
INTOX_COLOR = (200, 200, 0, 0)
POISON_COLOR = (135, 31, 120, 0)
COOL_COLOR = (191, 235, 255, 0)
hpPixels = 175
hpHeight = 24
offsetRight = 25

class Hud(object):

    """graphical stuff to draw like health"""

    def __init__(self, s, player):
        self.surfBorder = pygame.Surface((hpPixels + 4, hpHeight + 4))
        self.surfBorder.fill(glob.FONT_COLOR)
        self.player = player

        # Init FPS timer.
        if glob.DEBUG:
            self.clock = time.Clock()

    def draw(self, camera):
        """Draws the hud."""
        s = camera.surf
        player = self.player
        if player.health < 0:
            return
        # draw score
        surfScore = glob.FONT.render(
            "Score: " + str(glob.SCORE),
            True,
            glob.FONT_COLOR)
        scoreW = (s.get_width() / 2) - surfScore.get_width() / 2
        s.blit(surfScore, (scoreW, 0))

        # calculate width of hp bar and border
        healthW = player.health * hpPixels / player.maxHealth
        surfHealth = pygame.Surface((healthW, hpHeight))
        surfHealth.fill(HEALTH_COLOR)
        # calculate position of hp bar and border
        healthPos = s.get_width() - hpPixels - offsetRight
        # draw hp
        s.blit(self.surfBorder, (healthPos - 2, hpHeight - 2))
        s.blit(surfHealth, (healthPos, hpHeight))

        # draw inebriation
        # using HP box proporitions for simplicity
        intoxW = player.intox * hpPixels / player.maxIntox
        surfIntox = pygame.Surface((intoxW, hpHeight))
        if player.intox < 50:
            surfIntox.fill(INTOX_COLOR)
        else:
            surfIntox.fill(POISON_COLOR)
        s.blit(self.surfBorder, (healthPos - 2, (hpHeight * 2) - 2))
        s.blit(surfIntox, (healthPos, (hpHeight * 2)))
        # intox

        coolDownW = player.specCoolDown.getPercent() * hpPixels
        if coolDownW == 0:
            coolDownW = hpPixels
        surfCoolDown = pygame.Surface((coolDownW, hpHeight))
        surfCoolDown.fill(COOL_COLOR)
        s.blit(self.surfBorder, (healthPos - 2, (hpHeight * 3) - 2))
        s.blit(surfCoolDown, (healthPos, (hpHeight * 3)))

        if glob.DEBUG:
            # Draw FPS.
            self.clock.tick()
            surf = glob.FONT.render(
                "FPS: %3.2f" % (self.clock.get_fps()),
                True, glob.FONT_COLOR)
            s.blit(surf, (24, 24))

    def update(self, dt):
        pass

    def refresh(self, player):
        self.player = player


# essa é nossa fabrica onde criaremos o modelo de TEMPLANTE
# -- > aqui e nosso modelo do esquema de blocos
# Aqui vamos usar nosso modelo e trabalhar com suas informaçoes
# Autor: Felipe M A B Huinka

class fabrica :
    modelo = None
    nome = None
    modelos = {}

    def __init__(self,_nome):
        self.nome = _nome
        from visao.core.abstrata.esquema.modelo import modelo
        self.modelo = modelo
        self.modelos = {}

    def addBloco(self, _chaveBloco, _nomePai, _finalBloco=1):
        if self.vereficaChave(_chaveBloco):
            print("ERRO! Essa chave de bloco ja existe tente outra")
        else:
            blc = self.modelo(_chaveBloco, _nomePai, _finalBloco)
            self.modelos.update({_chaveBloco:blc})

    def vereficaChave(self,_chave):
        for k, v in self.modelos.items():
            if k == _chave:

                return True

        return False


import os
import sys

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "..", "..")))

from testrunner import CodersLabTestSuite, CodersLabException, p, dedent

tc = CodersLabTestSuite("Comparing numbers")

@tc.test("Numbers are saved in variables a and b", aborts=True)
def test_a_b(invoke, stdin, **kwargs):
    stdin.append("123456")
    stdin.append("345678")

    variables = invoke()

    if "a" not in variables:
        raise CodersLabException("Could not find variable {}".format(p.b.get("a")))

    if "b" not in variables:
        raise CodersLabException("Could not find variable {}".format(p.b.get("b")))

    if str(variables["a"]).split('.')[0] != "123456":
        raise CodersLabException(
            "Numeric keyboard input was not saved "
            "in the {} variable.".format(p.b.get("a"))
        )

    if str(variables["b"]).split('.')[0] != "345678":
        raise CodersLabException(
            "Numeric keyboard input was not saved "
            "in the {} variable.".format(p.b.get("b"))
        )

@tc.test(
    "Numbers {a} and {b} are compared correctly",
    params=[
        {"a": "123", "b": "456", "greater": "b"},
        {"a": "456", "b": "123", "greater": "a"},
    ],
    aborts=True,
)
def test_comparison_lex(invoke, stdin, stdout, a, b, greater, history, **kwargs):
    stdin.append(a)
    stdin.append(b)

    invoke()

    tc.assert_print_called(stdout)

    if "{} is greater!".format(greater) not in "".join(stdout).lower():
        raise CodersLabException(
            dedent(
                """
                Could not find the phrase {} in the printed text.

                Printed lines:
                {}
                """
            ).format(
                p.b.get("{} is greater!".format(greater)),
                p.b.get("".join(h.get("text", "") for h in history)),
            )
        )

@tc.test(
    "Numbers {a} and {b} are compared correctly",
    params=[
        {"a": "123", "b": "56", "greater": "a", "smaller": "b"},
        {"a": "99", "b": "789", "greater": "b", "smaller": "a"},
    ],
    aborts=True,
)
def test_comparison_as_number(
    invoke, stdin, stdout, a, b, greater, smaller, history, **kwargs
):
    stdin.append(a)
    stdin.append(b)

    invoke()

    wrong = "{} is greater!".format(smaller)

    if wrong in "".join(stdout).lower():
        raise CodersLabException(
            dedent(
                """
                Incorrect result ({}) found in the printed text:
                Likely reason is that the input data was compared as strings,
                not as numbers.
                "{}" looks like greater than "{}" because
                "{}" is behind "{}" in "computer alphabet".

                To compare them as numbers use the {} function.

                Example:
                >>> a = "12"
                >>> b = "34"
                >>> a + b
                "1234"
                >>> float(a) + float(b)
                46

                """
            ).format(
                p.b.get(wrong),
                p.b.get(min(a, b)),
                p.b.get(max(a, b)),
                p.b.get(str(max(a, b))[0]),
                p.b.get(str(min(a, b))[0]),
                p.b.get("float"),
            )
        )

    correct = "{} is greater!".format(greater)

tc.run()


import urllib
import urllib.request
import random
import re
import requests
from bs4 import BeautifulSoup
import time
from datetime import datetime, date
# set IP and proxy
def set_ip():
    # ip list
    iplist = ['45.125.32.181', '125.123.64.234', '58.22.212.39', '171.11.179.77','125.123.126.185','125.123.123.114','58.22.213.30']
    # create an opener
    proxy_support = urllib.request.ProxyHandler({'http': iplist[random.randint(0, len(iplist) - 1)]})
    opener = urllib.request.build_opener(proxy_support)

    # create a disguise header
    opener.addheaders = [('User-Agent',
                          'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36')]
    return opener

#requst html
def req_html(opener, url):
    # use opener to request url
    response = opener.open(url)
    # read response and decode it
    html = response.read().decode('utf-8')
    return html

def find_title(html):
    pattern = re.compile(r'
(.*?)
')
    title = pattern.findall(html)
    return title

def find_audratio(html):
    pattern = re.compile(r'class="graph_num">(.*?)')
    audr = pattern.findall(html)
    return audr

def find_episode(html):
    pattern = re.compile(r'(.*?)')
    episode = pattern.findall(html)
    return episode

def find_date(html):
    pattern  = re.compile(r'(.*?)')
    date = pattern.findall(html)
    return date

def find_tvstation(html):
    pattern = re.compile(r'(.*?)')
    tvs = pattern.findall(html)
    return tvs[0]

def find_localtime():
    detail = time.strftime("%Y-%m-%d", time.localtime())
    return detail

def decide_day():
    # Sunday == 0
    # Monday == 1
    # Tuesday == 2
    # Wednesday == 3
    # Thursday == 4
    # Friday == 5
    # Saturday == 6
    str = time.strftime("%w", time.localtime())
    return int(str)

def write_drama_model(lctime, tvs, title, dmdate, epsd, audr, arst, defin):
    lcd = lctime.split("-")
    m = " "
    lend = len(dmdate)
    for i in range(0, lend):
        dmd = dmdate[i].split("/")
        if int(lcd[2])-1 == int(dmd[2]) and i != (lend-1):
            # current audience ratio
            thisepsd = re.findall(r'\d+\.?\d', audr[i])
            thisepsd = float(thisepsd[0])
            # last audience ratio
            lastepsd = re.findall(r'\d+\.?\d', audr[i+1])
            lastepsd = float(lastepsd[0])
            diff = str("%.1f"%(thisepsd-lastepsd))
            if thisepsd - lastepsd > 0:
                diff = "+" + diff
            if defin == 1:
                # current episode
                episode = re.findall(r'\d+',epsd[i])[0]
                m = "第" + episode + "集:" + audr[i] + "(" + diff + ") 、" + m
            else:
                m = audr[i] + "(" + diff + ") 、" + m
        elif int(lcd[2])-1 == int(dmd[2]) and i == (lend-1):
            if defin == 1:
                episode = re.findall(r'\d+', epsd[i])[0]
                m = "第" + episode + "集:" + audr[i] + "（—）、" + m
            else:
                m = audr[i] + "（—）、" + m
            break
        else:
            break
    if defin == 1: m = (tvs + " "+ title + arst + m)
    else: m = (tvs + " " + title + m)
    return m

def cable_drama(weekday):
    drama_name = [['《#请融化我#》','《#他人即地狱#》','《#我的国家#》','《#美丽爱情完美人生#》','《#黄金庭院#》'],
                  ['《#请融化我#》','《#他人即地狱#》'],
                  ['《#伟大的show#》','《#花党：朝鲜婚姻介绍所#》','《#绿豆传#》'],
                  ['《#伟大的show#》','《#花党：朝鲜婚姻介绍所#》','《#绿豆传#》'],
                  ['《#碰巧发现的一天#》','《#奔跑的调查官#》','《#青日电子李小姐#》','《#山茶花开时#》'],
                  ['《#碰巧发现的一天#》','《#奔跑的调查官#》','《#青日电子李小姐#》','《#山茶花开时#》'],
                  ['《#很便宜，千里马超市#》', '《#我的国家#》']]
    drama_kr = [['날녹여주오','타인은지옥이다','나의나라','사랑은뷰티풀인생은원더풀','황금정원'],
                ['날녹여주오','타인은지옥이다'],
                ['위대한쇼','조선혼담공작소꽃파당','녹도'],
                ['위대한쇼','조선혼담공작소꽃파당','녹도'],
                ['어쩌다발견한하루','달리는조사관','청일전자미쓰리','동백꽃필무렵'],
                ['어쩌다발견한하루','달리는조사관','청일전자미쓰리','동백꽃필무렵'],
                ['쌉니다천리마마트','나의나라']]
    drama_arst = [['（主演：#池昌旭#、#尹世雅#）','（主演：#任时完#、#李栋旭#）','（主演：#梁世宗#、#禹棹焕#、#张赫#）',
                   '（主演：#金宰英#、#吴珉锡#、#尹博#、#薛仁雅#、#赵允熙#、#金美淑#）',
                   '（主演：#韩智慧#、#李尚禹#、#吴智恩#、#李泰成#）'],
                  ['（主演：#池昌旭#、#尹世雅#）',
                   '（主演：#任时完#、#李栋旭#）'],
                  ['（主演：#宋承宪#、#李先彬#）',
                   '（主演：#金旻载#、#孔升妍#、#朴志训# ）',
                   '（主演：#金所泫#、#张东允#、#宋建熙#）'],
                  ['（主演：#宋承宪#、#李先彬#）',
                   '（主演：#金旻载#、#孔升妍#、#朴志训# ）',
                   '（主演：#金所泫#、#张东允#、#宋建熙#）'],
                  ['（主演：#金惠允#、#金路云#、#李在旭#、#郑乾柱#、#金英大#、#李泰利#、#金智仁#）',
                   '（主演：#李枖原#、#崔奎华#）',
                   '（主演：#李惠利#、#金相庆#）',
                   '（主演：#孔晓振#、#姜河那#）', ],
                  ['（主演：#金惠允#、#金路云#、#李在旭#、#郑乾柱#、#金英大#、#李泰利#、#金智仁#）',
                   '（主演：#李枖原#、#崔奎华#）',
                   '（主演：#李惠利#、#金相庆#）',
                   '（主演：#孔晓振#、#姜河那#）',],
                  ['（主演：#李东辉#、#金炳哲#、#郑惠成#、#朴浩山#、#李顺载#）',
                   '（主演：#梁世宗#、#禹棹焕#、#张赫#）']]
    lend = len(drama_name[weekday])
    lctime = find_localtime()
    print(lctime[5:7]+"月"+str(int(lctime[8:10])-1)+"日电视剧收视率")
    for i in range(0, lend):
        url = 'https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query='
        u = url + urllib.parse.quote(drama_kr[weekday][i])
        opener = set_ip()
        html = req_html(opener, u)
        tvs = find_tvstation(html)
        title = find_title(html)
        dmdate = find_date(html)
        epsd = find_episode(html)
        audr = find_audratio(html)
        print(write_drama_model(lctime, tvs, drama_name[weekday][i], dmdate, epsd, audr, drama_arst[weekday][i], 1)[:-2])

def cable_variety(weekday):
    variety_name = [['《#自然而然#》','《#认识的哥哥#》','《#只因工作才见面#》','《#喂狗粮的男人#》',
                     '《#惊人的星期六#》'],
                    ['《#街头大胃王2#》','《#Camping Club#》'],
                    ['《#拜托冰箱#》','《#眼神交流#》','《#冤大头的排行榜#》'],
                    ['《#最佳的一击#》','《#Idol Room#》','《#You Quiz On The Block2#》'],
                    ['《#请给我一顿饭#》','《#Rewind#》','《#星期三是音乐节目#》'],
                    ['《#西伯利亚先遣队#》','《#Queendom#》','《#Love catcher2#》','《#signhere#》'],
                    ['《柳熙烈的sketchbook》','《#begin again 3#》','《#被歌声迷住#》','《#三时三餐山村篇#》','《#新西游记外传：三时三餐-冰岛三餐#》']]
    variety_kr = [['자연스럽게','아는형님','일로만난사이','개밥주는남자','놀라운토요일도레미마켓'],
                  ['스트이트푸드파이터2','캠핑클럽'],
                  ['냉장고부탁해','아이콘택트','호구의차트'],
                  ['최고의한방','아이돌룸','유퀴즈온더블럭2'],
                  ['한끼줍쇼','리와인드','수요일은음악프로'],
                  ['시베리아신발대','퀸덤','러브캐처2','사인히어'],
                  ['유희열의스케치북','비긴어게인3','노래에반하가','삼시세끼산촌편','신서유기외전삼시세끼']]
    lend = len(variety_name[weekday])
    lctime = find_localtime()
    print(lctime)
    print(lctime[5:7] + "月" + str(int(lctime[8:10])-1) + "日综艺收视率")
    for i in range(0, lend):
        url = 'https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query='
        u = url + urllib.parse.quote(variety_kr[weekday][i])
        opener = set_ip()
        html = req_html(opener, u)
        tvs = find_tvstation(html)
        title = find_title(html)
        dmdate = find_date(html)
        #epsd = find_episode(html)
        # print(epsd)
        audr = find_audratio(html)
        # print(audr)
        print(write_drama_model(lctime, tvs, variety_name[weekday][i], dmdate, tvs, audr, variety_name[weekday][i], 0)[:-2])

if __name__ == '__main__' :
    weekday = decide_day()
    cable_drama(weekday)
    print()
    cable_variety(weekday)


# ----------------------------------------------------------------------------
# -*- coding: utf-8 -*-
# @Author:              Gifty Attiah
# @Date:                2021-05-05
# @Email:               geattiah@gmail.com
# @Last Modified By:    Gifty Attiah
# @Last Modified Time:  Not Tracked
#
# PROGRAM DESCRIPTION:
# Load tiff file, flatten based on csv and perform calculattion and plot, ice thickness on small lakes
# ----------------------------------------------------------------------------

import csv
from PIL import Image
import pandas as pd
import numpy
import os
import matplotlib.pyplot as plt

csv_file = pd.read_csv(r"C:\Users\ReSEC2021\OneDrive - Wilfrid Laurier University\Arc_Analysis\thick.csv")
print(csv_file)

folder = r"C:\Users\ReSEC2021\OneDrive - Wilfrid Laurier University\Arc_Analysis"

frame = Image.open(r"C:\Users\ReSEC2021\OneDrive - Wilfrid Laurier University\Arc_Analysis\LC08_L1TP_047016_20190305_20190309_01_T1\LC08_L1TP_047016_20190305_20190309_01_T1_Frame_Lake.tif")
grace = Image.open(r"C:\Users\ReSEC2021\OneDrive - Wilfrid Laurier University\Arc_Analysis\LC08_L1TP_047016_20190305_20190309_01_T1\LC08_L1TP_047016_20190305_20190309_01_T1_Grace_Lake.tif")
handle = Image.open(r"C:\Users\ReSEC2021\OneDrive - Wilfrid Laurier University\Arc_Analysis\LC08_L1TP_047016_20190305_20190309_01_T1\LC08_L1TP_047016_20190305_20190309_01_T1_Handle_Lake.tif")
stewart = Image.open(r"C:\Users\ReSEC2021\OneDrive - Wilfrid Laurier University\Arc_Analysis\LC08_L1TP_047016_20190305_20190309_01_T1\LC08_L1TP_047016_20190305_20190309_01_T1_Stewart_Lake.tif")
longg = Image.open(r"C:\Users\ReSEC2021\OneDrive - Wilfrid Laurier University\Arc_Analysis\LC08_L1TP_047016_20190305_20190309_01_T1\LC08_L1TP_047016_20190305_20190309_01_T1_Long_Lake.tif")
h22 = Image.open(r"C:\Users\ReSEC2021\OneDrive - Wilfrid Laurier University\Arc_Analysis\LC08_L1TP_047016_20190305_20190309_01_T1\LC08_L1TP_047016_20190305_20190309_01_T1_H22_Lake.tif")

f_num = numpy.array(frame)
g_num = numpy.array(grace)
h_num = numpy.array(handle)
s_num = numpy.array(stewart)
l_num = numpy.array(longg)
hh_num = numpy.array(h22)

h2_num = hh_num
print(h2_num.shape)

p = []
uni_temp = csv_file["Temp"].unique()
#print(uni_temp)
for i in uni_temp:
    p.append(float(i))
#print(p)

for i in uni_temp:
    d = csv_file.loc[csv_file["Temp"] == i,'grid_code'].min()

b = [csv_file.loc[csv_file["Temp"] == i,'grid_code'].min() for i in uni_temp]
#print(b)
df = pd.DataFrame(uni_temp)

np_tick = dict(zip(uni_temp,b))

m = h2_num.flatten()
n = m.tolist()

q = [round(i,2) for i in n]
#print(q)

def closest(lst, K):

     lst = numpy.asarray(lst)
     idx = (numpy.abs(lst - K)).argmin()
     return lst[idx]

su = []
for i in q:
    a = closest(p, i)
    su.append(a)
    #print(a)
#print(su)

kv = [(k, np_tick[k]) for k in su if k in np_tick]
#print(kv)

g = []
for key, value in kv:
    g.append(value)
#print(g)

new_g = [round(i,3) if i != 1.09329961 else 0 for i in g]
#print(new_g)

t = numpy.asarray(new_g)
#print(t)

t = numpy.reshape(t, (9, 12))
t[t == 0] = 'nan'
#print(t)

im = Image.fromarray(t)
im.save(os.path.join(folder,"h2.tiff"), "TIFF")

plt.imshow(t, cmap='hot')
plt.show()


"""""
idade = int(input("Digite sua idade: "))

if idade <= 0:
    print("Idade invalida......")
else:
    if idade < 18:
        print("Voce é menor de idade")
    else:
        print("Voce é maior de idade!!!")
"""""
x = 1
y = x
if x > y:
    print("x maior que y")
elif x == y:
    print("x igual a y")
else:
    print("x menor que y")


import matplotlib.pyplot as plt
import numpy as np

standard = np.random.randn(1000)
G1= 10+2*standard
G2 = -6 +3*standard

plt.figure(figsize=(10,6))
plt.hist(standard, bins=50,color='blue', alpha=0.5)
plt.hist(G1,bins=50,color='orange',alpha=0.5)
plt.hist(G2,bins=50,color='green',alpha=0.5)

plt.show()


#!/usr/bin/env python3.10

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

import sys

import itertools
import numpy as np

from xml.dom import minidom
from collections import Counter

from spineigenfunctions import *

###################################################################

def ormas_like():
# finp is the xml file
    finp = sys.argv[1]
#    finp = 'input.xml'
    doc = minidom.parse(finp)

# general info
    general = doc.getElementsByTagName("general")
    outfile = general[0].getElementsByTagName('outfile')[0].childNodes[0].data
    elec = general[0].getElementsByTagName('electron')
    spin = int(general[0].getElementsByTagName('spin')[0].childNodes[0].data)
    na = elec[0].getAttribute("na")
    nb = elec[0].getAttribute("nb")

# Get all the blocks
    blocks = doc.getElementsByTagName("block")

    nCSFs = 0

    for block in blocks:
        spaces = block.getElementsByTagName('space')
        seqs = []
        occspace = []
        for space in spaces:
            ne = int(space.getAttribute("ne"))
            ip = int(space.getAttribute("imo"))
            fp = int(space.getAttribute("fmo"))

            seq = np.arange(ip, fp + 1)
            seqtot = np.concatenate((seq, seq), axis=0)
            seqs = np.concatenate((seqs, seq), axis=0)

            s = []
            ind = []
            for l in list(itertools.combinations(seqtot, ne)):
                count = []
                for i in range(ip, fp + 1):
                    count.append(l.count(i))
                s.append(count)

        # remove duplicates
            occ = []
            for i in s:
                if i not in occ:
                    occ.append(i)

            occspace.append(occ)

        if (len(occspace) == 1):
            seqocc = occspace[0]

        for i in range(len(occspace) - 1):
            if (i == 0):
                seqocc = occspace[i]
            s = []
            for j in seqocc:
                for k in occspace[i + 1]:
                    s.append(j + k)
                seqocc = s

        for occ in seqocc:
            p = []
            unp = []
            for i in range(len(occ)):
                if (occ[i] == 2):
                    p.append(int(seqs[i]))
                if (occ[i] == 1):
                    unp.append(int(seqs[i]))

            nCSFs += printCSF(spin, p, unp)

# print info in CI code format
    fhead = open('header.txt', 'a')
    print(nCSFs, '0.000000000000001', file=fhead)
    print(outfile, file=fhead)
    print(na, nb, file=fhead)
    print(nCSFs, file=fhead)
    fhead.close()

    return 0

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    import os

    if os.path.exists("header.txt"):
        os.remove("header.txt")
    if os.path.exists("list.txt"):
        os.remove("list.txt")
    if(ormas_like()==0):
        os.system("cat header.txt list.txt > input_cicode.txt")
        os.remove("header.txt")
        os.remove("list.txt")
        os.system("/home/nico/Workspace/Progs/Ints_From_gbtolib/MyGBTO_CIcode/myCI.exe input_cicode.txt")
        print('Job Done')


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

import configparser
from Predictor import Predictor
from Scraper import Scraper

class Searcher:

    def __init__(self):
        self.__BHK = 0
        self.__FloorArea = 0
        self.__Bathrooms = 0
        self.__Locality = ""
        self.__FurnishingStatus = ""
        self.__TypeofSale = ""

    def putBHK(self, BHK):
        self.__BHK = BHK

    def putFloorArea(self, FloorArea):
        self.__FloorArea = FloorArea

    def putBathrooms(self, Bathrooms):
        self.__Bathrooms = Bathrooms

    def putLocality(self, Locality):
        self.__Locality = Locality

    def putFurnishingStatus(self, FurnishingStatus):
        self.__FurnishingStatus = FurnishingStatus

    def putTypeofSale(self, TypeofSale):
        self.__TypeofSale = TypeofSale

    def searchProperties(self, BHK, FloorArea, Bathrooms, Locality, FurnishingStatus, TypeofSale):
        configParser = configparser.ConfigParser(allow_no_value = True)
        keys = []
        places = []
        configFilePath = 'config.ini'
        configParser.read(configFilePath)
        if(len(configParser.read(configFilePath)) > 0):
            details = configParser.sections()[0]
            for key in configParser[details]:
                keys.append(key)
            places += configParser[details][keys[0]].split(',')
        places_key=[]
        for place in places:
            places_key +=['Locality_'+place]
        inp={}
        inp = {'BHKs':[BHK],'FloorArea':[FloorArea],'Bathrooms':[Bathrooms]}
        for place in places_key:
            inp[place]= [0]
        inp.update({'Type_of_Sale_New':[0],'Type_of_Sale_Resale':[0],'Furnishing_Status_Furnished':[0],
                    'Furnishing_Status_Semi-Furnished':[0],'Furnishing_Status_Unfurnished':[0]})
        inp['Locality_'+Locality] = [1]
        inp['Furnishing_Status_'+FurnishingStatus] = [1]
        inp['Type_of_Sale_'+TypeofSale] = [1]
        #print(inp)
        predictor = Predictor()
        #print(type(predictor.regressor))
        #print(predictor.price)
        #return 0
        price = predictor.getPredictedPrice(inp)
        if price:
            return price
        else:
            predictor.managePredictor()
            return predictor.getPredictedPrice(inp)

    def viewProperties(self, BHK, Locality, FurnishingStatus, TypeofSale):
        scraper = Scraper()
        PropertyURL_list, ImageURL_list, Area_list, BHK_list = scraper.returnPropertyURLS(BHK, Locality, FurnishingStatus, TypeofSale)
        return PropertyURL_list, ImageURL_list, Area_list, BHK_list

"""
if __name__=='__main__':
    searcher = Searcher()"""


from flask import Flask, render_template, redirect, request, session
from hashlib import md5

from __main__ import app
from utils import *

#TODO shouldn't need to define constants twice...
ROLE_USER = 1
ROLE_ADMIN = 2
ROLE_TEACHER = 3

@app.route('/eventsChoose', methods = ["GET", "POST"])
def eventsChoose():
    if request.method == "POST":
        #Form has been submitted. Check whether they are adding or removing an entry and process accordingly
        if request.form["submit"] == "Add":
            connection = create_connection()
            with connection.cursor() as cursor:
                sql = "INSERT INTO tblEntries(userID, eventID) VALUES (%s, %s);"
                vals = (session["userID"], request.form["eventID"])
                cursor.execute(sql, vals)
                connection.commit()
                connection.close()
        elif  request.form["submit"] == "Remove":
            connection = create_connection()
            with connection.cursor() as cursor:
                sql = "DELETE FROM tblEntries WHERE userID = %s AND eventID = %s;"
                vals = (session["userID"], request.form["eventID"])
                cursor.execute(sql, vals)
                connection.commit()
                connection.close()

    #Display events. Need to pass all events to template, as well as all events that
    #user is currently entered for.
    connection = create_connection()
    with connection.cursor() as cursor:
        sql = "SELECT tblevents.eventID, eventName FROM tblevents;"
        cursor.execute(sql)
        events = cursor.fetchall()
        sql = "SELECT eventID, userID FROM tblEntries WHERE userID = %s;"
        vals = session["userID"]
        cursor.execute(sql, vals)
        enteredEvents = cursor.fetchall()
        connection.close()

    return render_template("eventsChoose.html", events = events, enteredEvents = enteredEvents)

@app.route('/eventsTickCompleted', methods = ["GET", "POST"])
def eventsTickCompleted():
    if request.method == "POST":
        connection = create_connection()
        with connection.cursor() as cursor:

            #First set all values to False for this user
            sql = "UPDATE tblentries SET completed = False WHERE userID = %s;"
            vals = (session["userID"])
            cursor.execute(sql, vals)
            connection.commit()

            #Then set True for all that were ticked in form
            completedEvents = request.form.getlist("completed")
            for event in completedEvents:
                sql = "UPDATE tblentries SET completed = True WHERE entryID = %s;"
                vals = (event)
                cursor.execute(sql, vals)
                connection.commit()
        connection.close()

    #Display events for this user.
    connection = create_connection()
    with connection.cursor() as cursor:
        sql = "SELECT tblevents.eventID, eventName, completed, entryID FROM tblentries INNER JOIN tblevents ON tblevents.eventID = tblentries.eventID WHERE tblentries.userID = %s;"
        vals = session["userID"]
        cursor.execute(sql, vals)
        enteredEvents = cursor.fetchall()
        connection.close()

    return render_template("eventsTickCompleted.html", enteredEvents = enteredEvents)

@app.route("/eventsAdd", methods=["GET", "POST"])
def eventsAdd():
    #First mke sure we have the rights to do this stuff
    if not session["roleID"] == ROLE_ADMIN:
        return redirect("/")
    else:
        if request.method == "POST":
            #Get values from form, insert into tblEvents.
            eventName = request.form["eventName"]

            connection = create_connection()
            with connection.cursor() as cursor:
                sql = "INSERT INTO tblevents(eventName) VALUES(%s)"
                vals = (eventName)
                cursor.execute(sql, vals)
                connection.commit()
                connection.close()

        return render_template("eventsAdd.html")

@app.route("/eventEdit", methods=["GET", "POST"])
def eventEdit():
    #First mke sure we have the rights to do this stuff
    if not session["roleID"] == ROLE_ADMIN:
        return redirect("/")
    else:
        if request.method == "POST":
            eventID = request.form["eventID"]
            eventName = request.form["eventName"]
            connection = create_connection()
            with connection.cursor() as cursor:
                sql = "UPDATE tblevents SET eventName=%s WHERE eventID=%s"
                vals = (eventName, eventID)
                cursor.execute(sql, vals)
                connection.commit()
                connection.close()
            return redirect("/events")
        else:
            eventID = request.args["eventID"]
            connection = create_connection()
            with connection.cursor() as cursor:
                sql  = "SELECT eventID, eventName FROM tblevents WHERE eventID = %s;"
                vals = (eventID)
                cursor.execute(sql, vals)
                event = cursor.fetchone()
                connection.close()
            return render_template("eventEdit.html", event = event)

@app.route("/events")
def events():
    if session["roleID"] == ROLE_ADMIN:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql  = "SELECT eventID, eventName FROM tblEvents;"
            cursor.execute(sql)
            events = cursor.fetchall()
            connection.close()
        return render_template("events.html", events = events)
    else:
        return redirect("/")


"""
Module to test TracePCA object.
"""
import os
from IPython import embed
import numpy as np
import pytest

from astropy.io import fits

from pypeit.tracepca import TracePCA
from pypeit.core.fitting import PypeItFit
from pypeit.tests.tstutils import data_path

@pytest.fixture
def vec_coo():
    nvec = 50
    return np.linspace(0,1,nvec)

@pytest.fixture
def bogus_vectors(vec_coo):
    # Generate some bogus vectors
    nspec = 1000
    spec_coo = np.linspace(0,1,nspec)
    coeff0 = 0.1*np.square(vec_coo) + vec_coo + 10
    coeff1 = 2*vec_coo - 3
    base_vector = 3*spec_coo + np.power(spec_coo,3)
    return coeff0[None,:] + coeff1[None,:]*base_vector[:,None]

def test_build(vec_coo, bogus_vectors):
    pca = TracePCA(trace_cen=bogus_vectors, npca=2, coo=vec_coo)
    pca.build_interpolator([1,2])

    assert pca.npca == 2, 'Incorrect number of components'
    assert pca.nspec == bogus_vectors.shape[0], 'Incorrect number of pixels'
    assert np.array_equal(vec_coo, pca.trace_coo), 'Coordinates do not match'
    assert pca.pca_coeffs_model.size == pca.npca, 'Incorrect number of models'
    assert isinstance(pca.pca_coeffs_model[0], PypeItFit)
    # TODO: More checks?

def test_prediction(vec_coo, bogus_vectors):
    pca = TracePCA(trace_cen=bogus_vectors, npca=2, coo=vec_coo)
    pca.build_interpolator([1,2])

    pred = pca.predict(0.5)
    assert pred.size == bogus_vectors.shape[0], 'Bad prediction'
    assert pred[0] > 10 and pred[-1] < 3, 'Prediction changed'
    # TODO: More checks?

def test_rms():
    """Test on some real data."""
    center = np.load(data_path('example_trace_deimos_1200G_M_7750.npz'))['center']

    pca = TracePCA(trace_cen=center, npca=2)
    pca.build_interpolator(np.array([3,1]), function='legendre') #, debug=True)
    pca_center = pca.predict(center[pca.reference_row,:])

    rms = np.std(center-pca_center, axis=0)
    assert np.sum(rms > 0.2) == 1, 'Change in the accuracy of the PCA.'

def test_to_hdu(vec_coo, bogus_vectors):
    pca = TracePCA(trace_cen=bogus_vectors, npca=2, coo=vec_coo)
    pca.build_interpolator([1,2])
    hdu = pca.to_hdu(add_primary=True)
    hdu_names = [h.name for h in hdu][1:]
    assert hdu_names == ['PCA', 'PCA_MODEL_1', 'PCA_MODEL_2'], 'Bad HDU extensions'

def test_write(vec_coo, bogus_vectors):
    pca = TracePCA(trace_cen=bogus_vectors, npca=2, coo=vec_coo)
    pca.build_interpolator([1,2])
    ofile = 'junkpca.fits'
    if os.path.isfile(ofile):
        os.remove(ofile)
    pca.to_file(ofile)
    os.remove(ofile)

def test_read(vec_coo, bogus_vectors):

    pca = TracePCA(trace_cen=bogus_vectors, npca=2, coo=vec_coo)
    pca.build_interpolator([1,2])
    ofile = 'junkpca.fits'
    if os.path.isfile(ofile):
        os.remove(ofile)
    pca.to_file(ofile)
    readpca = TracePCA.from_file(ofile)

    assert np.array_equal(pca.trace_coo, readpca.trace_coo), 'Bad read'
    assert np.array_equal(pca.pca_mean, readpca.pca_mean), 'Bad read'
    assert np.array_equal(pca.pca_coeffs, readpca.pca_coeffs), 'Bad read'
    assert np.array_equal(pca.pca_components, readpca.pca_components), 'Bad read'
    assert pca.npca == readpca.npca, 'Bad read'
    assert pca.nspec == readpca.nspec, 'Bad read'
    for i in range(pca.npca):
        assert np.array_equal(pca.pca_coeffs_model[i].fitc, readpca.pca_coeffs_model[i].fitc), \
                    'Bad read'
    os.remove(ofile)

def test_write_two(vec_coo, bogus_vectors):
    pca = TracePCA(trace_cen=bogus_vectors, npca=2, coo=vec_coo)
    pca.build_interpolator([1,2])
    pca2 = TracePCA(trace_cen=bogus_vectors, npca=2, coo=vec_coo)
    ofile = 'junkpca.fits'
    if os.path.isfile(ofile):
        os.remove(ofile)
    fits.HDUList([fits.PrimaryHDU()]
                  + pca.to_hdu(hdu_prefix='LEFT_')
                  + pca2.to_hdu(hdu_prefix='RIGHT_')).writeto(ofile)
    os.remove(ofile)

def test_read_two(vec_coo, bogus_vectors):
    pca = TracePCA(trace_cen=bogus_vectors, npca=2, coo=vec_coo)
    pca.build_interpolator([1,2])
    pca2 = TracePCA(trace_cen=bogus_vectors, npca=2, coo=vec_coo)
    ofile = 'junkpca.fits'
    if os.path.isfile(ofile):
        os.remove(ofile)
    hdu = fits.HDUList([fits.PrimaryHDU()]
                        + pca.to_hdu(hdu_prefix='LEFT_')
                        + pca2.to_hdu(hdu_prefix='RIGHT_'))
    _pca = TracePCA.from_hdu(hdu, hdu_prefix='LEFT_')
    _pca2 = TracePCA.from_hdu(hdu, hdu_prefix='RIGHT_')

    assert _pca.pca_coeffs_model is not None, 'Should find LEFT_PCA model'
    assert _pca2.pca_coeffs_model is None, 'Should not find RIGHT_PCA model'
    for i in range(pca.npca):
        assert np.array_equal(pca.pca_coeffs_model[i].fitc, _pca.pca_coeffs_model[i].fitc), \
                'Bad read'


"""The object returned by the `--settings` option."""
from __future__ import annotations

from typing import Any, Dict

import attrs

from civ4save.vanilla import enums as e

@attrs.define(slots=True)
class Settings:
    """Class representing the game's settings (sp only)."""

    # CvInitCore
    game_type: e.GameType
    game_name: str
    map_script: str
    """Name of the map script"""
    world_size: e.WorldType
    climate: e.ClimateType
    sea_level: e.SeaLevelType
    start_era: e.EraType
    game_speed: e.GameSpeedType
    game_options: Dict[str, bool]
    """Each GameOption and whether it's enabled"""
    max_turns: int
    advanced_start_points: int
    victories: Dict[str, bool]
    """Each VictoryType and whether it's enabled"""
    num_civs: int
    """Number of civs (not counting barbs)"""

    # CvGame
    start_turn: int
    start_year: int
    handicap: e.HandicapType
    map_random_seed: int
    soren_random_seed: int
    culture_victory_cities: int
    culture_victory_level: e.CultureLevelType

    # CvMap
    grid_width: int
    grid_height: int
    wrap_x: bool
    wrap_y: bool

    @classmethod
    def from_struct(cls, data: Any) -> Settings:
        """Return `Settings` from the parsed struct."""
        game_type = e.GameType[data.game_type]
        game_speed = e.GameSpeedType[data.game_speed]
        world_size = e.WorldType[data.world_size]
        climate = e.ClimateType[data.climate]
        sea_level = e.SeaLevelType[data.sea_level]
        start_era = e.EraType[data.start_era]

        handicap = e.HandicapType[data.handicap]
        culture_victory_level = e.CultureLevelType[data.culture_victory_level]

        game_options = {
            e.GameOptionType(n).name: v for n, v in enumerate(data.game_options)
        }

        advanced_start_points = 0
        if game_options["GAMEOPTION_ADVANCED_START"]:
            advanced_start_points = data.advanced_start_points

        victories = {e.VictoryType(n).name: v for n, v in enumerate(data.victories)}

        num_civs = len([c for c in data.civs[:-1] if c != "NO_CIVILIZATION"])

        return cls(
            game_type=game_type,
            game_name=data.game_name,
            map_script=data.map_script_name,
            world_size=world_size,
            climate=climate,
            sea_level=sea_level,
            start_era=start_era,
            game_speed=game_speed,
            game_options=game_options,
            max_turns=data.max_turns,
            advanced_start_points=advanced_start_points,
            victories=victories,
            num_civs=num_civs,
            start_turn=data.start_turn,
            start_year=data.start_year,
            handicap=handicap,
            map_random_seed=data.map_random_seed,
            soren_random_seed=data.soren_random_seed,
            culture_victory_cities=data.num_culture_victory_cities,
            culture_victory_level=culture_victory_level,
            grid_width=data.grid_width,
            grid_height=data.grid_height,
            wrap_x=data.wrap_x,
            wrap_y=data.wrap_y,
        )


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

import argparse
import sys

import tensorflow as tf

FLAGS = None

def deepnn(x):
  """deepnn builds the graph for a deep net for classifying digits.
  Args:
    x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    number of pixels in a standard MNIST image.
  Returns:
    A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    equal to the logits of classifying the digit into one of 10 classes (the
    digits 0-9). keep_prob is a scalar placeholder for the probability of
    dropout.
  """
  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1, W_fc2) + b_fc2
  return y_conv

def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def main(_):

  # Create the model
  # x = tf.placeholder(tf.float32, [None, 784])
  x = tf.placeholder(tf.float32, [None, 784], name="input")

  # No longer need keep_prob since removing dropout layers.
  y_conv = deepnn(x)
  output = tf.nn.softmax(y_conv, name='output')
  # V1版本保存为.ckpt文件格式
  saver = tf.train.Saver(tf.global_variables(),write_version=tf.train.SaverDef.V1)
  # 默认版本保存方式为文件夹形式
  # saver = tf.train.Saver(tf.global_variables())
  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run(tf.local_variables_initializer())
    # read the previously saved network.
    saver.restore(sess, './mnist_model' + '/mnist_model.ckpt')
    # save the version of the network ready that can be compiled for NCS
    saver.save(sess, './mnist_inference' + '/mnist_inference.ckpt')

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='MNIST_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)


"""
Define classes ``BaseCoherentScore`` and ``BaseCoherentScoreHM`` to
marginalize the likelihood over extrinsic parameters from
matched-filtering timeseries.

``BaseCoherentScore`` is meant for subclassing differently depending on
the waveform physics included (precession and/or higher modes).
``BaseCoherentScoreHM`` is an abstract subclass that implements phase
marginalization for waveforms with higher modes.
"""
from abc import abstractmethod, ABC
import itertools
import numba
import numpy as np
from scipy.stats import qmc
from scipy.interpolate import krogh_interpolate, make_interp_spline

from cogwheel import utils
from .lookup_table import LookupTable, LookupTableMarginalizedPhase22

class BaseCoherentScore(utils.JSONMixin, ABC):
    """
    Base class for computing coherent scores (i.e., marginalized
    likelihoods over extrinsic parameters) from matched-filtering
    timeseries.
    Meant to be subclassed differently depending on the waveform physics
    (precession and/or higher modes) that may require different
    algorithms.
    This class provides methods to initialize and perform some of the
    generic steps that the coherent score computation normally requires.
    """
    def __init__(self, sky_dict, lookup_table=None, log2n_qmc: int = 11,
                 seed=0, beta_temperature=.5, n_qmc_sequences=128):
        """
        Parameters
        ----------
        sky_dict:
            Instance of .skydict.SkyDictionary

        lookup_table:
            Instance of .lookup_table.LookupTable

        log2n_qmc: int
            Base-2 logarithm of the number of requested extrinsic
            parameter samples.

        seed: {int, None, np.random.RandomState}
            For reproducibility of the extrinsic parameter samples.

        beta_temperature: float
            Inverse temperature, tempers the arrival time probability at
            each detector.

        n_qmc_sequences: int
            The coherent score instance will generate `n_qmc_sequences`
            QMC sequences and cycle through them in subsequent calls.
            This alleviates the problem of repeated extrinsic parameter
            samples, without increasing the computational cost. It can
            also be used to estimate the uncertainty of the marginalized
            likelihood computation.
        """
        self.seed = seed
        self._rng = np.random.default_rng(seed)

        # Set up and check lookup_table with correct marginalized_params:
        if lookup_table is None:
            if self._lookup_table_marginalized_params == {'d_luminosity'}:
                lookup_table = LookupTable()
            elif self._lookup_table_marginalized_params == {'d_luminosity',
                                                            'phi_ref'}:
                lookup_table = LookupTableMarginalizedPhase22()
            else:
                raise ValueError('Unable to initialize `lookup_table`.')
        if (lookup_table.marginalized_params
                != self._lookup_table_marginalized_params):
            raise ValueError('Incompatible lookup_table.marginalized_params')
        self.lookup_table = lookup_table

        self.log2n_qmc = log2n_qmc
        self.sky_dict = sky_dict
        self.beta_temperature = beta_temperature

        self._current_qmc_sequence_id = 0
        self._qmc_sequences = [self._create_qmc_sequence()
                               for _ in range(n_qmc_sequences)]

        self._sample_distance = utils.handle_scalars(
            np.vectorize(self.lookup_table.sample_distance, otypes=[float]))

    @staticmethod
    @property
    @abstractmethod
    def _lookup_table_marginalized_params():
        """
        ``{'d_luminosity'}`` or ``{'d_luminosity', 'phi_ref'}``,
        allows to verify that the lookup table is of the correct type.
        """

    def _switch_qmc_sequence(self, qmc_sequence_id=None):
        if qmc_sequence_id is None:
            qmc_sequence_id = ((self._current_qmc_sequence_id + 1)
                               % self.n_qmc_sequences)
        self._current_qmc_sequence_id = qmc_sequence_id

    @property
    def _qmc_sequence(self):
        return self._qmc_sequences[self._current_qmc_sequence_id]

    @property
    def n_qmc_sequences(self):
        """Number of QMC sequences to alternate between."""
        return len(self._qmc_sequences)

    def _create_qmc_sequence(self):
        """
        Return a dictionary whose values are arrays corresponding to a
        Quasi Monte Carlo sequence that explores parameters per
        ``._qmc_range_dic``.
        The arrival time cumulatives are packed in a single entry
        'u_tdet'. An entry 'rot_psi' has the rotation matrices to
        transform the antenna factors between psi=0 and psi=psi_qmc.
        """
        sequence_values = qmc.scale(
            qmc.Sobol(len(self._qmc_range_dic), seed=self._rng
                     ).random_base2(self.log2n_qmc),
            *zip(*self._qmc_range_dic.values())).T

        n_det = len(self.sky_dict.detector_names)

        qmc_sequence = dict(zip(list(self._qmc_range_dic)[n_det:],
                                sequence_values[n_det:]),
                            u_tdet=sequence_values[:n_det])

        sintwopsi = np.sin(2 * qmc_sequence['psi'])
        costwopsi = np.cos(2 * qmc_sequence['psi'])
        qmc_sequence['rot_psi'] = np.moveaxis([[costwopsi, sintwopsi],
                                               [-sintwopsi, costwopsi]],
                                              -1, 0)  # qpp'
        return qmc_sequence

    @property
    def _qmc_range_dic(self):
        """
        Parameter ranges for the QMC sequence.
        The sequence explores the cumulatives of the single-detector
        (incoherent) likelihood of arrival times, the polarization, and
        the fine (subpixel) time of arrival.
        """
        dt = 1 / self.sky_dict.f_sampling
        return dict.fromkeys(self.sky_dict.detector_names, (0, 1)
                            ) | {'t_fine': (-dt/2, dt/2),
                                 'psi': (0, np.pi)}

    def _get_fplus_fcross(self, sky_inds, physical_mask):
        """
        Parameters
        ----------
        sky_inds: tuple of ints, of length n_physical
            Indices to sky_dict.sky_samples corresponding to the
            (physical) QMC samples.

        physical_mask: boolean array of length n_qmc
            Some choices of time of arrival at detectors may not
            correspond to any physical sky location, these are flagged
            ``False`` in this array.

        Return
        ------
        fplus_fcross: float array of shape (n_physical, n_detectors, 2)
            Antenna factors.
        """
        fplus_fcross_0 = self.sky_dict.fplus_fcross_0[sky_inds,]  # qdp
        rot_psi = self._qmc_sequence['rot_psi'][physical_mask]  # qpp'

        # Same but faster:
        # fplus_fcross = np.einsum('qpP,qdP->qdp', rot_psi, fplus_fcross_0)
        fplus_fcross = (rot_psi[:, np.newaxis]
                        @ fplus_fcross_0[..., np.newaxis]
                        )[..., 0]
        return fplus_fcross  # qdp

    def _draw_single_det_times(self, t_arrival_lnprob, times):
        """
        Choose time of arrivals independently at each detector according
        to the QMC sequence, according to a proposal distribution based
        on the matched-filtering timeseries.

        Parameters
        ----------
        t_arrival_lnprob: (n_times, n_det) float array
            Incoherent proposal for log probability of arrival times at
            each detector.

        times: (n_t,) float array
            Timestamps of the timeseries (s).

        Return
        ------
        t_first_det: float array of length n_qmc
            Time of arrival at the first detector (s) relative to tgps.

        delays: int array of shape (n_det-1, n_qmc)
            Time delay between the first detector and the other
            detectors, in units of 1/.skydict.f_sampling

        importance_sampling_weight: float array of length n_qmc
            Density ratio between the astrophysical prior and the
            proposal distribution of arrival times.
        """
        tdet_inds, tdet_weights = _draw_indices(
            t_arrival_lnprob.T, self._qmc_sequence['u_tdet'])  # dq, dq

        delays = tdet_inds[1:] - tdet_inds[0]  # dq  # In units of dt
        importance_sampling_weight = np.prod(
            tdet_weights / self.sky_dict.f_sampling, axis=0)  # q

        t_first_det = times[tdet_inds[0]] + self._qmc_sequence['t_fine']  # q

        return t_first_det, delays, importance_sampling_weight

    @staticmethod
    def _interp_locally(times, timeseries, new_times, spline_degree=3):
        """
        Spline interpolation along last axis of ``timeseries`` excluding
        data outside the range spanned by `new_times`. If there is too
        little data inside to make a spline, use an interpolating
        polynomial.
        """
        i_min, i_max = np.searchsorted(times,
                                       (new_times.min(), new_times.max()))
        i_min = max(0, i_min - 1)
        i_max = min(i_max, len(times) - 1)

        if i_max - i_min > spline_degree:  # If possible make a spline
            return make_interp_spline(
                times[i_min : i_max], timeseries[..., i_min : i_max],
                k=spline_degree, check_finite=False, axis=-1)(new_times)

        return krogh_interpolate(times[i_min : i_max],
                                 timeseries[..., i_min : i_max], new_times,
                                 axis=-1)

class BaseCoherentScoreHM(BaseCoherentScore):
    """
    With higher order modes it is not possible to marginalize the
    orbital phase analytically so we use trapezoid quadrature.
    ``BaseCoherentScoreHM`` provides attributes and methods for doing
    that.

    Attributes
    ----------
    m_arr
    m_inds
    mprime_inds
    nphi
    """
    # Remove from the orbital phase integral any sample with a drop in
    # log-likelihood from the peak bigger than ``DLNL_THRESHOLD``:
    DLNL_THRESHOLD = 12.

    _lookup_table_marginalized_params = {'d_luminosity'}

    def __init__(self, sky_dict, m_arr, lookup_table=None,
                 log2n_qmc: int = 11, nphi=128, seed=0,
                 beta_temperature=.5, n_qmc_sequences=128):
        """
        Parameters
        ----------
        sky_dict:
            Instance of .skydict.SkyDictionary

        m_arr: int array
            m number of the harmonic modes considered.

        lookup_table:
            Instance of lookup_table.LookupTable

        log2n_qmc: int
            Base-2 logarithm of the number of requested extrinsic
            parameter samples.

        nphi: int
            Number of orbital phases over which to perform
            marginalization with trapezoid quadrature rule.

        seed: {int, None, np.random.RandomState}
            For reproducibility of the extrinsic parameter samples.

        beta_temperature: float
            Inverse temperature, tempers the arrival time probability at
            each detector.

        n_qmc_sequences: int
            The coherent score instance will generate `n_qmc_sequences`
            QMC sequences and cycle through them in subsequent calls.
            This alleviates the problem of repeated extrinsic parameter
            samples, without increasing the computational cost. It can
            also be used to estimate the uncertainty of the marginalized
            likelihood computation.
        """
        super().__init__(sky_dict=sky_dict,
                         lookup_table=lookup_table,
                         log2n_qmc=log2n_qmc,
                         seed=seed,
                         beta_temperature=beta_temperature,
                         n_qmc_sequences=n_qmc_sequences)

        self.m_arr = np.asarray(m_arr)
        self.m_inds, self.mprime_inds = (
            zip(*itertools.combinations_with_replacement(
                range(len(self.m_arr)), 2)))

        self._dh_phasor = None  # Set by nphi.setter
        self._hh_phasor = None  # Set by nphi.setter
        self._dphi = None  # Set by nphi.setter
        self.nphi = nphi

    @property
    def nphi(self):
        """
        Number of orbital phase values to integrate over using the
        trapezoid rule. Setting this attribute also defines:
            ._dh_phasor
            ._hh_phasor
            ._phi_ref
            ._dphi
        """
        return self._nphi

    @nphi.setter
    def nphi(self, nphi):
        phi_ref, dphi = np.linspace(0, 2*np.pi, nphi,
                                    endpoint=False, retstep=True)
        self._nphi = nphi
        self._dh_phasor = np.exp(-1j * np.outer(self.m_arr, phi_ref))  # mo
        self._hh_phasor = np.exp(1j * np.outer(
            self.m_arr[self.m_inds,] - self.m_arr[self.mprime_inds,],
            phi_ref))  # mo
        self._phi_ref = phi_ref
        self._dphi = dphi

    def _get_lnl_marginalized_and_weights(self, dh_qo, hh_qo,
                                          prior_weights_q):
        """
        Parameters
        ----------
        dh_qo: (n_qmc, n_phi) float array
            ⟨d|h⟩ real inner product between data and waveform at
            ``self.lookup_table.REFERENCE_DISTANCE``.

        hh_qo: (n_qmc, n_phi) float array
            ⟨h|h⟩ real inner product of a waveform at
            ``self.lookup_table.REFERENCE_DISTANCE``  with itself.

        prior_weights_q: (n_qmc) float array
            Positive importance-sampling weights of the QMC sequence.

        Return
        ------
        lnl_marginalized: float
            log of the marginalized likelihood over extrinsic parameters
            excluding inclination (i.e.: time of arrival, sky location,
            polarization, distance, orbital phase).

        weights: float array of length n_important
            Positive weights of the QMC samples, including the
            likelihood and the importance-sampling correction.

        important: (array of ints, array of ints) of lengths n_important
            The first array contains indices between 0 and n_physical-1
            corresponding to (physical) QMC samples.
            The second array contains indices between 0 and n_phi-1
            corresponding to orbital phases.
            They correspond to samples with sufficiently high maximum
            likelihood over distance to be included in the integral.
        """
        max_over_distance_lnl = dh_qo * np.abs(dh_qo) / hh_qo / 2  # qo
        important = np.where(
            max_over_distance_lnl
            > np.max(max_over_distance_lnl) - self.DLNL_THRESHOLD)
        lnl_marg_dist = self.lookup_table.lnlike_marginalized(
            dh_qo[important], hh_qo[important])  # i

        lnl_max = lnl_marg_dist.max()
        like_marg_dist = np.exp(lnl_marg_dist - lnl_max)  # i

        weights = like_marg_dist * prior_weights_q[important[0]]  # i
        lnl_marginalized = lnl_max + np.log(weights.sum() * self._dphi
                                            / 2**self.log2n_qmc)
        return lnl_marginalized, weights, important

@numba.guvectorize([(numba.float64[:], numba.float64[:],
                     numba.int64[:], numba.float64[:])],
                   '(n),(m)->(m),(m)')
def _draw_indices(unnormalized_lnprob, quantiles, indices, weights):
    """
    Sample desired quantiles from a distribution using the inverse of
    its cumulative.

    Parameters
    ----------
    unnormalized_lnprob, quantiles

    Return
    ------
    indices, weights
    """
    prob = np.exp(unnormalized_lnprob - unnormalized_lnprob.max())
    cumprob = np.cumsum(prob)
    prob /= cumprob[-1]  # Unit sum
    cumprob /= cumprob[-1]
    indices[:] = np.searchsorted(cumprob, quantiles)
    weights[:] = 1 / prob[indices]


# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

from polyaxon_client import settings
from polyaxon_client.exceptions import PolyaxonClientException
from polyaxon_client.tracking import Experiment

try:
    from fastai.callbacks import TrackerCallback
except ImportError:
    raise PolyaxonClientException('Fastai is required to use PolyaxonFastai')

class PolyaxonFastai(TrackerCallback):

    def __init__(self, learn, experiment=None, monitor='val_loss', mode='auto'):
        super(PolyaxonFastai, self).__init__(learn, monitor=monitor, mode=mode)
        self.experiment = experiment
        if settings.IS_MANAGED:
            self.experiment = self.experiment or Experiment()

    def on_epoch_end(self, epoch, smooth_loss, last_metrics, **kwargs):
        if not self.experiment:
            return
        metrics = {
            name: stat for name, stat in
            list(zip(self.learn.recorder.names, [epoch, smooth_loss] + last_metrics))[1:]
        }

        self.experiment.log_metrics(**metrics)


#! /usr/bin/env python

import roslib
roslib.load_manifest('cocktail_party')
import rospy
import smach
import smach_ros

from pal_smach_utils.utils.global_common import succeeded, preempted, aborted, print_grasp_errors
from cocktail_party import CocktailPartyStateMachine

def main():
    rospy.init_node('cocktail_party_launch')

    sm = smach.StateMachine(outcomes=[succeeded, preempted, aborted])

    with sm:
        smach.StateMachine.add(
            "COCKTAIL_PARTY_TEST",
            CocktailPartyStateMachine(),
            transitions={succeeded: "PRINT_GRASP_ERRORS", preempted: "PRINT_GRASP_ERRORS", aborted: "PRINT_GRASP_ERRORS"}
        )

        smach.StateMachine.add(
            "PRINT_GRASP_ERRORS",
            smach.CBState(print_grasp_errors, outcomes=[succeeded])
        )

    sis = smach_ros.IntrospectionServer(
        'cocktail_party_launch_introspection', sm, '/SM_ROOT')
    sis.start()

    sm.execute()

    rospy.spin()
    sis.stop()

if __name__ == '__main__':
    main()


import pandas as pd
import numpy as np
import string
from sklearn.preprocessing import LabelEncoder
import tensorflow as tf
import random

## data set
data = {
    "intents" :
    [
        {
            "tag" : "greeting",
            "inputs" : [
                "hello",
                "hi"
            ],
            "responses" : [
                "Hello There"
            ]
        },
        {
            "tag" : "goodbye",
            "inputs" : [
                "Goodbye"
            ],
            "responses" : [
                "Goodbye!"
            ]
        },
        {
            "tag" : "greeting-jp",
            "inputs" : [
            "おはようございます"
            ],
            "responses" : [
            "おはようございます"
            ]
        }
    ]
}

tags = []
inputs = []
responses = {}
for intent in data['intents']:
    responses[intent['tag']] = intent['responses']
    for lines in intent['inputs']:
        inputs.append(lines)
        tags.append(intent['tag'])

df = pd.DataFrame(
    {
        "inputs" : inputs,
        "tags" : tags
    }
)

df = df.sample(frac=1)

## data pre processing
df['inputs'] = df['inputs'].apply(lambda wrd:[ltrs.lower() for ltrs in wrd if ltrs not in string.punctuation])
df['inputs'] = df['inputs'].apply(lambda wrd: ''.join(wrd))

tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=2000)
tokenizer.fit_on_texts(df['inputs'])
train = tokenizer.texts_to_sequences(df['inputs'])
X_train = tf.keras.preprocessing.sequence.pad_sequences(train)

## encode outputs to binary for the machine to understand
encoder = LabelEncoder()
y_train = encoder.fit_transform(df['tags'])

input_shape = X_train.shape[1]

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(input_shape,)),
    tf.keras.layers.Dense(64, activation = 'relu'),
    tf.keras.layers.Dense(64, activation  ='relu'),
    tf.keras.layers.Dense(1, activation = 'sigmoid')
  ]
)

initial_learning_rate = 0.06
decay_steps = 1000
decay_rate = 0.9

learning_rate_schedule = tf.optimizers.schedules.ExponentialDecay(initial_learning_rate, decay_steps, decay_rate)

optimiser = tf.keras.optimizers.Adam(learning_rate = learning_rate_schedule)

model.compile(optimizer = optimiser, loss = 'binary_crossentropy', metrics=['accuracy'])

model.fit(X_train, y_train, epochs=200)

while True:
    texts_p = []
    prediction_input = input('You: ')

    prediction_input = [letters.lower() for letters in prediction_input if letters not in string.punctuation]
    prediction_input = ''.join(prediction_input)
    texts_p.append(prediction_input)

    prediction_input = tokenizer.texts_to_sequences(texts_p)
    prediction_input = np.array(prediction_input).reshape(-1)
    prediction_input = tf.keras.preprocessing.sequence.pad_sequences([prediction_input], input_shape)

    output = model.predict(prediction_input)
    output = output.argmax()

    response_tag = encoder.inverse_transform([output])[0]
    bot_name = 'bob'

    print(f'{bot_name}: ', random.choice(responses[response_tag]))
    if response_tag == "goodbye":
        break


size=int(input("Enter the size of list: "))
list=[]
for i in range(size):
    ele=int(input("Enter the element: "))
    list.append(ele)
print(list)
large=list[0]
second_large=list[0]
for i in range(size):
    if list[i]>large:
        second_large=large
        large=list[i]
print("The second largest number is: ",second_large)


from tabnanny import check
import pandas as pd
import numpy as np
import argparse, os, glob
from analysis.checkpoints import all_checkpoints, checkpoints as paper_checkpoints

def main(env_name, fam, intervention=-1, checkpoint=None):

    if checkpoint is not None:
        assert checkpoint in all_checkpoints, "checkpoint not available"
        checkpoints = [checkpoint]
    else:
        checkpoints = paper_checkpoints
    df_list = []
    for checkpoint in checkpoints:
        dir = f"storage/results/intervention_js_div/{env_name}/{fam}/11_agents/30_states/trajectory/check_{checkpoint}/"
        number = {'Amidar':69, 'SpaceInvaders':88, 'Breakout':38}
        file = dir + f"{number[env_name]}_interventions.txt"
        d = pd.read_csv(file, sep=' ', skiprows=0, header=0, names = ["agent","state","intervention","js_div"])
        d = d.astype({"intervention":int,"state":int})
        d = d[d["state"]==0]
        d = d.drop(columns=['agent','state'])
        d["frame"] = checkpoint
        df_list.append(d)

    df_r = pd.concat(df_list, ignore_index=True)

    df_list = []
    dir = f"storage/results/intervention_performance/{env_name}/{fam}"
    loadfiles = glob.glob(dir + "/*.txt")
    for file in loadfiles:
        try:
            d = pd.read_csv(file, sep=',')
            if len(d)!=55:
                if fam == "c51":
                    d = d.loc[d["agent"].isin([1,2,3,4,5,6,7,8,9,10,11])]
                    df_list.append(d)
                elif fam == "ddqn":
                    d = d.loc[d["agent"].isin([1,2,3,4,5,6,7,8,9,10,11])]
                    df_list.append(d)
                else:
                    print("Length: ", len(d), " File: ", file)
            else:
                df_list.append(d)
        except pd.errors.EmptyDataError:
            print("Failed: ", file)

    df_p = pd.concat(df_list, ignore_index=True)
    df_p = df_p.groupby(["intervention","frame"]).agg({"mean": np.mean, "std":np.mean, "median": lambda x: x.tolist()}).reset_index()

    # df = df_p.groupby(["intervention","frame"]).mean()
    df = df_p.rename(columns = {"mean":"mean_performance", "std":"mean_std", "median":"median_performance"})
    # df = df.drop(columns = ['agent'])

    df = pd.merge(df, df_r, how="left", on=["intervention","frame"])
    file = f"storage/results/intervention_performance_results/{env_name}_{fam}_intvperf.csv"
    df.to_csv(file)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Analyse intervention performance of a single agent family."
    )
    parser.add_argument(
        "--env",
        nargs=1,
        type=str,
        help="environment name: SpaceInvaders, Amidar, or Breakout",
    )
    parser.add_argument(
        "--family",
        nargs=1,
        type=str,
        help="Agent family:  a2c,c51, dqn, ddqn, ppo, rainbow, vsarsa, vqn",
    )

    args = parser.parse_args()

    main(args.env[0], args.family[0])


# coding: utf-8

"""
    Fatture in Cloud API v2 - API Reference

    Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 500.000 businesses in Italy.   The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol.

    The version of the OpenAPI document: 2.0.30
    Contact: info@fattureincloud.it
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501

from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from typing import Optional, Union
from pydantic import BaseModel, Field, StrictBool, StrictFloat, StrictInt, StrictStr

class VatType(BaseModel):
    """
    VatType
    """

    id: Optional[StrictInt] = Field(None, description="Vat type id")
    value: Optional[Union[StrictFloat, StrictInt]] = Field(
        None, description="[Read Only] Vat type percentual value"
    )
    description: Optional[StrictStr] = Field(
        None, description="Vat type short description"
    )
    notes: Optional[StrictStr] = Field(
        None, description="Vat type notes shown in documents"
    )
    e_invoice: Optional[StrictBool] = Field(
        None, description="Vat type is usable for e-invoices"
    )
    ei_type: Optional[StrictStr] = Field(
        None, description="Vat type e-invoice type (natura)"
    )
    ei_description: Optional[StrictStr] = Field(
        None, description="Vat type e-invoice description"
    )
    editable: Optional[StrictBool] = Field(
        None, description="[Read Only] Is the vat type is editable."
    )
    is_disabled: Optional[StrictBool] = Field(
        None, description="Is the vat type disabled"
    )
    __properties = [
        "id",
        "value",
        "description",
        "notes",
        "e_invoice",
        "ei_type",
        "ei_description",
        "editable",
        "is_disabled",
    ]

    class Config:
        """Pydantic configuration"""

        allow_population_by_field_name = True
        validate_assignment = True

    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.dict(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> VatType:
        """Create an instance of VatType from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self):
        """Returns the dictionary representation of the model using alias"""
        _dict = self.dict(
            by_alias=True,
            exclude={
                "editable",
            },
            exclude_none=True,
        )
        return _dict

    @classmethod
    def from_dict(cls, obj: dict) -> VatType:
        """Create an instance of VatType from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return VatType.parse_obj(obj)

        _obj = VatType.parse_obj(
            {
                "id": obj.get("id") if obj.get("id") is not None else None,
                "value": float(obj.get("value"))
                if obj.get("value") is not None
                else None,
                "description": obj.get("description")
                if obj.get("description") is not None
                else None,
                "notes": obj.get("notes") if obj.get("notes") is not None else None,
                "e_invoice": obj.get("e_invoice")
                if obj.get("e_invoice") is not None
                else None,
                "ei_type": obj.get("ei_type")
                if obj.get("ei_type") is not None
                else None,
                "ei_description": obj.get("ei_description")
                if obj.get("ei_description") is not None
                else None,
                "editable": obj.get("editable")
                if obj.get("editable") is not None
                else None,
                "is_disabled": obj.get("is_disabled")
                if obj.get("is_disabled") is not None
                else None,
            }
        )
        return _obj


import cv2
import numpy as np

if __name__ == "__main__":
    # Get video from webcam
    cap = cv2.VideoCapture(0)
    # Define cascades
    face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
    eye_casacade = cv2.CascadeClassifier("haarcascade_eye.xml")

    # Infinite loop for processing image
    while True:
        ret, img = cap.read()
        # Convert image to gray
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # Find faces
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)

        # Draw faces on the image
        for (x, y, w, h) in faces:
            cv2.rectangle(img, (x, y), (x+w, x+h), (255, 255, 255), 2)
            # Find eyes on the face
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = img[y:y+h, x:x+w]
            eyes = eye_casacade.detectMultiScale(roi_gray)
            for (ex, ey, ew, eh) in eyes:
                # Draw rectangles near eyes
                cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0,0,255), 1)

        # Show images
        cv2.imshow("Detect face and eyes", img)

        k = cv2.waitKey(30) & 0xff
        if k == 27:
            break

    cap.release()
    cv2.destroyAllWindows()