import pygame
import random
import clown

# Initialize pygame
pygame.init()

# Set display surface
WINDOW_WIDTH = 1750
WINDOW_HEIGHT = 700
display_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Catch the Clown")

# Set FPS and clock
FPS = 60
clock = pygame.time.Clock()

# Set game values
PLAYER_STARTING_LIVES = 5
score = 0
player_lives = PLAYER_STARTING_LIVES

# Set colors
BLUE = (26, 130, 167)
PURPLE = (109, 61, 146)
RED = (229, 56, 73)

# Set font
font = pygame.font.Font("AlloyInk-nRLyO.ttf", 32)
end_font = pygame.font.Font("AlloyInk-nRLyO.ttf", 64)

# Set text
title_text = font.render("Catch the Clown", True, BLUE)
title_rect = title_text.get_rect()
title_rect.topleft = (50, 10)

score_text = font.render("Score: " + str(score), True, RED)
score_rect = score_text.get_rect()
score_rect.topright = ((WINDOW_WIDTH - 50, 10))

lives_text = font.render("Lives: " + str(player_lives), True, RED)
lives_rect = lives_text.get_rect()
lives_rect.topright = ((WINDOW_WIDTH - 50, 50))

game_over_text = end_font.render("Game Over", True, RED, BLUE)
game_over_rect = game_over_text.get_rect()
game_over_rect.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)

continue_text = end_font.render("Click Anywhere To Play Again", True, RED, BLUE)
continue_rect = continue_text.get_rect()
continue_rect.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 128)

# Set sound and music
click_sound = pygame.mixer.Sound("click_sound.wav")
click_sound.set_volume(.5)
miss_sound = pygame.mixer.Sound("miss_sound.wav")
miss_sound.set_volume(.5)
pygame.mixer.music.load("ctc_background_music.wav")

# Set images
background_image = pygame.image.load("circusresized.jpg")
background_rect = background_image.get_rect()
background_rect.topleft = (-700, -400)
# Background Attribution
# Cirque vector created by vectorpouch - www.freepik.com

# Create clown object
clown = clown.Clown()

# The main game loop
pygame.mixer.music.play(-1, 0, 0)
running = True
while running:
    # Check to see if the user wants to quit
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # A click is made
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x = event.pos[0]
            mouse_y = event.pos[1]

            # The clown was clicked
            if clown.clown_rect.collidepoint(mouse_x, mouse_y):
                click_sound.play()
                score += 1
                clown.clown_velocity += clown.CLOWN_ACCELERATION
                previous_directions = (clown.clown_dx, clown.clown_dy)
                while previous_directions == (clown.clown_dx, clown.clown_dy):
                    clown.clown_dx = random.choice([-1, 1])
                    clown.clown_dy = random.choice([-1, 1])
            # The clown was missed
            else:
                miss_sound.play()
                player_lives -= 1

    # Move clown
    clown.move()

    # Blit Background
    display_surface.blit(background_image, background_rect)

    # Update HUD
    score_text = font.render("Score: " + str(score), True, RED)
    lives_text = font.render("Lives: " + str(player_lives), True, RED)

    # Blit HUD
    display_surface.blit(title_text, title_rect)
    display_surface.blit(score_text, score_rect)
    display_surface.blit(lives_text, lives_rect)

    # Check for game over
    if player_lives == 0:
        display_surface.blit(game_over_text, game_over_rect)
        display_surface.blit(continue_text, continue_rect)
        pygame.display.update()
        is_paused = True
        pygame.mixer.music.stop()
        while is_paused:
            for event in pygame.event.get():
                # The player wants to quit
                if event.type == pygame.QUIT:
                    is_paused = False
                    running = False
                # The player wants to play again
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    is_paused = False
                    score = 0
                    player_lives = 5
                    clown.clown_velocity = clown.CLOWN_STARTING_VELOCITY
                    clown.clown_dx = random.choice([-1, 1])
                    clown.clown_dy = random.choice([-1, 1])
                    clown.clown_rect.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)
                    pygame.mixer.music.play(-1, 0, 0)

    # Blit Assets
    display_surface.blit(clown.clown_image, clown.clown_rect)

    # Update display and tick clock
    pygame.display.update()
    clock.tick(FPS)

# End the game
pygame.quit()


from django.core.management.base import BaseCommand, CommandError
from main.models import BoxLocation
from main.models import create_box_key

class Command(BaseCommand):
    help = 'Create Dummy Box locations'

    def handle(self, *args, **options):

        boxes = BoxLocation.objects.filter(is_active=True)
        for center in boxes:
            center:BoxLocation
            center.center_apikey=create_box_key()
            center.save()

        self.stdout.write(self.style.SUCCESS("Successfully updated %s box locations" %len(boxes)))


from django.db.models.signals import post_save
from django.dispatch import receiver
from archive_app.models import FamilyMember

@receiver(post_save, sender=FamilyMember)
def update_partner(sender, instance, created, **kwargs):
    print(created)
    print(instance.partner)
    if created and instance.partner:
        partner = FamilyMember.objects.get(id=instance.partner.id)
        partner.partner = instance
        partner.save()
    if created and instance.partner2:
        partner2 = FamilyMember.objects.get(id=instance.partner2.id)
        partner2.partner2 = instance
        partner2.save()


from pytube import Playlist

while True:
    # Prompt the user to enter a YouTube playlist URL
    playlist_url = input("Enter the URL of the YouTube playlist (or type 'exit' to terminate): ")

    if playlist_url.lower() == 'exit':
        break

    try:
        # Create a Playlist object
        playlist_obj = Playlist(playlist_url)

        # Extract video titles along with their numbers
        video_titles = [f"{i+1}. {video.title}" for i, video in enumerate(playlist_obj.videos)]

        # Define the output file name based on the playlist title
        playlist_title = playlist_obj.title
        output_file = f"{playlist_title}_titles.txt"

        # Write video titles to a text file
        with open(output_file, "w", encoding="utf-8") as file:
            file.write("\n".join(video_titles))

        print(f"{len(video_titles)} video titles have been saved to {output_file}.\n")
    except Exception as e:
        print(f"An error occurred: {str(e)}\n")

    # Ask the user if they want to continue
    while True:
        user_choice = input("Do you want to fetch another playlist? (yes/no): ").strip().lower()
        if user_choice in ('yes', 'no'):
            break
        else:
            print("Please enter 'yes' or 'no'.")

    if user_choice == 'no':
        break

print("Script terminated.")


import pandas as pd
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split

input_txt=pd.read_csv("../household data/train.csv");
test_txt=pd.read_csv("../household data/test.csv");

y=input_txt.SalePrice;
label=['LotArea','YearBuilt','1stFlrSF','2ndFlrSF','FullBath','BedroomAbvGr','TotRmsAbvGrd'];
x=input_txt[label];

train_x,val_x,train_y,val_y=train_test_split(x,y,random_state=0);
model=DecisionTreeRegressor();

#test_x=test_txt[label];
model.fit(train_x,train_y);

predicted=model.predict(val_x)
print(mean_absolute_error(val_y,predicted))


__author__ = 'dmyung'

#taken from the django debug toolbar sql panel
import six.moves.socketserver
import os
import traceback
import django
from django.conf import settings

# -*- coding: utf-8 -

# Figure out some paths
django_path = os.path.realpath(os.path.dirname(django.__file__))
socketserver_path = os.path.realpath(os.path.dirname(six.moves.socketserver.__file__))

SQL_WARNING_THRESHOLD = getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}) \
                            .get('SQL_WARNING_THRESHOLD', 500)

UNKOWN_INFO = {}

DEFAULT_UUID_BATCH_COUNT = 1000

couch_view_queries = []

def process_key(key_obj):

    if isinstance(key_obj, list):
        key_obj = [six.text_type(x).encode('utf-8') for x in key_obj]
    else:
        key_obj = key_obj.encode('utf-8')
    return key_obj

def tidy_stacktrace(strace):
    """
    Clean up stacktrace and remove all entries that:
    1. Are part of Django (except contrib apps)
    2. Are part of SocketServer (used by Django's dev server)
    3. Are the last entry (which is part of our stacktracing code)
    """
    trace = []
    for s in strace[:-1]:
        s_path = os.path.realpath(s[0])
        if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('HIDE_DJANGO_SQL', True) \
            and django_path in s_path and 'django/contrib' not in s_path:
            continue
        if socketserver_path in s_path:
            continue
        trace.append((s[0], s[1], s[2], s[3]))
    return trace

def ms_from_timedelta(td):
    """
    Given a timedelta object, returns a float representing milliseconds
    """
    return (td.seconds * 1000) + (td.microseconds / 1000.0)

FORMAT_VIEW = 'view'
FORMAT_OPEN_DOC = 'open_doc'

VIEW_OUTPUT_HEADERS = [
    'view_path',
    'duration',
    'offset',
    'rows',
    'total_rows',
    'result_cached',
    'include_docs',
    # 'params',
]

OPEN_DOC_OUTPUT_HEADERS = [
    'doc_id',
    'duration',
    'doc_type',
    'response',
    # 'params',
]


from kivy.app import App
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window

from pages.DirPathPage import DirPathPage
from pages.FilePathPage import FilePathPage
from pages.FinishPage import FinishPage
from pages.ResultPage import ResultPage

Window.size = 1200, 800

class MainWindow(App):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.finish_screen = None
        self.result_screen = None
        self.file_path_screen = None
        self.screen_manager = None
        self.dir_path_screen = None
        self.data = None
        self.restore_data = None

    def build(self):
        """
        self.window = GridLayout()
        self.window.cols = 1
        self.window.size_hint = (0.6, 0.7)
        self.window.pos_hint = {"center_x": 0.5, "center_y": 0.5}
        self.window.add_widget(Image(source="resources/images/logo_image.jpg"))

        self.date = TextInput(
            multiline=False,
            # padding_y=(30, 30),
            size_hint=(1, 0.7),
            font_size=30
        )
        self.window.add_widget(self.date)
        """
        self.title = 'ASR System'

        # self.theme_cls.theme_style = "Dark"
        self.screen_manager = ScreenManager()
        Builder.load_file('resources/screen_elements.kv')

        self.dir_path_screen = DirPathPage(main_parent=self)
        screen = Screen(name="Directory")
        screen.add_widget(self.dir_path_screen)
        self.screen_manager.add_widget(screen)

        self.file_path_screen = FilePathPage(main_parent=self)
        screen = Screen(name="File")
        screen.add_widget(self.file_path_screen)
        self.screen_manager.add_widget(screen)

        self.result_screen = ResultPage(main_parent=self)
        screen = Screen(name="Result")
        screen.add_widget(self.result_screen)
        self.screen_manager.add_widget(screen)

        self.finish_screen = FinishPage(main_parent=self)
        screen = Screen(name="Finish")
        screen.add_widget(self.finish_screen)
        self.screen_manager.add_widget(screen)

        # self.file_path_screen = ResultPage(main_parent=self)
        # screen = Screen(name="Result")
        # screen.add_widget(self.file_path_screen)
        # self.screen_manager.add_widget(screen)

        return self.screen_manager

    def restart(self):
        self.root.clear_widgets()
        self.stop()
        return MainWindow().run()

if __name__ == "__main__":
    MainWindow().run()


# -*- coding: utf-8 -*-
"""
Created on Sat Dec 06 11:44:28 2014

@author: Konstantin
"""

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def main():
    mu = np.array([1, 10, 20])
    sigma = np.matrix([[20, 10, 10],
                       [10, 25, 1],
                       [10, 1, 50]])
    np.random.seed(100)
    data = np.random.multivariate_normal(mu, sigma, 1000)
    print(data.shape)
    values = data.T
    print(values.shape)

    kde = stats.gaussian_kde(values)
    density = kde(values)

    fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
    x, y, z = values
    #print(x.shape)
    #print(y.shape)
    #print(z.shape)
    ax.scatter(x, y, z, c=density)
    plt.show()

if __name__ == '__main__':
    main()


"""Add has_assigned_courses to hod table

Revision ID: 3e4649d3af3d
Revises: 085dfd884e1d
Create Date: 2019-08-24 12:46:19.631062

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '3e4649d3af3d'
down_revision = '085dfd884e1d'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('hods', sa.Column('has_assigned_courses', sa.Boolean(), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('hods', 'has_assigned_courses')
    # ### end Alembic commands ###


import cv2

imageName = 'data/images/opening.png'

image = cv2.imread(imageName, 0)

cv2.imshow('original', image)

#Opening이란
openingSize = 3

element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,
                                    (2*openingSize+1, 2*openingSize+1) )

#iterations= 파라미터로 반복되는 것 지정해줌
imageOpened = cv2.morphologyEx(image, cv2.MORPH_OPEN, element, iterations=2)

cv2.imshow('Opened Image', imageOpened)

cv2.waitKey()
cv2.destroyAllWindows()


import asyncio

# Создаем экземпляр Event
event = asyncio.Event()

async def waiter():
    print('waiter: ожидаем события')
    await event.wait()
    print('waiter: событие произошло')

async def setter():
    print('setter: засыпаем')
    await asyncio.sleep(1)
    print('setter: просыпаемся и устанавливаем событие')
    event.set()

async def main():
    # Запускаем waiter и setter параллельно
    await asyncio.gather(waiter(), setter())

asyncio.run(main())


import pyro.mesh.boundary as bnd
import pyro.simulation_null as sn
from pyro.mesh import patch
from pyro.util import runparams

class TestSimulation:

    @classmethod
    def setup_class(cls):
        """ this is run once for each class before any tests """

    @classmethod
    def teardown_class(cls):
        """ this is run once for each class after all tests """

    def setup_method(self):
        """ this is run before each test """
        self.rp = runparams.RuntimeParameters()
        self.rp.params["driver.tmax"] = 1.0
        self.rp.params["driver.max_steps"] = 100
        self.rp.params["driver.init_tstep_factor"] = 0.5
        self.rp.params["driver.max_dt_change"] = 1.2
        self.rp.params["driver.fix_dt"] = -1.0

        self.sim = sn.NullSimulation("test", "test", self.rp)

        myg = patch.Grid2d(8, 16)
        myd = patch.CellCenterData2d(myg)
        bc = bnd.BC()
        myd.register_var("a", bc)
        myd.create()

        self.sim.cc_data = myd

    def teardown_method(self):
        """ this is run after each test """
        self.rp = None
        self.sim = None

    def test_finished_n(self):
        self.sim.n = 1000
        assert self.sim.finished()

    def test_finished_t(self):
        self.sim.cc_data.t = 2.0
        assert self.sim.finished()

    def test_compute_timestep(self):

        # set a dt and n = 0, then init_tstep_factor should kick in
        self.sim.dt = 2.0
        self.sim.n = 0
        self.sim.compute_timestep()
        assert self.sim.dt == 1.0

        # now set dt_old and a new dt and see if the max_dt_change kicks in
        self.sim.n = 1.0
        self.sim.dt_old = 1.0
        self.sim.dt = 2.0
        self.sim.compute_timestep()
        assert self.sim.dt == 1.2

        # now test what happens if we go over tmax
        self.sim.cc_data.t = 0.75
        self.sim.dt = 0.5
        self.sim.compute_timestep()
        assert self.sim.dt == 0.25

def test_grid_setup():

    rp = runparams.RuntimeParameters()
    rp.params["mesh.nx"] = 8
    rp.params["mesh.ny"] = 16
    rp.params["mesh.xmin"] = 0.0
    rp.params["mesh.xmax"] = 1.0
    rp.params["mesh.ymin"] = 0.0
    rp.params["mesh.ymax"] = 2.0

    g = sn.grid_setup(rp)

    assert g.nx == 8
    assert g.ny == 16
    assert g.dx == 1.0/8
    assert g.dy == 1.0/8


import re
import cn2an

road_num_pattern = re.compile(r"^(\w+[(大道)路])(\d+号)")
zu_num_pattern = re.compile(r"(\d+组)(\d+号)$")
unsure_zu_num_pattern = re.compile(r"[村浜区片桥]\w*[第]*(\w+组)(\d+号)$")
num_pattern = re.compile(r"\d+")

# 获取道路和道路号
def GetRoadNumByRegex(addr):
	m = road_num_pattern.match(addr)
	if m:
		return m.group(1),m.group(2)
	return "",""

# 获取组和组号
def GetZuAndNum(addr):
	m = zu_num_pattern.search(addr)
	if m:
		num = m.group(1)[:-1]
		value = cn2an.an2cn(num)
		return str(value)+"组",m.group(2)

	return getZuAndNumLast(addr)

def getZuAndNumLast(addr):
	ta = addr
	zu,zu_num = "",""
	for i in range(1,10):
		i = 0
		um = unsure_zu_num_pattern.search(ta)
		if um:
			zu = um.group(1)
			zu_num = um.group(2)
			ta = zu+zu_num
		else:
			break

	# if zu!="" and zu_num!="":
	# 	zu_str = zu[:len(zu)-1]
	# 	try:
	# 		value = cn2an.cn2an(zu_str, "strict")
	# 		value = str(value)
	# 		if num_pattern.match(value):
	# 			return value+"组",zu_num
	# 	except ValueError:
	# 		print(zu_str)
	# 		print("get zu zu_num wrong 1:"+addr)
	# 		return "",""
	# 	except TypeError:
	# 		print(zu_str)
	# 		print("get zu zu_num wrong 2:"+addr)
	# 		return "",""

	return "",""


import aiohttp
import json

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def get_code(station_name):

    url = 'https://suggests.rasp.yandex.net/all_suggests' \
          '?client_city=213' \
          '&field=from' \
          '&format=old' \
          '&lang=ru' \
          '&national_version=ru' \
          '&other_point=s9601782' \
          f'&part={station_name}'

    async with aiohttp.ClientSession() as session:
        html = await fetch(session, url)
        html_json = json.loads(html)
        stations = [s for s in html_json[1] if(s[2][:2] == 'пл')]
        print(f'stations - {len(stations)}')

    return stations


import onemsdk
import datetime
import jwt
import pytz
import random
import requests
import string

from ago import human

from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.urls import reverse
from django.views.generic import View as _View

from onemsdk.schema.v1 import (
    Response, Menu, MenuItem, Form, FormItem, FormItemType, FormMeta
)

class View(_View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *a, **kw):
        return super(View, self).dispatch(*a, **kw)

    def get_user(self):
        token = self.request.headers.get('Authorization')
        if token is None:
            raise PermissionDenied

        data = jwt.decode(token.replace('Bearer ', ''), key='87654321')
        user, created = User.objects.get_or_create(id=data['sub'])

        return user

    def to_response(self, content):
        response = Response(content=content)

        return HttpResponse(response.json(), content_type='application/json')

class HomeView(View):
    http_method_names = ['get','post', 'put']

    def get(self, request, post_id=None):
        user = self.get_user()
        if user.username == '':
            form_items = [
                FormItem(type=FormItemType.string,
                                name='username',
                                description='Please choose a username',
                                header='MENU',
                                footer='Send username')
            ]
            content = Form(body=form_items,
                           method='POST',
                           path=reverse('home'),
                           meta=FormMeta(confirmation_needed=False,
                                         completion_status_in_header=False,
                                         completion_status_show=False))
        else:
            menu_items = [
                MenuItem(description='Add post',
                         method='GET',
                         path=reverse('add_post')),
                MenuItem(description='My posts',
                         method='GET',
                         path=reverse('my_posts'))
            ]

            content = Menu(body=menu_items)

        if not cache.get('posts'):
            cache.set('posts', [])

        return self.to_response(content)

    def post(self, request):
        user = self.get_user()
        User.objects.filter(id=user.id).update(username=request.POST['username'])
        return HttpResponseRedirect(reverse('home'))

class AddPostView(View):
    http_method_names = ['get', 'post']

    def get(self, request):
        form_items = [
            FormItem(type=FormItemType.string,
                     name='title',
                     description='Give your new post a title (maximum 64 characters)',
                     header='add',
                     footer='Reply with post title or BACK'),
            FormItem(type=FormItemType.string,
                     name='description',
                     description='Send post content (max 50 words)',
                     header='add',
                     footer='Reply with post content or BACK'),
        ]
        form = Form(body=form_items,
                    method='POST',
                    path=reverse('add_post'),
                    meta=FormMeta(confirmation_needed=False,
                                  completion_status_in_header=False,
                                  completion_status_show=False))

        return self.to_response(form)

    def post(self, request):
        now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
        expires_at = now + datetime.timedelta(days=14)
        user_id = self.get_user().id

        # since we don't create DB records, we don't have a post id to use it
        # for hashids encoding thus we generate a random code
        code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))

        new_post = {
            'user': self.get_user(),
            'title': request.POST['title'],
            'description': request.POST['description'],
            'expires_at': expires_at,
            'code': code
        }

        # save post in cache
        existing_posts = cache.get('posts')
        if existing_posts:
            cache.set('posts', cache.get('posts') + [new_post])
        else:
            cache.set('posts', [new_post])
        cache.set('new_post', True)

        return HttpResponseRedirect(reverse('post_detail', args=[new_post['code']]))

class MyPostsListView(View):
    http_method_names = ['get']

    def get(self, request):
        menu_items = []

        posts = cache.get('posts')
        if posts:
            for post in posts:
                menu_items.append(
                    MenuItem(description=u'{}..'.format(post['title'][:15]),
                             method='GET',
                             path=reverse('post_detail', args=[post['code']]))
                )
        else:
            menu_items.append(
                MenuItem(description='You currently have no posts.')
            )
        content = Menu(body=menu_items, footer='Reply MENU')

        return self.to_response(content)

class PostDetailView(View):
    http_method_names = ['get']

    def get(self, request, code):
        post = [post for post in cache.get('posts') if post['code'] == code][0]

        menu_items = []
        body_pre = [
            post['description'],
            'Author: {}'.format(post['user'].username),
            'Expires in: {}'.format(human(post['expires_at'])),
            'Code: {}'.format(post['code']),
        ]

        # check to see if we have notifications set in cache for this post
        if cache.get('new_post'):
            body_pre.insert(0, 'Post successfuly created!')
            cache.delete('new_post')

        menu_items.extend([MenuItem(description=u'\n'.join(body_pre))])

        # TODO: get the post title from cache
        content = Menu(body=menu_items, header=post['title'], footer='Reply MENU')

        return self.to_response(content)


import sys
sys.path.append("..")
import os
from utils import all_losses, all_folds, all_datasets, convert_to_valid_path
import pickle
import numpy as np
from multiprocessing import Pool
import argparse
import pandas as pd
from scipy.spatial.distance import jensenshannon

def calculate_stats(grads):
    grad1, grad2 = grads
    grad1 = grad1.flatten()
    grad2 = grad2.flatten()

    corr = np.corrcoef(grad1, grad2)[0, 1]

    grad1 /= np.sum(grad1)
    grad2 /= np.sum(grad2)
    jsd = np.square(jensenshannon(grad1, grad2))

    return {
        "correlation": corr,
        "jensenshannondiv": jsd
    }

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("--loss1", type=str, help="First loss to use for the comparison")
    parser.add_argument("--loss2", type=str, help="Second loss to use for the comparison")
    parser.add_argument("--dataset", type=str, help="Dataset to use")
    parser.add_argument("--fold", type=int, help="Fold of dataset")
    args = parser.parse_args()

    print(f"Comparing {args.loss1} and {args.loss2} on {args.dataset} (fold {args.fold})")

    loss1_path = f"results/{convert_to_valid_path(args.loss1)}/{args.dataset}/{args.fold}.p"
    loss2_path = f"results/{convert_to_valid_path(args.loss2)}/{args.dataset}/{args.fold}.p"
    results_dir = f"stats/{args.dataset}/{args.fold}/"
    results_path = results_dir + f"{convert_to_valid_path(args.loss1)}_{convert_to_valid_path(args.loss2)}.csv"

    if os.path.exists(results_path):
        print(f"This combination was already checked.")
        sys.exit(0)

    with open(loss1_path, "rb") as f:
        grads1 = pickle.load(f)
        print(f"Loaded grads for {args.loss1}")

    if not os.path.exists(loss1_path) or not os.path.exists(loss2_path):
        print("Not all files are available.")
        sys.exit("Not all files are available.")

    with open(loss2_path, "rb") as f:
        grads2 = pickle.load(f)
        print(f"Loaded grads for {args.loss2}")

    print("Starting statistic generation")
    with Pool(processes=4) as pool:
        stats = pool.map(calculate_stats, zip(grads1, grads2))

    del grads1
    del grads2

    print("Creating DataFrame")
    stats = pd.DataFrame(stats)

    os.makedirs(results_dir, exist_ok=True)
    print("Saving DataFrame")
    stats.to_csv(results_path, index=False)

    print("Finished:")
    print(stats.describe())


import mariadb
import requests
from price import config
from price import mail
import time
import datetime
from price import insert1_12 as insert

headers = {
    'X-CMC_PRO_API_KEY': config.key_coinmarketcap,
    'Accepts': 'application/json.json',
}

params = {
    'start': '1',
    'limit': '50',
    'convert': 'USD'
}
# see docsc https://coinmarketcap.com/api/documentation/v1/#tag/cryptocurrency
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'

if 1 == 1 :
    def run(fetch_id):
        try:
            json_data = requests.get(url, params=params, headers=headers).json()
            coins = json_data['data']
            a=""
            insert.delete('coins')
            for i in coins:
                if i['symbol'] in ('BTC', 'ETH', 'WBTC', 'BNB', 'MATIC', 'ATOM', 'DOGE'):
                    a = str.lower(str(i['symbol']))
                    insert.html(str(i['id']), a)
                else:
                    insert.html(str(i['id']), str(i['symbol']))
                coinid = i['id']
                for userid in insert.getAlertsUsid():
                    try:
                        if i['quote']['USD']['price'] > insert.getconf('upper', userid[0], coinid) and int(
                                insert.getconf('new', userid[0], coinid)) == 1:
                            print('ueber')
                            mail.mail(
                                f"Hallo {insert.getusname(userid[0])}, \n\nDer Preis von {i['symbol']} ist ueber {insert.getconf('upper', userid[0], coinid)} gestiegen!\n\nDein Alert wurde deaktiviert, du kannst auf unserer Webseite einen neuen Alert einrichten oder diesen erneut aktivieren.\n\nViele Gruesse \ndein CryptoAlert Team :)",
                                config.subject, config.mailfrom, insert.getmail(userid[0]),
                                config.smtp, config.mail_usr, config.mail_pwd)
                            insert.updateconf(userid[0], coinid)
                        elif i['quote']['USD']['price'] < insert.getconf('lower', userid[0], coinid) and int(
                                insert.getconf('new', userid[0], coinid)) == 1:
                            print('unter')
                            mail.mail(
                                f"Hallo {insert.getusname(userid[0])}, \n\nDer Preis von {i['symbol']} ist unter {insert.getconf('lower', userid[0], coinid)} USD gefallen!\n\nDein Alert wurde deaktiviert, du kannst auf unserer Webseite einen neuen Alert einrichten oder diesen erneut aktivieren.\n\nViele Gruesse \ndein CryptoAlert Team :)",
                                config.subject, config.mailfrom, insert.getmail(userid[0]),
                                config.smtp, config.mail_usr, config.mail_pwd)
                            insert.updateconf(userid[0], coinid)
                        else:
                            print(f"\nKeine E-Mail zu Alert von {insert.getusname(userid[0])} bei {i['symbol']} versendet.\n")
                    except:
                        None

                try:
                    insert.insert(i['quote']['USD']['price'], str(i['quote']['USD']['last_updated']), str(i['symbol']).upper(), str(i['quote']['USD']['volume_24h']), str(i['quote']['USD']['volume_change_24h']), str(i['quote']['USD']['percent_change_1h']), str(i['quote']['USD']['percent_change_24h']), str(i['quote']['USD']['percent_change_7d']), str(i['quote']['USD']['percent_change_30d']), str(i['quote']['USD']['percent_change_60d']), str(i['quote']['USD']['percent_change_90d']), str(i['quote']['USD']['market_cap']), str(i['quote']['USD']['market_cap_dominance']), str(i['cmc_rank']), str(fetch_id))

                except mariadb.ProgrammingError:

                    insert.create(str(i['symbol']))
                    insert.insert(i['quote']['USD']['price'], str(i['quote']['USD']['last_updated']), str(i['symbol']), str(i['quote']['USD']['volume_24h']), str(i['quote']['USD']['volume_change_24h']), str(i['quote']['USD']['percent_change_1h']), str(i['quote']['USD']['percent_change_24h']), str(i['quote']['USD']['percent_change_7d']), str(i['quote']['USD']['percent_change_30d']), str(i['quote']['USD']['percent_change_60d']), str(i['quote']['USD']['percent_change_90d']), str(i['quote']['USD']['market_cap']), str(i['quote']['USD']['market_cap_dominance']), str(i['cmc_rank']), str(fetch_id))
            now = datetime.datetime.now()
            now = now.strftime('%Y-%m-%d %H:%M:%S')
            print(now)

            #insert.log(now)

        except requests.exceptions.ConnectionError:
            time.sleep(3)


from django import forms
from .models import Items, Members,MembersList,Sendler
from django.template import loader
from django.utils.safestring import mark_safe
from django.contrib.admin.widgets import AdminFileWidget

from django.conf import settings

class BootstrapInputWidget(AdminFileWidget):
    '''custom widget for display image in change_form.html'''
    def render(self, name, value, attrs=None, renderer=None):
        output = []
        if value and getattr(value, "url", None):
            image_url = value.url
            file_name = str(value)
            output.append(
                ''.
                    format(image_url, image_url, file_name))
        output.append(super().render(name, value, attrs))
        return mark_safe(u''.join(output))

class ItemForm(forms.ModelForm):
    class Meta:
        model = Items
        fields = ('caption', 'image', 'description', 'type','cost','link')
        widgets = {'caption': forms.TextInput,
                   'description': forms.Textarea,
                   'image': BootstrapInputWidget()
                   }
class MembersListForm(forms.ModelForm):
    class Meta:
        model = MembersList
        fields = ('name',)

class SendlerForm(forms.ModelForm):
    class Meta:
        model = Sendler
        fields = ('header', 'text', 'members_list','send_date', 'image')
        widgets = {'text': forms.Textarea, }

class MessageForm(forms.Form):
    msg = forms.CharField()

class MembersForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MembersForm, self).__init__(*args, **kwargs)
        for i in self.fields:
            self.fields[i].widget.attrs['readonly'] = True
    class Meta:
        model = Members
        fields = ('image', 'name', 'id_t', 'user_state', 'link_id')
        widgets = {
                   'image': BootstrapInputWidget()
                   }


import cv2
from helper_files import cv_utils

image = cv2.imread("images/shape1.png")

img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
img_blurred = cv2.GaussianBlur(img_gray, (7, 7), 0)
img_edged = cv2.Canny(img_blurred, 30, 150)

(_, cntrs, _) = cv2.findContours(img_edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

print("I have found %d objects" %(len(cntrs)))

# for c in cntrs:
#     cv2.drawContours(image, [c], -1, (0,0,255), 2)

cv2.drawContours(image, cntrs, -1, (0,0,255), 2)

cv_utils.show_image(image)


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

##################################################################
# PROGRAMMER: Pierre-Antoine Ksinant                             #
# DATE CREATED: 14/11/2018                                       #
# REVISED DATE: -                                                #
# PURPOSE: This file consists of a library of functions used the #
#          associated Jupyter Notebook, core of the project. Its #
#          main purpose is to manage the data and the generated  #
#          model.                                                #
##################################################################

##################
# Needed imports #
##################

import os
import pickle
import torch

#######################
# Constant dictionary #
#######################

SPECIAL_WORDS = {'PADDING': '<PAD>'}

######################
# Function load_data #
######################

def load_data(path):
    """
    Load dataset from file
    """

    input_file = os.path.join(path)

    with open(input_file, "r") as f:
        data = f.read()

    return data

#####################################
# Function preprocess_and_save_data #
#####################################

def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables):
    """
    Preprocess text data
    """

    text = load_data(dataset_path)

    # Ignore notice (we don't use it for analysing the data):
    text = text[81:]

    token_dict = token_lookup()
    for key, token in token_dict.items():
        text = text.replace(key, ' {} '.format(token))

    text = text.lower()
    text = text.split()

    vocab_to_int, int_to_vocab = create_lookup_tables(text + list(SPECIAL_WORDS.values()))
    int_text = [vocab_to_int[word] for word in text]
    pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('data/preprocessed_data.pickle', 'wb'))

############################
# Function load_preprocess #
############################

def load_preprocess():
    """
    Load the preprocessed training data and return them in batches of <batch_size> or less
    """

    return pickle.load(open('data/preprocessed_data.pickle', mode='rb'))

#######################
# Function save_model #
#######################

def save_model(filename, decoder):
    """
    Save the ENTIRE PyTorh model (not the recommended way to act)
    """

    torch.save(decoder, filename)

#######################
# Function load_model #
#######################

def load_model(filename):
    """
    Load an ENTIRE PyTorch model
    """

    return torch.load(filename)


from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.conf import settings

from .forms import ResumeForm

from easy_pdf.views import PDFTemplateView
import easy_pdf

# Create your views here.

class HelloPDFView(PDFTemplateView):
    template_name = 'pdf_generator/hello.html'

    base_url = 'file://' + str(settings.STATIC_ROOT)
    download_filename = 'hello.pdf'

    def get_context_data(self, **kwargs):
        return super(HelloPDFView, self).get_context_data(
            pagesize='letter',
            title='Hi there!',
            **kwargs
            )

def index(request):
    form = ResumeForm()
    if request.method == 'POST':
        form = ResumeForm(data=request.POST)
        if form.is_valid():
            context = {
            'name': request.POST.get('name'),
            }
            template = 'pdf_generator/hello.html'
            return easy_pdf.rendering.render_to_pdf_response(request,template,context,using=None,download_filename='Hello.pdf',content_type='application/pdf',response_class=HttpResponse)
    context = {
    'form': form,
    }
    return render(request, 'pdf_generator/index.html', context)


# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
from numpy.testing import assert_allclose
from astropy.units import Quantity
from ...utils.testing import assert_quantity_allclose
from ..powerlaw import (
    power_law_pivot_energy,
    power_law_energy_flux,
    power_law_integral_flux,
    power_law_compatibility,
)

def test_one():
    """Test one case"""
    I = power_law_integral_flux(f=1, g=2)

    assert_allclose(I, 1)

def test_powerlaw_energy_flux():
    """
    Test energy flux computation for power law against numerical solution.
    """
    e1 = Quantity(1, "TeV")
    e2 = Quantity(10, "TeV")
    e = Quantity(1, "TeV")
    g = 2.3
    I = Quantity(1e-12, "cm-2 s-1")

    val = power_law_energy_flux(I=I, g=g, e=e, e1=e1, e2=e2)

    ref = Quantity(2.1615219876151536e-12, "TeV cm-2 s-1")
    assert_quantity_allclose(val, ref)

def test_e_pivot():
    """Hard-coded example from fit example in survey/spectra.
    """
    e_pivot = power_law_pivot_energy(
        energy_ref=1, f0=5.35510540e-11, d_gamma=0.0318377, cov=6.56889442e-14
    )

    assert_allclose(e_pivot, 3.3540034240210987)

def test_compatibility():
    """
    Run a test case with hardcoded numbers:

    HESS J1912+101
    1FGL 1913.7+1007c

    We use the following symbols and units:
    e = pivot energy (MeV)
    f = flux density (cm^-2 s^-1 MeV^-1)
    g = "gamma" = spectral index
    """
    # Fermi power-law parameters
    e_fermi = 1296.2734
    f_fermi = 3.791907e-12
    f_err_fermi = 5.6907235e-13
    g_fermi = 2.3759267
    g_err_fermi = 0.08453985
    par_fermi = (e_fermi, f_fermi, f_err_fermi, g_fermi, g_err_fermi)

    # HESS power-law parameters
    e_hess = 1e6
    f_hess = 3.5 * 1e-12 * 1e-6
    f_err_hess = 0.6 * 1e-12 * 1e-6
    g_hess = 2.2
    g_err_hess = 0.2
    par_hess = (e_hess, f_hess, f_err_hess, g_hess, g_err_hess)

    compatibility = power_law_compatibility(par_fermi, par_hess)

    # Note: I just put the numbers here, didn't verify them!
    assert_allclose(compatibility["g_match"], 2.0901127509816506)
    assert_allclose(compatibility["sigma_low"], -3.380819211512078)
    assert_allclose(compatibility["sigma_high"], -0.5494362450917478)
    assert_allclose(compatibility["sigma_combined"], 3.4251742624791612)


import os
import copy
from collections import namedtuple, Counter, defaultdict
from .dict_config import infer_stage_name_class

def _load_yaml(filename):
    import yaml
    with open(filename, "r") as infile:
        cfg = yaml.safe_load(infile)
    return cfg

def config_dict_from_yaml(cfg_filename, output_dir=None, backend=None):
    cfg = _load_yaml(cfg_filename)

    this_dir = os.path.dirname(cfg_filename)
    cfg = expand_imports(cfg, this_dir=this_dir)

    # Override the output_dir in the config file if this function is given one
    if "general" not in cfg:
        cfg["general"] = {}
    if output_dir:
        cfg["general"]["output_dir"] = output_dir
    if backend:
        cfg["general"]["backend"] = backend

    return cfg

_StageDescription = namedtuple("_StageDescription", "name type config")

def expand_imports(cfg, this_dir):
    cfg = copy.deepcopy(cfg)
    stages = cfg.pop("stages")
    general = cfg.pop("general", None)

    internal_stage_list = preprocess_imports(stages, cfg, this_dir)
    expanded_cfg = build_config(internal_stage_list)
    if general is not None:
        expanded_cfg["general"] = general
    return expanded_cfg

def preprocess_imports(stages, configs, this_dir):
    expanded_stages = []
    for i, stage_cfg in enumerate(stages):
        name, target = infer_stage_name_class(i, stage_cfg)
        if name != "IMPORT":
            stage = _StageDescription(name, target, configs[name])
            expanded_stages.append(stage)
            continue

        expanded_stages += _handle_import(target.format(this_dir=this_dir))

    return expanded_stages

def _handle_import(cfg_filename):
    cfg = _load_yaml(cfg_filename)
    stages = cfg.pop("stages")
    this_dir = os.path.dirname(cfg_filename)
    return preprocess_imports(stages, cfg, this_dir=this_dir)

def build_config(internal_stage_list):
    # Count the number of unique stage names
    name_counts = Counter(s.name for s in internal_stage_list)
    stages_with_counter = {s for s, c in name_counts.items() if c > 1}

    out_stages = []
    out_config = {}
    stages_seen = defaultdict(int)
    for stage in internal_stage_list:
        name = stage.name
        if name in stages_with_counter:
            name += "." + str(stages_seen[name])
        stages_seen[stage.name] += 1

        out_stages.append({name: stage.type})
        out_config[name] = stage.config

    out_config["stages"] = out_stages
    return out_config