import plotly.graph_objects as go
import plotly.express as px

# -------------------------------------------Plot Pie Chart--------------------

def plotpie(labels, values, title, height=450, width=450):
    layout = go.Layout(title=title, height=height, width=width)
    fig = go.Figure(layout=layout)
    fig.add_trace(go.Pie(labels=labels, values=values, title='Genre', textinfo='label+percent', hole=0.2,
                         marker=dict(colors=['#f7d468', '#74cb35'],
                                     line_color='Gray',
                                     line_width=1),
                         textfont={'color': '#000', 'size': 12},
                         textfont_size=12))
    return fig

# --------------------------------Plot Bar Chart------------------------

def plotBar(x, y, title, xlabel, ylabel, width=600, height=500):

    layout = go.Layout(title=title,
                       xaxis=dict(title=xlabel),
                       yaxis=dict(title=ylabel), width=width, height=height)
    fig = go.Figure(layout=layout)
    fig.add_trace(go.Bar(x=x, y=y))
    return fig

# -------------------------------Plot GroupBAR Chart-----------------------

def plotGroupedBar(datapoints, categories, title, xlabel, ylabel, colors=['indianred', 'lightsalmon']):
    #layout=go.Layout(title=go.layout.Title(text="Number of Fiction Book published per Year."), hovermode='closest',xaxis=dict(title='Number Of Books', type='log', autorange=True),yaxis=dict(title='Years', type='log', autorange=True))

    layout = go.Layout(title=title,
                       xaxis=dict(title=xlabel),
                       yaxis=dict(title=ylabel))
    fig = go.Figure(layout=layout)

    for category, point, color in zip(categories, datapoints, colors):
        fig.add_trace(go.Bar(x=point.index, y=point.values,
                             name=category, marker_color=color))

    return fig

# ------------------------------------------

def plotLine(x, y, title, xlabel, ylabel, template="plotly_dark"):
    layout = go.Layout(title=title,
                       xaxis=dict(title=xlabel),
                       yaxis=dict(title=ylabel), template=template)
    fig = go.Figure(layout=layout)
    fig.add_trace(go.Line(x=x, y=y, line_color='#f63366'))
    return fig

def plotMultiLine(datapoints, title, xlabel, ylabel, template="plotly_dark"):
    layout = go.Layout(title=title,
                       xaxis=dict(title=xlabel),
                       yaxis=dict(title=ylabel), template=template)
    fig = go.Figure(layout=layout)

    for datapoint in datapoints:
        fig.add_trace(go.Line(x=datapoint.get('x'),
                              y=datapoint.get('y'), line_color='#f63366'))
    return fig

# --------------------------------

def plotHistogram(datapoints, title, xlabel, ylabel):
    layout = go.Layout(title=title,
                       xaxis=dict(title=xlabel),
                       yaxis=dict(title=ylabel))
    fig = go.Figure(layout=layout)

    fig.update_layout(template="ggplot2")
    fig.add_trace(go.Histogram(
        x=datapoints.values,
        # xbins = {'start': 1, 'size': 0.1, 'end' : 5}
    ))

    return fig

def plotScatter(data, x, y, color, title, template="plotly_dark"):
    fig = px.scatter(data_frame=data, x=x, y=y, color=color,
                     title=title)

    fig.update_traces(marker=dict(size=10,
                                  line=dict(width=2,
                                            color='DarkSlateGrey')),
                      selector=dict(mode='markers'))
    fig.update_layout(width=1000, height=500, template=template)

    return fig

def plotScatter1(data, x, y, title, template="plotly_dark"):
    fig = px.scatter(data_frame=data, x=x, y=y, title=title)

    fig.update_traces(marker=dict(color='rgb(249, 6, 6)',
                                  line=dict(color='rgb(0,0,0)', width=1.0)), mode='lines+markers')
    fig.update_layout(template=template)

    return fig

def plotMultiScatter1(datapoints, title, xlabel, ylabel, names, colors=['#f7d468', 'purple', '#b3d236'], template="plotly_dark"):

    layout = go.Layout(title=title,
                       xaxis=dict(title=xlabel),
                       yaxis=dict(title=ylabel))

    fig = go.Figure(layout=layout)

    for point, name, col in zip(datapoints, names, colors):
        fig.add_trace(go.Scatter(x=point.get('x'),
                                 y=point.get('y'), name=name, line=dict(color=col)))

    # fig.update_traces(marker=dict(color='#74cb35',
        # line=dict(color='rgb(0,0,0)', width=1.0)), mode='lines+markers')
    fig.update_layout(template=template)

    return fig


from electroncash.i18n import _
from electroncash.plugins import run_hook
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QFileDialog

from .util import ButtonsTextEdit, MessageBoxMixin, ColorScheme

class ShowQRTextEdit(ButtonsTextEdit):

    def __init__(self, text=None):
        ButtonsTextEdit.__init__(self, text)
        self.setReadOnly(1)
        self.addButton(":icons/qrcode.png", self.qr_show, _("Show as QR code"))

        run_hook('show_text_edit', self)

    def qr_show(self):
        from .qrcodewidget import QRDialog
        try:
            s = str(self.toPlainText())
        except:
            s = self.toPlainText()
        QRDialog(s).exec_()

    def contextMenuEvent(self, e):
        m = self.createStandardContextMenu()
        m.addAction(_("Show as QR code"), self.qr_show)
        m.exec_(e.globalPos())

class ScanQRTextEdit(ButtonsTextEdit, MessageBoxMixin):

    def __init__(self, text="", allow_multi=False):
        ButtonsTextEdit.__init__(self, text)
        self.allow_multi = allow_multi
        self.setReadOnly(0)
        self.addButton(":icons/file.png", self.file_input, _("Read file"))
        icon = ":icons/qrcode_white.png" if ColorScheme.dark_scheme else ":icons/qrcode.png"
        self.addButton(icon, self.qr_input, _("Read QR code"))
        run_hook('scan_text_edit', self)

    def file_input(self):
        fileName, __ = QFileDialog.getOpenFileName(self, 'select file')
        if not fileName:
            return
        try:
            with open(fileName, "r", encoding='utf-8') as f:
                data = f.read()
        except UnicodeDecodeError as reason:
            self.show_critical(_("The selected file appears to be a binary file.") +"\n"+ _("Please ensure you only import text files."), title=_("Not a text file"))
            return
        self.setText(data)

    def qr_input(self):
        from electroncash import qrscanner, get_config
        try:
            data = qrscanner.scan_barcode(get_config().get_video_device())
        except BaseException as e:
            self.show_error(str(e))
            data = ''
        if not data:
            data = ''
        if self.allow_multi:
            new_text = self.text() + data + '\n'
        else:
            new_text = data
        self.setText(new_text)
        return data

    def contextMenuEvent(self, e):
        m = self.createStandardContextMenu()
        m.addAction(_("Read QR code"), self.qr_input)
        m.exec_(e.globalPos())


import pandas as pd

LV95_PROJECTION = {'init': 'epsg:2056'}

GWR_HEADERS = [
    'federal_id',
    'official_building_number',
    'building_designation',
    'canton',
    'district_number',
    'district_name',
    'e_coordinate',
    'n_coordinate',
    'coordinate_origin',
    'building_category',
    'building_class',
    'building_status',
    'construction_year',
    'construction_month',
    'construction_period',
    'demolition_year',
    'building_area',
    'building_volume',
    'building_volume_norm',
    'building_volume_source',
    'number_floors',
    'number_apartments',
    'number_living_rooms',
    'civil_defence_room',
    'energy_reference_area',
    'heating_tech_1',
    'heating_tech_2',
    'heating_source_1',
    'heating_source_2',
    'heating_info_source_1',
    'heating_info_source_2',
    'heating_update_date_1',
    'heating_update_date_2',
    'hot_water_tech_1',
    'hot_water_tech_2',
    'hot_water_source_1',
    'hot_water_source_2',
    'hot_water_info_source_1',
    'hot_water_info_source_2',
    'hot_water_update_date_1',
    'hot_water_update_date_2',
    'local_code_1',
    'local_code_2',
    'local_code_3',
    'local_code_4',
    'quarter',
    'update_date',
    'export_date'
]

HEATING_TECH = {
    7400: "None",
    7410: "HeatPump",
    7411: "HeatPump",
    7420: "SolarThermal",
    7421: "SolarThermal",
    7430: "Boiler",
    7431: "Boiler",
    7432: "Boiler",
    7433: "Boiler",
    7434: "Boiler",
    7435: "Boiler",
    7436: "Boiler",
    7440: "Cogeneration",
    7441: "Cogeneration",
    7450: "Resistance",
    7451: "Resistance",
    7452: "Resistance",
    7460: "HeatExchanger",
    7461: "HeatExchanger",
    7499: "Unknown"
}

HOT_WATER_TECH = {
    7600: "None",
    7610: "HeatPump",
    7620: "SolarThermal",
    7630: "Boiler",
    7632: "Boiler",
    7634: "Boiler",
    7640: "Cogeneration",
    7650: "Resistance",
    7651: "Resistance",
    7660: "HeatExchanger",
    7699: "Unknown"
}

ENERGY_HEAT_SOURCE = {
    7500: 'None',
    7501: "Air",
    7510: "Ground",
    7511: "Ground",
    7512: "Ground",
    7513: "Water",
    7520: "Gas",
    7530: "Oil",
    7540: "Wood",
    7541: "Wood",
    7542: "Wood",
    7543: "Wood",
    7550: "ExhaustHeat",
    7560: "Electricity",
    7570: "Sun",
    7580: "DistrictHeating",
    7581: "DistrictHeating",
    7582: "DistrictHeating",
    7598: "Unknown",
    7599: "Unknown"
}

BUILDING_TYPE = {
    1110: "SINGLE_RES",
    1121: "MULTI_RES",
    1122: "MULTI_RES",
    1130: "MULTI_RES",
    1211: "HOTEL",
    1212: "HOTEL",
    1220: "OFFICE",
    1230: "RETAIL",
    1231: "RESTAURANT",
    1241: "PARKING",
    1242: "PARKING",
    1251: "INDUSTRIAL",
    1252: "INDUSTRIAL",
    1261: "LIBRARY",
    1262: "LIBRARY",
    1263: "SCHOOL",
    1264: "HOSPITAL",
    1265: "GYM",
    1271: "INDUSTRIAL",
    1272: "LIBRARY",
    1273: "LIBRARY",
    1274: "PARKING",
    1275: "HOSPITAL",
    1276: "INDUSTRIAL",
    1277: "INDUSTRIAL",
    1278: "INDUSTRIAL",
}

def read_gwr(gwr_path):
    filter_cols = [
        'canton',
        'district_number',
        'district_name',
        'e_coordinate',
        'n_coordinate',
        'building_category',
        'building_class',
        'building_status',
        'construction_year',
        'building_area',
        'number_floors',
        'heating_tech_1',
        'heating_source_1',
        'hot_water_tech_1',
        'hot_water_source_1'
    ]

    df = pd.read_csv(gwr_path, sep='\t', names=GWR_HEADERS, index_col=False).set_index('federal_id')[filter_cols]

    # Drop properties without any coordinates
    no_coords = df['e_coordinate'].isna() | df['n_coordinate'].isna()
    df = df[~no_coords]

    # Drop non-existing buildings
    existing_buildings = df['building_status'] == 1004
    df = df[existing_buildings]

    # Fill missing year with median
    df['construction_year'] = df['construction_year'].fillna(df['construction_year'].median()).astype(int)

    # Fill missing floors with median
    df['number_floors'] = df['number_floors'].fillna(df['number_floors'].median()).astype(int)

    return df

def filter_gwr_by_bounds(gwr_df, minx, miny, maxx, maxy):
    e_coords = gwr_df['e_coordinate'].values
    n_coords = gwr_df['n_coordinate'].values
    within_e = (minx <= e_coords) & (e_coords <= maxx)
    within_n = (miny <= n_coords) & (n_coords <= maxy)

    return gwr_df[within_e & within_n]

# FIXME: Implement missing supply types for heating and hot water e.g. Solar Thermal, Cogen, Heat Exchanger
def gwr_to_cea_code(gwr_df):
    # Heating
    gwr_df['heating_tech'] = gwr_df['heating_tech_1'].map(HEATING_TECH).fillna('None')
    gwr_df['heating_source'] = gwr_df['heating_source_1'].map(ENERGY_HEAT_SOURCE).fillna('None')

    no_heating = (gwr_df['heating_tech'] == 'None') | (gwr_df['heating_tech'] == 'Unknown')  # Set unknown to None
    oil_boiler = (gwr_df['heating_tech'] == 'Boiler') & (gwr_df['heating_source'] == 'Oil')
    coal_boiler = (gwr_df['heating_tech'] == 'Boiler') & (gwr_df['heating_source'] == 'Coal')
    gas_boiler = (gwr_df['heating_tech'] == 'Boiler') & (gwr_df['heating_source'] == 'Gas')
    electrical_boiler = gwr_df['heating_tech'] == 'Resistance'
    wood_boiler = (gwr_df['heating_tech'] == 'Boiler') & (gwr_df['heating_source'] == 'Wood')
    ground_heat_pump = (gwr_df['heating_tech'] == 'HeatPump') & (gwr_df['heating_source'] == 'Ground')
    air_heat_pump = (gwr_df['heating_tech'] == 'HeatPump') & (gwr_df['heating_source'] == 'Air')
    water_heat_pump = (gwr_df['heating_tech'] == 'HeatPump') & (gwr_df['heating_source'] == 'Water')
    district_heating = gwr_df['heating_source'] == 'DistrictHeating'

    gwr_df.loc[no_heating, 'heating_tech_code'] = "SUPPLY_HEATING_AS0"
    gwr_df.loc[oil_boiler, 'heating_tech_code'] = "SUPPLY_HEATING_AS1"
    gwr_df.loc[coal_boiler, 'heating_tech_code'] = "SUPPLY_HEATING_AS2"
    gwr_df.loc[gas_boiler, 'heating_tech_code'] = "SUPPLY_HEATING_AS3"
    gwr_df.loc[electrical_boiler, 'heating_tech_code'] = "SUPPLY_HEATING_AS4"
    gwr_df.loc[wood_boiler, 'heating_tech_code'] = "SUPPLY_HEATING_AS5"
    gwr_df.loc[ground_heat_pump, 'heating_tech_code'] = "SUPPLY_HEATING_AS6"
    gwr_df.loc[air_heat_pump, 'heating_tech_code'] = "SUPPLY_HEATING_AS7"
    gwr_df.loc[water_heat_pump, 'heating_tech_code'] = "SUPPLY_HEATING_AS8"
    gwr_df.loc[district_heating, 'heating_tech_code'] = "SUPPLY_HEATING_AS9"

    # Set everything else to no heating
    gwr_df['heating_tech_code'] = gwr_df['heating_tech_code'].fillna("SUPPLY_HEATING_AS0")

    # Hot water
    gwr_df['hot_water_tech'] = gwr_df['hot_water_tech_1'].map(HOT_WATER_TECH).fillna('None')
    gwr_df['hot_water_source'] = gwr_df['hot_water_source_1'].map(ENERGY_HEAT_SOURCE).fillna('None')

    no_hot_water = (gwr_df['hot_water_tech'] == 'None') | (gwr_df['hot_water_tech'] == 'Unknown')  # Set unknown to None
    oil_boiler = (gwr_df['hot_water_tech'] == 'Boiler') & (gwr_df['hot_water_source'] == 'Oil')
    coal_boiler = (gwr_df['hot_water_tech'] == 'Boiler') & (gwr_df['hot_water_source'] == 'Coal')
    gas_boiler = (gwr_df['hot_water_tech'] == 'Boiler') & (gwr_df['hot_water_source'] == 'Gas')
    electrical_boiler = gwr_df['hot_water_tech'] == 'Resistance'
    wood_boiler = (gwr_df['hot_water_tech'] == 'Boiler') & (gwr_df['hot_water_source'] == 'Wood')
    ground_heat_pump = (gwr_df['hot_water_tech'] == 'HeatPump') & (gwr_df['hot_water_source'] == 'Ground')
    air_heat_pump = (gwr_df['hot_water_tech'] == 'HeatPump') & (gwr_df['hot_water_source'] == 'Air')
    water_heat_pump = (gwr_df['hot_water_tech'] == 'HeatPump') & (gwr_df['hot_water_source'] == 'Water')
    district_heating = gwr_df['hot_water_source'] == 'DistrictHeating'

    gwr_df.loc[no_hot_water, 'hot_water_tech_code'] = "SUPPLY_HOTWATER_AS0"
    gwr_df.loc[oil_boiler, 'hot_water_tech_code'] = "SUPPLY_HOTWATER_AS1"
    gwr_df.loc[coal_boiler, 'hot_water_tech_code'] = "SUPPLY_HOTWATER_AS2"
    gwr_df.loc[gas_boiler, 'hot_water_tech_code'] = "SUPPLY_HOTWATER_AS3"
    gwr_df.loc[electrical_boiler, 'hot_water_tech_code'] = "SUPPLY_HOTWATER_AS4"
    gwr_df.loc[wood_boiler, 'hot_water_tech_code'] = "SUPPLY_HOTWATER_AS5"
    gwr_df.loc[ground_heat_pump, 'hot_water_tech_code'] = "SUPPLY_HOTWATER_AS6"
    gwr_df.loc[air_heat_pump, 'hot_water_tech_code'] = "SUPPLY_HOTWATER_AS7"
    gwr_df.loc[water_heat_pump, 'hot_water_tech_code'] = "SUPPLY_HOTWATER_AS8"
    gwr_df.loc[district_heating, 'hot_water_tech_code'] = "SUPPLY_HOTWATER_AS9"

    # Set everything else to no hot water
    gwr_df['hot_water_tech_code'] = gwr_df['hot_water_tech_code'].fillna("SUPPLY_HOTWATER_AS0")

    # Building type
    building_type = gwr_df['building_class'].map(BUILDING_TYPE)
    most_common_type = building_type.value_counts().idxmax()
    gwr_df['building_type'] = building_type.fillna(most_common_type)  # Fill empty values with most common building type

    return gwr_df


# import required libraries
import cv2
import numpy as np

path_img =r'C:\Users\Dell\lesson_1\holes_detection\images\Kamera2_ok194_13_12_2022_8_15_0.bmp'
#preprocess image
def preprocess_img(path_img):
    img = cv2.imread(fr'{path_img}')
    noiseless_image_colored = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)
# convert the image to grayscale
    gray = cv2.cvtColor(noiseless_image_colored, cv2.COLOR_BGR2GRAY)
# apply thresholding to convert the grayscale image to a binary image
    ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_OTSU)
    canny = cv2.Canny(thresh, 75, 200)
    return canny, img

# find the contours
def find_contours(canny, img):
    contours, _ = cv2.findContours(canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    image_copy = img.copy()
    contour_list = []
    small_holes_list=[]
    big_holes_list=[]
    middle_holes_list=[]
    for contour in contours:
        approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)
        area = cv2.contourArea(contour)
        print(area)
        if 1000 < area < 5000:
            contour_list.append(contour)

        if 1200 < area < 2000:
            small_holes_list.append(area)
        elif 4000 < area < 6000:
            big_holes_list.append(area)
        elif 2000< area < 4000:
            middle_holes_list.append(area)
    return image_copy, contour_list, contours, small_holes_list, big_holes_list,  middle_holes_list

#print contours
def draw_contours(image_copy, contour_list, contours,small_holes_list, big_holes_list,  middle_holes_list):
    cont=cv2.drawContours(image_copy,contour_list, -1, (0, 255, 0), 2)
    print(len(contours), "objects were found in this image.")

    quantity_small_holes=len(small_holes_list)//2
    quantity_big_holes=len(big_holes_list)//2
    quantity_middle_holes=len(middle_holes_list)//2

    return cont, quantity_small_holes, quantity_big_holes, quantity_middle_holes

# cv2.imshow('Objects Detected', image_copy)

def main():
    canny, img=preprocess_img(path_img)
    image_copy, contour_list, contours, small_holes_list, big_holes_list, middle_holes_list=find_contours(canny, img)
    cont, quantity_small_holes, quantity_big_holes, quantity_middle_holes =draw_contours(image_copy, contour_list, contours, small_holes_list, big_holes_list, middle_holes_list)
    print_val=f"Quantity big holes:{quantity_big_holes}\nQuantity small holes:{quantity_small_holes}\nQuantity middle holes:{quantity_middle_holes}"
    print(print_val)
    # cv2.imshow('Objects Detected', canny)
    # cv2.imshow('Objects Detected', image_copy)
    cv2.imwrite('holes.png', image_copy)
    print("After saving image:")
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()


from datetime import date, datetime, timedelta
from typing import Iterator, Sequence
from zoneinfo import ZoneInfo

from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

from simple_history.models import HistoricalRecords

from blackbaud.models import Teacher, Student

WEEKDAY_CHOICES = (
    (0, "Monday"),
    (1, "Tuesday"),
    (2, "Wednesday"),
    (3, "Thursday"),
    (4, "Friday"),
    (5, "Saturday"),
    (6, "Sunday"),
)

EMAIL_REPORT_CHOICES = (
    ("unassigned_advisor", "Unassigned advisees to advisors"),
    ("unassigned_admin", "Unassigned advisees to admins"),
    ("advisor_signups", "Advisee locations to advisors"),
    ("advisee_signups", "Advisee locations to advisees"),
    ("facilitator_signups", "Advisee locations to facilitators"),
    ("all_signups", "Full signup report"),
)

# Originally this used get_available_timezones, but that caused an issue in
# CI/CD checking for hanging migrations, since get_available_timezones() was
# returning different values in GitHub actions
TIMEZONE_CHOICES = tuple(
    (s, s)
    for s in (
        "America/New_York",
        "America/Chicago",
        "America/Denver",
        "America/Phoenix",
        "America/Los_Angeles",
        "America/Anchorage",
        "America/Adak",
        "Pacific/Honolulu",
        "UTC",
    )
)

RELATED_ADDRESS_CHOICES = (
    ("to", "To"),
    ("cc", "Cc"),
    ("bcc", "Bcc"),
    ("reply-to", "Reply To"),
)

def _choice_length(opts: Sequence[tuple[str, str]]):
    return max(len(p[0]) for p in opts)

class Slot(models.Model):
    """A time slot that Enrichment will run on"""

    date = models.DateField(db_index=True)
    title = models.CharField(
        max_length=256,
        blank=True,
        help_text="Any secondary description for this enrichment slot, generally not required",
    )
    editable_until = models.DateTimeField(
        help_text="When this slot will be locked out", default=timezone.now
    )
    active = models.BooleanField(default=True)

    history = HistoricalRecords()

    class Meta:
        ordering = ["date", "title"]

    def __str__(self):
        if self.title:
            return f"{self.date}: {self.title}"

        return f"{self.date}"

class Option(models.Model):
    """An enrichment option that students can be sent to"""

    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    location = models.CharField(max_length=256)
    description = models.CharField(max_length=4096, blank=True)

    admin_only = models.BooleanField(
        default=False,
        help_text="If this option should only be assignable by admin users",
    )

    only_available_on = models.ManyToManyField(
        Slot,
        help_text="An exclusive list of slots this option should be available on",
        related_name="+",
        blank=True,
    )

    not_available_on = models.ManyToManyField(
        Slot,
        help_text="A list of slots this option should not be available on",
        related_name="+",
        blank=True,
    )

    start_date = models.DateField(default=timezone.now)
    end_date = models.DateField(blank=True, null=True)

    history = HistoricalRecords()

    def __str__(self):
        teacher: Teacher = self.teacher
        if self.description:
            return f"{teacher.formal_name}: {self.description} in {self.location}"

        return f"{teacher.formal_name}: {self.location}"

class LocationOverride(models.Model):
    """An overridden location for a single option on a single day"""

    slot = models.ForeignKey(Slot, on_delete=models.CASCADE)
    option = models.ForeignKey(
        Option,
        on_delete=models.CASCADE,
        related_name="location_overrides",
    )

    location = models.CharField(max_length=256)

    class Meta:
        unique_together = (("slot", "option"),)

class Signup(models.Model):
    """A student signed up for a slot"""

    slot = models.ForeignKey(Slot, on_delete=models.CASCADE, db_index=True)
    option = models.ForeignKey(Option, on_delete=models.DO_NOTHING, db_index=True)
    student = models.ForeignKey(Student, on_delete=models.DO_NOTHING, db_index=True)
    admin_locked = models.BooleanField()

    history = HistoricalRecords()

    class Meta:
        unique_together = (("slot", "student"),)
        permissions = (
            (
                "edit_past_lockout",
                "Can edit enrichment signups past the lockout time",
            ),
            (
                "set_admin_locked",
                "Can set/unset admin locked, as well as ignore the flag usage",
            ),
            (
                "use_admin_only_options",
                "Can assign students to admin only options",
            ),
            (
                "assign_all_advisees",
                "Can assign any advisees",
            ),
            (
                "assign_other_advisees",
                "Can assign advisees for other advisors",
            ),
            (
                "view_reports",
                "Can view enrichment reports",
            ),
        )

    def __str__(self):
        return f"{self.slot}/{self.student}: {self.option}"

class EditConfig(models.Model):
    weekday = models.SmallIntegerField(
        choices=WEEKDAY_CHOICES,
        unique=True,
        help_text="What weekday this applies to",
    )
    days_before = models.PositiveSmallIntegerField(
        help_text="How many days before the slot date the lockout should be effective",
    )
    time = models.TimeField(
        help_text="When the slot should be locked out",
    )

    def __str__(self):
        return self.get_weekday_display()

class EmailConfig(models.Model):
    """General configs for email"""

    from_name = models.CharField(
        max_length=256,
        help_text="The name this email should be sent from",
    )

    from_address = models.EmailField(
        help_text="The address this email should be sent from",
    )

    created_at = models.DateTimeField(auto_now_add=True)

    last_sent = models.DateTimeField(
        help_text="The time this email was last sent",
        null=True,
    )

    report = models.CharField(
        choices=EMAIL_REPORT_CHOICES,
        max_length=_choice_length(EMAIL_REPORT_CHOICES),
    )

    enabled = models.BooleanField(default=True)

    start = models.PositiveSmallIntegerField(
        help_text="How many days ahead we should start looking for slots",
        default=0,
    )

    end = models.PositiveSmallIntegerField(
        help_text="How many days ahead we should stop looking for slots",
        default=0,
    )

    timezone = models.CharField(
        choices=TIMEZONE_CHOICES,
        max_length=_choice_length(TIMEZONE_CHOICES),
        default=timezone.get_current_timezone_name,
    )

    time = models.TimeField()
    monday = models.BooleanField()
    tuesday = models.BooleanField()
    wednesday = models.BooleanField()
    thursday = models.BooleanField()
    friday = models.BooleanField()
    saturday = models.BooleanField()
    sunday = models.BooleanField()

    history = HistoricalRecords()

    def __str__(self):
        return f"{self.get_report_display()}: {', '.join(self.weekday_labels)} at {self.time}"

    @property
    def weekday_flags(self) -> tuple[bool, bool, bool, bool, bool, bool, bool]:
        """True/false flags for each day of the week, starting with Monday"""

        return (
            self.monday,
            self.tuesday,
            self.wednesday,
            self.thursday,
            self.friday,
            self.saturday,
            self.sunday,
        )

    @property
    def weekday_labels(self) -> list[str]:
        labels = [
            _("Monday"),
            _("Tuesday"),
            _("Wednesday"),
            _("Thursday"),
            _("Friday"),
            _("Saturday"),
            _("Sunday"),
        ]

        return [str(l) for i, l in enumerate(labels) if self.weekday_flags[i]]

    @property
    def weekday_ints(self) -> set[int]:
        """Set if weekday integers with Monday being 0"""

        return {i for i in range(7) if self.weekday_flags[i]}

    @property
    def upcoming_send_times(self) -> Iterator[datetime]:
        if self.weekday_flags == (False, False, False, False, False, False, False):
            return

        tzinfo = ZoneInfo(self.timezone)

        today = date.today()
        effective_last_sent: datetime = self.created_at
        if self.last_sent:
            effective_last_sent = self.last_sent

        if not effective_last_sent:
            return

        dt = datetime(
            effective_last_sent.year,
            effective_last_sent.month,
            effective_last_sent.day,
            self.time.hour,
            self.time.minute,
            self.time.second,
            tzinfo=tzinfo,
        )

        while True:
            dt += timedelta(days=1)

            if dt < effective_last_sent:
                continue

            if dt.weekday() in self.weekday_ints:
                yield dt

    @property
    def next_run(self) -> datetime | None:
        if not self.enabled:
            return None

        try:
            return next(self.upcoming_send_times)
        except StopIteration:
            return None

class RelatedAddress(models.Model):
    """Related addresses for email configs"""

    name = models.CharField(max_length=255)
    address = models.EmailField()
    message = models.ForeignKey(
        EmailConfig,
        on_delete=models.CASCADE,
        related_name="addresses",
    )
    field = models.CharField(
        choices=RELATED_ADDRESS_CHOICES,
        max_length=_choice_length(RELATED_ADDRESS_CHOICES),
    )

    def __str__(self):
        return f"{self.get_field_display()}: {self.address}"


# dataset load and transform
import numpy as np
import skimage.io as io
import random
import h5py

from torch.utils.data import Dataset
from torch import from_numpy as from_numpy
from torchvision import transforms
import torch
import torchio as tio

class Random3DCrop_np(object):
    def __init__(self, output_size):
        assert isinstance(output_size, (int, tuple)), 'Attention: random 3D crop output size: an int or a tuple (length:3)'
        if isinstance(output_size, int):
            self.output_size=(output_size, output_size, output_size)
        else:
            assert len(output_size)==3, 'Attention: random 3D crop output size: a tuple (length:3)'
            self.output_size=output_size

    def random_crop_start_point(self, input_size):
        assert len(input_size)==3, 'Attention: random 3D crop output size: a tuple (length:3)'
        d, h, w=input_size
        d_new, h_new, w_new=self.output_size

        d_new = min(d, d_new)
        h_new = min(h, h_new)
        w_new = min(w, w_new)

        assert (d>=d_new and h>=h_new and w>=w_new), "Attention: input size should >= crop size; now, input_size is "+str((d,h,w))+", while output_size is "+str((d_new, h_new, w_new))

        d_start=np.random.randint(0, d-d_new+1)
        h_start=np.random.randint(0, h-h_new+1)
        w_start=np.random.randint(0, w-w_new+1)

        return d_start, h_start, w_start

    def __call__(self, img_3d, start_points=None):
        img_3d=np.array(img_3d)

        d, h, w=img_3d.shape
        d_new, h_new, w_new=self.output_size

        if start_points == None:
            start_points = self.random_crop_start_point(img_3d.shape)

        d_start, h_start, w_start = start_points
        d_end = min(d_start+d_new, d)
        h_end = min(h_start+h_new, h)
        w_end = min(w_start+w_new, w)

        crop=img_3d[d_start:d_end, h_start:h_end, w_start:w_end]

        return crop

class Normalization_np(object):
    def __init__(self, windowMin, windowMax):
        self.name = 'ManualNormalization'
        assert isinstance(windowMax, (int,float))
        assert isinstance(windowMin, (int,float))
        self.windowMax = windowMax
        self.windowMin = windowMin

    def __call__(self, img_3d):
        img_3d_norm = np.clip(img_3d, self.windowMin, self.windowMax)
        img_3d_norm-=np.min(img_3d_norm)
        max_99_val=np.percentile(img_3d_norm, 99)
        if max_99_val>0:
            img_3d_norm = img_3d_norm/max_99_val*255
        return img_3d_norm

class airway_dataset(Dataset):
    def __init__(self, data_dict, num_of_samples = None):
        # each item of data_dict is {name:{"image": img path, "label": label path}}
        self.data_dict = data_dict
        if num_of_samples is not None:
            num_of_samples = min(len(data_dict), num_of_samples)
            chosen_names = np.random.choice(np.array(list(data_dict)), num_of_samples, replace=False)
        else:
            chosen_names = np.array(list(data_dict))
        self.name_list = chosen_names
        self.para = {}
        self.set_para()

    def __len__(self):
        return len(self.name_list)

    def __getitem__(self, idx):
        return self.get(idx, file_format=self.para["file_format"],\
            crop_size=self.para["crop_size"],\
                windowMin=self.para["windowMin"],\
                    windowMax=self.para["windowMax"],\
                        need_tensor_output=self.para["need_tensor_output"],\
                            need_transform=self.para["need_transform"])

    def set_para(self, file_format='.npy', crop_size=32, windowMin=-1000, windowMax=150,\
        need_tensor_output=True, need_transform=True):
        self.para["file_format"] = file_format
        self.para["crop_size"] = crop_size
        self.para["windowMin"] = windowMin
        self.para["windowMax"] = windowMax
        self.para["need_tensor_output"] = need_tensor_output
        self.para["need_transform"] = need_transform

    def get(self, idx, file_format='.npy', crop_size=32, windowMin=-1000, windowMax=150,\
        need_tensor_output=True, need_transform=True):

        random3dcrop=Random3DCrop_np(crop_size)
        normalization=Normalization_np(windowMin, windowMax)

        name = self.name_list[idx]

        if file_format == ".npy":
            raw_img = np.load(self.data_dict[name]["image"])
            label_img = np.load(self.data_dict[name]["label"])
        elif file_format == '.nii.gz':
            raw_img = io.imread(self.data_dict[name]["image"], plugin='simpleitk')
            label_img = io.imread(self.data_dict[name]["label"], plugin='simpleitk')
        elif file_format == ".h5":
            hf = h5py.File(self.data_dict[name]["path"], 'r+')
            raw_img = np.array(hf["image"])
            label_img = np.array(hf["label"])
            hf.close()

        assert raw_img.shape == label_img.shape

        start_points=random3dcrop.random_crop_start_point(raw_img.shape)
        raw_img_crop=random3dcrop(np.array(raw_img, float), start_points=start_points)
        label_img_crop=random3dcrop(np.array(label_img, float), start_points=start_points)
        raw_img_crop=normalization(raw_img_crop)

        raw_img_crop = np.expand_dims(raw_img_crop, axis=0)
        label_img_crop = np.expand_dims(label_img_crop, axis=0)

        output = {"image": raw_img_crop, "label": label_img_crop}

        if need_tensor_output:
            output = self.to_tensor(output)
            if need_transform:
                output = self.transform_the_tensor(output, prob=0.5)

        return output

    def to_tensor(self, images):
        for item in images.keys():
            images[item]=from_numpy(images[item]).float()
        return images

    def transform_the_tensor(self, image_tensors, prob=0.5):
        dict_imgs_tio={}

        for item in image_tensors.keys():
            dict_imgs_tio[item]=tio.ScalarImage(tensor=image_tensors[item])
        subject_all_imgs = tio.Subject(dict_imgs_tio)
        transform_shape = tio.Compose([
            tio.RandomFlip(axes = int(np.random.randint(3, size=1)[0]), p=prob),tio.RandomAffine(p=prob)])
        transformed_subject_all_imgs = transform_shape(subject_all_imgs)
        transform_val = tio.Compose([
            tio.RandomBlur(p=prob),\
                tio.RandomNoise(p=prob),\
                    tio.RandomMotion(p=prob),\
                        tio.RandomBiasField(p=prob),\
                            tio.RandomSpike(p=prob),\
                                tio.RandomGhosting(p=prob)])
        transformed_subject_all_imgs['image'] = transform_val(transformed_subject_all_imgs['image'])

        for item in subject_all_imgs.keys():
            image_tensors[item] = transformed_subject_all_imgs[item].data

        return image_tensors

if __name__=="__main__":
    import pickle
    import matplotlib.pyplot as plt
    from torch.utils.data import DataLoader
    def load_obj(name):
        with open(name + '.pkl', 'rb') as f:
            return pickle.load(f)
    data_dict = load_obj("../dataset_info/train_test_set_dict_EXACT09_LIDC_IDRI_128_set_1_extended_more_big_10")
    dataset = airway_dataset(data_dict)
    output = dataset.get(0)
    for name in output.keys():
        print(name, output[name].shape)
    num_workers = 1
    dataset.set_para(file_format='.npy', crop_size=64, windowMin=-1000, windowMax=150,\
        need_tensor_output=True, need_transform=True)
    Dataset_loader = DataLoader(dataset, batch_size=3, shuffle=True, \
        num_workers=num_workers, pin_memory=False, persistent_workers=False)
    batch = next(iter(Dataset_loader))
    for name in batch.keys():
        print(name, batch[name].shape)


from django.shortcuts import render

from .models import Item, Slot, Bonus, ItemBonus
from django.http import HttpResponse
from django.core import serializers
import logging

# set up the logger
log = logging.getLogger(__name__)

#
# This view lists all the items in the database
#
def index(request):
    #log.debug("index being requested!")

    item_list = Item.objects.all()

    # render output
    context = {'item_list' : item_list}
    return render(request, 'index.html', context)

#
# This view shows the details for a specified item
#
def showitem(request):
    #log.info("showitem being requested!")

    # get the item id
    iid = request.GET["id"];
    #log.info(id)

    # get the Item with the specified id
    item = Item.objects.get(pk=iid)

    # render output
    context = {"item" : item}
    return render(request, "showitem.html", context)

#
# This view renders the search form
#
def searchform(request):
    #log.debug("searchform being requested!")

    # get a list of Slots
    slot_list = Slot.objects.all()

    # get a list of Bonuses
    bonus_list = Bonus.objects.all()

    # set up context
    context = {"slot_list" : slot_list, "bonus_list" : bonus_list}

    # render output
    return render(request, "searchform.html", context)

#
# This view accepts query parameters from the search form, performs the query,
# and returns the JSON'd result to the searchform to be displayed to the user
#
def search(request):
    #log.info("search being requested!")

    # get the specified item name
    item_name = request.GET.get("itemname", None)
    log.debug("item_name: " + item_name)

    # get the specified slot
    slot_id = request.GET.get("slot", None)
    log.debug("slot_id : " + slot_id)

    # get the first specified bonus
    bonus1_id = request.GET.get("bonus1", None)
    log.debug("bonus1_id: " + bonus1_id)

    # get the second specified bonus
    bonus2_id = request.GET.get("bonus2", None)
    log.debug("bonus2_id: " + bonus2_id)

    # start with the entire list, and we'll filter it down based on the
    # search criteria
    #item_list = Item.objects.all()
    item_list = Item.objects.all()

    # filter by name
    if item_name and item_name != "":
        item_list = item_list.filter(name__startswith=item_name)

    # filter by slot
    if slot_id:
        the_slot = Slot.objects.get(pk=slot_id)
        if the_slot:
            item_list = item_list.filter(slot=the_slot)

    # filter by first bonus
    if bonus1_id:
        bonus1 = Bonus.objects.get(pk=bonus1_id)
        if(bonus1):
            item_list = item_list.filter(bonuses=bonus1)

    # filter by second bonus
    if bonus2_id:
        bonus2 = Bonus.objects.get(pk=bonus2_id)
        if(bonus2):
            item_list = item_list.filter(bonuses=bonus2)

    # chop the list down to distinct items (currently it contains a row for
    # each bonus in each matching item)
    #item_list.distinct("item__name")

    # it seems that distinct() does not work with the sqlite backend.  As a
    # workaround, we'll copy the distinct items to a new list.
    #item_list = []
    #seen_item_ids = []
    #for item_bonus in combined_item_bonus_list:
    #    if(item_bonus.item.id not in seen_item_ids):
    #        seen_item_ids.append(item_bonus.item.id)
    #        item_list.append(item_bonus.item)

    json_result = ""

    # we need to serialize the QuerySet to JSON
    json_result = serializers.serialize("json", item_list)
    #log.debug("item_list: " + item_list.__str__())
    #log.debug("some_json: " + json_result)

    # return the search result
    #return JsonResponse({'foo':'bar'})
    return HttpResponse(json_result)


import configuration
import sqlite3

from contextlib import closing
from ootp15.date_loader import DateLoader
from ootp15.free_agents_loader import FreeAgentsLoader
from ootp15.league_loader import LeagueLoader
from ootp15.team_loader import TeamLoader

class TeamScraper(object):

    def save_teams(self):
        with closing(sqlite3.connect(configuration.DATABASE)) as db:
            cur = db.cursor()
            date_id = self.get_date_id(cur)
            old_player_teams = self.get_old_player_teams(cur)
            cur_player_teams = self.get_current_player_teams(cur)
            for player_id in cur_player_teams:
                if player_id not in old_player_teams or old_player_teams[player_id] != cur_player_teams[player_id]:
                    cur.execute('''
                        insert or ignore into player_teams
                        (player_id, date_id, team_id)
                        values
                        (?, ?, ?)''', (player_id, date_id, cur_player_teams[player_id]))
            db.commit()

    def get_old_player_teams(self, cur):
        old_player_teams = {}
        cur.execute('''
            select pt.player_id, pt.team_id
            from player_teams pt
            left join player_teams pt_later
              on pt_later.player_id = pt.player_id
              and pt_later.date_id > pt.date_id''')
        for row in cur.fetchall():
            old_player_teams[row[0]] = row[1]
        return old_player_teams

    def get_current_player_teams(self, cur):
        cur_player_teams = {}
        leagues = LeagueLoader().load_all()
        for league in leagues:
            for team_id in league.team_ids:
                team = TeamLoader(team_id).team
                cur.execute('''
                    insert or replace into teams
                    (id, name, level, parent_id, league_id, short_name)
                    values
                    (?, ?, ?, ?, ?, ?)
                    ''', (team_id, team.name, team.level, team.parent_team_id, team.league_id, team.short_name))
                for player_id in team.player_positions:
                    cur_player_teams[player_id] = team_id
        for player_id in  FreeAgentsLoader().player_positions:
            cur_player_teams[player_id] = 0
        return cur_player_teams

    def get_date_id(self, cur):
        current_date = DateLoader().date
        cur.execute('select id from dates where date = ?', (current_date,))
        row = cur.fetchone()
        if row:
            return row[0]
        cur.execute('select max(id) from dates')
        date_id = cur.fetchone()[0] + 1
        cur.execute('''
            insert into dates
            (id, date)
            values
            (?, ?)''', (date_id, current_date))
        return date_id


import pandas as pd
from pandas import DataFrame
from pandas import Series
import numpy as np
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

text = pd.read_csv("sample.csv",
                   sep = ",",
                   names = ['date', 'total', 'death', 'injuries'],
                   converters = {'date': str },
                   header = None)

text['date'] = pd.to_datetime(text['date'])
#print(text)
grouped = text.groupby(text['date'].dt.strftime('%Y'))['death'].sum()

gdf = pd.DataFrame({'date': grouped.index.astype(int), 'death': grouped.values})
x = gdf.iloc[:, 0].values
y = gdf.iloc[:, 1].values.reshape(-1, 1)
z = np.array([2018, 2019, 2020, 2021, 2022, 2023])
z = np.append(x, z)
predz = z.reshape(-1, 1)
x = x.reshape(-1, 1)

lin_reg = LinearRegression()
lin_reg.fit(x, y)
def viz_linear():
    plt.scatter(x, y, color='red')
    plt.plot(predz, lin_reg.predict(predz), color='blue')
    plt.xticks(z)
    plt.title("Yearly Accident Changes")
    plt.xlabel("Year")
    plt.ylabel("Total Death Accident Numbers")
    plt.show()
    return
viz_linear()


import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV

previsores = pd.read_csv('entradas_breast.csv')
classe = pd.read_csv('saidas_breast.csv')

def criarRede(optimizer, loos, kernel_initializer, activation, neurons):
    classificador = Sequential()
    classificador.add(Dense(units = neurons, activation = activation,
                        kernel_initializer = kernel_initializer, input_dim = 30))
    #20% DOS NEURONIOS SERAM ZERADOS PARA EVITAR OVERFITING
    classificador.add(Dropout(0.2))
    classificador.add(Dense(units = neurons, activation = activation,
                        kernel_initializer = kernel_initializer))
    #20% DA CAMADA ESCONDIDA SERAM ZERADOS PARA EVITAR OVERFITING
    classificador.add(Dropout(0.2))
    classificador.add(Dense(units = 1, activation = 'sigmoid'))
    classificador.compile(optimizer = optimizer, loss = loos,
                      metrics = ['binary_accuracy'])
    return classificador

classificador = KerasClassifier(build_fn = criarRede)
parametros = {'batch_size': [10, 30, 64],

              'epochs': [50],

              'optimizer': ['adam', 'sgd', 'RMSprop', 'adadelta', 'adagrad',
                            'adamax'],

              'loos': ['binary_crossentropy', 'hinge'],

              'kernel_initializer': ['random_uniform', 'normal', 'random_normal',
                                     'truncated_normal', 'zeros', 'ones',
                                     'glorot_normal', 'glorot_uniform', 'identity'],

              'activation': ['relu', 'sigmoid', 'softmax', 'softplus', 'softsign',
                             'tanh', 'selu', 'elu', 'exponential'],

              'neurons': [16, 8]}

grid_search = GridSearchCV(estimator = classificador,
                           param_grid = parametros,
                           scoring = 'accuracy',
                           cv = 5)

grid_search = grid_search.fit(previsores, classe)
melhores_parametros = grid_search.best_params_
melhor_precisao = grid_search.best_score_


#!/usr/bin/env python
# encoding: utf-8

# @author: Zhipeng Ye
# @contact: Zhipeng.ye19@xjtlu.edu.cn
# @file: text2tensor.py
# @time: 2020-08-30 08:49
# @desc:
import torch
from dataprocess.bert_pretrain.bert_service import MyBertServer
from dataprocess.bert_pretrain.bert_client import MyBertClient
import dataprocess.loaddata as ld
import pandas as pd
import csv
import numpy as np
import pickle

def loadsentspair(df_type):
    if df_type == 'train':
        df = pd.read_csv('../../dataset/stsbenchmark/sts-train.csv', delimiter='\t', error_bad_lines=False,
                         quoting=csv.QUOTE_NONE)
    elif df_type == 'dev':
        df = pd.read_csv('../../dataset/stsbenchmark/sts-dev.csv', delimiter='\t', error_bad_lines=False,
                         quoting=csv.QUOTE_NONE)
    else:
        df = pd.read_csv('../../dataset/stsbenchmark/sts-test.csv', delimiter='\t', error_bad_lines=False,
                         quoting=csv.QUOTE_NONE)
    df = df.dropna(how='any')

    sents_left = df.iloc[:, [5]].values
    sents_right = df.iloc[:, [6]].values
    score = df.iloc[:, [4]].values
    return sents_left, sents_right, score

if __name__ == "__main__":

    ser = MyBertServer()
    cli = MyBertClient()

    df_types = ['train', 'dev', 'test']

    prefix_file_name = '../../dataset/stsbenchmark/'
    for df_type in df_types:

        file_name = prefix_file_name + df_type + '.pkl'
        sents_left, sents_right, scores = loadsentspair(df_type)
        sents_left = sents_left.tolist()
        sents_right = sents_right.tolist()
        scores = scores.tolist()

        data_list = []
        for index, value in enumerate(sents_left):
            sent_left = sents_left[index][0]
            sent_right = sents_right[index][0]

            sent_left_tensor = cli.query_sentence_vec(sent_left)
            sent_right_tensor = cli.query_sentence_vec(sent_right)
            score = scores[index][0]
            data_list.append((sent_left_tensor, sent_right_tensor, score))
        with open(file_name, 'wb') as file:
            pickle.dump(data_list, file)
            print(file_name + 'has been written.')

        print('wait to terminate this programme')


from django.shortcuts import render
from django.views import View
from .forms import NumbersForm

class HomeView(View):
    form_class =NumbersForm

    def get(self, request):
        return render(request, 'num/form_numbers.html', {'form': self.form_class})

    def post(self, request):
        form = self.form_class(request.POST)
        if form.is_valid():
            if 'soudi' in request.POST:
                print('soudi')
                lis = form.cleaned_data.values()
                dic = form.cleaned_data
                key_form = list(dic.keys())
                int_lis = [eval(i) for i in lis]
                sort_list = sorted(int_lis)
                new_dic = {}
                for i in range(0, 10):
                    new_dic[key_form[i]] = sort_list[i]
                form = NumbersForm(initial=new_dic)
                return render(request, 'num/form_numbers.html', {'form': form})
            if 'nozouli' in request.POST:
                lis = form.cleaned_data.values()
                int_lis = [eval(i) for i in lis]
                sort_list = sorted(int_lis)
                sort_list.reverse()
                form.value = sort_list
                dic = form.cleaned_data
                new_dic = {}
                key_form = list(dic.keys())
                for i in range(0, 10):
                    new_dic[key_form[i]] = sort_list[i]
                form = NumbersForm(initial=new_dic)
                return render(request, 'num/form_numbers.html', {'form': form})


import os
from PySide6.QtCore import Qt
from PySide6.QtGui import QPixmap, QImage, QPainter, QFontMetrics, QColor
from PySide6.QtWidgets import QTreeWidgetItem, QLabel, QFrame, QWidget, QSizePolicy
from PIL import Image, ImageDraw

class ZiJun:
    def generateGrid(width: int, height: int):
        image = Image.new("RGB", (width, height), "white")
        draw = ImageDraw.Draw(image)
        cellSize = 8
        for x in range(0, width, cellSize):
            for y in range(0, height, cellSize):
                if (x // cellSize) % 2 == (y // cellSize) % 2:
                    draw.rectangle([x, y, x + cellSize, y + cellSize], fill="white")
                else:
                    draw.rectangle(
                        [x, y, x + cellSize, y + cellSize], fill=(204, 204, 204)
                    )
        return QPixmap.fromImage(
            QImage(
                image.tobytes(),
                image.width,
                image.height,
                image.width * 3,
                QImage.Format_RGB888,
            )
        )

    def generateColor(width: int, height: int, color: QColor):
        pixmap = QPixmap(width, height)
        pixmap.fill(color)
        return pixmap

    def changeBackground(grid: bool, width: int, height: int, color: QColor = None):
        if grid:
            return ZiJun.generateGrid(width, height)
        else:
            return ZiJun.generateColor(width, height, color)

    def loadImage(path):
        image = []
        temp = [path]
        while temp:
            current = temp.pop(0)
            for name in os.listdir(current):
                path = os.path.join(current, name)
                if os.path.isdir(path):
                    temp.append(path)
                if os.path.splitext(path)[-1].lower() in (
                    ".jpg",
                    ".jpeg",
                    ".png",
                    ".gif",
                    ".bmp",
                ):
                    image.append(path)
        return image


from django.urls import path,include
from .views import *

urlpatterns = [

    path('register/',RegistrationView,name="registerView"),
    path('login/',login,name="login"),
    path('fileupload/',fileCreate,name="fileUpload"),
    path('files/',fileList,name="fileList"),
    path('singlefile/<int:id>/',SingleFile,name="singleFile")

]


# Source: https://github.com/stelligent/cloudformation-custom-resources/blob/master/lambda/python/customresource.py

import json
import logging
import signal
import traceback
from urllib.request import build_opener, HTTPHandler, Request
from enum import Enum

import os, sys

# os.environ['PYTHONPATH'] = os.environ.get('PYTHONPATH', '') + (':' if 'PYTHONPATH' in os.environ else '') + os.path.dirname(
#     os.path.realpath(__file__)) + '/deps'
# sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '/deps')
# print("PYTHONPATH:", os.environ['PYTHONPATH'])

main_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, main_dir)
sys.path.insert(0, os.path.join(main_dir, 'deps'))

log = logging.getLogger("CfnWrap")
log.setLevel(logging.INFO)

log.info(f"Path: {sys.path}")

class CfnStatus(Enum):
    SUCCESS = "SUCCESS"
    FAILED = "FAILED"

class CrResponse:
    def __init__(self, status: CfnStatus, data=None, physical_id=None, fragment=None) -> None:
        '''The pysical_id should only ever change if the last version of the CR should be deleted.'''
        self.is_macro = fragment is not None
        self.is_cr = data is not None and physical_id is not None

        if (self.is_cr and self.is_macro) or not (self.is_cr or self.is_macro):
            raise Exception("must define either fragement or (data and physical_id)")

        self.fragment = fragment
        self.status = status
        self.data = data
        self.physical_id = physical_id

    def __str__(self):
        return json.dumps(dict(is_macro=self.is_macro, is_cr=self.is_cr, fragment=self.fragment, status=self.status,
                               data=self.data, physical_id=self.physical_id),
                          indent=2
                          )

def wrap_macro(_handler):
    """wrap a macro handler (lambda)"""
    def inner(event, context):
        # Setup alarm for remaining runtime minus a second
        ms_remaining = context.get_remaining_time_in_millis()
        timeout_in_s = max((ms_remaining // 1000) - 1, 15)
        log.debug(f'ms remaining: {ms_remaining}')
        log.debug(f'timing out in seconds: {timeout_in_s} (min 15s)')
        signal.alarm(timeout_in_s)
        def run():
            try:
                log.info('REQUEST RECEIVED:\n %s', event)
                log.info('REQUEST RECEIVED:\n %s', context)
                resp: CrResponse = _handler(event, context, **event['templateParameterValues'])
                if type(resp) != CrResponse:
                    raise Exception("Handler {} did not return a CrResponse!".format(_handler.__name__))
                if not resp.is_macro:
                    raise Exception("macro handlers must return a CrResponse with fragment!")
                return {
                    "requestId": event['requestId'],
                    "status": resp.status.value,
                    "fragment": resp.fragment
                }
            except Exception as e:
                traceback.print_exc()
                tb_str = traceback.format_exc()
                log.info('FAILED!')
                log.info("Exception: %s", repr(e))
                log.error(tb_str)
                return {
                    "requestId": event['requestId'],
                    "status": CfnStatus.FAILED.value,
                    "errorMessage": "Exception: {}\n\nTraceback:\n{}".format(repr(e), tb_str)
                }
        resp = run()
        logging.info(f"RESPONSE: {resp}")
        signal.alarm(0)
        return resp
    return inner

def wrap_handler(_handler):
    """Handle Lambda event from AWS"""

    def inner(event, context):
        # Setup alarm for remaining runtime minus a second
        signal.alarm((context.get_remaining_time_in_millis() // 1000) - 1)
        try:
            log.info('REQUEST RECEIVED:\n %s', event)
            log.info('REQUEST RECEIVED:\n %s', context)
            log.info(event)
            resp: CrResponse = _handler(event, context, **event['ResourceProperties'])
            signal.alarm(0)
            if type(resp) != CrResponse:
                raise Exception("Handler {} did not return a CrResponse!".format(_handler.__name__))
            resp_str = str(resp.data)
            log.info(f"-: RESPONSE ({len(resp_str)}) :-\n   {'V'*(9 + len(str(len(resp_str))))}\n\n{resp_str}")
            send_cfn_resp(event, context, resp)
        except Exception as e:
            traceback.print_exc()
            tb_str = traceback.format_exc()
            log.info('FAILED!')
            log.info("Exception: %s", repr(e))
            resource_id = event.get('PhysicalResourceId',
                                    "Unknown-PhysicalResourceId-{}".format(event['LogicalResourceId'])
                                    )
            signal.alarm(0)
            send_cfn_resp(event, context,
                          CrResponse(CfnStatus.FAILED, {
                              "Message": "Error: %s" % (repr(e),), "Traceback": tb_str
                          }, resource_id))

    return inner

def send_cfn_resp(evt, ctx, cfn_resp: CrResponse):
    return send_response(evt, ctx, cfn_resp)

def send_response(event, context, cfn_resp: CrResponse):
    if not cfn_resp.is_cr:
        raise Exception("send_response can only be used with CFN custom resource responses")
    response_status: CfnStatus = cfn_resp.status.value
    response_data = cfn_resp.data
    '''Send a resource manipulation status response to CloudFormation'''
    reason_prefix = response_data.get('Message', '')
    logs_url = "https://{region}.console.aws.amazon.com/cloudwatch/home?region={region}#logEventViewer:group={log_group};stream={log_stream}".format(
        region=context.invoked_function_arn.split(":")[3],
        log_group=context.log_group_name,
        log_stream=context.log_stream_name
    )
    resp_dict = {
        "Status": response_status,
        "Reason": reason_prefix,  # + ("" if response_status == CfnStatus.SUCCESS else "\nLogs URL: {}".format(logs_url)),
        "PhysicalResourceId": cfn_resp.physical_id,
        "StackId": event['StackId'],
        "RequestId": event['RequestId'],
        "LogicalResourceId": event['LogicalResourceId'],
    }
    log.info(f"resp_dict (no Data) sz size: {len(json.dumps(resp_dict))} (indent=1: {len(json.dumps(resp_dict, indent=1))})")
    resp_dict.update({"Data": response_data})
    log.info(f"resp_dict (w/ Data) sz size: {len(json.dumps(resp_dict))} (indent=1: {len(json.dumps(resp_dict, indent=1))})")
    log.info(json.dumps(resp_dict, indent=2))
    if 'Traceback' in response_data:
        tb_str = response_data['Traceback']
        split_at = "The above exception was the direct cause of the following exception:"
        if split_at in tb_str:
            tb_str = tb_str.split(split_at)[0].strip()
        tb_lines = tb_str.split('\n')
        nl = '\n'
        resp_dict['Reason'] += f"\nTB:\n{nl.join(tb_lines[1:3])}\n...\n{nl.join(tb_lines[-4:])}"
        del response_data['Traceback']
    resp_dict['Reason'] = resp_dict['Reason'][:600]
    response_body = json.dumps(resp_dict).encode()

    log.info('ResponseURL: %s', event['ResponseURL'])
    log.info('ResponseBody: %s', response_body.decode())

    opener = build_opener(HTTPHandler)
    request = Request(event['ResponseURL'], data=response_body)
    request.add_header('Content-Type', '')
    request.add_header('Content-Length', len(response_body))
    request.get_method = lambda: 'PUT'
    response = opener.open(request)
    log.info("Status code: %s", response.getcode())
    log.info("Status message: %s", response.msg)
    log.info(len(response_body))

def timeout_handler(_signal, _frame):
    '''Handle SIGALRM'''
    raise Exception('Time exceeded')

signal.signal(signal.SIGALRM, timeout_handler)


import os
import time
import argostranslate.package
import argostranslate.translate
import atlas_settings

from_code = atlas_settings.transcript_lang
to_code = atlas_settings.translation_lang
dir_path = atlas_settings.transcripts_directory

if(atlas_settings.whisper_task_settings == "translate"):
    print('Transcriber window will show whisper translations. You can close this window')

print('looping..')
while True:
    all_files = os.listdir(dir_path)
    if not all_files:
        time.sleep(1)

    else:
        files = [f for f in all_files if os.path.isfile(os.path.join(dir_path, f))]
        files.sort(key=lambda x: os.path.getmtime(os.path.join(dir_path, x)))
        oldest_file = files[0]
        argostranslate.package.update_package_index()
        available_packages = argostranslate.package.get_available_packages()
        package_to_install = next(
            filter(
            lambda x: x.from_code == from_code and x.to_code == to_code, available_packages
            )
        )
        argostranslate.package.install_from_path(package_to_install.download())

        # Translate
        with open(dir_path + oldest_file, 'r', encoding='utf-8') as f:
            text_to_translate = f.read()

        translatedText = argostranslate.translate.translate(text_to_translate, from_code, to_code)
        print(translatedText)
        os.remove(dir_path + oldest_file)


# https://www.interviewbit.com/problems/diffk/
def diff(arr, k):
    p1, p2, n = 0, 1, len(arr)
    while p1 < n and p2 < n:
        tmp = arr[p2] - arr[p1] - k
        if p1 != p2 and tmp == 0:
            return 1

        if tmp < 0:
            p2 += 1
        else:
            p1 += 1

    return 0


from tqdm import tqdm

class PathManagerSys:
    dir_paths = []
    dir_black_list = []
    file_black_list = []
    extensions = ['*.jpg', '*.jpeg', '*.png', '*.gif', '*.bmp', '*.tif', '*.tiff']

    def addDirPath(self, path):
        self.dir_paths.append(path)

    def addDirBlackList(self, path):
        self.dir_black_list.append(path)

    def addFileBlackList(self, path):
        self.file_black_list.append(path)

    def getFiles(self):
        files = []
        for dir_path in self.dir_paths:
            files.extend(get_files(dir_path, self.extensions))
        for dir_black in self.dir_black_list:
            files = [file for file in files if dir_black not in file]
        for file_black in self.file_black_list:
            files = [file for file in files if file_black != file]
        return files

    def IsFileInBlackList(self, filepath):
        for dir_black in self.dir_black_list:
            if dir_black in filepath:
                return True
        for file_black in self.file_black_list:
            if file_black == filepath:
                return True
        return False

    def ImportSettingsFromData(self, data):
        self.dir_paths = data.get('dir_paths', [])
        self.dir_black_list = data.get('dir_black_list', [])
        self.file_black_list = data.get('file_black_list', [])
        self.extensions = data.get('extensions', self.extensions)

    def ExportSettingsToData(self):
        data = {'dir_paths': self.dir_paths, 'dir_black_list': self.dir_black_list,
                'file_black_list': self.file_black_list, 'extensions': self.extensions}
        return data

def get_files(path, exts=None, file_ignore_masck=""):
    """
    :param path: ProjectSettingsPath to search
    :param exts: list of extensions to search ["*.jpg", "*.png"] need include "*" in mask
       :param file_ignore_masck:  of files to ignore "Thumbs.db"
    """
    if exts is None:
        exts = ["*"]
    import os
    import fnmatch
    matches = []
    for root, dirnames, filenames in tqdm(os.walk(path)):
        for file in filenames:
            if fnmatch.fnmatch(file, file_ignore_masck):
                continue
            for ext in exts:
                # no case match
                if fnmatch.fnmatch(file, ext):
                    matches.append(os.path.join(root, file))
    return matches


#  Bubble sorting is a kind of sorting in which swapping happens multiple times to swap expected right to left

def bubbleSort(l):
    n = len(l)
    for i in range(n):
        for j in range(i+1,n-1):
            if l[i]<l[j]:
                l[i],l[j]=l[j],l[i]

    print(l)
a = [1,2,3,4,4,41,2,3,22,11,12,18]

bubbleSort(a)


#
# @lc app=leetcode.cn id=56 lang=python3
#
# [56] 合并区间
#
# https://leetcode-cn.com/problems/merge-intervals/description/
#
# algorithms
# Medium (45.98%)
# Likes:    988
# Dislikes: 0
# Total Accepted:    252.7K
# Total Submissions: 549.6K
# Testcase Example:  '[[1,3],[2,6],[8,10],[15,18]]'
#
# 以数组 intervals 表示若干个区间的集合，其中单个区间为 intervals[i] = [starti, endi]
# 。请你合并所有重叠的区间，并返回一个不重叠的区间数组，该数组需恰好覆盖输入中的所有区间。
#
#
#
# 示例 1：
#
#
# 输入：intervals = [[1,3],[2,6],[8,10],[15,18]]
# 输出：[[1,6],[8,10],[15,18]]
# 解释：区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
#
#
# 示例 2：
#
#
# 输入：intervals = [[1,4],[4,5]]
# 输出：[[1,5]]
# 解释：区间 [1,4] 和 [4,5] 可被视为重叠区间。
#
#
#
# 提示：
#
#
# 1
# intervals[i].length == 2
# 0 i i
#
#
#

# @lc code=start
'''
关键字
区间调度

按起始排序，考虑各种情况即可
'''

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if len(intervals) == 0:
            return []
        intervals.sort(key=lambda x: x[0])
        res = []
        start = intervals[0][0]
        end = intervals[0][1]
        for l in intervals[1:]:
            m_start = l[0]
            m_end = l[1]

            if m_start > end:
                res.append([start, end])
                start = m_start
                end = m_end
            else:
                if m_end > end:
                    end = m_end

        res.append([start, end])

        return res
# @lc code=end


def sexo(n):
    if n == 1:
        return 'Ilmo Sr.'
    elif n ==2:
        return 'Ilma Sra.'

nome=input('Digite seu nome: ')
inf_sex=int(input('Defina seu sexo; Digite 1 para masculino ou 2 para feminino: '))
result=sexo(inf_sex)
print(f'{result} {nome}')


import os
import shutil
import random

# Must be run on each video twice, once for Leak and once for NoLeak
video = '4_HSM_Toggling'
category = 'Leak'
baseDir = os.path.join('C:\Git\BackgroundSubtraction\Data\Frames', video)
srcDir = os.path.join(baseDir, category)
trainDir = os.path.join(baseDir, 'Train', category)
testDir = os.path.join(baseDir, 'Test', category)
validationDir = os.path.join(baseDir, 'Validation', category)

# Separate into 70% training and 30% test
for filename in os.listdir(srcDir):
  chance = random.randint(1, 101)
  if chance <= 70:
    os.rename(os.path.join(srcDir, filename), os.path.join(trainDir, filename))
  else:
    os.rename(os.path.join(srcDir, filename), os.path.join(testDir, filename))

# Split 15% of training into validation
for filename in os.listdir(trainDir):
  chance = random.randint(1, 101)
  if chance <= 15:
    os.rename(os.path.join(trainDir, filename), os.path.join(validationDir, filename))

# add file name to files
# for filename in os.listdir(trainDir):
#   newFileName = video + '_' + filename
#   os.rename(os.path.join(trainDir, filename), os.path.join(trainDir, newFileName))

# for filename in os.listdir(testDir):
#   newFileName = video + '_' + filename
#   os.rename(os.path.join(testDir, filename), os.path.join(testDir, newFileName))

# for filename in os.listdir(validationDir):
#   newFileName = video + '_' + filename
#   os.rename(os.path.join(validationDir, filename), os.path.join(validationDir, newFileName))


"""hometask 8.5"""
#   Напишите шаблон регулярного выражения, который соответствовал бы паролю,
#   состоящему из 8-12 символов,
#   среди которых могут быть строчные и заглавные буквы латинского
#   алфавита, цифры, нижнее подчеркивание, звездочка, процент и амперсанд.
#   Пароль обязательно должен включать в себя одну строчную букву,
#   одну заглавную букву и одну цифру.

import re

########################################################
REGEX = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w*%&]{8,12}$"
########################################################

TEST_STR = ("YYY1YDDT\n"
            "20200As21pss\n"
            "20Sd08_*&%")

MATCHES = re.finditer(REGEX, TEST_STR, re.MULTILINE)

for matchNum, match in enumerate(MATCHES, start=1):

    print("Match {matchNum} was found at {start}-{end}: {match}"
          .format(matchNum=matchNum, start=match.start(),
                  end=match.end(), match=match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print("Group {groupNum} found at {start}-{end}: {group}".
              format(groupNum=groupNum, start=match.start(groupNum),
                     end=match.end(groupNum),
                     group=match.group(groupNum)))


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author      : Bhishan Poudel; Physics PhD Student, Ohio University
# Date        : Oct 06, 2016
# Last update :
#
#
# Imports
from __future__ import division, unicode_literals, print_function

from visual import *
s = sphere(color=color.cyan)

def change():
    if s.color == color.cyan:
        s.color = color.red
    else:
        s.color = color.cyan

scene.bind('click', change)


""" Control over a vehicle with two tracks """
import time
import machine
import network
import socket

import vehicle
import webpage
import json

def host_network(name):
    sta_if = network.WLAN(network.AP_IF)
    sta_if.active(True)
    sta_if.config(essid=name)
    sta_if.config(authmode=0)  # 0 = open network

def create_webpage(port, vehicle):
    server = webpage.ControlWebpage(port)

    index = webpage.file_responder_factory("index.html")
    server.register_get_handler(
        b'/index.html',
        index
    )
    server.register_get_handler(b'/', index)

    def control_vehicle(data):
        try:
            raw_data = json.loads(data.decode('utf-8'))
        except:
            return (webpage.ERR_200, "Json decode error")

        speed = raw_data.get('s')
        turn = raw_data.get('t')
        lights = raw_data.get('l')

        print("before", speed, turn)

        if not isinstance(speed, int) or speed < -100 or speed > 100:
            speed = 0
        if not isinstance(turn, int) or turn < -100 or turn > 100:
            turn = 0
        if not isinstance(lights, bool):
            lights = False

        vehicle.set_speed(speed / 100, turn / 100)
        vehicle.set_lights(lights)

        telem_dict = {
            'b': vehicle.get_battery()
        }

        return (webpage.OK_200, json.dumps(telem_dict).encode('utf-8'))

    server.register_post_handler(b'/control', control_vehicle)

    return server

if __name__ == "__main__":
    VEHICLE = vehicle.get_vehicle()
    host_network("tiny_trak")

    WEBPAGE = create_webpage(80, VEHICLE)

    while(True):
        WEBPAGE.update()


# tkinterモジュールをインポート
import tkinter as tk
import random

# キャラクタークラスを定義
class Character:
    def __init__(self, name, gender, age, job, image, x, y):
        # 基本的な属性
        self.name = name
        self.gender = gender
        self.age = age
        self.job = job
        # GUI用の属性
        self.image = tk.PhotoImage(file=image)  # 画像ファイルを読み込んでPhotoImageオブジェクトに変換
        self.x = x  # 画像の表示位置（x座標）
        self.y = y  # 画像の表示位置（y座標）
        # 感情的な属性（ランダムに値を与える）
        self.feeling = random.choice(["love", "like", "neutral", "dislike", "hate"])  # 想いの強さ
        self.reason = random.choice(["appearance", "personality", "interest", "fate", "other"])  # 想いの理由
        self.history = random.choice(["childhood friend", "classmate", "colleague", "neighbor", "stranger"])  # 想いの経緯
        # 行動的な属性（ランダムに値を与える）
        self.reaction = random.choice(["happy", "surprised", "confused", "sad", "angry"])  # 感情の反応
        self.action = random.choice(["approach", "avoid", "ignore", "confront", "support"])  # 行動の選択
        self.result = random.choice(["success", "failure", "neutral", "unknown"])  # 行動の結果

# 物語クラスを定義
class Story:
    def __init__(self, master):
        # キャラクタークラスのインスタンスを作成
        self.a = Character("A", "male", 20, "student", "a.png", 100, 200)
        self.b = Character("B", "female", 19, "student", "b.png", 300, 200)
        self.c = Character("C", "male", 21, "teacher", "c.png", 500, 200)
        # GUI用のウィジェットを作成
        self.master = master  # ルートウィンドウを属性として持つ
        self.master.title("BSS Generator")  # ウィンドウのタイトルを設定
        self.canvas = tk.Canvas(self.master, width=600, height=600)  # キャンバスを作成
        self.canvas.pack()  # キャンバスを配置
        self.button = tk.Button(self.master, text="Generate BSS Situation", command=self.generate)  # ボタンを作成
        self.button.pack()  # ボタンを配置

    # キャラクターの画像と名前を表示するメソッド
    def show_characters(self):
        # キャンバスに画像と名前を描画
        self.canvas.create_image(self.a.x, self.a.y, image=self.a.image)  # Aの画像を表示
        self.canvas.create_text(self.a.x, self.a.y + 100, text=self.a.name)  # Aの名前を表示
        self.canvas.create_image(self.b.x, self.b.y, image=self.b.image)  # Bの画像を表示
        self.canvas.create_text(self.b.x, self.b.y + 100, text=self.b.name)  # Bの名前を表示
        self.canvas.create_image(self.c.x, self.c.y, image=self.c.image)  # Cの画像を表示
        self.canvas.create_text(self.c.x, self.c.y + 100, text=self.c.name)  # Cの名前を表示

    # BとCが出会うメソッド
    def meet_bc(self):
        # BとCの想いの強さや理由や経緯を変更
        self.b.feeling = "love"
        self.b.reason = random.choice(["appearance", "personality", "interest", "fate", "other"])
        self.b.history = random.choice(["childhood friend", "classmate", "colleague", "neighbor", "stranger"])
        self.c.feeling = "love"
        self.c.reason = random.choice(["appearance", "personality", "interest", "fate", "other"])
        self.c.history = random.choice(["childhood friend", "classmate", "colleague", "neighbor", "stranger"])
        # BとCの反応や感情や行動を表示
        self.canvas.create_text(300, 50, text="B and C met and fell in love.")  # 出会いと恋に落ちたことを表示
        self.canvas.create_text(300, 100, text=f"B's feeling: {self.b.feeling}")  # Bの想いの強さを表示
        self.canvas.create_text(300, 150, text=f"B's reason: {self.b.reason}")  # Bの想いの理由を表示
        self.canvas.create_text(300, 200, text=f"B's history: {self.b.history}")  # Bの想いの経緯を表示
        self.canvas.create_text(300, 250, text=f"C's feeling: {self.c.feeling}")  # Cの想いの強さを表示
        self.canvas.create_text(300, 300, text=f"C's reason: {self.c.reason}")  # Cの想いの理由を表示
        self.canvas.create_text(300, 350, text=f"C's history: {self.c.history}")  # Cの想いの経緯を表示

    # AがBとCの関係を知るメソッド
    def know_ab(self):
        # Aの反応や感情や行動を表示
        self.canvas.create_text(300, 400, text="A found out that B and C are in love.")  # BとCの関係を知ったことを表示
        self.canvas.create_text(300, 450, text=f"A's reaction: {self.a.reaction}")  # Aの感情の反応を表示
        self.canvas.create_text(300, 500, text=f"A's action: {self.a.action}")  # Aの行動の選択を表示
        self.canvas.create_text(300, 550, text=f"A's result: {self.a.result}")  # Aの行動の結果を表示

    # BSSシチュエーションを生成するメソッド
    def generate(self):
        # キャンバスをクリア
        self.canvas.delete("all")
        # キャラクターの画像と名前を表示
        self.show_characters()
        # BとCが出会うメソッドを呼び出す
        self.meet_bc()
        # AがBとCの関係を知るメソッドを呼び出す
        self.know_ab()

# ルートウィンドウを作成
root = tk.Tk()
# 物語クラスのインスタンスを作成
story = Story(root)
# メインループを開始
root.mainloop()


# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Contains the main ShapeGuard class."""

from copy import copy

from typing import List, Dict, Union, Optional, Sequence
from typing_extensions import Protocol

from tensorguard import exception
from tensorguard import parser

class ShapedTensor(Protocol):
    shape: Sequence[int]

    def reshape(self, shape: Sequence[int]) -> 'ShapedTensor':
        pass

def matches(tensor: ShapedTensor, template: str, dims: Dict[str, int]) -> bool:
    shape = get_shape(tensor)
    spec = parser.parse(template)
    return spec.matches(shape, dims)

def reshape(tensor: ShapedTensor, template: str, dims: Dict[str, int]) -> ShapedTensor:
    spec = parser.parse(template)
    new_shape = spec.evaluate(dims)
    return tensor.reshape(new_shape)

def evaluate(template: str, dims: Dict[str, int]) -> List[Optional[int]]:
    dim_spec = parser.parse(template)
    return dim_spec.evaluate(dims)

def guard(tensor: ShapedTensor, template: str, dims: Dict[str, int]):
    shape = get_shape(tensor)
    spec = parser.parse(template)
    # compare rank
    if not spec.rank_matches(shape):
        raise exception.ShapeError(
            "Tensor has the wrong rank ({} != {}).\n"
            "Expected shape: {} (from template {})\n"
            "  Actual shape: {}".format(
                len(shape), len(spec), spec.partial_evaluate(dims), template, shape
            )
        )
    # infer dimensions
    inferred_dims = spec.infer(shape, dims)
    known_dims = copy(dims)
    known_dims.update(inferred_dims)
    # check if dimensions match
    if not spec.matches(shape, known_dims):
        raise exception.ShapeError(
            "Shape Mismatch\n"
            "Expected shape: {} (from template {})\n"
            "  Actual shape: {}".format(spec.partial_evaluate(dims), template, shape)
        )

    # return the inferred dims unless they start with '_'
    return {k: v for k, v in inferred_dims.items() if not k.startswith("_")}

def get_shape(tensor_or_shape: Union[Sequence[int], ShapedTensor]) -> List[int]:
    if isinstance(tensor_or_shape, (list, tuple)):
        return list(tensor_or_shape)
    elif hasattr(tensor_or_shape, 'shape') and hasattr(tensor_or_shape.shape, '__iter__'):
        return list(tensor_or_shape.shape)
    else:
        raise TypeError(
            "Unknown tensor/shape {} of type: {}".format(
                tensor_or_shape, type(tensor_or_shape)
            )
        )


from norminette.rules import PrimaryRule
from norminette.scope import UserDefinedType, GlobalScope, UserDefinedEnum

utypes = ["TYPEDEF", "UNION", "STRUCT", "ENUM"]

class IsUserDefinedType(PrimaryRule):
    def __init__(self):
        super().__init__()
        self.priority = 45
        self.scope = [GlobalScope, UserDefinedType]

    def typedef(self, context, pos):
        i = context.skip_ws(pos)
        if "TYPEDEF" not in [tkn.type for tkn in context.tokens[:i]]:
            return False, pos
        ret, i = context.check_identifier(i)
        if ret is False:
            i += 1
            if context.check_token(i, "LBRACE"):
                return True, i
            return False, pos
        i += 1
        return True, i

    def utype_definition(self, context, pos):
        utypes = ["STRUCT", "ENUM", "UNION"]
        if not [tkn for tkn in context.tokens[:pos] if tkn.type in utypes]:
            return False, pos
        return True, pos

    def run(self, context):
        """
        Catches user type definitions
        Can include the whole type definition in case it's a structure
        Variable declarations aren't included
        """
        i = context.skip_ws(0, nl=False)
        enum = False
        p = 0
        ids = []
        while context.peek_token(i) is not None:
            if context.check_token(i, utypes) is True and p <= 0:
                break
            if context.check_token(i, "LPARENTHESIS") is True:
                p += 1
            if context.check_token(i, "RPARENTHESIS") is True:
                p -= 1
            if context.check_token(i, ["NEWLINE", "SEMI_COLON"]) is True:
                return False, 0
            i += 1
        if context.peek_token(i) is None:
            return False, 0
        p = 0
        while context.peek_token(i):
            if context.check_token(i, "LPARENTHESIS") is True:
                p += 1
            if context.check_token(i, "RPARENTHESIS") is True:
                p -= 1
            if context.check_token(i, "ENUM") is True:
                enum = True
            if context.check_token(i, ["NEWLINE", "SEMI_COLON"]) is True and p == 0:
                break
            if context.check_token(i, "IDENTIFIER"):
                ids.append(context.peek_token(i))
            i += 1
        if context.check_token(i, "NEWLINE") is True and p <= 0:
            if enum is True:
                context.sub = context.scope.inner(UserDefinedEnum)
            else:
                context.sub = context.scope.inner(UserDefinedType)
            i = context.eol(i)
            return True, i
        elif context.check_token(i, "SEMI_COLON") is True:
            i += 1
            context.scope.vars_name.append(ids[-1])
            i = context.eol(i)
            return True, i


import pandas as pd
import numpy as np
import sys

def get_pupil_and_eye_ratios(raw_point_path, ellipse_fit_path):
    '''
    for both the eye and the pupil fit
    gets ratio of:
        distance between left and right most fit points
        _______________________________________________
        width of ellipse fit

    this ratio should be close to 1

    '''
    def get_range(columns, frame=1000):
        '''
        get min and max x values
        '''
        min_x = np.inf
        max_x = -np.inf

        for column in columns:
            x = raw_points[raw_points.columns.get_level_values(
                0)[0]][column].loc[frame]['x']
            if x < min_x:
                min_x = x
            if x > max_x:
                max_x = x

        return min_x, max_x

    # open raw points
    raw_points = pd.read_hdf(raw_points_path)

    # open ellipse fits
    ellipse_fits = {}
    for dataset in ['pupil', 'eye', 'cr']:
        ellipse_fits[dataset] = pd.read_hdf(ellipse_fit_path, dataset)

    # get pupil and eye columns from raw points
    pupil_columns = sorted([c for c in np.unique(
        np.array(raw_points.columns.get_level_values(1))) if c.startswith('pupil')])
    eye_columns = sorted([c for c in np.unique(
        np.array(raw_points.columns.get_level_values(1))) if c.startswith('eye')])

    # get ranges, then ratios
    min_x, max_x = get_range(pupil_columns)
    pupil_fit_ratio = (max_x - min_x) / (ellipse_fits['pupil'].loc[1000]['width']*2)

    min_x, max_x = get_range(eye_columns)
    eye_fit_ratio = (max_x - min_x) / (ellipse_fits['eye'].loc[1000]['width']*2)

    return pupil_fit_ratio, eye_fit_ratio

if __name__ == '__main__':
    raw_points_path = sys.argv[1]
    ellipse_fit_path = sys.argv[2]

    pr, er = get_pupil_and_eye_ratios(raw_points_path, ellipse_fit_path)
    print('\noutput:\n=========================================================================')
    print('pupil tracking point width to ellipse width ratio (should be ~1): {}'.format(pr))
    print('eye tracking point width to ellipse width ratio (should be ~1): {}'.format(er))


"""
    This file contains functions to calculate steering direction
    for a "moped" (see github.com/sics-sse/moped)
"""
import logging
import time

import driving as CRL_CAR
import picamera

from control.lateral import navigation

# Parameters used to set picamera image resolution
# Size: pixels in X-axis

RESOLUTIONX = 1024
# Size: pixels in Y-axis
RESOLUTIONY = 764

def main():
    """
        Captures image, tries to find a barcod once found it is sent to
        adapt_steering which sets the steering. This will loop
    """
    camera = picamera.PiCamera()
    camera.resolution = (RESOLUTIONX, RESOLUTIONY)
    camera.iso = 800
    time.sleep(2)
    while True:
        camera.capture('current-image.jpg')
        adapt_steering(navigation.get_xposition('current-image.jpg'))
        time.sleep(0.4)

def adapt_steering(position):
    """
        Calculates a steer-signal, sets steerdirection
        and prints the calculated value
    """
    center = RESOLUTIONX / 2
    offset = center - position
    steerfactor = offset / 10
    CRL_CAR.steer(steerfactor)
    logging.info(position)


# Databricks notebook source
#Creating delta table
from delta.tables import *

DeltaTable.create(spark)\
    .tableName("school_details")\
        .addColumn("school_name","STRING")\
        .addColumn("address","STRING")\
        .property("description","school table")\
        .location("/FileStore/shared_uploads/manigandan.mj@diggibyte.com/data_folder/merge_log")\
        .execute()

# COMMAND ----------

# MAGIC %sql
# MAGIC INSERT INTO school_details VALUES("SJS","tvm")

# COMMAND ----------

from pyspark.sql.types import *
from pyspark.sql.functions import *

schema = StructType([StructField("school_name",StringType(),True),
                     StructField("address",StringType(),True)

])
data = [("srms","chennai"),("Jeevan","bangalore")]
school_df = spark.createDataFrame(data = data,schema = schema)

# COMMAND ----------

display(school_df)
school_df.createOrReplaceTempView("source_view")

# COMMAND ----------

# MAGIC %sql
# MAGIC MERGE INTO school_details AS target
# MAGIC USING source_view  AS source
# MAGIC   ON target.school_name = source.school_name
# MAGIC   WHEN MATCHED
# MAGIC THEN UPDATE SET
# MAGIC   target.school_name = source.school_name,
# MAGIC   target.address = source.address
# MAGIC WHEN NOT MATCHED THEN
# MAGIC INSERT (school_name,address) VALUES (school_name,address)
# MAGIC

# COMMAND ----------

# MAGIC %sql
# MAGIC
# MAGIC SELECT * FROM school_details

# COMMAND ----------

#delta table to dataframe
delta_df = DeltaTable.forPath(spark, "/FileStore/shared_uploads/manigandan.mj@diggibyte.com/data_folder/merge_log")
last_opration_df = delta_df.history(1)
display(last_opration_df)

# COMMAND ----------

# MAGIC %sql
# MAGIC create table audit_log(opertaion STRING,
# MAGIC                       updated_time timestamp,
# MAGIC                       user_name string,
# MAGIC                       notebook_name string,
# MAGIC                       numTargetRowsUpdated int,
# MAGIC                       numTargetRowsInserted int,
# MAGIC                       numTargetRowsDeleted int)
# MAGIC

# COMMAND ----------

explode_df = last_opration_df.select(last_opration_df.operation,explode(last_opration_df.operationMetrics))
#explode_df_cast = explode_df.select(explode_df.operation,explode_df.key,explode_df.value.cast('int'))

# COMMAND ----------

display(explode_df)
#display(explode_df_cast)

# COMMAND ----------

pivot_df = explode_df_cast.groupBy("operation").pivot("key").sum("value")

# COMMAND ----------

display(pivot_df)

# COMMAND ----------

pivot_select = pivot_df.select(pivot_df.operation,pivot_df.numTargetRowsUpdated,pivot_df.numTargetRowsInserted,pivot_df.numTargetRowsDeleted)

# COMMAND ----------

display(pivot_select)

# COMMAND ----------

audit_df = pivot_select.withColumn("user_name",lit(dbutils.notebook.entry_point.getDbutils().notebook().getContext().userName().get())).withColumn("notebook_name",lit(dbutils.notebook.entry_point.getDbutils().notebook().getContext().notebookPath().get())).withColumn("updated_time",lit(current_timestamp()))
display(audit_df)

# COMMAND ----------


"""
https://leetcode.com/problems/container-with-most-water/
11. Container With Most Water
Medium
--------------------
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).
Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.

Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7].
In this case, the max area of water (blue section) the container can contain is 49.

Example 2:
Input: height = [1,1]
Output: 1

Example 3:
Input: height = [4,3,2,1,4]
Output: 16

Example 4:
Input: height = [1,2,1]
Output: 2

Constraints:
n = height.length
2 <= n <= 3 * 104
0 <= height[i] <= 3 * 104
"""

class Solution:
    def maxArea(self, height):
        return self.maxArea_2(height)

    def maxArea_2(self, height):
        """
        参考思路:
        https://leetcode.com/problems/container-with-most-water/solution/
        双指针夹逼法
        ----------------
        验证通过:
        Runtime: 164 ms, faster than 60.44% of Python3 online submissions for Container With Most Water.
        Memory Usage: 16.6 MB, less than 9.63% of Python3 online submissions for Container With Most Water
        :param height:
        :return:
        """
        if not height:
            return 0
        ret = 0
        l = 0
        r = len(height) - 1
        while l < r:
            ret = max(ret, min(height[l], height[r]) * (r - l))
            if height[l] < height[r]:
                l += 1
            else:
                r -= 1

        return ret

    def maxArea_brute(self, height):
        """
        暴力法:
        双重遍历,每两条线之间的面积都计算一遍,取最大值即可
        Time complexity:O(N*N)
        应该不满足要求
        :param height:
        :return:
        """
        if not height:
            return 0
        ret = 0
        for i in range(len(height)):
            for j in range(i + 1, len(height)):
                ret = max(ret, min(height[i], height[j]) * (j - i))
        return ret

def main():
    height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
    ret = Solution().maxArea(height)
    print(ret)
    print(ret == 49)
    print("---------------------")

    height = [1, 1]
    ret = Solution().maxArea(height)
    print(ret)
    print(ret == 1)
    print("---------------------")

    height = [4, 3, 2, 1, 4]
    ret = Solution().maxArea(height)
    print(ret)
    print(ret == 16)
    print("---------------------")

    height = [1, 2, 1]
    ret = Solution().maxArea(height)
    print(ret)
    print(ret == 2)
    print("---------------------")

if __name__ == "__main__":
    main()


# from https://github.com/joeybose/pytorch-normalizing-flows
import numpy as np

import torch
import torch.nn.functional as F
from torch import nn

from src.utils import get_device

class MaskedLinear(nn.Linear):
    """ same as Linear except has a configurable mask on the weights """

    def __init__(self, in_features, out_features, bias=True):
        super().__init__(in_features, out_features, bias)
        self.register_buffer('mask', torch.ones(out_features, in_features))

    def set_mask(self, mask):
        self.mask.data.copy_(torch.from_numpy(mask.astype(np.uint8).T))

    def forward(self, input):
        return F.linear(input, self.mask * self.weight, self.bias)

class MADE(nn.Module):
    def __init__(self, nin, hidden_sizes, nout, num_masks=1, natural_ordering=False):
        """
        nin: integer; number of inputs
        hidden sizes: a list of integers; number of units in hidden layers
        nout: integer; number of outputs, which usually collectively parameterize some kind of 1D distribution
              note: if nout is e.g. 2x larger than nin (perhaps the mean and std), then the first nin
              will be all the means and the second nin will be stds. i.e. output dimensions depend on the
              same input dimensions in "chunks" and should be carefully decoded downstream appropriately.
              the output of running the tests for this file makes this a bit more clear with examples.
        num_masks: can be used to train ensemble over orderings/connections
        natural_ordering: force natural ordering of dimensions, don't use random permutations
        """

        super().__init__()
        self.nin = nin
        self.nout = nout
        self.hidden_sizes = hidden_sizes
        assert self.nout % self.nin == 0, "nout must be integer multiple of nin"

        # define a simple MLP neural net
        self.net = []
        hs = [nin] + hidden_sizes + [nout]
        for h0, h1 in zip(hs, hs[1:]):
            self.net.extend([
                MaskedLinear(h0, h1),
                nn.ReLU(),
            ])
        self.net.pop()  # pop the last ReLU for the output layer
        self.net = nn.Sequential(*self.net)

        # seeds for orders/connectivities of the model ensemble
        self.natural_ordering = natural_ordering
        self.num_masks = num_masks
        self.seed = 0  # for cycling through num_masks orderings

        self.m = {}
        self.update_masks()  # builds the initial self.m connectivity
        # note, we could also precompute the masks and cache them, but this
        # could get memory expensive for large number of masks.

    def update_masks(self):
        if self.m and self.num_masks == 1: return  # only a single seed, skip for efficiency
        L = len(self.hidden_sizes)

        # fetch the next seed and construct a random stream
        rng = np.random.RandomState(self.seed)
        self.seed = (self.seed + 1) % self.num_masks

        # sample the order of the inputs and the connectivity of all neurons
        self.m[-1] = np.arange(self.nin) if self.natural_ordering else rng.permutation(self.nin)
        for l in range(L):
            self.m[l] = rng.randint(self.m[l - 1].min(), self.nin - 1, size=self.hidden_sizes[l])

        # construct the mask matrices
        masks = [self.m[l - 1][:, None] <= self.m[l][None, :] for l in range(L)]
        masks.append(self.m[L - 1][:, None] < self.m[-1][None, :])

        # handle the case where nout = nin * k, for integer k > 1
        if self.nout > self.nin:
            k = int(self.nout / self.nin)
            # replicate the mask across the other outputs
            masks[-1] = np.concatenate([masks[-1]] * k, axis=1)

        # set the masks in all MaskedLinear layers
        layers = [l for l in self.net.modules() if isinstance(l, MaskedLinear)]
        for l, m in zip(layers, masks):
            l.set_mask(m)

    def forward(self, x):
        return self.net(x)

class ARMLP(nn.Module):
    """ a 4-layer auto-regressive MLP, wrapper around MADE net """

    def __init__(self, nin, nout, nh):
        super().__init__()
        self.net = MADE(nin, [nh, nh, nh], nout, num_masks=1, natural_ordering=True)

    def forward(self, x):
        return self.net(x)

class MAF(nn.Module):
    """ Masked Auto-regressive Flow that uses a MADE-style network for fast forward """

    def __init__(self, dim, parity, net_class=ARMLP, nh=24):
        super().__init__()
        self.dim = dim
        self.net = net_class(dim, dim * 2, nh)
        self.parity = parity

    def forward(self, x):
        # here we see that we are evaluating all of z in parallel, so density estimation will be fast
        st = self.net(x)
        s, t = st.split(self.dim, dim=1)
        z = x * torch.exp(s) + t
        # reverse order, so if we stack MAFs correct things happen
        z = z.flip(dims=(1,)) if self.parity else z
        log_det = torch.sum(s, dim=1)
        return z, log_det

    def backward(self, z):
        # we have to decode the x one at a time, sequentially
        x = torch.zeros_like(z)
        log_det = torch.zeros(z.size(0)).cuda()
        z = z.flip(dims=(1,)) if self.parity else z
        for i in range(self.dim):
            st = self.net(x.clone())  # clone to avoid in-place op errors if using IAF
            s, t = st.split(self.dim, dim=1)
            x[:, i] = (z[:, i] - t[:, i]) * torch.exp(-s[:, i])
            log_det += -s[:, i]
        return x, log_det

class NormalizingFlow(nn.Module):
    """ A sequence of Normalizing Flows is a Normalizing Flow """

    def __init__(self, flows, device=None):
        super().__init__()
        self.flows = nn.ModuleList(flows)
        if not device:
            device = get_device()
        self.device = device

    def forward(self, x):
        m, _ = x.shape
        log_det = torch.zeros(m).to(self.device)
        zs = [x]
        for flow in self.flows:
            x, ld = flow(x)
            log_det += ld
            zs.append(x)
        return zs, log_det

    def backward(self, z):
        m, _ = z.shape
        log_det = torch.zeros(m).to(self.device)
        xs = [z]
        for flow in self.flows[::-1]:
            z, ld = flow.backward(z)
            log_det += ld
            xs.append(z)
        return xs, log_det


# Function to calculate median
def calcMedian(arr, startIndex, endIndex):
    index = ( startIndex + endIndex ) // 2
    if (endIndex - startIndex + 1) % 2 == 0:
        # return median for even no of elements
        return ( arr[index] + arr[index + 1] ) // 2
    else:
        # return median for odd no of elements
        return arr[index]

# Get n
n = int(input())

# Get list array X
X = list(map(int, input().split()))
F = list(map(int, input().split()))
S = []

n_ = 0

for i in range(n):
    for j in range(F[i]):
        S.append(X[i])
        n_ += 1

S.sort()

q1 = calcMedian(S, 0, n_//2 - 1)

if n_ % 2 == 0:
    q3 = calcMedian(S, n_//2, n_-1)
else:
    q3 = calcMedian(S, n_//2 + 1, n_-1)

print(round(float(q3 - q1), 2))

Tutorials/10 Days of Statistics/Day 1 - Interquartile Range/solution.py


a = "hello my name is nitesh"
count = len([x for x in a if x == " "])
print(count)

import re
a = "nitesh nitesh nites nite"
b = re.compile(r"nites")
lis = b.findall(a)
print(lis)

#mac address can be AB:AB:12:12:12:12 or ABAB:1212:1212
# write a program to match valid mac address
mac = "12:12:12:12:12:12"
b = re.compile(r"([0-9]|[A-F])([0-9]|[A-F]):([0-9]|[A-F])([0-9]|[A-F]):([0-9]|[A-F])([0-9]|[A-F]):([0-9]|[A-F])([0-9]|[A-F])")
b = re.compile(r"(([0-9a-fA-F]):?){12}")
match = b.search(mac)
print(match.group(2))

a = "hello world world"
import re
b = re.sub("world", "!there", a,1)
print(b)
import copy
old_list = [[1],[2],[3],[4],[5]]
new_list = copy.copy(old_list)

old_list[2][0] = 9

print('Old List:', old_list)
print('ID of Old List:', id(old_list))

print('New List:', new_list)
print('ID of New List:', id(new_list))

class A:
    def process(self):
        print('A process()')

class B(A):
    def process(self):
        print('B process()')

class C(A, B):
    pass

obj = C()
obj.process()