from astropy.io import fits
from astropy.wcs import WCS
from astropy import units as u
import sys
import os
import sip_tpv
import numpy
import argparse
import logging
import ccdproc

def main():
    parser = argparse.ArgumentParser(
        description=
        f"Build DIFFEXP by assembling DIFF/MASK and VARIANCE into an MEF."
        f""
        f"The VARIANCE plane is built from an analysis of the original image (ignores difference template variance)",

        fromfile_prefix_chars='@')

    parser.add_argument(
        "primary", help="base image, used for header keyword values")
    parser.add_argument(
        "interp_filename",  help="The file with base image swarped to common gird")
    parser.add_argument(
        "diff_filename",  help="The subtracted image, from ISSIS (conv_interp_????)")
    parser.add_argument(
        "mask_filename",  help="The MASK image")
    parser.add_argument(
            "--version", default='p', choices=['s','p'], help="Scrambled or Processed?")

    args = parser.parse_args()
    build_mef(args.primary, args.interp_filename, args.diff_filename, args.mask_filename, version=args.version)

def build_mef(primary: str, interp_filename: str, diff_filename: str, mask_filename: str, version: str) -> str:
    """

    :param primary: the primary image this is the DIFFEXP for
    :param interp_filename: the swarped version of primary (inter_)
    :param diff_filename: the difference image
    :param mask_filename: the mask image for this difference
    :param version: is this the scramble (s) or processed (p) version?

    :return: DIFF filename

    """

    PREFIX="DIFFEXP"
    if version == "s":
        PREFIX="rtDIFFEXP"

    with fits.open(primary) as hdulist:
        header = hdulist[0].header

    diff_hdulist = fits.HDUList()
    diff_hdulist.append(fits.PrimaryHDU(header=header))

    # get the WCS and variance from the interp image
    # this ignores variance coming from the co-add image
    with fits.open(interp_filename) as interp:
        sip_tpv.pv_to_sip(interp[0].header)
        wcs_header = WCS(interp[0].header).to_header()
        var = ccdproc.CCDData(interp[0].data, unit=u.adu)
        var = ccdproc.create_deviation(var, gain=1.6*u.electron/u.adu, readnoise=5*u.electron)
        var = var.uncertainty.array**2
        var[interp[0].data == 0] = 0

    # get the difference image
    # set the WCS using the interp_ image
    with fits.open(diff_filename) as conv_hdulist:
        conv_hdulist[0].data *= -1
        for keyword in wcs_header:
            conv_hdulist[0].header[keyword] = wcs_header[keyword]
            conv_hdulist[0].header['EXTTYPE'] = 'IMAGE'
        diff_hdulist.append(fits.ImageHDU(header=conv_hdulist[0].header, data=conv_hdulist[0].data))

    # add the mask plane, wcs from interp_
    with fits.open(mask_filename) as conv_hdulist:
        conv_hdulist[0].data = conv_hdulist[0].data * numpy.array([1]).astype('uint32')
        for keyword in wcs_header:
            conv_hdulist[0].header[keyword] = wcs_header[keyword]
        conv_hdulist[0].header['EXTTYPE'] = 'MASK'
        diff_hdulist.append(fits.ImageHDU(header=conv_hdulist[0].header, data=conv_hdulist[0].data))
        del (conv_hdulist[0].header['BITPIX'])
        diff_hdulist.append(fits.ImageHDU(header=conv_hdulist[0].header, data=var))
        diff_hdulist[-1].header['EXTTYPE'] = 'VARIANCE'

    expnum = diff_hdulist[0].header['EXPNUM']
    ccdnum = diff_hdulist[0].header["EXTVER"]
    diff_image = f"{PREFIX}-{expnum}-{ccdnum:02d}.fits"
    diff_hdulist.writeto(diff_image, overwrite=True)
    for filename in (interp_filename, diff_filename, mask_filename):
        os.unlink(filename)
    return diff_image

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Tue Nov 17 21:27:31 2020

@author: yusufkoc
"""
import EQLoS as eql
import StoryInfoWin as siw
import matplotlib.pyplot as plt
import numpy as np
import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class myApp(QtWidgets.QMainWindow):
    def __init__(self):
        super(myApp, self).__init__()
        # self.win = None
        self.ui = eql.Ui_Form()
        self.ui.setupUi(self)
        self.ui.draw_graphic.clicked.connect(self.spectrumGraphics)
        self.ui.story_info_button.clicked.connect(self.storyInfoWin)
        self.ui.calculate_button.clicked.connect(self.calcLoads)

    def storyInfoWin(self):
        self.win = QtWidgets.QMainWindow()
        self.story_win = siw.Ui_Story_info_screen()
        self.story_win.setupUi(self.win)
        self.win.show()
        self.number_story = int(self.ui.number_stories.text())
        self.story_win.story_heights.setHorizontalHeaderLabels(["Kat Yüksekliği"])
        self.story_win.story_weights.setHorizontalHeaderLabels(["Kat Ağırlığı"])
        self.story_win.story_heights.setRowCount(self.number_story)
        self.story_win.story_weights.setRowCount(self.number_story)
        self.story_win.story_info_save_button.clicked.connect(self.takeInfo)

    def takeInfo(self):
        self.storyWeights = []
        self.storyHeights = []
        self.sum_storyWeights = []
        self.sum_storyHeights = []
        for weight in range(self.number_story):
            self.storyWeights.append(float(self.story_win.story_weights.item(weight,0).text()))
            self.storyHeights.append(float(self.story_win.story_heights.item(weight,0).text()))
            self.sum_storyWeights.append(sum(self.storyWeights))
            self.sum_storyHeights.append(sum(self.storyHeights))
        self.ui.sum_structure_weight.setText(str(self.sum_storyWeights[-1]))
        self.ui.sum_structure_height.setText(str(self.sum_storyHeights[-1]))

    def spectrumGraphics(self):
        self.short_period_spectral_coeff = float(self.ui.short_period_spectral.text())
        self.one_second_period_spectral_coeff = float(self.ui.one_second_period_spectral.text())

        self.periods_graphics = np.arange(0,10,0.01)
        self.corner_period_big_result = round(self.one_second_period_spectral_coeff / self.short_period_spectral_coeff,4)
        self.corner_period_small_result = round(self.corner_period_big_result * 0.20,4)
        self.long_period = 6.0
        self.ui.corner_period_small_spectral.setText(str(self.corner_period_small_result))
        self.ui.corner_peiod_big_spectral.setText(str(self.corner_period_big_result))

        self.spectrum = []
        self.periods = []
        for self.period in self.periods_graphics:
            if 0 <= self.period < self.corner_period_small_result:
                self.Sae = (0.4 + 0.6 * self.period / self.corner_period_small_result) * self.short_period_spectral_coeff
                self.spectrum.append(self.Sae)
                self.periods.append(self.period)

            elif self.corner_period_small_result <= self.period <= self.corner_period_big_result:
                self.Sae = self.short_period_spectral_coeff
                self.spectrum.append(self.Sae)
                self.periods.append(self.period)

            elif self.corner_period_big_result < self.period <= self.long_period:
                self.Sae = self.one_second_period_spectral_coeff / self.period
                self.spectrum.append(self.Sae)
                self.periods.append(self.period)

            else:
                self.Sae = self.one_second_period_spectral_coeff * self.long_period / (self.period ** 2)
                self.spectrum.append(self.Sae)
                self.periods.append(self.period)

        plt.plot(self.periods, self.spectrum, "blue")
        plt.xlabel("Periyot")
        plt.ylabel("Yatay elastik tasarım spektral ivmesi")
        #plt.savefig("spektralGraph.png")
        #self.graphic.show()
        #self.imageGraph = QtGui.QImage("spektralGraph.png")
        #self.sizeImage =self.imageGraph(QtCore.QSize(100,100))
        #self.palette = QtGui.QPalette()
        #self.palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(self.sizeImage))
        #self.setPalette(self.palette)

    def calcLoads(self):
        self.ui.list_X.clear()
        self.ui.list_Y.clear()
        self.period_structure_X = float(self.ui.period_structure_X_direct.text())
        self.period_structure_Y = float(self.ui.period_structure_Y_direct.text())
        self.eql_reduce_coeff_X = int(self.ui.EQL_reduce_coeff_X_direct.text())
        self.eql_reduce_coeff_Y = int(self.ui.EQL_reduce_coeff_Y_direct.text())
        self.important_coeff = float(self.ui.struct_important_coeff.text())

        if 0 <= self.period_structure_X <= self.corner_period_small_result:
            self.Sae_X = (0.4 + 0.6 * (self.period_structure_X / self.corner_period_small_result)) * self.short_period_spectral_coeff
        elif self.corner_period_small_result <= self.period_structure_X <= self.corner_period_big_result:
            self.Sae_X = self.short_period_spectral_coeff
        elif self.corner_period_big_result <= self.period_structure_X <= self.long_period:
            self.Sae_X = self.one_second_period_spectral_coeff / self.period_structure_X
        else:
            self.Sae_X = (self.one_second_period_spectral_coeff * self.long_period) / (self.period_structure_X ** 2)

        if 0 <= self.period_structure_Y <= self.corner_period_small_result:
            self.Sae_Y = (0.4 + 0.6 * (self.period_structure_Y / self.corner_period_small_result)) * self.short_period_spectral_coeff
        elif self.corner_period_small_result <= self.period_structure_Y <= self.corner_period_big_result:
            self.Sae_Y = self.short_period_spectral_coeff
        elif self.corner_period_big_result <= self.period_structure_Y <= self.long_period:
            self.Sae_Y = self.one_second_period_spectral_coeff / self.period_structure_Y
        else:
            self.Sae_Y = (self.one_second_period_spectral_coeff * self.long_period) / (self.period_structure_Y ** 2)

        self.SaR_X = self.Sae_X / self.eql_reduce_coeff_X
        self.SaR_Y = self.Sae_Y / self.eql_reduce_coeff_Y
        self.Vt_X = round((float(self.ui.sum_structure_weight.text()) * self.SaR_X * 9.8075),3)
        self.Vt_Y = round((float(self.ui.sum_structure_weight.text()) * self.SaR_Y * 9.8075),3)

        self.ui.base_shear_load_X_direct.setText(str(self.Vt_X))
        self.ui.base_shear_load_Y_direct.setText(str(self.Vt_Y))

        self.loadFile = open("storyloads_new.txt","w")
        self.StoryLoad_X = []
        self.StoryLoad_Y = []

        self.deltaFN_X = 0.0075 * int(self.ui.number_stories.text()) * self.Vt_X
        self.deltaFN_Y = 0.0075 * int(self.ui.number_stories.text()) * self.Vt_Y
        self.sum_Fi_X = self.Vt_X - self.deltaFN_X
        self.sum_Fi_Y = self.Vt_Y - self.deltaFN_Y

        self.miHi = [a * b for a,b in zip(self.storyWeights, self.sum_storyHeights)]
        self.sum_miHi = sum(self.miHi)
        for self.mHx in self.miHi:
            self.Fi_X = self.sum_Fi_X * (self.mHx / self.sum_miHi)
            self.StoryLoad_X.append(self.Fi_X)
        for self.mHy in self.miHi:
            self.Fi_Y = self.sum_Fi_Y * (self.mHy / self.sum_miHi)
            self.StoryLoad_Y.append(self.Fi_Y)

        i = 0
        while i < int(self.ui.number_stories.text()):
            self.result_text_X = f"{i+1}. kata etkiyen deprem yükü X : {round((self.StoryLoad_X[i]),2)}"
            self.result_text_Y = f"{i+1}. kata etkiyen deprem yükü Y : {round((self.StoryLoad_Y[i]),2)}"
            self.ui.list_X.addItem(self.result_text_X)
            self.ui.list_Y.addItem(self.result_text_Y)
            i += 1

def app():
    app = QtWidgets.QApplication(sys.argv)
    win = myApp()
    win.setWindowIcon(QtGui.QIcon("icon.jpg"))
    win.show()
    sys.exit(app.exec_())

app()


#Iterative Form

def fibIte(n):
    a = 0
    b = 1

    for k in range(n):
        c = a + b
        a = b
        b = c

    return b

print("Result with Iterative Form: ")

for x in range(20):

    print(fibIte(x))

# Recursive Form

def fibRec(n):
    # fn = fn-1 + fn-2
    if n < 3:
        return n
    return fibRec(n-1) + fibRec(n-2)

print("Result with Recursive Form: ")

for x in range(20):

    print(fibRec(x))


#!/usr/bin/env python3

import sys

if len(sys.argv) != 2:
    sys.stderr.write("Usage: {} <inputfile>\n".format(sys.argv[0]))
    exit(1)

filename = sys.argv[1]

try:
    with open(filename, 'r') as stream:
        hydrophobic_chars = ['A', 'F', 'I', 'L', 'M', 'P', 'V', 'W']
        hydrophilic_chars = ['C', 'D', 'E', 'G', 'H', 'K', 'N', 'Q', 'R', 'S', 'T', 'Y']

        print("# hydrophobic\thydrophilic")

        for line in stream:
            [hydrophobic, hydrophilic] = [0, 0]

            for c in line:
                if c in hydrophobic_chars:
                    hydrophobic+=1
                elif c in hydrophilic_chars:
                    hydrophilic+=1

            print("{}\t{}".format(hydrophobic, hydrophilic))
except:
    sys.stderr.write("Could not open file '{}' \n".format(sys.argv[1]))
    exit(1)


## advent of code 2017
## https://adventofcode.com/2017
## day 08

import re

instruction_re = re.compile(
    r"(\w+) (inc|dec) (-?\d*) if (\w+) (>|<|>=|==|<=|!=) (-?\d*)"
)

class Instruction:
    def __init__(self, line):
        self.register_names = set()
        match = instruction_re.search(line)
        self.target_reg = match.group(1)
        if match.group(2) == "inc":
            self.multiplier = 1
        else:
            self.multiplier = -1

        self.modifier = int(match.group(3))
        self.comp_reg = match.group(4)
        self.comparison = match.group(5)
        self.comparitor = int(match.group(6))

class Puzzle:
    def __init__(self, lines):
        self.instructions = []
        self.register_names = set()
        for line in lines:
            instruction = Instruction(line)
            self.instructions.append(instruction)
            self.register_names.add(instruction.target_reg)
            self.register_names.add(instruction.comp_reg)

    def reset_registers(self):
        self.highest_reg_value = 0
        self.registers = {}
        for reg in self.register_names:
            self.registers[reg] = 0

    def execute_instruction(self, instruction):
        value1 = self.registers[instruction.comp_reg]
        value2 = instruction.comparitor
        should_execute = False
        if instruction.comparison == "==":
            should_execute = value1 == value2
        elif instruction.comparison == "!=":
            should_execute = not (value1 == value2)
        elif instruction.comparison == ">":
            should_execute = value1 > value2
        elif instruction.comparison == "<":
            should_execute = value1 < value2
        elif instruction.comparison == "<=":
            should_execute = value1 <= value2
        elif instruction.comparison == ">=":
            should_execute = value1 >= value2
        else:
            assert False
        if should_execute:
            old_value = self.registers[instruction.target_reg]
            new_value = old_value + instruction.modifier * instruction.multiplier
            self.highest_reg_value = max(self.highest_reg_value, new_value)
            self.registers[instruction.target_reg] = new_value

    def run_program(self):
        for instruction in self.instructions:
            self.execute_instruction(instruction)

    def get_largest_register_value(self):
        max_value = 0
        for reg in self.registers.values():
            max_value = max(max_value, reg)

        return max_value

def parse_input(lines):
    return Puzzle(lines)

def part1(puzzle):
    puzzle.reset_registers()
    puzzle.run_program()
    return puzzle.get_largest_register_value()

def part2(puzzle):
    return puzzle.highest_reg_value


import yt_dlp
from yt_dlp.utils import DownloadError

ydlp = yt_dlp.YoutubeDL()

def get_info(url):
    with ydlp:
        try:
            result = ydlp.extract_info(url, download=False)
        except DownloadError:
            return None

    if "entries" in result:
        video = result["entries"][0]
    else:
        video = result

    infos = ["id", "title", "channel", "view_count", "like_count", "channel_id", "duration", "categories", "tags"]

    def key_name(key):
        if key == "id":
            return "video_id"
        return key

    return {key_name(key): video[key] for key in infos}


from typing import Optional, Any, Dict
from typing_extensions import Literal

from phidata.aws.api_client import AwsApiClient
from phidata.aws.resource.base import AwsResource
from phidata.utils.cli_console import print_info, print_error
from phidata.utils.log import logger

class S3Bucket(AwsResource):
    """
    # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#service-resource
    """

    resource_type = "s3.Bucket"
    service_name = "s3"

    # name of bucket
    name: str
    # The canned ACL to apply to the bucket.
    acl: Optional[
        Literal["private", "public-read", "public-read-write", "authenticated-read"]
    ] = None
    grant_full_control: Optional[str] = None
    grant_read: Optional[str] = None
    grant_read_ACP: Optional[str] = None
    grant_write: Optional[str] = None
    grant_write_ACP: Optional[str] = None
    object_lock_enabled_for_bucket: Optional[bool] = None
    object_ownership: Optional[
        Literal["BucketOwnerPreferred", "ObjectWriter", "BucketOwnerEnforced"]
    ] = None

    def _create(self, aws_client: AwsApiClient) -> bool:
        """Creates the s3.Bucket

        Args:
            aws_client: The AwsApiClient for the current cluster
        """
        print_info(f"Creating {self.get_resource_type()}: {self.get_resource_name()}")

        # Step 1: Build bucket configuration
        # Bucket names are GLOBALLY unique!
        # AWS will give you the IllegalLocationConstraintException if you collide
        # with an already existing bucket and you've specified a region different than
        # the region of the already existing bucket. If you happen to guess the correct region of the
        # existing bucket it will give you the BucketAlreadyExists exception.
        bucket_configuration = None
        if aws_client.aws_region != "us-east-1":
            bucket_configuration = {"LocationConstraint": aws_client.aws_region}

        # create a dict of args which are not null, otherwise aws type validation fails
        not_null_args: Dict[str, Any] = {}
        if bucket_configuration:
            not_null_args["CreateBucketConfiguration"] = bucket_configuration
        if self.acl:
            not_null_args["ACL"] = self.acl
        if self.grant_full_control:
            not_null_args["GrantFullControl"] = self.grant_full_control
        if self.grant_read:
            not_null_args["GrantRead"] = self.grant_read
        if self.grant_read_ACP:
            not_null_args["GrantReadACP"] = self.grant_read_ACP
        if self.grant_write:
            not_null_args["GrantWrite"] = self.grant_write
        if self.grant_write_ACP:
            not_null_args["GrantWriteACP"] = self.grant_write_ACP
        if self.object_lock_enabled_for_bucket:
            not_null_args[
                "ObjectLockEnabledForBucket"
            ] = self.object_lock_enabled_for_bucket
        if self.object_ownership:
            not_null_args["ObjectOwnership"] = self.object_ownership

        # Step 2: Create Bucket
        service_resource = self.get_service_resource(aws_client)
        try:
            bucket = service_resource.create_bucket(Bucket=self.name, **not_null_args)
            logger.debug(f"Bucket: {bucket}")

            # Validate Bucket creation
            bucket.load()
            creation_date = bucket.creation_date
            logger.debug(f"creation_date: {creation_date}")
            if creation_date is not None:
                print_info(f"Bucket created: {bucket.name}")
                self.active_resource = bucket
                return True
        except Exception as e:
            print_error(f"{self.get_resource_type()} could not be created.")
            print_error(e)
        return False

    def post_create(self, aws_client: AwsApiClient) -> bool:

        # Wait for Bucket to be created
        if self.wait_for_creation:
            try:
                print_info(f"Waiting for {self.get_resource_type()} to be created.")
                waiter = self.get_service_client(aws_client).get_waiter("bucket_exists")
                waiter.wait(
                    Bucket=self.name,
                    WaiterConfig={
                        "Delay": self.waiter_delay,
                        "MaxAttempts": self.waiter_max_attempts,
                    },
                )
            except Exception as e:
                print_error("Waiter failed.")
                print_error(e)
        return True

    def _read(self, aws_client: AwsApiClient) -> Optional[Any]:
        """Returns the s3.Bucket

        Args:
            aws_client: The AwsApiClient for the current cluster
        """
        logger.debug(f"Reading {self.get_resource_type()}: {self.get_resource_name()}")

        from botocore.exceptions import ClientError

        service_resource = self.get_service_resource(aws_client)
        try:
            bucket = service_resource.Bucket(name=self.name)

            bucket.load()
            creation_date = bucket.creation_date
            logger.debug(f"Bucket creation_date: {creation_date}")
            if creation_date is not None:
                logger.debug(f"Bucket found: {bucket.name}")
                self.active_resource = bucket
        except ClientError as ce:
            logger.debug(f"ClientError: {ce}")
        except Exception as e:
            print_error(f"Error reading {self.get_resource_type()}.")
            print_error(e)
        return self.active_resource

    def _delete(self, aws_client: AwsApiClient) -> bool:
        """Deletes the s3.Bucket

        Args:
            aws_client: The AwsApiClient for the current cluster
        """
        print_info(f"Deleting {self.get_resource_type()}: {self.get_resource_name()}")

        self.active_resource = None
        try:
            bucket = self._read(aws_client)
            logger.debug(f"Bucket: {bucket}")
            if bucket is None:
                logger.warning(f"No {self.get_resource_type()} to delete")
                return True

            bucket.delete()
            print_info(f"Bucket deleted: {bucket}")
            return True
        except Exception as e:
            print_error(f"{self.get_resource_type()} could not be deleted.")
            print_error(e)
        return False

    def get_uri(self) -> str:
        """Returns the URI of the s3.Bucket

        Returns:
            str: The URI of the s3.Bucket
        """
        return f"s3://{self.name}"


import json
import os
import uuid
import asyncio

class Config:
    """The "database" object. Internally based on ``json``."""

    def __init__(self, name, **options):
        self.name = name
        self.object_hook = options.pop('object_hook', None)
        self.encoder = options.pop('encoder', None)

        try:
            hook = options.pop('hook')
        except KeyError:
            pass
        else:
            self.object_hook = hook.from_json
            self.encoder = self._create_encoder(hook)

        self.loop = options.pop('loop', asyncio.get_event_loop())
        self.lock = asyncio.Lock()
        if options.pop('load_later', False):
            self.loop.create_task(self.load())
        else:
            self.load_from_file()

    def _create_encoder(cls):
        def _default(self, o):
            if isinstance(o, cls):
                return o.to_json()
            return super().default(o)

        return type('_Encoder', (json.JSONEncoder,), { 'default': _default })

    def load_from_file(self):
        try:
            with open(self.name, 'r') as f:
                self._db = json.load(f, object_hook=self.object_hook)
        except FileNotFoundError:
            self._db = {}

    async def load(self):
        async with self.lock:
            await self.loop.run_in_executor(None, self.load_from_file)

    def _dump(self):
        temp = '%s-%s.tmp' % (uuid.uuid4(), self.name)
        with open(temp, 'w', encoding='utf-8') as tmp:
            json.dump(self._db.copy(), tmp, ensure_ascii=True, cls=self.encoder, separators=(',', ':'))

        # atomically move the file
        os.replace(temp, self.name)

    async def save(self):
        async with self.lock:
            await self.loop.run_in_executor(None, self._dump)

    def get(self, key, *args):
        """Retrieves a config entry."""
        return self._db.get(str(key), *args)

    async def put(self, key, value, *args):
        """Edits a config entry."""
        self._db[str(key)] = value
        await self.save()

    async def remove(self, key):
        """Removes a config entry."""
        del self._db[str(key)]
        await self.save()

    def __contains__(self, item):
        return str(item) in self._db

    def __getitem__(self, item):
        return self._db[str(item)]

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

    def all(self):
        return self._db


# medium

'''
You have n bags numbered from 0 to n - 1.
You are given two 0-indexed integer arrays capacity and rocks.
The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks.
You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags.

Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags.
'''

class Solution:
    def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int:

        result = []
        count = 0

        for i in range(len(capacity)):
            result.append((capacity[i] - rocks[i]))

        if additionalRocks >= sum(result):
                return len(capacity)

        result.sort()

        i = 0
        while additionalRocks >= 0:
            additionalRocks -= result[i]
            count += 1
            i += 1

        return count - 1

class Solution:
    def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int:
        diff = [x - y for x, y in zip(capacity, rocks)]
        diff.sort()
        ans = 0
        for x in diff:
            if x <= additionalRocks:
                ans += 1
                additionalRocks -= x
        return ans

Medium/2279. Maximum Bags With Full Capacity of Rocks.py


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from math import sqrt
from statsmodels.tsa.api import ExponentialSmoothing, SimpleExpSmoothing, Holt
import statsmodels.api as sm
import warnings
warnings.filterwarnings("ignore")
#we will use the yearly dataset to forecast the next years total of students that will use the cafeteria
#we also see that seasonality plays an important role in the amount of students that use the cafeteria
#so different from the monthly estimation, we also will use Holt-Winters to consider the seasonality

df = pd.read_csv("yearlycafeteria.csv", sep=',', usecols = ["student"])
print(df.axes)

seriesname = 'student'
series = df
sarray = np.asarray(series)
print("Estimating", "student")
print("Series Data:", sarray)

size = len(series)
train = series[0:size-5]
trainarray= np.asarray(train)
test = series[size-5:]
testarray = np.asarray(test)
print("Training data:", trainarray, "Test data:", testarray)

#Naive approach
print("Naive")
dd= np.asarray(train.values)
y_hat = test.copy()
y_hat['naive'] = [dd[len(dd)-1]]*len(test)
rms = sqrt(mean_squared_error(test.values, y_hat.naive))
print("RMSE: ",rms)

#Simple average approach
print("Simple Average")
y_hat_avg = test.copy()
y_hat_avg['avg_forecast'] = train.values.mean()
rms = sqrt(mean_squared_error(test.values, y_hat_avg.avg_forecast))
print("RMSE: ",rms)

#Moving average approach
print("Moving Average")
windowsize = 1
y_hat_avg = test.copy()
y_hat_avg['moving_avg_forecast'] = [train.rolling(windowsize).mean().iloc[-1]]*len(test)
rms = sqrt(mean_squared_error(test.values, y_hat_avg.moving_avg_forecast))
print("RMSE: ",rms)

# Simple Exponential Smoothing
print("Simple Exponential Smoothing")
y_hat_avg = test.copy()
alpha = 0.2
fit2 = SimpleExpSmoothing(np.asarray(train.values)).fit(smoothing_level=alpha,optimized=False)
y_hat_avg['SES'] = fit2.forecast(len(test))
rms = sqrt(mean_squared_error(test.values, y_hat_avg.SES))
print("RMSE: ",rms)

# Holt
print("Holt")
date_range = pd.date_range(start = '01-01-2018', freq='MS', periods = len(train))
train = pd.DataFrame({'values': train.values[:,0]}, index=date_range)
sm.tsa.seasonal_decompose(train).plot()
result = sm.tsa.stattools.adfuller(train.iloc[:,0].values)
# plt.show()

y_hat_avg = test.copy()
alpha = 0.4
fit1 = Holt(np.asarray(train.values)).fit(smoothing_level = alpha,smoothing_slope = 0.1)
y_hat_avg['Holt_linear'] = fit1.forecast(len(test))
rms = sqrt(mean_squared_error(test.values, y_hat_avg.Holt_linear))
print("RMSE: ",rms)
#because there are some seasonal differences among the months, we also use Holt-Winters for this dataset
# Holt-Winters
print("Holt-Winters")
y_hat_avg = test.copy()
seasons = 12
fit1 = ExponentialSmoothing(np.asarray(train.values) ,seasonal_periods=seasons ,trend='add', seasonal='add',).fit()
y_hat_avg['Holt_Winter'] = fit1.forecast(len(test))
rms = sqrt(mean_squared_error(test.values, y_hat_avg.Holt_Winter))
print("RMSE: ",rms)

# Holtlari data eksigi yuzunden calistiramadik hocam :(


from xml.etree.ElementTree import Element

from frappe.model.document import Document
from trebelge.TRUBLCommonElementsStrategy.TRUBLCommonElement import TRUBLCommonElement
from trebelge.TRUBLCommonElementsStrategy.TRUBLDocumentReference import TRUBLDocumentReference
from trebelge.TRUBLCommonElementsStrategy.TRUBLLocation import TRUBLLocation

class TRUBLMaritimeTransport(TRUBLCommonElement):
    _frappeDoctype = 'UBL TR MaritimeTransport'

    def process_element(self, element: Element, cbcnamespace: str, cacnamespace: str) -> Document:
        frappedoc: dict = {}
        # ['VesselID'] = ('cbc', '', 'Seçimli (0...1)')
        # ['VesselName'] = ('cbc', '', 'Seçimli (0...1)')
        # ['RadioCallSignID'] = ('cbc', '', 'Seçimli (0...1)')
        cbcsecimli01: list = ['VesselID', 'VesselName', 'RadioCallSignID']
        for elementtag_ in cbcsecimli01:
            field_: Element = element.find('./' + cbcnamespace + elementtag_)
            if field_ is not None:
                if field_.text is not None:
                    frappedoc[elementtag_.lower()] = field_.text
        # ['GrossTonnageMeasure'] = ('cbc', '', 'Seçimli (0...1)')
        grosstonnagemeasure_: Element = element.find('./' + cbcnamespace + 'GrossTonnageMeasure')
        if grosstonnagemeasure_ is not None:
            if grosstonnagemeasure_.text is not None:
                frappedoc['grosstonnagemeasure'] = grosstonnagemeasure_.text
                frappedoc['grosstonnagemeasureunitcode'] = grosstonnagemeasure_.attrib.get('unitCode')
        # ['NetTonnageMeasure'] = ('cbc', '', 'Seçimli (0...1)')
        nettonnagemeasure_: Element = element.find('./' + cbcnamespace + 'NetTonnageMeasure')
        if nettonnagemeasure_ is not None:
            if nettonnagemeasure_.text is not None:
                frappedoc['nettonnagemeasure'] = nettonnagemeasure_.text
                frappedoc['nettonnagemeasureunitcode'] = nettonnagemeasure_.attrib.get('unitCode')
        # ['RegistryCertificateDocumentReference'] = ('cac', 'DocumentReference', 'Seçimli (0...1)')
        # ['RegistryPortLocation'] = ('cac', 'Location', 'Seçimli (0...1)')
        cacsecimli01: list = \
            [{'Tag': 'RegistryCertificateDocumentReference', 'strategy': TRUBLDocumentReference(),
              'fieldName': 'registrycertificatedocumentreference'},
             {'Tag': 'RegistryPortLocation', 'strategy': TRUBLLocation(), 'fieldName': 'registryportlocation'}
             ]
        for element_ in cacsecimli01:
            tagelement_: Element = element.find('./' + cacnamespace + element_.get('Tag'))
            if tagelement_ is not None:
                tmp = element_.get('strategy').process_element(tagelement_, cbcnamespace, cacnamespace)
                if tmp is not None:
                    frappedoc[element_.get('fieldName')] = tmp.name
        if frappedoc == {}:
            return None
        document = self._get_frappedoc(self._frappeDoctype, frappedoc)
        # ['ShipsRequirements'] = ('cbc', '', 'Seçimli (0...n)')
        shipsrequirements_: list = element.findall('./' + cbcnamespace + 'ShipsRequirements')
        if len(shipsrequirements_) != 0:
            for shipsrequirement_ in shipsrequirements_:
                element_ = shipsrequirement_.text
                if element_ is not None and element_.strip() != '':
                    document.append("shipsrequirements", dict(note=element_.strip()))
                    document.save()

        return document

    def process_elementasdict(self, element: Element, cbcnamespace: str, cacnamespace: str) -> dict:
        pass


import json
import operator
from itertools import groupby

from flask import Flask, request
from flask_api import status
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError

from grading.configuration import SQLALCHEMY_DATABASE_URI
from grading.redis_client import set_lock, release_lock
from grading.validators import validate_student, auth, validate_email, validate_course, validate_students, \
    validate_grade, validate_grade_range

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

@app.route('/student', methods = ['POST'])
@auth.login_required
def add_student():
    from grading.models import add_student_model
    student_data = request.get_json()
    first_name = student_data.get('first_name')
    second_name = student_data.get('second_name')
    email = student_data.get('email')
    validate_message = validate_student(first_name, second_name, email)
    if validate_message:
        return validate_message, status.HTTP_400_BAD_REQUEST

    try:
        result = add_student_model(student_data)
    except IntegrityError:
        return 'student email  exists', status.HTTP_409_CONFLICT
    return json.dumps(result), status.HTTP_201_CREATED

@app.route('/student/<int:id>', methods = ['PUT'])
@auth.login_required
def update_student(id):
    from grading.models import update_student_model
    student_data = request.get_json()
    email = student_data.get('email')
    if email:
        message = validate_email(email)
        if message:
            return message, status.HTTP_400_BAD_REQUEST
    try:
        set_lock('student'+str(id))
        if not update_student_model(id, student_data):
            return 'student not found', status.HTTP_404_NOT_FOUND
    finally:
        release_lock('student'+str(id))
    result = {'id': id}
    return json.dumps(result), status.HTTP_200_OK

@app.route('/student/<int:id>', methods = ['DELETE'])
@auth.login_required
def delete_student(id):
    from grading.models import delete_student_model

    try:
        set_lock('student'+str(id))
        if not delete_student_model(id):
            return 'student not found', status.HTTP_404_NOT_FOUND
    finally:
        release_lock('student'+str(id))
    return '', status.HTTP_204_NO_CONTENT

@app.route('/student/<int:id>', methods = ['GET'])
@auth.login_required
def get_student(id):
    from grading.models import get_student_model

    result = get_student_model(id)
    if result:
        return json.dumps(result), status.HTTP_200_OK
    else:
        return 'student not found', status.HTTP_404_NOT_FOUND

@app.route('/course', methods = ['POST'])
@auth.login_required
def add_course():
    from grading.models import add_course_model
    course_data = request.get_json()
    name = course_data.get('name')
    students = course_data.get('students')
    validate_message = validate_course(name, students)
    if validate_message:
        return validate_message, status.HTTP_400_BAD_REQUEST
    try:
        result = add_course_model(course_data)
    except IntegrityError:
        return 'course exists', status.HTTP_409_CONFLICT
    return json.dumps(result), status.HTTP_201_CREATED

@app.route('/course/<int:id>', methods = ['PUT'])
@auth.login_required
def update_course(id):
    from grading.models import update_course_model
    course_data = request.get_json()
    students = course_data.get('students')
    if students:
        message = validate_students(students)
        if message:
            return message, status.HTTP_400_BAD_REQUEST
    try:
        set_lock('course'+str(id))
        if not update_course_model(id, course_data):
            return 'course not found', status.HTTP_404_NOT_FOUND
    finally:
        release_lock('course'+str(id))
    result = {'id': id}
    return json.dumps(result), status.HTTP_200_OK

@app.route('/course/<int:id>', methods = ['DELETE'])
@auth.login_required
def delete_course(id):
    from grading.models import delete_course_model

    try:
        set_lock('course'+str(id))
        if not delete_course_model(id):
            return 'course not found', status.HTTP_404_NOT_FOUND
    finally:
        release_lock('course'+str(id))
    return '', status.HTTP_204_NO_CONTENT

@app.route('/course/<int:id>', methods = ['GET'])
@auth.login_required
def get_course(id):
    from grading.models import get_course_model

    result = get_course_model(id)
    if result:
        return json.dumps(result), status.HTTP_200_OK
    else:
        return 'course not found', status.HTTP_404_NOT_FOUND

@app.route('/grade', methods = ['POST'])
@auth.login_required
def add_grade():
    from grading.models import add_grade_model
    grade_data = request.get_json()
    grade = grade_data.get('grade')
    student = grade_data.get('student')
    course = grade_data.get('course')
    validate_message = validate_grade(grade, student, course)
    if validate_message:
        return validate_message, status.HTTP_400_BAD_REQUEST
    try:
        add_grade_model(grade_data)
    except IntegrityError:
        return 'bad parameters', status.HTTP_400_BAD_REQUEST
    return '', status.HTTP_201_CREATED

@app.route('/grade', methods = ['PUT'])
@auth.login_required
def update_grade():
    from grading.models import update_grade_model
    grade_data = request.get_json()
    grade = grade_data.get('grade')
    student = grade_data.get('student')
    course = grade_data.get('course')
    validate_message = validate_grade(grade, student, course)
    if validate_message:
        return validate_message, status.HTTP_400_BAD_REQUEST
    try:
        set_lock('grade'+str(student)+str(course))
        if not update_grade_model(student, course, {'grade': grade}):
            return 'grade not found', status.HTTP_404_NOT_FOUND
    finally:
        release_lock('grade'+str(student)+str(course))
    return '', status.HTTP_200_OK

@app.route('/grade/<int:student>/<int:course>', methods = ['DELETE'])
@auth.login_required
def delete_grade(student, course):
    from grading.models import delete_grade_model

    try:
        set_lock('grade'+str(student)+str(course))
        if not delete_grade_model(student, course):
            return 'grade not found', status.HTTP_404_NOT_FOUND
    finally:
        release_lock('grade'+str(student)+str(course))
    return '', status.HTTP_204_NO_CONTENT

@app.route('/grade/<int:student>/<int:course>', methods = ['GET'])
@auth.login_required
def get_grade(student, course):
    from grading.models import get_grade_model

    result = get_grade_model(student, course)
    if result:
        return json.dumps(result), status.HTTP_200_OK
    else:
        return 'grade not found', status.HTTP_404_NOT_FOUND

@app.route('/grade', methods = ['GET'])
@auth.login_required
def get_grades():
    from grading.models import get_grade_model
    result = get_grade_model()
    if result:
        return json.dumps(result), status.HTTP_200_OK
    else:
        return 'grade not found', status.HTTP_404_NOT_FOUND

@app.route('/best_student', methods = ['GET'])
@auth.login_required
def get_best_student():
    from grading.models import get_grade_model, get_student_model
    grades = get_grade_model()
    if grades:
        average_score = {}
        for student, grade_list in groupby(grades, key=lambda x: x['student']):
            grade_list = list(grade_list)
            average = float(sum(grade['grade'] for grade in grade_list)) / len(grade_list)
            average_score[student] = average
        best_student = max(average_score.items(), key=operator.itemgetter(1))[0]
        result = get_student_model(best_student)
        return result, status.HTTP_200_OK
    else:
        return 'grades not found', status.HTTP_404_NOT_FOUND

@app.route('/easy_course', methods = ['GET'])
@auth.login_required
def get_easy_course():
    from grading.models import get_grade_model, get_course_model
    grades = get_grade_model()
    if grades:
        average_score = {}
        for course, grade_list in groupby(grades, key=lambda x: x['course']):
            grade_list = list(grade_list)
            average = float(sum(grade['grade'] for grade in grade_list)) / len(grade_list)
            average_score[course] = average
        easy_course = min(average_score.items(), key=operator.itemgetter(1))[0]
        result = get_course_model(easy_course)
        return result, status.HTTP_200_OK
    else:
        return 'grades not found', status.HTTP_404_NOT_FOUND

if __name__ == "__main__":
    with app.app_context():
        from grading.models import create_tables

        create_tables()
    app.run(debug=True)


'''
JOB LOG:
采用和 handout 一样的层级架构但参数不同。
一开始参数少，准确率低。尝试多加一层 conv + relu，并没有显著的效果；
又修改为增加每层的参数，特别是增加通道数和增大 kernel size，效果显著。
'''
import torch.nn as nn

class ConvNet(nn.Module):
    def __init__(self, num_class=10):
        super(ConvNet, self).__init__()
        self.seq = nn.Sequential(
            nn.Conv2d(3, 32, 3, padding=1),
            nn.ReLU(),
            nn.Conv2d(32, 64, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2, stride=2),  # 16*16
            nn.Conv2d(64, 64, 5, padding=1, stride=1),  # 14*14
            nn.ReLU(),
            nn.Conv2d(64, 64, 5, padding=1, stride=1),  # 12*12
            nn.ReLU(),
            nn.MaxPool2d(3, stride=3),  # 4*4
            nn.Flatten(),  # 4*4*64
            nn.Linear(4 * 4 * 64, 512),  # 512
            nn.ReLU(),
            nn.Linear(512, 10)  # 10
        )

    def forward(self, x):
        # x: B*H*W*3
        logits = self.seq(x)  # B*N
        return logits

if __name__ == '__main__':
    import torch
    from torch.utils.tensorboard import SummaryWriter
    from dataset import CIFAR10

    writer = SummaryWriter(log_dir='../experiments/network_structure')
    net = ConvNet()
    train_dataset = CIFAR10()
    train_loader = torch.utils.data.DataLoader(
        train_dataset, batch_size=2, shuffle=False, num_workers=2)
    # Write a CNN graph.
    # Please save a figure/screenshot to '../results' for submission.
    for imgs, labels in train_loader:
        writer.add_graph(net, imgs)
        writer.close()
        break


'''
다중 perceptron -> mlp
'''
from keras.datasets import mnist
import tensorflow as tf
tf.set_random_seed(66)

# 1. data
x_data = [[0, 0], [0, 1], [1, 0], [1, 1]]
y_data = [[0], [1], [1], [0]]

# 2. modeling
x = tf.placeholder(tf.float32, shape=[None,2])
y = tf.placeholder(tf.float32, shape=[None,1])

# hidden layer 1
w1 = tf.Variable(tf.random_normal([2, 8]))
b1 = tf.Variable(tf.random_normal([8]))
# x, b를 0에서 1사이의 랜덤한 값으로 지정

layer1 = tf.nn.sigmoid(tf.matmul(x, w1) + b1)

# hidden layer 2
w2 = tf.Variable(tf.random_normal([8, 4]))
b2 = tf.Variable(tf.random_normal([4]))
# x, b를 0에서 1사이의 랜덤한 값으로 지정

layer2 = tf.nn.sigmoid(tf.matmul(layer1, w2) + b2)

# output layer
w = tf.Variable(tf.random_normal([4, 1]))
b = tf.Variable(tf.random_normal([1]))

hypothesis = tf.nn.sigmoid(tf.matmul(layer2, w) + b)

cost = -tf.reduce_mean(y*tf.log(hypothesis)+(1-y)*tf.log(1-hypothesis))

optimizer = tf.train.GradientDescentOptimizer(learning_rate=1)
train = optimizer.minimize(cost)

predict = tf.cast(hypothesis > 0.5, dtype=tf.float32)
# 0.5를 초과하면 1, 아니면 0
accuracy = tf.reduce_mean(tf.cast(tf.equal(predict, y), dtype=tf.float32))

sess = tf.compat.v1.Session()
sess.run(tf.global_variables_initializer())

for epochs in range(2001):
    cost_val, hy_val, _ = sess.run([cost, hypothesis, train],
                    feed_dict={x:x_data, y:y_data})
    if epochs % 10 == 0:
        print(epochs, 'cost: ', cost_val, "\n", hy_val)

c, a = sess.run([predict, accuracy], feed_dict={x:x_data, y:y_data})
print('predict:\n ', hy_val, "\n 예측결과 값\n : ", c, "\n Accuracy: ", a)

sess.close()


from SimEx.Parameters.AbstractCalculatorParameters import AbstractCalculatorParameters
from SimEx.Utilities.EntityChecks import checkAndSetInstance, checkAndSetPhysicalQuantity
from SimEx.Utilities.Units import meter, electronvolt, joule, radian

from scipy import constants
from wpg import Wavefront, wpg_uti_wf
from wpg.srwlib import srwl
import math
import numpy
import os
import sys

class PhotonBeamParameters(AbstractCalculatorParameters):
    def __init__(self,
            photon_energy,
            beam_diameter_fwhm,
            pulse_energy,
            photon_energy_relative_bandwidth=None,
            divergence=None,
            photon_energy_spectrum_type=None,
            **kwargs
            ):
        """
        :class PhotonBeamParameters: Encapsulates the parameters of a photon beam.

        :param photon_energy: The mean photon energy in units of electronvolts (eV).
        :type photon_energy: float

        :param photon_energy_relative_bandwidth: The relative energy bandwidth
        :type photon_energy_relative_bandwidth: float (>0.0).

        :param beam_diameter_fwhm: Beam diameter in units of metre (m).
        :type beam_diameter_fwhm: float

        :param pulse_energy: Total energy of the pulse in units of Joule (J).
        :type pulse_energy: float

        :param divergence: Beam divergence angle in units of radian (rad).
        :type divergence: float (0 < divergence < 2*pi)

        :param photon_energy_spectrum_type: Type of energy spectrum ("SASE" | "tophat" | "twocolour", default "SASE").
        :type photon_energy_spectrum_type: float

        :param kwargs: Key-value pairs to be passed to the parent class constructor.
        :type kwargs: dict

        """
        super(PhotonBeamParameters, self).__init__(**kwargs)

        self.photon_energy = photon_energy
        self.photon_energy_relative_bandwidth = photon_energy_relative_bandwidth
        self.beam_diameter_fwhm = beam_diameter_fwhm
        self.pulse_energy = pulse_energy
        self.divergence = divergence
        self.photon_energy_spectrum_type = photon_energy_spectrum_type

    def _setDefaults(self):
        """ Set default for required inherited parameters. """
        self._AbstractCalculatorParameters__cpus_per_task_default = 1

    @property
    def photon_energy(self):
        """ Query the 'photon_energy' parameter. """
        return self.__photon_energy
    @photon_energy.setter
    def photon_energy(self, val):
        """ Set the 'photon_energy' parameter to val."""
        self.__photon_energy = checkAndSetPhysicalQuantity( val, None,  electronvolt)

    @property
    def photon_energy_spectrum_type(self):
        """ Query the 'photon_energy_spectrum_type' parameter. """
        return self.__photon_energy_spectrum_type
    @photon_energy_spectrum_type.setter
    def photon_energy_spectrum_type(self, val):
        """ Set the 'photon_energy_spectrum_type' parameter to val."""
        self.__photon_energy_spectrum_type = checkAndSetInstance( str, val, "SASE")

    @property
    def photon_energy_relative_bandwidth(self):
        """ Query the 'photon_energy_relative_bandwidth' parameter. """
        return self.__photon_energy_relative_bandwidth
    @photon_energy_relative_bandwidth.setter
    def photon_energy_relative_bandwidth(self, val):
        """ Set the 'photon_energy_relative_bandwidth' parameter to val."""
        self.__photon_energy_relative_bandwidth = checkAndSetInstance( float, val, 0.01)

    @property
    def beam_diameter_fwhm(self):
        """ Query the 'beam_diameter_fwhm' parameter. """
        return self.__beam_diameter_fwhm
    @beam_diameter_fwhm.setter
    def beam_diameter_fwhm(self, val):
        """ Set the 'beam_diameter_fwhm' parameter to val."""
        self.__beam_diameter_fwhm = checkAndSetPhysicalQuantity( val , 1.0e-6, meter )

    @property
    def divergence(self):
        """ Query the 'divergence' parameter. """
        return self.__divergence
    @divergence.setter
    def divergence(self, val):
        """ Set the 'divergence' parameter to val."""
        self.__divergence = checkAndSetPhysicalQuantity( val, 0.0, radian)

    @property
    def pulse_energy(self):
        """ Query the 'pulse_energy' parameter. """
        return self.__pulse_energy
    @pulse_energy.setter
    def pulse_energy(self, val):
        """ Set the 'pulse_energy' parameter to val."""
        self.__pulse_energy = checkAndSetPhysicalQuantity( val, 1.0e-3, joule)

    def serialize(self, stream=sys.stdout):
        """ Serialize the object (write to a stream)

        :param stream: The stream to write to (default sys.stdout)
        :type stream:  str || file

        """

        if isinstance(stream, str):
            with open(stream, 'w') as ostream:
                self._serialize(ostream)
        elif hasattr(stream, 'write'):
                self._serialize(stream)

    def _serialize(self, stream=sys.stdout):
        """ """
        """ Workhorse serialization function """

        stream.write("; [Photon beam parameters]" )
        stream.write("\n")
        stream.write("\n")
        stream.write("; photon energy (eV)" )
        stream.write("\n")
        stream.write("beam/photon_energy = %8.7e" % (self.photon_energy.m_as(electronvolt)) )
        stream.write("\n")
        stream.write("\n")
        stream.write("; Number of photons per pulse" )
        stream.write("\n")
        stream.write("beam/fluence = %8.7e" % (self.pulse_energy.m_as(joule) / self.photon_energy.m_as(joule) ) )
        stream.write("\n")
        stream.write("\n")
        stream.write("; Radius of X-ray beam (m)" )
        stream.write("\n")
        stream.write("beam/radius = %8.7e" % (self.beam_diameter_fwhm.m_as(meter)/2. ) )
        stream.write("\n")

def propToBeamParameters( prop_output_path ):
    """ Utility to setup a PhotonBeamParameters instance from propagation output. """

    # Check prop out exists.
    if not os.path.isfile(prop_output_path):
        raise IOError("File not found: %s." % (prop_output_path) )

    # Construct the wavefront.
    wavefront = Wavefront()
    wavefront.load_hdf5( prop_output_path )

    pulse_energy = wpg_uti_wf.calc_pulse_energy( wavefront )

    mesh = wavefront.params.Mesh
    dx = (mesh.xMax - mesh.xMin)/(mesh.nx - 1)
    dy = (mesh.yMax - mesh.yMin)/(mesh.ny - 1)
    int0 = wavefront.get_intensity().sum(axis=0).sum(axis=0)  # I(slice_num)
    total_intensity = int0*dx*dy # [J]

    times = numpy.linspace(mesh.sliceMin, mesh.sliceMax, mesh.nSlices)

    t = times[:-1]
    dt = times[1:] - times[:-1]

    It = total_intensity[:-1]

    m0 = numpy.sum( It*dt)
    m1 = numpy.sum( It*t*dt )/m0
    m2 = numpy.sum( It*t**2*dt)/m0

    rms = math.sqrt(m2 - m1**2)

    spike_fwhm_J = constants.hbar/rms
    spike_fwhm_eV = spike_fwhm_J/constants.e

    # Switch to energy domain
    srwl.SetRepresElecField(wavefront._srwl_wf, 'f')

    mesh = wavefront.params.Mesh
    spectrum = wavefront.get_intensity().sum(axis=0).sum(axis=0)  # I(slice_num)
    energies = numpy.linspace(mesh.sliceMin, mesh.sliceMax, mesh.nSlices)

    w = energies[:-1]
    dw = energies[1:] - energies[:-1]

    Iw = spectrum[:-1]

    m0 = numpy.sum( Iw*dw)
    m1 = numpy.sum( Iw*w*dw )/m0
    m2 = numpy.sum( Iw*w**2*dw)/m0

    rms = math.sqrt(m2 - m1**2)

    photon_energy = m1
    #spec_fwhm_eV = rms

    # Extract beam diameter fwhm
    xy_fwhm = wpg_uti_wf.calculate_fwhm(wavefront)

    # Extract divergence
    # Switch to reciprocal space
    srwl.SetRepresElecField(wavefront._srwl_wf, 'a')
    qxqy_fwhm = wpg_uti_wf.calculate_fwhm(wavefront)

    del wavefront

    beam_parameters = PhotonBeamParameters(
            photon_energy=photon_energy*electronvolt,
            photon_energy_relative_bandwidth=spike_fwhm_eV/photon_energy,
            pulse_energy=pulse_energy*joule,
            divergence=max([qxqy_fwhm['fwhm_x'],qxqy_fwhm['fwhm_y']])/2.*radian,
            beam_diameter_fwhm=max([xy_fwhm['fwhm_x'],xy_fwhm['fwhm_y']])*meter,
            photon_energy_spectrum_type="SASE",
            )

    return beam_parameters


import io
import time
import typing
import base64
import binascii
import re
import datetime
from datetime import datetime
from urllib.parse import quote as urlquote
import psutil
import os

import sys
sys.dont_write_bytecode = True

from utils import *

import discord
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType

class Manager(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        guilds = len(list(bot.guilds))

    @commands.Cog.listener()
    async def on_guild_join(self, guild):

        guilds = len(list(self.bot.guilds))
        members = len(set(self.bot.get_all_members()))
        channel = self.bot.get_channel(692753703488192514)

        embed = discord.Embed(colour=discord.Colour.from_rgb(59, 185, 255), title="New Guild")
        embed.add_field(name="Owner", value=f"{guild.owner}", inline=True)
        embed.add_field(name="Owner ID", value=f"{guild.owner.id}", inline=False)
        embed.add_field(name="Guild Name", value=f"{guild}", inline=False)
        embed.add_field(name="Guild ID", value=f"{guild.id}", inline=True)
        embed.add_field(name="Member count", value=f"{guild.member_count}", inline=False)
        await channel.send(embed=embed)

        embedmessage = discord.Embed(colour=discord.Colour.from_rgb(124, 252, 0), title="Welcome - tb!")
        embedmessage.add_field(name="Station Bot Auto Message", value="pls don't hurt me this is an auto message ahh", inline=False)
        embedmessage.add_field(name=f"Hi, {guild.owner}", value=f"hi there, i'm a bot, beep boop. \n\nThis is a message sent regarding the basics of the bot. Thank you for adding me!\n\nWe currently only support the UK, country-wise however we plan on expanding that!", inline=False)
        embedmessage.add_field(name="Getting Started", value="Type **tb!help** for a list of commands. Also, **tb!station** to get information about a station. Pretty cool, ey?")
        embedmessage.add_field(name="Developer", value="beepy boopy. the developer is Emil#0581 - and i hope this message didn't bother you too much! C:")
        await guild.owner.send(embed=embedmessage)

        await self.bot.get_channel(693863811978887180).edit(name=f"Member Count: {members}")
        await self.bot.get_channel(693863787748655104).edit(name=f"Guild Count: {guilds}")

    @commands.Cog.listener()
    async def on_guild_remove(self, guild):

        guilds = len(list(self.bot.guilds))
        members = len(set(self.bot.get_all_members()))
        channel = self.bot.get_channel(692753703488192514)

        embed = discord.Embed(colour=discord.Colour.from_rgb(59, 185, 255), title="Left Guild")
        embed.add_field(name="Owner", value=f"{guild.owner}", inline=True)
        embed.add_field(name="Owner ID", value=f"{guild.owner.id}", inline=False)
        embed.add_field(name="Guild Name", value=f"{guild}", inline=False)
        embed.add_field(name="Guild ID", value=f"{guild.id}", inline=True)
        embed.add_field(name="Member count", value=f"{guild.member_count}", inline=False)
        await channel.send(embed=embed)

        await self.bot.get_channel(693863811978887180).edit(name=f"Member Count: {members}")
        await self.bot.get_channel(693863787748655104).edit(name=f"Guild Count: {guilds}")

def setup(bot):
    bot.add_cog(Manager(bot))


import ctypes
import time
import numpy as np
import cv2
import pyautogui

LEFT = 0x25
UP = 0x26
RIGHT = 0x27
DOWN = 0x28
Z=0x5a
X=0x58
SHIFT=0x10

def getkey(key):
    return(bool(ctypes.windll.user32.GetAsyncKeyState(key)&0x8000))

def getKeys():
    str=''
    if getkey(LEFT):
        str+="left,"
    if getkey(RIGHT):
        str+="right,"
    if getkey(UP):
        str+="up,"
    if getkey(DOWN):
        str+="down,"
    if getkey(Z):
        str+="Z,"
    if getkey(X):
        str+="X,"
    if getkey(SHIFT):
        str+="SHIFT,"
    return str

stamp=str(time.time())

fourcc = cv2.VideoWriter_fourcc('D','I','V','X')
writer = cv2.VideoWriter('data/output'+stamp+'.avi',fourcc,30,(384,448))
f=open('data/keys'+stamp+'.txt',mode='w')

def save_data(frame):
    writer.write(frame)
    f.write(getKeys()+'\n')

def main():
    libc = ctypes.WinDLL("Project5.dll")
    x=384*448*3
    life_board_size=144*48*3

    UBYTE_Array = ctypes.c_ubyte * x
    Life_Board=ctypes.c_ubyte*life_board_size

    i_arr=[0*x]
    i_arr_c=UBYTE_Array(*i_arr)

    life_board_arr=[0*life_board_size]
    life_board_arr_c=Life_Board(*life_board_arr)

    t1=time.time()
    count=0
    sum=0
    before_img=0
    start=False

    while True:
        libc.capture_foreground(i_arr_c)
        image=np.ctypeslib.as_array(i_arr_c).reshape(448,384,3)
        image=cv2.flip(image,0)

        cv2.imshow("aa",image)
        cv2.waitKey(1)
        before_img=image
        if 'SHIFT' in getKeys():
            start=True
        if start:
            save_data(image)
        print(getKeys())

if __name__ == '__main__':
    main()


"""
Display the product information by its index on the page
"""

from pprint import pprint

if __name__ == "__main__":
    from shop import Shop

    shop = Shop("http://some-website")

    product_number = 21
    product_url = shop.get_all_product_urls(catalog_url="/shop/all/tops_sweaters")[
        product_number - 1
    ]

    pprint(shop.get_product_info(product_url=product_url))


'''
prime number always gretaer than 1

'''

def isprime(nums):
    flag = False
    # prime number is always greater then 1
    if nums > 1:
        for i in range(2, nums):
            # check for factors
            if nums % i == 0:
                flag = True
                break
    if flag:
        print("num is not prime")
    else:
        print("nums is prime")
nums = 8
isprime(nums)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul  9 16:32:55 2017
   Mesh Point Cloud
@author: amit
"""
import numpy as np
import vtk as v

"""
Read a polydata vtk file and insert triangles in it
"""
def meshPointCloud( inputVTKfile, searchRad ):
    reader = v.vtkPolyDataReader()
    reader.SetFileName( inputVTKfile )
    reader.Update()
    pd = reader.GetOutput()
    N = pd.GetNumberOfPoints()
    kdt = v.vtkKdTree()
    kdt.BuildLocatorFromPoints( pd.GetPoints() )

    polys = v.vtkCellArray()
    for i in range( N ):
        currPoint = pd.GetPoint(i)
        idList = v.vtkIdList()
        kdt.FindPointsWithinRadius( searchRad, currPoint, idList )

        neighbors = []
        for j in range( idList.GetNumberOfIds() ):
            currId = idList.GetId(j)
            if j != i:
                neighbors.append(currId)


from jdet.models.boxes.box_ops import rotated_box_to_poly_single
from jdet.utils.registry import DATASETS
from jdet.config.constant import FAIR_CLASSES_, FAIR1M_1_5_CLASSES
from jdet.models.boxes.box_ops import rotated_box_to_poly_single
from jdet.data.dota import DOTADataset
import os
import numpy as np

@DATASETS.register_module()
class FAIRDataset(DOTADataset):
    CLASSES = FAIR_CLASSES_
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.CLASSES = FAIR_CLASSES_

        img_infos = []
        for img_info in self.img_infos:
            boxes = img_info["ann"]["bboxes"]
            w,h = boxes[:,2],boxes[:,3]
            area = w*h
            index = area>1.
            img_info["ann"]["bboxes"] = img_info["ann"]["bboxes"][index]
            img_info["ann"]["labels"] = img_info["ann"]["labels"][index]

    def _balance_categories(self):
        img_infos = self.img_infos
        cate_dict = {}
        for idx,img_info in enumerate(img_infos):
            unique_labels = np.unique(img_info["ann"]["labels"])
            for label in unique_labels:
                if label not in cate_dict:
                    cate_dict[label]=[]
                cate_dict[label].append(idx)

        # fair
        # labels: [ 5, 10, 27, 36, 26, 12, 19, 33, 29, 28, 22, 37, 34,  9, 31, 16,  3, 15,  8,  4,  2, 20,  7, 32, 17, 30,  1, 14,  6, 35, 13, 23, 18, 11, 24, 25, 21]
        # counts: [ 644, 733,   1051,   2173,   2199,   2413,   2511,   2984, 3178,   3398,   3890,   3980,   3997,   4274,   4838,   5940,  6064,   6364,   6371,   6403,   6498,   9033,  10413,  11187, 11515,  11554,  16014,  23120,  24386,  24875,  30084,  35516, 37878,  40175,  97638, 503094, 544446]
        # category: []
        # ['C919',
        # 'ARJ21',
        # 'Tractor',
        # 'Roundabout',
        # 'Trailer',
        # 'Passenger Ship',
        # 'Warship',
        # 'Football Field',
        # 'Truck Tractor',
        # 'Excavator',
        # 'Bus',
        # 'Bridge',
        # 'Baseball Field',
        # 'A350',
        # 'Basketball Court',
        # 'Engineering Ship',
        # 'Boeing777',
        # 'Tugboat',
        # 'A330',
        # 'Boeing787',
        # 'Boeing747',
        # 'other-ship',
        # 'A321',
        # 'Tennis Court',
        # 'Liquid Cargo Ship',
        # 'other-vehicle',
        # 'Boeing737',
        # 'Fishing Boat',
        # 'A220',
        # 'Intersection',
        # 'Motorboat',
        # 'Cargo Truck',
        # 'Dry Cargo Ship',
        # 'other-airplane',
        # 'Dump Truck',
        # 'Van',
        # 'Small Car']
        new_idx = []
        balance_dict={
            "C919":(8,0),
            "ARJ21":(7,0),
            "Tractor":(5,0)
        }

        for k,d in cate_dict.items():
            classname = FAIR_CLASSES_[k-1]
            l1,l2 = balance_dict.get(classname,(1,0))
            new_d = d*l1+d[:l2]
            new_idx.extend(new_d)
        img_infos = [self.img_infos[idx] for idx in new_idx]
        return img_infos

@DATASETS.register_module()
class FAIR1M_1_5_Dataset(DOTADataset):
    CLASSES = FAIR1M_1_5_CLASSES
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.CLASSES = FAIR1M_1_5_CLASSES

        for img_info in self.img_infos:
            boxes = img_info["ann"]["bboxes"]
            if boxes.shape[0] == 0:
                continue
            w,h = boxes[:,2],boxes[:,3]
            area = w*h
            index = area>1.
            img_info["ann"]["bboxes"] = img_info["ann"]["bboxes"][index]
            img_info["ann"]["labels"] = img_info["ann"]["labels"][index]
        pass

@DATASETS.register_module()
class FAIR1M_1_5_Dataset_fold(DOTADataset):
    CLASSES = FAIR1M_1_5_CLASSES
    def __init__(self,*arg, folds=[0,1,2,3],**kwargs):

        super().__init__(*arg, **kwargs)
        self.CLASSES = FAIR1M_1_5_CLASSES
        assert folds is not None
        self.img_infos = self._filter_folds(folds)
        self.csv = os.path.join(self.dataset_dir, 'trainval_folds.csv')
        self.total_len = len(self.img_infos)

    def _filter_folds(self, folds):
        import pandas as pd
        folds = set(folds)
        csv = os.path.join(self.dataset_dir, 'trainval_folds.csv')
        csv = pd.read_csv(csv, names = ['filename', 'folds'])
        new = []
        for img_info in self.img_infos:
            if csv[csv['filename']==img_info["filename"].replace('.png', '.txt')].iloc[0,1] in folds:
                new.append(img_info)
        return new


import re
from nltk.corpus import stopwords
from textblob import TextBlob
import cv2
import numpy as np

REPLACE_NO_SPACE = re.compile("[.;:!\'?,\"()\[\]]")
REPLACE_WITH_SPACE = re.compile("(<br\s*/><br\s*/>)|(\-)|(\/)")

bio = """here to make new friends, just seeing da vibes and going with the flow"""

def breakSentenceToWords(input):
    input = [REPLACE_NO_SPACE.sub("", line.lower()) for line in input.split()]
    input = [REPLACE_WITH_SPACE.sub(" ", line) for line in input]
    return input

#Replace this with textblob
def validMatch(sentence, preference="pos"):

    dic = {"pos":0.1 , "neg":-0.1}
    threshold = dic[preference]
    blob1 = TextBlob(sentence)
    return blob1.sentiment.polarity*threshold >=0

#Replace this with tokenise
def splitSentence(input):
    input = input.split(".")
    return input

def keywordPresent(sentences, keyword, preference="pos"):
    for line in sentences:
        if keyword in line and validMatch(line, preference):
            return True
    return False

def calculatePercentage(total, keywords):
    percentage = total/len(keywords)
    return percentage * 100

def checkKeyword(bio, keywords, percentage, sentiments):

    parsedBio = splitSentence(bio)
    total = 0
    for idx, keys in enumerate( keywords):
        if (keywordPresent(parsedBio, keys , sentiments[idx])):
            total = total + 1
    #print(total)
    matchPercentage = calculatePercentage(total, keywords)
    #print(matchPercentage)
    if matchPercentage >= percentage:
        return True
    else:
        return False

print(checkKeyword(bio, "new friend", 60, ["pos"]))


import json
import tensorflow as tf
import numpy as np
from collections import OrderedDict
from collections import Counter

# 3-class classification demo
class Classifier(object):
    def __init__(self, corpus_path, min_freq=1, special=['<PAD>', '<UNKNOWN>']):
        assert corpus_path, "corpus_path must be given."
        self.max_seq_len = 6
        self.batch_size = 4
        self.iter_num = 50
        self.min_freq = min_freq
        self.special = special
        self.counter = Counter()
        self.vocab = OrderedDict()
        self.corpus = self.load_corpus(corpus_path)
        self.feed_dict = {}

    def load_corpus(self, corpus_path):
        ret_corpus = OrderedDict()
        with open(corpus_path, 'r', encoding='utf-8') as f:
            for line in f:
                data = json.loads(line)
                text, label = data["text"], data['items'][0]['sentiment']
                self.counter.update(list(text))
                ret_corpus[text] = int(label)
        return ret_corpus

    def build_vocab(self):
        if self.special:
            for token in self.special:
                self.vocab[token] = len(self.vocab)
        # select 20 words in corpus
        for token, cnt in self.counter.most_common(20):
            if cnt < self.min_freq:
                break
            self.vocab[token] = len(self.vocab)

    def build_embedding(self, word_ids):
        # first token is padding, set it untrainable
        embed_t = tf.get_variable(shape=[1, 8], trainable=False, name="embed_t",
                                  initializer=tf.zeros_initializer())
        embed_ut = tf.get_variable(shape=[len(self.vocab) - 1, 8], trainable=True, name="embed_ut",
                                   initializer=tf.truncated_normal_initializer())
        embedding = tf.concat([embed_t, embed_ut], axis=0, name="embedd_w")
        return tf.nn.embedding_lookup(embedding, word_ids)

    def models(self, word_ids):
        embeded_sent = self.build_embedding(word_ids)
        lstm_cell = tf.nn.rnn_cell.LSTMCell(num_units=8)
        initial_state = lstm_cell.zero_state(self.batch_size, dtype=tf.float32)
        outputs, state = tf.nn.dynamic_rnn(lstm_cell, embeded_sent, initial_state=
                                           initial_state)
        # full connected layer
        logits = tf.layers.dense(state[1], units=3)
        return logits

    def train(self):
        global_steps = tf.Variable(0, trainable=False, name="global_steps")
        word_ids = tf.placeholder(tf.int32, [None, self.max_seq_len], name="input_text")
        label = tf.placeholder(tf.int32, [None], name="label")
        logits = self.models(word_ids)
        loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label)
        optimizer = tf.train.AdamOptimizer(2.5e-4)
        grad_and_var = optimizer.compute_gradients(loss)
        train_op = optimizer.apply_gradients(grad_and_var, global_step=global_steps)
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            # generator for training process
            train_gens = self.get_batch(self.batch_size)
            for iter in range(self.iter_num):
                texts, labels = next(train_gens)
                _, iter_num, loss_eval, embed_w = sess.run([train_op, global_steps, loss, "embedd_w:0"],
                                                           feed_dict={word_ids: texts, label: labels})
                print("-" * 30 + "iteration {}".format(iter_num) + "-" * 30)
                print(embed_w[0:2, :])

    def get_batch(self, batch_size=4):
        train_data = list(self.corpus.items())

        def text2id(query):
            ret = []
            for i in range(self.max_seq_len):
                if i < len(query):
                    ret.append(self.vocab[query[i]] if query[i] in self.vocab
                               else self.vocab["<UNKNOWN>"])
                else:
                    ret.append(self.vocab["<PAD>"])
            return ret
        # get a batch data
        while True:
            batch = np.random.choice(len(train_data), batch_size, replace=False)
            batch = [train_data[idx] for idx in batch]
            texts, labels = [], []
            for text, lbl in batch:
                # transform word to id
                texts.append(text2id(text))
                labels.append(lbl)
            yield texts, labels

if __name__ == "__main__":
    classifier = Classifier("./result.txt")
    classifier.build_vocab()
    classifier.train()


# Problem 994
# Date completed: 2019/09/18

# 68 ms
class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        if not grid: return

        self.fresh = sum([row.count(1) for row in grid])
        if self.fresh == 0: return 0

        w = len(grid[0])
        h = len(grid)

        rotten = [[i,j] for i in range(h) for j in range(w) if grid[i][j] == 2]
        new_rotten = []

        def helper(i,j):
            if grid[i][j] == 1:
                grid[i][j] = 2
                new_rotten.append([i,j])
                self.fresh -= 1

        time = 0
        while rotten:
            i,j = rotten.pop(0)
            if i>0: helper(i-1,j)
            if j>0: helper(i,j-1)
            if i<h-1: helper(i+1,j)
            if j<w-1: helper(i,j+1)

            # print(grid)
            # print(new_rotten,rotten,self.fresh)

            if not rotten:
                rotten = list(new_rotten)
                new_rotten = []
                time += 1
                if self.fresh<=0: return time

        return -1


import re

# parse the text and check for regex pattern of ip address.
def parse ( ip_text ):
    '''
    Summary line.
    Searches for a regular expression pattern that matches an ip address.

    Parameters
    ----------
    ip_text : str
    This is the strings read in from the input file.

    Returns
    -------
    list_of_ips : list
    Description of return value
    Returns a list of all ip addresses that matches with the regex pattern.
    '''
    # creates an arg variable, makes args attributes available within function.
    list_of_ips = re.findall ( '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', ip_text )
    return (list_of_ips)

# convert input file into data
def file_to_text ( file_name ):
    '''
    Summary line.
    Opens the input file passed by flag -f.

    Parameters
    ----------
    file_name : str
    name of input file

    Returns
    -------
    ip_text : file type
    string : str
    Description of return value
    Returns the opened file, if not able to open file.
    Tells user it's unable to open the file.
    '''
    # try to open file
    try:
        ip_file = open ( file_name, 'r' )
        ip_text = ip_file.read ( )
        return (ip_text)
    # if not able, then return output to user.
    except:
        print ( "Unable to open the file", file_name )

# display results of sql query
def display_dict ( dictionary ):
    '''
    Summary line.
    Takes a dictionary as input and makes the sql query readable
    by the user.

    Parameters
    ----------
    dictionary : dict
    Dictionary of column names and values.

    Returns
    -------
    string : str
    Description of return value
    Returns the sql query in a readable format and outputs
    to the console.
    '''
    # iterate through each line in dictionary
    for line in dictionary:
        # get keys dictionary
        keys = list ( line.keys ( ) )
        # iterate through grabbing keys and values.
        for i in range ( len ( keys ) ):
            # output to console.
            print ( keys [ i ], " = ", line [ keys [ i ] ], end = " | " )
        print ( "\n" )

# grab the file and convert to format to be parsed through.
def main ( file_name ):
    ip_text = file_to_text ( file_name )
    print ( ip_text )
    list_of_ips = parse ( ip_text )
    print ( list_of_ips )
    print ( len ( list_of_ips ) )

if __name__ == "__main__":
    file_name = "list_of_ips.txt"
    main ( file_name )


from PIL import Image
import os
import glob
import msvcrt

#classes
class image:
    filename = ""
    image = ""
    def __init__(self,filename):
        self.filename = filename
        self.image = Image.open(filename)

#vari
mode = 1
imagelist = []

#functions

#main while
while True:
    if mode == 1:
        print("Please wait...")
        for filename in glob.glob(os.path.abspath('.')+r"\*.*"):
            if filename.endswith("jpg" or "png" or "jpeg"):
                imagelist.append(image(filename))
        print(str(len(imagelist))+" files founded")
        os.system("cls")
        mode = 2

    if mode == 2:
        show = 0
        select = 0
        while True:
            print("Please select image you want to process:")
            i = show
            if len(imagelist) < 5:
                max = len(imagelist)
            else:
                if show + 5 <= len(imagelist):
                    max = show + 5
                else:
                    max = len(imagelist)
                    i = max - 5
            while i < max:
                print(imagelist[i].filename,end="")
                if select == i:
                    print(" <--Selected")
                else:
                    print("\n",end="")
                i += 1
            tinput = msvcrt.getch()
            if tinput == b'H':
                show -= 1
                select -= 1
            if tinput == b'P':
                show += 1
                select += 1
            if tinput == b'\r':
                mode = 3
                break
            if show + 4 > len(imagelist):
                show = len(imagelist) - 4
            if show < 0:
                show = 0
            if select < 0:
                select = 0
            if select >= len(imagelist):
                select = len(imagelist) - 1
            os.system("cls")

    if mode == 3:
        selectmode = 0
        while True:
            os.system("cls")
            print("Please choose the devide mode:")

            print("left to right",end='')

            if selectmode == 0:
                print(" <--Selected")
            else:
                print("\n",end='')

            print("up to down",end='')

            if selectmode == 1:
                print(" <--Selected")
            else:
                print("\n",end='')

            tinput = msvcrt.getch()
            if tinput == b'H':
                selectmode = 0
            if tinput == b'P':
                selectmode = 1
            if tinput == b'\r':
                mode = 4
                break

    if mode == 4:
        print("Please enter the number you want to divide the picture into")
        a = input()
        try:
            a = int(a)
        except ValueError:
            print("NaN,Please retry!")
            continue
        mode = 5

    if mode == 5:
        print("Please enter the beginning number")
        name = input()
        try:
            name = int(name)
        except ValueError:
            print("NaN,Please retry!")
            continue
        mode = 6

    if mode == 6:
        print("Please wait...")
        i = 1
        process = 0
        if selectmode == 0: #left to right
            canvassize = [imagelist[select].image.size[0]/a,imagelist[select].image.size[1]]
        else:
            canvassize = [imagelist[select].image.size[0],imagelist[select].image.size[1]/a]
        if selectmode == 0:
            while i <= a:
                print("width:"+str(process)+","+str(process+canvassize[0]))
                canvas = imagelist[select].image.crop((process,0,process+canvassize[0],canvassize[1]))
                process += canvassize[0]
                canvas.save(str(i+name-1)+".jpg",quality = 100)
                i += 1
        else:
            while i <= a:
                print("height:"+str(process)+","+str(process+canvassize[1]))
                canvas = imagelist[select].image.crop((0,process,canvassize[0],process+canvassize[1]))
                process += canvassize[1]
                canvas.save(str(i+name-1)+".jpg",quality = 100)
                i += 1
        imagelist = []
        mode = 1


#!/usr/bin/env python

from os import path

dir_setup = path.dirname(path.realpath(__file__))
requires = [];

from setuptools import setup, Command

modules = [
    ]

tests = [
    ]

long_description = '''QuantPyCython is the QuantPy library Plugin using Cython for quantum computing.
It aims to become extension library set of quantpy.'''

with open(path.join(dir_setup, 'quantpycython', 'release.py')) as f:
    # Defines __version__
    exec(f.read())

if __name__ == '__main__':
    setup(name='quantpycython',
        version=__version__,
        description='QuantPy Plugin using Cython, that extends quantum Executor/Simulator.',
        long_description=long_description,
        author='QuantPy development team',
        author_email='quantpy@openql.org',
        license='Apache 2.0',
        keywords="Math Physics quantum quantpy",
        url='http://quantpy.org',
        packages=['quantpycython'] + modules + tests,
        ext_modules=[],
        classifiers=[
            'License :: OSI Approved :: Apache Software License',
            'Operating System :: OS Independent',
            'Programming Language :: Python',
            'Topic :: Scientific/Engineering',
            'Topic :: Scientific/Engineering :: Mathematics',
            'Topic :: Scientific/Engineering :: Physics',
            'Programming Language :: Python :: 3.5',
            'Programming Language :: Python :: 3.6',
            ],
        install_requires=requires,
        )


from torch import nn
from torch import distributions as pyd
import torch
from torch.distributions.utils import _standard_normal

class TruncatedNormal(pyd.Normal):
    def __init__(self, loc, scale, low=-1.0, high=1.0, eps=1e-6):
        super().__init__(loc, scale, validate_args=False)
        self.low = low
        self.high = high
        self.eps = eps

    def _clip(self, x):
        clipped_x = torch.clip(x, self.low + self.eps, self.high - self.eps)
        x = x - x.detach() + clipped_x.detach()
        return x

    def sample(self, clip=None, sample_shape=torch.Size()):
        shape = self._extended_shape(sample_shape)
        eps = _standard_normal(shape,
                               dtype=self.loc.dtype,
                               device=self.loc.device)
        eps *= self.scale
        if clip is not None:
            eps = torch.clip(eps, -clip, clip)
        x = self.loc + eps
        return self._clip(x)

class BasicActor(nn.Module):
    def __init__(self, state_dim, action_dim):
        super().__init__()

        self.policy_net = nn.Sequential(
            nn.Linear(state_dim, 128),
            nn.LeakyReLU(),
            nn.Linear(128, 128),
            nn.LeakyReLU(),
            nn.Linear(128, action_dim),
            nn.Tanh()
        )

    def forward(self, obs, std=None):
        if std is None:
            std = 0.001
        action_mean = self.policy_net(obs)
        std = torch.ones_like(action_mean) * std
        dist = TruncatedNormal(action_mean, std)
        return dist

class BasicQCritic(nn.Module):
    def __init__(self, state_dim, actor_dim):
        super().__init__()

        self.q_value_net = nn.Sequential(
            nn.Linear(state_dim + actor_dim, 128),
            nn.LeakyReLU(),
            nn.Linear(128, 128),
            nn.LeakyReLU(),
            nn.Linear(128, 1)
        )

    def forward(self, obs, action):
        return self.q_value_net(torch.concatenate([obs, action], dim=1))


"""
Failure Module.

This module contains the failure handler class.
"""

class FailureHandler:
    """
    FailureHandlerClass.

    This module is used to fail tor - aggr links.
    One can specific the link degradation from
    0 [No Failure] to 1 [Complete Failure] for
    any tor - aggr link.
    """

    def __init__(self, simulator):
        self.simulator = simulator

    def run(self, failedLinks, recoveredLinks):
        self.setLinkFailures(failedLinks)
        self.setLinkRecoveries(recoveredLinks)

    def setLinkFailures(self, links):
        for src, dst, degradation in links:

            if src[0:3] != 'tor' or dst[0:4] != 'aggr':
                self.simulator.logger.error('Incorrect Link Failure')

            if (src, dst) not in self.simulator.topo.edges:
                self.simulator.logger.error('Link not in Topology.')

            self.simulator.failed_links[(src, dst)] = float(degradation)

    def setLinkRecoveries(self, links):
        for src, dst in links:
            if src[0:3] != 'tor' or dst[0:4] != 'aggr':
                self.simulator.logger.error('Incorrect Link Recovery')

            if (src, dst) not in self.simulator.topo.edges:
                self.simulator.logger.error('Link not in Topology.')

            self.simulator.failed_links[(src, dst)] = 1.0


import random

numList = []
resList = []

while len(numList) < 100:
    numList.append(random.randint(-20, 20))

for x in range(len(numList)-1):
    if numList[x] not in resList:
        resList.append(numList[x])

print(resList)