import os
import sys
import ctypes
import numpy as np
import math
import OpenGL.GL as gl
import OpenGL.GLUT as glut
from perlin_noise import PerlinNoise

# Initializing Global Parameters
noise = PerlinNoise()
fieldOfView = 80
byteOffset = 0
perlinNoiseFactor = 0.12

# Setting perlin Noise factor through Command Line Arguments
if len(sys.argv) == 2:
    perlinNoiseFactor = float(sys.argv[1])

# Paramters [ Mesh Size, Screen Reoslution, Scaling Size, Perlin Factor]
parameters = [48, 25, 8, 4, 4, perlinNoiseFactor]
startPoint = 0

# Vetex Shader Definition
vertexShaderCode = """
    attribute vec3 position;
    uniform mat4 transformationMatrix[2];
    uniform mat4 projectionMatrix;
    uniform mat4 translate;

    void main(){
        gl_Position = projectionMatrix * transformationMatrix[0] * transformationMatrix[1] * translate * vec4(position, 1.0);
    }
    """

# Fragment Shader Definition
fragmentShaderCode = """
    void main(){
        gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
    }
    """

# -- Building Data --
def generateTerrain(value):
    global data
    global noise

    data = []

    halfDataX = int(value[0] * value[4] / 2)
    halfDataY = int(value[1] * value[4] / 2)

    scaledResolutionX = int(value[2] * value[4] / 2)
    scaledResolutionY = int(value[3] * value[4] / 2)

    startX = 0
    startY = 0
    for j in range(-halfDataY, halfDataY):
        for i in range(-halfDataX, halfDataX):
            iData = i / scaledResolutionX
            jData = j / scaledResolutionY
            nextiData = (i + 1) / scaledResolutionX
            nextjData = (j + 1) / scaledResolutionY
            data.append([iData, jData, mapNoise(noise([startX, startY]))])
            data.append([iData, nextjData, mapNoise(noise([startX, (startY + value[5])]))])
            data.append([nextiData, jData, mapNoise(noise([(startX + value[5]), startY]))])
            startX = startX + value[5]

        startY = startY + value[5]
        startX = 0

    data = np.array(data, dtype = np.float32)
    return data

# Animate function to create a dynamically flowing terrain through y-axis [called every 10 microsecond]
def animate(offset):
    global noise
    global byteOffset
    global parameters
    global fieldOfView

    offsetY = int(parameters[1] * parameters[4] / 2) + offset

    halfDataX = int(parameters[0] * parameters[4] / 2)

    scaledResolutionX = int(parameters[2] * parameters[4] / 2)
    scaledResolutionY = int(parameters[3] * parameters[4] / 2)

    noOfData = 2 * halfDataX * 3

    translation = generateTranslation([0.0, -offset/scaledResolutionY, 0.0])

    loc = gl.glGetUniformLocation(program, "translate")
    gl.glUniformMatrix4fv(loc, 1, gl.GL_TRUE, translation)

    projectionMatrix = generatePerspective()

    loc = gl.glGetUniformLocation(program, "projectionMatrix")
    gl.glUniformMatrix4fv(loc, 1, gl.GL_TRUE, projectionMatrix)

    data = []
    nextjData = (offsetY + 1) / scaledResolutionY
    jData = offsetY / scaledResolutionY
    startY = ((parameters[1] * parameters[4]) + offset) * parameters[5]
    startX = 0
    for i in range(-halfDataX, halfDataX):
        iData = i / scaledResolutionX
        nextiData = (i + 1) / scaledResolutionX
        data.append([iData, jData, mapNoise(noise([startX, startY]))])
        data.append([iData, nextjData, mapNoise(noise([startX, (startY + parameters[5])]))])
        data.append([nextiData, jData, mapNoise(noise([(startX + parameters[5]), startY]))])
        startX = startX + parameters[5]
    data = np.array(data, dtype = np.float32)

    rowBytes = noOfData * data.strides[0]
    maxBuffer = int(parameters[1] * parameters[4]) -1

    # Set Byte Offset to 0 on reaching maximum bytes
    if  byteOffset > maxBuffer:
        byteOffset = 0

    # Substitute the Buffer Data based on byte offset
    gl.glBufferSubData(gl.GL_ARRAY_BUFFER, byteOffset * rowBytes, rowBytes, data)

    byteOffset = byteOffset + 1

    # Call oneself every 10 microsecond
    glut.glutTimerFunc(10, animate, offset + 1)

# funtion to map noise values between Min and Max
def mapNoise(noiseValue, maxMap = 1, minMap = 0.75):
    if noiseValue > 0:
        return noiseValue * maxMap
    else:
        return noiseValue * minMap

# function to request and compiler shader slots from GPU
def createShader(source, type):
    # request shader
    shader = gl.glCreateShader(type)

    # set shader source using the code
    gl.glShaderSource(shader, source)

    gl.glCompileShader(shader)
    if not gl.glGetShaderiv(shader, gl.GL_COMPILE_STATUS):
        error = gl.glGetShaderInfoLog(shader).decode()
        print(error)
        raise RuntimeError(f"{source} shader compilation error")

    return shader

# function to build and activate program
def createProgram(vertex, fragment):
    program = gl.glCreateProgram()

    # attach shader objects to the program
    gl.glAttachShader(program, vertex)
    gl.glAttachShader(program, fragment)

    gl.glLinkProgram(program)
    if not gl.glGetProgramiv(program, gl.GL_LINK_STATUS):
        print(gl.glGetProgramInfoLog(program))
        raise RuntimeError("Linking error")

    # Get rid of shaders (no more needed)
    gl.glDetachShader(program, vertex)
    gl.glDetachShader(program, fragment)

    return program

# Rotation Matrix Generator
def generateRotation(transformationData = None):
    if not transformationData or transformationData[0] == "":
        transformationMatrix = np.array(
            [
                1.0,0.0,0.0,0.0,
                0.0,1.0,0.0,0.0,
                0.0,0.0,1.0,0.0,
                0.0,0.0,0.0,1.0,
            ],
            np.float32,
        )
        return transformationMatrix
    cTheta = np.cos(transformationData[1] / 180 * math.pi)
    sTheta = np.sin(transformationData[1] / 180 * math.pi)

    # x - axis rotation
    if transformationData[0] == "pitch":
        transformationMatrix = np.array(
            [
                1.0,0.0,0.0,0.0,
                0.0,cTheta,-sTheta,0.0,
                0.0,sTheta,cTheta,0.0,
                0.0,0.0,0.0,1.0,
            ],
            np.float32,
        )

    # y - axis rotation
    elif transformationData[0] == "yaw":
        transformationMatrix = np.array(
            [
                cTheta,0.0,sTheta,0.0,
                0.0,1.0,0.0,0.0,
                -sTheta,0.0,cTheta,0.0,
                0.0,0.0,0.0,1.0,
            ],
            np.float32,
        )

    # z - axis rotation
    elif transformationData[0] == "roll":
        transformationMatrix = np.array(
            [
                cTheta,-sTheta,0.0,0.0,
                sTheta,cTheta,0.0,0.0,
                0.0,0.0,1.0,0.0,
                0.0,0.0,0.0,1.0,
            ],
            np.float32,
        )

    return transformationMatrix

# Translation Matrix Generator
def generateTranslation(translationData = None):
    if not translationData or translationData[0] == "":
        transformationMatrix = np.array(
            [
                1.0,0.0,0.0,0.0,
                0.0,1.0,0.0,0.0,
                0.0,0.0,1.0,0.0,
                0.0,0.0,0.0,1.0,
            ],
            np.float32,
        )

        return transformationMatrix

    transformationMatrix = np.array(
            [
                1.0,0.0,0.0,translationData[0],
                0.0,1.0,0.0,translationData[1],
                0.0,0.0,1.0,translationData[2],
                0.0,0.0,0.0,1.0,
            ],
            np.float32,
        )

    return transformationMatrix

# Perspective Projection Generatior based on Field of View
def generatePerspective():
    global fieldOfView

    fov = (fieldOfView * math.pi)/180
    tanFOVHalf = np.tan(fov / 2.0)
    f = 1/tanFOVHalf
    projectionMatrix = np.array([f, 0.0, 0.0, 0.0,
                                0.0, 1.0, 0.0, 0.0,
                                0.0, 0.0, 1.0, 0.0,
                                0.0, 0.0, 1.0, 1.0], dtype = np.float32)
    return projectionMatrix

# initialization function
def initialize():
    global program
    global data
    global parameters
    global vertexBuffer
    global fieldOfView

    # Enabling Depth Buffer Test
    gl.glEnable(gl.GL_DEPTH_TEST)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
    gl.glClearColor(0.0, 0.0, 0.0, 0.0)
    gl.glLoadIdentity()

    # Initializing the Global Program
    program = createProgram(
        createShader(vertexShaderCode, gl.GL_VERTEX_SHADER),
        createShader(fragmentShaderCode, gl.GL_FRAGMENT_SHADER),
    )

    # building data
    data = generateTerrain(parameters)

    # generating projection, translation and rotation matrix
    projectionMatrix = generatePerspective()

    translationMatrix =generateTranslation([0, 0.0, 0.3])

    translation = generateTranslation()
    rotationMatrix = generateRotation(["pitch", 45])

    transformationMatrix = np.array([rotationMatrix, translationMatrix])

    # make program the default program
    gl.glUseProgram(program)

    # Generate Vexter Buffer
    vertexBuffer = gl.glGenBuffers(1)

    # Make this generated Buffer to be Array Buffer
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vertexBuffer)

    # Bind the position attribute
    stride = data.strides[0]
    offset = ctypes.c_void_p(0)
    loc = gl.glGetAttribLocation(program, "position")
    gl.glEnableVertexAttribArray(loc)
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vertexBuffer)
    gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)

    # Bind the transformation, rotation and projection matrices to vertex shader's uniforms
    loc = gl.glGetUniformLocation(program, "transformationMatrix")
    gl.glUniformMatrix4fv(loc, 2, gl.GL_TRUE, transformationMatrix)

    loc = gl.glGetUniformLocation(program, "projectionMatrix")
    gl.glUniformMatrix4fv(loc, 1, gl.GL_TRUE, projectionMatrix)

    loc = gl.glGetUniformLocation(program, "translate")
    gl.glUniformMatrix4fv(loc, 1, gl.GL_TRUE, translation)

    # Upload data
    gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, gl.GL_DYNAMIC_DRAW)

def display():
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

    # Set Drwaing mode to Lines instead of Fill
    gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)

    # Draw Traingular Meshes
    gl.glDrawArrays(gl.GL_TRIANGLES, 0, data.shape[0])
    glut.glutSwapBuffers()
    glut.glutPostRedisplay()

def reshape(width, height):
    gl.glViewport(0, 0, width, height)

# Exit on Escape
def keyboard(key, x, y):
    if key == b"\x1b":
        os._exit(1)

# Track the change in Mouse Pointer on Drag to modify Field of View
def mouse(x ,y):
    global startPoint
    global fieldOfView

    delX = x - startPoint

    if (delX == 0):
        fieldOfView = 70
    else:
        fieldOfView = (fieldOfView + (delX * 0.0050)) % 180

# GLUT init
glut.glutInit()
glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH)
glut.glutCreateWindow("Graphics Window")
glut.glutReshapeWindow(1920, 1080)
glut.glutReshapeFunc(reshape)

initialize()
animate(0)

glut.glutDisplayFunc(display)
glut.glutPostRedisplay()
glut.glutKeyboardFunc(keyboard)
glut.glutMotionFunc(mouse)

# enter the mainloop
glut.glutMainLoop()


import streamlit as st
import pandas as pd
import numpy as np

sorama = pd.read_csv('https://raw.githubusercontent.com/Jordds/gemEindhoven/main/sorama.csv',  nrows = 5)
vinotion = pd.read_csv('https://raw.githubusercontent.com/Jordds/gemEindhoven/main/csv_vinotion_sept.csv', nrows = 5)
tno = pd.read_csv('https://raw.githubusercontent.com/Jordds/gemEindhoven/main/csv_dust_sept.csv', nrows = 5)

devID = sorama['deviceId']
s = sorama['content'].str.split(',', n=3, expand = True)
s = s.rename(columns={0: 'measurementType', 1 :'timestamp', 2:'duration', 3:'value'})
s['timestamp'] = s['timestamp'].str[10:29]
s['date'] = pd.to_datetime(s['timestamp']).dt.date
s['time'] = pd.to_datetime(s['timestamp']).dt.time
s['hour'] = pd.to_datetime(s['timestamp']).dt.hour
s['value'] = s['value'].str.extract('(\d*\.\d+|\d+)', expand = False).astype(float)
s['measurementType'] = s['measurementType'].str[21:25]
s = s[['date', 'time', 'hour','measurementType', 'value']]
df3 = pd.concat([s, devID], axis=1)
df3['value'] = df3['value'].astype('float16') #reducing load on RAM

vinotion['Date'] = pd.to_datetime(vinotion['timestamp']).dt.date
vinotion['Time'] = pd.to_datetime(vinotion['timestamp']).dt.time
vinotion['camID'] = vinotion['cameraId'].str[17:19]
vinotion['direction'] = vinotion['ruleId'].str[20:27].str.replace('/', ' ')
vinotion['speed'] = vinotion['speed'] * 3.6 #csv contains m/s not km/h
df2 = vinotion[['Date', 'Time', 'speed', 'classification', 'camID','direction']]

conditions = [
        (df2['camID'] == '12') & (df2['direction'] == 'Count 0'),
        (df2['camID'] == '12') & (df2['direction'] == 'Count 1'),
        (df2['camID'] == '12') & (df2['direction'] == 'Count 2'),
        (df2['camID'] == '11') & (df2['direction'] == 'Count 0'),
        (df2['camID'] == '11') & (df2['direction'] == 'Count 1'),
        (df2['camID'] == '13') & (df2['direction'] == 'Count 0'),
        (df2['camID'] == '15') & (df2['direction'] == 'Count 0'),
        (df2['camID'] == '15') & (df2['direction'] == 'Count 1'),
        (df2['camID'] == '15') & (df2['direction'] == 'Count 2'),
        (df2['camID'] == '15') & (df2['direction'] == 'Count 3'),
        (df2['camID'] == '14') & (df2['direction'] == 'Count 0'),
        (df2['camID'] == '14') & (df2['direction'] == 'Count 1'),
        (df2['camID'] == '14') & (df2['direction'] == 'Count 2')
    ]
values = ['Onze Lieve Vrouwestraat',
          'Crossover from city',
          'Crossover to city',
          'From Kennedylaan',
          'Ring',
          'Ring',
          'From City',
          'From Ring',
          'Crossover to left',
          'Crossover to right',
          'Ring',
          'To the city',
          'Illegal turning'
         ]
df2['real_direction'] = np.select(conditions, values)
df2 = df2[['Date', 'Time', 'speed', 'classification', 'camID','real_direction']]

tno = tno.drop(tno.iloc[:,15:23], axis = 1)
tno['Lat'] = tno['geoPointLocation'].str.extract('(\d*\.\d+|\d+)', expand = False).astype(float)
tno['Lon'] = tno['geoPointLocation'].str[15:].str.extract('(\d*\.\d+|\d+)', expand = False).astype(float)
tno['Date'] = pd.to_datetime(tno['timestamp']).dt.date
tno['Time'] = pd.to_datetime(tno['timestamp']).dt.time
df = tno[['Date', 'Time', 'Lat', 'Lon', 'pm1', 'pm10', 'pm25']]

st.title("Data verzameld door de sensoren")
st.subheader("Sorama")
st.write(sorama)
st.write(df3)

st.subheader("vinotion")
st.write(vinotion)
st.write(df2)

st.subheader("TNO")
st.write(tno)
st.write(df)


from http.server import HTTPServer, CGIHTTPRequestHandler

def run_server():
    server_address = ("127.0.0.1",2222)
    print("Веб-сервер запущено!")
    httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
    httpd.serve_forever()

if __name__ == "__main__":
    run_server()


from dotenv import load_dotenv
from pprint import pprint
from newsapi import NewsApiClient
import urllib
import os
from bs4 import BeautifulSoup
from readability import Document
from find_entity import find_entity
import pickle
import pandas as pd
from mysql_caching import set_cache_entities, get_cached_entities
import functools

load_dotenv()

newsapi = NewsApiClient(api_key=os.environ.get("GOOGLE_NEWS_API"))

@functools.lru_cache(maxsize=512)
def html2text(url: str) -> str:
    request = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0'})
    html = urllib.request.urlopen(request).read()
    doc = Document(html)
    cleaned = "
" + doc.short_title() + "

" + doc.summary()
    soup = BeautifulSoup(cleaned, features="html.parser")

    # kill all script and style elements
    for script in soup(["script", "style"]):
        script.extract()  # rip it out

    # get text
    text = soup.get_text()

    # break into lines and remove leading and trailing space on each
    lines = (line.strip() for line in text.splitlines())
    # break multi-headlines into a line each
    chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
    # drop blank lines
    text = "\n".join(chunk for chunk in chunks if chunk)
    return text

def process_headlines(language="en", country="gb"):
    top_headline = newsapi.get_top_headlines(
        language=language, country=country, page_size=100
    )
    result = []
    for article in top_headline["articles"]:
        try:

            article["text"] = html2text(article["url"])
            entities = get_cached_entities(article["url"])
            if entities is None:
                entities = find_entity(article["text"], language=language)
                set_cache_entities(article["url"], entities)
            article["entities"] = entities
            print("It worked for", article["url"], flush=True)
            result.append(article)
        except urllib.error.HTTPError as e:
            print(f"We cannot fetch for", article["url"], e, flush=True)
        except urllib.error.URLError as e:
            print(f"the url is wrong", article["url"], e, flush=True)

    df = pd.DataFrame(result)
    with open("headline_google.pickle", "wb") as output_file:
        pickle.dump(df, output_file)
    return df.to_json()

if __name__ == "__main__":
    process_headlines(language="en", country="gb")


# run simulation using simulation.py
# assumes varying mass

from simulation import sim_system
from sandbox.rocky.tf.envs.vary_wrapper import VaryMassRolloutWrapper
import os
import numpy as np
import tensorflow as tf

prefix = "/Users/Chelsea/Dropbox/AAHAA/src/rllab/data/local/experiment/"
policy_name = "EXCELLENT_POLICY_relu_small_network_ppo_capped_action_simpler_dense_layer_xW_learn_std_smaller_learning_rate"
policy_file = os.path.join(prefix, policy_name, 'params.pkl')
start_range = ([-5*np.pi/180, -60*np.pi/180],
			   [5*np.pi/180, 60*np.pi/180])
#([-10*np.pi/180, -120*np.pi/180],[10*np.pi/180, 120*np.pi/180])

safe_range = ([-10*np.pi/180, -60*np.pi/180],[10*np.pi/180, 60*np.pi/180])
#([-0.17453292519943295, -2.0943951023931953],
#			  [ 0.17453292519943295,  2.0943951023931953]
#			 )
nsteps = 2
nsims = 150
wrap_fn = None

# labels for plotting are in deg but computations happen in radians
labels = ["theta, deg", "thetadot, deg/s"]

with tf.Session() as sess:
	sim_system(policy_file, policy_name, start_range, safe_range, nsteps, nsims, wrap_fn, labels=labels, plot_trajs=True, rand=False)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 17 17:39:16 2021

@author: BenHong
"""
import time
import random as rd
import numpy as np
import matplotlib.pyplot as plt
from numpy import linalg as LA

d = 30
f_opt = -418.9828 * d

def constraint(x): # constraint in the homework
    if x > 500:
        return 500
    elif x < -500:
        return -500
    else :
        return x

def f(x):  # optimaize target
    sum = 0
    for i in range(0,d-1):
        sum -= x[i]*math.sin(math.sqrt(abs(x[i])))
    return sum

def error(f_x): # relative error
    return abs(f_x-f_opt)/abs(f_opt)

# w:weight , n:number of Particle Swarm ,T : max iteration
def Particle_Swarm_Optimization(n,T):
    start = time.time()
    ParticleSwarm = np.random.uniform(-500,500,size=(n,d)) #generate Particle Swarm
    fitness = [f(ParticleSwarm[i]) for i in range(n)]
    Local_optimal = ParticleSwarm.copy()
    optimal_value = [f(Local_optimal[i]) for i in range(n)]
    Global_optimal = np.zeros(d+1)
    Global_optimal[:-1] = Local_optimal[np.argsort(optimal_value)[0]]
    Global_optimal[-1] = min(optimal_value )
    velocity = np.zeros((n,d))
    e = []
    speed = []
    e.append(error(Global_optimal[-1]))
    print('Relative error:',e[-1],"\n position:",Global_optimal[:-1])
    t = 0
    while(time.time()-start < 60*10 and t<T):
        w = 0.9 - 0.5/T*t    # weight linear decay
        c = 2.5 - 1.5/T*t
        r_1 = rd.random()
        r_2 = rd.random()
        velocity = [w*velocity[i] + r_1*(Local_optimal[i] - ParticleSwarm[i]) + r_2*(Global_optimal[:-1]- ParticleSwarm[i]) for i in range (n)]
        ParticleSwarm = ParticleSwarm + velocity
        for i in range(n):                    ##bound Particle Swarm
            for j in range (d):
                ParticleSwarm[i][j]=constraint(ParticleSwarm[i][j])

        fitness = [f(ParticleSwarm[i]) for i in range(n)]

        for i in range (n):
            if optimal_value[i] > fitness[i] :
                Local_optimal[i] = ParticleSwarm[i]
        optimal_value = [f(Local_optimal[i]) for i in range(n)]
        Global_optimal_old = Global_optimal.copy()
        Global_optimal[:-1] = Local_optimal[np.argsort(optimal_value)[0]]
        Global_optimal[-1] = min(optimal_value)
        e.append(error(Global_optimal[-1]))
        speed.append(LA.norm((Global_optimal[:-1]-Global_optimal_old[:-1]),2))
        t+=1
        print('Relative error:',e[-1],"\n position:",Global_optimal[:-1])
    plt.title("Relative error") # title
    plt.plot(e)
    plt.show()
    plt.title("velocity of the GB particle") # title
    plt.plot(speed)
    plt.show()


import pygame, copy, random, math
from Vec2d import Vec2d
from pygame.locals import *
from sys import exit
from threading import *
from time import sleep
background = './bg.jpg'
my_plan_picture = './plane01.png'
enemy_picture = './enemy.png'
my_bullet_picture = './bullet.png'
enemy_bullet_picture = './enemybullet.png'
boom_picture = './boom.png'
boss_picture = './boss.png'
fire_picture = './fire.png'
plan_not_defeat = './plane8888.png'
box = './box.png'
missile = './daodan.png'
lock = './lock.png'
music = './bgm.mp3'
pygame.init()

class Plan(object):
    def __init__(self):
        self.screen = pygame.display.set_mode((1920, 1080), pygame.FULLSCREEN, 32)
        # 游戏组件
        self.background = pygame.image.load(background).convert()
        self.my_plan_picture = pygame.image.load(my_plan_picture).convert_alpha()
        self.enemy_picture = pygame.image.load(enemy_picture).convert_alpha()
        self.my_bullet_picture = pygame.image.load(my_bullet_picture).convert_alpha()
        self.enemy_bullet_picture = pygame.image.load(enemy_bullet_picture).convert_alpha()
        self.small_plan = pygame.transform.scale(self.my_plan_picture, (50, 35))
        self.boom_picture = pygame.image.load(boom_picture).convert_alpha()
        self.boss_picture = pygame.image.load(boss_picture).convert_alpha()
        self.fire_picture = pygame.image.load(fire_picture).convert_alpha()
        self.not_defeat_picture = pygame.image.load(plan_not_defeat).convert_alpha()
        self.box_picture = pygame.image.load(box).convert_alpha()
        self.missile_picture = pygame.image.load(missile).convert_alpha()
        self.lock_picture = pygame.image.load(lock).convert_alpha()
        pygame.mixer_music.load(music)
        pygame.mixer_music.set_volume(0.2)
        pygame.mixer_music.play(50)
        # 时间标志
        # self.clock = pygame.time.Clock()
        self.time_record = 0
        # 存在的各种子弹数组
        self.my_bullets = []
        self.enemy_bullets = []
        self.missile_list = [[], []]
        # 本机子弹速度和数量
        self.my_bullet_speed = 20
        self.my_bullet_number = 1
        # 能量
        self.my_power = 1000
        self.sub_my_power = 0
        # 存在的敌机
        self.live_enemy = []
        # 正在爆炸的坐标
        self.booming_pos = []
        # 剩余生命
        self.my_life = 3
        # 初始化本机且不无敌
        self.my_plan_pos = [900, 500]
        self.now_plan_picture = self.my_plan_picture
        self.is_not_defeat = 0
        # 初始化导弹数为0
        self.missile_number = 0
        # 初始化字体
        self.my_font = pygame.font.SysFont('kaiti', 22, True, True)
        # 初始化得分
        self.my_count = 0
        # 道具
        self.box_list = []
        self.have_box = 0
        self.fire_time = 0
        # 初始化boss坐标，并且无boss
        self.have_boss = 0
        self.boss_pos = [800, -250]
        self.boss_do_shut = 0
        self.boss_life = 350
        # boss左右移动方向
        self.boss_toward = -1
        # 难度值
        self.hard = 0

    # 移动本机
    def move_my_plan(self):
        my_plan_move = pygame.mouse.get_rel()
        # 超出边界则不移动
        if 0 < self.my_plan_pos[0]+self.my_plan_picture.get_width()/2+my_plan_move[0] < 1920:
            self.my_plan_pos[0] += my_plan_move[0]
        if 0 < self.my_plan_pos[1]+self.my_plan_picture.get_height()/2+my_plan_move[1] < 1080:
            self.my_plan_pos[1] += my_plan_move[1]
        self.screen.blit(self.now_plan_picture, self.my_plan_pos)

    # 创造本机子弹
    def create_my_bullet(self):
        # 间隔某段时间就添加子弹
        if self.time_record % self.my_bullet_speed == 0:
            if self.my_bullet_number == 1:
                self.my_bullets.append([self.my_plan_pos[0]+68, self.my_plan_pos[1]-13])
            elif self.my_bullet_number == 2:
                self.my_bullets.append([self.my_plan_pos[0]+53, self.my_plan_pos[1]-13])
                self.my_bullets.append([self.my_plan_pos[0]+83, self.my_plan_pos[1]-13])
        # 子弹轨迹
        for bullet in self.my_bullets:
            if bullet[1] <= 0:
                # 销毁超出范围的子弹
                self.my_bullets.remove(bullet)
            else:
                # 没超出范围则向上移动4像素
                bullet[1] -= 4
                self.screen.blit(self.my_bullet_picture, bullet)
        # 创造僚机子弹
        if self.fire_time > 0:
            self.screen.blit(self.fire_picture, [self.my_plan_pos[0] - 15, self.my_plan_pos[1] + 30])
            self.screen.blit(self.fire_picture, [self.my_plan_pos[0] + 130, self.my_plan_pos[1] + 30])
            if self.time_record % 20 == 0:
                self.my_bullets.append([self.my_plan_pos[0] - 8, self.my_plan_pos[1] + 30])
                self.my_bullets.append([self.my_plan_pos[0] + 140, self.my_plan_pos[1] + 30])
            self.fire_time -= 1
        # 如果场上没有导弹就创造一个导弹
        if self.missile_number > 0 and len(self.missile_list[0]) == 0:
            # 导弹起始点为当前本机坐标
            missile_pos = copy.deepcopy([self.my_plan_pos[0]+50, self.my_plan_pos[1]-50])
            self.missile_list[0] = missile_pos
            self.missile_number -= 1
        # 发射导弹
        if len(self.missile_list[0]) > 0:
            # 导弹打向敌机
            if len(self.live_enemy) > 0:
                enemy_pos = [self.live_enemy[0][0]-10, self.live_enemy[0][1]-20]
                vec = (Vec2d(enemy_pos) - Vec2d(self.missile_list[0])).normalized()
                self.missile_list[1] = vec
                # 改变导弹朝向
                angle = 270-vec.get_angle()
                toward = pygame.transform.rotate(self.missile_picture, angle)
                # 画出标记
                self.screen.blit(self.lock_picture, [enemy_pos[0]-10, enemy_pos[1]])
                self.screen.blit(toward, (self.missile_list[0]))
                self.missile_list[0][0] += self.missile_list[1][0] * 6
                self.missile_list[0][1] += self.missile_list[1][1] * 6

    # 创造多种道具效果
    def show_box(self):
        # 第一种，创造两个发射普通子弹的僚机
        if self.have_box == 1:
            self.fire_time = 1500
            self.have_box = 0
        # 第二种，清屏
        elif self.have_box == 2:
            self.enemy_bullets = []
            self.have_box = 0
        # 第三种，发射跟踪导弹
        elif self.have_box == 3:
            self.missile_number = 30
            self.have_box = 0
        # 第四种，无敌
        elif self.have_box == 4:
            self.is_not_defeat = 1600
            self.have_box = 0

    # 创造敌机
    def create_enemy(self):
        # 间隔某段时间就创建新的敌机
        if self.time_record % (250-self.hard*40) == 0:
            x = random.randint(0, 1920)
            vec_x = random.randint(-1920, 1920)
            vec_y = random.randint(200, 500)
            vec_normal = Vec2d(vec_x, vec_y).normalized()
            self.live_enemy.append([x, 0, vec_normal, [vec_x, vec_y]])
        # 移动敌机
        for enemy_pos in self.live_enemy:
            # 销毁超出范围的敌机并扣一分
            if enemy_pos[1] >= 1080:
                self.live_enemy.remove(enemy_pos)
                if self.my_count > 0:
                    self.my_count -= 1
            # 改变碰壁敌机的移动方向
            elif enemy_pos[0] < 10 or enemy_pos[0] > 1910:
                new_vec_x = 1000-enemy_pos[0]
                new_vec_y = random.randint(enemy_pos[3][1] + 200, enemy_pos[3][1] + 500)
                new_vec_normal = Vec2d(new_vec_x, new_vec_y).normalized()
                self.live_enemy[self.live_enemy.index(enemy_pos)][2] = new_vec_normal
                self.live_enemy[self.live_enemy.index(enemy_pos)][3] = [new_vec_x, new_vec_y]
        for enemy_pos in self.live_enemy:
            # 到达随机方向向量的y坐标附近就随机一个新的方向
            if enemy_pos[3][1]-30 < enemy_pos[1] < enemy_pos[3][1]+30:
                new_vec_x = random.randint(-1920, 1920)
                new_vec_y = random.randint(enemy_pos[3][1]+400, enemy_pos[3][1]+500)
                new_vec_normal = Vec2d(new_vec_x, new_vec_y).normalized()
                self.live_enemy[self.live_enemy.index(enemy_pos)][2] = new_vec_normal
                self.live_enemy[self.live_enemy.index(enemy_pos)][3] = [new_vec_x, new_vec_y]
            # 否则按单位向量移动敌机
            else:
                self.live_enemy[self.live_enemy.index(enemy_pos)][0] += self.live_enemy[self.live_enemy.index(enemy_pos)][2][0]
                self.live_enemy[self.live_enemy.index(enemy_pos)][1] += self.live_enemy[self.live_enemy.index(enemy_pos)][2][1]
        # 画出敌机
        for enemy_pos in self.live_enemy:
            # 按照飞机中心为标准
            self.screen.blit(self.enemy_picture, [enemy_pos[0]-self.enemy_picture.get_width()/2, enemy_pos[1]-self.enemy_picture.get_height()/2])

    # 创造敌机子弹
    def create_enemy_bullet(self):
        # 敌机随机概率发射朝向本机的子弹
        for enemy in self.live_enemy:
            if random.randint(0, 1600-300*self.hard) == 0:
                enemy_pos = [enemy[0]-20, enemy[1]+15]
                normal_vec = (Vec2d(self.my_plan_pos[0]+self.my_plan_picture.get_width()/4+20, self.my_plan_pos[1]+self.my_plan_picture.get_height()/4) - Vec2d(enemy_pos)).normalized()
                self.enemy_bullets.append([enemy_pos, normal_vec])
        # 画出子弹轨迹
        for bullet in self.enemy_bullets:
            if 0 < bullet[0][0] < 1920 and bullet[0][1] < 1080:
                bullet[0][0] += bullet[1][0]*2
                bullet[0][1] += bullet[1][1]*2
                self.screen.blit(self.enemy_bullet_picture, bullet[0])
            # 销毁超出范围的子弹
            else:
                self.enemy_bullets.remove(bullet)

    # boss发射子弹
    def boss_shut(self):
        do_shut = random.randint(1, 3)
        # 第一种方法,圆形
        if do_shut == 1:
            for x in range(21):
                angle = math.pi / 10
                copy_pos = copy.deepcopy([self.boss_pos[0] + 140, self.boss_pos[1] + 100])
                normal_vec = Vec2d(math.cos(x*angle), math.sin(x*angle)).normalized()
                self.enemy_bullets.append([copy_pos, normal_vec])
        # 第二种方法，螺旋
        elif do_shut == 2:
            for x in range(-10, 11):
                angle = math.pi / 10
                copy_pos = copy.deepcopy([self.boss_pos[0] + 140, self.boss_pos[1] + 100])
                normal_vec = Vec2d(math.cos(x * angle), math.sin(x * angle)).normalized()
                self.enemy_bullets.append([copy_pos, normal_vec])
                sleep(0.05)
        # 第三种方法，来回
        elif do_shut == 3:
            for x in range(-10, 11):
                angle = math.pi / 10
                copy_pos = copy.deepcopy([self.boss_pos[0] + 140, self.boss_pos[1] + 100])
                normal_vec = Vec2d(math.cos(x * angle), abs(math.sin(x * angle))).normalized()
                self.enemy_bullets.append([copy_pos, normal_vec])
                sleep(0.1)

    # 创造boss
    def create_boss(self):
        if self.my_count == 100 and self.have_boss == 0:
            self.have_boss = 1
        if self.have_boss == 1:
            # 登场
            if self.boss_pos[1] < 60:
                it_font = pygame.font.SysFont('heiti', 60, True)
                text = it_font.render('Boss Coming!', True, (random.randint(100, 205), self.time_record % 255, random.randint(100, 200)))
                self.screen.blit(text, (800, 500))
                self.boss_pos[1] += 0.3
                self.screen.blit(self.boss_picture, self.boss_pos)
            else:
                if self.time_record % (800-self.hard*100) == 0:
                    Thread(target=self.boss_shut).start()
                # 左右移动
                if self.boss_pos[0] < 0 or self.boss_pos[0] > 1600:
                    self.boss_toward = self.boss_toward - 2 * self.boss_toward
                self.boss_pos[0] += self.boss_toward / 2
                self.screen.blit(self.boss_picture, self.boss_pos)

    # 判断是否击中敌机
    def judge_damage_enemy(self):
        width = self.enemy_picture.get_width()
        height = self.enemy_picture.get_height()
        for enemy in self.live_enemy:
            for bullet_pos in self.my_bullets:
                # 敌机坐标
                enemy_pos = copy.deepcopy([enemy[0], enemy[1]])
                # 判断敌机是否在子弹周围
                if enemy_pos[0]-width/2 <= bullet_pos[0] <= enemy_pos[0]+width/2 and enemy_pos[1] <= bullet_pos[1] <= enemy_pos[1]+height:
                    # 删除击中敌机的子弹
                    self.my_bullets.remove(bullet_pos)
                    # 在没有道具的情况下有概率爆出道具
                    if random.randint(1, 15) == 5 and self.have_box == 0 and len(self.box_list) == 0:
                        self.box_list.append([enemy_pos[0]-30, enemy_pos[1]-70])
                    # 向爆炸列表中添加坐标并初始化爆炸时间为0
                    try:
                        self.live_enemy.remove(enemy)
                    except ValueError:
                        pass
                    self.booming_pos.append([[enemy_pos[0]-width/2, enemy_pos[1]-height/2], 0])
                    # 得分+1
                    self.my_count += 1
                # 判断导弹是否击中敌机
                if len(self.missile_list[0]) > 0:
                    if enemy_pos[0]-width/2 <= self.missile_list[0][0] <= enemy_pos[0]+width/2 and enemy_pos[1]-20 <= self.missile_list[0][1] <= enemy_pos[1]+20:
                        # 删除该导弹
                        self.missile_list = [[], []]
                        # 在没有道具的情况下有概率爆出道具
                        if random.randint(1, 15) == 5 and self.have_box == 0 and len(self.box_list) == 0:
                            self.box_list.append([enemy_pos[0]-30, enemy_pos[1]-70])
                        # 向爆炸列表中添加坐标并初始化爆炸时间为0
                        try:
                            self.live_enemy.remove(enemy)
                        except ValueError:
                            pass
                        self.booming_pos.append([[enemy_pos[0]-width/2, enemy_pos[1]-height/2], 0])
                        # 得分+1
                        self.my_count += 1
        # 判断是否击中boss
        if self.have_boss == 1:
            for bullet in self.my_bullets:
                if self.boss_pos[0] < bullet[0] < self.boss_pos[0]+280 and self.boss_pos[1] < bullet[1] < self.boss_pos[1]+100:
                    self.booming_pos.append([bullet, 0])
                    self.my_bullets.remove(bullet)
                    # boss血量-1
                    self.boss_life -= 1
                    self.my_count += 1

    # 判断是否击中本机
    def judge_damage_me(self):
        width = self.enemy_picture.get_width()
        height = self.enemy_picture.get_height()
        for bullet in self.enemy_bullets:
            if self.my_plan_pos[0]+20 < bullet[0][0] < self.my_plan_pos[0]+80 and self.my_plan_pos[1] < bullet[0][1] < self.my_plan_pos[1]+80:
                # 删除该子弹并添加爆炸
                self.enemy_bullets.remove(bullet)
                self.booming_pos.append([self.my_plan_pos, 0])
                # 生命-1
                self.my_life -= 1
                # 设置无敌时间并重置坐标
                self.is_not_defeat = 400
                self.my_plan_pos = [900, 800]
        # 判断撞击
        for enemy in self.live_enemy:
            enemy_pos = copy.deepcopy([enemy[0] - width / 2, enemy[1] - height / 2])
            if enemy_pos[0]-10 < self.my_plan_pos[0]+self.my_plan_picture.get_width()/2 < enemy_pos[0]+60 and enemy_pos[1]-10 < self.my_plan_pos[1]+self.my_plan_picture.get_height()/2 < enemy_pos[1]+60:
                # 向爆炸列表中添加坐标并初始化爆炸时间为0
                try:
                    self.live_enemy.remove(enemy)
                except ValueError:
                    pass
                self.booming_pos.append([[enemy_pos[0], enemy_pos[1]], 0])
                self.booming_pos.append([self.my_plan_pos, 0])
                # 生命-1
                self.my_life -= 1
                # 设置无敌时间并重置坐标
                self.is_not_defeat = 400
                self.my_plan_pos = [900, 800]

    # 移动道具盒子
    def move_box(self):
        for box_pos in self.box_list:
            box_pos[1] += 1
            self.screen.blit(self.box_picture, box_pos)
            # 判断是否捡到
            if self.my_plan_pos[0]-50 < box_pos[0] < self.my_plan_pos[0]+70 and self.my_plan_pos[1]-60 < box_pos[1] < self.my_plan_pos[1]+20:
                self.box_list.remove(box_pos)
                # 随机一个道具效果
                self.have_box = random.randint(1, 4)

    # 使本机无敌
    def remove_not_defeat(self):
        if self.is_not_defeat > 0:
            self.now_plan_picture = self.not_defeat_picture
            self.is_not_defeat -= 1
        else:
            # 恢复普通状态
            self.now_plan_picture = self.my_plan_picture

    # 显示数据
    def draw_life_count(self):
        # 显示剩余生命
        for number in range(self.my_life):
            self.screen.blit(self.small_plan, [number*50, 10])
        # 显示得分
        string = '得分 %d' % self.my_count
        submit = self.my_font.render(string, True, (150, 200, 0))
        self.screen.blit(submit, (1800, 20))
        # 显示难度系数
        how_hard = self.my_font.render('难度 %d' % self.hard, True, (0, 50, 230))
        pygame.draw.line(self.screen, (255, 100, 0), (1850, 150), (1850, 150-self.hard*10), 10)
        pygame.draw.lines(self.screen, (0, 150, 150), True, [(1844, 100), (1856, 100), (1856, 110), (1844, 110), (1844, 120), (1856, 120), (1856, 130), (1844, 130), (1844, 140), (1856, 140), (1856, 150), (1844, 150)], 2)
        pygame.draw.line(self.screen, (0, 150, 150), (1856, 100), (1856, 150), 2)
        # 显示剩余能量
        self.screen.blit(how_hard, (1800, 50))
        how_hard = self.my_font.render('能量', True, (0, 230, 50))
        self.screen.blit(how_hard, (28, 215))
        pygame.draw.line(self.screen, (0, 50, 255), (50, 200), (50, 200-self.my_power/10), 14)
        pygame.draw.lines(self.screen, (255, 50, 0), True, [(43, 100), (58, 100), (58, 200), (43, 200)], 2)
        # 显示boss血条
        if self.boss_life > 0:
            pygame.draw.line(self.screen, (5, 250, 100), self.boss_pos, (self.boss_pos[0] + self.boss_life*1.1, self.boss_pos[1]), 13)

    # 爆炸特效
    def boom(self):
        # 依次爆炸
        for pos in self.booming_pos:
            if pos[1] <= 80:
                self.screen.blit(self.boom_picture, pos[0])
                # 爆炸延迟
                pos[1] += 1

    # 开始主循环
    def began(self):
        over = 0
        while 1:
            # 隐藏鼠标
            pygame.mouse.set_visible(False)
            # 时间标志
            self.time_record += 1
            # time_pass = self.clock.tick()
            # pass_second = self.time_pass/1000.0
            # 判断退出
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.display.quit()
                    exit()
                elif event.type == KEYDOWN:
                    keys_press = pygame.key.get_pressed()
                    # alt+f4退出
                    if keys_press[K_LALT] and keys_press[K_F4]:
                        pygame.display.quit()
                        exit()
                    # 调节难度
                    elif keys_press[K_LCTRL]:
                        if self.hard != 5:
                            self.hard += 1
                        else:
                            self.hard = 0
                # 使用能量
                elif event.type == MOUSEBUTTONDOWN and self.my_power > 0:
                        self.sub_my_power = 1
                elif event.type == MOUSEBUTTONUP:
                    self.my_bullet_speed = 20
                    self.my_bullet_number = 1
                    self.sub_my_power = 0
            # 消耗能量
            if self.sub_my_power == 1 and self.my_power > 0:
                self.my_bullet_speed = 10
                self.my_bullet_number = 2
                self.my_power -= 1.9
            else:
                self.my_bullet_speed = 20
                self.my_bullet_number = 1
            # 恢复能量
            if self.my_power < 1000:
                self.my_power += 0.4
            self.screen.blit(self.background, (0, 0))
            self.remove_not_defeat()
            if self.boss_life > 0:
                self.create_boss()
            else:
                self.have_boss = 0
            self.move_my_plan()
            self.create_enemy()
            self.create_my_bullet()
            self.create_enemy_bullet()
            self.judge_damage_enemy()
            # 无敌状态
            if self.is_not_defeat == 0:
                self.judge_damage_me()
            self.move_box()
            self.show_box()
            self.boom()
            self.draw_life_count()
            # 结束游戏
            if self.my_life < 0:
                over += 1
            if over == 1:
                font = pygame.font.SysFont('kaiti', 50, True)
                text = font.render('Game Over!', True, (255, 20, 50))
                self.screen.blit(text, (800, 400))
                text = font.render('最终得分 %d' % self.my_count, True, (255, 20, 50))
                self.screen.blit(text, (780, 500))
                pygame.display.update()
            if self.my_life >= 0:
                pygame.display.update()

plane = Plan()
plane.began()


import pygame as pg
import random
import math
import params

class Block(pg.sprite.Sprite):
    def __init__(self, speed):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface([40, 20])
        self.image.fill(pg.Color('black'))

        self.rect = self.image.get_rect()
        self.width = 40
        self.height = 20
        self.pos = [50,50]
        self.speed = speed

    def reset_pos(self):
        self.rect.y = random.randrange(-100, -10)
        self.rect.x = random.randrange(params.screen_width)

    def update(self):
        self.pos[1] += self.speed
        self.rect.x = int(self.pos[0])
        self.rect.y = int(self.pos[1])
        if self.rect.y > params.screen_height:
            self.reset_pos()

class Player(pg.sprite.Sprite):
    def __init__(self):
        self.width = 100
        self.height = 20
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface([self.width, self.height])
        #self.image = pg.image.load("player.png").convert()
        #self.image.set_colorkey(pg.Color('white'))
        self.image.fill(pg.Color('red'))

        self.rect = self.image.get_rect()

    def update(self):
        pos = pg.mouse.get_pos()
        self.rect.x = pos[0] - self.width / 2

class Bullet(pg.sprite.Sprite):
    def __init__(self):
        self.width = 4
        self.height = 10
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface([self.width,self.height])
        self.image.fill(pg.Color('red'))
        self.rect = self.image.get_rect()

    def update(self):
        self.rect.y -= 6

class Ball(pg.sprite.Sprite):
    def __init__(self):

        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface([10,10])
        self.image = pg.image.load('ball.png').convert()
        self.image.set_colorkey(pg.Color('black'))

        self.rect = self.image.get_rect()
        self.rect.x = 50
        self.rect.y = 50
        self.angle = 180
        self.speed = 2.0
        self.rad = 5
        self.pos = [50.0,50.0]
        self.acc = 0.001

    def update(self):
        self.pos[0] += math.sin(self.angle * math.pi / 180.0) * self.speed
        self.pos[1] -= math.cos(self.angle * math.pi / 180.0) * self.speed
        self.rect.x = int(self.pos[0])
        self.rect.y = int(self.pos[1])
        self.speed += self.acc


''' Ketika fotonya ditampilin
ada dua pilihan,
mencet escape lalu keluar aja
atau mencet save yang akan mensave si gambarnya'''

import cv2
img = cv2.imread('D:/A LEARN/Image Processing/Program Youtube/Gambar/lena.jpg', 0)
cv2.imshow('Gambar Grayscale', img)
print ('Press ESC to Out\nOr \nPress S to save the picture')

k = cv2.waitKey() & 0xFF

if k == 27:
    cv2.destroyAllWindows()

elif k == ord('s'):
    cv2.imwrite('D:/A LEARN/Image Processing/Program Youtube/Gambar/lena_grayscale.PNG', img)
    cv2.destroyAllWindows()


import pygame
from game_data import *
from sprite import SpriteSheet
from game_data import *

class Enemy(pygame.sprite.Sprite):
    def __init__(self, pos, size = tile_size, type = "ball", change_x = 0, change_y = 0, period = 1):
        super().__init__()
        self.frameIndex = 0
        self.animationSpeed = 0.15
        self.type = type
        self.pos = pos
        self.size = size
        self.animations = []

        self.period = period
        self.change_x = change_x
        self.change_y = change_y
        self.frames = 0

        self.setupEnemy()

    def setupEnemy(self):
        if self.type == "ball":
            self.image = pygame.image.load('./midia/ball.png').convert_alpha()
            self.image = pygame.transform.scale(self.image, (self.size, self.size))

            self.rect = self.image.get_rect(topleft = self.pos)
            self.collideRect = pygame.Rect(self.rect.x + 13, self.rect.y + 17, self.rect.width - 22, self.rect.height - 30)

        if self.type == "saw":
            enemySheet = SpriteSheet("./midia/saw38x38.png")

            for num in range(8):
                self.animations.append(enemySheet.get_image(num* 38, 0, 38, 38))

            self.image = self.animations[0]
            self.rect = self.image.get_rect(topleft = self.pos)
            self.collideRect = pygame.Rect(self.rect.x + 12, self.rect.y + 11, self.rect.width - 22, self.rect.height - 22)

    def animate(self):
        if len(self.animations) > 0:
            #loop over index
            self.frameIndex += self.animationSpeed

            if self.frameIndex >= len(self.animations):
                self.frameIndex = 0

            self.image = self.animations[int(self.frameIndex)]
            self.image = pygame.transform.scale(self.image, (self.size, self.size)).convert_alpha()

    def move(self):
        self.frames += 1
        if self.frames % int(self.period*FPS) == 0:
            if self.type == "saw":
                self.change_x *= -1
                self.change_y *= -1
        self.rect.x += self.change_x
        self.rect.y += self.change_y
        self.collideRect.x += self.change_x
        self.collideRect.y += self.change_y

    def update(self, dx):
        self.animate()
        self.move()
        self.rect.x += dx
        self.collideRect.x += dx


class Solution(object):
    def minSubArrayLen(self, s, nums):
        """
        :type s: int
        :type nums: List[int]
        :rtype: int
        """
        start = 0
        end = 0
        sum = 0
        min = float("inf")
        """
        Strategy:
            Keep two pointers start and end to track the subarray.
            Keep moving forward and update the min after each pointer update.
        """
        while (end < len(nums)):
            # increment end while sum is less that target.
            while (sum < s and end < len(nums)):
                sum += nums[end]
                end += 1
            # increment start while sum is greater than equal to the target.
            while (sum >= s and start < end):
                sum -= nums[start]
                start += 1
            # pointers point to min subarray until this end; update min answer length.
            if (end - start + 1 < min):
                min = end - start + 1
            # take care of boundary condition when sum == target
            if (sum == s):
                sum -= nums[start]
                start += 1

        # if no such subarray found, return 0
        if (min > len(nums)):
            min = 0

        return min


# We use loops to repeat some set of instructions
# While Loops are used to repeat until some condition is met, that is, we don't know up from how many repeats are needed

# Initialize loop variable
x = 0
# Condition to check
while (x < 10):
    # Indented code is what gets repeated
    print(x)
    # Last indented line is where we change the loop variable
    x = x + 3

# Doesn't get printed if not indented
print ("Code goes here when the loop ends.")

# Important: If we forget to include the last line, which changes our loop variable, we have an infinite loop. The loop will never end and our program will probably not function how we like.
# Condition (Inside th parentheses after the while command word) must be something that can evaluate to True or False

# When comparing in our while loop conditions, we use the same set of opertators as we use for if commands: <, >, <=, >=, ==, !=

#  Example 1
# Wrote a while loop the prints the numbers starting at 15, ending at 0 (inclusive), ant counts down by 3.

n = 15
while n >= 0:
    print(n)
    n = n - 3

# What happens if we move the last statement to be the first inside the loop?

n = 15
while n >= 0:
    n = n - 3
    print(n)

# Answer: All of the output is shifted. We will now start at 12 and end at -3, neither of which is correct for this problem

# Write a program that prints your name some number of times. Start counting at 1. After you print your name, decide if the current count is even or odd. If even, add 3 to your count. If odd, add 1 to your count. Stop when the count is greater than 100.

count = 1

while count <= 100:
    print("Ananya", count)
if count % 2 == 0:
    count = count + 3
else:
    count = count + 1

# Two special while loops uses are Diagnostic while loop and a Sentinel while loop.

# Diagnostic while loop is used to check for a bad user input
# Diagnostic loops check for failure

# Ask the user to input a positive number

number = int(input("Please enter a positive number: "))
# Checking for bad data
while number <= 0:
    print("Sorry, incorrect value.")
    number = int(input("Please enter a positive number: "))

# Write a Diagnostic Loop that asks the user to input a number that is less than 100.

number = int(input("Please enter a number that is less than 100: "))
while number >= 100:
    print("Sorry, incorrect value. Again, enter a number less than 100.")
    number = int(input("Please enter a number that is less than 100: "))

# Sentinel while loops allow the user to easily restart a program from the beginning

again = "Y"
while again == "Y":
    print("This is where your program does what it does!")
    # Note that your whole program goes within this while loop
    again = input("Would you like to run this program again? (Y/N): ")
print ("End of program. Thanks!")

# Write a while loop that adds all of the numbers between 1 and 1000 (inclusive)

add = 1
all = 0
while add <= 1000:
    all = all + add
    add = add + 1
print("Total: " + all)


#!/usr/bin/env python3
"""
Base Model Class of Models Module
"""

import json
from application import models
from uuid import uuid4, UUID
from datetime import datetime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Float, DateTime

Base = declarative_base()

class BaseModel:
    """
    The base model for our database models
    """

    id = Column(String(60), nullable=False, primary_key=True)
    created_at = Column(DateTime, nullable=False,
                        default=datetime.utcnow())
    updated_at = Column(DateTime, nullable=False,
                        default=datetime.utcnow())

    def __init__(self, *args, **kwargs):
        """
        initialize new BaseModel Class
        """
        if kwargs:
            self.__set_attributes(kwargs)
        else:
            self.id = str(uuid4())
            self.created_at = datetime.utcnow()

    def __set_attributes(self, attr_dict):
        """
        private: converts attr_dict values to python class attributes
        """
        if 'id' not in attr_dict:
            attr_dict['id'] = str(uuid4())
        if 'created_at' not in attr_dict:
            attr_dict['created_at'] = datetime.utcnow()
        elif not isinstance(attr_dict['created_at'], datetime):
            attr_dict['created_at'] = datetime.strptime(
                attr_dict['created_at'], "%Y-%m-%d %H:%M:%S.%f"
            )
        if 'updated_at' not in attr_dict:
            attr_dict['updated_at'] = datetime.utcnow()
        elif not isinstance(attr_dict['updated_at'], datetime):
            attr_dict['updated_at'] = datetime.strptime(
                attr_dict['updated_at'], "%Y-%m-%d %H:%M:%S.%f"
            )
        for attr, val in attr_dict.items():
            setattr(self, attr, val)

    @staticmethod
    def __is_serializable(obj_v):
        """
        private: checks if object is serializable
        """
        try:
            obj_to_str = json.dumps(obj_v)
            return obj_to_str is not None and isinstance(obj_to_str, str)
        except:
            return False

    def bm_update(self, attr_dict=None):
        """
        updates the basemodel and sets updated attributes
        """
        ignore = [
            'id', 'created_at', 'updated_at', 'user_id'
        ]
        if attr_dict:
            updated_dict = {
                k: v for k, v in attr_dict.items() if k not in ignore
            }
            for key, value in updated_dict.items():
                setattr(self, key, value)
            self.save()

    def save(self):
        """
        updates attribute updated_at to current time and saves class to database
        """
        self.updated_at = datetime.utcnow()
        models.database.new(self)
        models.database.save()

    def to_json(self, saving_file_storage=False):
        """
        Creates dictionary of class with sqlalchemy instance state removed
        :param saving_file_storage:
        :return:
        The dictionary of our class with relevant values
        """
        obj_class = self.__class__.__name__
        bm_dict = {
            k: v if self.__is_serializable(v) else str(v)
            for k, v in self.__dict__.items()
        }
        bm_dict.pop('_sa_instance_state', None)
        bm_dict.update({
            '__class__': obj_class
            })
        if not saving_file_storage and obj_class == 'User':
            bm_dict.pop('password', None)
        return bm_dict

    def __str__(self):
        """
        str magic method
        :return:
        formatted string representation of class
        """
        class_name = type(self).__name__
        return '[{}] ({}) {}'.format(class_name, self.id, self.__dict__)

    def delete(self):
        """
        deletes instance from storage
        """
        models.database.delete(self)


# l'épicerie est elle ouverte ?
# fonction avec en entrée une variable par défaut aléatoire pourvant etre forcée a une valeur fixe

# *********************************
# import de la bibliotheque numpy pour l'aléatoire a soortir de la fonction dans un deuxieme temps
from numpy.random import randint

def fonc_ouverture (heure_cour = randint (0,24),minute_cour = randint (0,60)):

# Affichage de l'heure choisie ou tirée au sort
    print ("Il est actuellement ",heure_cour," heure et ",minute_cour,"minutes")

# Définition des heures d'ouverture
    horaires = (8,12,14,18)
# convertion heure en minutes pour faciliter les tests
    hm_cour = (heure_cour*60+minute_cour)

# Affichage des horaires d'ouverture
    print ("MATIN :","\n ouverture : ",horaires[0],"\n fermeture : ",horaires[1])
    print ("APRES-MIDI :","\n ouverture : ",horaires[2],"\n fermeture : ",horaires[3])

# test si l'épicerie ouverte
    if (((hm_cour) >= (horaires[0]*60)) and ((hm_cour) <= (horaires[1]*60))
    or ((hm_cour) >= horaires[2]*60) and ((hm_cour) <= horaires[3]*60)):
        return True
    else:
        return False


import random
from typing import Optional

from flamapy.metamodels.configuration_metamodel.models.configuration import Configuration
from flamapy.core.operations import Sampling

from flamapy.metamodels.bdd_metamodel.models import BDDModel
from flamapy.metamodels.bdd_metamodel.operations import BDDProductsNumber

class BDDSampling(Sampling):
    """Uniform Random Sampling (URS) using a Binary Decision Diagram (BDD).

    This is an adaptation of
    [Heradio et al. 2021.
    Uniform and Scalable Sampling of Highly Configurable Systems.
    Empirical Software Engineering]
    which relies on counting-based sampling inspired in the original Knuth algorithm.

    This implementation supports samples with and without replacement,
    as well as samples from a given partial configuration.
    """

    def __init__(self, size: int, with_replacement: bool = False,
                 partial_configuration: Optional[Configuration] = None) -> None:
        self.result: list[Configuration] = []
        self.bdd_model = None
        self.size = size
        self.with_replacement = with_replacement
        self.partial_configuration = partial_configuration

    def execute(self, model: BDDModel) -> 'BDDSampling':
        self.bdd_model = model
        self.result = sample(self.bdd_model, self.size, self.with_replacement,
                             self.partial_configuration)
        return self

    def get_result(self) -> list[Configuration]:
        return self.result

    def sample(self, size: int, with_replacement: bool = False,
               partial_configuration: Optional[Configuration] = None) -> list[Configuration]:
        return sample(self.bdd_model, size, with_replacement, partial_configuration)

def sample(bdd_model: BDDModel, size: int, with_replacement: bool = False,
           partial_configuration: Optional[Configuration] = None) -> list[Configuration]:
    nof_configs = BDDProductsNumber(partial_configuration).execute(bdd_model).get_result()
    if size < 0 or (size > nof_configs and not with_replacement):
        raise ValueError('Sample larger than population or is negative.')

    configurations = []
    for _ in range(size):
        config = random_configuration(bdd_model, partial_configuration)
        configurations.append(config)

    if not with_replacement:
        set_configurations = set(configurations)
        while len(set_configurations) < size:
            config = random_configuration(bdd_model, partial_configuration)
            set_configurations.add(config)

    return list(set_configurations)

def random_configuration(bdd_model: BDDModel,
                         p_config: Optional[Configuration] = None) -> Configuration:
    # Initialize the configurations and values for BDD nodes with already known features
    values = {} if p_config is None else dict(p_config.elements.items())

    # Set the BDD nodes with the already known features values
    u_func = bdd_model.bdd.let(values, bdd_model.root)

    care_vars = set(bdd_model.variables) - values.keys()
    n_vars = len(care_vars)
    for feature in care_vars:
        # Number of configurations with the feature selected
        v_sel = bdd_model.bdd.let({feature: True}, u_func)
        nof_configs_var_selected = bdd_model.bdd.count(v_sel, nvars=n_vars - 1)
        # Number of configurations with the feature unselected
        v_unsel = bdd_model.bdd.let({feature: False}, u_func)
        nof_configs_var_unselected = bdd_model.bdd.count(v_unsel, nvars=n_vars - 1)

        # Randomly select or not the feature
        selected = random.choices([True, False],
                                  [nof_configs_var_selected, nof_configs_var_unselected],
                                  k=1)[0]

        # Update configuration and BDD node for the new feature
        values[feature] = selected
        u_func = bdd_model.bdd.let({feature: selected}, u_func)

        n_vars -= 1
    return Configuration(values)


from typing import List
import json
from GraphAlgoInterface import GraphAlgoInterface
from DiGraph import DiGraph, NodeData
from src import GraphInterface
import matplotlib.pyplot as plot_avi
import random
import math
from queue import PriorityQueue
from typing import Dict

class GraphAlgo(GraphAlgoInterface):

    def __init__(self,g:DiGraph=DiGraph()):
        self.graph = g

    def get_graph(self) -> GraphInterface:
        return self.graph

    def load_from_json(self, file_name: str) -> bool:
        try:
            with open(file_name,'r') as f:
                json_file = json.load(f)

            self.graph = DiGraph()
            #{"id": 0}
            #{"pos": "35.20319591121872,32.10318254621849,0.0","id": 1}
            for x in json_file.get('Nodes'):
               if x.get('pos') is None:
                   self.graph.add_node(x.get('id'))
               else:
                   li=x.get('pos').split(",")
                   pos = tuple(map(float,li))
                   self.graph.add_node(x.get('id') , pos)

            # {"src":0,"w":1.4620268165085584,"dest":10}
            for x in json_file.get('Edges'):
                self.graph.add_edge(x.get('src'),x.get('dest'),x.get('w'))

            return True
        except FileNotFoundError:
            return False

    def save_to_json(self, file_name: str) -> bool:
        nodes = []
        # {"id": 0}
        # {"pos": "35.20319591121872,32.10318254621849,0.0","id": 1}
        for x in self.graph.get_all_v().values():
            node:NodeData= x
            if node.pos is None:
                nodes.append({"id": node.getKey()})
            else:
                str_pos = str(node.pos[0])+","+str(node.pos[1])+","+str(node.pos[2])
                nodes.append({"pos": str_pos,"id": node.getKey()})

        edges=[]
        for s in self.graph.get_all_v().keys():
            for d,value in self.graph.all_out_edges_of_node(s).items():
                edges.append({"src":s,"w":value,"dest":d})

        lists= {'Edges':edges,'Nodes':nodes}
        try:
            with open(file_name, 'w') as f:
                json.dump(lists,f)
            return True
        except FileNotFoundError:
            return False

    def shortest_path(self, id1: int, id2: int) -> (float, list):
        if id1 not in self.graph.get_all_v() or id2 not in self.graph.get_all_v():
            return math.inf,[]               # in case that we dont have the nodes in the list
        if id1 is id2 :                      # in case that id1 = id2
            return 0,[id1]

        return self.Dijkstra(id1, id2)

    def connected_component(self, id1: int) -> list:
        # in this two function we will use in DFS algorithm and we will sava the results from the end to the beginning,
        # we will make transpose to the graph and we make DFS again and all the sons that we got in the
        # algorithm (whit the recursion ) will be scc.
        # Complications -  O( v + |E|)

        scc=[]
        on_Scc:Dict[int,bool]=dict()
        low: Dict[int, int] = dict()
        ids: Dict[int, int] = dict()
        id = 0

        for node in self.graph.get_all_v().keys():
            low.update({node:0})
            ids.update({node: 0})
            on_Scc.update({node: False})

        recursion =[(id1,0)]
        while recursion:
            v,i=recursion[-1]
            del recursion[-1]
            if i==0:
                id+=1
                low.update({v:id})
                ids.update({v: id})
                scc.append(v)
                on_Scc.update({v:True})
            flag=False
            k=0
            for w in self.graph.all_out_edges_of_node(v).keys():
                if ids.get(w) == 0:
                    recursion.append((v,k+1))
                    recursion.append((w, 0))
                    flag=True
                    k+=1
                    break
                elif on_Scc.get(w):
                    k+=1
                    low.update({v:min(low.get(v),low.get(w))})
            if flag: continue
            if ids.get(v) == low.get(v):
                way=[]
                while scc:
                    node = scc.pop()
                    low.update({node:ids.get(v)})
                    on_Scc.update({node:False})
                    way.insert(0,node)
                    if node == v : break
            if recursion:
                w=v
                v,_=recursion[-1]
                low.update({v:min(low.get(v),low.get(w))})
        return way

    def connected_components(self) -> List[list]:
        scc = []
        on_Scc: Dict[int, bool] = dict()
        low: Dict[int, int] = dict()
        ids: Dict[int, int] = dict()
        id = 0

        way =[]
        for node in self.graph.get_all_v().keys():
            low.update({node: 0})
            ids.update({node: 0})
            on_Scc.update({node: False})
        for x in self.graph.get_all_v():
            if ids.get(x) == 0:
                id1=x
                recursion = [(id1, 0)]
                while recursion:
                    v, i = recursion[-1]
                    del recursion[-1]
                    if i == 0:
                        id += 1
                        low.update({v: id})
                        ids.update({v: id})
                        scc.append(v)
                        on_Scc.update({v: True})
                    flag = False
                    k = 0
                    for w in self.graph.all_out_edges_of_node(v).keys():
                        if ids.get(w) == 0:
                            recursion.append((v, k + 1))
                            recursion.append((w, 0))
                            flag = True
                            k += 1
                            break
                        elif on_Scc.get(w):
                            k += 1
                            low.update({v: min(low.get(v), low.get(w))})
                    if flag: continue
                    if ids.get(v) == low.get(v):
                        path = []
                        while scc:
                            node = scc.pop()
                            low.update({node: ids.get(v)})
                            on_Scc.update({node: False})
                            path.insert(0, node)
                            if node == v: break
                        way.insert(0,path)
                    if recursion:
                        w = v
                        v, _ = recursion[-1]
                        low.update({v: min(low.get(v), low.get(w))})

        return way

    def plot_graph(self) -> None:

        x_=[]
        y_=[]
        n_=[]
        for key,value in self.graph.get_all_v().items():
            node:NodeData = value
            if node.pos is None:
                node.pos= (random.uniform(35.18, 35.2),random.uniform(2.1, 32.2))
            x_.append(node.pos[0])
            y_.append(node.pos[1])
            n_.append(key)

        fig, ax = plot_avi.subplots()
        for p, txt in enumerate(n_):
            ax.annotate(n_[p], (x_[p], y_[p]))

        plot_avi.plot(x_,y_,"*",color = "black")

        for s in self.graph.get_all_v().keys():
            for d,value in self.graph.all_out_edges_of_node(s).items():
                node_s:NodeData=self.graph.get_all_v().get(s)
                node_d:NodeData = self.graph.get_all_v().get(d)

                plot_avi.arrow(node_s.pos[0], node_s.pos[1], (node_d.pos[0] - node_s.pos[0]),
                          (node_d.pos[1] - node_s.pos[1]), length_includes_head=True, width=0.0000003,
                          head_width=0.0002, color='blue')

        plot_avi.show()

    def Dijkstra (self, id1: int, id2: int) -> (float, list):
        # init all nodes
        for node in self.graph.get_all_v().values():
            node.tag=-1       # dont visit
            node.weight=math.inf     # default whight

        queue = PriorityQueue()
        src:NodeData = self.graph.get_all_v().get(id1)
        src.weight=0    # init the weight
        queue.put(src)

        while not queue.empty():
            node1:NodeData = queue.get()    # the first node in the queue
            #Dict[int,float]
            for key,weight_of_node in self.graph.all_out_edges_of_node(node1.getKey()).items():    # all the neighborhoods of node1
                node2:NodeData = self.graph.get_all_v().get(key)
                dest = node1.weight+weight_of_node
                if dest <node2.weight:
                    node2.weight=dest

                    node2.tag=node1.getKey()
                    queue.put(node2)

        dest: NodeData = self.graph.get_all_v().get(id2)
        if dest.weight is math.inf:     # for the case that id2 is not exist
            return math.inf,[]
        way=[]
        way.insert(0,dest.getKey())

        current = dest.tag
        while current != -1:
            way.insert(0, current)
            current = self.graph.get_all_v().get(current).tag

        return dest.weight,way


#!/usr/bin/python3
"""Function that creates an Object from a json file"""
import json

def load_from_json_file(filename):
    """Creates an object from a json file
    Args:
        filename (str): name of the json file
    Returns:
        Python Object
    """
    Object = None
    with open(filename, 'r', encoding='utf-8') as f:
        Object = json.load(f)
    return Object


"""Use canny edge detection to extract salient parts of the time series
"""
import logging
import numpy as np
from scipy.ndimage.filters import gaussian_filter1d
from scipy.ndimage import sobel

LOG = logging.getLogger("M.CannyEdge")

def detect_edge_scipy(data, sigma, lo=0.9, hi=0.99):
    """Apply canny edge detector from scipy image
    """
    from skimage import feature

    edge = np.empty_like(data)
    data = np.stack([data, data, data], axis=1)
    for row in range(data.shape[0]):
        _edge = feature.canny(
            data[row],
            sigma=sigma,
            low_threshold=lo,
            high_threshold=hi,
            use_quantiles=True,
        )
        edge[row] = _edge[1]
        del _edge
    return edge

def detect_edge(data, sigma, truncate, intermediate_out=None):
    """Apply gaussian filtering, sobel filtering, and threshold filtering
    """
    data = (
        _PipelinedArray(data, intermediate_out)
        .apply(
            lambda x: gaussian_filter1d(x, sigma, axis=1, truncate=truncate),
            label="Gaussian",
        )
        .apply(lambda x: sobel(x, axis=1), label="Sobel")
        # .apply(_non_maximum_suppression, label="Non-maximum Suppression")
        .apply(lambda x: _sigma_filter(x, 2), label="Filter by 2-sigma")
        .data
    )

    return data

def _sigma_filter(data, sigma):
    mean = np.mean(data, axis=1, keepdims=True)
    std = np.std(data, axis=1, keepdims=True)
    mask = np.abs(data - mean) > (sigma * std)
    return data * mask

def _non_maximum_suppression(array):
    larger_left = np.ones_like(array, dtype=np.bool)
    larger_right = np.ones_like(array, dtype=np.bool)
    less_left = np.ones_like(array, dtype=np.bool)
    less_right = np.ones_like(array, dtype=np.bool)

    larger_left[:, 1:] = array[:, 1:] > array[:, :-1]
    larger_right[:, :-1] = array[:, :-1] > array[:, 1:]
    less_left[:, 1:] = array[:, 1:] < array[:, :-1]
    less_right[:, :-1] = array[:, :-1] < array[:, 1:]

    maxima = larger_left & larger_right
    minima = less_left & less_right

    return array * (maxima | minima)

class _PipelinedArray(object):
    def __init__(self, original: np.ndarray, intermediate_out: dict = None):
        self.data = original
        self.intermediate_out = intermediate_out
        self._add_to_intermediate("orginial", original)

    def apply(self, func, label="Unamed"):
        """Applying a new function on the array
        """
        LOG.info("Pipelined Array applying funciton %s", label)
        self.data = func(self.data)
        self._add_to_intermediate(label, self.data)
        return self

    def _add_to_intermediate(self, label, data):
        if self.intermediate_out is not None:
            if label in self.intermediate_out:
                label = label + "+"
            self.intermediate_out[label] = np.copy(data)


# Pandas is used for data manipulation
import pandas as pd
# Read in data and display first 5 rows
train = pd.read_csv('C:/Users/TheUnlikelyMonk/Desktop/Analytics Vidhya/LTFS/newtraindata.csv')
train.head(5)
print('The shape of our features is:', train.shape)
test = pd.read_csv('C:/Users/TheUnlikelyMonk/Desktop/Analytics Vidhya/LTFS/newtestdata.csv')
test.shape

# One-hot encode the data using pandas get_dummies
features = pd.get_dummies(train)
# Display the first 5 rows of the last 12 columns
train.iloc[:,5:].head(5)

feature_list = list(train.columns)
print(feature_list)

# Use numpy to convert to arrays
import numpy as np
# Labels are the values we want to predict
labels = np.array(train['loan_default'])
# Remove the labels from the features
# axis 1 refers to the columns
features= train.drop('loan_default', axis = 1)
# Saving feature names for later use
feature_list = list(train.columns)
# Convert to numpy array
features = np.array(train)

train = train.drop(['Unnamed: 0'], axis=1)
test = test.drop(['Unnamed: 0'], axis=1)

x = train.drop(['loan_default'], axis=1)
y = train['loan_default'];

# Import the model we are using
from sklearn.ensemble import RandomForestRegressor
# Instantiate model with 1000 decision trees
rf = RandomForestRegressor(n_estimators = 1000, random_state = 42)
# Train the model on training data
rf.fit(x,y);

#import pickle
#filename = 'randomforest.sav'
#pickle.dump(rf, open(filename, 'wb'))

# Use the forest's predict method on the test data
predictions = rf.predict(test)
# Calculate the absolute errors
#errors = abs(predictions - test_labels)
# Print out the mean absolute error (mae)
#print('Mean Absolute Error:', round(np.mean(errors), 2), 'degrees.')
#Mean Absolute Error: 3.83 degrees.

print(predictions)
pred = []
for i in predictions:
    if i < 0.5:
        pred.append(0)
    else:
        pred.append(1)

fp = open("out.csv","w")
fp.write(repr(pred))


import numpy as np
from utils import draw_save_plane_with_points

if __name__ == "__main__":

    # load data, total 130 points inlcuding 100 inliers and 30 outliers
    noise_points = np.loadtxt("HM1_ransac_points.txt")
    size = len(noise_points[..., 0])
    #RANSAC
    # we recommend you to formulate the palnace function as:  A*x+B*y+C*z+D=0

    sample_time = 11  #more than 99.9% probability at least one hypothesis does not contain any outliers
    distance_threshold = 0.05

    # sample points group
    index = np.random.choice(size, sample_time * 3)
    sample = noise_points[index].reshape((sample_time, 3, 3))
    #x1=sample[-1,0,0] y1=sample[-1,0,1] z1=sample[-1,0,2]
    # estimate the plane with sampled points group
    # a,b,c,d
    ans = np.zeros((sample_time, 4))
    #a=(y2-y1)*(z3-z1)-(y3-y1)*(z2-z1)
    ans[...,
        0] = (sample[..., 1, 1] -
              sample[..., 0, 1]) * (sample[..., 2, 2] - sample[..., 0, 2]) - (
                  sample[..., 2, 1] - sample[..., 0, 1]) * (sample[..., 1, 2] -
                                                            sample[..., 0, 2])
    #b=(z2-z1)*(x3-x1)-(z3-z1)*(x2-x1)
    ans[...,
        1] = (sample[..., 1, 2] -
              sample[..., 0, 2]) * (sample[..., 2, 0] - sample[..., 0, 0]) - (
                  sample[..., 2, 2] - sample[..., 0, 2]) * (sample[..., 1, 0] -
                                                            sample[..., 0, 0])
    #c=(x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)
    ans[...,
        2] = (sample[..., 1, 0] -
              sample[..., 0, 0]) * (sample[..., 2, 1] - sample[..., 0, 1]) - (
                  sample[..., 2, 0] - sample[..., 0, 0]) * (sample[..., 1, 1] -
                                                            sample[..., 0, 1])
    #d=-a*x1-b*y1-c*z1
    ans[..., 3] = -(ans[..., 0] * sample[..., 0, 0]) - (
        ans[..., 1] * sample[..., 0, 1]) - (ans[..., 2] * sample[..., 0, 2])
    #evaluate inliers (with point-to-plance distance < distance_threshold)
    dis = ans[..., 0:3] @ (noise_points.T)
    dis = dis / np.tile(
        (np.sqrt(ans[..., 0]**2 + ans[..., 1]**2 + ans[..., 3]**2)).reshape(
            11, 1), size)
    threshold = np.sum(dis < distance_threshold, axis=1)
    is_max = np.argmax(threshold)
    # minimize the sum of squared perpendicular distances of all inliers with least-squared method
    pf = ans[is_max]
    print(pf)
    # draw the estimated plane with points and save the results
    # check the utils.py for more details
    # pf: [A,B,C,D] contains the parameters of palnace function  A*x+B*y+C*z+D=0

    draw_save_plane_with_points(pf, noise_points, "result/HM1_RANSAC_fig.png")
    np.savetxt("result/HM1_RANSAC_plane.txt", pf)


import pandas as pd
import numpy as np

import azure.functions as func

TEMPERATURE = "temperature"
HUMIDITY = "humidity"
TIMESTAMP = "timestamp"
VALUE = "value"

POOR_CONDITIONS = 0
TOLERABLE_CONDITIONS = 1
GOOD_CONDITIONS = 2

def main(req: func.HttpRequest) -> func.HttpResponse:

    try:
        # Convert request to json
        req_body = req.get_json()

        # If requst consists all of required keys,
        # convert it to series and process using process_environment
        # method.
        if TEMPERATURE in req_body and HUMIDITY in req_body:
            temperature = dict_to_series(req_body[TEMPERATURE])
            humidity = dict_to_series(req_body[HUMIDITY])

            kpi = process_environment(temperature, humidity)

    except ValueError as ex:
        return func.HttpResponse(status_code=401, body=str(ex))

    return func.HttpResponse(
        status_code=200, body=str({
            "Warunki srodowiskowe": kpi
        })
    )

def dict_to_series(post_request: dict) -> pd.Series:
    """
    Convert given dict input to pandas.Series collection.
    """
    df = pd.DataFrame(post_request)
    df[TIMESTAMP] = pd.to_datetime(df[TIMESTAMP])
    df = df.set_index(TIMESTAMP)
    series = df.squeeze('columns')
    return series

def process_environment(temperature: pd.Series, humidity: pd.Series) -> int:
    """
    Returns a status of environmental conditions based on given
    temperature and humidity.

    Args:
        temperature - pd.Series
        humidity - pd.Series

    Returns:
        int:
            0 - poor conditions
            1 - tolerable conditions
            2 - good conditions
    """
    mean_temperature = np.mean(temperature)
    mean_humidity = np.mean(humidity)

    if 20 <= mean_temperature < 50 or 15 <= mean_humidity < 40:
        return GOOD_CONDITIONS
    elif 0 <= mean_temperature < 20 or 50 <= mean_temperature < 70 \
        or 10 <= mean_humidity < 15 or 40 <= mean_humidity < 50:
        return TOLERABLE_CONDITIONS
    else:
        return POOR_CONDITIONS


def sortArrayByParity(A):
    i,j=0,len(A)-1
    while i<j:
        if A[i]%2!=0:
            A[i],A[j]=A[j],A[i]
            j-=1
        else:
            i+=1
    return A

a = [3,1,2,4]
print(sortArrayByParity(a))


import pyttsx3
from gtts import gTTS
import urllib3

engine = pyttsx3.init() # object creation

""" RATE"""
rate = engine.getProperty('rate')   # getting details of current speaking rate
print (rate)                        #printing current voice rate
engine.setProperty('rate', 125)     # setting up new voice rate

"""VOLUME"""
volume = engine.getProperty('volume')   #getting to know current volume level (min=0 and max=1)
print (volume)                          #printing current volume level
engine.setProperty('volume',1.0)    # setting up volume level  between 0 and 1

"""VOICE"""
voices = engine.getProperty('voices')       #getting details of current voice
#engine.setProperty('voice', voices[0].id)  #changing index, changes voices. o for male
engine.setProperty('voice', voices[1].id)   #changing index, changes voices. 1 for female

#engine.say("Hello World!")
#engine.say('My current speaking rate is ' + str(rate))

#engine.say("olá")
#engine.runAndWait()
#engine.stop()

def format(text):
    text = text.replace("\n", "")
    text = text.replace(" ", "")
    text = text[:10]
    text = "audio_" + text + ".wav"
    return text

text = ('''
    Sua ligação será transferida para um consultor de serviço. Para a sua segurança a ligação será gravada.
        ''')

tts = gTTS(text=text, lang='pt')
tts.save(format(text))
print("File saved!")


import re

def parse_memory(s: str) -> int:
    m = re.fullmatch(r"(\d+)(?:\s*([kMGTPEZY])B?)?", s)
    if not m:
        raise ValueError(s)
    x = int(m[1])
    if m[2] is not None:
        x <<= 10 * ("kMGTPEZY".index(m[2]) + 1)
    return x


from flask.sessions import SessionMixin, SessionInterface
import uuid
import json
from itsdangerous import Signer, BadSignature, want_bytes

class MySession(dict, SessionMixin):

    def __init__(self, initial=None, sessionId=None):
        self.initial = initial
        self.sessionId = sessionId
        super(MySession, self).__init__(initial or ())  #MySession'ı ürettiğim sınıfların initini çağırıyorum

    def __setitem__(self, key, value):
        super(MySession, self).__setitem__(key, value)

    def __getitem__(self, item):
        super(MySession, self).__getitem__(item)

    def __delitem__(self, key):
        super(MySession, self).__delitem__(key)

class MySessionInterface(SessionInterface):
    session_class = MySession  #Klasın adresini veriyoruz.
    salt = 'my-session'
    container = dict()

    def __init__(self):
        pass

    def open_session(self, app, request):                #oluşturduğumuz nesnenin bir örneğini döner. Session bilgilerinin döner(MySession)

        signedSessionId = request.cookies.get(app.config['SESSION_COOKIE_NAME']) #Config session ismini almamızı sağlar. Ototmatikman SesssionId'yi buluruz
        if not signedSessionId:                         #SessionId yoksa burada üretiliyor.
            sessionId = str(uuid.uuid4())
            return self.session_class(sessionId=sessionId)

        signer = Signer(app.secret_key, salt=self.salt, key_derivation='hmac')
        try:
            sessionId =signer.unsign(signedSessionId).decode()
        except BadSignature:
            sessionId = str(uuid.uuid4())
            return self.session_class(sessionId=sessionId)

        initialSessionvalueAsJson = self.container.get(sessionId)
        try:
            initialSessionvalue = json.load(initialSessionvalueAsJson)
        except:
            sessionId = str(uuid.uuid4())
            return self.session_class(sessionId=sessionId)

        return(self.session_class(initialSessionvalue, sessionId=sessionId))

    def save_session(self, app, session, response):  #Kaydetmeyi sağlar

        sessionAsJson = json.dumps(dict(session))      #session'ı jsaon'a çevirip kaydetmeye hazır hale getiriyoruz.

        self.container[session.sessionId] = sessionAsJson

        signer = Signer(app.secret_key, salt=self.salt, key_derivation='hmac')
        signedSessionId = signer.sign(want_bytes(session.sessionId))  #sessionId imzalanıyor

        response.set_cookie(app.config['SESSION_COOKIE_NAME'], signedSessionId)


# Author: Jochen Gast <jochen.gast@visinf.tu-darmstadt.de>

import functools
import random

import torch
from torch.nn import functional as tf

from contrib.cmap import ColorMap
from contrib.middlebury import FlowToColor
from utils import summary
from visualizers import factory
from visualizers.visualizer import Visualizer

def random_indices(k, n):
    indices = list(range(n))
    random.shuffle(indices)
    return sorted(indices[0:k])

class GoProVisualizer(Visualizer):
    def __init__(self,
                 args,
                 model_and_loss,
                 optimizer,
                 param_scheduler,
                 lr_scheduler,
                 train_loader,
                 validation_loader,
                 images_every_n_epochs=5,
                 keep_num_training_steps=30,
                 keep_num_validation_steps=30,
                 track_epochs=False):
        super().__init__()
        self.args = args
        self.global_train_step = 0
        self.optimizer = optimizer
        self.param_scheduler = param_scheduler
        self.lr_scheduler = lr_scheduler
        self.validation_loader = validation_loader
        self.training_loader = train_loader
        self.images_every_n_epochs = images_every_n_epochs
        self.keep_num_training_steps = keep_num_training_steps
        self.keep_num_validation_steps = keep_num_validation_steps
        self.flow2rgb = FlowToColor()
        self.err2rgb = ColorMap(cmap='jet')
        self.do_track_epochs = track_epochs
        self.model = model_and_loss.model
        self.epoch = None
        self.total_epochs = None
        self.prefix = None
        self.track_epoch = None
        self.random_step_indices = None

    def on_epoch_init(self, lr, train, epoch, total_epochs):
        self.epoch = epoch
        self.total_epochs = total_epochs
        self.prefix = 'train' if train else 'valid'
        self.random_step_indices = []

        if train:
            summary.scalar('train/lr', lr[0], global_step=epoch)

        # we track the first 2 epochs and then some others
        # self.track_epoch = False
        self.track_epoch = self.do_track_epochs and (epoch <= 2) or (epoch % self.images_every_n_epochs) == 0
        if self.track_epoch:
            if train:
                if self.keep_num_training_steps > 0:
                    self.random_step_indices = random_indices(
                        k=self.keep_num_training_steps,
                        n=len(self.training_loader))
            else:
                if self.keep_num_validation_steps > 0:
                    self.random_step_indices = random_indices(
                        k=self.keep_num_validation_steps,
                        n=len(self.validation_loader))

    @staticmethod
    def downsample(x, rscale=2):
        h, w = x.size()[2:4]
        h0, w0 = [s // rscale for s in [h, w]]
        return tf.interpolate(x, (h0, w0))

    def on_step_finished(self, example_dict, model_dict, loss_dict, train, step, total_steps):
        if train:
            self.global_train_step += 1
            for key, value in loss_dict.items():
                summary.scalar('train/%s' % key, value, global_step=self.global_train_step)

        def from_basename(name, in_basename):
            return "{}_{}/{}".format(in_basename, self.prefix, name)

        # ------------------------------------------------------------------------------
        # We also track some epochs completely on a subset of simple
        # ------------------------------------------------------------------------------
        if self.track_epoch:
            global_step = self.global_train_step if train else self.epoch
            if step in self.random_step_indices:
                batch_idx = 0
                basename = example_dict['basename'][batch_idx]
                basename = basename.replace('/', '_')
                make_name = functools.partial(from_basename, in_basename=basename)

                # visualize inputs
                input1 = example_dict['input1'][batch_idx:batch_idx + 1, ...]
                input2 = example_dict['input2'][batch_idx:batch_idx + 1, ...]
                input3 = example_dict['input3'][batch_idx:batch_idx + 1, ...]
                input4 = example_dict['input4'][batch_idx:batch_idx + 1, ...]
                input5 = example_dict['input5'][batch_idx:batch_idx + 1, ...]
                summary.images(make_name('input1'), input1, global_step=global_step)
                summary.images(make_name('input2'), input2, global_step=global_step)
                summary.images(make_name('input3'), input3, global_step=global_step)
                summary.images(make_name('input4'), input4, global_step=global_step)
                summary.images(make_name('input5'), input5, global_step=global_step)

                # visualize target
                target1 = example_dict['target1'][batch_idx:batch_idx + 1, ...]
                summary.images(make_name('gt'), target1, global_step=global_step)

                # visualize output
                output1 = model_dict['output1'][batch_idx:batch_idx + 1, ...]
                summary.images(make_name('output'), output1, global_step=global_step)

                # visualize error
                b, _, h, w = output1.size()
                error1 = torch.sum((output1 - target1) ** 2, dim=1, keepdim=True)
                error1 = self.err2rgb(error1)
                summary.images(make_name('error'), error1, global_step=global_step)

                # visualize concatenated summary image
                x1 = torch.cat((input3, target1), dim=3)
                x2 = torch.cat((error1.float() / 255, output1), dim=3)
                x = torch.cat((x1, x2), dim=2)
                summary.images(make_name('summary'), self.downsample(x), global_step=global_step)

                # visualize warped images
                if 'warped1' in model_dict.keys():
                    warped1 = model_dict['warped1'][batch_idx:batch_idx + 1, ...]
                    warped2 = model_dict['warped2'][batch_idx:batch_idx + 1, ...]
                    warped4 = model_dict['warped4'][batch_idx:batch_idx + 1, ...]
                    warped5 = model_dict['warped5'][batch_idx:batch_idx + 1, ...]
                    summary.images(make_name('warped1'), warped1, global_step=global_step)
                    summary.images(make_name('warped2'), warped2, global_step=global_step)
                    summary.images(make_name('warped4'), warped4, global_step=global_step)
                    summary.images(make_name('warped5'), warped5, global_step=global_step)

    def on_epoch_finished(self, avg_loss_dict, train, epoch, total_epochs):
        if not train:
            for key, value in avg_loss_dict.items():
                summary.scalar('valid/%s' % key, value, global_step=epoch)

factory.register('GoProVisualizer', GoProVisualizer)


# -*- coding: utf-8 -*-
# import csv

# if __name__ == '__main__':
#     # store reviews in CSV file
#    with open('input.csv', newline='') as csvfile:
#     spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='|')
#     for row in spamreader:
#         print(row)

# -*- coding: utf-8 -*-
# from googlemaps import GoogleMapsScraper
from termcolor import colored
import argparse
import csv
from multiprocessing import Pool, freeze_support

def do_the_job(file_url, debug):
   print(file_url, colored(debug, 'cyan'));
   return file_url

def callback(some):
    print(some, colored("deu bom"));

def error_callback(some):
    print(some, colored("deu ruim"));

def main():
    parser = argparse.ArgumentParser(description='Google Maps reviews scraper.')
    parser.set_defaults(place=False, debug=False, source=False)

    args = parser.parse_args()
    results = []
    with open("urls.txt", newline='') as csvfile:
        with Pool(processes=4) as pool:
            for row in csv.DictReader(csvfile, delimiter=',', quotechar='|'):
                url = row['url']
                result = pool.apply_async(do_the_job, (url, args), callback=callback, error_callback=error_callback)
                results.append(result)
            [result.wait() for result in results]
        # pool.apply_async(func=do_the_job, args=[], callback=callback, error_callback=error_callback)

if __name__=="__main__":
    freeze_support()
    main()


# Prepare ScanNet Data into the form we want

import os
import glob
import plyfile
import numpy as np
import multiprocessing as mp
import torch
import open3d as o3d
import argparse

def load_obj_with_normals(filepath):
    mesh = o3d.io.read_triangle_mesh(str(filepath))
    if not mesh.has_vertex_normals():
        mesh.compute_vertex_normals()
    coords = np.asarray(mesh.vertices)
    normals = np.asarray(mesh.vertex_normals)
    colors = np.asarray(mesh.vertex_colors)
    feats = np.hstack((colors, normals))

    return coords, feats

def newf(fn):
    fn2 = fn[:-3]+'labels.ply'
    coords, feats = load_obj_with_normals(fn)
    a = plyfile.PlyData().read(fn2)
    labels = remapper[np.array(a.elements[0]['label'])]
    torch.save((coords, feats, labels, fn.split('/')[-1]), fn[:-4]+'.pth')
    print(fn, fn2)

def newf_test(fn):
    coords, feats = load_obj_with_normals(fn)
    num_points = coords.shape[0]
    labels = np.zeros(num_points).astype(np.int32)
    torch.save((coords, feats, labels, fn.split('/')[-1]), fn[:-4] + '.pth')
    print(fn)

if __name__ == '__main__':
    # Map relevant classes to {0,1,...,19}, and ignored classes to -100
    parser = argparse.ArgumentParser(description="Prepare ScanNet Data")
    parser.add_argument("basepath", help="base path of the downloaded ScanNet dataset")
    parser.add_argument("split", help="The split that you want to parse (train/validation/test). For test, the labels are set to 0")
    args = parser.parse_args()
    data_path = args.basepath
    split = args.split
    if split != "test":
        scan_path = os.path.join(data_path, "scans")
    else:
        scan_path = os.path.join(data_path, "scans_test")

    with open("scannetv2_" + split + ".txt") as f:
        scans_name = [x.strip() for x in f.readlines()]

    print(len(scans_name))

    for scan_name in scans_name:
        print("copy scene: ", scan_name)
        ply_path = os.path.join(scan_path, scan_name, scan_name + "_vh_clean_2.ply")
        label_path = os.path.join(scan_path, scan_name, scan_name + "_vh_clean_2.labels.ply")
        segsjson_path = os.path.join(scan_path, scan_name, scan_name + "_vh_clean_2.0.010000.segs.json")
        aggjson_path = os.path.join(scan_path, scan_name, scan_name + ".aggregation.json")

        os.system('cp %s %s' % (ply_path, split))

        if split != "test":
            os.system('cp %s %s' % (label_path, split))
            os.system('cp %s %s' % (segsjson_path, split))
            os.system('cp %s %s' % (aggjson_path, split))

    remapper = np.ones(150)*(-100)
    for i, x in enumerate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36, 39]):
        remapper[x] = i

    files = sorted(glob.glob(os.path.join(data_path, '*/*_vh_clean_2.ply')))
    if split != 'test':
        files2 = sorted(glob.glob(os.path.join(data_path, '*/*_vh_clean_2.labels.ply')))
        assert len(files) == len(files2)
    p = mp.Pool(processes=mp.cpu_count())
    if split != 'test':
        p.map(newf, files)
    else:
        p.map(newf_test, files)
    p.close()
    p.join()


numbers = []
d = dict()
for _ in range(10):
    numbers.append(int(input()))
for number in numbers:
    if d.get(number):
        d[number] += 1
    else:
        d[number] = 1
print(int(sum(numbers)/10))
print(sorted(list(d.items()), key=lambda v: -v[1])[0][0])


#!/usr/bin/env python

import inspect
import os

import utils

# import git

################################################################################
## PATH
################################################################################
def mk_spath(sfname, makedirs=False):

    __file__ = inspect.stack()[1].filename
    if "ipython" in __file__:  # for ipython
        __file__ = "/tmp/fake.py"

    ## spath
    fpath = __file__
    fdir, fname, _ = split_fpath(fpath)
    sdir = fdir + fname + "/"
    spath = sdir + sfname

    if makedirs:
        os.makedirs(utils.general.split_fpath(spath)[0], exist_ok=True)

    return spath

def find_the_git_root_dir():
    repo = git.Repo(".", search_parent_directories=True)
    return repo.working_tree_dir

def split_fpath(fpath):
    """Split a file path to (1) the directory path, (2) the file name, and (3) the file extention
    Example:
        dirname, fname, ext = split_fpath('../data/01/day1/split_octave/2kHz_mat/tt8-2.mat')
        print(dirname) # '../data/01/day1/split_octave/2kHz_mat/'
        print(fname) # 'tt8-2'
        print(ext) # '.mat'
    """
    dirname = os.path.dirname(fpath) + "/"
    base = os.path.basename(fpath)
    fname, ext = os.path.splitext(base)
    return dirname, fname, ext