#!/usr/bin/env python3

import os
import re
import click
import json
import logging
import zipfile
import portalocker
import contextlib
import traceback
import imghdr
import multiprocessing
import functools
import threading
import time
import sys
import ctypes
import psutil

from pathlib import Path
from functools import partial
from tqdm import tqdm
from atomicwrites import atomic_write
from contextlib import contextmanager, nullcontext
from functools import partial

from origami.core.time import elapsed_timer
from origami.batch.core.io import *
from origami.batch.core.utils import Spinner
from origami.batch.core.mutex import DatabaseMutex, FileMutex, DummyMutex

def qt_app():
	try:
		from PySide2 import QtGui
	except ImportError:
		from PySide6 import QtGui

	os.environ["QT_QPA_PLATFORM"] = "offscreen"
	return QtGui.QGuiApplication()

class WatchdogState(enum.Enum):
	RUNNING = 0
	DONE = 1
	CANCEL = 2

class StopWatch:
	def __init__(self):
		self._last_reset = time.time()

	def reset(self):
		self._last_reset = time.time()

	@property
	def age(self):
		return time.time() - self._last_reset

class SharedMemoryStopWatch:
	def __init__(self):
		self._shared = multiprocessing.Value('L', int(time.time()))

	def reset(self):
		with self._shared.get_lock():
			self._shared.value = int(time.time())

	@property
	def age(self):
		with self._shared.get_lock():
			return time.time() - self._shared.value

WorkSetEntry = collections.namedtuple(
	'WorkSetEntry', ['path', 'pid', 'age'])

class SharedMemoryWorkSet:
	def __init__(self, access, n):
		assert n >= 1

		self._array = multiprocessing.Array(
			ctypes.c_int64, n * 4)

		# each slot has 4 integer entries:
		# 0: value
		# 1: pid
		# 2: timestamp
		# 3: not used

		self._n = n
		for i in range(self._n * 4):
			self._array[i] = -1

		self._access = access

	def _cleanup(self):
		with self._array.get_lock():
			for i in range(self._n):
				pid = self._array[4 * i + 1]
				if pid >= 0 and not psutil.pid_exists(pid):
					logging.warning(f"removing killed pid {pid} from work set.")
					self._array[4 * i] = -1
					self._array[4 * i + 1] = -1
					self._array[4 * i + 2] = -1

	def add(self, value):
		assert value >= 0
		with self._array.get_lock():
			self._cleanup()

			free = None
			for i in range(self._n):
				if self._array[4 * i] == value:
					return
				elif free is None and self._array[4 * i] < 0:
					free = i

			if free is None:
				raise RuntimeError(
					f"no free slots for adding {value}, pid {os.getpid()}: {self.active}")

			self._array[4 * free] = value
			self._array[4 * free + 1] = int(os.getpid())
			self._array[4 * free + 2] = int(time.time())

	def remove(self, value):
		assert value >= 0
		with self._array.get_lock():
			found = None
			for i in range(self._n):
				if self._array[4 * i] == value:
					found = i
					break
			assert found is not None
			self._array[4 * found] = -1
			self._array[4 * found + 1] = -1
			self._array[4 * found + 2] = -1

	@property
	def active(self):
		result = []
		with self._array.get_lock():
			self._cleanup()

			for i in range(self._n):
				if self._array[4 * i] >= 0:
					result.append(WorkSetEntry(
						path=self._access(self._array[4 * i]),
						pid=self._array[4 * i + 1],
						age=int(time.time() - self._array[4 * i + 2])))
		return result

	def print(self):
		active = self.active
		if active:
			logging.error(f"{len(active)} entries in work set:")
			for i, entry in enumerate(active):
				logging.error(f"  ({i + 1}) {entry}]")
		else:
			logging.error("no entries in work set.")

global global_stop_watch
global_stop_watch = SharedMemoryStopWatch()

# global_stop_watch needs to be global indeed, as pickling
# over the fork in imap_unordered will not work otherwise.

global global_work_set

class Watchdog(threading.Thread):
	def __init__(self, pool, stop_watch, work_set, timeout):
		threading.Thread.__init__(self)
		self._pool = pool
		self._timeout = timeout
		self._stop_watch = stop_watch
		self._work_set = work_set
		self._state = WatchdogState.RUNNING
		self._cond = threading.Condition()
		stop_watch.reset()

	def _print_work_set(self):
		self._work_set.print()

	def _cancel(self):
		if self._state != WatchdogState.CANCEL:
			logging.error("no new results after %d s. stopping." % self._stop_watch.age)
			self._print_work_set()
			self._state = WatchdogState.CANCEL
			self._pool.terminate()
			t = threading.Thread(target=lambda: self._pool.join(), args=())
			t.start()
			self._stop_watch.reset()
		elif self._state == WatchdogState.CANCEL:
			logging.error("stopping failed. killing process.")
			self._print_work_set()
			os._exit(1)

	def run(self):
		with self._cond:
			while True:
				self._cond.wait(
					max(0, self._timeout - self._stop_watch.age))

				if self._state == WatchdogState.DONE:
					break

				if self._stop_watch.age > self._timeout:
					self._cancel()

	def set_is_done(self):
		with self._cond:
			if self._state == WatchdogState.RUNNING:
				self._state = WatchdogState.DONE
				self._cond.notify()

	def is_cancelled(self):
		return self._state == WatchdogState.CANCEL

def chunks(items, n):
	for i in range(0, len(items), n):
		yield items[i:i + n]

class Processor:
	def __init__(self, options, needs_qt=False):
		self._overwrite = options.get("overwrite", False)
		self._processes = options.get("processes", 1)
		self._timeout = options.get("alive", 600)
		self._name = options.get("name", "")
		self._verbose = False

		self._lock_strategy = options.get("lock_strategy", "DB")
		self._lock_level = options.get("lock_level", "PAGE")
		self._lock_timeout = options.get("lock_timeout", "60")
		self._max_lock_age = options.get("max_lock_age")
		self._lock_chunk_size = 25
		self._mutex = None

		if self._lock_strategy == "DB":
			self._lock_database = options.get("lock_database")
		elif self._lock_strategy in ("FILE", "NONE"):
			pass
		else:
			raise ValueError(self._lock_strategy)

		if needs_qt:
			self._qt_app = qt_app()
			if self._processes > 1:
				logging.warning(
					"this batch does not support multiple processes.")
				self._processes = 1  # cannot safely fork here.
		else:
			self._qt_app = None

		if options.get("profile"):
			from profiling.sampling import SamplingProfiler
			self._profiler = SamplingProfiler()
			self._overwrite = True  # profile implies overwrite
		else:
			self._profiler = None

		self._print_paths = False
		self._plain = options.get("plain")
		if self._plain:
			self._print_paths = True

		self._debug_write = options.get("debug_write", False)
		self._track_changes = options.get("track_changes", False)

	@staticmethod
	def options(f):
		options = [
			click.option(
				'--processes',
				type=int,
				default=1,
				help="Number of parallel processes to employ."),
			click.option(
				'--alive',
				type=int,
				default=600,
				help="Seconds to wait after inactive process is killed."),
			click.option(
				'--name',
				type=str,
				default="",
				help="Only process paths that conform to the given pattern."),
			click.option(
				'--lock-strategy',
				type=click.Choice(['FILE', 'DB', 'NONE'], case_sensitive=False),
				default="DB",
				help="How to implement locking for concurrency."),
			click.option(
				'--lock-level',
				type=click.Choice(['PAGE', 'TASK'], case_sensitive=False),
				default="PAGE",
				help="Lock granularity."),
			click.option(
				'--lock-database',
				type=click.Path(),
				required=False,
				help="Mutex database path used for concurrent processing"),
			click.option(
				'--lock-timeout',
				type=int,
				default=60,
				required=False,
				help="Seconds to wait to acquire locking. NFS volumes might need high values."),
			click.option(
				'--max-lock-age',
				type=int,
				default=600,
				required=False,
				help="Maximum age of a lock in seconds until it is considered invalid."),
			click.option(
				'--overwrite',
				is_flag=True,
				default=False,
				help="Recompute and overwrite existing result files."),
			click.option(
				'--profile',
				is_flag=True,
				default=False,
				help="Enable profiling and show results."),
			click.option(
				'--plain',
				is_flag=True,
				default=False,
				help="Print plain output that is friendly to piping."),
			click.option(
				'--debug-write',
				is_flag=True,
				default=False,
				help="Debug which files are written."),
			click.option(
				'--track-changes',
				type=str,
				default="",
				help="Recompute files and track changes with given tag.")
		]
		return functools.reduce(lambda x, opt: opt(x), options, f)

	@property
	def processor_name(self):
		return self.__class__.__name__

	def is_image(self, path):
		# imghdr might be the perfect tool for this, but
		# it fails to detect some valid images. so we go
		# with extenstions for the most part.
		# see https://stackoverflow.com/questions/36870661/
		# imghdr-python-cant-detec-type-of-some-images-image-extension

		if path.suffix.lower() in (".jpg", ".png", ".tif", ".tiff"):
			return True

		return imghdr.what(path) is not None

	def should_process(self, page_path):
		return True

	def prepare_process(self, page_path):
		artifacts = self.artifacts()

		if self._track_changes:
			file_writer = TrackChangeWriter(self._track_changes)
		else:
			file_writer = AtomicFileWriter(overwrite=self._overwrite)
			if self._debug_write:
				file_writer = DebuggingFileWriter(file_writer)

		kwargs = dict()
		for arg, spec in artifacts:
			f = spec.instantiate(
				page_path=page_path,
				processor=self,
				file_writer=file_writer)

			f.fix_inconsistent()

			if not f.is_ready():
				if self._verbose:
					print("skipping %s: missing %s" % (page_path, f.missing))
				return False

			kwargs[arg] = f

		return kwargs

	def _trigger_process1(self, p, kwargs, locked):
		work = locked

		if not locked:
			logging.warning(f"failed to obtain lock for {p}. ignoring.")

		try:
			if work:
				# a concurrent worker might already have done this.
				for f in kwargs.values():
					if not f.is_ready():
						work = False
						break

			if work:
				with elapsed_timer() as elapsed:
					data_path = find_data_path(p)
					data_path.mkdir(exist_ok=True)

					runtime_info = self.process(p, **kwargs)

				if runtime_info is None:
					runtime_info = dict()
				runtime_info["status"] = "COMPLETED"
				runtime_info["elapsed"] = round(elapsed(), 2)

				self._update_runtime_info(
					p, {self.processor_name: runtime_info})

		except KeyboardInterrupt:
			logging.exception("Interrupted at %s." % p)
			raise

		except:
			logging.exception("Failed to process %s." % p)
			runtime_info = dict(
				status="FAILED",
				traceback=traceback.format_exc())
			self._update_runtime_info(p, {
				self.processor_name: runtime_info})

		finally:
			# free memory allocated in cached io.Reader
			# attributes. this can get substantial for
			# long runs.
			kwargs.clear()

	def _trigger_process(self, chunk):
		if self._lock_level == "PAGE":
			lock_actor_name = "page"
		elif self._lock_level == "TASK":
			lock_actor_name = self.processor_name
		else:
			raise ValueError(self._lock_level)

		with self._mutex.lock(
			lock_actor_name,
			[str(p) for _, p, _ in chunk]) as locked:

			for i, p, kwargs in chunk:
				global_work_set.add(i)
				try:
					self._trigger_process1(p, kwargs, locked)
				finally:
					global_work_set.remove(i)
				yield i, p

	def _trigger_process_async(self, chunk):
		results = []
		for i, p in self._trigger_process(chunk):
			results.append((i, p))
			global_stop_watch.reset()
		return results

	def _process_queue(self, queued):
		global global_work_set
		global_work_set = SharedMemoryWorkSet(
			lambda i: queued[i][1], max(1, self._processes))

		with self._profiler or nullcontext():
			chunked_queue_gen = chunks(queued, self._lock_chunk_size)

			def iprogress(i):
				nd = len(str(len(queued)))
				return f"[{str(i + 1).rjust(nd)} / {len(queued)}]"

			if self._processes > 1:
				with multiprocessing.Pool(self._processes, maxtasksperchild=4) as pool:
					watchdog = Watchdog(
						pool=pool,
						stop_watch=global_stop_watch,
						work_set=global_work_set,
						timeout=self._timeout)
					watchdog.start()

					with tqdm(total=len(queued), disable=self._print_paths) as progress:
						for chunk in pool.imap_unordered(
							self._trigger_process_async, chunked_queue_gen):

							if self._print_paths:
								for i, p in chunk:
									print(f"{iprogress(i)} {p}", flush=True)
							else:
								progress.update(len(chunk))

							global_stop_watch.reset()

				if watchdog.is_cancelled():
					watchdog.kill()
					sys.exit(1)
				else:
					watchdog.set_is_done()
			else:
				with tqdm(total=len(queued), disable=self._print_paths) as progress:
					for chunk in chunked_queue_gen:
						for i, p in self._trigger_process(chunk):
							if self._print_paths:
								print(f"{iprogress(i)} {p}", flush=True)
							else:
								progress.update(1)

	def _build_queue(self, path):
		path = Path(path)
		if not path.exists():
			raise FileNotFoundError("%s does not exist." % path)

		queued = []
		counts = dict(images=0)

		def add_path(p):
			if not p.exists():
				print("skipping %s: path does not exist." % p)
				return

			if self._name and not re.search(self._name, str(p)):
				return

			if not self.is_image(p):
				if self._verbose:
					print("skipping %s: not an image." % p)
				return

			counts['images'] += 1

			if not self.should_process(p):
				if self._verbose:
					print("skipping %s: should_process is False" % p)
				return

			kwargs = self.prepare_process(p)
			if kwargs is not False:
				queued.append((len(queued), p, kwargs))

		if not path.is_dir():
			if path.suffix == ".txt":
				with open(path, "r") as f:
					for line in f:
						line = line.strip()
						if line:
							add_path(Path(line))
			else:
				raise FileNotFoundError(
					"%s is not a valid path or text file of paths." % path)
		else:
			print(f"scanning {path}... ", flush=True, end="")

			with Spinner(disable=self._plain):
				for folder, dirs, filenames in os.walk(path):
					folder = Path(folder)
					if folder.name.endswith(".out"):
						dirs.clear()
						continue
					else:
						dirs.sort()

						for filename in sorted(filenames):
							add_path(folder / filename)

			print("done.", flush=True)
			print(f"{counts['images']} documents found, {len(queued)} ready to process.")

		return queued

	def traverse(self, path: Path):
		print(f"running {self.processor_name}.", flush=True)

		queued = self._build_queue(path)

		if self._lock_strategy == "DB":
			if self._lock_database:
				db_path = Path(self._lock_database)
			elif Path(path).is_dir():
				db_path = Path(path) / "origami.lock.db"
			else:
				db_path = Path(path).parent / "origami.lock.db"

			self._mutex = DatabaseMutex(
				db_path, timeout=self._lock_timeout)

			self._mutex.clear_locks(self._max_lock_age)

		elif self._lock_strategy == "FILE":
			self._mutex = FileMutex()

		elif self._lock_strategy == "NONE":
			self._mutex = DummyMutex()

		else:
			raise ValueError(self._lock_strategy)

		try:
			self._process_queue(queued)
		finally:
			self._mutex = None

		if self._profiler:
			self._profiler.run_viewer()

	def process(self, p: Path):
		pass

	def lock_or_open(self, path, mode):
		if self._lock_strategy == "FILE":
			return portalocker.Lock(
				path,
				mode,
				flags=portalocker.LOCK_EX,
				timeout=1,
				fail_when_locked=True)
		else:
			return open(path, mode)

	def _update_json(self, page_path, artifact, updates):
		try:
			data_path = find_data_path(page_path)
			json_path = data_path / artifact.filename()

			new_json_path = json_path.parent / (
				json_path.stem + ".updated" + json_path.suffix)
			if new_json_path.exists():
				os.remove(new_json_path)

			if json_path.exists():
				with open(json_path, "r") as f:
					file_data = f.read()
					data = json.loads(file_data)
			else:
				data = dict()

			for k, v in updates.items():
				if v is None:
					del data[k]
				else:
					data[k] = v

			with open(new_json_path, "w") as f:
				json.dump(data, f)

			if json_path.exists():
				os.remove(json_path)
			os.rename(new_json_path, json_path)

		except:
			logging.error(traceback.format_exc())

	def _update_runtime_info(self, page_path, updates):
		self._update_json(page_path, Artifact.RUNTIME, updates)


days_vacation = int(input())
left_money = 0
for day in range(1, days_vacation+1):
    max_money = 60
    count_products = 0
    if left_money > 0:
        max_money += left_money
    while max_money > 0:
        price_product = input()
        if price_product == "Day over":
            if max_money > 0:
                print(f"Money left from today: {max_money:.2f}. You've bought {count_products} products.")
            break
        else:
            price_product = float(price_product)
            if max_money < price_product:
                pass
            else:
                max_money -= price_product
                count_products += 1
                if max_money == 0:
                    print(f"Daily limit exceeded! You've bought {count_products} products.")

    if max_money > 0:
        left_money = max_money


from urllib.request import urlopen
import json

def E(X):
    '''
    :param X: [(xi, pi), ...]
    :return: int expected value of random variable X
    '''
    return sum([e[0] * e[1] for e in X])

url = 'https://api.blockchain.info/charts/market-price?timespan=1year&format=json'

http_file = urlopen(url)
lines = http_file.readlines()
s = [str(line, encoding = 'utf-8') for line in lines]
t =''
for line in s:
    t += line
s = json.loads(t)
values = s.get('values')
X = []
P = [0.1550018235964546, 0.20615242538328463, 0.27418272575976854, 0.36466302526049216]
for i in range(1, len(values)):
    e2, e1 = values[i], values[i-1]
    dzeta = e2.get('y')/e1.get('y')
    quarter = int(i//91.25)
    X.append((dzeta-1, P[quarter]/91))
if __name__ == '__main__':
    print(E(X))  # revenue per day
k = (E(X)) * 30  # revenue per month
def kbn(month_sum):
    return month_sum/k
if __name__ == '__main__':
    print(1/k)


# coding: utf8
# Create by Narata on 2018/4/10

import urllib.request
import re

def get_url_list():
    url = 'http://www.budejie.com/video/'
    req = urllib.request.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36')
    response = urllib.request.urlopen(req)
    html = response.read().decode('utf8')
    print(type(html))
    reg = r'data-mp4="(.*?)"'
    url_list = re.findall(reg, html)
    for url in url_list:
        urllib.request.urlretrieve(url, 'mp4/{}.mp4'.format(url.split('/')[-1].split('.')[0]))
        print(url)

get_url_list()


import random
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageFilter
from torchvision import datasets, transforms

class RandomGaussianBlur(object):
    def __call__(self, image):
        if random.random() < 0.5:
            image = image.filter(ImageFilter.GaussianBlur(
                radius=random.random()))

        return image

class RandomSaltPepperBlur(object):
    def __call__(self, image, prob=0.05):
        image = np.array(image)
        for i in range(image.shape[0]):
            for j in range(image.shape[1]):
                rdn = random.random()
                if rdn < prob:
                    image[i][j] = round(random.random()) * 255

        return Image.fromarray(image)

def Mnist(data_dir="data", input_size=(224, 224), train=True):
    if train:
        tsf = transforms.Compose([
            transforms.RandomRotation(30),
            transforms.Resize(input_size),
            RandomGaussianBlur(),
            RandomSaltPepperBlur(),
            transforms.ToTensor(),
        ])
    else:
        tsf = transforms.Compose([
            transforms.Resize(input_size),
            transforms.ToTensor(),
        ])
    dataset = datasets.MNIST(data_dir,
                             train=train,
                             transform=tsf,
                             download=True)

    return dataset

if __name__ == '__main__':
    import cv2
    from torch.utils.data import DataLoader
    dataset = Mnist(train=False)
    mm = DataLoader(dataset)
    for i, sample in enumerate(mm):
        if i > 5: break;
        img = sample[0].numpy().reshape((224, 224))
        plt.imshow(img)
        cv2.imwrite('demo/img_{}.png'.format(i), img*255)
        plt.show()


# -*- coding: utf-8 -*-
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

import re
from odoo import api, fields, models

class OFCalculationHeatLossLine(models.Model):
    _name = 'of.calculation.heat.loss.line'
    _description = u"Appareils compatibles pour la déperdition de chaleur"

    calculation_heat_loss_id = fields.Many2one(
        comodel_name='of.calculation.heat.loss', string=u"Calcul de déperdition de chaleur")
    product_id = fields.Many2one(comodel_name='product.template', string=u"Article", store=True)
    brand_name = fields.Many2one(
        comodel_name='of.product.brand', string=u"Marque", related='product_id.brand_id', store=True)
    list_price = fields.Float(string=u"Prix de vente", related="product_id.list_price")
    power_char = fields.Char(string=u"Puissance nominale", related="product_id.of_puissance_nom", store=True)
    power = fields.Float(string=u"Puissance nominale", compute='_compute_power')
    to_print = fields.Boolean(string=u"Impression", help=u"Activer / Désactiver l'impression")

    @api.depends('power_char')
    def _compute_power(self):
        for line in self:
            try:
                # Extract float from string
                line.power = re.findall(r"[-+]?(?:\d*\.*\d+)", line.power_char.replace(',','.'))[0]
            except ValueError:
                line.power = 0.0


#
# This file is part of the Robotic Observatory Control Kit (rockit)
#
# rockit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# rockit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with rockit.  If not, see <http://www.gnu.org/licenses/>.

"""Constants and status codes used by domed"""

from rockit.common import TFmt

class CommandStatus:
    """Numeric return codes"""
    # General error codes
    Succeeded = 0
    Failed = 1
    Blocked = 2
    HeartbeatTimedOut = 3
    HeartbeatCloseInProgress = 4
    HeartbeatUnavailable = 5
    HeartbeatInvalidTimeout = 6
    EngineeringModeRequiresHeartbeatDisabled = 7
    EngineeringModeActive = 8
    InvalidControlIP = 10

    _messages = {
        # General error codes
        1: 'error: command failed',
        2: 'error: another command is already running',
        10: 'error: command not accepted from this IP',

        # dome specific codes
        3: 'error: heartbeat monitor has tripped',
        4: 'error: heartbeat monitor is closing the dome',
        5: 'error: heartbeat monitor is not available',
        6: 'error: heartbeat timeout must be less than 120s',
        7: 'error: heartbeat monitor must be disabled before enabling engineering mode',
        8: 'error: dome is in engineering mode',

        -100: 'error: terminated by user',
        -101: 'error: unable to communicate with dome daemon'
    }

    @classmethod
    def message(cls, error_code):
        """Returns a human readable string describing an error code"""
        if error_code in cls._messages:
            return cls._messages[error_code]
        return f'error: Unknown error code {error_code}'

class DomeShutterStatus:
    """Status of the dome shutters"""
    Closed, Open, PartiallyOpen, Opening, Closing, HeartbeatMonitorForceClosing = range(6)

    _labels = {
        0: 'CLOSED',
        1: 'OPEN',
        2: 'PARTIALLY OPEN',
        3: 'OPENING',
        4: 'CLOSING',
        5: 'FORCE CLOSING',
    }

    _formats = {
        0: TFmt.Red + TFmt.Bold,
        1: TFmt.Green + TFmt.Bold,
        2: TFmt.Cyan + TFmt.Bold,
        3: TFmt.Yellow + TFmt.Bold,
        4: TFmt.Yellow + TFmt.Bold,
        5: TFmt.Red + TFmt.Bold,
    }

    @classmethod
    def label(cls, status, formatting=False):
        """
        Returns a human readable string describing a status
        Set formatting=true to enable terminal formatting characters
        """
        if formatting:
            if status in cls._formats and status in cls._formats:
                return cls._formats[status] + cls._labels[status] + TFmt.Clear
            return TFmt.Red + TFmt.Bold + 'UNKNOWN' + TFmt.Clear

        if status in cls._labels:
            return cls._labels[status]
        return 'UNKNOWN'

class DomeHeartbeatStatus:
    """Status of the dome heartbeat monitoring"""
    Disabled, Active, TrippedClosing, TrippedIdle, Unavailable = range(5)

    _labels = {
        0: 'DISABLED',
        1: 'ACTIVE',
        2: 'CLOSING DOME',
        3: 'TRIPPED',
        4: 'UNAVAILABLE',
    }

    _formats = {
        0: TFmt.Bold,
        1: TFmt.Green + TFmt.Bold,
        2: TFmt.Red + TFmt.Bold,
        3: TFmt.Red + TFmt.Bold,
        4: TFmt.Yellow + TFmt.Bold,
    }

    @classmethod
    def label(cls, status, formatting=False):
        """
        Returns a human readable string describing a status
        Set formatting=true to enable terminal formatting characters
        """
        if formatting:
            if status in cls._formats and status in cls._formats:
                return cls._formats[status] + cls._labels[status] + TFmt.Clear
            return TFmt.Red + TFmt.Bold + 'UNKNOWN' + TFmt.Clear

        if status in cls._labels:
            return cls._labels[status]
        return 'UNKNOWN'


import json
import numpy as np
import matplotlib.pyplot as plt

def read_file():
    # 读取数据
    hero_list = json.load(open("./file/heroskin.json", 'r', encoding='utf-8'))
    hero_skin_data = hero_list["hero_skin_data"]
    return hero_skin_data

def get_hero_skin_count():
    hero_skin_data = read_file()

    # 所有英雄、皮肤个数
    hero_name_list = []
    hero_skin_count = []

    for hero_skin_item in hero_skin_data:
        temp_name = hero_skin_item["hero_name"]
        temp_skin_count = hero_skin_item["hero_skin_count"]
        hero_name_list.append(temp_name)
        hero_skin_count.append(temp_skin_count)
    return hero_name_list, hero_skin_count
    pass

def drawLine():
    # 显示负号
    plt.rcParams['axes.unicode_minus'] = False
    # 显示中文标签
    plt.rcParams['font.sans-serif'] = ['SimHei']
    # 显示负号
    plt.rcParams['axes.unicode_minus'] = False

    # 英雄数据
    hero_name_list, hero_skin_count = get_hero_skin_count()
    # 设置坐标数据 数组
    x_text = hero_name_list
    y_text = hero_skin_count

    # 设置窗口展示大小
    plt.figure(figsize=(20, 8), dpi=80)

    # 显示网格
    plt.grid(True, linestyle="--", color='gray', linewidth='0.5', axis='both')

    # 标题
    plt.title('英雄皮肤数据折线图')
    # 设置坐标轴名称
    plt.xlabel('英雄名称')
    plt.ylabel('皮肤数量')

    # 设置x轴文字角度
    plt.xticks(rotation=60, fontsize=9)

    # 设置间隔
    plt.xlim(-0.5, 100)

    # 柱形图
    bar = plt.bar(x=x_text, height=y_text, color='steelblue', alpha=0.8)

    # 折线图
    line = plt.plot(x_text,  y_text, color='red', linewidth=1, marker='o', markerfacecolor='salmon', markersize=3)
    # 设置数字标签
    for x, y in zip(x_text, y_text):
        plt.text(x, y, y, ha='center', va='bottom', fontsize=10)

    # 设置图例样式
    plt.legend(line, ("英雄皮肤数量",), loc='upper left')

    # 设置平均线
    avg = np.mean(y_text)
    plt.axhline(y=avg, color="green")

    # 显示
    plt.show()

def main():
    drawLine()

if __name__ == '__main__':
    main()


from sokoban.fast_sokoban import extract_all_patterns
import numpy as np

class MinimalLocalForwardModel:
    def __init__(self, model, mask, span, remember_predictions=False):
        self.model = model
        self.mask = mask
        self.span = span
        self.remember_predictions = remember_predictions
        if self.remember_predictions:
            self.known_predictions = dict()
        pass

    def extract_unknown_patterns(self, game_state, action, mask, span):
        """
        :param prev_game_state:
        :param action:
        :param game_state:
        :param mask:
        :param span:
        :param data_set:
        :return:
        """
        prediction_mask = np.zeros(game_state.shape, dtype=np.bool)
        result = np.zeros(game_state.shape, dtype=np.int)
        data_set = []

        # only iterate over positions that were affected by the game state's changes
        positions = [(x, y) for x in range(game_state.shape[0]) for y in range(game_state.shape[1])]
        ext_game_state_grid = np.pad(game_state, span, "constant", constant_values=1)

        for i, (x, y) in enumerate(positions):
            el = ext_game_state_grid[span + x - span: span + x + span + 1, span + y - span: span + y + span + 1][
                mask].tolist()
            el.append(action)
            el = tuple(el)
            if el in self.known_predictions:
                result[x, y] = self.known_predictions[el]
            else:
                prediction_mask[x, y] = 1
                data_set.append(el)
        return data_set, prediction_mask, result

    def predict(self, level, action):
        if self.remember_predictions:
            data, prediction_mask, result = self.extract_unknown_patterns(level, action, self.mask, self.span)

            if len(data) > 0:
                prediction = self.model.predict(data)
                result[prediction_mask] = prediction
                for el, pred in zip(data, prediction):
                    self.known_predictions[el] = pred
            return result
        else:
            data = extract_all_patterns(level, action, self.mask, self.span)
            return self.model.predict(data).reshape(level.shape)


# -*- coding: utf-8 -*-

import cottonformation as ctf
from cottonformation.res import iam, awslambda

# create a ``Template`` object to represent your cloudformation template
tpl = ctf.Template(
    Description="Aws Lambda Versioning Example",
)

iam_role_for_lambda = iam.Role(
    "IamRoleForLambdaExecution",
    rp_AssumeRolePolicyDocument=ctf.helpers.iam.AssumeRolePolicyBuilder(
        ctf.helpers.iam.ServicePrincipal.awslambda()
    ).build(),
    p_RoleName="lbd-versioning-poc",
    p_ManagedPolicyArns=[
        ctf.helpers.iam.AwsManagedPolicy.AmazonDynamoDBFullAccess,
    ]
)
tpl.add(iam_role_for_lambda)

lbd_func = awslambda.Function(
    "LbdFuncVersioningPOC",
    rp_Code=awslambda.PropFunctionCode(
        p_S3Bucket="sanhe-admin-for-everything",
        p_S3Key="lambda/MacHu-GWU/lbd-versioning/066212d310fb9d829154d197be860d0f.zip",
    ),
    rp_Role=iam_role_for_lambda.rv_Arn,
    p_FunctionName="lbd-versioning-poc",
    p_MemorySize=256,
    p_Timeout=3,
    p_Runtime=ctf.helpers.awslambda.LambdaRuntime.python36,
    p_Handler="lbd_handler.main",
    ra_DependsOn=iam_role_for_lambda,
    p_Tags=ctf.Tag.make_many(Stage="Dev", Description="Changed"),
)
tpl.add(lbd_func)

if __name__ == "__main__":
    import boto3

    boto_ses = boto3.session.Session(profile_name="sanhe")
    env = ctf.Env(boto_ses=boto_ses)
    env.deploy(
        template=tpl,
        stack_name="lbd-versioning-poc",
        bucket_name="sanhe-admin-for-everything",
        include_iam=True,
    )


# !pip install xlsxwriter
import pandas as pd

df = pd.DataFrame([{'foo':i,'bar':2*i,'baz':3*i} for i in range(76)])

writer = pd.ExcelWriter('sample_xl.xlsx',engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add some cell formats.
format1 = workbook.add_format({'bg_color': '#FFC7CE',
                               'font_color': '#9C0006'})
format2 = workbook.add_format({'bg_color': '#C6EFCE',
                               'font_color': '#006100'})
# How to add conditional formatting:
# Write a conditional format over a range.
worksheet.conditional_format('B2:D77', {'type': 'cell',
                                         'criteria': '>=',
                                         'value': 50,
                                         'format': format1})
worksheet.conditional_format('B2:D77', {'type': 'cell',
                                         'criteria': '<',
                                         'value': 50,
                                         'format': format2})
# Note: It isn't possible to format any cells that already have a format such
# as the index or headers or any cells that contain dates or datetimes.

# Set the column width and format.
# worksheet.set_column('B:B', 18, format1)

# Set the format but not the column width.
# worksheet.set_column('C:C', None, format2)

# Close the Pandas Excel writer and output the Excel file.
writer.save()


"""Config files
"""
import logging
import os
import sys
from pathlib import Path

import torch

MAIN_PATH = Path(__file__).resolve().parents[1]
DATA_PATH = MAIN_PATH / "data"
DEPLOY_PATH = MAIN_PATH / "src" / "deploy"
ARTIFACT_PATH = MAIN_PATH / "artifacts"

DEVICE = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
NUM_WORKERS = os.cpu_count()

EPOCHS = 20
LEARNING_RATE = 1e-4
EPS = 1e-8
BATCH_SIZE = 32
CLIP = 1.5
ALPHA = 1000.0
HIDDEN_SIZE = 2

### Class Translation
fmnist_classes = [
    "T-shirt/top",
    "Trouser",
    "Pullover",
    "Dress",
    "Coat",
    "Sandal",
    "Shirt",
    "Sneaker",
    "Bag",
    "Ankle boot",
]
cifar10_classes = [
    "airplane",
    "automobile",
    "bird",
    "cat",
    "deer",
    "dog",
    "frog",
    "horse",
    "ship",
    "truck",
]

CLASSES = {
    "mnist": {digit: digit for digit in range(10)},
    "fmnist": {label: idx for idx, label in enumerate(fmnist_classes)},
    "cifar10": {label: idx for idx, label in enumerate(cifar10_classes)},
}

### Model Params
MODEL_PARAMS = {
    "BaseVAE": {},
    "DeepVAE": {},
    "ConvVAE": {"kernel_size": 3},
    "BaseCVAE": {},
    "DeepCVAE": {},
    "ConvCVAE": {},
    "GAN": {},
    "CGAN": {},
    "ConvGAN": {},
    "ConvCGAN": {},
}

### Logging configurations
LOGGER = logging.getLogger(__name__)

stream_handler = logging.StreamHandler(sys.stdout)
if not (ARTIFACT_PATH / "model_ckpt").exists():
    (ARTIFACT_PATH / "model_ckpt").mkdir(parents=True)

file_handler = logging.FileHandler(
    filename=str(ARTIFACT_PATH / "model_ckpt" / "logfile.log")
)

formatter = logging.Formatter("%(asctime)s:%(levelname)s: %(message)s")
file_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)

LOGGER.setLevel(logging.INFO)
LOGGER.addHandler(stream_handler)
LOGGER.addHandler(file_handler)


from typing import Dict, Optional, Type, Union, Callable, Any
from types import TracebackType
from functools import wraps
from threading import Lock

from qiskit_ibm_provider.utils.converters import hms_to_seconds

from qiskit_ibm_runtime import QiskitRuntimeService
from .runtime_job import RuntimeJob
from .utils.result_decoder import ResultDecoder
from .ibm_backend import IBMBackend
from .utils.default_session import set_cm_session
from .utils.deprecation import deprecate_arguments

def _active_session(func):  # type: ignore
    """Decorator used to ensure the session is active."""

    @wraps(func)
    def _wrapper(self, *args, **kwargs):  # type: ignore
        if not self._active:
            raise RuntimeError("The session is closed.")
        return func(self, *args, **kwargs)

    return _wrapper

class Session:
    """Class for creating a flexible Qiskit Runtime session.

    A Qiskit Runtime ``session`` allows you to group a collection of iterative calls to
    the quantum computer. A session is started when the first job within the session
    is started. Subsequent jobs within the session are prioritized by the scheduler.
    Data used within a session, such as transpiled circuits, is also cached to avoid
    unnecessary overhead.

    You can open a Qiskit Runtime session using this ``Session`` class and submit jobs
    to one or more primitives.

    For example::

        from qiskit.test.reference_circuits import ReferenceCircuits
        from qiskit_ibm_runtime import Sampler, Session, Options

        options = Options(optimization_level=3)

        with Session(backend="ibmq_qasm_simulator") as session:
            sampler = Sampler(session=session, options=options)
            job = sampler.run(ReferenceCircuits.bell())
            print(f"Sampler job ID: {job.job_id()}")
            print(f"Sampler job result: {job.result()}")

    """

    def __init__(
        self,
        service: Optional[QiskitRuntimeService] = None,
        backend: Optional[Union[str, IBMBackend]] = None,
        max_time: Optional[Union[int, str]] = None,
    ):  # pylint: disable=line-too-long
        """Session constructor.

        Args:
            service: Optional instance of the ``QiskitRuntimeService`` class.
                If ``None``, the service associated with the backend, if known, is used.
                Otherwise ``QiskitRuntimeService()`` is used to initialize
                your default saved account.
            backend: Optional instance of :class:`qiskit_ibm_runtime.IBMBackend` class or
                string name of backend. An instance of :class:`qiskit_ibm_provider.IBMBackend` will not work.
                If not specified, a backend will be selected automatically (IBM Cloud channel only).

            max_time: (EXPERIMENTAL setting, can break between releases without warning)
                Maximum amount of time, a runtime session can be open before being
                forcibly closed. Can be specified as seconds (int) or a string like "2h 30m 40s".
                This value must be less than the
                `system imposed maximum
                <https://docs.quantum.ibm.com/run/max-execution-time>`_.

        Raises:
            ValueError: If an input value is invalid.
        """

        if service is None:
            if isinstance(backend, IBMBackend):
                self._service = backend.service
            else:
                self._service = (
                    QiskitRuntimeService()
                    if QiskitRuntimeService.global_service is None
                    else QiskitRuntimeService.global_service
                )

        else:
            self._service = service

        if self._service.channel == "ibm_quantum" and not backend:
            raise ValueError('"backend" is required for ``ibm_quantum`` channel.')

        self._instance = None
        if isinstance(backend, IBMBackend):
            self._instance = backend._instance
            backend = backend.name
        self._backend = backend

        self._setup_lock = Lock()
        self._session_id: Optional[str] = None
        self._active = True
        self._max_time = (
            max_time
            if max_time is None or isinstance(max_time, int)
            else hms_to_seconds(max_time, "Invalid max_time value: ")
        )

    @_active_session
    def run(
        self,
        program_id: str,
        inputs: Dict,
        options: Optional[Dict] = None,
        callback: Optional[Callable] = None,
        result_decoder: Optional[Type[ResultDecoder]] = None,
    ) -> RuntimeJob:
        """Run a program in the session.

        Args:
            program_id: Program ID.
            inputs: Program input parameters. These input values are passed
                to the runtime program.
            options: Runtime options that control the execution environment.
                See :class:`qiskit_ibm_runtime.RuntimeOptions` for all available options.
            callback: Callback function to be invoked for any interim results and final result.

        Returns:
            Submitted job.
        """

        options = options or {}

        if "instance" not in options:
            options["instance"] = self._instance

        options["backend"] = self._backend

        if not self._session_id:
            # Make sure only one thread can send the session starter job.
            self._setup_lock.acquire()
            # TODO: What happens if session max time != first job max time?
            # Use session max time if this is first job.
            options["session_time"] = self._max_time

        try:
            job = self._service.run(
                program_id=program_id,
                options=options,
                inputs=inputs,
                session_id=self._session_id,
                start_session=self._session_id is None,
                callback=callback,
                result_decoder=result_decoder,
            )

            if self._session_id is None:
                self._session_id = job.job_id()
        finally:
            if self._setup_lock.locked():
                self._setup_lock.release()

        if self._backend is None:
            self._backend = job.backend().name

        return job

    def cancel(self) -> None:
        """Cancel all pending jobs in a session."""
        self._active = False
        if self._session_id:
            self._service._api_client.cancel_session(self._session_id)

    def close(self) -> None:
        """Close the session so new jobs will no longer be accepted, but existing
        queued or running jobs will run to completion. The session will be terminated once there
        are no more pending jobs."""
        self._active = False
        if self._session_id:
            self._service._api_client.close_session(self._session_id)

    def backend(self) -> Optional[str]:
        """Return backend for this session.

        Returns:
            Backend for this session. None if unknown.
        """
        return self._backend

    def status(self) -> Optional[str]:
        """Return current session status.

        Returns:
            The current status of the session, including:
            Pending: Session is created but not active.
            It will become active when the next job of this session is dequeued.
            In progress, accepting new jobs: session is active and accepting new jobs.
            In progress, not accepting new jobs: session is active and not accepting new jobs.
            Closed: max_time expired or session was explicitly closed.
            None: status details are not available.
        """
        details = self.details()
        if details:
            state = details["state"]
            accepting_jobs = details["accepting_jobs"]
            if state in ["open", "inactive"]:
                return "Pending"
            if state == "active" and accepting_jobs:
                return "In progress, accepting new jobs"
            if state == "active" and not accepting_jobs:
                return "In progress, not accepting new jobs"
            return state.capitalize()

        return None

    def details(self) -> Optional[Dict[str, Any]]:
        """Return session details.

        Returns:
            A dictionary with the sessions details, including:
            id: id of the session.
            backend_name: backend used for the session.
            interactive_timeout: The maximum idle time (in seconds) between jobs that
            is allowed to occur before the session is deactivated.
            max_time: Maximum allowed time (in seconds) for the session, subject to plan limits.
            active_timeout: The maximum time (in seconds) a session can stay active.
            state: State of the session - open, active, inactive, or closed.
            accepting_jobs: Whether or not the session is accepting jobs.
            last_job_started: Timestamp of when the last job in the session started.
            last_job_completed: Timestamp of when the last job in the session completed.
            started_at: Timestamp of when the session was started.
            closed_at: Timestamp of when the session was closed.
        """
        if self._session_id:
            response = self._service._api_client.session_details(self._session_id)
            if response:
                return {
                    "id": response.get("id"),
                    "backend_name": response.get("backend_name"),
                    "interactive_timeout": response.get("interactive_ttl"),
                    "max_time": response.get("max_ttl"),
                    "active_timeout": response.get("active_ttl"),
                    "state": response.get("state"),
                    "accepting_jobs": response.get("accepting_jobs"),
                    "last_job_started": response.get("last_job_started"),
                    "last_job_completed": response.get("last_job_completed"),
                    "started_at": response.get("started_at"),
                    "closed_at": response.get("closed_at"),
                }
        return None

    @property
    def session_id(self) -> str:
        """Return the session ID.

        Returns:
            Session ID. None until a job runs in the session.
        """
        return self._session_id

    @property
    def service(self) -> QiskitRuntimeService:
        """Return service associated with this session.

        Returns:
            :class:`qiskit_ibm_runtime.QiskitRuntimeService` associated with this session.
        """
        return self._service

    @classmethod
    def from_id(
        cls,
        session_id: str,
        service: Optional[QiskitRuntimeService] = None,
        backend: Optional[Union[str, IBMBackend]] = None,
    ) -> "Session":
        """Construct a Session object with a given session_id

        Args:
            session_id: the id of the session to be created. This must be an already
                existing session id.
            service: instance of the ``QiskitRuntimeService`` class.
            backend: instance of :class:`qiskit_ibm_runtime.IBMBackend` class or
                string name of backend.

        Returns:
            A new Session with the given ``session_id``

        """
        if backend:
            deprecate_arguments("backend", "0.15.0", "Sessions do not support multiple backends.")

        session = cls(service, backend)
        session._session_id = session_id
        return session

    def __enter__(self) -> "Session":
        set_cm_session(self)
        return self

    def __exit__(
        self,
        exc_type: Optional[Type[BaseException]],
        exc_val: Optional[BaseException],
        exc_tb: Optional[TracebackType],
    ) -> None:
        set_cm_session(None)
        self.close()


def kerulet(r):
    pi = 3.14
    return(2*r*pi)
def terulet(r):
    pi = 3.14
    return(r**2)*pi
sugar = float(input("A kör sugara: "))
K = kerulet(sugar)
T = terulet(sugar)
print("A kör kerülete: {0} egység.".format(K))
print("A kör területe: {0} négyzetegység.".format(T))


from flask import Flask, jsonify, request, make_response
from functions import calculate_penalty,possession

app = Flask(__name__)

@app.route('/')
def index():
    return 'This is index page'

@app.route('/penalties', methods={'POST'})
def getpenalities():

        drug_class=request.form.get('drug_class')
        culpability = request.form.get('culpability')
        harm = request.form.get('harm')
        print((drug_class,culpability,harm))

        result = calculate_penalty(drug_class,culpability,int(harm))
        return jsonify( response = result, status=200,message="success" )

@app.route('/possession_of_a_drug', methods={'POST'})
def possession_of_a_drugapi():
    drug_class = request.form.get('drug_class')
    result = possession(drug_class)
    return jsonify(response=result, status=200, message="success")

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


"""
Created on Sat Oct 20 16:01:38 2018

@author: Varun
"""

import numpy as np
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dropout, Flatten, Dense
from keras import applications
import shutil

#reads in csv file
df = pd.read_csv("data/train_target.csv")
df1 = df['Id']
testLabels = []
validateLabels = []
jpg = []
i = 0
j = 0
#keeps track of number of files
trainMale = 0
trainFemale = 0
validateMale = 0
validateFemale = 0

leastGender = 0

#separates data into two Male/ Female Directories
while i < 28360:
    print(df1.iloc[i])
    imageName = ('data/train/' + df1.iloc[i])
    testTarget = df.iloc[i][1]
    if (testTarget == 1):
        trainMale = trainMale +1
        shutil.copy(imageName, "data/Split/Male/Male" + str (trainMale) + ".jpg" )
    else:
        trainFemale = trainFemale +1
        shutil.copy(imageName, "data/Split/Female/Female" + str (trainFemale) + ".jpg" )
    i = i+1

if(trainMale > trainFemale):
    leastGender = trainFemale
else:
    leastGender = trainMale

print(leastGender)
k = 1
while(k<leastGender +1):
    genderSwitch = 0
    imageName = ("data/Split/")
    if(k < 1 +leastGender - 2000):
        if(genderSwitch == 0):
            shutil.move(imageName+"Male/Male"+ str (k) + ".jpg", "data/Ultimate_train/Male/Male" + str (k) + ".jpg" )
            genderSwitch = 1
        if(genderSwitch == 1):
            shutil.move(imageName+"Female/Female"+ str (k) + ".jpg", "data/Ultimate_train/Female/Female" + str (k) + ".jpg" )
            genderSwitch = 0
    else:
        if(genderSwitch == 0):
            shutil.move(imageName+"Male/Male"+ str (k) + ".jpg", "data/Ultimate_validation/Male/Male" + str (k) + ".jpg" )
            genderSwitch = 1
        if(genderSwitch == 1):
            shutil.move(imageName+"Female/Female"+ str (k) + ".jpg", "data/Ultimate_validation/Female/Female" + str (k) + ".jpg" )
            genderSwitch = 0
    k = k+1

FemCounter = 1;
while(k<(leastGender*2) +1):
    imageName = ("data/Split/")
    if(k <  (leastGender*2) - 2000 +1):
        shutil.move(imageName+"Male/Male"+ str (k) + ".jpg", "data/Ultimate_train/Male/Male" + str (k) + ".jpg" )
        shutil.copy("data/training_set1/Female/Female" + str (FemCounter) + ".jpg", "data/Ultimate_train/Female/Female" + str (k) + ".jpg" )
    else:
        shutil.move(imageName+"Male/Male"+ str (k) + ".jpg", "data/Ultimate_validation/Male/Male" + str (k) + ".jpg" )
        shutil.copy("data/validation_set1/Female/Female" + str (FemCounter) + ".jpg", "data/Ultimate_validation/Female/Female" + str (k) + ".jpg" )
    k = k+1
    FemCounter = FemCounter +1

FemCounter = 1;
while(k <  (leastGender*3) - 2000 +1):

    shutil.move(imageName+"Male/Male"+ str (k) + ".jpg", "data/Ultimate_train/Male/Male" + str (k) + ".jpg" )
    shutil.copy("data/training_set1/Female/Female" + str (FemCounter) + ".jpg", "data/Ultimate_train/Female/Female" + str (k) + ".jpg" )
    k = k+1
    FemCounter = FemCounter +1


# -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 07:57:10 2020

@author: KANNAN
"""

from flask import Flask, render_template, request
import pandas as pd
#import sklearn
import pickle

model = pickle.load(open("flight_rf.pkl", "rb"))

app = Flask(__name__)

@app.route('/')

def home():
    return render_template('Airlines.html')

@app.route('/Predict', methods = ["GET", "POST"])

def Predict():
    if request.method == "POST":
        #Date of Journey
        # Departure DMY
        date_dep = request.form["Departure_Date"]
        Dep_day = int(pd.to_datetime(date_dep, format="%Y-%m-%dT%H:%M").day)
        Dep_month = int(pd.to_datetime(date_dep, format="%Y-%m-%dT%H:%M").month)
        Dep_year = int(pd.to_datetime(date_dep, format="%Y-%m-%dT%H:%M").year)
        # Departure Time
        Dep_hour = int(pd.to_datetime(date_dep, format="%Y-%m-%dT%H:%M").hour)
        Dep_minute = int(pd.to_datetime(date_dep, format="%Y-%m-%dT%H:%M").minute)

        date_arrival = request.form["Arrival_Date"]
        #Arrival DMY
        Arrival_day = int(pd.to_datetime(date_arrival, format="%Y-%m-%dT%H:%M").day)
        Arrival_month = int(pd.to_datetime(date_arrival, format="%Y-%m-%dT%H:%M").month)
        Arrival_year = int(pd.to_datetime(date_arrival, format="%Y-%m-%dT%H:%M").year)
        # Arrival Time
        Arrival_hour = int(pd.to_datetime(date_arrival, format="%Y-%m-%dT%H:%M").hour)
        Arrival_minute = int(pd.to_datetime(date_arrival, format="%Y-%m-%dT%H:%M").minute)

        # Duration in hrs
        from datetime import datetime
        dep_date = datetime(Dep_year,Dep_month,Dep_day,Dep_hour,Dep_minute)
        arrival_date = datetime(Arrival_year,Arrival_month,Arrival_day,Arrival_hour,Arrival_minute)
        diff = arrival_date - dep_date
        t = pd.to_datetime(diff,format="%H:%M:%S")
        duration_hour = t.hour
        duration_minute = t.minute

        # Source
        source = request.form["Source"]
        if (source == 'New Delhi'):
            s_New_Delhi = 1
            s_Kolkata = 0
            s_Mumbai = 0
            s_Chennai = 0

        elif (source == 'Kolkata'):
            s_New_Delhi = 0
            s_Kolkata = 1
            s_Mumbai = 0
            s_Chennai = 0

        elif (source == 'Mumbai'):
            s_New_Delhi = 0
            s_Kolkata = 0
            s_Mumbai = 1
            s_Chennai = 0

        elif (source == 'Chennai'):
            s_New_Delhi = 0
            s_Kolkata = 0
            s_Mumbai = 0
            s_Chennai = 1

        else:
            s_New_Delhi = 0
            s_Kolkata = 0
            s_Mumbai = 0
            s_Chennai = 0

        # Destination
        destination = request.form["Destination"]
        if (destination == 'Cochin'):
            d_Cochin = 1
            d_New_Delhi = 0
            d_Hyderabad = 0
            d_Kolkata = 0

        elif (destination == 'New Delhi'):
            d_Cochin = 0
            d_New_Delhi = 1
            d_Hyderabad = 0
            d_Kolkata = 0

        elif (destination == 'Hyderabad'):
            d_Cochin = 0
            d_New_Delhi = 0
            d_Hyderabad = 1
            d_Kolkata = 0

        elif (destination == 'Kolkata'):
            d_Cochin = 0
            d_New_Delhi = 0
            d_Hyderabad = 0
            d_Kolkata = 1

        else:
            d_Cochin = 0
            d_Delhi = 0
            d_New_Delhi = 0
            d_Hyderabad = 0
            d_Kolkata = 0

        # Airline
        airline = request.form["Airline"]

        if(airline=='Jet Airways'):
            Jet_Airways = 1
            IndiGo = 0
            Air_India = 0
            Multiple_carriers = 0
            SpiceJet = 0
            Vistara = 0
            GoAir = 0
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 0
            Trujet = 0

        elif (airline=='IndiGo'):
            Jet_Airways = 0
            IndiGo = 1
            Air_India = 0
            Multiple_carriers = 0
            SpiceJet = 0
            Vistara = 0
            GoAir = 0
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 0
            Trujet = 0

        elif (airline=='Air India'):
            Jet_Airways = 0
            IndiGo = 0
            Air_India = 1
            Multiple_carriers = 0
            SpiceJet = 0
            Vistara = 0
            GoAir = 0
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 0
            Trujet = 0

        elif (airline=='Multiple carriers'):
            Jet_Airways = 0
            IndiGo = 0
            Air_India = 0
            Multiple_carriers = 1
            SpiceJet = 0
            Vistara = 0
            GoAir = 0
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 0
            Trujet = 0

        elif (airline=='SpiceJet'):
            Jet_Airways = 0
            IndiGo = 0
            Air_India = 0
            Multiple_carriers = 0
            SpiceJet = 1
            Vistara = 0
            GoAir = 0
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 0
            Trujet = 0

        elif (airline=='Vistara'):
            Jet_Airways = 0
            IndiGo = 0
            Air_India = 0
            Multiple_carriers = 0
            SpiceJet = 0
            Vistara = 1
            GoAir = 0
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 0
            Trujet = 0

        elif (airline=='GoAir'):
            Jet_Airways = 0
            IndiGo = 0
            Air_India = 0
            Multiple_carriers = 0
            SpiceJet = 0
            Vistara = 0
            GoAir = 1
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 0
            Trujet = 0

        elif (airline=='Multiple carriers Premium economy'):
            Jet_Airways = 0
            IndiGo = 0
            Air_India = 0
            Multiple_carriers = 0
            SpiceJet = 0
            Vistara = 0
            GoAir = 0
            Multiple_carriers_Premium_economy = 1
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 0
            Trujet = 0

        elif (airline=='Jet Airways Business'):
            Jet_Airways = 0
            IndiGo = 0
            Air_India = 0
            Multiple_carriers = 0
            SpiceJet = 0
            Vistara = 0
            GoAir = 0
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 1
            Vistara_Premium_economy = 0
            Trujet = 0

        elif (airline=='Vistara Premium economy'):
            Jet_Airways = 0
            IndiGo = 0
            Air_India = 0
            Multiple_carriers = 0
            SpiceJet = 0
            Vistara = 0
            GoAir = 0
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 1
            Trujet = 0

        elif (airline=='Trujet'):
            Jet_Airways = 0
            IndiGo = 0
            Air_India = 0
            Multiple_carriers = 0
            SpiceJet = 0
            Vistara = 0
            GoAir = 0
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 0
            Trujet = 1

        else:
            Jet_Airways = 0
            IndiGo = 0
            Air_India = 0
            Multiple_carriers = 0
            SpiceJet = 0
            Vistara = 0
            GoAir = 0
            Multiple_carriers_Premium_economy = 0
            Jet_Airways_Business = 0
            Vistara_Premium_economy = 0
            Trujet = 0

        # Total_Stops
        stops = int(request.form["Total_Stops"])

        prediction=model.predict([[
            stops,
            Dep_day,
            Dep_month,
            Dep_hour,
            Dep_minute,
            Arrival_hour,
            Arrival_minute,
            duration_hour,
            duration_minute,
            Air_India,
            GoAir,
            IndiGo,
            Jet_Airways,
            Jet_Airways_Business,
            Multiple_carriers,
            Multiple_carriers_Premium_economy,
            SpiceJet,
            Trujet,
            Vistara,
            Vistara_Premium_economy,
            s_Chennai,
            s_Kolkata,
            s_Mumbai,
            s_New_Delhi,
            d_Cochin,
            d_Hyderabad,
            d_Kolkata,
            d_New_Delhi
        ]])

        output=round(prediction[0],2)

        return render_template('Airlines.html',prediction_text = "Your Flight Fare is {} INR".format(output))

    return render_template('Airlines.html')

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


"""
Lists Basics - More Exercises
Check your code: https://judge.softuni.bg/Contests/Practice/Index/1726#3

SUPyF2 Lists More Exercise - 04. Battle Ships

Problem:
You will be given a number n representing the number of rows of the field.
On the next n lines you will receive each row of the field as a string with numbers separated by a space.
Each number greater than zero represents a ship with a health equal to the number value.
After that you will receive the squares that are being attacked in the format: "{row}-{col} {row}-{col}".
Each time a square is being attacked, if there is a ship there (number greater than 0) you should reduce its value.
After the attacks have ended, print how many ships were destroyed (if its value has reached zero)

Example:
Input:
3
1 0 0 1
2 0 0 0
0 3 0 1
0-0 1-0 2-1 2-1 2-1 1-1 2-1

Output:
2
"""
rows = int(input())
all_ships = []
count_destroyed_ships = 0

for row in range(rows):
    all_ships += [[int(ship) for ship in input().split()]]
attacks = input().split(" ")

for attack in attacks:
    attack = attack.split("-")
    row = int(attack[0])
    col = int(attack[1])
    if all_ships[row][col] > 0:
        all_ships[row][col] -= 1
        if all_ships[row][col] == 0:
            count_destroyed_ships += 1

print(count_destroyed_ships)

SoftUni Lessons/Python Development/Python Fundamentals September 2019/Problems And Files/10 EXERCISE LISTS BASICS - Дата 4-ти октомври, 1430 - 1730/More Exercises/04. Battle Ships.py


import pytest
from subarraySum import Solution

@pytest.mark.parametrize("nums, k, expected", [
    ([], 2, 0),
    ([1, 1, 1], 2, 2),
    ([1, 1, 1, 1], 2, 3)
])
def test_subarraySum(nums, k, expected):
    actual = Solution().subarraySum(nums, k)
    assert actual == expected


import numpy as np
import sys
import time
sys.path.append("Interface/python/")
from init import NeuronLayerBox
import cv2

def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])

if __name__ == '__main__':
	NLB=NeuronLayerBox(step_ms=1,model=1,spike=0,restore=0)

	input_src=[]
	img=cv2.imread("load_data/input.bmp")
	img=rgb2gray(img).astype(int)

	input_src.append(img)
	NLB.step(20)
	NLB.input(input_src)
	for i in range(50):
		NLB.step(5)
		a=(NLB.output()['11']/max(np.max(NLB.output()['11']),0.0000001))*255
		cv2.imshow("1.jpg",a)
		cv2.waitKey(1)
	time.sleep(10)
	NLB.save()
	NLB.exit()


import csv
import json

BATCH_ID='4574137'
ROUND='1'

with open('wrong_hit.txt'.format(BATCH_ID)) as f:
    wrong_hit = f.read().splitlines()
    # print(len(wrong_hit))

save_data = []
csv_columns = []
all = 0
wrong = 0
with open('csv/Batch_{}_batch_results{}.csv'.format(BATCH_ID, '_'+ROUND if ROUND != '0' else ''), newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['AssignmentStatus'] != 'Submitted':
            continue
        all += 1
        time_missing = False
        label_missing = False
        for i in range(1, 6):
            label_exist = len(row["Answer.verb{}".format(i)]) > 2 and len(row["Answer.object{}".format(i)]) > 2
            time_exist = len(row["Answer.start{}".format(i)]) > 2 and len(row["Answer.end{}".format(i)]) > 2
            # print(row["Answer.verb{}".format(i)], row["Answer.object{}".format(i)], row["Answer.start{}".format(i)], row["Answer.end{}".format(i)])
            # print(label_exist, time_exist)
            if (label_exist == False and time_exist == False):
                continue
            if (label_exist != time_exist):
                label_missing = True
                break
            for j in range (1, 5):
                index = ["zero", "one", "two", "three"]
                if j == 1:
                    start = row["Answer.start{}".format(i)]
                    end = row["Answer.end{}".format(i)]
                else:
                    try:
                        if row["Answer.morethan{}{}".format(index[j-1], i)] != "on":
                            continue
                        start = row["Answer.start{}_{}".format(i,j)]
                        end = row["Answer.end{}_{}".format(i,j)]
                    except:
                        break
                if (len(start) > 2) != (len(end) > 2):
                    time_missing = True
                    break

        if time_missing or label_missing:
            row['Reject']='Incomplete annotations'
            wrong += 1
        elif row['HITId'] in wrong_hit:
            row['Reject']='Wrong annotations'
            wrong += 1
        else:
            row['Approve']='x'
        save_data.append(row)
        csv_columns = row.keys()
    print('Wrong annos {}/{}={:.2%}'.format(wrong, all, wrong/all))

with open('csv/rev_{}.csv'.format(BATCH_ID+"_"+ROUND if ROUND != '0' else BATCH_ID), 'w') as save_csv:
    writer = csv.DictWriter(save_csv, fieldnames=csv_columns)
    writer.writeheader()
    for row in save_data:
        writer.writerow(row)


import sys
import codecs

def readFile(tweetFileName,classFileName) :
	classMap = dict()
	fin1 = codecs.open(tweetFileName)
	fin2 = codecs.open(classFileName)

	for inputline1 in fin1 :
		inputline1 = inputline1.strip('\r\n')
		inputline2 = fin2.next().strip('\r\n')
		if inputline2 not in classMap :
			classMap[inputline2] = []
			classMap[inputline2].append(inputline1)
		else :
			if(len(classMap[inputline2]) < 750) :
				classMap[inputline2].append(inputline1)
	fin1.close()
	fin2.close()

	fout1 = codecs.open('newinput_step5-T.txt','w')
	fout2 = codecs.open('newclassFileName-T.txt','w')

	for key in classMap :
		for element in classMap[key] :
			fout1.write(element + '\r\n')
			fout2.write(key + '\r\n')
	fout1.close()
	fout2.close()

if __name__ == '__main__' :
	tweetFileName = '../data/input_step5-T.txt'
	classFileName = '../data/classFileName-T.txt'
	readFile(tweetFileName,classFileName)


from tensorflow.keras import layers, models
import glob
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from datetime import datetime

width = 75
height = 100
channel = 1

def load_data():
    images = np.array([]).reshape(0, height, width)
    labels = np.array([])

    dictionary = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 10,
                  'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, 'G': 16, 'H': 17, 'I': 18, 'J': 19, 'K': 20,
                  'L': 21, 'M': 22, 'N': 23, 'P': 24, 'Q': 25, 'R': 26, 'S': 27, 'T': 28, 'U': 29, 'V': 30,
                  'W': 31, 'X': 32, 'Y': 33, 'Z': 34}

    directories = [directory for directory in glob.glob('datasets/BelgianLicencePlates/TrainLetters/*')]
    for directory in directories:
        file_list = glob.glob(directory + '/*.jpg')
        sub_images = np.array([np.array(Image.open(file_name)) for file_name in file_list])
        sub_labels = [dictionary[directory[-1]]] * len(sub_images)
        images = np.append(images, sub_images, axis=0)
        labels = np.append(labels, sub_labels, axis=0)
    x_train, x_test, y_train, y_test = train_test_split(images, labels, test_size=0.2, random_state=42, shuffle=True)
    return (x_train, y_train), (x_test, y_test)

(train_images, train_labels), (test_images, test_labels) = load_data()
train_images = train_images.reshape((train_images.shape[0], height, width, channel))
test_images = test_images.reshape((test_images.shape[0], height, width, channel))
train_images, test_images = train_images / 255.0, test_images / 255.0
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(height, width, channel)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(35, activation='softmax'))
start = datetime.now().replace(microsecond=0)
model.summary()
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=8)
end = datetime.now().replace(microsecond=0)
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy: ', test_acc)
print('Test loss: ', test_loss)
print('Training duration: ', (end - start))
model.save('models/character_recognition_cnn.h5')
print('> Saved model to disk <')


import cv2
import os
import numpy as np
import json
import mmcv
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
import matplotlib.pyplot as plt
from glob import glob
import ast
from mmrotate.core import poly2obb_np

def poly2obb_np_oc(poly):
    """Convert polygons to oriented bounding boxes.

    Args:
        polys (ndarray): [x0,y0,x1,y1,x2,y2,x3,y3]

    Returns:
        obbs (ndarray): [x_ctr,y_ctr,w,h,angle]
    """
    bboxps = np.array(poly).reshape((4, 2))
    rbbox = cv2.minAreaRect(bboxps)
    x, y, w, h, a = rbbox[0][0], rbbox[0][1], rbbox[1][0], rbbox[1][1], rbbox[
        2]
    if w < 2 or h < 2:
        return
    while not 0 < a <= 90:
        if a == -90:
            a += 180
        else:
            a += 90
            w, h = h, w
    a = a / 180 * np.pi
    assert 0 < a <= np.pi / 2
    return x, y, w, h, a

def _get_adaptive_scales(areas, min_area=800, max_area=30000):
    """Get adaptive scales according to areas.

    The scale range is [0.5, 1.0]. When the area is less than
    ``'min_area'``, the scale is 0.5 while the area is larger than
    ``'max_area'``, the scale is 1.0.

    Args:
        areas (ndarray): The areas of bboxes or masks with the
            shape of (n, ).
        min_area (int): Lower bound areas for adaptive scales.
            Default: 800.
        max_area (int): Upper bound areas for adaptive scales.
            Default: 30000.

    Returns:
        ndarray: The adaotive scales with the shape of (n, ).
    """
    scales = 0.5 + (areas - min_area) / (max_area - min_area)
    scales = np.clip(scales, 0.5, 1.0)
    return scales

def draw_rbboxes(ax, bboxes, color='g', alpha=0.3, thickness=2):
    """Draw oriented bounding boxes on the axes.

    Args:
        ax (matplotlib.Axes): The input axes.
        bboxes (ndarray): The input bounding boxes with the shape
            of (n, 5).
        color (list[tuple] | matplotlib.color): the colors for each
            bounding boxes.
        alpha (float): Transparency of bounding boxes. Default: 0.8.
        thickness (int): Thickness of lines. Default: 2.

    Returns:
        matplotlib.Axes: The result axes.
    """
    polygons = []
    for i, bbox in enumerate(bboxes):
        xc, yc, w, h, ag = bbox[:5]
        wx, wy = w / 2 * np.cos(ag), w / 2 * np.sin(ag)
        hx, hy = -h / 2 * np.sin(ag), h / 2 * np.cos(ag)
        p1 = (xc - wx - hx, yc - wy - hy)
        p2 = (xc + wx - hx, yc + wy - hy)
        p3 = (xc + wx + hx, yc + wy + hy)
        p4 = (xc - wx + hx, yc - wy + hy)
        poly = np.int0(np.array([p1, p2, p3, p4]))
        polygons.append(Polygon(poly))
    p = PatchCollection(
        polygons,
        facecolor='none',
        edgecolors=color,
        linewidths=thickness,
        alpha=alpha)
    ax.add_collection(p)

    return ax

# arirang json to txt

ann_path = '/data/2_data_server/cv_data/arirang/validate_objects_labeling_json/'
# out_path = '/data/2_data_server/cv_data/arirang/val/annfiles/'

# ann_path = '/data/2_data_server/cv_data/arirang/validate_objects_labeling_json/'
label_test = []

for i in glob(ann_path+'*.json'):
    # print(i)
    with open(i) as f:
        json_data = json.load(f)
    img_id = json_data['features'][0]['properties']['image_id']
    for j in range(len(json_data['features'])):

        bbox_info = json_data['features'][j]['properties']['object_imcoords']
        bbox_info = ast.literal_eval(bbox_info)
        bbox_info = list(bbox_info)

        bbox_label = json_data['features'][j]['properties']['type_name'].replace(" ","-")
        bbox_id = json_data['features'][j]['properties']['type_id']

        if bbox_label == "military-aircraft":
            print(img_id)
            exit()
        if label_test == []:
            # label_test.append(bbox_id)
            label_test.append(bbox_label)
        if bbox_label not in label_test:
            # label_test.append(bbox_id)
            label_test.append(bbox_label)

        # first [:4] 지운 후
        # if j == 0:
        #     with open(out_path+img_id[:-4]+'.txt',"w") as (fw):
        #         for k in range(len(bbox_info)):
        #             fw.write(str(int(bbox_info[k])))
        #             fw.write(" ")
        #         # fw.write(bbox_info)
        #         # fw.write(" ")
        #         fw.write(bbox_label)
        #         fw.write(" ")
        #         fw.write("0\n")
        # else:
        #     with open(out_path+img_id[:-4]+'.txt',"a") as (fw):
        #         for k in range(len(bbox_info)):
        #             fw.write(str(int(bbox_info[k])))
        #             fw.write(" ")
        #         # fw.write(bbox_info)
        #         # fw.write(" ")
        #         fw.write(bbox_label)
        #         fw.write(" ")
        #         fw.write("0\n")

# aitod json to txt

# ann_path = '/data/2_data_server/cv_data/ai_todv2/aitodv2_train.json'
# out_path = '/data/2_data_server/cv_data/ai_todv2/train/annfiles/'

# # ann_path = '/data/2_data_server/cv_data/arirang/validate_objects_labeling_json/'
# label_test = []

# for i in glob(ann_path):
#     # print(i)
#     with open(i) as f:
#         json_data = json.load(f)

#     img_id = json_data['features'][0]['properties']['image_id']
#     for j in range(len(json_data['features'])):

#         bbox_info = json_data['features'][j]['properties']['object_imcoords']
#         bbox_info = ast.literal_eval(bbox_info)
#         bbox_info = list(bbox_info)

#         bbox_label = json_data['features'][j]['properties']['type_name'].replace(" ","-")
#         # bbox_id = json_data['features'][j]['properties']['type_id']
#         # if label_test == []:
#         #     # label_test.append(bbox_id)
#         #     label_test.append(bbox_label)
#         # if bbox_label not in label_test:
#         #     # label_test.append(bbox_id)
#         #     label_test.append(bbox_label)

#         # first [:4] 지운 후
#         if j == 0:
#             with open(out_path+img_id[:-4]+'.txt',"w") as (fw):
#                 for k in range(len(bbox_info)):
#                     fw.write(str(int(bbox_info[k])))
#                     fw.write(" ")
#                 # fw.write(bbox_info)
#                 # fw.write(" ")
#                 fw.write(bbox_label)
#                 fw.write(" ")
#                 fw.write("0\n")
#         else:
#             with open(out_path+img_id[:-4]+'.txt',"a") as (fw):
#                 for k in range(len(bbox_info)):
#                     fw.write(str(int(bbox_info[k])))
#                     fw.write(" ")
#                 # fw.write(bbox_info)
#                 # fw.write(" ")
#                 fw.write(bbox_label)
#                 fw.write(" ")
#                 fw.write("0\n")

# min,max 출력
# ann_path = '/data/2_data_server/cv_data/arirang_split/train_ms/annfiles/'

# num_min = 100000
# num_max = 0

# num_total = 0
# for i in glob(ann_path+'*.txt'):
#     # print(i)
#     num_lines = sum(1 for line in open(i))

#     num_min = min(num_lines, num_min)
#     num_max = max(num_lines, num_max)
#     if num_max == 1891:
#         print(i)
#         exit()

# print(num_min,num_max)

# # gt 개수
# ann_path = '/data/2_data_server/cv_data/arirang_split/val_ms/annfiles/'

# # CLASSES = ('small-ship', 'large-ship', 'civilian-aircraft', 'military-aircraft', 'small-car', 'bus', 'truck', 'train', 'crane', 'bridge',
# #             'oil-tank', 'dam', 'outdoor-playground', 'helipad', 'roundabout', 'indoor-playground','helicopter','individual-container','grouped-container','swimming-pool','etc')

# CLASSES = ('small-ship', 'large-ship', 'civilian-aircraft', 'military-aircraft', 'small-car', 'bus', 'truck', 'train')

# label_cnt = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
# cls_map = {c: i
#             for i, c in enumerate(CLASSES)
#             }

# for i in glob(ann_path+'*.txt'):
#     # print(i)
#     f = open(i,"r")
#     lines = f.readlines()
#     for line in lines:
#         label = line.split()
#         cls_name = label[8]
#         if cls_name == 'military-aircraft':
#             print(i)
#             exit()
#         # label = cls_map[cls_name]
#         # label_cnt[label] = label_cnt[label] + 1

# # print(label_cnt)

##### size check
# ann_path = '/data/2_data_server/cv_data/arirang/validate_objects_labeling_json/'
# # out_path = '/data/2_data_server/cv_data/arirang/val/annfiles/'

# # ann_path = '/data/2_data_server/cv_data/arirang/validate_objects_labeling_json/'
# label_test = []

# c1 = 0
# c2 = 0
# c3 = 0
# c4 = 0
# c5 = 0
# c6 = 0
# c7 = 0
# c8 = 0
# c9 = 0
# c10 = 0
# c11 = 0
# c12 = 0
# c13 = 0
# c14 = 0
# c15 = 0
# c16 = 0
# c17 = 0
# c18 = 0
# c19 = 0
# c20 = 0
# c21 = 0

# c1_num = 0
# c2_num = 0
# c3_num = 0
# c4_num = 0
# c5_num = 0
# c6_num = 0
# c7_num = 0
# c8_num = 0
# c9_num = 0
# c10_num = 0
# c11_num = 0
# c12_num = 0
# c13_num = 0
# c14_num = 0
# c15_num = 0
# c16_num = 0
# c17_num = 0
# c18_num = 0
# c19_num = 0
# c20_num = 0
# c21_num = 0

# for i in glob(ann_path+'*.json'):
#     # print(i)
#     with open(i) as f:
#         json_data = json.load(f)

#     for j in range(len(json_data['features'])):

#         bbox_info = json_data['features'][j]['properties']['object_imcoords']
#         bbox_info = ast.literal_eval(bbox_info)

#         poly = np.array(bbox_info,dtype=np.float32)

#         poly = poly2obb_np(poly)

#         if poly is not None:
#             w = poly[2]
#             h = poly[3]
#             area = w*h
#         # area =
#             bbox_label = json_data['features'][j]['properties']['type_name'].replace(" ","-")

#             if bbox_label =="small-ship":
#                 c1 += 1
#                 c1_num += area
#             if bbox_label =="large-ship":
#                 c2 += 1
#                 c2_num += area
#             if bbox_label =="civilian-aircraft":
#                 c3 += 1
#                 c3_num += area
#             if bbox_label =="military-aircraft":
#                 c4 += 1
#                 c4_num += area
#             if bbox_label =="small-car":
#                 c5 += 1
#                 c5_num += area
#             if bbox_label =="bus":
#                 c6 += 1
#                 c6_num += area
#             if bbox_label =="truck":
#                 c7 += 1
#                 c7_num += area
#             if bbox_label =="train":
#                 c8 += 1
#                 c8_num += area
#             if bbox_label =="crane":
#                 c9 += 1
#                 c9_num += area
#             if bbox_label =="bridge":
#                 c10 += 1
#                 c10_num += area
#             if bbox_label =="oil-tank":
#                 c11 += 1
#                 c11_num += area
#             if bbox_label =="dam":
#                 c12 += 1
#                 c12_num += area
#             if bbox_label =="outdoor-playground":
#                 c13 += 1
#                 c13_num += area
#             if bbox_label =="helipad":
#                 c14 += 1
#                 c14_num += area
#             if bbox_label =="roundabout":
#                 c15 += 1
#                 c15_num += area
#             if bbox_label =="indoor-playground":
#                 c16 += 1
#                 c16_num += area
#             if bbox_label =="helicopter":
#                 c17 += 1
#                 c17_num += area
#             if bbox_label =="individual-container":
#                 c18 += 1
#                 c18_num += area
#             if bbox_label =="grouped-container":
#                 c19 += 1
#                 c19_num += area
#             if bbox_label =="swimming-pool":
#                 c20 += 1
#                 c20_num += area

# print("c1------")
# print(c1,c1_num)
# print("------")
# print("c2------")
# print(c2,c2_num)
# print("------")
# print("c3------")
# print(c3,c3_num)
# print("------")
# print("c4------")
# print(c4,c4_num)
# print("------")
# print("c5------")
# print(c5,c5_num)
# print("------")
# print("c6------")
# print(c6,c6_num)
# print("------")
# print("c7------")
# print(c7,c7_num)
# print("------")
# print("c8------")
# print(c8,c8_num)
# print("------")
# print("c9------")
# print(c9,c9_num)
# print("------")
# print("c10------")
# print(c10,c10_num)
# print("------")
# print("c11------")
# print(c11,c11_num)
# print("------")
# print("c12------")
# print(c12,c12_num)
# print("------")
# print("c13------")
# print(c13,c13_num)
# print("------")
# print("c14------")
# print(c14,c14_num)
# print("------")
# print("c15------")
# print(c15,c15_num)
# print("------")
# print("c16------")
# print(c16,c16_num)
# print("------")
# print("c17------")
# print(c17,c17_num)
# print("------")
# print("c18------")
# print(c18,c18_num)
# print("------")
# print("c19------")
# print(c19,c19_num)
# print("------")
# print("c20------")
# print(c20,c20_num)
# print("------")


import json

no = 0
groups = 0
reserve = []

data = {
        "no": no,
        "groups": groups,
        "reserve": reserve
}

with open("data.json", "w") as f:
    json.dump(data, f)

opend = open("./data.json","r")
loaded = json.load(opend)

print(loaded)
print("no: ", loaded["no"], "groups: ", loaded["groups"])


"""Module contains functionality that parses main page for RedHat vulnerabilities."""

import time

import lxml
import lxml.etree
from selenium import webdriver
from selenium.common.exceptions import WebDriverException, NoSuchElementException
from selenium.webdriver.chrome.options import Options
from cve_connector.vendor_cve.implementation.parsers.general_and_format_parsers\
    .html_parser import HtmlParser
from cve_connector.vendor_cve.implementation.utilities.utility_functions import string_to_date

class RedHatMainPageParser(HtmlParser):
    """
    Class providing functionality for parsing RedHat main page.
    """
    def __init__(self, url, logger, from_date=None, to_date=None):
        super().__init__(url, from_date, to_date)
        self.date_format = '%d %b %Y'  # 20 Apr 2018
        self.driver = None
        self.entry_added = False
        self.last_added = False
        self.first_cve_on_page = ''
        self.logger = logger
        try:
            self.load_content()
        except ValueError:
            self.logger.error('Unable to load content from {0}'.format(self.url))

    def get_content_from_ulr(self):
        """
        Gets and returns content from URL.

        :return: content
        """
        if not self.url:
            raise ValueError('Url must not be empty.')
        options = Options()
        options.add_argument('--headless')
        options.add_argument('--no-sandbox')

        driver = webdriver.Chrome(chrome_options=options)
        driver.get(self.url)
        driver.implicitly_wait(10)
        content = driver.page_source
        self.driver = driver
        return content

    def parse(self):
        """
        Provides parsing functionality.

        :return: None
        """
        try:
            loading = True
            while loading:
                loading = self.parse_current_page_content()
                if loading:
                    loaded = False
                    while not loaded:
                        loaded = self.load_next_page()
        except ValueError as val_err:
            self.logger.error('Error while parsing RH.')
            self.logger.error(val_err)
        finally:
            self.driver.close()

    def do_click(self):
        """
        Accomplishes clicking on a web page.

        :return: True if successful
        """
        try:
            elm = self.driver.find_element_by_link_text("›")
            elm.click()
            return True
        except WebDriverException:
            return False

    def load_next_page(self):
        """
        Load web page.

        :return: True if successful
        """
        driver = self.driver
        try:
            click = False
            start = time.time()
            end = time.time()
            while not click:
                if (end - start) > 120:
                    raise ValueError('RedHat page could not be loaded.')
                driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
                click = self.do_click()
                self.logger.debug("CLICK in RedHat")
                end = time.time()

            time.sleep(3)
            content = driver.page_source
            self.data = lxml.etree.HTML(content.replace('<br>', ''))
            self.driver = driver
            return True
        except (NoSuchElementException, WebDriverException):
            return False

    def parse_current_page_content(self):
        """
        Parses current page in property data.

        :return: True if next page is needed to load, False otherwise.
        """
        table_rows = self.data.xpath(
            './/table[contains(@summary, "Common Vulnerabilities and Exposures")]//tbody/tr')
        for row in table_rows:
            url_list = row.xpath('.//th//a/@href')
            date_str_list = row.xpath('.//td//time/text()')
            if len(url_list) != 1 or len(date_str_list) != 1:
                raise ValueError('Format of data provided in RH table has changed.')

            date = string_to_date(date_str_list[0], self.date_format)
            if date < self.from_date:
                return False
            if self.from_date <= date <= self.to_date:
                self.entities.append(url_list[0])
                self.entry_added = True
                self.last_added = True
            else:
                self.last_added = False
            if not self.last_added and self.entry_added:
                return False
        return self.last_added or not self.entry_added


import matplotlib.pyplot as plt
from pymol import cmd
from multiprocessing import Pool, cpu_count
from tqdm import tqdm  # Import tqdm for progress bar

# Define a function to calculate RMSD for a single frame
def calculate_rmsd(frame_number, object_1, reference_object):
    cmd.frame(frame_number)
    #cmd.align(object_1, reference_object, frame_number, 1)
    return cmd.rms_cur(object_1, reference_object, frame_number, 0)

# Define the process_frame function outside of RMSD_vs_frame
def process_frame(args):
    return calculate_rmsd(*args)

# Define a function to plot RMSD vs frame number
def RMSD_vs_frame(object_1, stride=1, num_process=1):
    # Initialize an empty list to store RMSDs
    RMSDs = []
    reference_object = 'ref'
    cmd.create(reference_object, object_1, 1, 0)

    # Calculate total number of frames
    total_frames = cmd.count_states(object_1)

    # Set default number of processes if not specified
    if num_process == 1:
        num_process = min(cpu_count(), total_frames)  # Use the number of CPU cores or total_frames, whichever is smaller

    # Create a list of frame numbers to process
    frames_to_process = range(1, total_frames + 1, stride)

    # Create a list of arguments for the process_frame function
    args_list = [(frame_number, object_1, reference_object) for frame_number in frames_to_process]

    # Create a pool of workers for multiprocessing
    with Pool(processes=num_process) as pool, tqdm(total=len(args_list), desc="Calculating RMSD") as pbar:
        # Use multiprocessing to calculate RMSD for each frame
        for rmsd in pool.imap_unordered(process_frame, args_list):
            RMSDs.append(rmsd)
            pbar.update(1)  # Update the progress bar

    # Create x and y data for the plot
    x1 = frames_to_process    # Frame numbers will be on the x-axis
    y1 = RMSDs                # RMSDs will be on the y-axis

    # Plot the data
    plt.figure()
    plt.plot(x1, y1, label=object_1, color='blue', linewidth=2)
    plt.xlabel('Frame', fontsize=12)
    plt.ylabel('Distance', fontsize=12)
    plt.title('Distance vs Frame', fontsize=16)
    plt.legend(fontsize=10)
    plt.grid(True, linestyle='--', linewidth=0.5, alpha=0.7)
    plt.tick_params(axis='both', which='major', labelsize=10)
    plt.tight_layout()  # Adjust the spacing for better layout
    plt.show()  # Display the plot

# Usage: RMSD_vs_frame('object_name', stride=1, num_process=1)
print("USAGE: RMSD_vs_frame('protein selection', stride=5, num_process=4)")


from django.conf import settings
from django.db.models import Q

from django_filters import rest_framework as filters

from ...models import Event

class EventFilterSet(filters.FilterSet):

    category = filters.MultipleChoiceFilter(
        method='filter_category',
        label='Category',
        choices=settings.EVENT_TYPE_CHOICES,
    )
    follow_type = filters.MultipleChoiceFilter(
        method='filter_follow_type',
        label='Follow Type',
        choices=settings.EVENT_FOLLOW_MODE_CHOICES,
    )

    languages = filters.CharFilter(
        method='filter_languages',
    )

    location = filters.CharFilter(
        method='filter_location',
    )

    class Meta:
        model = Event
        fields = [
            'category',
            'follow_type',
            'languages',
            'location'
        ]

    def filter_category(self, queryset, name, value):
        query = Q()
        for query_value in value:
            query |= Q(category__code=query_value)
        return queryset.filter(query)

    def filter_follow_type(self, queryset, name, value):
        query = Q()
        for query_value in value:
            query |= Q(follow_type__contains=query_value)
        return queryset.filter(query)

    def filter_languages(self, queryset, name, value):
        query = Q()
        for language in value.split(','):
            query |= Q(languages__contains=[language])
        return queryset.filter(query)

    def filter_location(self, queryset, name, value):
        query = Q()
        for location in value.split(','):
            query |= Q(location__icontains=location)

        return queryset.filter(query)


from io import StringIO
from itertools import chain
from typing import Any, Dict, List, Union

import simplejson as json

from jubeatools import song as jbt
from jubeatools.formats.filetypes import SongFile
from jubeatools.utils import lcm

from ..tools import make_memon_dumper
from . import schema

def _long_note_tail_value_v0(note: jbt.LongNote) -> int:
    dx = note.tail_tip.x - note.position.x
    dy = note.tail_tip.y - note.position.y
    try:
        return schema.X_Y_OFFSET_TO_P_VALUE[dx, dy]
    except KeyError:
        raise ValueError(
            f"memon cannot represent a long note with its tail starting ({dx}, {dy}) away from the note"
        ) from None

def _get_timing(song: jbt.Song) -> jbt.Timing:
    if song.common_timing is not None:
        return song.common_timing
    else:
        return next(
            chart.timing for chart in song.charts.values() if chart.timing is not None
        )

def _raise_if_unfit_for_v0(song: jbt.Song, version: str) -> None:
    """Raises an exception if the Song object is ill-formed or contains information
    that cannot be represented in a memon v0.x.y file (includes legacy)"""

    if song.common_timing is None and all(
        chart.timing is None for chart in song.charts.values()
    ):
        raise ValueError("The song has no timing information")

    chart_timings = [
        chart.timing for chart in song.charts.values() if chart.timing is not None
    ]

    if chart_timings:
        first_one = chart_timings[0]
        if any(t != first_one for t in chart_timings):
            raise ValueError(
                f"memon:{version} cannot represent a song with per-chart timing"
            )

    timing = _get_timing(song)
    number_of_timing_events = len(timing.events)
    if number_of_timing_events != 1:
        if number_of_timing_events == 0:
            raise ValueError("The song has no BPM")
        else:
            raise ValueError(f"memon:{version} does not handle BPM changes")

    event = timing.events[0]
    if event.BPM <= 0:
        raise ValueError(f"memon:{version} only accepts strictly positive BPMs")

    if event.time != 0:
        raise ValueError(f"memon:{version} only accepts a BPM on the first beat")

    for difficulty, chart in song.charts.items():
        if len(set(chart.notes)) != len(chart.notes):
            raise ValueError(
                f"{difficulty} chart has duplicate notes, these cannot be represented"
            )

def _dump_to_json(memon: dict) -> bytes:
    memon_fp = StringIO()
    json.dump(memon, memon_fp, use_decimal=True, indent=4)
    return memon_fp.getvalue().encode("utf-8")

def _compute_resolution(notes: List[Union[jbt.TapNote, jbt.LongNote]]) -> int:
    return lcm(
        *chain(
            iter(note.time.denominator for note in notes),
            iter(
                note.duration.denominator
                for note in notes
                if isinstance(note, jbt.LongNote)
            ),
        )
    )

def _dump_memon_note_v0(
    note: Union[jbt.TapNote, jbt.LongNote], resolution: int
) -> Dict[str, int]:
    """converts a note into the {n, t, l, p} form"""
    memon_note = {
        "n": note.position.index,
        "t": note.time.numerator * (resolution // note.time.denominator),
        "l": 0,
        "p": 0,
    }
    if isinstance(note, jbt.LongNote):
        memon_note["l"] = note.duration.numerator * (
            resolution // note.duration.denominator
        )
        memon_note["p"] = _long_note_tail_value_v0(note)

    return memon_note

def _dump_memon_legacy(song: jbt.Song, **kwargs: Any) -> SongFile:
    _raise_if_unfit_for_v0(song, "legacy")
    timing = _get_timing(song)

    memon: Dict[str, Any] = {
        "metadata": {
            "song title": song.metadata.title,
            "artist": song.metadata.artist,
            "music path": str(song.metadata.audio),
            "jacket path": str(song.metadata.cover),
            "BPM": timing.events[0].BPM,
            "offset": -timing.beat_zero_offset,
        },
        "data": [],
    }
    for difficulty, chart in song.charts.items():
        resolution = _compute_resolution(chart.notes)
        memon["data"].append(
            {
                "dif_name": difficulty,
                "level": chart.level,
                "resolution": resolution,
                "notes": [
                    _dump_memon_note_v0(note, resolution)
                    for note in sorted(
                        set(chart.notes), key=lambda n: (n.time, n.position)
                    )
                ],
            }
        )

    return SongFile(contents=_dump_to_json(memon), song=song)

dump_memon_legacy = make_memon_dumper(_dump_memon_legacy)

def _dump_memon_0_1_0(song: jbt.Song, **kwargs: Any) -> SongFile:
    _raise_if_unfit_for_v0(song, "v0.1.0")
    timing = _get_timing(song)

    memon: Dict[str, Any] = {
        "version": "0.1.0",
        "metadata": {
            "song title": song.metadata.title,
            "artist": song.metadata.artist,
            "music path": str(song.metadata.audio),
            "album cover path": str(song.metadata.cover),
            "BPM": timing.events[0].BPM,
            "offset": -timing.beat_zero_offset,
        },
        "data": dict(),
    }
    for difficulty, chart in song.charts.items():
        resolution = _compute_resolution(chart.notes)
        memon["data"][difficulty] = {
            "level": chart.level,
            "resolution": resolution,
            "notes": [
                _dump_memon_note_v0(note, resolution)
                for note in sorted(set(chart.notes), key=lambda n: (n.time, n.position))
            ],
        }

    return SongFile(contents=_dump_to_json(memon), song=song)

dump_memon_0_1_0 = make_memon_dumper(_dump_memon_0_1_0)

def _dump_memon_0_2_0(song: jbt.Song, **kwargs: Any) -> SongFile:
    _raise_if_unfit_for_v0(song, "v0.2.0")
    timing = _get_timing(song)

    memon: Dict[str, Any] = {
        "version": "0.2.0",
        "metadata": {
            "song title": song.metadata.title,
            "artist": song.metadata.artist,
            "music path": str(song.metadata.audio),
            "album cover path": str(song.metadata.cover),
            "BPM": timing.events[0].BPM,
            "offset": -timing.beat_zero_offset,
        },
        "data": {},
    }

    if song.metadata.preview is not None:
        memon["metadata"]["preview"] = {
            "position": song.metadata.preview.start,
            "length": song.metadata.preview.length,
        }

    for difficulty, chart in song.charts.items():
        resolution = _compute_resolution(chart.notes)
        memon["data"][difficulty] = {
            "level": chart.level,
            "resolution": resolution,
            "notes": [
                _dump_memon_note_v0(note, resolution)
                for note in sorted(set(chart.notes), key=lambda n: (n.time, n.position))
            ],
        }

    return SongFile(contents=_dump_to_json(memon), song=song)

dump_memon_0_2_0 = make_memon_dumper(_dump_memon_0_2_0)

def _dump_memon_0_3_0(song: jbt.Song, **kwargs: Any) -> SongFile:
    _raise_if_unfit_for_v0(song, "v0.3.0")
    timing = _get_timing(song)

    memon: Dict[str, Any] = {
        "version": "0.3.0",
        "metadata": {
            "song title": song.metadata.title,
            "artist": song.metadata.artist,
            "BPM": timing.events[0].BPM,
            "offset": -timing.beat_zero_offset,
        },
        "data": {},
    }

    if song.metadata.audio is not None:
        memon["metadata"]["music path"] = str(song.metadata.audio)

    if song.metadata.cover is not None:
        memon["metadata"]["album cover path"] = str(song.metadata.cover)

    if song.metadata.preview is not None:
        memon["metadata"]["preview"] = {
            "position": song.metadata.preview.start,
            "length": song.metadata.preview.length,
        }

    if song.metadata.preview_file is not None:
        memon["metadata"]["preview path"] = str(song.metadata.preview_file)

    for difficulty, chart in song.charts.items():
        resolution = _compute_resolution(chart.notes)
        memon["data"][difficulty] = {
            "level": chart.level,
            "resolution": resolution,
            "notes": [
                _dump_memon_note_v0(note, resolution)
                for note in sorted(set(chart.notes), key=lambda n: (n.time, n.position))
            ],
        }

    return SongFile(contents=_dump_to_json(memon), song=song)

dump_memon_0_3_0 = make_memon_dumper(_dump_memon_0_3_0)