import math
from django.shortcuts import render, get_object_or_404, redirect, reverse
from django.utils import timezone
from authentication.models import UserProfile
from issue_tracker.models import Issue, Comment
from django.contrib.auth.models import User
from issue_tracker.forms import IssueForm, CommentForm
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Create your views here.
def get_all_issues(request):
    """
    Create a view that will return all the Issues from all Users
    that were published prior to now and render them all to issues.html
    template
    """
    all_issues = Issue.objects.filter(published_date__lte=timezone.now()).order_by("-total_votes")
    comments = Comment.objects.filter()
    paginator = Paginator(all_issues, 9)
    page = request.GET.get('page-issues')
    try:
        all_issues = paginator.page(page)
    except PageNotAnInteger:
        all_issues = paginator.page(1)
    except EmptyPage:
        all_issues = paginator.page(paginator.num_pages)
    paginator.page(paginator.num_pages)
    return render(request, "issues.html", {"all_issues": all_issues,
                                           "comments": comments,
                                        #   "comment_count": comment_count,
                                            })

def single_issue(request, pk):
    """
    Create a view that returns an issue based on the issue id (pk)
    and render it to viewissue.html or return 404 error if issue is not found
    """
    issue = get_object_or_404(Issue, pk=pk)
    comments = Comment.objects.filter(issue=issue).order_by("-id")
    if request.method == "POST":
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            content = request.POST.get('content')
            comment = Comment.objects.create(issue=issue,
                                             user_logged_in=request.user,
                                             content=content)
            comment.save()
            # Issue.objects.create(comment)
            issue.comment_number += 1
            issue.save()
            return redirect(single_issue, issue.pk)
    else:
        comment_form = CommentForm()

    author_image = []
    try:
        image = UserProfile.objects.get(user=issue.author).image
        author_image.append({"image": image})
    except:
        author_image.append({"image": None})

    comments_with_images = []
    for comment in comments:
        try:
            image = UserProfile.objects.get(user=comment.user_logged_in).image
            comments_with_images.append({"image": image, "comment": comment})
        except:
            comments_with_images.append({"image": None, "comment": comment})
    comment_count = comments.count()
    first_three_comments = comments_with_images[:3]
    return render(request, "viewissue.html", {"author_image": author_image,
                                              "issue": issue,
                                              "comments_with_images": comments_with_images,
                                              "comment_count": comment_count,
                                              "comment_form": comment_form,
                                              "first_three_comments": first_three_comments,
                                              })

def create_or_edit_issue(request, pk=None):
    """
    Create a view that allows the user to create or edit
    an issue depending if the issue ID is null or not
    """
    issue = get_object_or_404(Issue, pk=pk) if pk else None
    if request.method == "POST":
        form = IssueForm(request.POST, request.FILES, instance=issue)
        if form.is_valid():
            issue = form.save()
            issue.author = request.user
            issue.save()
            return redirect(single_issue, issue.pk)
    else:
        form = IssueForm(instance=issue)
    return render(request, "issueform.html", {"form": form})

def delete_issue(request, pk):
    """
    author of issue can delete their posted issue
    """
    issue = get_object_or_404(Issue, pk=pk)
    issue.delete()

    return redirect(get_all_issues)

@csrf_exempt
def vote(request, pk):
    """
    User in session can vote for an issue if it's helped them
    """
    user = request.user
    issue = get_object_or_404(Issue, pk=pk)
    vote_number = issue.total_votes
    if user.is_authenticated():
        if user in issue.vote.all():
            issue.vote.remove(user)
            up_vote = False
            vote_number -= 1
        else:
            issue.vote.add(user)
            up_vote = True
            vote_number += 1
    issue.total_votes = issue.vote.count()
    issue.save()
    data = {
        "up_vote": up_vote,
        "vote_number": vote_number
    }
    return JsonResponse(data)

@csrf_exempt
def done(request, pk):
    """
    Author of issue can click button if 'admin' has fixed the issue in
    their opinon
    """
    issue = get_object_or_404(Issue, pk=pk)
    data = {
        "is_done": issue.done
    }
    is_done = request.POST.get('is_done')
    if request.method == "POST":
        if str(is_done) == "true":
            issue.done = True
            issue.save()
        else:
            issue.done = False
            issue.save()
    return JsonResponse(data)


import numpy as np

def checkerboard(n):
    if n%2!=0:
        return
    array=np.zeros((n,n),dtype=int)
    for i in range(1-n,n,2):
        array+=np.eye(n,k=i,dtype=int)
    return array

print(checkerboard(int(input("Enter the even no of Rows : "))))

print("thank you")


from src import Constants
from src.Objects.GenericObject import GenericObject

class Item(GenericObject):
    def __init__(self, itemConfig):
        super().__init__(itemConfig)
        self.effect = itemConfig[Constants.effect]

    def activate(self, user, isCrit):
        return {
            Constants.description: "{} used {} to {}".format(user.name, self.name, self.effect),
            Constants.attack: user.attack + self.attack,
            Constants.effect: self.effect
        }

    def receive(self, change, data):
        baseResult = super().receive(change, data)
        if isinstance(baseResult, list):
            # Return the loot
            return baseResult
        #Handle peaceful interactions with characters
        if baseResult == Constants.take:
            data.current_room.objects = [o for o in data.current_room.objects if o.name is not self.name]
            return self


from concurrent.futures.thread import ThreadPoolExecutor

import requests

# url = "http://www.eversunshine.cn/"
# url = "https://static-4c89007f-af34-418a-909e-be456bf03b70.bspapp.com/#/"
# url = "https://www.baidu.com/"

def DOS():
    # resp = requests.get(url, timeout=3)
    # print(resp.text)
    # print(data)
    resp = requests.get(url)
    print(resp.text)

if __name__ == "__main__":
    with ThreadPoolExecutor(1000) as t:
        for i in range(100000):
            t.submit(DOS)


import tkinter as tk
#import sys
#import os

#if os.environ.get('DISPLAY','') == '':
 #   print('no display found. Using :0.0')
  #  os.environ.__setitem__('DISPLAY', ':0.0')

venster=tk.Tk()
tekst=tk.Label(venster, text="Demo")
tekst.pack()

venster.mainloop()


# -*- coding: utf-8 -*-
"""
Created on Thu Jul 30 16:21:28 2018

@author: bob.lee
"""
from src.model_test import image_cnn
from PIL import Image
import sys

def image_main(image_name):
    image = Image.open(image_name)
    image = image.flatten() / 255
    predict_text = image_cnn(image)
    return predict_text

if __name__ == '__main__':
    result = image_main(sys.argv[1])
    print(result)


# -*- coding: utf-8 -*-
# pylint: disable-msg=W0403,W0603,C0111,C0103,W0142,C0301
""" partialy stolen from python locale tests ;)
    requires nose (easy_install nose)
    nosetests -v --with-coverage --cover-package=localization test_localization.py
"""

from django.conf import settings
settings.configure(DEBUG=True,
                   )
import nose
import locale
import sys
from localization import (setlocale, format, atoi, atof, _normalize,
                          nl_langinfo, localeconv)

OLD_LOCALE_TM = None
def setup_tm():
    """ setup for date/time tests """
    global OLD_LOCALE_TM
    OLD_LOCALE_TM = locale.setlocale(locale.LC_TIME)
#

def tear_down_tm():
    """ cleanup for date/time tests """
    locale.setlocale(locale.LC_TIME, OLD_LOCALE_TM)
#

OLD_LOCALE_NUM = None
def setup_num():
    """ setup for numeric tests """
    global OLD_LOCALE_NUM
    OLD_LOCALE_NUM = locale.setlocale(locale.LC_NUMERIC)
#

def tear_down_num():
    """ cleanup for numeric tests """
    locale.setlocale(locale.LC_NUMERIC, OLD_LOCALE_NUM)
#

# setup locale list and ensure that C and en comes first
CANDIDATE_LOCALES = [x[0] for x in [('C', 1), ('en', 1)]]# + list(settings.LANGUAGES)]

OLD_LOCALE_NUM = locale.setlocale(locale.LC_NUMERIC)

if sys.platform.startswith("win"):
    locale.setlocale(locale.LC_NUMERIC, "en")
elif sys.platform.startswith("freebsd"):
    locale.setlocale(locale.LC_NUMERIC, "en_US.US-ASCII")
else:
    locale.setlocale(locale.LC_NUMERIC, "en_US")
#

# BASE FUNCTIONALITY

def test_number_format():
    setlocale('en')

    td = (
          # w/o grouping
          (("%f", 1024), '1024.000000'),
          (("%f", 102), '102.000000'),
          (("%f", -42), '-42.000000'),
          (("%+f", -42), '-42.000000'),
          (("%20.f", -42), '                 -42'),
          (("%+10.f", -4200), '     -4200'),
          (("%-10.f", 4200),'4200      '),

          # with grouping
          (("%f", 1024, 1), '1,024.000000'),
          (("%f", 102, 1), '102.000000'),
          (("%f", -42, 1), '-42.000000'),
          (("%+f", -42, 1), '-42.000000'),
          (("%20.f", -42, 1), '                 -42'),
          (("%+10.f", -4200, 1), '    -4,200'),
          (("%-10.f", 4200, 1),'4,200     '),
          )

    for args, res in td:
        assert format(*args) == res, '%r != %r' % (format(*args), res)
#

def _set_locale(what, loc):
    try:
        locale.setlocale(what, loc)
    except locale.Error:
        locale.setlocale(what, '')
#

@nose.with_setup(setup_num, tear_down_num)
def test_conversion():
    setlocale('en')

    # INT
    val = 123456789

    s1 = format("%d", 123456789, 1)
    assert s1 == '123,456,789', '%r != %r' % (val, s1)
    assert val == atoi(s1), '%r != %r' % (val, atoi(s1))

    # FLOAT
    val = 123456789.14
    s1 = str(val)
    s2 = format("%.2f", val, 1)
    assert s2 == '123,456,789.14', '%r != %r' % (val, s2)
    assert val == atof(s1), '%r != %r' % (val, atof(s1))
#

@nose.with_setup(setup_num, tear_down_num)
def test_numeric():
    for loc in CANDIDATE_LOCALES:
        lc_norm = _normalize(loc)
        _set_locale(locale.LC_NUMERIC, lc_norm)
        setlocale(loc)
        # short
        for what in (locale.ALT_DIGITS, locale.RADIXCHAR, locale.THOUSEP):
            nl = nl_langinfo(what)
            lo = locale.nl_langinfo(what)
            assert nl == lo, '%s (%s): %r != %r' % (loc, lc_norm, nl, lo)
        #
    # for
#

@nose.with_setup(setup_num, tear_down_num)
def test_monetary():
    for loc in CANDIDATE_LOCALES:
        lc_norm = _normalize(loc)
        _set_locale(locale.LC_NUMERIC, lc_norm)
        setlocale(loc)
        # short
        nl = locale.localeconv()
        li = localeconv()
        for k, v in nl.items():
            assert v == li[k], '%s (%s): %s %r != %r' % (loc, lc_norm, k, v, li[k])
        #
    # for
#

@nose.with_setup(setup_tm, tear_down_tm)
def test_date_time_format():
    for loc in CANDIDATE_LOCALES:
        lc_norm = _normalize(loc)
        _set_locale(locale.LC_TIME, lc_norm)
        setlocale(loc)
        for what in (
                     locale.D_T_FMT, locale.D_FMT, locale.T_FMT, locale.T_FMT_AMPM,
                     ):
            nl = nl_langinfo(what)
            lo = locale.nl_langinfo(what)
            assert nl == lo, '%r != %r' % (nl, lo)
        #
    #
#

@nose.with_setup(setup_tm, tear_down_tm)
def test_day_names():
    for loc in CANDIDATE_LOCALES:
        lc_norm = _normalize(loc)
        _set_locale(locale.LC_TIME, lc_norm)
        setlocale(loc)
        for what in (
                     locale.DAY_1, locale.DAY_2, locale.DAY_3, locale.DAY_4, locale.DAY_5, locale.DAY_6, locale.DAY_7,
                     locale.ABDAY_1, locale.ABDAY_2, locale.ABDAY_3, locale.ABDAY_4, locale.ABDAY_5, locale.ABDAY_6, locale.ABDAY_7,
                     ):
            nl = nl_langinfo(what)
            lo = locale.nl_langinfo(what)
            assert nl == lo, '%r != %r' % (nl, lo)
        #
    #
#

@nose.with_setup(setup_tm, tear_down_tm)
def test_month_names():
    for loc in CANDIDATE_LOCALES:
        lc_norm = _normalize(loc)
        _set_locale(locale.LC_TIME, lc_norm)
        setlocale(loc)
        for what in (
                     locale.MON_1, locale.MON_2, locale.MON_3, locale.MON_4, locale.MON_5, locale.MON_6, locale.MON_7, locale.MON_8, locale.MON_9, locale.MON_10, locale.MON_11, locale.MON_12,
                     locale.ABMON_1, locale.ABMON_2, locale.ABMON_3, locale.ABMON_4, locale.ABMON_5, locale.ABMON_6, locale.ABMON_7, locale.ABMON_8, locale.ABMON_9, locale.ABMON_10, locale.ABMON_11, locale.ABMON_12,
                     ):
            nl = nl_langinfo(what)
            lo = locale.nl_langinfo(what)
            assert nl == lo, '%r != %r' % (nl, lo)
        #
    #
#

@nose.with_setup(setup_tm, tear_down_tm)
def test_era():
    for loc in CANDIDATE_LOCALES:
        lc_norm = _normalize(loc)
        _set_locale(locale.LC_TIME, lc_norm)
        setlocale(loc)
        for what in (
                     locale.ERA, locale.ERA_D_T_FMT, locale.ERA_D_FMT,
                     ):
            nl = nl_langinfo(what)
            lo = locale.nl_langinfo(what)
            assert nl == lo, '%r != %r' % (nl, lo)
        #
    #
#

def test_sr_number_format():
    setlocale('sr')

    td = (
          # w/o grouping
          (("%f", 1024), '1024,000000'),
          (("%f", 102), '102,000000'),
          (("%f", -42), '-42,000000'),
          (("%+f", -42), '-42,000000'),
          (("%20.f", -42), '                 -42'),
          (("%+10.f", -4200), '     -4200'),
          (("%-10.f", 4200),'4200      '),

          # with grouping
          (("%f", 1024, 1), '1.024,000000'),
          (("%f", 102, 1), '102,000000'),
          (("%f", -42, 1), '-42,000000'),
          (("%+f", -42, 1), '-42,000000'),
          (("%20.f", -42, 1), '                 -42'),
          (("%+10.f", -4200, 1), '    -4.200'),
          (("%-10.f", 4200, 1),'4.200     '),
          )

    for args, res in td:
        assert format(*args) == res, '%r != %r' % (format(*args), res)
#

# DJANGO FUNCTIONALITY

# FIXME: specific number and date/time tests


import threading
import json
import os
from astar_model import AStarModel
from tkinter.ttk import Progressbar
from tkinter import (Tk, Frame, Button, Label, Entry, Checkbutton, Scale, Canvas, messagebox, filedialog,
                     StringVar, IntVar,
                     DISABLED, NORMAL,
                     W, S, NW, EW, NSEW,
                     BOTTOM, TOP, LEFT,
                     X, Y,
                     HORIZONTAL,
                     YES)

class AStarView(Tk):
    def __init__(self, width=15):
        Tk.__init__(self)
        self.title('A* Search Visualizer')

        # Application version
        self.__VERSION = '1.0.0'

        # Grid width slider range
        self.__MAX_GRID_WIDTH = 100
        self.__MIN_GRID_WIDTH = 2

        # Width of the control frame in pixels (you can modify this)
        self.__CONTROL_DIM_WIDTH = 250

        # Width of the grid in pixels (you can modify this)
        self.__GRID_DIM_WIDTH = 800

        # Calculate the correct dimensions for the root frame (8px offsets prevent grid clipping from grid border thickness)
        self.geometry('{}x{}'.format(
            self.__CONTROL_DIM_WIDTH + self.__GRID_DIM_WIDTH + 8, self.__GRID_DIM_WIDTH + 8))

        # Disable application resizing
        self.resizable(0, 0)

        # Event bindings
        self.bind('<ButtonPress-1>', self.__on_m1_down)
        self.bind('<B1-Motion>', self.__on_m1_down)
        self.bind('<ButtonPress-3>', self.__on_m3_down)
        self.bind('<B3-Motion>', self.__on_m3_down)
        self.bind('<KeyPress>', self.__on_key_press)
        self.bind('<KeyRelease>', self.__on_key_release)

        # Toggles when certain keys are held down
        self.__EDIT_MODE = {
            'setStart': False,
            'setEnd': False,
        }

        # Button colours (you can change these)
        self.__COLOUR_RECONFIGURE_BUTTON = 'coral'
        self.__COLOUR_HOW_TO_USE_BUTTON = 'SlateGray2'
        self.__COLOUR_ABOUT_BUTTON = 'SlateGray1'
        self.__COLOUR_IMPORT_MAZE_BUTTON = 'sandy brown'
        self.__COLOUR_EXPORT_MAZE_BUTTON = 'dark salmon'

        # Maze colours (you can change these)
        self.__COLOUR_EMPTY = 'white'
        self.__COLOUR_WALL = 'gray25'
        self.__COLOUR_START = 'pale green'
        self.__COLOUR_END = 'salmon'
        self.__COLOUR_UNSOLVED = 'thistle'
        self.__COLOUR_SOLVED = 'lemon chiffon'
        self.__COLOUR_PATH = 'light slate blue'

        # Dictionary for when update_gui() is called
        self.__SYMBOL_TO_COLOUR = {
            ' ': self.__COLOUR_EMPTY,
            'W': self.__COLOUR_WALL,
            'S': self.__COLOUR_START,
            'E': self.__COLOUR_END,
            '?': self.__COLOUR_UNSOLVED,
            'X': self.__COLOUR_SOLVED,
            'P': self.__COLOUR_PATH
        }

        # Dialog messages
        self.__DIALOG_MESSAGES = {
            'help': ('Holding left-click places walls\n'
                     'Holding right-click removes walls\n\n'
                     'Holding [S] while pressing left-click sets the start point\n'
                     'Holding [E] while pressing left-click sets the end point\n\n'
                     'Press [space] to start / stop the solver\n'
                     'Press [Esc] to close the application'),

            'about': ('This application visualizes the A* search algorithm.\n\n'
                      'Made by Jonathan Mack\n'
                      'v{}'.format(self.__VERSION)),
        }

        # Contains the GUI representaiton of model.settings
        self.cb_values = {}

        # Disables mouse and keyboard events while True
        self.__is_reconfiguring = False

        # Initialize the backing model
        self.__initialize_model(width, width)

        # Initialize the GUI
        self.__initialize_gui()

    def __initialize_model(self, nRow, nCol):
        ''' Initializes the backing model for the view.

        Args:
            nRow::[int]
                The number of rows in the model
            nCol::[int]
                The number of columns in the model

        Returns:
            None
        '''
        self.model = AStarModel(view=self, nRow=nRow, nCol=nCol)

        # Set the model settings to the GUI settings during reconfiguration
        self.__handle_cb()

        # Disable print to console
        self.model.set_setting('enablePrintToConsole', False)

    def __initialize_gui(self):
        ''' Initializes the GUI.

        Args:
            None

        Returns:
            None
        '''
        self.__initialize_control_frame()
        self.__initialize_grid_frame()

    def __initialize_control_frame(self):
        ''' Initializes the control frame which contains application options.

        Args:
            None

        Returns:
            None
        '''
        # The control frame itself
        control_frame = Frame(self, width=self.__CONTROL_DIM_WIDTH)
        control_frame.pack_propagate(0)
        control_frame.pack(side=LEFT, fill=Y)

        # Initialize children frames
        self.__initialize_configuration_frame(control_frame)
        self.__initialize_options_frame(control_frame)
        self.__initialize_import_export_frame(control_frame)
        self.__initialize_stats_frame(control_frame)
        self.__initialize_help_frame(control_frame)

        # Initialize the Start / Stop button
        self.start_stop_button = Button(control_frame,
                                        text='START',
                                        bg='pale green',
                                        relief='flat',
                                        pady=20,
                                        command=self.__toggle_solver)
        self.start_stop_button.pack(side=BOTTOM, fill=X)

        # Interactive GUI components are disabled during reconfiguration
        self.__interactive_gui_components = [self.grid_width_slider,
                                             self.__reconfigure_button,
                                             self.__cb_diagonal,
                                             self.__cb_grid_lines,
                                             self.__how_to_use_button,
                                             self.__about_button,
                                             self.__import_button,
                                             self.__export_button,
                                             self.start_stop_button]

    def __initialize_configuration_frame(self, master):
        ''' Initializes the configuration frame which is a child of the control frame.

        Args:
            master::[tk.Frame]
                The parent frame of this frame (the control frame)

        Returns:
            None
        '''
        # The configuration frame itself
        configuration_frame = Frame(master)
        configuration_frame.pack(anchor=W, padx=20, pady=20, fill=X)

        # Allow grid components to fill the width of the frame
        configuration_frame.grid_columnconfigure(0, weight=1)
        configuration_frame.grid_columnconfigure(1, weight=1)

        # Configuration label
        configuration_label = Label(
            configuration_frame, text='CONFIGURATION', font=('Helvetica', 16))
        configuration_label.grid(row=0, column=0, sticky=W, columnspan=2)

        # Grid width label
        self.grid_width_label = Label(
            configuration_frame, text='Grid width: {}'.format(self.model.get_nrow()))
        self.grid_width_label.grid(row=1, column=0, sticky=W, columnspan=2)

        # Grid width slider
        self.grid_width_slider = Scale(configuration_frame,
                                       width=20,
                                       from_=self.__MIN_GRID_WIDTH,
                                       to=self.__MAX_GRID_WIDTH,
                                       orient=HORIZONTAL,
                                       showvalue=False)

        # Set default slider value
        self.grid_width_slider.set(self.model.get_nrow())

        # Slider bindings
        self.grid_width_slider.bind(
            '<B1-Motion>', self.__handle_grid_width_slider_change)
        self.grid_width_slider.bind(
            '<ButtonRelease-1>', self.__handle_grid_width_slider_change)
        self.grid_width_slider.grid(row=2, column=0, sticky=EW, columnspan=2)

        # Reconfigure button
        self.__reconfigure_button = Button(
            configuration_frame,
            text='Reconfigure',
            bg=self.__COLOUR_RECONFIGURE_BUTTON,
            command=self.__handle_reconfigure)
        self.__reconfigure_button.grid(row=3,
                                       column=0,
                                       sticky=EW,
                                       columnspan=2)

        # Progress bar for reconfiguration
        self.__progress_bar = Progressbar(
            configuration_frame,
            orient=HORIZONTAL,
            mode='indeterminate')

    def __initialize_options_frame(self, master):
        ''' Initializes the options frame which is a child of the control frame.

        Args:
            master::[tk.Frame]
                The parent frame of this frame (the control frame)

        Returns:
            None
        '''
        # The options frame itself
        options_frame = Frame(master)
        options_frame.pack(anchor=W, padx=20, pady=20, fill=X)

        # Allow grid components to fill the width of the frame
        options_frame.grid_columnconfigure(0, weight=1)

        # Options label
        options_label = Label(
            options_frame,
            text='OPTIONS',
            font=('Helvetica', 16))
        options_label.grid(row=0, column=0, sticky=W, columnspan=2)

        # Allow diagonal movement Checkbutton
        self.allow_diagonals = IntVar(
            value=self.model.get_setting('allowDiagonals'))
        self.cb_values['allowDiagonals'] = self.allow_diagonals
        self.__cb_diagonal = Checkbutton(
            options_frame,
            text='Allow diagonal movement',
            variable=self.allow_diagonals,
            command=self.__handle_cb)
        self.__cb_diagonal.grid(row=1, column=0, sticky=W)

        # Show grid lines Checkbutton
        self.show_grid_lines = IntVar(value=True)
        self.__cb_grid_lines = Checkbutton(
            options_frame,
            text='Show grid lines',
            variable=self.show_grid_lines,
            command=self.__handle_show_grid_lines)
        self.__cb_grid_lines.grid(row=2, column=0, sticky=W)

    def __initialize_import_export_frame(self, master):
        ''' Initializes the Import / Export frame which is a child of the control frame.

        Args:
            master::[tk.Frame]
                The parent frame of this frame (the control frame)

        Returns:
            None
        '''
        # The Import / Export frame itself
        import_export_frame = Frame(master)
        import_export_frame.pack(anchor=W, padx=20, pady=20, fill=X)

        # Allow grid components to fill the width of the frame
        import_export_frame.grid_columnconfigure(0, weight=1)
        import_export_frame.grid_columnconfigure(1, weight=1)

        # Import / Export label
        import_export_label = Label(
            import_export_frame,
            text='IMPORT / EXPORT',
            font=('Helvetica', 16)
        )
        import_export_label.grid(row=0, column=0, sticky=W, columnspan=2)

        # Import button
        self.__import_button = Button(import_export_frame,
                                      text="Import Maze",
                                      bg=self.__COLOUR_IMPORT_MAZE_BUTTON,
                                      command=self.__handle_import)
        self.__import_button.grid(row=1, column=0, sticky=EW)

        # Export button
        self.__export_button = Button(import_export_frame,
                                      text="Export Maze",
                                      bg=self.__COLOUR_EXPORT_MAZE_BUTTON,
                                      command=self.__handle_export)
        self.__export_button.grid(row=1, column=1, sticky=EW)

    def __initialize_stats_frame(self, master):
        ''' Initializes the stats frame which is a child of the control frame.

        Args:
            master::[tk.Frame]
                The parent frame of this frame (the control frame)

        Returns:
            None
        '''
        # The stats frame itself
        stats_frame = Frame(master)
        stats_frame.pack(anchor=W, padx=20, pady=20, fill=X)

        # Allow grid components to fill the width of the frame
        stats_frame.grid_columnconfigure(0, weight=1)
        stats_frame.grid_columnconfigure(1, weight=5)

        # Stats label
        stats_label = Label(
            stats_frame,
            text='STATS',
            font=('Helvetica', 16)
        )
        stats_label.grid(row=0, column=0, sticky=W, columnspan=2)

        # Unsolved label
        self.unsolved_label_var = StringVar()
        unsolved_static_label = Label(
            stats_frame,
            text='# Unsolved Nodes',
            bg=self.__COLOUR_UNSOLVED,
            anchor=W
        )
        unsolved_static_label.grid(row=1, column=0, sticky=EW)

        unsolved_dynamic_label = Label(
            stats_frame,
            textvariable=self.unsolved_label_var
        )
        unsolved_dynamic_label.grid(row=1, column=1, sticky=W)

        # Solved label
        self.solved_label_var = StringVar()
        solved_static_label = Label(
            stats_frame,
            text='# Solved Nodes',
            bg=self.__COLOUR_SOLVED,
            anchor=W
        )
        solved_static_label.grid(row=2, column=0, sticky=EW)

        solved_dynamic_label = Label(
            stats_frame,
            textvariable=self.solved_label_var
        )
        solved_dynamic_label.grid(row=2, column=1, sticky=W)

        # Path label
        self.path_label_var = StringVar()
        path_static_label = Label(
            stats_frame,
            text='# Path Nodes',
            bg=self.__COLOUR_PATH,
            anchor=W
        )
        path_static_label.grid(row=3, column=0, sticky=EW)

        path_dynamic_label = Label(
            stats_frame,
            textvariable=self.path_label_var
        )
        path_dynamic_label.grid(row=3, column=1, sticky=W)

        # Elapsed time label
        self.elapsed_label_var = StringVar()
        elapsed_time_static_label = Label(
            stats_frame,
            text='Elapsed Time (s)'
        )
        elapsed_time_static_label.grid(row=4, column=0, sticky=W)

        elapsed_time_dynamic_label = Label(
            stats_frame,
            textvariable=self.elapsed_label_var
        )
        elapsed_time_dynamic_label.grid(row=4, column=1, sticky=W)

    def __initialize_help_frame(self, master):
        # The help frame itself
        help_frame = Frame(master)
        help_frame.pack(anchor=W, padx=20, pady=20, fill=X)

        # Allow grid components to fill the width of the frame
        help_frame.grid_columnconfigure(0, weight=1)
        help_frame.grid_columnconfigure(1, weight=1)

        # Help label
        help_label = Label(help_frame, text='HELP', font=('Helvetica', 16))
        help_label.grid(row=0, column=0, sticky=W, columnspan=2)

        # How to Use button
        self.__how_to_use_button = Button(help_frame,
                                          text='How to Use',
                                          bg=self.__COLOUR_HOW_TO_USE_BUTTON,
                                          command=lambda title='How to Use', message=self.__DIALOG_MESSAGES['help']: self.__show_info_dialog(title, message))
        self.__how_to_use_button.grid(row=1, column=0, sticky=EW)

        # About button
        self.__about_button = Button(help_frame,
                                     text='About',
                                     bg=self.__COLOUR_ABOUT_BUTTON,
                                     command=lambda title='About', message=self.__DIALOG_MESSAGES['about']: self.__show_info_dialog(title, message))
        self.__about_button.grid(row=1, column=1, sticky=EW)

    def __initialize_grid_frame(self):
        self.grid_frame = Frame(self,
                                height=self.__GRID_DIM_WIDTH,
                                width=self.__GRID_DIM_WIDTH,
                                highlightbackground='gray',
                                highlightthickness=3)

        # Create blank canvas
        self.canvas = Canvas(self.grid_frame,
                             height=self.__GRID_DIM_WIDTH,
                             width=self.__GRID_DIM_WIDTH,
                             bg='white')

        self.canvas.pack()
        self.grid_frame.pack(side=LEFT)

        # Colour the entire grid initially
        self.__POS_TO_SQUARE = {}

        all_indices = [(x, y) for x in range(self.model.get_nrow())
                       for y in range(self.model.get_ncol())]

        self.update_gui(maze=self.model.get_curr_maze(),
                        diff_positions=all_indices,
                        is_rapid_config=False)

    '''
    GUI HANDLERS.
    '''

    def __handle_reconfigure(self, is_importing=False, loaded_maze=None):

        def reconfiguration_thread():
            # Disable mouse and keyboard events
            self.__is_reconfiguring = True

            # Change the grid width slider before the GUI is disabled
            if is_importing:
                # Move the grid width slider to the new grid width
                self.grid_width_slider.set(loaded_maze['gridWidth'])

                # Update the grid width label
                self.grid_width_label.configure(
                    text='Grid width: {}'.format(self.grid_width_slider.get()))

            # Disable interactive GUI components
            self.__disable_gui()

            # Set the new grid width to the one in the imported file if importing, otherwise use the slider value
            print('{}...'.format(
                'Importing maze' if is_importing else 'Reconfiguring'))

            new_width = loaded_maze['gridWidth'] if is_importing else int(
                self.grid_width_slider.get())

            # Replace the Reconfigure button with the progress bar
            self.__reconfigure_button.grid_remove()
            self.__progress_bar.grid(row=3, column=0, sticky=EW, columnspan=2)
            self.__progress_bar.start()

            # The long reconfiguration task
            reconfigure(new_width=new_width,
                        is_importing=is_importing,
                        loaded_maze=loaded_maze)

            # Replace the progress bar with the Reconfigure button
            self.__progress_bar.stop()
            self.__progress_bar.grid_forget()
            self.__reconfigure_button.grid(
                row=3, column=0, sticky=EW, columnspan=2)

            # Re-enable mouse and keyboard events
            self.__is_reconfiguring = False

            # Re-enable interactive GUI components
            self.__enable_gui()

            print('{} complete!'.format(
                'Import' if is_importing
                else 'Reconfiguration'))

            # Show success dialog
            self.__show_info_dialog(
                title='{} Complete'.format(
                    'Import' if is_importing else 'Reconfiguration'),
                message='Successfully {} a {} x {} maze!'.format('imported' if is_importing else 'configured',
                                                                 self.model.get_nrow(),
                                                                 self.model.get_ncol()))

        def reconfigure(new_width, is_importing, loaded_maze):
            # Recreate the backing model and redraw the GUI
            self.__initialize_model(new_width, new_width)
            self.__POS_TO_SQUARE = {}
            self.canvas.delete('all')

            # Colour the entire grid initially
            all_indices = [(x, y) for x in range(self.model.get_nrow())
                           for y in range(self.model.get_ncol())]

            self.update_gui(maze=self.model.get_curr_maze(),
                            diff_positions=all_indices,
                            is_rapid_config=False)

            # Update model with the imported data if the reconfiguration was triggered by an import
            if is_importing and loaded_maze is not None:
                self.model.import_maze_data(loaded_maze)

        # Make sure that the solver is stopped
        if not self.model.is_solving():
            # Display confirmation dialog
            is_reconfiguring = messagebox.askyesno(title='Reconfigure',
                                                   message=('Are you sure you want to reconfigure?\n'
                                                            'All walls will be erased.'),
                                                   icon='warning')
            if is_reconfiguring == YES:
                threading.Thread(target=reconfiguration_thread).start()
        else:
            messagebox.showerror(title='Failed to Reconfigure',
                                 message='Cannot reconfigure while the solver is running.')

    def __handle_grid_width_slider_change(self, event):
        self.grid_width_label.configure(
            text='Grid width: {}'.format(self.grid_width_slider.get()))

    def __handle_cb(self):
        for k, v in self.cb_values.items():
            self.model.set_setting(k, bool(v.get()))

    def __handle_show_grid_lines(self):
        # Determine outline colour
        outline_colour = 'gray' if self.show_grid_lines.get() else ''

        # Colour all square outlines
        for pos in self.__POS_TO_SQUARE:
            square = self.__POS_TO_SQUARE[pos]
            self.canvas.itemconfig(square, outline=outline_colour)

    def __handle_import(self):
        if not self.model.is_solving():
            # Display load file dialog
            filename = filedialog.askopenfilename(parent=self,
                                                  title='Import Maze',
                                                  initialdir=os.getcwd() + '/sample_mazes')

            if filename != '':
                try:
                    # Read the contents of the file
                    with open(filename, 'r') as file:
                        content = file.readlines()

                    # Assign the file contents to a dictionary
                    loaded_maze = json.loads(content[0])

                    # Reconfigure the maze using the imported data
                    self.__handle_reconfigure(
                        is_importing=True, loaded_maze=loaded_maze)
                except:
                    print('Failed to import maze from {}: Incompatible or corrupted file'.format(
                        filename))

    def __handle_export(self):
        if not self.model.is_solving():
            # Display save file dialog
            filetypes = [('JSON', '*.json')]
            filename = filedialog.asksaveasfilename(parent=self,
                                                    title='Export Maze',
                                                    initialfile='my_astar_maze',
                                                    defaultextension='.json',
                                                    filetypes=filetypes)

            # Prepare the current maze configuration data
            curr_maze = {
                'gridWidth': self.model.get_nrow(),
                'start': self.model.get_start(),
                'end': self.model.get_end(),
                'walls': list(self.model.get_walls())
            }

            # Write to the file
            if filename != '':
                with open(filename, 'w') as file:
                    file.write(json.dumps(curr_maze))
                print('Successfully exported maze configuration to {}.'.format(filename))

    '''
    EVENT HANDLERS.
    '''

    def __on_m1_down(self, event):
        self.__handle_mouse_down(event, True)

    def __on_m3_down(self, event):
        self.__handle_mouse_down(event, False)

    def __handle_mouse_down(self, event, is_setting_wall):
        def is_event_pos_valid():
            return 0 <= event.x <= self.__GRID_DIM_WIDTH and 0 <= event.y <= self.__GRID_DIM_WIDTH

        def calculate_square_pos():
            square_pos_x = int(event.x // self.__SQUARE_WIDTH)
            square_pos_y = int(event.y // self.__SQUARE_WIDTH)
            return (square_pos_x, square_pos_y)

        # Validate that the solver is stopped, the GUI is not reconfiguring, and the position is good
        if (not self.model.is_solving()
            and not self.__is_reconfiguring
            and event.widget == self.canvas
                and is_event_pos_valid()):

            square_pos = calculate_square_pos()

            if self.__EDIT_MODE['setStart']:
                self.model.set_start(square_pos)
            elif self.__EDIT_MODE['setEnd']:
                self.model.set_end(square_pos)
            else:
                self.model.set_wall(square_pos, is_setting_wall)

    def __on_key_press(self, event):
        ''' Hanldes keyboard events.

        [space] - Start / stop the solver
        [Esc] - Quit the application
        [S] - Toggle set start node
        [E] - Toggle set end node

        Args:
            event::[tkinter.Event]
                The keyboard event.

        Returns:
            None
        '''
        key_code = event.keysym

        # Only handle keyboard events when the GUI is not reconfiguring
        if not self.__is_reconfiguring:

            # Press [space] to start / stop the solver
            if key_code == 'space':
                self.__toggle_solver()

            # Press [Esc] to quit the application
            elif key_code == 'Escape':
                if not self.model.is_solving():
                    # Display confirmation dialog
                    is_quitting = messagebox.askyesno(title='Exit Application',
                                                      message='Are you sure you want to exit the application?',
                                                      icon='warning')
                    if is_quitting == YES:
                        print('Closing application...')
                        self.destroy()
                else:
                    print(
                        'Cannot close the application while the solver is running.')
                    messagebox.showerror(title='Failed to Close Application',
                                         message='Cannot close the application while the solver is running.')

            # Edit mode toggles
            elif key_code == 's':
                self.__EDIT_MODE['setStart'] = True
            elif key_code == 'e':
                self.__EDIT_MODE['setEnd'] = True

    def __on_key_release(self, event):
        key_code = event.keysym

        if key_code == 's':
            self.__EDIT_MODE['setStart'] = False
        elif key_code == 'e':
            self.__EDIT_MODE['setEnd'] = False

    def __handle_wall_click(self, pos):
        self.model.set_wall(pos, True)

    '''
    UTILITY METHODS.
    '''

    def __toggle_solver(self):
        if not self.model.is_solving():
            # Disable everything in the GUI except the Start / Stop button and the Show grid lines Checkbutton
            self.__disable_gui()
            self.start_stop_button.configure(state=NORMAL)
            self.__cb_grid_lines.configure(state=NORMAL)
            self.model.solve()
        else:
            print('Solver stopped.')
            self.__enable_gui()
            self.model.stop_solving()

    def __disable_gui(self):
        for component in self.__interactive_gui_components:
            component.configure(state=DISABLED)

    def __enable_gui(self):
        for component in self.__interactive_gui_components:
            component.configure(state=NORMAL)

    def __show_info_dialog(self, title, message):
        messagebox.showinfo(title, message)

    def __show_error_dialog(self, title, message):
        messagebox.showerror(title, message)

    '''
    UPDATE METHOD.
    '''

    def __calculate_square_width(self):
        # Update the square width depending on the new model
        self.__SQUARE_WIDTH = self.__GRID_DIM_WIDTH / self.model.get_nrow()

    def update_gui(self, maze, diff_positions, is_rapid_config):
        ''' Updates the GUI by colouring the grid labels contained in diff_indices according to the maze symbols.
        Also updates the stats frame.

        Args:
            maze::[list[list]]
                A 2D array containing symbols that represent the maze
            diff_indices::[list]
                A list containing the positions of nodes that have changed since the previous update

        Returns:
            None
        '''
        # Configure the Start / Stop button to display the appropriate text and colour
        if self.model.is_solving():
            self.start_stop_button.configure(text='STOP', bg='salmon')
        elif not self.__is_reconfiguring:
            # Re-enable the GUI if the solver is done
            self.__enable_gui()
            self.start_stop_button.configure(text='START', bg='pale green')

        # Update the square width based on the current number of rows in the model
        self.__calculate_square_width()

        # Determine outline colour
        outline_colour = 'gray' if self.show_grid_lines.get() else ''

        # Update grid by colouring the appropriate square
        for (x, y) in diff_positions:

            # Create a square at (x, y) if it does not yet exist
            if (x, y) not in self.__POS_TO_SQUARE:
                square = self.canvas.create_rectangle(x * self.__SQUARE_WIDTH,
                                                      y * self.__SQUARE_WIDTH,
                                                      (x + 1) *
                                                      self.__SQUARE_WIDTH,
                                                      (y + 1) *
                                                      self.__SQUARE_WIDTH,
                                                      fill=self.__SYMBOL_TO_COLOUR[maze[x][y]],
                                                      outline=outline_colour,
                                                      tag='to-delete')
                self.__POS_TO_SQUARE[(x, y)] = square

            # Configure the square at (x, y) since it exists
            else:
                self.canvas.itemconfig(self.__POS_TO_SQUARE[(
                    x, y)], fill=self.__SYMBOL_TO_COLOUR[maze[x][y]])

        # Update stats
        self.unsolved_label_var.set(str(self.model.get_stat('numUnsolved')))
        self.solved_label_var.set(str(self.model.get_stat('numSolved')))
        self.path_label_var.set(str(self.model.get_stat('numPath')))
        self.elapsed_label_var.set(str(self.model.get_stat('elapsedTime')))

        # Handle GUI updates differently if the update is caused by a wall config or not
        if is_rapid_config:
            # update_idletasks() prevents fatal crashes when setting / removing nodes rapidly
            self.update_idletasks()
        else:
            # update() allows the user to stop the solver and prevents calls to model.solve() from queueing
            self.update()

def main():
    print('Starting application...')
    app = AStarView()
    app.mainloop()

if __name__ == '__main__':
    main()


#!/bin/env python

import streamlit as st
import pandas as pd
import os
import yaml
################################################################

def _main():
    _filenames = os.listdir()

    _filenames = [e for e in _filenames if os.path.splitext(e)[1] == '.json']
    _filenames = [os.path.splitext(e)[0] for e in _filenames]
    _filenames = [os.path.splitext(e)[0]
                  for e in _filenames if (not e.startswith('Master_')
                                          and not e.startswith('match_'))]

    _filenames.remove('EPFL')
    option = st.selectbox(
        "Select the university", _filenames, key="unisersity_selector_stat")

    try:
        with open(f'match_{option}.json', "r") as f:
            courses_matches = yaml.safe_load(f.read())
    except Exception:
        st.error("Matching tab should be executed once at least")
        return

    df = pd.read_json(option+'.json')
    df_epfl = pd.read_json('EPFL.json')

    sorted_match = {}

    for epfl_title, other_title in courses_matches.items():
        _sel = df_epfl[df_epfl["Course Title"] == epfl_title]
        if _sel.shape[0] == 0:
            st.write(f"cannot find class: {epfl_title}")
            continue
        epfl_class = _sel.iloc[0]
        epfl_year = epfl_class['Year']
        epfl_semester = epfl_class['Semester']
        other_class = df[df["Course Title"] == other_title].iloc[0]

        if epfl_year not in sorted_match:
            sorted_match[epfl_year] = {}
        if epfl_semester not in sorted_match[epfl_year]:
            sorted_match[epfl_year][epfl_semester] = []

        sorted_match[epfl_year][epfl_semester].append(
            (epfl_class, other_class))

    def plot_class(layout, title, year, semester, ects):
        layout.markdown(f"**{title}**, Year{year}-{semester} ({ects} ECTS)")

    hide = st.checkbox("Show only mismatches")

    def are_classes_different(classes):
        cols = st.columns(len(classes))
        ref_class = classes[0]
        ref_title = ref_class['Course Title']
        ref_year = ref_class['Year']
        ref_semester = ref_class['Semester']
        ref_ects = ref_class['ECTS']

        for c, col in zip(classes[1:], cols[1:]):
            title = c['Course Title']
            year = c['Year']
            semester = c['Semester']
            ects = c['ECTS']

            if year != ref_year:
                year = f":red[{year}]"
            if semester != ref_semester:
                semester = f":red[{semester}]"
            if ects != ref_ects:
                ects = f":red[{ects}]"

            if year == ref_year and semester == ref_semester and ects == ref_ects and hide:
                return

            plot_class(col, option + " " + title, year, semester, ects)
        plot_class(cols[0], 'EPFL-' + ref_title,
                   ref_year, ref_semester, ref_ects)

        with st.expander('description', expanded=False):
            cols = st.columns(len(classes))
            for c, col in zip(classes[:], cols[:]):
                col.markdown('- ' + '\n - '.join(c['Description']))

    for year, semesters in sorted_match.items():
        for semester, matches in semesters.items():
            st.markdown(f'### Year {year} - {semester} Semester')
            for classes in matches:
                are_classes_different(classes)
                st.markdown('---')

def main():
    with st.spinner('Loading'):
        _main()


# coding:utf-8
"""
Create by Wangmeng Song
July 21,2017
"""

import shapefile as sf
from shapely.geometry import Polygon, Point
import os
import inspect
import numpy as np
import json

filedir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + "/" + "area"
pingchearea = u'pincheArea.dbf'  # 拼车的区域，已更新
westoutside = u'area26.dbf'   # 已变成area26
eastpick = u'area28.dbf'   # area28
westpick = u'area27.dbf'    # area27
# 成都
chengdujieji = u'zhuanchejieji.dbf'
chengdusongji = u'zhuanchesongji.dbf'
# 宜宾
yibing = ''
# 绵阳
mianyang = ''
# 重庆
chongqing = ''
# 西安
xian = ''
# 在东边的区域
ateastarray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 27]

class SIDE:
    # 不再用此排班范围
    # def chengduArea(self, advanceGetOnTheCar, rmtspID, rmtspLoc, rmtspSeat):
    #     latfilename = filedir + "/" + schedulearea
    #     polys = sf.Reader(latfilename)
    #     polygon = polys.shapes()
    #     shpfilePoints = []
    #     for shape in polygon:
    #         shpfilePoints = shape.points
    #     polygon = Polygon(shpfilePoints)
    #     delindex = []
    #     for i in range(len(rmtspLoc)):
    #         lng = rmtspLoc[i][1]
    #         lat = rmtspLoc[i][0]
    #         point = Point(lng, lat)
    #         if polygon.contains(point):
    #             continue
    #         else:
    #             advanceGetOnTheCar.append(rmtspID[i])   # 去除显示区域外的订单
    #             delindex.append(i)
    #     # 删除提前上车的订单
    #     for deli in reversed(delindex):
    #         del (rmtspID[deli])
    #         del (rmtspLoc[deli])
    #         del (rmtspSeat[deli])
    # 地区东边和西边的代码，地图东为1，西为2,array
    def ateast(self, orderNum, arealoclist):
        sideNo = np.zeros([orderNum], dtype=int)
        for i in range(len(arealoclist)):
            if arealoclist[i] in ateastarray:
                sideNo[i] = 1
            else:
                sideNo[i] = 2
        return sideNo

    def atwest2out(self, westLoc, orderNo):
        westsideNo = np.zeros([orderNo], dtype=int)
        westoutfilename = filedir + "/" + westoutside
        polys = sf.Reader(westoutfilename)
        polygon = polys.shapes()
        shpfilePoints = []
        for shape in polygon:
            shpfilePoints = shape.points
        polygon = Polygon(shpfilePoints)
        for i in range(len(westLoc)):
            lng = westLoc[i][1]
            lat = westLoc[i][0]
            point = Point(lng, lat)
            if polygon.contains(point):
                westsideNo[i] = 1         # 1表示在2环到2.5环之间
            else:
                westsideNo[i] = 2           # 2表示在西边2环内
        return westsideNo

    # 判断是否在西边2环和2.5环
    # def ateast2out(self, eastLoc, orderNo):
    #     eastsideNo = np.zeros([orderNo], dtype=int)
    #     eastoutfilename = filedir + "/" + eastoutside
    #     polys = sf.Reader(eastoutfilename)
    #     polygon = polys.shapes()
    #     shpfilePoints = []
    #     for shape in polygon:
    #         shpfilePoints = shape.points
    #     polygon = Polygon(shpfilePoints)
    #     for i in range(len(eastLoc)):
    #         lng = eastLoc[i][1]
    #         lat = eastLoc[i][0]
    #         point = Point(lng, lat)
    #         if polygon.contains(point):
    #             eastsideNo[i] = 1         # 1表示在2环到2.5环之间
    #         else:
    #             eastsideNo[i] = 2           # 2表示在东边2环内
    #     return eastsideNo

    def orderinchengdutwofive(self, orderdata):
        latfilename = filedir + "/" + pingchearea
        polys = sf.Reader(latfilename)
        polygon = polys.shapes()
        shpfilePoints = []
        for shape in polygon:
            shpfilePoints = shape.points
        polygon = Polygon(shpfilePoints)
        lng = orderdata['bdlng']
        lat = orderdata['bdlat']
        point = Point(lng, lat)
        if polygon.contains(point):
            orderdata['inside'] = True
        else:
            orderdata['inside'] = False
        jsondatar = json.dumps(orderdata, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
        return jsondatar

    # 判断是否在同一个区域里
    def judgeinarea(self, filepath, lat, lng):
        polys = sf.Reader(filepath)
        polygon = polys.shapes()
        shpfilePoints = []
        for shape in polygon:
            shpfilePoints = shape.points
        polygon = Polygon(shpfilePoints)
        point = Point(lng, lat)
        if polygon.contains(point):
            return True
        else:
            return False

    def specificitywholeChengDu(self, SpecificityOrderdata):
        try:
            city = SpecificityOrderdata['city']
        except:
            # 没有传城市编码，默认为成都
            city = 510100
        tripnum = SpecificityOrderdata['triptype']  # 1为接机，2为送机
        lng = SpecificityOrderdata['bdlng']
        lat = SpecificityOrderdata['bdlat']
        # 宜宾
        if city == 'YBP':
            # 接机和送机类型
            SpecificityOrderdata['inside'] = False
            # latfilename = filedir + "/" + yibing
            # if self.judgeinarea(latfilename, lat, lng):
            #     SpecificityOrderdata['inside'] = True
            # else:
            #     SpecificityOrderdata['inside'] = False
        # 绵阳
        elif city == 510700:
            SpecificityOrderdata['inside'] = True
            # latfilename = filedir + "/" + mianyang
            # if self.judgeinarea(latfilename, lat, lng):
            #     SpecificityOrderdata['inside'] = True
            # else:
            #     SpecificityOrderdata['inside'] = False
        # 重庆
        elif city == 'CKG':
            SpecificityOrderdata['inside'] = False
            # latfilename = filedir + "/" + chongqing
            # if self.judgeinarea(latfilename, lat, lng):
            #     SpecificityOrderdata['inside'] = True
            # else:
            #     SpecificityOrderdata['inside'] = False
        # 西安
        elif city == 610100:
            SpecificityOrderdata['inside'] = True
            # latfilename = filedir + "/" + xian
            # if self.judgeinarea(latfilename, lat, lng):
            #     SpecificityOrderdata['inside'] = True
            # else:
            #     SpecificityOrderdata['inside'] = False
        # 成都
        elif city == 510100:
            if tripnum == 1:  # 1为接机
                latfilename = filedir + "/" + chengdujieji
            else:   # 2为送机
                latfilename = filedir + "/" + chengdusongji
            if self.judgeinarea(latfilename, lat, lng):
                SpecificityOrderdata['inside'] = True
            else:
                SpecificityOrderdata['inside'] = False
        jsondatar = json.dumps(SpecificityOrderdata, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
        return jsondatar

    def eastpick(self, pickpoint):
        eastfile = filedir + "/" + eastpick
        polys = sf.Reader(eastfile)
        polygon = polys.shapes()
        shpfilePoints = []
        for shape in polygon:
            shpfilePoints = shape.points
        polygon = Polygon(shpfilePoints)
        lng = pickpoint[1]
        lat = pickpoint[0]
        point = Point(lng, lat)
        if polygon.contains(point):
            return True
        else:
            return False

    def westpick(self, pickpoint):
        westfile = filedir + "/" + westpick
        polys = sf.Reader(westfile)
        polygon = polys.shapes()
        shpfilePoints = []
        for shape in polygon:
            shpfilePoints = shape.points
        polygon = Polygon(shpfilePoints)
        lng = pickpoint[1]
        lat = pickpoint[0]
        point = Point(lng, lat)
        if polygon.contains(point):
            return True
        else:
            return False


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@author:ai
@file:sendOrder.py
@time:2020/05/28
"""
import sys
import pandas as pd
from configs.Database import DEV
from tradingSystem.CATS.catsserverapi.catsConfig import CatsTypeTotradeAcct
from tradingSystem.CATS.catsserverapi.models.Account import LocalOsInfo
from tradingSystem.CATS.catsserverapi.RootNetToCats import RootNetToCats

def run(env=DEV, mode='test',strategyids: list = None,targetOrders: pd.DataFrame = None,T0TargetOrder=pd.DataFrame(), accountType='CASH'):
    rntc = RootNetToCats(env=env,mode=mode)
    accountAndstrategy = rntc.getAccountInfoByDB()
    for account, strategy_id in accountAndstrategy:
        if strategy_id not in strategyids: continue
        if CatsTypeTotradeAcct[account.tradeAcctType] != accountType: continue
        rntc.loadAlgoConfig(strategy_id, algo_type='AITWAP3')
        localInfo = LocalOsInfo()
        if rntc.login(account, localInfo):
            rntc.sendOrder(strategy_id, account, targetOrders, algo_id='AITWAP3')
            if accountType =='CASH':
                rntc.sendToOrder(strategy_id, account, T0TargetOrder, algo_id='AITWAP3')
            rntc.saveInstanceidToDB(type='twap')
    if rntc.rootNet:
        rntc.close()

if __name__ == '__main__':
    run(env=DEV, mode='test',strategyids=['S-L-4|LastPrice|CLOSE|RISK-169'])


import streamlit as st
import requests
import json
from dbnomics import fetch_series
import pandas as pd
from pandas.api.types import (
    is_categorical_dtype,
    is_datetime64_any_dtype,
    is_numeric_dtype,
)

import altair as alt

st.set_page_config(page_title="DB Nomics Marco Data Vizualizer", layout="wide")

state = st.session_state
if 'provider_code' not in state:
    state['provider_code'] = ""
if 'provider_name' not in state:
    state['provider_name'] = ""
if 'dataset_code' not in state:
    state['dataset_code'] = ""
if 'dataset_name' not in state:
    state['dataset_name'] = ""

@st.experimental_memo
def get_providers():
    limts_providers = {"limit": "1000", "offset": "0"}
    request_providers = requests.get("https://api.db.nomics.world/v22/providers",
                                     params=limts_providers)
    json_providers = json.loads(request_providers.text)
    providers = json_providers["providers"]["docs"]
    return [(provider["code"], provider["name"]) for provider in providers]

provider_details = get_providers()

selected_provider_name = st.selectbox(
    "Select a **provider**",
    [j for i, j in provider_details])

for item in provider_details:
    if item[1] == selected_provider_name:
        selected_provider_code = item[0]
        break

def change_provider(selected_provider_name, selected_provider_code):
    state['provider_name'] = selected_provider_name
    state['provider_code'] = selected_provider_code

st.button("**Load datasets**", on_click=change_provider,
          args=(selected_provider_name, selected_provider_code,))

@st.experimental_memo
def get_datasets(provider_code):
    limts_datasets = {"limit": "500", "offset": "0"}
    request_datasets = requests.get(
        f"https://api.db.nomics.world/v22/datasets/{provider_code}",
        params=limts_datasets)
    json_datasets = json.loads(request_datasets.text)
    datasets = json_datasets["datasets"]["docs"]
    datasets_number = json_datasets["datasets"]["num_found"]
    dataset_details = [(dataset["code"], dataset["name"], dataset["nb_series"],
                       dataset["nb_series"]) for dataset in datasets]
    return dataset_details, datasets_number

if state['provider_code'] == selected_provider_code:
    dataset_details, datasets_number = get_datasets(state['provider_code'])

if "dataset_details" not in globals():
   dataset_details = []
   selected_dataset_name = None
   selected_dataset_code = None
else:
    st.info(f"**Provider:** {state['provider_name']}"
            f"**Datasets:** {datasets_number}"
            f"**Link:** [DBNomics Provider Info]"
            f"(https://db.nomics.world/{state['provider_code']})"
            , icon="ℹ")
    if datasets_number > 50:
        st.warning(f"This alpha version can only show the first 50 datasets "
                   f"of each provider. {state['provider_name']} "
                   f"has {datasets_number} datasets.")

selected_dataset_name = st.selectbox(
    "Select a **dataset**",
    [j for i, j, k, o in dataset_details])

for item in dataset_details:
    if item[1] == selected_dataset_name:
        selected_dataset_code = item[0]
        selected_dataset_series = item[2]
        selected_dataset_updated = item[3]
        break

if dataset_details != []:
    st.info(f"**Dataset Code:** {selected_dataset_code} "
            f"**Series in Dataset:** {selected_dataset_series} "
            f"**Last update:** {selected_dataset_updated} "
            f"**Link:** [DBNomics Dataset Info]('https://db.nomics.world/"
            f"{state['provider_code']}/"
            f"{selected_dataset_code}')",
            icon="ℹ")
    if selected_dataset_series > 2000:
        st.warning("This dataset has more than 2000 series."
                   " Loading can take some time and might not be successful.")

@st.experimental_memo
def get_dataset_data(provider_code, dataset_code):
    return fetch_series(provider_code, dataset_code, max_nb_series=10000)

def filter_dataframe(df: pd.DataFrame) -> pd.DataFrame:
    """
    Adds a UI on top of a dataframe to let viewers filter columns

    Args:
        df (pd.DataFrame): Original dataframe

    Returns:
        pd.DataFrame: Filtered dataframe
    """

    df = df.copy()

    # Try to convert datetimes into a standard format (datetime, no timezone)
    # for col in df.columns:
    #     if is_object_dtype(df[col]):
    #         try:
    #             df[col] = pd.to_datetime(df[col])
    #         except Exception:
    #             pass

    #     if is_datetime64_any_dtype(df[col]):
    #         df[col] = df[col].dt.tz_localize(None)

    modification_container = st.container()

    with modification_container:
        to_filter_columns = st.multiselect("Filter dataframe on", df.columns)
        for column in to_filter_columns:
            left, right = st.columns((1, 20))
            # Treat columns with < 10 unique values as categorical
            if is_categorical_dtype(df[column]) or df[column].nunique() < 40:
                user_cat_input = right.multiselect(
                    f"Values for {column}",
                    df[column].unique(),
                    default=list(df[column].unique()),
                )
                df = df[df[column].isin(user_cat_input)]
            elif is_numeric_dtype(df[column]):
                _min = float(df[column].min())
                _max = float(df[column].max())
                step = (_max - _min) / 100
                user_num_input = right.slider(
                    f"Values for {column}",
                    min_value=_min,
                    max_value=_max,
                    value=(_min, _max),
                    step=step,
                )
                df = df[df[column].between(*user_num_input)]
            elif is_datetime64_any_dtype(df[column]):
                user_date_input = right.date_input(
                    f"Values for {column}",
                    value=(
                        df[column].min(),
                        df[column].max(),
                    ),
                )
                if len(user_date_input) == 2:
                    user_date_input = tuple(map(pd.to_datetime, user_date_input))
                    start_date, end_date = user_date_input
                    df = df.loc[df[column].between(start_date, end_date)]
            else:
                user_text_input = right.text_input(
                    f"Substring or regex in {column}",
                )
                if user_text_input:
                    df = df[df[column].astype(str).str.contains(user_text_input)]

    return df

def get_data(provider_code, dataset_code):
    df = get_dataset_data(provider_code, dataset_code)
    return filter_dataframe(df)

def change_dataset(selected_dataset_name, selected_dataset_code):
    state['dataset_name'] = selected_dataset_name
    state['dataset_code'] = selected_dataset_code

st.button("**Load data**",
    on_click=change_dataset,
    args=(selected_dataset_name,
    selected_dataset_code,))

if state['dataset_code'] != "":
    data = get_data(state['provider_code'], state['dataset_code'])
    st.dataframe(data)

    brush = alt.selection(type='interval', encodings=['x'])
    selection = alt.selection_multi(fields=['series_code'], bind='legend')

    upper = alt.Chart(data).mark_line().encode(
        x = alt.X('period:T', scale=alt.Scale(domain=brush)),
        y = 'value:Q',
        color = "series_code:N",
        opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
    ).properties(
        width=1000,
        height=300,
    ).add_selection(
    selection
    )

    lower = alt.Chart(data).mark_area().encode(
        x = 'period:T',
        y = 'max(value):Q'
    ).properties(
        width=1000,
        height=100,
    ).add_selection(brush)

    chart = upper & lower

    tab1, tab2 = st.tabs(["Chart 1", "Chart 2"])

    with tab1:
        st.altair_chart(chart, theme="streamlit", use_container_width=True)
    with tab2:
        st.write("Test")


#!/usr/bin/env python3

"""
Sample Input
10 4
1
2
-1
-2
2

Sample Output
0.7696
"""

# if speeds[i] == 0:

def strangeClock(L, T, speeds):
    if not speeds or L == 0:
        print("{0:0.7f}".format(0))
    elif T == 0:
        failProb = ((L-1)/L) ** len(speeds)
        print("{0:0.7f}".format(1 - failProb))
    else:
        failProb = .0
        flag = False
        lens = len(speeds)
        for i in range(lens):
            x = abs(T * speeds[i])
            if x < L:
                if not flag:
                    flag = True
                    failProb = (L - x) / L
                else:
                    failProb *= (L - x) / L
        print("{0:0.7f}".format(1 - failProb))

if __name__ == '__main__':
    speeds = []
    inp = list(map(int, input().split(" ")))
    for _ in range(inp[1]):
        speeds.append(int(input()))
    T = int(input())
    strangeClock(inp[0], T, speeds)


import numpy as np
#from pyGITR.math_helper import *
from typing import Callable
import matplotlib.pyplot as plt
import pydoc
import netCDF4
import os

class Sputtering_and_reflection():

    def ShowAvailableProjectiles(self):
        for D in ['H', 'D', 'T', 'He4', 'Si', 'C', 'W']:
            print(D)

    def ShowAvailableTargets(self):
        for D in ['C', 'Si', 'W', 'SiC']:
            print(D)

    # these parameter values are hard-coded. Want to put it in a text file separately
    @classmethod
    def Set_PhysicalSputteringParameters(cls, Projectile, Target):
        if Projectile == 'H' and Target =='C':
            cls.lambda_parameter = 1.3533
            cls.q_parameter = 0.0241
            cls.mu_parameter = 1.4103
            cls.Eth_parameter = 38.630 # in eV

        elif Projectile == 'D' and Target =='C':
            cls.lambda_parameter = 1.2848
            cls.q_parameter = 0.0539
            cls.mu_parameter = 1.1977
            cls.Eth_parameter = 27.770 # in eV
        elif Projectile == 'T' and Target =='C':
            cls.lambda_parameter = 1.9050
            cls.q_parameter = 0.0718
            cls.mu_parameter = 1.1512
            cls.Eth_parameter = 23.617 # in eV
        elif Projectile == 'He4' and Target =='C':
            cls.lambda_parameter = 4.5910
            cls.q_parameter = 0.1951
            cls.mu_parameter = 1.7852
            cls.Eth_parameter = 19.124 # in eV
        elif Projectile == 'C' and Target =='C':
            cls.lambda_parameter = 13.9666
            cls.q_parameter = 0.7015
            cls.mu_parameter = 2.0947
            cls.Eth_parameter = 21.4457 # in eV
        elif Projectile == 'W' and Target =='C':  # Carolina Bjorkas
            cls.lambda_parameter = 1.2625
            cls.q_parameter = 1.3902
            cls.mu_parameter = 3.5395
            cls.Eth_parameter = 114.9398 # in eV

        elif Projectile == 'Si' and Target =='C': # Fit with RUSTBCA simulations
            cls.lambda_parameter = 1.0
            cls.q_parameter = 1.8
            cls.mu_parameter = 0.3
            cls.Eth_parameter = 10.457 # in eV

        elif Projectile == 'H' and Target =='Si':
            cls.lambda_parameter = 0.4819
            cls.q_parameter = 0.0276
            cls.mu_parameter = 0.9951
            cls.Eth_parameter = 49.792 # in eV

        elif Projectile == 'D' and Target =='Si':
            cls.lambda_parameter = 0.5326
            cls.q_parameter = 0.0569
            cls.mu_parameter = 1.6537
            cls.Eth_parameter = 24.543 # in eV

        elif Projectile == 'T' and Target =='Si':
            cls.lambda_parameter = 0.4112
            cls.q_parameter = 0.0816
            cls.mu_parameter = 0.9325
            cls.Eth_parameter = 21.298 # in eV
        elif Projectile == 'He4' and Target =='Si':
            cls.lambda_parameter = 0.2524
            cls.q_parameter = 0.2319
            cls.mu_parameter = 1.4732
            cls.Eth_parameter = 18.899 # in eV
        elif Projectile == 'Si' and Target =='Si':
            cls.lambda_parameter = 0.6726
            cls.q_parameter = 2.6951
            cls.mu_parameter = 1.7584
            cls.Eth_parameter = 20.035 # in eV
        elif Projectile == 'C' and Target =='Si':  # Fit with RUSTBCA simulations
            cls.lambda_parameter = 1.0
            cls.q_parameter = 1.4
            cls.mu_parameter = 12.0
            cls.Eth_parameter = 14 # in eV
        elif Projectile == 'W' and Target =='Si':
            print('Choose a different set of projectile and target, data not available for W->Si')
        elif Projectile == 'H' and Target =='W':
            cls.lambda_parameter = 1.0087
            cls.q_parameter = 0.0075
            cls.mu_parameter = 1.2046
            cls.Eth_parameter = 457.42 # in eV
        elif Projectile == 'D' and Target =='W':
            cls.lambda_parameter = 0.3583
            cls.q_parameter = 0.0183
            cls.mu_parameter = 1.4410
            cls.Eth_parameter = 228.84 # in eV
        elif Projectile == 'T' and Target =='W':
            cls.lambda_parameter = 0.2870
            cls.q_parameter = 0.0419
            cls.mu_parameter = 1.5802
            cls.Eth_parameter = 153.8842 # in eV
        elif Projectile == 'He4' and Target =='W':
            cls.lambda_parameter = 0.1692
            cls.q_parameter = 0.1151
            cls.mu_parameter = 1.7121
            cls.Eth_parameter = 120.56 # in eV
        elif Projectile == 'C' and Target =='W':  # Carolina Bjorkas
            cls.lambda_parameter = 0.0447
            cls.q_parameter = 1.5622
            cls.mu_parameter = 1.0200
            cls.Eth_parameter = 59.1980  # in eV
        elif Projectile == 'W' and Target =='W':
            cls.lambda_parameter = 2.2697
            cls.q_parameter = 18.6006
            cls.mu_parameter = 3.1273
            cls.Eth_parameter = 24.9885 # in eV

        elif Projectile == 'C' and Target =='SiC':  # from RustBCA
            cls.lambda_parameter = 1.0
            cls.q_parameter = 2.0
            cls.mu_parameter = 1.3
            cls.Eth_parameter = 25 # in eV

        elif Projectile == 'Si' and Target =='SiC': # from RustBCA
            cls.lambda_parameter = 2.0
            cls.q_parameter = 4.0
            cls.mu_parameter = 1.3
            cls.Eth_parameter = 70 # in eV

        elif Projectile == 'H' and Target =='SiC': # from RustBCA
            cls.lambda_parameter = 2.2
            cls.q_parameter = 0.031
            cls.mu_parameter = 1.5
            cls.Eth_parameter = 40 # in eV

        elif Projectile == 'Si' and Target =='W':
            print('Choose a different set of projectile and target, data not available for Si-> W')
        else:
            print('Choose a different set of projectile and target')

    @classmethod
    def Set_Mass_AtomicN(cls, Projectile, Target):
        if Projectile == 'H':
            cls.Projectile_Mass = 1
            cls.Projectile_AtomicN = 1
        elif Projectile == 'D':
            cls.Projectile_Mass = 2.014
            cls.Projectile_AtomicN = 1
        elif Projectile == 'T':
            cls.Projectile_Mass = 3.016
            cls.Projectile_AtomicN= 1
        elif Projectile == 'He4':
            cls.Projectile_Mass = 4
            cls.Projectile_AtomicN = 2
        elif Projectile == 'Si':
            cls.Projectile_Mass = 28.0855
            cls.Projectile_AtomicN = 14
        elif Projectile == 'C':
            cls.Projectile_Mass = 12.011
            cls.Projectile_AtomicN = 6
        elif Projectile == 'W':
            cls.Projectile_Mass = 183.84
            cls.Projectile_AtomicN = 74

        if Target == 'C':
            cls.Target_Mass = 12.011
            cls.Target_AtomicN = 6
        elif Target == 'Si':
            cls.Target_Mass = 28.0855
            cls.Target_AtomicN = 14
        elif Target == 'W':
            cls.Target_Mass = 183.84
            cls.Target_AtomicN = 74
        elif Target == 'SiC':
            cls.Target_Mass = 40
            cls.Target_AtomicN = 20

    @classmethod
    def Set_ReflectionParameters(cls, Projectile, Target):
        if Projectile == 'C' and Target =='C':
            cls.a_1 = -0.03022
            cls.a_2 = -1.107
            cls.a_3 = 6.544
            cls.a_4 = 0.1256
        elif Projectile == 'C' and Target =='W':
            cls.a_1 = 1.96
            cls.a_2 = 0.1
            cls.a_3 = 2.2
            cls.a_4 = 0.18
        elif Projectile == 'W' and Target =='W':
            cls.a_1 = -3.685
            cls.a_2 = 0.02781
            cls.a_3 = 0.7825e-4
            cls.a_4 = -1.109
        elif Projectile == 'Si' and Target =='Si':
            cls.a_1 = -0.8631e1
            cls.a_2 = 0.6888e-1
            cls.a_3 = 0.1808e-1
            cls.a_4 = -0.8577

        else:
            print('Choose a different set of projectile and target')

    @classmethod
    def Calculate_PhysicalSputtering_RotationFactor(cls, Projectile, Target, Incident_Energy, Incident_Theta):

        flag = 0 # change it to zero if not found from the list

        from scipy.interpolate import interp1d

        if Projectile == 'H' and Target =='C':
            Sputtering_Dictionary = Sputtering_Rotation_H_C

        elif Projectile == 'D' and Target =='C':
            Sputtering_Dictionary = Sputtering_Rotation_D_C

        elif Projectile == 'T' and Target =='C':
            Sputtering_Dictionary = Sputtering_Rotation_T_C

        elif Projectile == 'C' and Target =='C':
            Sputtering_Dictionary = Sputtering_Rotation_C_C

        elif Projectile == 'D' and Target =='Si':
            Sputtering_Dictionary = Sputtering_Rotation_D_Si

        elif Projectile == 'Si' and Target =='Si':
            Sputtering_Dictionary = Sputtering_Rotation_Si_Si

        elif Projectile == 'H' and Target =='W':
            Sputtering_Dictionary = Sputtering_Rotation_H_W

        elif Projectile == 'D' and Target =='W':
            Sputtering_Dictionary = Sputtering_Rotation_D_W

        elif Projectile == 'T' and Target =='W':
            Sputtering_Dictionary = Sputtering_Rotation_T_W

        elif Projectile == 'W' and Target =='W':
            Sputtering_Dictionary = Sputtering_Rotation_W_W

        elif Projectile == 'W' and Target =='C':
            Sputtering_Dictionary = Sputtering_Rotation_W_C

        elif Projectile == 'C' and Target =='W':
            Sputtering_Dictionary = Sputtering_Rotation_C_W

        else:
            flag = 1

        if flag == 0:
            E0_array =  np.array(Sputtering_Dictionary['E0'])
            f_array = np.array(Sputtering_Dictionary['f'])
            b_array = np.array(Sputtering_Dictionary['b'])
            c_array = np.array(Sputtering_Dictionary['c'])
            Theta0_star_array = np.array(Sputtering_Dictionary['Theta0_star'])

            f_interpolate = interp1d(E0_array,f_array,bounds_error=False,fill_value="extrapolate")
            b_interpolate = interp1d(E0_array, b_array,bounds_error=False,fill_value="extrapolate")
            c_interpolate = interp1d(E0_array, c_array,bounds_error=False,fill_value="extrapolate")
            Theta0star_interpolate = interp1d(E0_array, Theta0_star_array,bounds_error=False,fill_value="extrapolate")

            cosine_factor = np.cos((np.pi*0.5*Incident_Theta/Theta0star_interpolate(Incident_Energy))**c_interpolate(Incident_Energy))

            factor = (cosine_factor)**(-f_interpolate(Incident_Energy)) * np.exp(b_interpolate(Incident_Energy)*(1-(1/cosine_factor) ))

            if factor>1000000:
                factor = 1
            elif np.isnan(factor):
                factor = 1
            #print("factor is   ",factor)
            return factor

        else:
            return 1

    def Calculate_PhysicalSputteringParameters(self, Projectile, Target, Incident_Energy, Incident_Theta:float=0.0):
        Sputtering_and_reflection.Set_PhysicalSputteringParameters(Projectile,Target)
        Sputtering_and_reflection.Set_Mass_AtomicN(Projectile,Target)

        electric_charge_square = 1.4399 # eV nm
        Bohr_radius = 0.0529177 # nm

        Lindhard_length = (9*np.pi**2/128)**(1/3) * Bohr_radius * (self.Target_AtomicN**(2/3)+ self.Projectile_AtomicN**(2/3))**(-0.5)  # nm

        epsilon = Incident_Energy*(self.Target_Mass/(self.Projectile_Mass + self.Target_Mass))* (Lindhard_length/(self.Projectile_AtomicN*self.Target_AtomicN)*electric_charge_square)
        Nuclear_stopping = (0.5*np.log(1+1.2288*epsilon))/(epsilon + 0.1728*np.sqrt(epsilon) + 0.008*epsilon**0.1504)

        #Y = self.q_parameter*Nuclear_stopping*((Incident_Energy/self.Eth_parameter)-1)**self.mu_parameter/(self.lambda_parameter + ((Incident_Energy/self.Eth_parameter)-1)**self.mu_parameter)

        Numerator = ((Incident_Energy/self.Eth_parameter)-1)

        if Numerator < 0:
            Numerator = 0.0

        Y = self.q_parameter*Nuclear_stopping*Numerator**self.mu_parameter/(self.lambda_parameter + Numerator**self.mu_parameter)

        if (Incident_Theta>0.0):
            Y = Sputtering_and_reflection.Calculate_PhysicalSputtering_RotationFactor(Projectile, Target, Incident_Energy, Incident_Theta)*Y

        return Y

    def Calculate_ReflectionCoefficients(self, Projectile, Target, Incident_Energy):
        Sputtering_and_reflection.Set_ReflectionParameters(Projectile,Target)
        Sputtering_and_reflection.Set_Mass_AtomicN(Projectile,Target)

        electric_charge_square = 1.4399 # eV nm
        Bohr_radius = 0.0529177 # nm

        Lindhard_length = (9*np.pi**2/128)**(1/3) * Bohr_radius * (self.Target_AtomicN**(2/3)+ self.Projectile_AtomicN**(2/3))**(-0.5)  # nm

        epsilon_L = ((self.Target_Mass + self.Projectile_Mass)/self.Target_Mass)*(self.Target_AtomicN*self.Projectile_AtomicN*electric_charge_square/Lindhard_length)

        epsilon = Incident_Energy/epsilon_L

        R_N = np.exp(self.a_1*epsilon**self.a_2)/(1+np.exp(self.a_3*epsilon**self.a_4))

        return R_N.real

class Physical_Sputtering_Reflection_Plots():

    @classmethod
    def Sputtering_yields(cls, Projectile, Target,Energies):

        s_plot = Sputtering_and_reflection()

        #Energies = np.linspace(460,1e5,10000)
        Sputtering = np.zeros(Energies.size)
        counter = 0

        for energy in Energies:

            Sputtering[counter] = s_plot.Calculate_PhysicalSputteringParameters(Projectile,Target,energy).real
            counter = counter + 1

        return Sputtering

    @classmethod
    def Reflection_yields(cls, Projectile, Target, Energies):

        s_plot = Sputtering_and_reflection()

        #Energies = np.linspace(20,1e5,10000)
        Reflection = np.zeros(Energies.size)
        counter = 0

        for energy in Energies:

            Reflection[counter] = s_plot.Calculate_ReflectionCoefficients(Projectile,Target,energy).real
            counter = counter + 1

        return Reflection
       #plt.plot(Energies,Sputtering)

#s = Sputtering_and_reflection()
#s.ShowAvailableTargets()


import fcntl
import os
import socket
import struct
from threading import Thread
from time import sleep
import time
import sys
import re
import errno

from discovery.discovery_report import DiscoveryReport

RUNNING = True
MCAST_GRP = '239.255.255.250'
detected_bulbs = {}
bulb_idx2ip = {}
scan_socket = None
listen_socket = None

devices = []

def yeelight_discovery():
    print("START SCANNING LAN FOR YEELIGHT DEVICES")
    print("This operation may take a while...")
    global scan_socket, listen_socket
    # Socket setup
    scan_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    fcntl.fcntl(scan_socket, fcntl.F_SETFL, os.O_NONBLOCK)
    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    listen_socket.bind(("", 1982))
    fcntl.fcntl(listen_socket, fcntl.F_SETFL, os.O_NONBLOCK)
    mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
    listen_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    # Give socket some time to set up
    sleep(2)

    # First discover the lamp and connect to the lamp, with the bulb detection thread
    detection_thread = Thread(target=bulbs_detection_loop)
    detection_thread.start()
    # Give detection thread some time to collect bulb info
    sleep(10)
    max_wait = 0
    while len(bulb_idx2ip) == 0 and max_wait < 10:
        # Wait for 10 seconds to see if some bulb is present
        # The number of seconds could be extended if necessary
        sleep(1)
        max_wait += 1

    if len(bulb_idx2ip) == 0:
        print("Bulb list is empty.")
    else:
        sleep(15)
        global devices
        devices = display_bulbs()

    # Stop bulb detection loop
    global RUNNING
    RUNNING = False
    detection_thread.join()
    print("FINISH SCANNING FOR YEELIGHT DEVICES")
    return

def display_bulb(idx):
    """
    Display a bulb found in the network and returns a Discovery Report object
    """
    if idx not in bulb_idx2ip:
        print("error: invalid bulb idx")
        return None
    bulb_ip = bulb_idx2ip[idx]
    model = detected_bulbs[bulb_ip][1]
    power = detected_bulbs[bulb_ip][2]
    bright = detected_bulbs[bulb_ip][3]
    rgb = detected_bulbs[bulb_ip][4]
    host_port = detected_bulbs[bulb_ip][5]
    print(str(idx) + ": ip=" \
          + bulb_ip + ",model=" + model \
          + ",power=" + power + ",bright=" \
          + bright + ",rgb=" + rgb)
    return DiscoveryReport(result="Yeelight discovery", protocol="yeelight",
                           timestamp=time.time(), ip=bulb_ip, port=host_port)

def display_bulbs():
    """
    Display all bulbs found in the network and returns a list of lamps
    """
    lamps = []
    print(str(len(detected_bulbs)) + " managed bulbs")
    for i in range(1, len(detected_bulbs) + 1):
        lamps.append(display_bulb(i))
    return lamps

def send_search_broadcast():
    """
    Multicast search request to all hosts in LAN, do not wait for response
    """
    print("send_search_broadcast running")
    multicase_address = (MCAST_GRP, 1982)
    msg = "M-SEARCH * HTTP/1.1\r\n"
    msg = msg + "HOST: 239.255.255.250:1982\r\n"
    msg = msg + "MAN: \"ssdp:discover\"\r\n"
    msg = msg + "ST: wifi_bulb"
    scan_socket.sendto(msg.encode(), multicase_address)

def bulbs_detection_loop():
    """
    A standalone thread broadcasting search request and listening on all responses
    """
    print("bulbs_detection_loop running")
    search_interval = 30000
    read_interval = 100
    time_elapsed = 0

    while RUNNING:
        if time_elapsed % search_interval == 0:
            send_search_broadcast()

        # Scanner
        while True:
            try:
                data = scan_socket.recv(2048)
            except socket.error as e:
                err = e.args[0]
                if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
                    break
                else:
                    print(e)
                    sys.exit(1)
            handle_search_response(data)

        # Passive listener
        while True:
            try:
                data, addr = listen_socket.recvfrom(2048)
            except socket.error as e:
                err = e.args[0]
                if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
                    break
                else:
                    print(e)
                    sys.exit(1)
            handle_search_response(data)

        time_elapsed += read_interval
        sleep(read_interval / 1000.0)
    scan_socket.close()
    listen_socket.close()
    sys.exit()

def get_param_value(data, param):
    """
    Match line of 'param = value'
    """
    param_re = re.compile(param + ":\s*([ -~]*)")  # Match all printable characters
    match = param_re.search(data.decode())
    if match is not None:
        value = match.group(1)
        return value

def get_support_value(data):
    """
    Match line of 'support = value'
    """
    support_re = re.compile("support" + ":\s*([ -~]*)")  # Match all printable characters
    match = support_re.search(data.decode())
    if match is not None:
        value = match.group(1)
        return value

def handle_search_response(data):
    """
    Parse search response and extract all interested data
    If new bulb is found, insert it into dictionary of managed bulbs
    """
    location_re = re.compile("Location.*yeelight[^0-9]*([0-9]{1,3}(\.[0-9]{1,3}){3}):([0-9]*)")
    match = location_re.search(data.decode())
    if match is None:
        # logging.error("invalid data received: " + data.decode())
        return

    host_ip = match.group(1)
    if host_ip in detected_bulbs:
        bulb_id = detected_bulbs[host_ip][0]
    else:
        bulb_id = len(detected_bulbs) + 1
    host_port = match.group(3)
    model = get_param_value(data, "model")
    power = get_param_value(data, "power")
    bright = get_param_value(data, "bright")
    rgb = get_param_value(data, "rgb")
    supported_methods = get_support_value(data).split(sep=None)
    # print(supported_methods)
    # Use two dictionaries to store index->ip and ip->bulb map

    detected_bulbs[host_ip] = [bulb_id, model, power, bright, rgb, host_port, supported_methods]
    bulb_idx2ip[bulb_id] = host_ip

def main():
    yeelight_discovery()
    global devices
    return devices

if __name__ == '__main__':
    main()


#dfs
import sys
sys.setrecursionlimit(10**5)

def dfs(v, graph, visited):
    visited[v] = 1 # 방문 처리
    for i in graph[v]:
        if visited[i] == 0: # 아직 방문을 하지 않음
            dfs(i, graph,visited)

def solution(n,m,graph):
    answer = 0
    visited = [0]*(n+1)
    for i in range(1, n+1):
        if visited[i] == 0: # 아직 방문하지 않은 노드
            dfs(i, graph, visited)
            answer += 1
    print(answer)

#n,m = map(int, input().split()) # 노드, 간선
n, m = map(int, sys.stdin.readline().rstrip().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
    u,v = map(int, sys.stdin.readline().rstrip().split())
    #u,v = map(int, input().split())
    graph[u].append(v)
    graph[v].append(u)
solution(n,m,graph)


from timeit import timeit

def caesarCipherEncryptor(string, key):
    # Write your code here.
    res = []
    key %= 26
    for char in string:
        newCode = (ord(char) + key - 97) % 26 + 97
        res.append(chr(newCode))
    return "".join(res)

def caesarCipherEncryptor_sol1(string, key):
    # Write your code here.
    res = []
    newKey = key % 26
    for char in string:
        res.append(getNewLetter1(char, newKey))
    return "".join(res)

def getNewLetter1(char, key):
    alphabet = list("abcdefghijklmnopqrstuvwxyz")
    newLetterCode = alphabet.index(char) + key
    return alphabet[newLetterCode % 26]

def caesarCipherEncryptor_sol2(string, key):
    # Write your code here.
    res = []
    newKey = key % 26
    for char in string:
        res.append(getNewLetter2(char, newKey))
    return "".join(res)

def getNewLetter2(char, key):
    newLetterCode = ord(char) + key
    return (chr(newLetterCode) if newLetterCode <= 122 else
            chr(96 + newLetterCode % 122))

print(caesarCipherEncryptor("xyz", 2))

string = "asdfghjkjhgfdsaasdkjhasdlkjhmasd"
itr = 100_000

for foo in [caesarCipherEncryptor, caesarCipherEncryptor_sol1,
            caesarCipherEncryptor_sol2]:
    t = timeit(stmt="foo(string, 2)", number=itr, globals=globals())
    print(f"{foo.__name__} runed in {t:.6f} seconds")


# -*- coding: utf-8 -*-
"""
Created on Tue Jan 23 02:22:23 2018

@author: RAJAT
"""

import numpy as np
from time import time
from keras.models import Sequential
from keras.layers import Dense, Dropout , Activation,Flatten,Convolution2D, MaxPooling2D ,AveragePooling2D
from keras.callbacks import TensorBoard
# This is where we create the model for training purpose
# 1.  we create a function self_driving
#     returns a model
# 2.  we create a function to save
move_encode = {
            'W':np.array([1,0,0,0,0]).reshape(1,5),
            'S':np.array([0,1,0,0,0]).reshape(1,5),
            'A':np.array([0,0,1,0,0]).reshape(1,5),
            'D':np.array([0,0,0,1,0]).reshape(1,5),
            '.':np.array([0,0,0,0,1]).reshape(1,5),
        }

move_decode ={
            0:'W',
            1:'S',
            2:'A',
            3:'D',
            4:'.'
        }

def encode_movement(move):
    try:
        return move_encode[move[0]]
    except (KeyError , IndexError) as e:
        return move_encode['.']

def self_driving(shape):
    model = Sequential()
    model.add(Convolution2D(512 , kernel_size=(2,2), strides=(1,1) , padding='valid' , activation='relu', input_shape=shape))
    model.add(Convolution2D(128 , kernel_size=(1,1), strides=(1,1) , padding='valid' , activation='relu', input_shape=shape))
    model.add(Convolution2D(256 , kernel_size=(2,2), strides=(1,1) , padding='valid' , activation='relu', input_shape=shape))
    model.add(AveragePooling2D(pool_size=(2,2)))
    model.add(Convolution2D(64 , kernel_size=(1,1), strides=(1,1) , padding='valid' , activation='relu', input_shape=shape))
    model.add(Convolution2D(128 , kernel_size=(2,2), strides=(2,2) , padding='valid' , activation='relu', input_shape=shape))
    model.add(AveragePooling2D(pool_size=(2,2)))
    model.add(Convolution2D(32 , kernel_size=(1,1), strides=(1,1) , padding='valid' , activation='relu', input_shape=shape))
    model.add(Convolution2D(64 , kernel_size=(2,2), strides=(3,3) , padding='valid' , activation='relu', input_shape=shape))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(256, activation='relu'))
    model.add(Dropout(0.25))
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.25))
    model.add(Dense(64, activation='relu'))
    model.add(Dense(32, activation='relu'))
    model.add(Dense(5, activation='softmax'))
    model.compile(loss='categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])
    return model

def save_model(model,name):
     model_json = model.to_json()
     with open(name+".json", "w") as json_file:
         json_file.write(model_json)
     model.save_weights(name+".h5")
     print("\n SAVED THE WEIGHTS AND MODEL !!!!")

def load_model_weights(name):
    from keras.models import model_from_json
    json_file = open(name+'.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    loaded_model.load_weights(name+".h5")
    loaded_model.compile(loss='categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])
    return loaded_model

if __name__ == '__main__':
    from datacollect import load_train_data
    X_train , Y_train = load_train_data()
    model = load_model_weights('v1_nfs_ai')
    #model = self_driving(X_train[0].shape)
    for i in range(100):
        model.fit(X_train, Y_train,
              batch_size=30,nb_epoch=1, verbose=1)
        save_model(model , "v1_nfs_ai")