from django.db import models
from django.contrib.auth import get_user_model
from website.models import Match

class RecommendedMatch(models.Model):
    CONTENTBASED = 'CONTENTBASED'
    COLLABORATIVE = 'COLLABORATIVE'
    HYBRID = 'HYBRID'
    RULEBASED = 'RULEBASED'
    RECOMMENDATION_TYPE = (
        (CONTENTBASED, 'Content-based'),
        (COLLABORATIVE, 'Collaborative'),
        (RULEBASED, 'Rule-based'),
        (HYBRID, 'Hybrid')
    )

    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='recommended_matches', null=True, blank=True)
    match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='+')
    recommendatoin_type = models.CharField(max_length=13, choices=RECOMMENDATION_TYPE, default=CONTENTBASED)
    value = models.FloatField()
    created = models.DateTimeField(auto_now_add=True)

class ScoreTable(models.Model):
    competition = models.ForeignKey('website.Competition', on_delete=models.CASCADE)
    season = models.ForeignKey('website.Season', on_delete=models.CASCADE)

    team = models.ForeignKey('website.Team', on_delete=models.CASCADE)
    played = models.IntegerField(default=0)

    rank = models.IntegerField(default=0)
    won = models.IntegerField(default=0)
    draw = models.IntegerField(default=0)
    lost = models.IntegerField(default=0)
    point = models.IntegerField(default=0)


from setuptools import setup

SHORT_DESCRIPTION = """
A tool to get your member's overtime from King of Time for every N weeks.""".strip()

DEPENDENCIES = [
    'fire==0.1.2',
    'beautifultable==0.4.0',
    'requests==2.18.4',
]

TEST_DEPENDENCIES = [
]

VERSION = '0.1.4'
URL = 'https://github.com/showwin/scrum-overtime-kot'

setup(
    name='sokot',
    version=VERSION,
    description=SHORT_DESCRIPTION,
    url=URL,

    author='showwin',
    author_email='showwin_kmc@yahoo.co.jp',
    license='Apache Software License',

    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],

    entry_points={
        'console_scripts': 'sokot = sokot.main:main'
    },

    keywords='overtime king-of-time scrum python tool cli',

    packages=['sokot'],

    install_requires=DEPENDENCIES,
    tests_require=TEST_DEPENDENCIES,
)


from typing import Optional, TypeVar, Generic, Any
import logging
import io
import time
import msgpack
import numpy as np

from PIL import Image

logger = logging.getLogger(__name__)
T = TypeVar('T')

class Topic:

    def __init__(self, dtype: type = Any, name: Optional[str] = None,):
        """
        :param name:
        :param dtype:
        """
        self._name = name
        self._dtype = dtype
        if self.name is not None and dtype == Any:
            logger.warning("If dtype is Any, topic.name has no effect.")

    @property
    def name(self) -> str:
        return self._name

    @property
    def dtype(self) -> type:
        return self._dtype

    @property
    def uuid(self):
        return f"{self.name}:{self.dtype if self.dtype is not None else None}"

    @property
    def is_control_topic(self):
        return self.dtype == MSPControlMessage.ControlTopic.ControlType

    def __hash__(self):
        return hash(self.uuid)

    def __eq__(self, sink_topic):
        """
        Args:
            sink_topic: Sink
            TODO:
        Returns:
        """
        if not isinstance(sink_topic, Topic):
            return False    #TODO: can we replace isinstance?

        if self.dtype is Any or sink_topic.dtype is Any:
            return True

        dtype_matches = sink_topic.dtype == self.dtype

        if sink_topic.name is not None:
            name_matches = sink_topic.name == self.name
        else:
            name_matches = True

        return dtype_matches and name_matches

    def __str__(self):
        return f"{self.dtype if self.dtype is not None else None}:{self.name}"

    def __repr__(self):
        return f"Topic(dtype={self.dtype if self.dtype is not None else None}, name={self.name})"

class MSPDataFrame(Generic[T]):

    def __init__(self, topic: Topic, timestamp: float = None, duration: float = 0, data: Optional[T] = None):
        super(MSPDataFrame, self).__init__()
        self._timestamp = time.perf_counter() if timestamp is None else timestamp
        self._duration = duration
        self._topic = topic
        self._data = data
        self._source_uuid = None

    @property
    def timestamp(self) -> float:
        return self._timestamp

    @timestamp.setter
    def timestamp(self, timestamp: float):
        self._timestamp = timestamp

    @property
    def topic(self) -> Topic:
        return self._topic

    @topic.setter
    def topic(self, topic: Topic):
        self._topic = topic

    @property
    def source_uuid(self) -> str:
        return self._source_uuid

    @source_uuid.setter
    def source_uuid(self, source_uuid: str):
        self._source_uuid = source_uuid

    @property
    def data(self) -> T:
        return self._data

    @data.setter
    def data(self, data: T):
        self._data = data

    @property
    def duration(self) -> float:
        return self._duration

    @duration.setter
    def duration(self, duration: float):
        self._duration = duration

    @staticmethod
    def msgpack_encode(obj):
        if isinstance(obj, MSPDataFrame):
            return {
                "__dataframe__": True,
                "topic": obj.topic,
                "timestamp": obj.timestamp,
                "duration": obj.duration,
                "data": obj.data
            }
        if isinstance(obj, Topic):
            return {
                "__topic__": True,
                "name": obj.name,
                "dtype": str(obj.dtype) if obj.dtype is not None else None  # TODO: how to encode a type?
            }
        if isinstance(obj, np.integer):
            return int(obj)
        if isinstance(obj, np.float):
            return float(obj)
        if isinstance(obj, np.ndarray):
            return {
                "__ndarray__": True,
                "data": obj.tolist(),
                "shape": obj.shape,
                "dtype": obj.dtype.name
            }
        if isinstance(obj, Image.Image):
            buffer = io.BytesIO()
            obj.save(buffer, format="jpeg", quality=90)
            return {
                "__jpeg__": True,
                "bytes": buffer.getvalue()
            }
        return obj

    def serialize(self) -> bytes:
        return msgpack.packb(self, default=MSPDataFrame.msgpack_encode)

    @staticmethod
    def deserialize(frame: bytes):
        return msgpack.unpackb(frame, object_hook=MSPDataFrame.msgpack_decode, raw=False)

    @staticmethod
    def msgpack_decode(obj):
        if '__dataframe__' in obj:
            obj = MSPDataFrame(
                topic=obj["topic"],
                timestamp=obj["timestamp"],
                duration=obj["duration"],
                data=obj["data"]
            )
        elif '__topic__' in obj:
            obj = Topic(name=obj["name"], dtype=obj["dtype"])
        elif '__ndarray__' in obj:
            obj = np.array(
                object=obj["data"],
                # shape=obj["shape"],
                dtype=obj["dtype"]
            )
        elif '__jpeg__' in obj:
            obj = Image.open(io.BytesIO(obj["bytes"]))
        return obj

    @staticmethod
    def get_msgpack_unpacker(filehandle) -> msgpack.Unpacker:
        return msgpack.Unpacker(file_like=filehandle, object_hook=MSPDataFrame.msgpack_decode, raw=False)

class MSPControlMessage(MSPDataFrame):

    class ControlTopic(Topic):
        class ControlType:
            pass
        name = None
        dtype = ControlType

    END_OF_STREAM = "EOS"
    PASS = "PASS"

    def __init__(self, message):
        topic = self.ControlTopic()
        super(MSPControlMessage, self).__init__(topic=topic)
        self._data = message


import discord
from discord.ext import commands
from discord.ext.commands import cooldown, BucketType
import json

import html
import random
import requests

from libraries.economyLib import *
from libraries.miscLib import get_input
from libraries.settings import *

class ecotrivia(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(
        name="trivia",
        aliases=["quiz", "triv"],
        brief=f"""
        play trivia with your friends!
        valid difficulty levels are: easy, medium, hard, or e, m, h
        for a list of categories, use a!trivia categories or a!trivia help
        """,
    )
    @cooldown(1, 2, BucketType.user)
    async def triviaCommand(self, ctx, category="random", difficulty="random"):
        dif = difficulty
        await ctx.channel.typing()
        help_strs = ["help", "category", "categories"]
        if category.lower() in help_strs:
            await ctx.send(
                f"""
List of valid categories, to play a specific category, use the category name or ID {ctx.prefix}trivia <category> <difficulty>
if you want to add more questions to the database, go to <https://opentdb.com/>, create a new account, and add your questions there

General - ID = 1
Books - ID = 2
Film - ID = 3
Music - ID = 4
Musicals & Theatres - ID = 5
Television - ID = 6
Video Games - ID = 7
Board Games - ID = 8
Science & Nature - ID = 9
Computers - ID = 10
Mathematics - ID = 11
Mythology - ID = 12
Sports - ID = 13
Geography - ID = 14
History - ID = 15
Politics - ID = 16
Art - ID = 17
Celebrities - ID = 18
Animals - ID = 19
Vehicles - ID = 20
Comics - ID = 21
Gadgets - ID = 22
Japanese Anime & Manga - ID = 23
Cartoon & Animations - ID = 24
Beavers - ID = 25 (does not have difficulties)

            """
            )
            return

        # THIS IS LITTERALLY JUST A COPY OF THE CODE BUT SLIGHTLY MODIFIED AS IT USES A COMPLETELY DIFFERENT API, aka a fucking json file lmao
        if str(category).lower() in ["beav", "beaver", "beavers", "25"]:
            with open("storage/misc/beaver_quiz.json", "r") as f:
                quiz_data = json.load(f)

            question = quiz_data[f"question{random.randrange(0, len(quiz_data))}"]

            answers = [question["correct"], question["ans0"], question["ans1"], question["ans2"]]

            random.shuffle(answers)

            abcd = ["a", "b", "c", "d"]

            for abc, answer in zip(abcd, answers):
                if answer == question["correct"]:
                    correct_answer_ID = abc
                    correct_answer = answer
                    break

            embed = discord.Embed(title="Trivia", description=f"**Beavers || ID: 25**", color=ctx.author.color)
            embed.add_field(name="Question", value=question["title"], inline=False)
            embed.add_field(
                name="is it?",
                value=f"""
a) {answers[0]}
b) {answers[1]}
c) {answers[2]}
d) {answers[3]}
                            """,
                inline=False,
            )

            await ctx.reply(embed=embed)

            response = await get_input(self, ctx, 30)

            if response.content.lower() == correct_answer.lower() or response.content.lower() == correct_answer_ID:
                await ctx.send(f"{ctx.author.mention} you are correct! it was {correct_answer_ID}, {correct_answer}")
                return

            await ctx.send(f"sorry {ctx.author.mention}, the answer was {correct_answer_ID}, {correct_answer}")
            return

        # if category is not beaver, continue as normal

        req_str = "https://opentdb.com/api.php?amount=1"

        difs = ["easy", "medium", "hard"]
        short_difs = ["e", "m", "h"]

        for x, y in zip(difs, short_difs):
            if category.lower() == x.lower() or category.lower() == y.lower():
                req_str += f"&difficulty={x}"
                category = "random"
                break

        for x, y in zip(difs, short_difs):
            if dif.lower() == x.lower() or dif.lower() == y.lower():
                req_str += f"&difficulty={x}"
                break

        human_readable_categories = [
            "General",
            "Books",
            "Film",
            "Music",
            "Musicals & Theatres",
            "Television",
            "Video Games",
            "Board Games",
            "Science & Nature",
            "Computers",
            "Mathematics",
            "Mythology",
            "Sports",
            "Geography",
            "History",
            "Politics",
            "Art",
            "Celebrities",
            "Animals",
            "Vehicles",
            "Comics",
            "Gadgets",
            "Japanese Anime & Manga",
            "Cartoon & Animations",
        ]
        categories = [
            "General Knowledge",
            "Entertainment: Books",
            "Entertainment: Film",
            "Entertainment: Music",
            "Entertainment: Musicals & Theatres",
            "Entertainment: Television",
            "Entertainment: Video Games",
            "Entertainment: Board Games",
            "Science & Nature",
            "Science: Computers",
            "Science: Mathematics",
            "Mythology",
            "Sports",
            "Geography",
            "History",
            "Politics",
            "Art",
            "Celebrities",
            "Animals",
            "Vehicles",
            "Entertainment: Comics",
            "Science: Gadgets",
            "Entertainment: Japanese Anime & Manga",
            "Entertainment: Cartoon & Animations",
        ]
        category_ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
        random_categories = ["random", "rand", "r", "any", "a", "all"]

        if category.lower() not in random_categories:
            for z, x, y in zip(human_readable_categories, categories, category_ids):
                if category.lower() == z.lower() or category.lower() == x.lower() or category.lower() == str(y):
                    req_str += f"&category={y+8}"
                    break

        r = requests.get(f"{req_str}&type=multiple")

        questions = json.loads(r.content)
        if questions["response_code"] != 0:
            if questions["response_code"] == 1:
                return await ctx.send("**Code 1: No Results** Could not return results. The API doesn't have enough questions for your query.")
            if questions["response_code"] == 2:
                return await ctx.send("**Code 2: Invalid Parameter** Contains an invalid parameter. Arguements passed in aren't valid.")
            if questions["response_code"] == 3:
                return await ctx.send("**Code 3: Token Not Found** Session Token does not exist.")
            if questions["response_code"] == 4:
                return await ctx.send("**Code 4: Token Empty** Session Token has returned all possible questions for the specified query. Resetting the Token is necessary.")

            return await ctx.send(f"error code {questions['response_code']}, please try again later")

        questions = questions["results"][0]
        answers = [
            html.unescape(questions["correct_answer"]),
            html.unescape(questions["incorrect_answers"][0]),
            html.unescape(questions["incorrect_answers"][1]),
            html.unescape(questions["incorrect_answers"][2]),
        ]

        random.shuffle(answers)

        abcd = ["a", "b", "c", "d"]

        for abc, answer in zip(abcd, answers):
            if answer == html.unescape(questions["correct_answer"]):
                correct = abc
                break

        result_category_id = "None"
        reslult_category = questions["category"]
        for x, y in zip(categories, category_ids):
            if x == reslult_category:
                result_category_id = y
                break

        embed = discord.Embed(title="Trivia", description=f"**{reslult_category} || ID: {result_category_id}**", color=ctx.author.color)
        embed.set_footer(text=f"Difficulty: {questions['difficulty']}")

        embed.add_field(name="Question:", value=f"{html.unescape(questions['question'])}", inline=False)
        embed.add_field(
            name="is it?",
            value=f"""
a) {answers[0]}
b) {answers[1]}
c) {answers[2]}
d) {answers[3]}
                        """,
            inline=False,
        )

        await ctx.reply(embed=embed)

        response = await get_input(self, ctx, 25)

        if response.content.lower() == questions["correct_answer"].lower() or response.content.lower() == correct:
            await ctx.send(f"{ctx.author.mention} you are correct! it was {correct}, {html.unescape(questions['correct_answer'])}")
            return

        await ctx.send(f"sorry {ctx.author.mention}, the answer was {correct}, {html.unescape(questions['correct_answer'])}")

async def setup(bot):
    await bot.add_cog(ecotrivia(bot))


"""
Simple checkpoint tracking helper class with dictionary-like access.  This is
used for modular inputs to track their state between executions.
"""

import json
import os
from copy import deepcopy
from datetime import datetime, timedelta
from logging import getLogger
from urllib.parse import quote

logger = getLogger("cypresspoint.checkpoint")

def json_dt_converter(o):
    if isinstance(o, datetime):
        return o.__str__()

class ModInputCheckpoint(object):
    NotSet = object()

    def __init__(self, checkpoint_dir, input_name):
        self.checkpoint_dir = checkpoint_dir
        self.input_name = input_name
        self.filename = self._safe_filename(checkpoint_dir, input_name)
        self.dump_after_updates = 10
        self._data = None
        self.default_item = KeyError
        self.updates = 0
        self._last_dump = None

    def __del__(self):
        # XXX: Review this.  What are the rules about raising an exception in __del__; no guarantees
        if self.updates > 0:
            raise Exception("You forgot to dump the checkpoint data.   Changes not saved!")

    def _safe_filename(self, checkpoint_dir, input_name):
        input_name = input_name.replace("://", "__")
        input_name = quote(input_name, safe="")
        return os.path.join(checkpoint_dir, input_name + ".json")

    def load(self, default=None):
        # XXX:  Support pulling in old checksum data from backup, IF primary gets corrupted.
        #       Shouldn't happen as we attempt to create the file safely, but weird things happen.
        cp_filename = self.filename
        logger.debug("Loading checkpoint data from %s", cp_filename)
        try:
            with open(cp_filename) as fp:
                self._data = json.load(fp) or {}
        except (IOError, ValueError):
            # If you see this message logged frequently, then there's an issue.
            logger.warning("[%s] Unable to process checkpoint file '%s'.  "
                           "This is normal for a new input.  Starting from scratch.",
                           self.input_name, cp_filename)
            if default:
                self._data = default
            else:
                self._data = {}

    def dump_on_interval(self, delta: timedelta) -> bool:
        """ Dump to disk if interval has elapsed even if dump_after_updates
        hasn't been reached.  This is helpful for long-lived modular inputs.

        A dump will also occur the very first time this function is called.
        """
        now = datetime.now()
        if self._last_dump:
            if self.updates == 0:
                return False
            age = now - self._last_dump
            if age < delta:
                return False
        self.dump(_now=now)
        return True

    def dump(self, _now=None):
        # Safely write out checkpoint data; this should avoid MOST common issues
        cp_filename = self.filename

        cp_filename_bk = cp_filename + ".bak"
        cp_filename_new = "{}.new-{}".format(cp_filename, os.getpid())
        try:
            with open(cp_filename_new, "w") as fp:
                # Indentation makes this human readable, with minimal overhead
                json.dump(self._data, fp, indent=2, default=json_dt_converter)
                cp_file_size = fp.tell()

            # Backup existing file (unless this is the first-time run)
            if os.path.isfile(cp_filename):
                # Remove old backup, if present
                if os.path.isfile(cp_filename_bk):
                    os.unlink(cp_filename_bk)
                # Move previous live file to "backup"
                os.rename(cp_filename, cp_filename_bk)

            # Move NEW checkpoint data (temporary file) into place
            os.rename(cp_filename_new, cp_filename)
            if self._data is not None:
                logger.info("Checkpoint data saved file=%s entries=%d bytes=%d",
                            cp_filename, len(self._data), cp_file_size)
        except Exception:
            logger.exception("[%s] Failure while writing out checkpoint data.  "
                             "State not saved.", self.input_name)
            logger.warning("[%s] Emergency dump of checkpoint data to log:\n%s",
                           self.input_name, json.dumps(self._data), default=json_dt_converter)
        self.updates = 0
        self._last_dump = _now or datetime.now()

    def __getitem__(self, item):
        try:
            return self._data[item]
        except KeyError:
            if isinstance(self.default_item, Exception):
                raise self.default_item(item)
            return deepcopy(self.default_item)

    def get(self, item, default=NotSet):
        try:
            return self._data[item]
        except KeyError:
            if default is self.NotSet:
                return deepcopy(self.default_item)
            else:
                return default

    def __setitem__(self, key, value):
        self._data[key] = value
        self.updates += 1
        if self.updates >= self.dump_after_updates:
            self.dump()

    def setdefault(self, key, default):
        if key not in self._data:
            self._data[key] = default
        return self._data[key]


import requests
_HOST_ = 'https://api.frankfurter.app'
_CURRENCIES_ = '/currencies'
_LATEST_ = '/latest'

response=""
currency_url=""
latest_url=""

def call_api(url: str) -> requests.models.Response:
    """
    Function that will call the specified API endpoint and return the response

    Parameters
    ----------
    url : str
        URL of the API endpoint to be called

    Pseudo-code
    ----------
    # => To be filled by student
        response=get request from _HOST_
        return response

    Returns
    -------
    requests.models.Response
        Response from API request
    """
    # => To be filled by student
    global response
    response = requests.get(url)

    return response

def format_currencies_url() -> str:
    """
    Function that will format the URL to the currency endpoint

    Parameters
    ----------
    None

    Pseudo-code
    ----------
    # => To be filled by student
        hosturl =https://api.frankfurter.app
        currencies=/currencies
            needed_url=https://api.frankfurter.app/currencies
        so
        cocatenate both variables to get needed_url by
        needed_url=hosturl+currencies
        now we call to api by the api fucntion using new url
        call_api(needed_url)

    Returns
    -------
    str
        Formatted URL to the currency endpoint
    """
    # => To be filled by student
    global currency_url
    currency_url=_HOST_+_CURRENCIES_
##    print("url is:"+currency_url)

    return currency_url

def get_currencies():
    """
    Function that will extract the currency codes available from the Frankfurter app as a list

    Parameters
    ----------
    None

    Pseudo-code
    ----------
    # => To be filled by student
        When this function is called, we use response given from call_api function to analyse/process the data.
        Since data is in a .json format so we can use .json function to extract data
        .json format is in a dictionary so we use keys with currency codes being the keys.
        We extract them using
         d=resp.json()
        keylist=data.keys()
        now convert the keylist to a list from dictionary by
        type casting
        list(data.keys) and return list

    Returns
    -------
    list
        Currency codes available from the Frankfurter app
    """
    # => To be filled by student
        # => To be filled by student
    format_currencies_url()
    call_api(currency_url)
    data=response.json()
    keys_list=data.keys()
    list_currency=list(keys_list)
    #print(list_currency)

    return list_currency

def format_latest_url(from_currency: str, to_currency: str) -> str:
    """
    Function that will format the URL to the latest endpoint

    Parameters
    ----------
    from_currency : str
        Currency code to be converted from
    to_currency : str
        Currency code to be converted to

    Pseudo-code
    ----------
    # => To be filled by student
        this function is used to send 'to' command to extract the current rate of defined currencies
        latesturl=host+to=from_currency,to_currency
        return
        latesturl

    Returns
    -------
    str
        Formatted URL to the latest endpoint
    """
    # => To be filled by student

    global currency_url
    latest_url=_HOST_+_LATEST_+"?to="+from_currency+","+to_currency
    #print(latest_url)
    return latest_url


from __future__ import division, absolute_import, print_function
from scitbx.array_family import flex
from LS49.sim.fdp_plot import george_sherrell
import math
# %%% boilerplate context: specialize to packaged big data %%%
from LS49 import ls49_big_data
from LS49.sim import step5_pad
step5_pad.big_data = ls49_big_data
from LS49.sim.step5_pad import full_path
# %%%%%%

class GS_ROI(george_sherrell):
  def __init__(self,path):
    george_sherrell.__init__(self,path)
    selection = (self.energy >= 7070.).__and__(self.energy < 7170.)
    self.energy = self.energy.select(selection)
    self.fp = self.fp.select(selection)
    self.fdp = self.fdp.select(selection)

def fp_distro(plt):
  OX = GS_ROI(full_path("data_sherrell/pf-rd-ox_fftkk.out"))
  RD = GS_ROI(full_path("data_sherrell/pf-rd-red_fftkk.out"))
  MM = GS_ROI(full_path("data_sherrell/Fe_fake.dat"))
  delta_fp = flex.double()

  for i in range(1,100):
    #delta_fp.append ( MM.fp[i]-MM.fp[i-1] );
    delta_fp.append ( OX.fp[i]-OX.fp[i-1] ); delta_fp.append ( RD.fp[i]-RD.fp[i-1] )
  STATS = flex.mean_and_variance(delta_fp)
  mean = STATS.mean()
  sigma = STATS.unweighted_sample_standard_deviation()
  displaynorm = 3.0
  plotx = flex.double([0.005*x for x in range(-100,100)])
  ploty = flex.double([displaynorm *
       (1./math.sqrt(2.*math.pi*sigma*sigma))*math.exp(-0.5*(math.pow(x-mean,2))/(sigma*sigma))
       for x in plotx])
  mean2 = 0.0
  sigma2 = 0.1
  displaynorm2 = 20. * math.sqrt(2 * math.pi * sigma2 *sigma2)
  ploty2 = flex.double([displaynorm2 *
       (1./math.sqrt(2.*math.pi*sigma2*sigma2))*math.exp(-0.5*(math.pow(x-mean2,2))/(sigma2*sigma2))
       for x in plotx])
  print("mean",mean,"sigma",sigma)
  #compute_functional_and_gradients_fp(FE1_fp=OX.fp,FE2_fp=RD.fp,mean=mean,sigma=sigma)
  n,bins,patches = plt.hist(delta_fp, 50, normed=0, facecolor="orange", alpha=0.75)
  plt.plot(plotx, ploty, "r-")
  plt.plot(plotx, ploty2, "b-")

  #plt.xlabel("Delta fp")
  #plt.title("Histogram of Delta fp")
  plt.axis([-0.75,0.75,0,40])

def fdp_distro(plt):
  OX = GS_ROI(full_path("data_sherrell/pf-rd-ox_fftkk.out"))
  RD = GS_ROI(full_path("data_sherrell/pf-rd-red_fftkk.out"))
  MM = GS_ROI(full_path("data_sherrell/Fe_fake.dat"))
  delta_fdp = flex.double()

  for i in range(1,100):
    #delta_fp.append ( MM.fp[i]-MM.fp[i-1] );
    delta_fdp.append ( OX.fdp[i]-OX.fdp[i-1] ); delta_fdp.append ( RD.fdp[i]-RD.fdp[i-1] )
  STATS = flex.mean_and_variance(delta_fdp)
  mean = STATS.mean()
  sigma = STATS.unweighted_sample_standard_deviation()
  displaynorm = 3.0
  plotx = flex.double([0.005*x for x in range(-100,100)])
  mean2 = 0.0
  sigma2 = 0.2
  displaynorm2 = 20. * math.sqrt(2 * math.pi * sigma2 *sigma2)
  ploty = flex.double([displaynorm *
       (1./math.sqrt(2.*math.pi*sigma*sigma))*math.exp(-0.5*(math.pow(x-mean,2))/(sigma*sigma))
       for x in plotx])
  ploty2 = flex.double([displaynorm2 *
       (1./math.sqrt(2.*math.pi*sigma2*sigma2))*math.exp(-0.5*(math.pow(x-mean2,2))/(sigma2*sigma2))
       for x in plotx])
  print("mean",mean,"sigma",sigma)
  #compute_functional_and_gradients_fp(FE1_fp=OX.fp,FE2_fp=RD.fp,mean=mean,sigma=sigma)
  n,bins,patches = plt.hist(delta_fdp, 50, normed=0, facecolor="orange", alpha=0.75)
  plt.plot(plotx, ploty, "r-")
  plt.plot(plotx, ploty2, "b-")
  #plt.xlabel("Delta d")
  #plt.title("Histogram of Delta fdp")
  plt.axis([-0.75,0.75,0,40])

if __name__=="__main__":

  from matplotlib import pyplot as plt
  fig, axes = plt.subplots(2, 1, figsize=(3.2,4.8)) #,figsize=(24,14)) default 6.4,4.8; new 4.8,4.8
  fp_distro(axes[0])
  fdp_distro(axes[1])
  plt.show()


"""User App URL Configuration"""

from django.urls import path
from django.conf import settings
from inventory.views import InventoryCreateView, InventoryListView, InventoryDetailsView, InvetoryUpdateView, \
    OSCreateView, FactoryCreateView, OSFListView, OSDeleteView, FactoryDeleteView, DomainCreateView, PurchaseListView

urlpatterns = [
    path('domain_create/', DomainCreateView.as_view(), name='domain_create'),
    path('inventory_create/', InventoryCreateView.as_view(), name='inventory_create'),
    path('inventory_list/', InventoryListView.as_view(), name='inventory_list'),
    path('purchase_list/', PurchaseListView.as_view(), name='purchase_list'),
    path('inventory_laptops_list/', InventoryListView.as_view(template_name='inventory_laptops_list.html'),
         name='inventory_laptops_list'),
    path('inventory_mobiles_list/', InventoryListView.as_view(template_name='inventory_mobiles_list.html'),
         name='inventory_mobiles_list'),
    path('inventory_monitors_list/', InventoryListView.as_view(template_name='inventory_monitors_list.html'),
         name='inventory_monitors_list'),
    path('inventory_others_list/', InventoryListView.as_view(template_name='inventory_others_list.html'),
         name='inventory_others_list'),
    path('inventory/<int:pk>/details', InventoryDetailsView.as_view(), name='inventory_details'),
    path('inventory/<int:pk>/update', InvetoryUpdateView.as_view(), name='inventory_update'),
    path('os_create/', OSCreateView.as_view(), name='os_create'),
    path('os_delete/<int:pk>', OSDeleteView.as_view(), name='os_delete'),
    path('factory_create/', FactoryCreateView.as_view(), name='factory_create'),
    path('factory_delete/<int:pk>', FactoryDeleteView.as_view(), name='factory_delete'),
    path('system_list/', OSFListView.as_view(), name='system_list'),
]


import socket
from threading import Thread
import threading

from datetime import datetime
from PyQt5.QtCore import QThread,pyqtSignal
from PyQt5.QtWidgets import (QApplication,QLineEdit,QListWidget,QListWidgetItem,QPushButton,
        QHBoxLayout, QLabel, QTextBrowser,
        QVBoxLayout, QWidget,QTabWidget)
from logger import logger

class ipv6_client(QWidget):

    def __init__(self):
        super(ipv6_client, self).__init__()
        self.tcp_flag = 0
        self.udp_flag = 0

        mainlayout = QVBoxLayout()

        self.client_ip_info_layer()
        self.client_socket_info()

        self.tab2_layout()
        # self.create_tabwidget()

        self.setLayout(mainlayout)
        # self.setWindowTitle("QTtest")
        # self.resize(800,300)
        # mainlayout.addWidget(self.tabwidget)
        mainlayout.addWidget(self.tab2)

        # self.tcp_connect_button.clicked.connect(self.tcp_connect_done)

        self.client =None
        self.tcp_socket_client =None
        self.udp_client1 = None

    def tab2_layout(self):
        self.tab2 = QWidget()
        self.tab2_layout = QVBoxLayout()
        self.tab2_layout.addLayout(self.client_all_layer)
        self.tab2_layout.addLayout(self.client_socket_list_layer)
        self.tab2.setLayout(self.tab2_layout)

    # def create_tabwidget(self):
    #     self.tabwidget = QTabWidget(self)
    #     self.tabwidget.setMinimumWidth(600)
    #
    #     self.tabwidget.addTab(self.tab2,"client")
    #
    #     self.tab_layout=QHBoxLayout()
    #     self.tab_layout.addWidget(self.tabwidget)

    def client_ip_info_layer(self):
        self.client_tcp_ipv6_line = QLineEdit()
        self.client_tcp_port_line = QLineEdit()

        self.client_tcp_ipv6_line.setText("fe80::d869:5350:d234:24f3")
        self.client_tcp_port_line.setText("8989")
        self.client_tcp_ipv6_lable = QLabel(text="ipv6")
        self.client_tcp_port_label = QLabel(text="port")

        self.tcp_connect_button = QPushButton()
        self.tcp_connect_button.setText("TCP_connect")
        self.tcp_connect_button.toggle()

        self.udp_connect_button = QPushButton()
        self.udp_connect_button.setText("UDP_connect")
        self.udp_connect_button.toggle()

        self.tcp_connect_button.pressed.connect(self.tcp_click_button_method)
        self.udp_connect_button.pressed.connect(self.udp_click_button_method)

        self.client_link_status = QListWidget()
        self.client_link_status.itemPressed.connect(self.link_list_press)

        self.client_ipv6_info_layer = QHBoxLayout()
        self.client_ipv6_info_layer.addWidget(self.client_tcp_ipv6_lable)
        self.client_ipv6_info_layer.addWidget(self.client_tcp_ipv6_line)
        self.client_ipv6_info_layer.addWidget(self.client_tcp_port_label)
        self.client_ipv6_info_layer.addWidget(self.client_tcp_port_line)
        self.client_ipv6_info_layer.addWidget(self.tcp_connect_button)
        self.client_ipv6_info_layer.addWidget(self.udp_connect_button)

        self.client_ipv6_layer =QVBoxLayout()
        self.client_ipv6_layer.addLayout(self.client_ipv6_info_layer)
        # self.tcp_udp_client_ipv6_layer.addLayout(self.udp_conenct_ipv6_info_layer)

        self.client_all_layer = QHBoxLayout()
        self.client_all_layer.addLayout(self.client_ipv6_layer)

    def client_socket_info(self):

        self.client_send_msg_text_line = QLineEdit()
        self.client_socket_send_button = QPushButton()
        self.client_socket_send_button.setText("send")
        self.client_socket_send_button.clicked.connect(self.client_send)
        self.client_socket_listwidget = QListWidget()
        self.client_socket_listwidget.itemPressed.connect(self.client_socket_textbrowser_show)
        self.client_socket_link_data_textbrowser = QTextBrowser()

        self.client_socket_send_layer = QHBoxLayout()
        self.client_socket_send_layer.addWidget(self.client_send_msg_text_line)
        self.client_socket_send_layer.addWidget(self.client_socket_send_button)

        self.client_socket_list_layer = QVBoxLayout()
        self.client_socket_list_layer.addLayout(self.client_socket_send_layer)
        self.client_socket_list_layer.addWidget(self.client_socket_listwidget)
        self.client_socket_list_layer.addWidget(self.client_socket_link_data_textbrowser)

    def socket_list_add(self,address,data):
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        item = QListWidgetItem(timestamp+" "+address+":"+data)
        item.data = data
        self.server_socket_listwidget.addItem(item)

    # def link_list_add(self,address,client):
    #     item = QListWidgetItem(address)
    #     item.client = client
    #     self.link_status.addItem(item)

    def link_list_press(self,item):
        print(type(item))
        logger.debug(item.client)

    def tcp_listen_close(self):
        self.server_tcp_ipv6_line.setEnabled(True)
        self.server_tcp_port_line.setEnabled(True)
        self.server_tcp_listen_button.setEnabled(True)

    def tcp_client_close(self,client):
        if client:
            for i in self.link_status.item():
                if client == i.client:
                    row = self.link_status.row(i)
                    if row:
                        self.link_status.takeItem(row)
        else:
            row = self.link_status.currentRow()
            client = self.link_status.currentItem().client
            logger.debug(client)
            try:
                self.tcp_socket_server.client_close(client)
                self.link_status.takeItem(row)
            except Exception as e:
                logger.debug(e)

    def tcp_connect_done(self):
        tcp_ipv6 = self.client_tcp_ipv6_line.text()
        tcp_port = int(self.client_tcp_port_line.text())
        try:

            self.tcp_socket_client =Tcp_Client(tcp_ipv6,tcp_port)
            self.tcp_socket_client.tcp_client_get_msg_sin.connect(self.client_list_add)
            self.tcp_socket_client.start()
            logger.debug(tcp_ipv6)
            logger.debug(tcp_port)
            logger.debug("start_tcp_client_connect")
            self.client_list_add("Tcp_server connect success")

        except Exception as e:
            logger.debug(e)

    def udp_connect_done(self):
        tcp_ipv6 = self.client_tcp_ipv6_line.text()
        tcp_port = int(self.client_tcp_port_line.text())

        try:
            self.udp_client1 = Udp_Client(tcp_ipv6,tcp_port)
            self.udp_client1.udp_client_get_msg_sin.connect(self.client_list_add)
            self.udp_client1.start()
            logger.debug(tcp_ipv6)
            logger.debug(tcp_port)
            logger.debug("start_udp_client_connect")

        except Exception as e:
            logger.debug(e)

    def tcp_close_done(self):
        try:

            self.tcp_socket_client.exit()
            self.tcp_socket_client.quit()
            #print(self.tcp_socket_client.isAlive())
            print(self.tcp_socket_client)
            self.tcp_socket_client = None

            logger.debug("close_tcp_client_connect")
        except BaseException as e:
            logger.debug(e)

    def udp_close_done(self):
        try:
            self.udp_client1.exit()
            logger.debug("close_udp_client_connect")
        except BaseException as e:
            logger.debug(e)

    def tcp_click_button_method(self):
        self.tcp_connect_button.setCheckable(True)

        if self.tcp_connect_button.isChecked() == False:
            if self.udp_connect_button.isChecked():
                print(self.tcp_connect_button.isChecked())
                print(self.udp_connect_button.isChecked())
                logger.debug("TCP "+self.tcp_connect_button.isChecked())
                logger.debug("UDP "+self.udp_connect_button.isChecked())
                logger.debug("udp_close_client")
                self.udp_close_done()
                self.udp_connect_button.setChecked(False)

            self.tcp_connect_done()
            logger.debug("tcp_client_connect")
        elif self.tcp_connect_button.isChecked():
            logger.debug("tcp_close_connect")
            self.tcp_close_done()

    def udp_click_button_method(self):
        self.udp_connect_button.setCheckable(True)

        if self.udp_connect_button.isChecked() == False:
            if self.tcp_connect_button.isChecked():
                print(self.tcp_connect_button.isChecked())
                print(self.udp_connect_button.isChecked())
                logger.debug("TCP "+self.tcp_connect_button.isChecked())
                logger.debug("UDP "+self.udp_connect_button.isChecked())
                self.tcp_close_done()
                logger.debug("tcp_close_client")
                self.tcp_connect_button.setChecked(False)

            self.udp_connect_done()
            logger.debug("udp_client_connect")
        elif self.udp_connect_button.isChecked():
            self.udp_close_done()
            logger.debug("udp_close_connect")

    def client_list_add(self,data):
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        item = QListWidgetItem(timestamp+":"+data)
        item.data = data
        self.client_socket_listwidget.addItem(item)

    def client_send(self):
        try:
            msg = self.client_send_msg_text_line.text()
            if self.tcp_socket_client:

                self.tcp_socket_client.client_send_msg(msg)
            elif self.udp_client1:
                self.udp_client1.send_msg(msg)
            else:
                pass

        except Exception as e:
            logger.debug(e)

    def client_socket_textbrowser_show(self):
        self.client_socket_link_data_textbrowser.setText("")
        data = self.client_socket_listwidget.currentItem().data
        self.client_socket_link_data_textbrowser.setText(data)

class Tcp_Client(QThread):

    tcp_connect_sin = pyqtSignal(object)
    tcp_close_socket_sin = pyqtSignal(object)
    tcp_client_get_msg_sin = pyqtSignal(object)
    tcp_client_sin = pyqtSignal(object,object)

    def __init__(self,ipv6,port):
        super(Tcp_Client,self).__init__()
        self.ipv6 = ipv6
        self.port = port
        self.addrinfo = socket.getaddrinfo(self.ipv6, int(self.port))[0]

        self.clients=[]
        self.clients_name_ip={}

    def get_msg(self,client,clitens,clients_name_ip,address):
        while True:
            try:
                data = client.recv(35565).decode()
                if data:
                    addr = "TCP " + address[0] + "：" + str(address[1])
                    self.tcp_get_msg_sin.emit(addr,data)
                    logger.debug(data)

                    length = len(threading.enumerate())
                    print('当前运行的线程数为：%d' % length)
                    if length <= 1:
                        break

            except Exception as e:
                logger.debug(client)
                logger.debug("close error")
                break

        #         发送消息

    def send_msg(self,client,msg):
        client.send(msg.encode())

    def recv_msg(self):
        while True:
            try:
                data = self.client.recv(35565).decode()
                print(data)
                data = data + "\n"
                self.content.append(data)
            except BaseException as e:
                logger.debug(e)

    def client_close(self,client):
        client.close()

        #     匿名类，线程处理,发送是一个线程，接受是一个线程

    def client_send_msg(self,data):
            self.client.send(data.encode())  # 把命令发送给对端

    def client_recv_msg(self):
        while self.client:
        #while True:
            data = self.client.recv(65535).decode()
            logger.debug(data)
            self.tcp_client_get_msg_sin.emit(data)

    def run(self):
        try:
            self.client= socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0)
            self.client.connect(self.addrinfo[-1])
            Thread(target=self.client_recv_msg).start()

        except Exception as e:
            logger.debug(e)

class Udp_Client(QThread):
    tcp_connect_sin = pyqtSignal(object)
    tcp_close_socket_sin = pyqtSignal(object)
    udp_client_get_msg_sin = pyqtSignal(object)
    tcp_client_sin = pyqtSignal(object,object)

    def __init__(self,ipv6,port):
        super(Udp_Client,self).__init__()
        self.ipv6 = ipv6
        self.port = port
        self.addrinfo = socket.getaddrinfo(self.ipv6, int(self.port))[0]

        self.clients=[]
        self.clients_name_ip={}
        self.send_flag = False

    def send_msg(self,msg):
        msg = msg.encode()
        self.udp_client.sendto(msg,self.addrinfo[-1])
        self.send_flag =True

    def udp_recv_msg(self):
        while True:
            while self.send_flag:
                data,address = self.udp_client.recvfrom(65535)
                data = data.decode()
                logger.debug(data)
                if data:
                    addr = "UDP " + address[0] + "：" + str(address[1])
                    self.udp_client_get_msg_sin.emit(data)
                    # logger.debug(data)

                    # length = len(threading.enumerate())
                    # print('当前运行的线程数为：%d' % length)
                    # if length <= 1:
                    #     break

    def run(self) :
        self.udp_client = socket.socket(socket.AF_INET6,socket.SOCK_DGRAM)

        Thread(target=self.udp_recv_msg).start()

# if __name__ == '__main__':
#     import sys
#     app = QApplication(sys.argv)
#     screenshot = ipv6_client()
#     screenshot.show()
#     sys.exit(app.exec_())


# -*- encoding: utf-8 -*-
##############################################################################
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program 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 this program.  If not, see http://www.gnu.org/licenses/.
#
##############################################################################

from openerp import models, fields, api
import logging

class IrTranslation(models.Model):
    _inherit = "ir.translation"

    @api.multi
    def write(self, values):
        product_obj = self.env['product.template']
        for record in self:
            if record.name == "product.template,name" and record.type == 'model' and record.lang == 'es_ES':
                _logger = logging.getLogger(__name__)
                product_name = record.src
                product_ids = product_obj.search([('name', '=', product_name)])

                for product_id in product_ids:
                    product_id.write({'dsn_name_en': record.src,
                                      'dsn_name_es': record.value})
                    _logger.info('updating PRODUCT ' + str(product_id.id) + ' ' + record.value)

                    break

        return super(IrTranslation, self).write(values)

class product(models.Model):

    _inherit = "product.template"

    def _default_translation(self):
        return self.name

    # @api.multi
    # @api.depends('write_date')
    # def dsn_update_es_en_names(self):
    #     translation_obj = self.env['ir.translation']
    #     _logger = logging.getLogger(__name__)
    #     for record in self:
    #         translation_ids = translation_obj.search([('src','=',record.name),
    #                                                   ('name','=','product.template,name'),
    #                                                   ('type','=','model'),
    #                                                   ('lang','=','es_ES')])
    #         if translation_ids:
    #             _logger.info('ENTRANDO')
    #             translation_id=translation_ids=[0]
    #             record.dsn_name_en = record.name
    #             record.dsn_name_es = translation_id.value
    #             _logger.info('updating PRODUCT ' + str(record.id) + ' ' + translation_id.value)

    @api.model
    def dsn_update_es_en_description(self):
        product_obj = self.env['product.template']
        translation_obj = self.env['ir.translation']
        product_ids = product_obj.search(['|',('dsn_name_es','=',False),('dsn_name_en','=',False)])

        _logger = logging.getLogger(__name__)

        if product_ids:
            for product_id in product_ids:

                translat_ids = translation_obj.search([('name','=','product.name,template'),
                                                        ('type','=','model'),
                                                        ('lang','=','es_ES'),
                                                        ('src','=',product_id.name)])
                if translat_ids:
                    translat_es = translat_ids[0].value

                    if translat_es:

                        product_id.write({"dsn_name_es": translat_es,
                                       "dsn_name_en": product_id.name})

                        _logger.info('updting PRODUCT ' + str(product_id.id) + ' ' + translat_es)

    dsn_name_es = fields.Char(string='Traducción ES')

    dsn_name_en = fields.Char(string='English Traduction')


import optparse
import yaml
import statistics

def add_space_size(string):
  x = f'{int(string):,d}'.replace(',', '\\,')
  return x

def add_space_time(string):
  y = str(string).split('.')[0]
  z = str(string).split('.')[1]
  y = f'{int(y):,d}'.replace(',', '\\,')
  return y +'.'+ z

def printsize(data, case, tool):
  casedata = data[case]
  if casedata.get(tool, {}).get('reachability') == ' ':
    return "noresults"
  elif casedata.get(tool, {}).get('reachability') != ' ' and casedata.get(tool, {}).get('reachability', {}).get('size', '-') != '-':
    sizes = casedata.get(tool, {}).get('reachability', {}).get('size', {})
    return add_space_size(sizes)
  else:
    sizes = "\\textbf{--}"
    return sizes

def printtime(data, case, tool):
  casedata = data[case]
  if casedata.get(tool, {}).get('reachability') == ' ':
    return "noresults"
  elif casedata.get(tool, {}).get('reachability').get('times', {}) != 'timeout' and casedata.get(tool, {}).get('reachability').get('times', {}) != 'outofmemory':
    times = casedata.get(tool, {}).get('reachability', {}).get('time', {})
    return float('{:.1f}'.format(times))
  elif casedata.get(tool, {}).get('reachability').get('times', {}) == 'timeout':
    return "t-o"
  elif casedata.get(tool, {}).get('reachability').get('times', {}) == 'outofmemory':
    return "o-o-m"
  else:
    times = "\\textbf{--}"
    return times

def getrow(data, D, case, reportsizes, reporttimes, stdev):
  result = ''
  if reportsizes:
    result += ' {0} & {1} & {2} & {3}'.format(printsize(data, case, 'static_only'),
      printsize(data, case, 'default_master'),
      printsize(data, case, 'default_parunfold'),
      printsize(data, case, 'alternative_parunfold'))
    if printsize(data, case, 'static_only') == printsize(data, case, 'default_master') == printsize(data, case, 'default_parunfold') == printsize(data, case, 'alternative_parunfold'):
        result = '\\multicolumn{4}{c|}{' + format(printsize(data, case, 'static_only') + '}')
    elif printsize(data, case, 'static_only') == printsize(data, case, 'default_master') and (printsize(data, case, 'default_parunfold') == printsize(data, case, 'alternative_parunfold'))  :
        result = '\\multicolumn{2}{c|}{' + format(printsize(data, case, 'static_only')) + '}' + ' &\\multicolumn{2}{c|}{' + format(printsize(data, case, 'default_parunfold') + '}')
    elif printsize(data, case, 'static_only') == printsize(data, case, 'default_master') == printsize(data, case, 'default_parunfold'):
        result = '\\multicolumn{3}{c|}{' + format(printsize(data, case, 'static_only')) + '} & \\multicolumn{1}{c|}{' + format(printsize(data, case, 'alternative_parunfold') + '}')
    elif printsize(data, case, 'default_master') == printsize(data, case, 'default_parunfold') == printsize(data, case, 'alternative_parunfold'):
        result = format(printsize(data, case, 'static_only') + ' & \\multicolumn{3}{|c|}{' + format(printsize(data, case, 'default_master')) + '}')

  if reporttimes:
    result += '& {0}{1} & {2}{3} & {4}{5} & {6}{7}'.format(get_mean(data, case, D, 'static_only'), get_stdev(data, case, D, 'static_only', stdev) ,
      get_mean(data, case, D, 'default_master'), get_stdev(data, case, D, 'default_master', stdev),
      get_mean(data, case, D, 'default_parunfold') , get_stdev(data, case, D, 'default_parunfold', stdev),
      get_mean(data, case, D, 'alternative_parunfold') , get_stdev(data, case, D, 'alternative_parunfold', stdev))

  return '{0} \\\\'.format(result)

def get_mean(data, case, D, tool):
  x = []
  casedata = data[case]
  if casedata.get(tool, {}).get('reachability').get('times', {}) != 'timeout' and casedata.get(tool, {}).get(
          'reachability').get('times', {}) != 'outofmemory':
    for d in D:
      x.append(printtime(d, case, tool))
    return add_space_time('{:.1f}'.format(statistics.mean(x)))
  else:
    return printtime(data, case, tool)

def get_stdev(data, case, D, tool, stdev):
  x = []
  casedata = data[case]
  if len(D) > 1 and stdev == True:
    if casedata.get(tool, {}).get('reachability').get('times', {}) != 'timeout' and casedata.get(tool, {}).get(
            'reachability').get('times', {}) != 'outofmemory':
      for d in D:
        x.append(printtime(d, case, tool))
      #print('SD {}'.format((statistics.stdev(x)*100)/statistics.mean(x)))
      return '(' + str(float('{:.1f}'.format(statistics.stdev(x)))) + ')'
    else:
      return ''
  else:
    return ''

def gettable(data, D, outfilename, sizes, times, stdev):
  print('Getting table, sizes: {0}, times: {1}'.format(sizes, str(times)))
  texfile = open(outfilename, 'w')
  y = sorted(data.keys())
  print(y)
  columns = 3
  if sizes:
    columns += 9
  if times:
    columns += 9

  texfile.write('''\\begin{center}
  \\renewcommand{\\arraystretch}{1.7}
    \\scriptsize
    ''')
  texfile.write(
    '\\begin{tabular}{r|c@{\\hspace{6pt}}c@{\\hspace{6pt}}c@{\\hspace{6pt}}c@{\\hspace{6pt}}|r@{\\hspace{6pt}}r@{\\hspace{6pt}}r@{\\hspace{6pt}}r}')
  texfile.write('{0}{1}\\\\'.format('\\multicolumn{1}{c}{Models} &  \\multicolumn{4}{c}{Sizes}' if sizes else '',
                                     ' & \\multicolumn{4}{c}{Times}' if times else ''))
  texfile.write('& {0}{1}\\\\'.format(
    '\\texttt{static} & \\texttt{def.master} & \\texttt{def.par} & \\texttt{alt.par}' if sizes else '',
    ' & \\texttt{static} & \\texttt{def.master} & \\texttt{def.par} & \\texttt{alt.par}' if times else ''))
  texfile.write('''
    \\toprule
    ''')

  for key in y:
    print(key)
    texfile.write('\\emph{' + key + '}&' + getrow(data, D, str(key), sizes, times, stdev))
    texfile.write('\n')

  texfile.write('''
\\bottomrule
\\end{tabular}
\\end{center}
''')
  texfile.close()
  return texfile.name

def runCmdLine():
  D = []
  parser = optparse.OptionParser(usage='usage: %prog [options] infile1 ... infilen outfile')
  parser.add_option('-s', action='store_true', dest='stdev',
                    help='Print standard deviation for the times')
  options, args = parser.parse_args()
  if len(args) < 2:
    parser.error(parser.usage)

  data = yaml.safe_load(open(args[0]).read())
  for i in args[:-1]:
    D.append(yaml.safe_load(open(i).read()))
  outfilename = args[-1]

  gettable(data, D, outfilename, sizes = True, times = True, stdev = options.stdev)

if __name__ == '__main__':
  runCmdLine()


from __future__ import unicode_literals
from django.conf.urls import url

from . import views

app_name='watsonstt'

urlpatterns = [
#    url( r'^', views.ngmain,     name='ngmain'),
    url( r'^ngmain/', views.ngmain,     name='ngmain'),

    url( r'^newwordsave/',  views.newwordsave,    name='newwordsave'),
    url( r'^newwordlist/',  views.newwordlist,    name='newwordlist'),
    url( r'^newworddelete/',  views.newworddelete,    name='newworddelete'),

    url( r'^start/', views.start,       name='start'),

# XHR era
    url( r'^xhour1/',  views.xhour1,   name='xhour1'),
    url( r'^getcred/', views.getcred,  name='getcred'),
    url( r'^getcust/', views.getcust,  name='getcust'),
# XHR era
# AJS era
    url( r'^singleword/',       views.singleword,       name='singleword'),
    url( r'^singlewordsave/',   views.singlewordsave,   name='singlewordsave'),
    url( r'^singlewordrender/', views.singlewordrender, name='singlewordrender'),

    url( r'^multiword/',      views.multiword,        name='multiword'),
    url( r'^angularcred/',     views.angularcred,        name='angularcred'),
    url( r'^angularcust/',     views.angularcust,        name='angularcust'),
    url( r'^multiwordsave/',  views.multiwordsave,    name='multiwordsave'),

######
    url( r'^generalquery/', views.generalquery, name='generalquery'),
    url( r'^executequery/', views.executequery, name='executequery'),
######

    url( r'^ang/', views.ang,           name='ang'),

#    url( r'^tempword1/', views.tempword1,                     name='tempword1'),
    url( r'^tempword2/', views.tempword2,                     name='tempword2'),
    url( r'^tempword3/(?P<word_id>[0-9]+)/', views.tempword3, name='tempword3'),
    url( r'^tempword4/(?P<word_id>[0-9]+)/', views.tempword4, name='tempword4'),
    url( r'^tempword5/(?P<sound_id>\d+)/', views.tempword5,   name='tempword5'),
    url( r'^tempword6/(?P<word_id>\d+)/', views.tempword6,    name='tempword6'),

##### credential
    url( r'^step1list/', views.step1list,           name='step1list'),
    url( r'^step1form/', views.step1form,           name='step1form'),

###### customization
    url( r'^step2form/', views.step2form,           name='step2form'),
    url( r'^step2list/', views.step2list,           name='step2list'),

    url( r'^filetest1/', views.filetest1,           name='filetest1'),
    url( r'^filetest2/', views.filetest2,           name='filetest2'),

# AJS era end

######
#    url( r'^step6formword/', views.step6formword,           name='step6formword'),
#    url( r'^step6formsond/', views.step6formsond,           name='step6formsond'),
#    url( r'^step6final/',    views.step6final,              name='step6final'),
######
    url( r'^step9home/', views.step9home,              name='step9home'),
    url( r'^step9formword/', views.step9formword,        name='step9formword'),
    url( r'^step9editword/(?P<word_id>\d+)/', views.step9editword,   name='step9editword'),
    url( r'^step9soundaword/(?P<word_id>\d+)/', views.step9soundaword,   name='step9soundaword'),
    url( r'^step9deletesound/(?P<sound_id>\d+)/', views.step9deletesound,   name='step9deletesound'),
    url( r'^step9deleteword/(?P<word_id>\d+)/',   views.step9deleteword,   name='step9deleteword'),
#    url( r'^step9formsond/', views.step9formsond,        name='step9formsond'),
#    url( r'^step9listsound/', views.step9listsound,         name='step9listsound'),

###### ###### ###### ###### ###### ###### ###### ###### ###### ###### ###### ###### ######
# test
    url( r'^formsettest/', views.formsettest,           name='formsettest'),

    url( r'^dynamictest/', views.dynamictest,                   name='dynamictest'),
    url( r'^api1/', views.api1,                   name='api1'),
    url( r'^api2/', views.api2,                   name='api2'),
# old
#    url( r'^form/', views.get_name,               name='form'),
# temp

#    url( r'^$',     views.HomePageView.as_view(),  name='home'),
]


import random
import torch
import pickle
import os
import numpy as np
import matplotlib.pyplot as plt
from collections import deque
from World import World
from dqn_agent import Agent

def main():
    env = World()
    agents = [Agent(state_size=env.observation_space, action_size=env.action_space, seed=0) for i in range(env.getAgentNum())]
    scores = dqn(env, agents)
    with open('./multiagent/scores.pkl', 'wb') as f:
        pickle.dump(scores, f, protocol=pickle.HIGHEST_PROTOCOL)

    # plot the scores
    scores_window = deque(maxlen=100)
    avg_scores = []
    for score in scores:
        scores_window.append(score)
        avg_scores.append(np.mean(scores_window))

    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.plot(np.arange(len(scores)), scores, linewidth=0.5, label='score')
    plt.plot(np.arange(len(avg_scores)), avg_scores, linewidth=2, label='MA score')
    plt.legend(['score', 'MA score'])
    plt.ylabel('Score')
    plt.xlabel('Episode #')
    fig.savefig('./multiagent/training_curve.png')

def dqn(env, agents, n_episodes=10000, max_t=720, eps_start=1.0, eps_end=0.01, eps_decay=0.995):
    """Deep Q-Learning.

    Params
    ======
        n_episodes (int): maximum number of training episodes
        max_t (int): maximum number of timesteps per episode
        eps_start (float): starting value of epsilon, for epsilon-greedy action selection
        eps_end (float): minimum value of epsilon
        eps_decay (float): multiplicative factor (per episode) for decreasing epsilon
    """
    scores = []                        # list containing scores from each episode
    scores_window = deque(maxlen=100)  # last 100 scores
    eps = eps_start                    # initialize epsilon
    first_episode = 0

    if os.path.exists('./multiagent/checkpoint_50000.pkl'):
        with open('./multiagent/checkpoint_50000.pkl', 'rb') as f:
            ckpt = pickle.load(f)
        scores = ckpt['scores']
        for score in scores:
            scores_window.append(score)
        first_episode = 0
        eps = ckpt['eps']
        for i, agent in enumerate(agents):
            agent.qnetwork_target.load_state_dict(ckpt['qnetwork_target'][i])
            agent.qnetwork_local.load_state_dict(ckpt['qnetwork_local'][i])
            agent.optimizer.load_state_dict(ckpt['optimizer'][i])

    for i_episode in range(first_episode + 1, n_episodes+1):
        state = env.reset()
        score = 0
        done = False
        eps = 1/i_episode
        for t in range(max_t):
            actions = []
            for ID, agent in enumerate(agents):
                action = agent.act(state, eps)
                actions.append(action)
            next_state, reward, done, _ = env.step(actions)
            for ID, agent in enumerate(agents):
                agent.step(state, actions[ID], reward[ID], next_state, done)
            state = next_state
            score += sum(reward)
            if done:
                break
        scores_window.append(score)       # save most recent score
        scores.append(score)              # save most recent score
        eps = max(eps_end, eps_decay*eps) # decrease epsilon
        print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end="")
        if i_episode % 100 == 0:
            print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)))
            ckpt = {'qnetwork_local':[agent.qnetwork_local.state_dict() for agent in agents],
                    'qnetwork_target':[agent.qnetwork_target.state_dict() for agent in agents],
                    'optimizer':[agent.optimizer.state_dict() for agent in agents],
                    'episode':i_episode,
                    'scores':scores,
                    'eps':eps
            }
            with open('./multiagent/checkpoint.pkl', 'wb') as f:
                pickle.dump(ckpt, f)
            # torch.save(ckpt, './multiagent/checkpoint.pth')#要改成pickle！！！
        if np.mean(scores_window) >= 5000.0:
            print('\nEnvironment solved in {:d} episodes!\tAverage Score: {:.2f}'.format(i_episode-100, np.mean(scores_window)))
            ckpt = {'qnetwork_local':[agent.qnetwork_local.state_dict() for agent in agents],
                    'qnetwork_target':[agent.qnetwork_target.state_dict() for agent in agents],
                    'optimizer':[agent.optimizer.state_dict() for agent in agents],
                    'episode':i_episode,
                    'scores':scores,
                    'eps':eps
            }
            with open('./multiagent/checkpoint.pkl', 'wb') as f:
                pickle.dump(ckpt, f)
            # torch.save(ckpt, './multiagent/checkpoint.pth')
            break
    return scores

if __name__ == '__main__':
    main()


from sqlalchemy import create_engine
from sqlalchemy import sql

from BarBeerDrinker import config
engine = create_engine(config.database_uri)

def get_bars():
    with engine.connect() as con:
        rs = con.execute("SELECT * from barsN;")
        return [dict(row) for row in rs]
def get_bars_only():
        with engine.connect() as con:
                rs = con.execute("SELECT name from barsN ORDER BY name;")
                return [row['name'] for row in rs]

def get_top_10_spenders(bar):
        with engine.connect() as con:
                query = sql.text(
                "SELECT Patron, sum(total) as sum_total \
                FROM Transactions \
                WHERE bar = :bar \
                GROUP BY Patron \
                ORDER BY sum_total desc limit 10;"
                )
                rs = con.execute(query, bar = bar)
                results = [dict(row) for row in rs]
                for r in results:
                        r['sum_total'] = float(r['sum_total'])
                return results

def find_bar(name):
    with engine.connect() as con:
        query = sql.text(
            "SELECT * from barsN WHERE name = :name;"
        )
        rs = con.execute(query, name=name)
        result = rs.first()
        if result is None:
            return None
        return dict(result)

def filter_beers(max_price):
    with engine.connect() as con:
        query = sql.text(
            "SELECT * FROM Sells4 WHERE Price < :max_price;"
        )
        rs = con.execute(query, max_price = max_price)
        results = [dict(row) for row in rs]
        for r in results:
            r['Price'] = float(r['Price'])
        return results

def get_bar_menu(bar_name):
    with engine.connect() as con:
        if bar_name is None:
                rs = con.execute('SELECT * from Sells4 WHERE Food is null')
                results = [dict(row) for row in rs]
                for i, _ in enumerate(results):
                    results[i]['Price'] = float(results[i]['Price'])
                return results
        query = sql.text('SELECT a.bar, a.beer, a.price, b.manf, coalesce(c.like_count, 0) as likes \
                FROM Sells4 AS a \
                JOIN Beers AS b \
                ON a.beer = b.name \
                LEFT OUTER JOIN (SELECT beer, count(*) as like_count FROM Likes GROUP BY beer) as c \
                ON a.beer = c.beer \
                WHERE a.bar = :bar; \
                ')
        rs = con.execute(query, bar = bar_name)
        results = [dict(row) for row in rs]
        for i, _ in enumerate(results):
            results[i]['price'] = float(results[i]['price'])
        return results

def get_menu_top(beer):
        with engine.connect() as con:
                query = sql.text('SELECT bar, count(*) as like_count \
                        FROM Transactions WHERE beer =:beer \
                        GROUP BY beer, bar \
                        ORDER BY like_count desc limit 10 \
                        ')
                rs = con.execute(query, beer = beer)
                results = [dict(row) for row in rs]
                return results

def get_bar_top(bar, week):
        with engine.connect() as con:
                query = sql.text('SELECT beer, count(*) as beer_count \
                        FROM Transactions WHERE bar = :bar \
                        AND beer is not null \
                        AND Weekend = :week \
                        GROUP BY beer, bar \
                        ORDER BY beer_count desc limit 10; \
                        ')
                rs = con.execute(query, bar = bar, week = week)
                results = [dict(row) for row in rs]
                return results

def get_bars_selling(beer):
    with engine.connect() as con:
        query = sql.text('SELECT a.Bar, a.Price, b.customers \
                FROM Sells4 AS a \
                JOIN (Select bar, count(*) AS customers FROM Frequents GROUP BY bar) as b \
                ON a.bar = b.bar \
                WHERE a.beer = :beer \
                ORDER BY a.price; \
                ')
        rs = con.execute(query, beer = beer)
        results = [dict(row) for row in rs]
        for i, _ in enumerate(results):
            results[i]['Price'] = float(results[i]['Price'])
        return results

def get_bar_frequent_counts():
    with engine.connect() as con:
        query = sql.text('SELECT bar, count(*) as frequentCount \
                FROM Frequents \
                GROUP BY bar; \
                ')
        rs = con.execute(query)
        results = [dict(row) for row in rs]
        return results

def get_bar_cities():
    with engine.connect() as con:
        rs = con.execute('SELECT DISTINCT State FROM barsN;')
        return [row['State'] for row in rs]

def get_beers():
    with engine.connect() as con:
        rs = con.execute('SELECT name, manf FROM Beers;')
        return [dict(row) for row in rs]

def get_beers_only():
    with engine.connect() as con:
        rs = con.execute('SELECT name from Beers;')
        return [row['name'] for row in rs]

def get_beer_manufacturer(beer):
    with engine.connect() as con:
        if beer is None:
            rs = con.execute('SELECT DISTINCT manf FROM Beers ORDER BY manf;')
            return [row['manf'] for row in rs]
        query = sql.text('SELECT manf FROM Beers WHERE name = :beer;')
        rs = con.execute(query, beer = beer)
        result = rs.first()
        if result is None:
            return None
        return result['manf']

def get_beers_of_manf(manf):
        with engine.connect() as con:
                query = sql.text('SELECT name FROM Beers where manf = :manf')
                rs = con.execute(query, manf = manf)
                return [dict(row) for row in rs]

def get_drinkers():
    with engine.connect() as con:
       rs = con.execute('SELECT * FROM Drinkers;')
       return [dict(row) for row in rs]

def get_drinkers_only():
    with engine.connect() as con:
       rs = con.execute('SELECT name FROM Drinkers;')
       return [row['name'] for row in rs]

def get_likes(drinker_name):
    with engine.connect as con:
        query = sql.text("SELECT beer FROM Likes WHERE drinker = :name;")
        rs = con.execute(query, name = drinker_name)
        return [row['Beer'] for row in rs]

def get_drinker_info(drinker_name):
    with engine.connect() as con:
        query = sql.text("SELECT * from Drinkers WHERE name = :name;")
        rs = con.execute(query, name=drinker_name)
        result = rs.first()
        if result is None:
            return None
        return dict(result)

def get_drinker_top(beer):
        with engine.connect() as con:
                query = sql.text('SELECT Patron, count(*) as like_count \
                        FROM Transactions \
                        where beer = :beer \
                        and beer is not null \
                        GROUP BY Patron \
                        ORDER BY like_count desc limit 10 \
                        ')
                rs = con.execute(query, beer = beer)
                results = [dict(row) for row in rs]
                return results

def get_frequents(drinker):
        with engine.connect() as con:
                query = sql.text('SELECT bar FROM Frequents where drinker = :drinker;')
                rs = con.execute(query, drinker = drinker)
                return [dict(row) for row in rs]

def get_drinker_trans(name):
        with engine.connect() as con:
                query = sql.text('SELECT * FROM Transactions \
                        where patron = :name ORDER BY bar, HTime, MTime')
                rs = con.execute(query, name = name)
                results = [dict(row) for row in rs]
                for i, _ in enumerate(results):
                        results[i]['Total'] = float(results[i]['Total'])
                        results[i]['Tip'] = float(results[i]['Tip'])
                return results

def get_drinker_beer_most(name):
        with engine.connect() as con:
                query = sql.text('SELECT Beer, count(Beer) as beer_count \
                        FROM Transactions \
                        WHERE Patron = :name \
                        AND Beer is not null \
                        GROUP BY Beer \
                        ORDER BY beer_count desc limit 10')
                rs = con.execute(query, name = name)
                results = [dict(row) for row in rs]
                return results

def get_drinker_bar_most(name):
        with engine.connect() as con:
                query = sql.text('SELECT Bar, sum(Total) as bar_total \
                        FROM Transactions \
                        WHERE Patron = :name \
                        GROUP BY Bar \
                        ORDER BY bar_total desc')
                rs = con.execute(query, name = name)
                results = [dict(row) for row in rs]
                for i, _ in enumerate(results):
                        results[i]['bar_total'] = float(results[i]['bar_total'])
                return results

def get_bartenders():
        with engine.connect() as con:
                rs = con.execute('SELECT DISTINCT bartender FROM Bartenderskevin ORDER BY bartender')
                return [row['bartender'] for row in rs]

def get_bartenders_shifts(name):
        with engine.connect() as con:
                query = sql.text('SELECT * FROM Bartenderskevin \
                        WHERE bartender = :name')
                rs = con.execute(query, name = name)
                results = [dict(row) for row in rs]
                return results

def get_beers_sold_by(name):
        with engine.connect() as con:
                query = sql.text('SELECT a.beer, count(a.beer) as beer_count \
                        FROM Transactions as a, Bartenderskevin as b \
                        WHERE a.bar = b.bar \
                        and b.shiftstart < a.HTime \
                        AND b.shiftend > a.HTime \
                        AND a.daynumber = b.daynumber \
                        AND beer is not null \
                        AND b.bartender = :name \
                        GROUP BY beer \
                        ')
                rs = con.execute(query, name = name)
                results = [dict(row) for row in rs]
                return results


import datetime
import os

import openpyxl
from openpyxl.styles import Alignment

from postgre.commands_db import select_user

path = os.getenv("PATH_XLSX")

long_text = Alignment(
    horizontal='left',
    vertical='top',
    wrap_text=True,
    shrink_to_fit=True
)
small_text = Alignment(
    horizontal='left',
    vertical='top',
    wrap_text=True,
    shrink_to_fit=True
)

def create_answer_xlsx(from_user, about_user, txt_about_place, txt_about_user):
    from_user_data = select_user(from_user)[0]
    about_user_data = select_user(about_user)[0]
    print(from_user_data)

    workbook = openpyxl.load_workbook(path)
    sheet = workbook.active
    max_row = sheet.max_row + 1
    date = datetime.date.today()
    print(date.strftime('%d.%m.%y'))
    sheet[f'A{max_row}'].alignment = long_text
    sheet[f'A{max_row}'] = date
    sheet[f'B{max_row}'].alignment = long_text
    sheet[f'B{max_row}'] = f'{from_user_data[1]} - (@{from_user_data[2]})'
    sheet[f'C{max_row}'].alignment = long_text
    sheet[f'C{max_row}'] = f'{about_user_data[1]} - (@{about_user_data[2]})'
    sheet[f'D{max_row}'].alignment = long_text
    sheet[f'D{max_row}'] = txt_about_place
    sheet[f'E{max_row}'].alignment = long_text
    sheet[f'E{max_row}'] = txt_about_user

    workbook.save(path)


# Banana test function for arbitrary dimension

import numpy as np
from scipy.stats import special_ortho_group
import warnings

class Banana:
    def __init__(self, dim: int, a: np.ndarray, seed: bool = None):
        """
        Creates a random rotation of the following function in D dimensions:
            f(x) = exp (- 0.5*(x_1^2 + (a_0 x_1^2 + a_1 x_2 + a_2)^2 + sum_{i=3}^D a_i x_i^2 ))
        :param a: parameters of the banana
        """
        if a.size < dim + 1:
            warnings.warn('parameter vector is too short, remaining ones will be filled with 1.')
            a = np.concatenate([a.flatten(), np.ones((dim+1 - a.size))])

        self.dim = dim
        self.a = a

        # sample a random rotation matrix
        if seed is not None:
            self.R = special_ortho_group(dim, seed).rvs()
        else:
            self.R = np.eye(dim)

    def _x_trafo(self, x):
        x = self.R @ x
        if x.ndim == 1:
            x = x[:, None]
        x[1, :] = self.a[0] * x[0, :] ** 2 + self.a[1] * x[1, :] + self.a[2]
        x[2:, :] = self.a[3:, None] * x[2:, :]
        return x

    def f(self, x):
        "Some unnormalized density"
        return np.exp(-self.pot_energy(x)).squeeze()

    def pot_energy(self, x):
        "The negative log of the above, that is, the potential energy"
        arg = self._x_trafo(x)
        return 0.5 * (arg ** 2).sum(axis=0).squeeze()

    def grad_e(self, x):
        grad = self._x_trafo(x)
        grad[0, :] = grad[0, :] + grad[1, :] * 2 * x[0, :] * self.a[0]
        grad[1, :] = grad[1, :] * self.a[1]
        return grad


import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from scipy.integrate import quad
from RealIntegratedLuminosity import L_int_summary_18

plt.rcParams.update({
  "text.usetex": True,
  "font.family": "Helvetica",
  "font.size": 12
})

f=open('Data/a_18_4Par.txt',"r")
lines=f.readlines()
a_18=[]
for x in lines:
    a_18.append(float(x.split(' ')[0]))

f.close()

f=open('Data/b_18_4Par.txt',"r")
lines=f.readlines()
b_18=[]
for x in lines:
    b_18.append(float(x.split(' ')[0]))

f.close()

f=open('Data/c_18_4Par.txt',"r")
lines=f.readlines()
c_18=[]
for x in lines:
    c_18.append(float(x.split(' ')[0]))

f.close()

f=open('Data/d_18_4Par.txt',"r")
lines=f.readlines()
d_18=[]
for x in lines:
    d_18.append(float(x.split(' ')[0]))

f.close()

f=open('Data/ts_18_4Par.txt',"r")
lines=f.readlines()
ts_18=[]
for x in lines:
    ts_18.append(float(x.split(' ')[0]))

f.close()

#model parameters and initial guesses
ts_18=np.array(ts_18)
a_18=np.array(a_18)
b_18=np.array(b_18)
c_18=np.array(c_18)
d_18=np.array(d_18)

#Objective Function
def fun(t1):
    result=np.empty(len(x0))
    for i in range(len(x0)):
        lam=lambda x1: a_18[i]*np.exp(-(b_18[i]*x1))+c_18[i]*np.exp(-d_18[i]*x1)
        result[i]=-quad(lam, 0, t1[i])[0]

    result = np.sum(result)
    return result

#constraint
def cons(t1):
    res = np.sum(t1) - (tot)
    return res

#jacobian of the objective function
def jacb(t1):
    der=-a_18*np.exp(-(b_18*t1))-c_18*np.exp(-d_18*t1)
    #result=np.sum(der)
    return der

#Initial guesses
x0=ts_18

#constraint determination
tot=sum(x0)

#bounds
list=[[1800,86400]]
for li in range(1, len(a_18)):
    list=list+[[1800, 86400]]

bnd=list

#optimization
res = minimize(fun, x0, options={'disp': True, 'maxiter':10000}, constraints={'type':'eq', 'fun': cons, 'jac': lambda x: np.ones(len(x0))}, jac=jacb, method='SLSQP', bounds=bnd) #

#saving optimized times
with open('Data/res_opt_2018.txt', 'w') as f:
        f.write('')
        f.close()
for el in res.x:
    with open('Data/res_opt_2018.txt', 'a') as f:
        f.write(str(el))
        f.write('\n')


from flask import Blueprint, flash, g, redirect, render_template, request, session, url_for

from zip_code_app.models import City
from sqlalchemy import func

from zip_code_app.db import get_db

bp = Blueprint("city", __name__, url_prefix="/cities")

@bp.route("/", methods=['GET'])
def get_cities_groupby():
    cities = []
    db = get_db()
    cities_groupby = City.query.with_entities(City.latitude, City.longitude, func.count(City.id)).group_by(City.latitude, City.longitude).all()

    for city in cities_groupby:
        cities.append({
            'latitude': city[0],
            'longitude': city[1],
            'count': city[2]
        })
    return {
        "data": cities
    }

@bp.route("/all", methods=['GET'])
def get_cities_all():
    cities = []
    db = get_db()

    for city in City.query.all():
        cities.append(city.serialize())
    return {
        "data": cities
    }


import torch.nn as nn
import torch
import torch.nn.functional as F
from models.n_utils.separableconvblock import SeparableConvBlock,MaxPool2dStaticSamePadding,Swish

class BiFPN(nn.Module):

    def __init__(self, num_channels, epsilon = 1e-4, attention = True):

        super(BiFPN, self).__init__()
        self.epsilon = epsilon

        #Conv layers

        self.conv6_up = SeparableConvBlock(num_channels)
        self.conv5_up = SeparableConvBlock(num_channels)
        self.conv4_up = SeparableConvBlock(num_channels)
        self.conv3_up = SeparableConvBlock(num_channels)
        self.conv4_down = SeparableConvBlock(num_channels)
        self.conv5_down = SeparableConvBlock(num_channels)
        self.conv6_down = SeparableConvBlock(num_channels)
        self.conv7_down = SeparableConvBlock(num_channels)

        self.p4_downsample = MaxPool2dStaticSamePadding(3, 2)
        self.p5_downsample = MaxPool2dStaticSamePadding(3, 2)
        self.p6_downsample = MaxPool2dStaticSamePadding(3, 2)
        self.p7_downsample = MaxPool2dStaticSamePadding(3, 2)

        self.swish = Swish()

        # weight
        self.p6_w1 = nn.Parameter(torch.ones(2, dtype= torch.float32), requires_grad= True)
        self.p6_w1_relu = nn.ReLU()

        self.p5_w1 = nn.Parameter(torch.ones(2, dtype= torch.float32), requires_grad= True)
        self.p5_w1_relu = nn.ReLU()

        self.p4_w1 = nn.Parameter(torch.ones(2, dtype= torch.float32), requires_grad= True)
        self.p4_w1_relu = nn.ReLU()

        self.p3_w1 = nn.Parameter(torch.ones(2, dtype= torch.float32), requires_grad= True)
        self.p3_w1_relu = nn.ReLU()

        self.p4_w2 = nn.Parameter(torch.ones(3, dtype=torch.float32), requires_grad=True)
        self.p4_w2_relu = nn.ReLU()

        self.p5_w2 = nn.Parameter(torch.ones(3, dtype=torch.float32), requires_grad=True)
        self.p5_w2_relu = nn.ReLU()

        self.p6_w2 = nn.Parameter(torch.ones(3, dtype=torch.float32), requires_grad=True)
        self.p6_w2_relu = nn.ReLU()

        self.p7_w2 = nn.Parameter(torch.ones(2, dtype=torch.float32), requires_grad=True)
        self.p7_w2_relu = nn.ReLU()

        self.attention = attention

    def forward(self, inputs):

        p3_in, p4_in, p5_in, p6_in, p7_in = inputs

        # weight for p6_0 and p7_0 to p6_1
        p6_w1 = self.p6_w1_relu(self.p6_w1)
        weight = p6_w1 / (torch.sum(p6_w1, dim=0) + self.epsilon)

        p6_up = self.conv6_up(self.swish(weight[0] * p6_in + weight[1] * F.interpolate(p7_in,scale_factor=2 ,mode='bilinear',align_corners=True)))

        # weight for p5_0 and p6_1 to p5_1
        p5_w1 = self.p5_w1_relu(self.p5_w1)
        weight = p5_w1 / (torch.sum(p5_w1, dim=0) + self.epsilon)

        p5_up = self.conv5_up(self.swish(weight[0] * p5_in + weight[1] * F.interpolate(p6_up,scale_factor=2 ,mode='bilinear',align_corners=True)))

        #weight for p4_0 and p5_1 to p4_1
        p4_w1 = self.p4_w1_relu(self.p4_w1)
        weight = p4_w1 / (torch.sum(p4_w1, dim=0) + self.epsilon)

        p4_up = self.conv4_up(self.swish(weight[0] * p4_in + weight[1] * F.interpolate(p5_up,scale_factor=2 ,mode='bilinear',align_corners=True)))

        # weight for p3_0 and p4_1 to p3_2
        p3_w1 = self.p3_w1_relu(self.p3_w1)
        weight = p3_w1 / (torch.sum(p3_w1, dim=0) + self.epsilon)

        p3_out = self.conv3_up(self.swish(weight[0] * p3_in + weight[1] * F.interpolate(p4_up,scale_factor=2 ,mode='bilinear',align_corners=True)))

        #weights for p4_0 p4_1 and p3_2 to p4_2
        p4_w2 = self.p4_w2_relu(self.p4_w2)
        weight = p4_w2 / (torch.sum(p4_w2, dim= 0) + self.epsilon)

        p4_out = self.conv4_down(
            self.swish(weight[0] * p4_in + weight[1] * p4_up + weight[2] * self.p4_downsample(p3_out)))

        #weights for p5_0 p5_1 and p4_2 to p5_2
        p5_w2 = self.p5_w2_relu(self.p5_w2)

        weight = p5_w2 / (torch.sum(p5_w2 ,dim = 0) + self.epsilon)

        p5_out = self.conv5_down(
            self.swish(weight[0] * p5_in + weight[1] * p5_up + weight[2] * self.p5_downsample(p4_out)))

        #weights for p6_0 p6_1 and p5_2 for p6_2
        p6_w2 = self.p6_w2_relu(self.p6_w2)

        weight = p6_w2 / (torch.sum(p6_w2,dim = 0) + self.epsilon)

        p6_out = self.conv6_down(
            self.swish(weight[0] * p6_in + weight[1] * p6_up + weight[2] * self.p6_downsample(p5_out)))

        # weight for p7_0 and p6_2 to p7_2
        p7_w2 = self.p7_w2_relu(self.p7_w2)

        weight = p7_w2 / (torch.sum(p7_w2, dim=0) + self.epsilon)

        p7_out = self.conv7_down(self.swish(weight[0]*p7_in + weight[1] * self.p7_downsample(p6_out)))

        return p3_out, p4_out, p5_out, p6_out, p7_out