#!/usr/bin/python3.9

from multiprocessing import Pool, Manager
import pymysql
import time, os, subprocess
import json

def init(maxP = 4):
    processingNum = maxP
    path = [""] * processingNum

    for i in range(processingNum):
        out_r, out_w = os.pipe()
        out_r, out_w = os.fdopen(out_r, "r"), os.fdopen(out_w, "w")

        subprocess.run(["isolate", '--cg', "--box-id=" + str(i + 1), "--cleanup"])
        subprocess.run(["isolate", '--cg', "--box-id=" + str(i + 1), "--init"], stdout = out_w)
        path[i] = out_r.readline().replace("\n", "") + "/box/"
        out_w.close()

    return path

def worker(Sol, wid, path, queue, busy):

    def compile_code(file_name, language):
        compilers = {
            "C" : "timeout 30 gcc %s -o %s_ -Wall -lm -O2 -std=c11",
            "CPP"   : "timeout 30 g++ %s -o %s_ -O2 -Wall -lm -std=c++17",
            "JAVA"   : "timeout 30 javac %s",
            "PYTHON2": '''timeout 30 python2 -c "import py_compile; py_compile.compile('%s', '%s_')"''',
            "PYTHON3": '''timeout 30 python3 -c "import py_compile; py_compile.compile('%s', '%s_')"'''
            }
        if language != "JAVA":
            cmd = compilers[language] % (file_name, file_name)
        else:
            cmd = compilers[language] % (file_name)
        p = subprocess.Popen(cmd, shell=True, cwd="/var/www/judger", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out,err =  p.communicate()

        if p.returncode == 0:
            return (True, "")

        return (False,err.decode())

    run = {
        "C" : "./",
        "CPP"   : "./",
        "JAVA"   : "/usr/lib/jvm/java-11-openjdk-amd64/bin/java",
        "PYTHON2": "/usr/bin/python",
        "PYTHON3": "/usr/bin/python3.7"
        }
    queue.put((1, Sol, 0))

    try:
        file_type = {'C': '.c', 'CPP':'.cpp','PYTHON2':'', 'PYTHON3':'', 'JAVA':'.java'}

        problem = json.loads(open("/var/www/problems/" + str(Sol[2]) + ".json", "r").read())

        file_name = "P" + str(Sol[2])
        subprocess.run(["cp", "/var/www/judger/solutions/" + str(Sol[0]) , path + file_name + file_type[Sol[1]]])

        status = {'Subproblems': []}

        tmp1, tmp2 = compile_code(path + file_name + file_type[Sol[1]], Sol[1])

        if Sol[1] == "JAVA":
            file_name += ""
        else:
            file_name += file_type[Sol[1]] + "_"

        if not tmp1:
            status['status'] = 9
            status['Description'] = tmp2.replace(path, "/")
            result = open("/var/www/judger/results/" + str(Sol[0]) + ".json", "w")
            result.write(json.dumps(status))
            result.close()
            queue.put((9 ,Sol, 0))
            busy[wid] = False
            return
        system_err = True
    except Exception as e:
        status['status'] = 10
        status['Description'] = e.replace(path, "/")
        result = open("/var/www/judger/results/" + str(Sol[0]) + ".json", "w")
        result.write(json.dumps(status))
        result.close()
        queue.put((10, Sol, 0))
        busy[wid] = False
        return

    score = 0
    final_status = True

    time_cost = 0
    memory_cost = 0
    testcase_num = 0
    # print("Compiled.")

    for j in problem["Subproblems"]:
        status['Subproblems'].append({"Testcases":[]})
        status['Subproblems'][-1]['Debugger'] = j['Debugger']
        result_status = True
        for k in j['Testcases']:
            try:
                input_file = open(path + "input", 'w')
                input_file.write(k[0])
                input_file.close()
            except Exception as e:
                status['Subproblems'][-1]["Testcases"].append({'status': 10, 'Time': 0, 'Memory': 0, 'Input':k[0], 'Answer':  k[1], 'Output': '', 'Description': str(e) + "Fatal error when importing input_file."})
                result_status = False
                continue;
            try:
                if run[Sol[1]] == "./":
                    subprocess.run(["isolate","--box-id=" + str(1+wid),'--time=' + str(int(k[2]) / 1000), '--cg', '--cg-mem=' + str(int(k[3]) * 1024), '--mem=' + str(int(k[3]) * 1024), "--stdin=input", "--stderr=err" , "--stdout=output" , "--meta=" + path + "meta", "--run", run[Sol[1]] + file_name])

                elif Sol[1] == "JAVA":
                    subprocess.run(["isolate","--box-id=" + str(1+wid),'--time=' + str(int(k[2]) / 1000), '--cg', '--cg-mem=' + str(int(k[3]) * 1536), '-p', "--stdin=input", "--stderr=err"  , "--stdout=output" , "--meta=" + path + "meta", "--run", run[Sol[1]] , file_name])

                else:
                    subprocess.run(["isolate","--box-id=" + str(1+wid),'--time=' + str(int(k[2]) / 500), '--cg', '--cg-mem=' + str(int(k[3]) * 1024), '--mem=' + str(int(k[3]) * 1024), "--stderr=err", "--stdin=input", "--stdout=output" , "--meta=" + path + "meta", "--run", run[Sol[1]] ,   file_name])

                try:
                    output_file = open(path + "output", "r")
                    output = output_file.read()
                    output_file.close()
                    output = output.replace(path, "/")
                except Exception:
                    output = ""

                try:
                    err_file = open(path + "err", "r")
                    err = err_file.read()
                    err = err.replace(path, "/")
                    err_file.close()
                except Exception:
                    err = ""

                meta_file = open(path + "meta", "r")
                meta = meta_file.read()
                meta_file.close()
                meta_file = {}
                for m in meta.split("\n"):
                    if ":" in m:
                        meta_file[m.split(":")[0]] = m.split(":")[1]

                time = memory = 0
                status_code = 0

                if 'status' in meta_file or ('exitcode' in meta_file and meta_file['exitcode'] != "0"):
                    status_code = {"RE": 7, "TO": 4, "SG": 7, "XX": 10}[meta_file['status']]

                    if 'exitsig' in meta_file and meta_file['exitsig'] == "11":
                        err = "錯誤編號 11：不允許的記憶體調用。"
                    elif 'exitsig' in meta_file:
                        err = "錯誤編號 " + meta_file['exitsig']

                if status_code == 0:
                    time = int(float(meta_file['time']) * 1000)
                    memory = round(int(meta_file['max-rss'])  / 1024, 1)
                    if output == k[1]:
                        status_code = 2
                        time_cost += time
                        memory_cost += memory
                        testcase_num += 1
                    elif output.strip() == k[1].strip():
                        status_code = 2
                        time_cost += time
                        memory_cost += memory
                        testcase_num += 1
                    elif (output.replace(" ", "").replace("\n", "").replace("   ", "").replace("\r", "") == k[1].replace(" ", "").replace("\n", "").replace("   ", "").replace("\r", "")):
                        status_code = 3
                        time_cost += time
                        memory_cost += memory
                        testcase_num += 1
                    elif len(output) >= 2 ** 32 and len(output) >= len(k[1]):
                        output = output[2 ** 16:]
                        status_code = 8
                    else:
                        status_code = 6
                if status_code != 2:
                    result_status = False
                status['Subproblems'][-1]["Testcases"].append({'status': status_code, 'Time': time, 'Memory': memory, 'Input':k[0], 'Answer':  k[1], 'Output': output, 'Description': err})
                # print("Ok!", time, "s", memory, "k")

            except Exception as e:
                result_status = False
                status['Subproblems'][-1]["Testcases"].append({'status': 10, 'Time': 0, 'Memory': 0, 'Input':k[0], 'Answer':  k[1], 'Output': '', 'Description': str(e) + "Fatal error when running."})

        status['Subproblems'][-1]['Score'] = j['Score']

        if result_status:
            score += j['Score']
            status['Subproblems'][-1]['GetScore'] = j['Score']
        else:
            status['Subproblems'][-1]['GetScore'] = 0
            result_status = True
            final_status = False

    status['status'] = 2 if final_status else 11;
    status['score'] = score
    status['time'] = round(time_cost / testcase_num, 1) if testcase_num != 0 else 0
    status['memory'] = round(memory_cost / testcase_num, 1) if testcase_num != 0 else 0

    # print("?", status)
    queue.put((status['status'], Sol, score, status))

#     result = open("/var/www/judger/results/" + str(Sol[0]) + ".json", "w")
#     result.write(json.dumps(status))
#     result.close()
    subprocess.run(['rm', '-r', path])
    subprocess.run(['mkdir', path])
    busy[wid] = False


import openai

from .base import LLM

class OpenAi(LLM):
    name = 'openai'

    def __init__(self, cfg):
        super().__init__(cfg)

        self.model = self.cfg.get('model', '')
        self.api_key = self.cfg.get('api_key', '')
        self.api_base = self.cfg.get('api_base', '')

    def generate(self, prompt):
        messages = [{'role': 'user', 'content': prompt}]

        response = openai.ChatCompletion.create(
            model=self.model,
            api_key=self.api_key,
            api_base=self.api_base,
            messages=messages,
            stream=False)
        completions = []
        if response and 'choices' in response:
            for choice in response['choices']:
                if 'message' in choice:
                    completions.append(choice['message']['content'])
        response = ''.join(completions)

        # truncate response
        idx = response.find('<|endofthink|>')
        if idx != -1:
            response = response[:idx + len('<|endofthink|>')]
        return response


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 17:20:30 2021

@author: hmc
"""

import os
import base64
import json
import numpy as np
from tqdm import tqdm
from pycocotools.coco import COCO as _COCO
import datetime
from glob import glob
import cv2
from utils import label_list

with open("./labelme_sample.json", "r+") as f:
    data = json.load(f)
f.close()

sample = data["shapes"]

def area_of_polygon(polygon):
    polygon = np.array(polygon).astype(int)
    return cv2.contourArea(polygon)

def find_all_img_anns(coco):

    img_id_list = []
    ann_list = []

    for img_info in coco['images']:
        img_id_list.append(img_info['id'])
        ann_list.append([])

    print("START LOADING annotation data")

    for ann in tqdm(coco['annotations']):
        index = img_id_list.index(ann['image_id'])
        ann_list[index].append(ann)

    return coco['images'], ann_list

class COCO():
    def __init__(self, img_dir = None, ann_path = None, list_path = None):
        """
        Arguments Description
        Label_list -> coco category look-up table (dictionary format)

        COCO FORMAT STRUCTURE
        info
         - description : What data ?
         - url : where do you get this data ?
         - version : The version of annotation data
         - year : The year of generating annotation data
         - contributor : contributor's name
         - data_created : date
        images (list)
         - license : I don't know what it means exactly.
         - file_name : image filename
         - coco_url : MSCOCO TEAM'S Website. (Indicating an image on the website)
         - height : The height of an image
         - width : The width of an image
         - flickr_url : COCO data is generated by using flickr app.
         So, in here, the url of flickr exists.
         - id : image id. it is unique.
        licenses
         - url : indicate an institute's url having copyright of this data.
         - id : Maybe... institute's id ?
         - name : The institute's name
        annotations (list)
         when iscrowd : 1
         - segmentation
           - counts : uncompressed RLE format annotation data
           - size : uncompressed RLE format annotation data
           Please check https://github.com/cocodataset/cocoapi/issues/135
         when iscrowd : 0
         - segmentation
           - N-dimensional polygon's coordinates like x_1, y_1 ... x_N, y_N
         - area : Region of the segmentation polygon.
         - iscrowd : crowd target or not.
         - image_id : literally same
         - bbox : literally same
         - category_id : literally same
         - id : ??
        categories (list)
         - supercategory : High level concept category
         - id : Category number
         - category : Concrete category
         example, sup_cat : Furniture
                  cat : Chair
        """

        self.img_dir = img_dir
        self.COCO = _COCO(ann_path)
        self.image_ids = self.COCO.getImgIds()
        self._list = label_list(list_path = list_path)

    def load_image_info(self, img_idx):
        """
        image_info is dictionary having following structure

        {'license': 3,
         'file_name': 'COCO_val2014_000000391895.jpg',
         'coco_url': 'http://images.cocodataset.org/val2014/COCO_val2014_000000391895.jpg',
         'height': 360,
         'width': 640,
         'date_captured': '2013-11-14 11:18:45',
         'flickr_url': 'http://farm9.staticflickr.com/8186/8119368305_4e622c8349_z.jpg',
         'id': 391895
         }

        """
        image_info = self.COCO.loadImgs(self.image_ids[img_idx])[0]

        return image_info

    def load_annotation(self, image_index: int, encode_img: bool):

        image_info = self.load_image_info(img_idx=image_index)
        annotations_ids = self.COCO.getAnnIds(imgIds=self.image_ids[image_index], iscrowd=False)
        ann_data = self.coco.loadAnns(annotations_ids)
        # Partial annotation data based on an image id
        shapes = []

        for item_id, item in enumerate(ann_data):
            # bbox : x_min, y_min, width, height
            x_min, y_min, width, height = item['bbox']
            tmp_shape = {"label": self._list.cat_mapping(True, cat_id=str(item['category_id'])),
                         "points": [[x_min, y_min],[x_min+width, y_min + height]],
                         "group_id": None,
                         "shape_type": "rectangle",
                         "flags": {}
                         }

            shapes.append(tmp_shape)

        LABELME_FORMAT = {"version":"4.5.6", # If labelme is updated, you should change this value
                  "flags":{}, # You can use this value space customly.
                  "shapes":shapes, # Annotation items are in here
                  "imagePath":image_info['file_name'], # Image filename
                  "imageData":None, # Base64 encoding data
                  "imageHeight":image_info['height'],
                  "imageWidth":image_info['width']
                  }

        if encode_img == True:
            img = open(os.path.join(self.img_dir, image_info['file_name']), 'rb').read()
            LABELME_FORMAT["imageData"] = base64.b64encode(img).decode("utf-8")

        return LABELME_FORMAT

    def generate(self, img_dir, label_dir, output_path):
        VALID_IMAGE_FORMAT = ['jpg', 'png', 'jpeg', 'tiff']
        img_list = []
        ann_list = glob(os.path.join(label_dir, '*.json'))
        amount_of_ann = len(ann_list)

        for form in VALID_IMAGE_FORMAT:
            img_list += [glob(os.path.join(img_dir, "*.{}".format(form)))]

        if len(img_list) == 0:
            raise Exception("There is no valid images. Please check the image folder")

        if len(ann_list) == 0:
            raise Exception("There is no annotation files. Please check the annotation folder")

        now = datetime.datetime.now()

        data = dict(
            info=dict(
                description = "What kind of dataset?",
                version="v1.0",
                year=now.year,
                contributor="LEE KANG IL, AIRLAB",
                date_created=now.strftime("%Y-%m-%d %H:%M:%S.%f")
                ),
            images=[],
            annotations=[],
            categories = self._list.COCO_LIKE_MAP
            )

        for image_id, label_path in enumerate(ann_list):
            with open(os.path.join(label_dir, label_path), 'r+') as f:
                label_data = json.load(f)
            f.close()

            data["images"].append(
                dict(
                    file_name = label_data["imagePath"],
                    height = label_data["imageHeight"],
                    width = label_data["imageWidth"],
                    id = image_id,
                    )
                )

            for label_id in range(len(label_data["shapes"])):
                label_data[label_id]['label']
                if label_data[label_id]['shape_type'] == 'rectangle':
                    (x_min, y_min), (x_max, y_max) = label_data[label_id]['points']
                    bbox = [x_min, y_min, x_max-x_min, y_max-y_min]
                    area = bbox[2] * bbox[3]

                elif label_data[label_id]['shape_type'] == 'polygon':
                    polygon_pts = label_data[label_id]['points']
                    area = area_of_polygon(polygon_pts)
                    bbox = polygon_pts

                data["annotations"].append(
                    dict(
                        segmentation = [],
                        area = area,
                        iscrowd = 0,
                        image_id = image_id,
                        bbox = bbox, # x_min, y_min, w, h
                        category_id = self._list.cat_mapping(False,
                                                             cat_name = label_data[label_id]['label']),
                        id = str(image_id).zfill(len(str(amount_of_ann))) + str(label_id).zfill(3)
                        ))
                """
                If you don't want to set specific super cat. and etc, please set sup cat as None
                and the others are properly dealt.
                """

        with open(output_path, 'w') as out_file:
            json.dump(data, out_file, indent=4)


from __future__ import print_function

from os import path
import sys

from setuptools import setup

packages = [
    'paramsurvey_tooling',
]

# remember: keep requires synchronized with requirements.txt
requires = ['paramsurvey[ray]', 'psutil']

test_requirements = ['pytest', 'pytest-cov', 'coveralls', 'pyfakefs']

package_requirements = ['twine', 'setuptools', 'setuptools-scm[toml]']

extras_require = {
    'test': test_requirements,
    'package': package_requirements,
}

# if somehow we are running under python 2, which shouldn't happen,
# print a useful diagnostic instead of crashing on open(encoding=)

if sys.version_info[0] < 3:
    print('Somehow we are running under Python 2, which is not supported.')
    print('Python sys.executable:\n')
    print(sys.executable)
    exit(1)

this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
    description = f.read()

setup(
    name='paramsurvey_tooling',
    description='A toolkit to make paramsurvey easy to use on clusters and cloud',
    use_scm_version=True,
    long_description=description,
    long_description_content_type='text/markdown',
    author='Greg Lindahl and others',
    author_email='lindahl@pbm.com',
    url='https://github.com/wumpus/paramsurvey-tooling',
    packages=packages,
    python_requires=">=3.6.*",
    extras_require=extras_require,
    install_requires=requires,
    entry_points='''
        [console_scripts]
        pstool = paramsurvey_tooling.cli:main
    ''',
    license='Apache 2.0',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Operating System :: POSIX :: Linux',
        'Environment :: MacOS X',
        'Intended Audience :: Information Technology',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python',
        #'Programming Language :: Python :: 3.5',  # setuptools-scm problem
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Python :: 3.10',
        'Programming Language :: Python :: 3 :: Only',
    ],
)


import numpy as np
from particle.base import Particle

class SuperEllipsoid(Particle):
    def __init__(self, a, b, c, p):
        super().__init__()
        self.dim = 3

        # semi-axis length (a: b: c) and shape parameter (by default p1=p2=p)
        self.a = a
        self.b = b
        self.c = c
        self.p = p

        self.rot_mat = np.diag(np.ones(self.dim))

    @property
    def semi_axis(self):
        return np.array([self.a, self.b, self.c])

    @property
    def volume(self):
        return 4./3.*np.pi*np.cumprod(self.semi_axis)[2]

    @property
    def inscribed_d(self):
        """
        diameter of the outscribed sphere
        """
        return np.min(self.semi_axis)

    @property
    def outscribed_d(self):
        """
        diameter of the outscribed sphere
        """
        # Hölder Inequality
        if (self.p > 1.):
            k = self.p/(self.p-1.)
            temp = self.a**(2.*k) + self.b**(2.*k) + self.c**(2.*k)
            return temp**(1./k)
        else: return np.max(self.semi_axis)

    def shapeFun(self, r_l: np.array):
        """ Superellipsoid function """
        y = 0.
        for i in range(self.dim):
            y += np.fabs(r_l[i] / self.semi_axis[i])**(2.*self.p)
        return y

    def shapeFund(self, r_l: np.array):
        """ The first-order derivative of superellipsoid function"""
        dx = np.zeros(self.dim)
        for i in range(self.dim):
            dx[i] = 2.*self.p/self.semi_axis[i]*np.fabs(r_l[i]/self.semi_axis[i])**(2.*self.p-1.)*np.sign(r_l[i])
        return dx

    def support_func(self, u: np.array):
        """
        Particle's support function: h(u) = max(K) u . x

        located in the origin, without rotation by default.
        """

        r_u = np.linalg.norm(u)
        # dxt = k*Ru/|u|
        dp = 2.*self.p - 1.

        normal = u / r_u
        r_c = np.zeros(self.dim)
        for i in range(self.dim):
            r_c[i] = self.semi_axis[i] * np.fabs(normal[i]*self.semi_axis[i]/2./self.p)**(1./dp) * np.sign(u[i])

        k = (1. / self.shapeFun(r_c))**(dp/2./self.p)
        r_c *= k**(1./dp)

        return np.dot(r_c, u)

    def support_funcs(self, u: np.array):
        """
        The support function of a specific particle:

        Particle's centroid & rotation matrix must be taken into consideration, i.e.,
        h_i(u) = h(R^T_i*u) + u*r_i
        """
        y = self.support_func(np.matmul(self.rot_mat.T, u.T).T)
        y += np.dot(u, self.centroid)
        return y

    def check(self, vector):

        r_v = np.linalg.norm(vector)

        # https://baike.baidu.com/item/球坐标系/8315363
        temp = np.sqrt(vector[0]**2. + vector[1]**2.)
        sin_cita = temp / r_v
        cos_cita = vector[2] / r_v

        if (temp == 0.):
            sin_fai, cos_fai = 1., 0.
        else:
            sin_fai, cos_fai = vector[1] / temp, vector[0] / temp

        point = np.array([sin_cita*cos_fai, sin_cita*sin_fai, cos_cita])
        r = (1. / self.shapeFun(point))**(0.5/self.p)
        point *= r

        u = self.shapeFund(point)

        tr = np.dot(point, u)

        return (tr-self.support_func(u))


from typing import List
class Solution:
    def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
        answer = []
        sumSoFar = sum([num for num in nums if num%2==0])
        for val, i in queries:

            if nums[i]%2 == 0:

                # integer was even till now.
                # substract the value from the total sum.
                # (otherwise the value would be added twice)
                sumSoFar -= nums[i]

            # add new value val to the value at index i.
            nums[i] += val

            if nums[i]%2 == 0:
                # if new value is even, add to total sum.
                sumSoFar += nums[i]

            # append total sum of iteration to answer list.
            answer.append(sumSoFar)
        return answer

nums = [1,2,3,4]
queries = [[1,0],[-3,1],[-4,0],[2,3]]
x = Solution()
x.sumEvenAfterQueries(nums, queries)


import numpy as np
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, and_

from flask import Flask, jsonify

engine = create_engine("sqlite:///hawaii.sqlite")

Base=automap_base()
Base.prepare(engine, reflect=True)

Measurements=Base.classes.measurement
Station=Base.classes.station

app=Flask(__name__)

@app.route("/")
def welcome():

    return(
        f"List all available API routes:
"
        f"/api/v1.0/precipitation
"
        f"/api/v1.0/stations
"
        f"/api/v1.0/tobs
"
        f"/api/v1.0/<start>
"
        f"/api/v1.0/<start>/<end>"
    )

@app.route("/api/v1.0/precipitation")
def Precipitation():
    session=Session(engine)
    results=session.query(Measurements.date, Measurements.prcp).\
                order_by(Measurements.date).all()
    prcp_list=[]
    for date, prcp in results:
        new_dict = {}
        new_dict[date] = prcp
        prcp_list.append(new_dict)

    session.close()

    return jsonify(prcp_list)

@app.route("/api/v1.0/stations")
def Stations():
    session=Session(engine)
    stations={}
    results=session.query(Station.station, Station.name).all()
    for s,name in results:
        stations[s]=name
    session.close()
    return jsonify(stations)

@app.route("/api/v1.0/tobs")
def tobs():
    session=Session(engine)

    last_date=session.query(Measurements.date).order_by(Measurements.date.desc()).first()

    last_year_date=(dt.datetime.strptime(last_date[0],'%Y-%m-%d') \
                    - dt.timedelta(days=365)).strftime('%Y-%m-%d')

    results =   session.query(Measurements.date, Measurements.tobs).\
                filter(and_(Measurements.date >=last_year_date, Measurements.station== "USC00519281")).\
                order_by(Measurements.date).all()

    tobs_date_list = []

    for date, tobs in results:
        new_dict = {}
        new_dict[date] = tobs
        tobs_date_list.append(new_dict)

    session.close()

    return jsonify(tobs_date_list)

@app.route("/api/v1.0/<start>")
def temp_range_start(start):
    session=Session(engine)
    return_list=[]
    results=session.query(Measurements.date, func.min(Measurements.tobs),\
                          func.avg(Measurements.tobs),\
                          func.max(Measurements.tobs)).\
                    filter(Measurements.date >=start).\
                    group_by(Measurements.date).all()
    for date, min,avg,max in results:
        new_dict={}
        new_dict["Date"]=date
        new_dict["TMIN"]=min
        new_dict["TAVG"]=avg
        new_dict["TMAX"]=max
        return_list.append(new_dict)

    session.close()

    return jsonify(return_list)

@app.route("/api/v1.0/<start>/<end>")
def temp_range_start_end(start,end):
    session=Session(engine)

    return_list=[]

    results=session.query(Measurements.date, func.min(Measurements.tobs),\
                          func.avg(Measurements.tobs),\
                          func.max(Measurements.tobs)).\
                    filter(and_(Measurements.date >=start, Measurements.date<= end)).\
                    group_by(Measurements.date).all()
    for date, min,avg,max in results:
        new_dict={}
        new_dict["Date"]=date
        new_dict["TMIN"]=min
        new_dict["TAVG"]=avg
        new_dict["TMAX"]=max
        return_list.append(new_dict)

    session.close()

    return jsonify(return_list)

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


from scipy.optimize import linprog

def get_objective(line):
  arr = line.split()
  res = []
  for i in range(0, len(arr), 2):
    if arr[i][0]=='+' or arr[i][0]=='-':
      num = float(arr[i][1:])
    else:
      num = float(arr[i])
    if arr[i][0]=='-':
      num = -num
    res.append(num)
  return res

def get_less_than_inequality(line, n_vars):
  arr = line.split()
  res = []
  prev_var = -1
  for i in range(0, len(arr)-2, 2):
    cur_var = int(arr[i+1].split('_')[1])
    for j in range(cur_var-prev_var-1):
      res.append(0)
    if arr[i][0]=='+' or arr[i][0]=='-':
      num = float(arr[i][1:])
    else:
      num = float(arr[i])
    if arr[i][0]=='-':
      num = -num
    res.append(num)
    prev_var = cur_var
  for j in range(n_vars-len(res)):
    res.append(0)

  i = len(arr)-1
  if arr[i][0]=='+' or arr[i][0]=='-':
    num = float(arr[i][1:])
  else:
    num = float(arr[i])
  if arr[i][0]=='-':
    num = -num

  return res, num

def read_model(file_name):
  print('Reading model.... All equations must be in less than equal to form')
  c = []
  A = []
  b = []
  f = open(file_name, 'r')
  line = f.readline().strip()
  maximize = False
  while line!='':
    #print(line)
    while line[0]=='#':
      line = f.readline().strip()
    if line=='maximize:' or line=='minimize:':
      type='objective'
      if line=='maximize:':
        maximize = True
    elif line=='subject to:':
      type='constraints'
    else:
      if type=='objective':
        c = get_objective(line)
        if maximize:
          c = convert_min_to_max(c)
      elif type=='constraints':
        coeff, cons = get_less_than_inequality(line, len(c))
        A.append(coeff)
        b.append(cons)
    line = f.readline().strip()
  f.close()
  return c, A, b

def convert_min_to_max(c):
  c = [-x for x in c]
  return c

def run_lin_prog(file_name):
  print('Running linear program')
  c, A, b = read_model(file_name)
  bounds = []
  for i in range(len(c)):
    bounds.append((0, None))
  res = linprog(c, A_ub=A, b_ub=b, bounds=bounds)
  print(res)

#run_lin_prog('simple.txt')
run_lin_prog('farmer.txt')


# OrderedDictionary

from collections import OrderedDict
class LRUCache(OrderedDict):

    def __init__(self, capacity: int):
        """
        :type capacity: int
        """

        self.capacity = capacity

    def get(self, key: int):
        """
        :type key:int
        :rtype: int

        """
        if key not in self:
            return -1
        self.move_to_end(key)
        return self[key]

    def put(self, key: int, value: int):
        """
        :type key:int
        :type value:int
        :rtype:void
        """

        if key in self:
            self.move_to_end(key)
        self[key] = value
        if len(self) > self.capactiy:
            self.popitem(last = False)

# TC:O(1)
# SC:O(capacity)
# Link: https://leetcode.com/problems/lru-cache/


import json
import os
from sqlalchemy import Column, Integer, Float, DateTime, create_engine, MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

metadata = MetaData()

class Readings(Base):
    __tablename__ = 'readings'

    id = Column(Integer, primary_key=True)
    date_time = Column(DateTime)
    soil_temperature_1 = Column(Float)
    soil_temperature_2 = Column(Float)
    soil_moisture_1 = Column(Float)
    soil_temperature_2 = Column(Float)
    ambient_temperature = Column(Float)
    ambient_humidity = Column(Float)
    ambient_pressure = Column(Float)

    def __repr__(self):
        return "f{self.date_time}"

DBSession = sessionmaker(bind=engine)
session = DBSession()
Base.metadata.create_all(engine)


import matplotlib.pyplot as plt
from random import randint, uniform
import os
#os.system('clear')
def hum(n,x,y):
    a = []
    b = []
    c = []
    s = 0
    for i in range(n):
        val = float(input("guess:"))
        valrand = randint(x,y)
        print("machine:",valrand,"homme:",val)
        if valrand == val:
            print("NICE")
        else:
            print("failed")
        if valrand == val:
            s +=1
        a.append(i)
        title = "humaine score is "+str(s)+"/"+str(i)
        b.append(val)
        c.append(valrand)
        want = int(input("if you wanna rep graphique no:[0] yes:[1]>>:"))
        if want == 1:
            plt.plot(a,b,label="guess")
            plt.plot(a,c,label="aleatoire")
            plt.title(title)
            plt.legend()
            plt.show()
        else:
            continue
    plt.plot(a,b,label="guess")
    plt.plot(a,c,label="aleatoire")
    title = "humaine score is "+str(s)+"/"+str(n)
    plt.legend()
    plt.title(title)
    plt.show()
    hum(n)
def mach(n,x,y):
    a = []
    b = []
    c = []
    s = 0
    for i in range(n):
        val1 = randint(x,y)
        val2 = randint(x,y)
        print("machine1:",val1,"machine2:",val2)
        if val1 == val2:
            s +=1
        a.append(i)
        title = "humaine score is "+str(s)+"/"+str(i)
        b.append(val1)
        c.append(val2)
    plt.plot(a,b,label="machine1")
    plt.plot(a,c,label="macine2")
    title = "machine1 score is "+str(s)+"/"+str(n)
    plt.legend()
    plt.title(title)
    plt.show()
#mach(10,0,10)
#hum(10,0,10)


import paths
import numpy as np
import ccdproc as ccdp
import figure_utils as utils
import matplotlib.pyplot as plt

DIM = 1030
raw_bias_path = paths.data / "raw_photometry" / "CALIB" / "BIAS"
files = [
    "EFOSC.2000-12-30T05:17:49.057.fits",
    "EFOSC.2000-12-29T04:39:50.783.fits",
    "EFOSC.2000-12-28T22:11:19.687.fits",
    "EFOSC.2000-12-30T04:19:55.000.fits",
]

bias_collection = ccdp.ImageFileCollection(location=raw_bias_path, filenames=files)

biases = list(bias_collection.ccds(ccd_kwargs={"unit": "adu"}))

fig, ax = plt.subplots(2, 2, figsize=(10, 10))
ax = ax.flatten()
for i, bias in enumerate(biases):
    print(f"Mean bias {i + 1}: {np.mean(bias.data)}")
    utils.show_image(bias, fig=fig, ax=ax[i], cbar_label="Signal [ADU]")
    ax[i].set_title(f"Bias {i + 1}", fontsize=16)

fig.suptitle("Randomly Selected Bias Frames", fontsize=20)
fig.tight_layout()
fig.savefig(paths.figures / "random_bias_frames.pdf")


from PIL import Image

from django.template import Library
from django.conf import settings
register = Library()

@register.filter
def pdf_and_docx_to_png(file_path):
    """Converts a PDF or DOCX file to a PNG image.

    Args:
        file_path: The path to the PDF or DOCX file.

    Returns:
        A PIL Image object.
    """
    if file_path.endswith('.pdf'):
        image = Image.open(settings.BASE_DIR / file_path)
        image = image.convert('RGB')
        return image
    elif file_path.endswith('.docx'):
        from docx import Document
        document = Document(file_path)
        image = Image.open(document.part.blob)
        image = image.convert('RGB')
        return image
    else:
        raise Exception('Unsupported file type.')


import traceback

from django.core.validators import RegexValidator
from django.forms import MultiValueField
from phone_form_field.country_choices import choice_list
from django.forms.widgets import Select
from django.forms.fields import ChoiceField
from django.forms.fields import CharField
from django.forms.widgets import TextInput
from django.forms.widgets import MultiWidget
from django.core.exceptions import ValidationError
from django.forms import Form
from phonenumbers import phonenumber
import phonenumbers
from phonenumbers.phonenumberutil import NumberParseException

class CountryCodeWidget(Select):
    initial = None
    """Choice widget that sets the first choice to the country code given in the initial variable.
    The initial variable must be a tuple of length equal to two. The first index of the tuple will be the value if the option
    and the second index will be the text content of the drop-down option.  """
    def __init__(self, initial=None, attrs=None):

        self.choices = choice_list.copy()
        if initial is not None:
            if not type(initial) is tuple:
                raise TypeError("Initial Value for Country Code Widget must be a tuple")
            else:
                self.choices[0]=initial
        super().__init__(choices=self.choices, attrs=attrs)

class PhoneField(MultiValueField):
    enter_number_message = "Enter a valid phone number"
    enter_national_number = "Enter a national phone number"
    def __init__(self, initial=None, attrs=None, **kwargs):
        """initial must be passed in the subclass of PhoneForm's constructor"""
        widget = PhoneMultiWidget(attrs=attrs, initial=initial)
        error_messages= {"invalid": "Enter a valid phone number"}
        fields = (
            ChoiceField(
                choices=choice_list
            ),
            CharField(
                error_messages={'incomplete': self.enter_national_number},
            ),

        )
        super().__init__(
            fields=fields, require_all_fields=True, widget=widget, error_messages=error_messages, **kwargs
        )

    def compress(self, data_list):
        """Combines the two field's values into a single value. This is called after each field's values are first cleaned and then combined into a list"""
        try:
            number = phonenumbers.parse(data_list[0] + data_list[1], "US")
        except NumberParseException:
            raise ValidationError(self.enter_number_message)
        if not phonenumbers.is_valid_number(number):
            raise ValidationError(self.enter_number_message)
        else:
            return "+" + str(number.country_code) + str(number.national_number)

class PhoneMultiWidget(MultiWidget):
    def __init__(self, attrs=None, initial=None):
        if initial is not None:
            self.initial = self.decompress(initial)
            if attrs:
                textattrs = attrs.copy()
                textattrs["value"] = self.initial[1]
            else:
                textattrs= {}
                textattrs["value"] = self.initial[1]
            widgets = (CountryCodeWidget(initial=self.initial[0], attrs=attrs), TextInput(attrs=textattrs))
        else:
            widgets = (CountryCodeWidget(attrs=attrs), TextInput(attrs=attrs))
        super().__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            try:
                value = phonenumbers.parse(value, "US")
                if value.country_code is not None:
                    return [("+" + str(value.country_code), "Country Code +" + str(value.country_code)), str(value.national_number)]
            except NumberParseException as e:
                print("Could not parse phone number")

        return [None, ""]

class PhoneForm(Form):
    """For the initial value of the Phone Field to work, your form must extend this form and pass the initial phone_number in the constructor
    in the format of a string, with or without the country code. """
    def __init__(self, *args, phone_number=None, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields["phone"] = PhoneField(label="Phone Number", initial=phone_number)


#!/bin/env python
"""
    Initialize the logging environment.
"""

#
# A simple logger for the name server
#
import sys
import logging
import logConfig

"""
 Look in the current directory for .logcollectorrc .
 If not there, look in  $HOME/.logcollectorrc
 Any user flags will override config file settings.

 The config parameters will look similar to:
    {
        append: True,    # Append logs to existing file.
                         # Creates a file if the filed does not exist.
        log_file:"/home/me/simple/logs.log",  # Name of log file.
        noisy:  False,   # Echo all collected logs to console.
                         # Used in debugging.
        port:   5570,    # Port to listen for messages.
    }

"""
DEFAULT_COLLECTOR_CONFIG_FILE = '.logcollectorrc'

ALREADY_INITED = False  # Allow multiple calls without penalty

def loggerInit():
    """
    Initialize the logger, but only once.
    """
    global ALREADY_INITED

    if ALREADY_INITED:
        return

    # Embed the app name in the log
    logging.basicConfig(filename=logConfig.LOG_FILENAME,
                        format='%(asctime)s.%(msecs)03d\t%(levelname)s' +
                        '\t%(message)s',
                        datefmt='%Y-%m-%dT%H:%M:%S',
                        level=logging.NOTSET)   # NOTSET means log EVERYTHING!
    if logConfig.TESTING:
        # If testing, echo logs to stdout as well as logfile.
        log = logging.getLogger('')
        log.addHandler(logging.StreamHandler(sys.stdout))
        logging.info('Logging Started')
    ALREADY_INITED = True

if __name__ == '__main__':
    logConfig.TESTING = True
    loggerInit()
    # Call again to make sure the init flag works.
    loggerInit()


import json
import playsound
from datetime import date
import os
import speech_recognition as sr
import random
import time
import datetime
import json
from main.data.speech.RealtimeSpeech import SpeechSynthesis

class Initialisation:
    def __init__(self):

        # Define A Path for Json File Containing DB Data for User
        self.path = './user.json'
        # existence(variable -> checking for existence of path)
        self.existence = os.path.exists(self.path)

        # check_existence
        self.check_existence()

    def check_existence(self):
        # while existence
        if self.existence:
            self.runMain()

        # while existence not true
        else:
            self.welcomeUser()
            self.yourName()

    """ Task Execution """

    def speakData(self, data):
        try:
            synthesis = SpeechSynthesis()
            synthesis.synthesize(data)

        except:
            print(data)

    def listen_Data(self):
        try:
            # use the microphone as source for input.
            with sr.Microphone() as source:

                # Define the Recognizer
                r = sr.Recognizer()

                # the surrounding noise level
                r.adjust_for_ambient_noise(source, duration=0.2)

                # Use Pause Threshold
                r.pause_threshold = 1

                print("Listening...")
                audio = r.listen(source)

                # Using google to recognize audio
                inputtext = r.recognize_google(audio)

                # Lower input text
                inputtext = inputtext.lower()

                # Replace empty spaces
                inputtext = inputtext.replace(" ", "")

                return inputtext

        except Exception as e:
            # print(e)
            # Say that again will be printed in case of improper voice
            print("Please Say that Again...")
            return self.listen_Data()

        except sr.UnknownValueError:
            print("Google Speech Recognition could not understand audio")

        except sr.RequestError as e:
            print(
                "Could not request results from Google Speech Recognition service{0}".format(e))

    def db_save(self, name, weather_api_key, compute_engine_api_key):

        dateCreated = str(datetime.date.today().day) + "/" + \
            str(datetime.date.today().month) + \
            "/" + str(datetime.date.today().year)
        jsonData = {"name": name, "dateCreated": dateCreated,
                    "wolframalpha_api": compute_engine_api_key}

        # Dump Data
        jsonString = json.dumps(jsonData)

        # Open Json File
        jsonFile = open("user.json", "w")

        # Write data
        jsonFile.write(jsonString)
        jsonFile.close()
        jsonData = {"weather_api": weather_api_key}
        jsonString = json.dumps(jsonData)

        # Open Json File
        jsonFile = open("core/packages/Weather/user.json", "w")

        # Write data
        jsonFile.write(jsonString)
        jsonFile.close()

    def startDocumentation(self, inputtext):
        try:
            # Begin the app for marketing/explaining purposes
            self.speakData(
                f"{inputtext}, Follow through the documentation, and once you are done, just close the window and I'll be ready.")
            # Change Active Directory
            os.chdir("app")
            # if node_modules exists
            if os.path.isdir("node_modules"):
                # Start the app
                os.system("npm start")

            self.speakData(
                "Installing Desktop App Packages. Executing Data. Predicting Output. Loading files... ")
            self.speakData(
                "This will take some time depending on your internet connection. Please wait. ")
            # Install node_modules/electron packages
            os.system("npm install --save-dev electron")
            # Start the app
            self.speakData("And Done. Starting the app. ")
            os.system("npm start")

        except Exception as AppStartBundleException:
            self.speakData(AppStartBundleException)
            self.speakData(
                "Sorry. I have encountered an issue. Please try again later. For now you can manually try installing packages. Follow these instructions. ")
            self.speakData("Open your terminal.")
            self.speakData("Go to the directory where you installed Seven.")
            self.speakData("Change Directory to app by typing cd app")
            self.speakData("Type npm install --save-dev electron")
            self.speakData("Try again")

    """ Proccess Execution """

    def runMain(self):
        # json_file(variable -> opening the file)
        with open(self.path) as json_file:

            # data(variable -> reading the file)
            data = json.load(json_file)

            # close json_file
            json_file.close()

            # cd main/python3 main.py (redirect to main)
            os.chdir("main")
            os.system("python3  main.py")

    def welcomeUser(self):
        # welcome_user(variable -> welcome user)
        # Introduce Seven
        response = random.choice(["A new user I see. Welcome. Welcome to Seven. Allow me to introduce myself. I am Seven, made by Rishabh Mishra, Sarthak Rawool, and Shubham Mishra. And about me well, I'm a damn brilliant guy! Here let me get you through setup",
                                  "Hey. I am Seven. Let me introduce myself, As you know me I am Seven. I was made by a few brilliant idiots Rishabh Mishra, Shubham Mishra, Sarthak Rawool. The Guys, eh? Anyways, let me get you through setup. ", "Here's looking at you Kid. I'm Seven. I was made by Rishabh Mishra, Shubham Mishra, and Sarthak Rawool, Ya. Let me get you through setup. "])
        self.speakData(response)

    def yourName(self):
        # your_name(variable -> your name)
        # Introduce your name

        self.speakData("What is your name? ")

        # your_name(variable -> your name)
        # Get your name

        self.your_name = self.listen_Data()

        if self.your_name:
            self.speakData("Is {} your name? ".format(self.your_name))

            self.your_name_confirm = self.listen_Data()
            if "yes" in self.your_name_confirm.lower() or "yeah" in self.your_name_confirm.lower():
                self.speakData("Okay. Let's get started. ")

            else:
                self.yourName()

        self.apprun = input(
            "Do you want to run the app locally too (Y/N) [NPM is required]: ")
        self.weather_input = input(
            "Please enter your weather api key (If you do not have one, Please make one at https://openweathermap.org/api): ")
        self.compute_engine_input = input(
            "Please enter your WolframAlpha API key (If you do not have one, Please make one at https://products.wolframalpha.com/api/): ")
        self.db_save(self.your_name, self.weather_input,
                     self.compute_engine_input)
        if self.apprun != "N":
            self.startDocumentation(self.your_name)
            print("Processing, it will take less than a minute...")
            os.system("python3  ../main/main.py")
        else:
            print("Processing, it will take less than a minute...")
            os.system("python3  ../main/main.py")

###############################
# Run Intialiasation Process
###############################
Initialisation = Initialisation()


import os,sys,argparse
# import fileinput,time
import glob
import re,bisect
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size']=14
import seaborn as sns
sns.set(font_scale=1.)
sns.set_style("whitegrid", {'axes.grid' : False})
import scipy
import scipy.optimize
sns.set_style("ticks")
matplotlib.rcParams["font.sans-serif"] = ["Arial"]
from matplotlib import gridspec

outdir = 'f1_CP_heatmap'
os.makedirs(outdir+os.sep+'_csv',exist_ok=True)

indirs = ['CP_TFBS_vs_TFMS','CP_TFBS_with_motif_vs_TFMS','CP_TFBS_without_motif_vs_TFMS']
group_info = {
'CP': {'data_median_fisher':
       ['log10-distance CP t-stats',
        'log10-distance CP pvalue Fisher-TF-Celltype-combined'],
       'data_fisher_fisher':
       ['log10-distance CP t-stats',
        'log10-distance CP pvalue Fisher-data-combined Fisher-TF-Celltype-combined'],
    },
'SE': {'data_median_fisher':
       ['fisher_exact_s',
        'fisher_exact_p Fisher-TF-Celltype-combined'],
       'data_fisher_fisher':
       ['fisher_exact_s',
        'fisher_exact_p Fisher-data-combined Fisher-TF-Celltype-combined'],
    }}

or_thre = {'CP':9,'SE':6}
label_name = {'CP':'log2 T-statistics','SE':'log2 Odds Ratio'}

index_cutoff = 18
celltype_cutoff = 6

for indir in indirs[:]:
    # outdir = 'f1_CP_heatmap'
    # os.makedirs(outdir,exist_ok=True)
    infile = '../f2_TFMS_TFBS_CP/{}/per_TF_per_Celltype_{}.csv'.format(indir,indir)
    df = pd.read_csv(infile,index_col = 0)
    # === data for CP and SE enrichment
    for or_key in group_info.keys():
        for fisher_P_key in group_info[or_key].keys():
            s_col = group_info[or_key][fisher_P_key][0]
            p_col = group_info[or_key][fisher_P_key][1]
            df_s = pd.DataFrame()
            df_p = pd.DataFrame()
            basename = '{}_{}_{}'.format(or_key,fisher_P_key,indir)
            # print(p_col,basename)
            for ii in df.index:
                factor = ii.split('_')[0]
                celltype = ii.split('_')[1]
                df_s.loc[factor,celltype] = df.loc[ii,s_col]
                df_p.loc[factor,celltype] = df.loc[ii,p_col]
            df_s.to_csv(outdir+os.sep+'_csv/{}_OR.csv'.format(basename))
            df_p.to_csv(outdir+os.sep+'_csv/{}_P.csv'.format(basename))

            # ==== select the TF/cell-type with sufficient data
            selected_index = df_s.notnull().sum(axis=1).sort_values(ascending=False).index[:index_cutoff][::-1]
            selected_col = df_s.notnull().sum(axis=0).sort_values(ascending=False).index[:celltype_cutoff]
            df_s = df_s.loc[selected_index,selected_col]
            df_s = np.log2(df_s)
            df_p = df_p.loc[selected_index,selected_col]
            df_p = df_p.replace(0,1e-299)

            # == plot the heatmap
            plt.figure(figsize=(4,7))
            width_ratios = [4,.0,0,.5]
            gs = gridspec.GridSpec(3,4,width_ratios=width_ratios,wspace=.15,hspace=.5)
            pal = plt.cm.bwr
            vmax = or_thre[or_key]
            vmin = -1*vmax
            norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
            color_map = matplotlib.cm.ScalarMappable(norm=norm, cmap=pal)
            scatter_scale = 1
            ax = plt.subplot(gs[:,0])
            for ii in np.arange(len(df_s.index)):
                for jj in np.arange(len(df_s.columns)):
                    odds_ratio = df_s.loc[df_s.index[ii],df_s.columns[jj]]
                    pvalue = df_p.loc[df_s.index[ii],df_s.columns[jj]]
                    if not np.isnan(odds_ratio):
                        color = color_map.to_rgba(odds_ratio)
                        size = -1*np.log10(pvalue)#;print(size)
                        ax.scatter(jj,ii,s = scatter_scale*size, color = color)
                        # ax.text(jj,ii,df_s.index[ii],fontsize=12)
                    else:
                        ax.scatter(jj,ii,marker = 'x',s = scatter_scale*30, color = 'k')

            ax.set_yticks(np.arange(len(df_s.index)))
            ax.set_yticklabels(df_s.index,fontsize=13)
            ax.set_xticks(np.arange(len(df_s.columns)))
            ax.set_xticklabels(df_s.columns,rotation=60,fontsize=13)
            ax.set_xlim([-.5,len(df_s.columns)-.5])
            ax.set_title('{}\n{}\n{}'.format(or_key,fisher_P_key,indir),fontsize=13,va='bottom')

            # color bar
            ax = plt.subplot(gs[0,3])
            cbar = matplotlib.colorbar.ColorbarBase(ax,cmap=pal,norm=norm,orientation='vertical')
            cbar.set_ticks([vmin,0,vmax])
            cbar.set_label(label_name[or_key],labelpad=-60,fontsize=12)
            # pvalue legend
            ax = plt.subplot(gs[1,3])
            ax.scatter(0,.15,s = -1*scatter_scale*np.log10(1e-10), color = 'k')
            ax.scatter(0,.5,s = -1*scatter_scale*np.log10(1e-50), color = 'k')
            ax.scatter(0,.9,s = -1*scatter_scale*np.log10(1e-100), color = 'k')
            ax.text(0,.0,'1e-10',ha='center')
            ax.text(0,.3,'1e-50',ha='center')
            ax.text(0,.67,'1e-100',ha='center')
            ax.set_xlim([-1,1])
            ax.set_ylim([.0,1.05])
            ax.set_title('P-value',ha='center',fontsize=13)
            ax.axis('off')

            # heatmap of AICAP
            # read TF AICAP
            # idrfile = '../f2_TF_motif_IDR_SE_mutation/data/13059_2021_2456_MOESM2_ESM.xlsx'
            # idrdf = pd.read_excel(idrfile,sheet_name='condition 2(1,6-HD-2)',index_col=0)
            # vmin=-2;vmax=2
            # ax = plt.subplot(gs[:,1])
            # plot_data = idrdf.loc[df_s.index[::-1],['AICAP']]
            # plot_data = np.log2(plot_data)
            # g = sns.heatmap(plot_data,cmap=plt.cm.PiYG,cbar=False\
            #                 ,vmax=vmax,vmin=vmin\
            #                 ,ax=ax\
            #                 ,xticklabels=True,yticklabels=False)
            # ax.set_xticklabels(['AICAP'],rotation=60)
            # # color bar
            # ax = plt.subplot(gs[2,3])
            # norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
            # cbar = matplotlib.colorbar.ColorbarBase(ax,cmap=plt.cm.PiYG,norm=norm,orientation='vertical')
            # # cbar.set_ticks([-1,0,2])
            # cbar.set_label('log2 AICAP',labelpad=-55,fontsize=13)

            plt.savefig('{}/{}.pdf'.format(outdir,basename),bbox_inches='tight',pad_inches=0.02,transparent=True)
            plt.show()
            plt.close()


from __future__ import print_function

import numpy as np
import pickle
import tensorflow as tf
import matplotlib.pyplot as plt

from dcgenerator import Generator
from dcdiscriminator import Discriminator

class DCGAN(object):
    def __init__(self, batch_size, in_shape, g_depths, d_depths, colorspace_dim=3,
            s_size=4, n_latent=100, eta=0.0002, beta1=0.5):
        self.batch_size = batch_size
        self.s_size = s_size
        self.n_latent = n_latent # Also known as z-dim
        self.in_shape = in_shape
        self.colorspace_dim = colorspace_dim

        # Input image placeholder
        self.x_placeholder = tf.placeholder(tf.float32, [None, in_shape[0],
            in_shape[1], colorspace_dim])
        # Latent probability distribution sample placeholder
        self.z_placeholder = tf.placeholder(tf.float32, [None, 1, 1, n_latent])

        # Generator, given sample from latent space
        self.x_hat = Generator(self.z_placeholder, g_depths,
                colorspace_dim=colorspace_dim, s_size=s_size, reuse=False,
                training=True).model[-1]
        # Discriminator for fake image
        self.y_hat = Discriminator(self.x_hat, d_depths, batch_size,
                colorspace_dim=colorspace_dim, reuse=False,
                training=True).model[-1]
        # Discriminator for real
        self.y = Discriminator(self.x_placeholder, d_depths, batch_size,
                colorspace_dim=colorspace_dim, reuse=True,
                training=True).model[-1]

        # Loss tensors
        self.d_loss = Discriminator.loss(self.y, self.y_hat)
        self.g_loss = Generator.loss(self.y_hat)

        # Variable list
        self.gen_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,
                scope="generator")
        self.dis_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,
                scope="discriminator")

        print("Generator variables:")
        print(self.gen_vars)
        print("Discriminator variables:")
        print(self.dis_vars)

        # Optimizers
        self.d_optimizer = tf.train.AdamOptimizer(eta,
                beta1=beta1).minimize(self.d_loss, var_list=self.dis_vars)
        self.g_optimizer = tf.train.AdamOptimizer(eta,
                beta1=beta1).minimize(self.g_loss, var_list=self.gen_vars)

        # Session
        self.session = tf.InteractiveSession()
        self.session.run(tf.global_variables_initializer())
        self.saver = tf.train.Saver(max_to_keep=None)

    def sample(self, z_mu):
        return self.session.run(self.x_hat, feed_dict={
            self.z_placeholder: z_mu
        })

    def generate_file(self, z_mus, step, n=20, img_dir="images/"):
        out = np.empty( (self.in_shape[0] * n, self.in_shape[1] * n,
            self.colorspace_dim) )
        if self.colorspace_dim == 1:
            out = np.empty( (self.in_shape[0] * n, self.in_shape[1] * n) )
        for x_idx in range(n):
            for y_idx in range(n):
                img = self.sample(z_mus[x_idx + y_idx * n])
                if self.colorspace_dim == 1:
                    out[x_idx * self.in_shape[0] : (x_idx+1) * self.in_shape[0],
                        y_idx * self.in_shape[1] : (y_idx+1) * self.in_shape[1]] = img[0].reshape(self.in_shape)
                else:
                    out[x_idx * self.in_shape[0] : (x_idx+1) * self.in_shape[0],
                        y_idx * self.in_shape[1] : (y_idx+1) * self.in_shape[1]] = img[0].reshape(
                                tuple(list(self.in_shape) + [ self.colorspace_dim ]) )
        plt.imsave(img_dir + str(step) + ".png", out, cmap="hsv")

    def train(self, dataset, img_size=64, num_steps=5000, d_steps=1, save=True):
        z_mus = [np.random.uniform(-1,1,[1,1,1,self.n_latent]) for _ in range(400)]

        for step in range(num_steps):
            batch_x, _ = dataset.next_batch(self.batch_size)
            batch_x = batch_x.reshape((-1, img_size, img_size, self.colorspace_dim))
            batch_x = tf.image.resize_images(batch_x, list(self.in_shape)).eval()
            batch_x = (batch_x - 0.5) / 0.5
            for _ in range(d_steps):
                batch_z = np.random.uniform(-1, 1, [self.batch_size,
                    1, 1, self.n_latent])
                self.session.run(self.d_optimizer, feed_dict={
                    self.x_placeholder: batch_x,
                    self.z_placeholder: batch_z,
                })
            batch_z = np.random.uniform(-1, 1, [self.batch_size, 1, 1,
                self.n_latent])
            self.session.run(self.g_optimizer, feed_dict={
                self.z_placeholder: batch_z,
            })

            if step % 10 == 0:
                print("Step: %r of %r" % (step, num_steps))
            if step % 500 == 0:
                self.generate_file(z_mus, step)
            if save and step % 1000 == 0:
                with open("checkpoints/animeds-step_%r.pyobj" % (step,), 'w') as _f:
                    pickle.dump(dataset, _f)
                print("Saved to:", self.saver.save(self.session, "checkpoints/step_%r.ckpt" % (step,)))


from __future__ import division

__all__ = ['PropertyPackageConstants', 'IDEAL_PKG', 'NRTL_PKG', 'UNIFAC_PKG',
           'UNIFAC_DORTMUND_PKG', 'PR_PKG', 'SRK_PKG']

from fluids.numerics import brenth, ridder, derivative, numpy as np

from chemicals.utils import log, exp
from fluids.constants import R, pi, N_A
from chemicals.identifiers import IDs_to_CASs
from chemicals.rachford_rice import flash_inner_loop
from thermo.eos_mix import PRMIX, SRKMIX
from thermo.eos import PR, SRK
from thermo.chemical import Chemical
from thermo.mixture import Mixture
from thermo.property_package import *

IDEAL_PKG = 'Ideal'
NRTL_PKG = 'NRTL'
UNIFAC_PKG = 'Unifac'
UNIFAC_DORTMUND_PKG = 'Unifac Dortmund'

PR_PKG = 'PR'
SRK_PKG = 'SRK'

property_packages = [IDEAL_PKG, NRTL_PKG, UNIFAC_PKG, UNIFAC_DORTMUND_PKG,
                     PR_PKG, SRK_PKG]
property_packages_cubic = [PR_PKG, SRK_PKG]

property_package_to_eos = {PR_PKG: PRMIX, SRK_PKG: SRKMIX}
property_package_to_eos_pures = {PR_PKG: PR, SRK_PKG: SRK}

property_package_names_to_objs = {IDEAL_PKG: IdealCaloric,
                                  NRTL_PKG: Nrtl, # Not complete  - enthalpy missing
                                  UNIFAC_PKG: UnifacCaloric,
                                  UNIFAC_DORTMUND_PKG: UnifacDortmundCaloric,
                                  PR_PKG: GceosBase,
                                  SRK_PKG: GceosBase,
                                 }

class PropertyPackageConstants(object):
    '''Class to store kijs, as well as allow properties to be edited; load
    them from the database and then be ready to store them.
    '''
    def __init__(self, mixture, name=IDEAL_PKG, **kwargs):
        if isinstance(mixture, list):
            self.CASs = IDs_to_CASs(mixture)
            self.Chemicals = [Chemical(CAS) for CAS in self.CASs]
        elif isinstance(mixture, Mixture):
            self.Chemicals = mixture.Chemicals
        self.name = name

        if name not in property_packages_cubic:
            eos_mix = PRMIX
            eos = PR
        else:
            eos_mix = property_package_to_eos[name]
            eos = property_package_to_eos_pures[name]

        self.eos = eos
        self.eos_mix = eos_mix

        self.eos_in_a_box = [eos_mix]

        self.pkg_obj = property_package_names_to_objs[self.name]

        self.set_chemical_constants()
        self.set_Chemical_property_objects()
        self.set_TP_sources()

        self.kwargs = kwargs
        self.pkg = self.new_package()

    def new_package(self):
        pkg_args = {'VaporPressures': self.VaporPressures,
                   'Tms': self.Tms, 'Tbs': self.Tbs, 'Tcs': self.Tcs,
                   'Pcs': self.Pcs, 'omegas': self.omegas, 'VolumeLiquids': self.VolumeLiquids,
                   'HeatCapacityLiquids': self.HeatCapacityLiquids,
                   'HeatCapacityGases': self.HeatCapacityGases,
                   'EnthalpyVaporizations': self.EnthalpyVaporizations,
                   'VolumeLiquids': self.VolumeLiquids,
                   'VolumeGases': self.VolumeGases,
                    'eos': self.eos, 'eos_mix': self.eos_mix,
                    'MWs': self.MWs,
                    'atomss': self.atomss,
                    'Hfs': self.Hfgms,
                    'Gfs': self.Gfgms,
                   }
        pkg_args.update(self.kwargs)

        if self.name == UNIFAC_PKG:
            pkg_args['UNIFAC_groups'] = self.UNIFAC_groups
        elif self.name == UNIFAC_DORTMUND_PKG:
            pkg_args['UNIFAC_groups'] = self.UNIFAC_Dortmund_groups

        return self.pkg_obj(**pkg_args)

    def from_json(self, json):
        self.__dict__.update(json)
        self.set_Chemical_property_objects()
        self.set_TP_sources()

transfer_methods = ['set_chemical_constants', 'set_Chemical_property_objects',
                   'set_TP_sources', 'UNIFAC_Dortmund_groups', 'UNIFAC_groups',
                   'atomss']

try:
    for method in transfer_methods:
        attr = Mixture.__dict__[method]
        setattr(PropertyPackageConstants, method, attr)
except:
    for method in transfer_methods:
        setattr(PropertyPackageConstants, method, getattr(Mixture, method))


import requests
import inspect

# Designed to be the Parent class for all the FindBySomething classes
class FindByX:

    def __init__(self):
        stack = inspect.stack()
        # Storing the child class name when its object is created
        self.class_name = stack[1][0].f_locals["self"].__class__.__name__

    # Generates url to query the API
    # NOTE: the calling function's Class must be present as key in the config.json to generate corresponding URL
    def generate_url(self, domain, config):
        url = domain
        try:
            class_name = self.class_name

            if class_name in config:
                config = config[class_name]
                url = url + '&'.join([f"{key}={value}" for key, value in config.items()])
                return url

        except Exception as error:
            print('No information found for ' + class_name)
            print('Exiting program to avoid over information sharing.')
            exit(0)

    # Used to get data from the API
    def execute_request(self, request_url):
        try:
            response = requests.get(request_url)
            if response.status_code == requests.codes.ok:
                response_json = response.json()
                return response_json
            else:
                print('Response Status Code:', response.status_code)
                print(response.text)
                raise Exception(response)
        except Exception as error:
            print(error)
            exit(0)


import sys
sys.path.append("../..")
sys.path.append("..")

from limits.limits import *
from hypothesis.strategies import *
from hypothesis import given
from timeout import run_with_timeout
from typing import *

numbers = lists(integers(), min_size=1, max_size=MAX_SEQUENCE_LEN)
strategy = numbers
if not isinstance(strategy, tuple):
    strategy = (strategy,)

def multiply_num(numbers):
    total = 1
    for x in numbers:
        total *= x
    return total/len(numbers)

@given(tuples(*strategy))
def test_fuzz(args):
    run_with_timeout(0.3, multiply_num, *args)


# -*- coding: utf-8 -*-
"""WWDT Downloader.

Methods to download and format West Wide Drought Tracker datasets.

Notes:
    Watch for this resampling error:
        "failed to prevent overwriting existing key grid_mapping in attrs."
    Is only periodic, check for this before overwritting original.
"""
import os
import shutil
import time
import warnings

from multiprocessing.pool import ThreadPool
from pathlib import Path

import dask
import xarray as xr

from rasterio.enums import Resampling

from drip.downloaders.utilities import Downloader
from drip.loggers import init_logger, set_handler
from drip.app.options.options import INDEX_NAMES
from drip.downloaders.utilities import NetCDF

logger = init_logger(__name__)

PRISM_URL = "https://wrcc.dri.edu/wwdt/data/PRISM"

class WWDT_Builder(NetCDF):
    """Methods for downloading and formatting selected data from the WWDT."""

    def __init__(self, index, resolution=0.25, template=None,
                 std_limit=3):
        """Initialize DIBuilder object.

        Parameters
        ----------
        index : str
            Index key. Must be in prf.options.INDEX_NAMES.
        resolution : float
            Resolution of target drought index NetCDF4 file in decimal degrees.
        template : str
            Path to file to use as template for georeferencing.
        """
        super().__init__()
        self.url = PRISM_URL
        self.resolution = resolution
        self.template = template
        self.set_index(index)
        self._set_logger(index)

    def __repr__(self):
        """Print representation string."""
        argstr = ", ".join([f"{k}='{v}'" for k, v in self.__dict__.items()])
        return f"<DIBuilder object: {argstr}>"

    def build(self, overwrite=False):
        """Download and combine multiple NetCDF files from WWDT into one."""
        dst = self.final_path
        if dst.exists() and not overwrite:
            logger.info("%s exists, skipping.", dst)
        else:
            start = time.time()
            logger.info("Building %s...", dst)

            self.download_all(self.index_paths)
            self.resample_all()
            self.combine()

            tmp_folder = self.home.joinpath(f"{self.index}")
            logger.info("Removing %s", tmp_folder)
            shutil.rmtree(tmp_folder)

            end = time.time()
            duration = round((end - start) / 60, 2)
            logger.info("%s completed in %f minutes.", dst, duration)

    def combine(self):
        """Combine monthly WWDT files into one."""
        logger.info("Combining monthly %s files into singular timeseries...",
                    self.index)

        # Get all monthly file paths
        paths = [entry["dst"] for entry in self.index_paths]

        # Combine by day dimension
        try:
            chunk_option = "array.slicing.split_large_chunks"
            with dask.config.set(**{chunk_option: False}):
                data = xr.open_mfdataset(
                    paths,
                    combine="nested",
                    concat_dim="day"
                )

                # Resort by day
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore")
                    data = data.sortby("day")

                # Check that it was concatenated correctly
                single = xr.open_dataset(paths[0])
                lonshape = single["longitude"].shape[0]
                latshape = single["latitude"].shape[0]
                tshape = (lonshape, latshape)
                lonshape = data["longitude"].shape[0]
                latshape = data["latitude"].shape[0]
                nshape = (lonshape, latshape)
                assert tshape == nshape

                # Change dataset name to 'index'
                data = data.rename({"data": "index"})

                # Write to file
                data.to_netcdf(self.combined_path)

            logger.info("Build for %s complete.", self.combined_path)

        except AssertionError:
            print(f"Combination of {self.index} failed with incorrect shape: "
                  f"target spatial shape: {tshape}, generated spatial shape "
                  f"{nshape}")
            logger.error("Combination of %s failed with incorrect "
                         "shape: target spatial shape: %s, "
                         "generated spatial shape %s", self.index,
                         str(tshape), str(nshape))
            raise

        except Exception as error:
            print(error.__dict__)
            print(f"Combination of {self.index} failed with error "
                  f"message: {type(error)}, {error}")
            logger.error("Combination of %s failed. %s: %s", self.index,
                         type(error), error)
            raise

    @property
    def combined_path(self):
        """Return path for all year, 12-monthly combined dataset."""
        return self.home.joinpath(self.index + ".nc")

    @property
    def final_path(self):
        """Return final path for indexed NetCDF file."""
        return self.home.joinpath(self.index + ".nc")

    @property
    def home(self):
        """Return data home directory."""
        return self.paths["indices"]

    @property
    def index_paths(self):
        """Return list of remote urls and local destination paths."""
        paths = []
        for i in range(1, 13):
            url = os.path.join(
                self.url,
                f"{self.index}/{self.index}_{i}_PRISM.nc"
            )
            fname = f"{self.index}_{i:02d}_temp.nc"
            dst = self.home.joinpath(f"{self.index}/{fname}")
            os.makedirs(os.path.dirname(dst), exist_ok=True)
            entry = {"url": url, "dst": dst}
            paths.append(entry)

        return paths

    def resample(self, path):
        """Resample indices to target resolution."""
        dst = str(path).replace(".nc", "_2.nc")
        path = str(path)

        try:
            data = xr.open_dataset(path)
        except RuntimeError:
            try:
                data = xr.open_dataset(path)
                logger.warning("RuntimeError opening %s, trying again.", path)
            except RuntimeError as error:
                logger.error("RuntimeError opening %s: %s", path, error)

        data = set_georeferencing(self.index, data)

        if not self.template:
            if data.rio.resolution()[0] != self.resolution:
                logger.info("Resampling %s to %f decimal degrees...", path,
                            self.resolution)
                try:
                    ndata = data.rio.reproject(
                        data.rio.crs,
                        transform=self.resolution,
                        resampling=Resampling.bilinear
                    )
                    ndata.to_netcdf(dst)
                    logger.info("Resampling %s to %f complete.", path,
                                self.resolution)
                except Exception as error:
                    print(error.__dict__)
                    print(f"Resampling {path} failed with error message: "
                        f"{type(error)}, {error}")
                    logger.error("Resampling %s failed. %s: %s", path,
                                type(error), error)
            else:
                logger.info("%s already has %f resolution, skipping...",
                            path, self.resolution)

        else:
            logger.info("Reprojecting %s to match georeferencing of "
                        "%s ...", path, self.template)

            # Reproject Matching requires x and y dim names
            templ = xr.open_dataset(self.template)
            templ = set_georeferencing(self.index, templ, xy=True)
            data = set_georeferencing(self.index, data, xy=True)

            try:
                ndata = data.rio.reproject_match(
                    match_data_array=templ["index"],
                    resampling=Resampling.bilinear
                )
                ndata = set_georeferencing(self.index, ndata)
                ndata.to_netcdf(dst)
                templ.close()
            except Exception as error:
                print(error.__dict__)
                print(f"Resampling {path} failed with error message: "
                        f"{type(error)}, {error}")
                logger.error("Resampling %s failed. %s: %s", path,
                            type(error), error)

            data.close()

            path = Path(path)
            tmp = path.parent.joinpath("tmp", path.name)
            tmp.parent.mkdir(exist_ok=True)
            shutil.move(path, tmp)
            shutil.move(dst, path)
            logger.info("Reprojection of %s to match %s complete.", path,
                        self.template)

    def resample_all(self):
        """Resample all downloading monthly files to target resolution."""
        paths = [entry["dst"] for entry in self.index_paths]
        with ThreadPool(os.cpu_count() - 1) as pool:
            for _ in pool.imap(self.resample, paths):
                pass

    def set_index(self, index):
        """Set the index key and index name.

        Parameters
        ----------
        index : str
            Index key. Must be in prf.options.INDEX_NAMES.
        """
        if index not in INDEX_NAMES:
            available_keys = ", ".join(list(INDEX_NAMES.keys()))
            msg = (f"{index} key is not avaiable. Available keys: "
                   f"{available_keys}")
            logger.error(msg)
            raise KeyError(msg)
        self.index = index
        self.index_name = INDEX_NAMES[index]

    def _set_logger(self, index):
        """Create logging file handler for this process."""
        filename = self.home.joinpath("logs", index + ".log")
        set_handler(logger, filename)

if __name__ == "__main__":
    index = "pdsi"
    self = Data_Builder(index=index)


#!/usr/bin/env python

import sympy as sp
from sympy.solvers import solve
import numpy as np
import matplotlib.pyplot as plt

def nth_derivative_at_zero(uhat,s,n):
  '''
  returns the the nth derivative of u(x) evaluated at zero given the laplace
  transform of u(x)
  PARAMETERS
  ----------
    uhat: laplace transform of u. This is a symbolic function of s.
    s: the laplace domain variable
    n: the derivative order

  RETURNS
  -------
    nth_derivative: symbolic expression for the nth derivative of u evaluated
                    at zero
  '''
  assert n >= 0
  if n == 0:
    expr = s*uhat
    zeroth_derivative = expr.limit(s,np.inf)
    return zeroth_derivative
  elif n > 0:
    expr = s**(n+1)*uhat
    # note that m goes up to n-1
    for m in range(0,n):
      expr -= s**(m+1)*nth_derivative_at_zero(uhat,s,n-m-1)
    nth_derivative = expr.limit(s,np.inf)
    return nth_derivative

def inverse_laplace_transform_series_expansion(uhat,s,t,N):
  '''
  returns the Taylor series expansion of u(x) about zero given its laplace
  transform

  PARAMETERS
  ----------
    uhat: symbolic expression for the laplace transform of u(x)
    s: laplace domain variable
    N: order of the Taylor series expansion

  RETURNS
  -------
    series: symbolic expression for the series expansion of the u(x)
          about x=0
  '''
  series = 0
  # note that n goes up to N
  for n in range(N+1):
    # sum each term in the taylor series expansion
    series += (nth_derivative_at_zero(uhat,s,n)*t**n)/sp.factorial(n)
  return series

x,s = sp.symbols('x s')

u = 3*x**2 + 2*x + 1 # test function
uhat = sp.laplace_transform(u,x,s)[0] # test function laplace transform
u_expansion = inverse_laplace_transform_series_expansion(uhat,s,x,2)
assert sp.simplify(u - u_expansion) == 0

'''

Maxwell viscoelastic 2D two layered earthquake model
  I am demonstrating here that the surface deformation resulting from viscous
  relaxation following an earthquake in a layered halfspace is, to first order,
  a linear function of the viscosities in each layer.

Variables used
  x: distance from fault strike
  t: time
  D: locking depth of the fault
  H: thickness of the top layer
  mu1,mu2: shear modulus of the first and second layer
  eta1,eta2: viscosity of the first and second layer

'''
x,t,D,H,theta = sp.symbols('x t D H theta')
mu1,mu2 = sp.symbols('mu1 mu2')
eta1,eta2 = sp.symbols('eta1 eta2')
b = sp.Function('b')(t)
n = sp.symbols('n') # dummy summation variable
nmax = 3 # The number of terms used to approximate the infinite series

'''
The surface displacements for a layered viscous halfspace can be found by using
the displacements for a layered elastic halfspace and the correspondence
principle. The surface displacements for a layered elastic halfspace are:
'''
gamma = (mu1-mu2)/(mu1+mu2)
W = sp.Function('W')(n)
# uncomment for explicit W
#W = 1/sp.pi*(sp.atan((D + 2*n*H)/x) + sp.atan((D - 2*n*H)/x))
u_elastic = b*(sp.Rational(1,2)*W.subs(n,0) + sp.summation(gamma**n*W,(n,1,nmax)))

'''
The correpondence principle says that the Laplace transform of displacements
in an elastic medium is the same form as the displacements in a viscoelastic
medium. The laplace transform of displacements for an elastic medium are:
'''
uhat_elastic = sp.laplace_transform(u_elastic,t,s)

'''
Replacing the shear modulii with the equivalent maxwell viscoelastic shear
modulii in the laplace domain gives us the laplace transform of displacements
in the viscoelastic model
'''
mu1hat = s/((s/mu1) + (1/eta1)) # equivalent shear modulii
mu2hat = s/((s/mu2) + (1/eta2))
uhat_viscoelastic = uhat_elastic.subs(((mu1,mu1hat),(mu2,mu2hat)))

'''
for the sake of simplicity, although this does not reduce the generality of our
conclusions, we assume that the viscoelastic model has a homogeneous shear modulus
'''
uhat_viscoelastic = uhat_viscoelastic.subs(mu2,mu1)

'''
We are interested in the viscous deformation and so we remove the elastic
component of deformation.  Doing so also removes a singularity in the
displacement field at the time of the earthquake making subsequent computations
easier.
'''
uhat_viscous = uhat_viscoelastic - uhat_elastic.subs(mu2,mu1)

'''
Using the initial value theorem, the first term in the Taylor series expansion
of the viscous deformation is b(t) convolved with:
'''
bhat = sp.laplace_transform(b,t,s)
u_viscous_term0 = inverse_laplace_transform_series_expansion(uhat_viscous/bhat,s,t,0)
sp.pprint(sp.expand(u_viscous_term0))

'''
We can find the next few  terms of the Taylor series expansion of viscous
deformation using an extension of the initial value theorem.  The viscous
deformation is b(t) convolved with:
'''
u_viscous_term0to2 = inverse_laplace_transform_series_expansion(uhat_viscous/bhat,s,t,2)
sp.pprint(sp.collect(sp.expand(u_viscous_term0to2),t))

'''
An approximation for early postseismic deformation can then be found by
combining the elastic deformation with the first term in the Taylor series of the
viscous component of deformation.
'''
u_elastic = u_elastic.subs(mu2,mu1)
u_approx = u_elastic + sp.integrate(b.subs(t,theta)*u_viscous_term0,(theta,0,t))
sp.pprint(u_approx)

'''
Maxwell viscoelastic 2D three layered earthquake model
  This procedure can be repeated for a three layered viscoelastic earthquake
  model.  We start with the solution for the three layered elastic solution from
  Chinnery and Jovanovich 1972. WE ADOPT THE NOTATION FROM CHINNERY AND
  JOVANOVICH 1972 which is described below

variables used:
  mu3,mu2,mu1: shear modulus for the top, middle, and bottom layer (mu4 from
               Chinnery and Jovanovich is assumed 0)
  eta3,eta2,eta1: viscosity for the top, middle, and bottom layer
  h3,h2: thichness of the top and middle layer
  p: depth to the bottom of the fault. (down is positive)
'''

l_max = 2
m_max = 2
n_max = 2

h2,h3,p,y = sp.symbols('h2 h3 p y')
mu1,mu2,mu3 = sp.symbols('mu1 mu2 mu3')
eta1,eta2,eta3 = sp.symbols('eta1 eta2 eta3')
M,N = sp.symbols('M N')

a1    = (mu2 - mu1) / (mu2 + mu1)
a2    = (mu3 - mu2) / (mu3 + mu2)
a3    = -1
b1    = 2*mu1 / (mu1 + mu2)
b2    = 2*mu2 / (mu2 + mu3)
b3    = 2
d1    = 2*mu2 / (mu1 + mu2)
d2    = 2*mu3 / (mu2 + mu3)
W = sp.Function('W')(M,N)
# uncomment for explicit W
#W = 1/pi*(sp.atan((-2*M*h2 - N*h3 + p)/y) + a3*sp.atan((-2*M*h2 - N*h3 - p)/y))

def P(l,m,n):
  N = sp.factorial(n+1) * sp.factorial(l+m-1)
  D = sp.factorial(l) * sp.factorial(n) * sp.factorial(l-1) * sp.factorial(m)
  return N / D

def Q(l,m,n):
  N = sp.factorial(n+l) * sp.factorial(l+m)
  D = sp.factorial(l) * sp.factorial(n) * sp.factorial(l) * sp.factorial(m)
  return N / D

u = -b3*sp.Rational(-1,2)*W.subs(((N,0),(M,0)))
for n in range(n_max):
  coeff = a2*b3*(-a2*a3)**n
  u += coeff*W.subs(((M,0),(N,n+1)))

for l in range(1,l_max):
  for m in range(m_max):
    for n in range(n_max):
      coeff = a2*b3*(-a1*a2)**m*(-a2*a3)**n*(-a2*a3*d2*b2)**l*P(l,m,n)
      u += coeff*W.subs(((M,l+m),(N,l+n+1)))

for l in range(l_max):
  for m in range(m_max):
    for n in range(n_max):
      coeff = a1*d2*b2*b3*(-a1*a3)**m*(-a2*a3)**n*(-a1*a3*d2*b2)**l*Q(l,m,n)
      u += coeff*W.subs(((M,l+m+1),(N,l+n+1)))

u_elastic = sp.Rational(1,2)*b*u

'''
Assuming a homogeneous shear modulus, mu1, the Laplace transform of the
viscous component of deformation is:
'''
uhat_elastic = sp.laplace_transform(u_elastic,t,s)
mu1hat = s/((s/mu1) + (1/eta1))
mu2hat = s/((s/mu1) + (1/eta2))
mu3hat = s/((s/mu1) + (1/eta3))
uhat_viscoelastic = uhat_elastic.subs(((mu1,mu1hat),(mu2,mu2hat),(mu3,mu3hat)))
uhat_viscous = uhat_viscoelastic - uhat_elastic.subs(((mu2,mu1),(mu3,mu1)))

'''
The first term in the Taylor series expansion of the viscous component of
deformation is b(t) convolved with (this will take a few minutes):
'''
u_viscous_term0 = inverse_laplace_transform_series_expansion(uhat_viscous/bhat,s,t,0)
u_viscous_term0 = sp.expand(u_viscous_term0)
sp.pprint(u_viscous_term0)

'''
An approximation for early postseismic deformation can then be found by
combining the elastic deformation with the first term in the Taylor series of the
viscous component.
'''
theta = sp.symbols('theta')
u_elastic = u_elastic.subs(((mu2,mu1),(mu3,mu1)))
u_approx = u_elastic + sp.integrate(b.subs(t,theta)*u_viscous_term0,(theta,0,t))
sp.pprint(u_approx)


"""
Small utility for creating shareable links to Civis services.
"""
import argparse

import civis

def list_services(args):
    client = civis.APIClient()
    services = client.services.list()
    print("List of services:")
    for service in services:
        print(f"\tID: {service['id']}\tName: {service['name']}")

def share_service(args):
    client = civis.APIClient()
    service = client.services.get(args.id)
    try:
        response = client.services.post_tokens(args.id, args.name)
        url = f"{service['current_url']}/civis-platform-auth?token={response['token']}"
        print(f"Share service id {args.id} with the following URL: {url}")
    except civis.base.CivisAPIError as e:
        if "Name has already been taken" in str(e):
            print(
                f"The share name {args.name} is already in use. "
                "Please choose another"
            )
        else:
            raise e

def unshare_service(args):
    client = civis.APIClient()
    tokens = client.services.list_tokens(args.id)
    try:
        token = next(t for t in tokens if t["name"] == args.name)
        client.services.delete_tokens(args.id, token["id"])
        print(f"Successfully unshared {args.name}")
    except StopIteration:
        print(f"Could not find share token with the name {args.name}")

def main():
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    list_parser = subparsers.add_parser("list")
    list_parser.set_defaults(func=list_services)

    share_parser = subparsers.add_parser("share")
    share_parser.add_argument("id", type=int, help="The ID of the service to share")
    share_parser.add_argument("name", type=str, help="A name to give the share URL")
    share_parser.set_defaults(func=share_service)

    unshare_parser = subparsers.add_parser("unshare")
    unshare_parser.add_argument("id", type=int, help="The ID of the service to unshare")
    unshare_parser.add_argument(
        "name", type=str, help="The name of the service to unshare"
    )
    unshare_parser.set_defaults(func=unshare_service)

    args = parser.parse_args()
    args.func(args)

if __name__ == "__main__":
    main()


from django import forms
from .models import Pergunta, Simulado
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class RespostaForm(forms.Form):
    def __init__(self, *args, **kwargs):
        questoes = kwargs.pop('perguntas')  # Removendo 'perguntas' do kwargs
        super(RespostaForm, self).__init__(*args, **kwargs)
        for pergunta in questoes:
            alternativas = pergunta.alternativa_set.all()
            self.fields[f'pergunta_{pergunta.id}'] = forms.ChoiceField(
                choices=[(alternativa.id, alternativa.texto) for alternativa in alternativas],
                widget=forms.RadioSelect,
                label=pergunta.enunciado,
                required=False,
                initial=self.initial.get(f'pergunta_{pergunta.id}')  # Definindo as alternativas iniciais
            )

class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2']