import asyncio
from contextlib import asynccontextmanager
from typing import AsyncGenerator

from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection

from realtime.message import Message, parse

async def subscribe(
    con: AsyncConnection,
    slot_name: str = "realtime_py",
    poll_delay: float = 0.1,
    drop_on_close: bool = True,
) -> AsyncGenerator[Message, None]:
    """Subscribe to a PostgreSQL +9.4 database for changes"""

    GET_UPDATES = text(
        "SELECT lsn, xid, data from pg_logical_slot_get_changes(:slot_name, NULL, NULL)"
    )

    async with replication_slot(
        slot_name=slot_name, con=con, drop_on_close=drop_on_close
    ):

        while True:
            cursor = await con.execute(GET_UPDATES, {"slot_name": slot_name})

            for _, _, data in cursor:
                yield parse(data)

            # Sleep for 0.25 seconds before polling again
            await asyncio.sleep(poll_delay)

@asynccontextmanager
async def replication_slot(
    slot_name: str, con: AsyncConnection, drop_on_close: bool
) -> AsyncGenerator[None, None]:

    CREATE_SLOT = text(
        """
    with check_exists as (
        SELECT
            count(1) = 1 as already_exists
        FROM
            pg_replication_slots
        WHERE
            slot_name = :slot_name
    )

    SELECT
        CASE
            WHEN already_exists THEN 0
            ELSE (
                SELECT
                    1
                FROM
                    pg_create_logical_replication_slot(
                        :slot_name,
                        'test_decoding'
                    )
            )
        END as res
    FROM
        check_exists
    """
        ""
    )
    DROP_SLOT = text("SELECT pg_drop_replication_slot(:slot_name);")

    params = dict(slot_name=slot_name)

    await con.execute(CREATE_SLOT, params)
    try:
        yield
    finally:
        if drop_on_close:
            await con.execute(DROP_SLOT, params)


from __future__ import print_function, absolute_import
import re
from llvm.core import (Type, Builder, LINKAGE_INTERNAL, inline_function,
                       Constant, ICMP_EQ)
from numba import typing, types, cgutils
from numba.targets.base import BaseContext
from .cudadrv import nvvm
from . import nvvmutils

# -----------------------------------------------------------------------------
# Typing

class CUDATypingContext(typing.BaseContext):
    def init(self):
        from . import cudadecl, cudamath

        self.install(cudadecl.registry)
        self.install(cudamath.registry)

# -----------------------------------------------------------------------------
# Implementation

VALID_CHARS = re.compile(r'[^a-z0-9]', re.I)

class CUDATargetContext(BaseContext):
    implement_powi_as_math_call = True

    def init(self):
        from . import cudaimpl, libdevice

        self.insert_func_defn(cudaimpl.registry.functions)
        self.insert_func_defn(libdevice.registry.functions)

    def mangler(self, name, argtypes):
        def repl(m):
            ch = m.group(0)
            return "_%X_" % ord(ch)

        qualified = name + '.' + '.'.join(str(a) for a in argtypes)
        mangled = VALID_CHARS.sub(repl, qualified)
        return mangled

    def prepare_cuda_kernel(self, func, argtypes):
        # Adapt to CUDA LLVM
        module = func.module
        func.linkage = LINKAGE_INTERNAL
        wrapper = self.generate_kernel_wrapper(func, argtypes)
        func.delete()
        del func

        nvvm.set_cuda_kernel(wrapper)
        nvvm.fix_data_layout(module)

        return wrapper

    def generate_kernel_wrapper(self, func, argtypes):
        module = func.module
        argtys = self.get_arguments(func.type.pointee)
        fnty = Type.function(Type.void(), argtys)
        wrapfn = module.add_function(fnty, name="cudaPy_" + func.name)
        builder = Builder.new(wrapfn.append_basic_block(''))

        # Define error handling variables
        def define_error_gv(postfix):
            gv = module.add_global_variable(Type.int(),
                                            name=wrapfn.name + postfix)
            gv.initializer = Constant.null(gv.type.pointee)
            return gv

        gv_exc = define_error_gv("__errcode__")
        gv_tid = []
        gv_ctaid = []
        for i in 'xyz':
            gv_tid.append(define_error_gv("__tid%s__" % i))
            gv_ctaid.append(define_error_gv("__ctaid%s__" % i))

        callargs = []
        for at, av in zip(argtypes, wrapfn.args):
            av = self.get_argument_value(builder, at, av)
            callargs.append(av)

        status, _ = self.call_function(builder, func, types.void, argtypes,
                                       callargs)

        # Check error status
        with cgutils.if_likely(builder, status.ok):
            builder.ret_void()

        with cgutils.ifthen(builder, builder.not_(status.exc)):
            # User exception raised
            old = Constant.null(gv_exc.type.pointee)

            # Use atomic cmpxchg to prevent rewriting the error status
            # Only the first error is recorded
            xchg = builder.atomic_cmpxchg(gv_exc, old, status.code,
                                          "monotonic")
            changed = builder.icmp(ICMP_EQ, xchg, old)

            # If the xchange is successful, save the thread ID.
            sreg = nvvmutils.SRegBuilder(builder)
            with cgutils.ifthen(builder, changed):
                for dim, ptr, in zip("xyz", gv_tid):
                    val = sreg.tid(dim)
                    builder.store(val, ptr)

                for dim, ptr, in zip("xyz", gv_ctaid):
                    val = sreg.ctaid(dim)
                    builder.store(val, ptr)

        builder.ret_void()

        # force inline
        inline_function(status.code)

        module.verify()
        return wrapfn

    def link_dependencies(self, module, depends):
        for lib in depends:
            module.link_in(lib, preserve=True)

    def make_constant_array(self, builder, typ, ary):
        """
        Return dummy value.

        XXX: We should be able to move cuda.const.array_like into here.
        """

        a = self.make_array(typ)(self, builder)
        return a._getvalue()

    def insert_string_const_addrspace(self, builder, string):
        """
        Insert a constant string in the constant addresspace and return a
        generic i8 pointer to the data.

        This function attempts to deduplicate.
        """
        lmod = builder.basic_block.function.module
        text = Constant.stringz(string)
        name = "__conststring__.%s" % string
        charty = Type.int(8)

        for gv in lmod.global_variables:
            if gv.name == name and gv.type.pointee == text.type:
                break
        else:
            gl = lmod.add_global_variable(text.type, name=name,
                                          addrspace=nvvm.ADDRSPACE_CONSTANT)
            gl.linkage = LINKAGE_INTERNAL
            gl.global_constant = True
            gl.initializer = text

            constcharptrty = Type.pointer(charty, nvvm.ADDRSPACE_CONSTANT)
            charptr = builder.bitcast(gl, constcharptrty)

        conv = nvvmutils.insert_addrspace_conv(lmod, charty,
                                               nvvm.ADDRSPACE_CONSTANT)
        return builder.call(conv, [charptr])


from nltk.tokenize import RegexpTokenizer
from stop_words import get_stop_words
from nltk.stem.porter import PorterStemmer
from gensim import corpora, models
import gensim
import pickle
import warnings
import pandas as pd
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
warnings.filterwarnings("ignore")

MAX_TOPICS=8
MIN_PERC=0.8
MAX_DS_SIZE=2000

dict_symptoms=pickle.load(open("datasets/covid19_symptoms.pickle","rb"))
list_categories=pickle.load(open("datasets/covid19_tags.pickle","rb"))

tokenizer = RegexpTokenizer(r'\w+')

# create English stop words list
en_stop = get_stop_words('en')

# Create p_stemmer of class PorterStemmer
p_stemmer = PorterStemmer()

# create sample documents

# compile sample documents into a list
#doc_set = [doc_a, doc_b, doc_c, doc_d, doc_e]
doc_set=[]
doc_ids=[]
for key in dict_symptoms.keys():
    doc_set.append(dict_symptoms[key].split(","))
    doc_ids.append(str(key))

# set max data set size
import random
MAX_DS_SIZE=2000
doc_ids=random.sample(doc_ids,MAX_DS_SIZE)
doc_set=[dict_symptoms[id].split(",") for id in doc_ids]

# list for tokenized documents in loop
texts = []

# loop through document list
for tokens in doc_set:
    # clean and tokenize document string

    # stem tokens
    # stemmed_tokens = [p_stemmer.stem(i) for i in tokens]

    # add tokens to list
    texts.append(tokens)

# turn our tokenized documents into a id <-> term dictionary
dictionary = corpora.Dictionary(texts)

# convert tokenized documents into a document-term matrix
corpus = [dictionary.doc2bow(text) for text in texts]

# generate LDA model
ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=MAX_TOPICS, id2word=dictionary, passes=20,alpha='auto',eta='auto')

# print keywords
topics = ldamodel.print_topics(num_words=10)
for topic in topics:
    print(topic)

ldamodel.save('outputs/model5.gensim')

list_tags=[]
for i in range(MAX_TOPICS):
    list_tags.append("t"+str(i+1))

from gensim.models import CoherenceModel
if __name__ == '__main__':
    # Compute Perplexity
    print('\nPerplexity: ', ldamodel.log_perplexity(corpus))  # a measure of how good the model is. lower the better.

    # Compute Coherence Score
    coherence_model_lda = CoherenceModel(model=ldamodel, texts=texts, dictionary=dictionary, coherence='c_v')
    coherence_lda = coherence_model_lda.get_coherence()
    print('\nCoherence Score (CV): ', coherence_lda)

    # Visualize the topics
    #import pyLDAvis
    i#mport pyLDAvis.sklearn

    #vis = pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary)
    #pyLDAvis.save_html(vis, f'visualize/pyLDAvis_{MAX_TOPICS}.html')


import sys
import logging
import datetime
import time

###################################################
# Unlock script
#================================================

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
#================================================ Android View Client
from com.dtmilano.android.viewclient import ViewClient

###################################################
# Main
###################################################
#==================================================
def main():
    # config logging
    logging.basicConfig(
            level=logging.DEBUG,
            format='%(asctime)s : %(levelname)s %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S',
            filename='Reservior.log',
            filemode='w')

    logging.info('-------------- Begin --------------')
    # Connects to the current device, returning a MonkeyDevice object
    device = MonkeyRunner.waitForConnection()
    vc = ViewClient(device=device, serialno='0123456789ABCDEF', adb=None)

    sim_SN = sys.argv[1]

    print('sim_SN: ' + sim_SN.encode('utf-8'))

    print('start!!!')
    device.wake()

    print('drag screen lock slide!!!')
    device.drag((160, 440), (320, 440), 0.5, 1)
    time.sleep(1)
    print('unlock pin code')
    id_0 = getViewId(vc, u'0')
    print('id_o = ' + str(id_0))
    for i in range(4):
        touchButton(vc, id_0)
    touchButtonByText(vc, u'OK')

    mpr(vc, device, "GW" + sim_SN)

    print('end!!!')
    logging.info('-------------- End --------------')

#==================================================
###################################################
# Function
###################################################
def mpr(vc, device, simSN):
    print('Go to main menu')
    touchButtonByText(vc, u'Main menu')
    print('Go to Replacement')
    touchButtonByText(vc, u'Replace')
    print('Select Pump base')
    touchButtonByText(vc, u'Pump base')
    print('press Replace button')
    touchButtonByText(vc, u'Replace')
    print('press Yes button of remove pump base info')
    touchButtonByText(vc, u'Yes')
    print('press Done button of sidpose system component info')
    touchButtonByText(vc, u'Done')
    print('press Done button of prepare micropump')
    touchButtonByText(vc, u'Done')
    print('press save button of reservior amount')
    touchButtonByText(vc, u'Save')
    print('press next button of paire pump')
    touchButtonByText(vc, u'Next')
    print('select enter pump keys')
    touchButtonByText(vc, u'Enter pump key')
    print('select pump serial number')
    touchButtonByText(vc, simSN)
    # input pin number
    print('input pin number')
    getViewId(vc, u'Enter pump key')
    touchPosition(device, 200, 100)
    time.sleep(2)
    device.type("00000000")
    touchPosition(device, 200, 150)
    touchPosition(device, 280, 40)
    time.sleep(3)
    print('press Fill button')
    touchButtonByText(vc, u'Fill')
    print('press OK button')
    touchButtonByText(vc, u'OK')
    print('press Next button')
    touchButtonByText(vc, u'Next')
    print('insulin button pressed')
    getViewId(vc, u'Activate basal rate profile')
    device.press('KEYCODE_F10', MonkeyDevice.DOWN_AND_UP)
    time.sleep(5)

def isW85(vc):
    try:
        vc.dump(window=-1)
        vc.findViewWithTextOrRaise(u'W-85')
        return True
    except:
        print('No W-85')
        return False

def getDateInfo(device, cmd):
    value = device.shell(cmd)
    return value.encode('utf-8')

def touchButtonByText(vc, text):
    while True:
        try:
            vc.dump(window=-1)
            b = vc.findViewWithTextOrRaise(text)
            b.touch()
            break
        except:
            print('[touchButtonByText] View is not found by text: ' + text.encode('utf-8'))
            logging.info('[touchButtonByText] View is not found by text: ' + text)
            if isW85(vc) == True:
                # press Ok
                touchButtonByText(vc, u'OK')

def getViewId(vc, text):
    id = 0
    while id == 0:
        try:
            vc.dump(window=-1)
            b = vc.findViewWithTextOrRaise(text)
            id = b.getId()
        except:
            print('[getViewId] View is not found by text: ' + text.encode('utf-8'))
            logging.info('[getViewId] View is not found by text: ' + text)
            id = 0
    return id

def touchButton(vc, id):
    try:
       b = vc.findViewByIdOrRaise(id)
       b.touch()
    except:
        print('[touchButton] View is not found by id: ' + str(id))
        logging.info('[touchButton] View is not found by id: ' + str(id))

def touchPosition(device, x, y, delay=1):
    device.touch(x, y, MonkeyDevice.DOWN_AND_UP)
    time.sleep(delay)

if __name__ == '__main__':
    main()


"""
@file boxes.py
@author Ryan Missel

Handles generating the datasets for the box experiments under a number of situations
"""
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.utils.data import Dataset

class PymunkData(Dataset):
    """
    Load sequences of images
    """
    def __init__(self, file_path, config):
        # Load npz files
        npzfile = np.load(file_path)
        clsfile = np.load(file_path[:-4] + '_cls.npz')

        # Load data
        self.images = npzfile['images'].astype(np.float32)
        if config['out_distr'] == 'bernoulli':
            self.images = (self.images > 0).astype('float32')

        self.images = torch.from_numpy(self.images).to(device=torch.Tensor().device)[:, :30]
        self.images = self.images.unsqueeze(2)

        # Load classes
        self.classes = torch.from_numpy(clsfile['cls'].astype(np.float32)).to(device=torch.Tensor().device)

        # Load ground truth position and velocity (if present). This is not used in the KVAE experiments in the paper.
        if 'state' in npzfile:
            # Only load the position, not velocity
            self.state = npzfile['state'].astype(np.float32)[:, :, :2]
            self.velocity = npzfile['state'].astype(np.float32)[:, :, 2:]

            # Normalize the mean
            self.state = self.state - self.state.mean(axis=(0, 1))

            # Set state dimension
            self.state_dim = self.state.shape[-1]

        # Get data dimensions
        self.sequences, self.timesteps, self.channels, self.d1, self.d2 = self.images.shape

        # We set controls to zero (we don't use them even if dim_u=1). If they are fixed to one instead (and dim_u=1)
        # the B matrix represents a bias.
        self.controls = np.zeros((self.sequences, self.timesteps, config['dim_u']), dtype=np.float32)
        self.controls = torch.from_numpy(self.controls).to(device=torch.Tensor().device)

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

    def __getitem__(self, idx):
        """ Couple images and controls together for compatibility with other datasets """
        return torch.Tensor([idx]), self.images[idx], self.controls[idx], self.classes[idx]

if __name__ == '__main__':
    config = {'dataset': 'box_gravity_train', 'out_distr': 'bernoulli', 'dim_u': 1}

    dataset = PymunkData("box_data/{}.npz".format(config['dataset']), config)
    print(dataset.images.shape)
    print(dataset.images[0].shape)

    images = dataset.images[[0, 20, 25, 4, 5], 0, 0]
    images = np.hstack(images)
    plt.imshow(images, cmap='gray')
    plt.xticks([])
    plt.yticks([])
    plt.show()

    # for image in dataset.images[np.random.randint(0, dataset.images.shape[0], 1)[0]]:
    #     plt.imshow(image.squeeze())
    #     plt.show()


"""
    To use the code, users should to config detpath, annopath and imagesetfile
    detpath is the path for 15 result files, for the format, you can refer to "http://captain.whu.edu.cn/DOTAweb/tasks.html"
    search for PATH_TO_BE_CONFIGURED to config the paths
    Note, the evaluation is on the large scale images
"""
import os
import numpy as np
import dota_utils as util
import re
import time
import pdb
import tqdm
import torch
import torchgeometry as tgm
from detectron2.layers import nms_rotated
## the thresh for nms when merge image
nms_thresh = 0.3

# singlenet with round sample
# threshold = {'roundabout': 0.3, 'tennis-court': 0.2, 'swimming-pool': 0.05, 'storage-tank': 0.3,
#                'soccer-ball-field': 0.3, 'small-vehicle': 0.2, 'ship': 0.2, 'plane': 0.3,
#                'large-vehicle': 0.3, 'helicopter': 0.1, 'harbor': 0.4, 'ground-track-field': 0.4,
#                'bridge': 0.2, 'basketball-court': 0.1, 'baseball-diamond': 0.5}

# singlenet with ellipse sample
threshold = {'roundabout': 0.3, 'tennis-court': 0.2, 'swimming-pool': 0.05, 'storage-tank': 0.3,
               'soccer-ball-field': 0.3, 'small-vehicle': 0.2, 'ship': 0.2, 'plane': 0.3,
               'large-vehicle': 0.2, 'helicopter': 0.1, 'harbor': 0.1, 'ground-track-field': 0.3,
               'bridge': 0.1, 'basketball-court': 0.1, 'baseball-diamond': 0.5,
            'container-crane': nms_thresh, 'airport': nms_thresh, 'helipad': nms_thresh}

# threshold = {'roundabout': nms_thresh, 'tennis-court': nms_thresh, 'swimming-pool': nms_thresh, 'storage-tank': nms_thresh,
#             'soccer-ball-field': nms_thresh, 'small-vehicle': nms_thresh, 'ship': nms_thresh, 'plane': nms_thresh,
#             'large-vehicle': nms_thresh, 'helicopter': nms_thresh, 'harbor': nms_thresh, 'ground-track-field': nms_thresh,
#             'bridge': nms_thresh, 'basketball-court': nms_thresh, 'baseball-diamond': nms_thresh}

# threshold = {'roundabout': nms_thresh, 'tennis-court': nms_thresh, 'swimming-pool': nms_thresh, 'storage-tank': nms_thresh,
#                 'soccer-ball-field': nms_thresh, 'small-vehicle': nms_thresh, 'ship': nms_thresh, 'plane': nms_thresh,
#                 'large-vehicle': nms_thresh, 'helicopter': nms_thresh, 'harbor': nms_thresh, 'ground-track-field': nms_thresh,
#                 'bridge': nms_thresh, 'basketball-court': nms_thresh, 'baseball-diamond': nms_thresh,
#                 'container-crane': nms_thresh, 'airport': nms_thresh, 'helipad': nms_thresh}

def batch_polygonToRotRectangle(bbox):
    """
    :param bbox: The polygon stored in format [x1, y1, x2, y2, x3, y3, x4, y4]
    :return: Rotated Rectangle in format [cx, cy, w, h, theta]
    """
    bbox = torch.stack([bbox[:, 0::2], bbox[:, 1::2]], dim=1)
    angle = torch.atan2(-(bbox[:, 0,1]-bbox[:, 0,0]),
                        bbox[:, 1,1]-bbox[:, 1,0])

    center = torch.zeros(bbox.size(0), 2, 1, dtype=bbox.dtype, device=bbox.device)

    for i in range(4):
        center[:, 0, 0] += bbox[:, 0,i]
        center[:, 1, 0] += bbox[:, 1,i]

    center = center / 4.0
    R = torch.stack([torch.cos(angle), -torch.sin(angle),
                     torch.sin(angle), torch.cos(angle)], dim=1)
    R = R.reshape(-1, 2, 2)

    normalized = torch.matmul(R.transpose(2,1), bbox - center)

    if bbox.size(0) == 0:
        return torch.empty((0, 5), dtype=bbox.dtype, device=bbox.device)

    xmin = torch.min(normalized[:, 0,:], dim=1)[0]
    xmax = torch.max(normalized[:, 0,:], dim=1)[0]
    ymin = torch.min(normalized[:, 1,:], dim=1)[0]
    ymax = torch.max(normalized[:, 1,:], dim=1)[0]

    w = xmax - xmin
    h = ymax - ymin

    center = center.squeeze(-1)
    center_x = center[:, 0]
    center_y = center[:, 1]
    new_box = torch.stack([center_x, center_y, w, h, -tgm.rad2deg(angle)], dim=1)
    return new_box

def py_cpu_nms_poly(dets, thresh):
    scores = dets[:, 8]
    polys = []
    areas = []
    for i in range(len(dets)):
        tm_polygon = polyiou.VectorDouble([dets[i][0], dets[i][1],
                                            dets[i][2], dets[i][3],
                                            dets[i][4], dets[i][5],
                                            dets[i][6], dets[i][7]])
        polys.append(tm_polygon)
    order = scores.argsort()[::-1]

    keep = []
    while order.size > 0:
        ovr = []
        i = order[0]
        keep.append(i)
        for j in range(order.size - 1):
            iou = polyiou.iou_poly(polys[i], polys[order[j + 1]])
            ovr.append(iou)
        ovr = np.array(ovr)
        inds = np.where(ovr <= thresh)[0]
        order = order[inds + 1]
    return keep

def detectron2_rota_nms(dets, cls_name):

    keep = None
    # try:
    scores = dets[:, 8]
    thresh = float(threshold[cls_name])
    rbox = batch_polygonToRotRectangle(torch.from_numpy(dets[:, 0:8])).to(torch.device('cuda'))
    keep = nms_rotated(rbox, torch.from_numpy(scores).to(torch.device('cuda')), thresh)
    keep = keep.to(torch.device('cpu')).numpy()

    return keep

def py_cpu_nms(dets, thresh):
    """Pure Python NMS baseline."""
    #print('dets:', dets)
    x1 = dets[:, 0]
    y1 = dets[:, 1]
    x2 = dets[:, 2]
    y2 = dets[:, 3]
    scores = dets[:, 4]

    areas = (x2 - x1 + 1) * (y2 - y1 + 1)
    ## index for dets
    order = scores.argsort()[::-1]

    keep = []
    while order.size > 0:
        i = order[0]
        keep.append(i)
        xx1 = np.maximum(x1[i], x1[order[1:]])
        yy1 = np.maximum(y1[i], y1[order[1:]])
        xx2 = np.minimum(x2[i], x2[order[1:]])
        yy2 = np.minimum(y2[i], y2[order[1:]])

        w = np.maximum(0.0, xx2 - xx1 + 1)
        h = np.maximum(0.0, yy2 - yy1 + 1)
        inter = w * h
        ovr = inter / (areas[i] + areas[order[1:]] - inter)

        inds = np.where(ovr <= thresh)[0]
        order = order[inds + 1]

    return keep

def nmsbynamedict(nameboxdict, nms, cat_name):
    nameboxnmsdict = {x: [] for x in nameboxdict}
    for imgname in tqdm.tqdm(nameboxdict):
        #print('imgname:', imgname)
        #keep = py_cpu_nms(np.array(nameboxdict[imgname]), thresh)
        #print('type nameboxdict:', type(nameboxnmsdict))
        #print('type imgname:', type(imgname))
        #print('type nms:', type(nms))
        keep = nms(np.array(nameboxdict[imgname]), cat_name)
        #print('keep:', keep)
        outdets = []
        #print('nameboxdict[imgname]: ', nameboxnmsdict[imgname])
        for index in keep:
            # print('index:', index)
            outdets.append(nameboxdict[imgname][index])
        nameboxnmsdict[imgname] = outdets
    return nameboxnmsdict
def poly2origpoly(poly, x, y, rate):
    origpoly = []
    for i in range(int(len(poly)/2)):
        tmp_x = float(poly[i * 2] + x) / float(rate)
        tmp_y = float(poly[i * 2 + 1] + y) / float(rate)
        origpoly.append(tmp_x)
        origpoly.append(tmp_y)
    return origpoly

def mergebase(srcpath, dstpath, nms, dota=1):
    filelist = util.GetFileFromThisRootDir(srcpath)
    for fullname in filelist:
        name = util.custombasename(fullname)
        # print('name:', name)
        dstname = os.path.join(dstpath, name + '.txt')
        with open(fullname, 'r') as f_in:
            nameboxdict = {}
            lines = f_in.readlines()
            splitlines = [x.strip().split(' ') for x in lines]
            print("Runninng file merge: {}, numbers: {}".format(name, len(splitlines)))
            for splitline in splitlines:
                subname = splitline[0]
                splitname = subname.split('__')
                oriname = splitname[0]
                pattern1 = re.compile(r'__\d+___\d+')
                #print('subname:', subname)
                x_y = re.findall(pattern1, subname)
                x_y_2 = re.findall(r'\d+', x_y[0])
                x, y = int(x_y_2[0]), int(x_y_2[1])

                pattern2 = re.compile(r'__([\d+\.]+)__\d+___')

                rate = re.findall(pattern2, subname)[0]

                confidence = splitline[1]
                poly = list(map(float, splitline[2:]))
                origpoly = poly2origpoly(poly, x, y, rate)
                det = origpoly
                det.append(confidence)
                det = list(map(float, det))
                if (oriname not in nameboxdict):
                    nameboxdict[oriname] = []
                nameboxdict[oriname].append(det)
                cat_name = name.split('_')[-1]
            nameboxnmsdict = nmsbynamedict(nameboxdict, nms, cat_name)
            with open(dstname, 'w') as f_out:
                for imgname in nameboxnmsdict:
                    for det in nameboxnmsdict[imgname]:
                        #print('det:', det)
                        confidence = det[-1]
                        bbox = det[0:-1]
                        x1, y1, x2, y2, x3, y3, x4, y4 = bbox
                        if dota == 1:
                            line = f"{x1:.1f} {y1:.1f} {x2:.1f} {y2:.1f} {x3:.1f} {y3:.1f} {x4:.1f} {y4:.1f}"
                        if dota == 2:
                            line = f"{x1:.0f} {y1:.0f} {x2:.0f} {y2:.0f} {x3:.0f} {y3:.0f} {x4:.0f} {y4:.0f}"
                        outline = imgname + ' ' + str(confidence) + ' ' + line
                        #print('outline:', outline)
                        f_out.write(outline + '\n')
def mergebyrec(srcpath, dstpath):
    """
    srcpath: result files before merge and nms
    dstpath: result files after merge and nms
    """
    # srcpath = r'E:\bod-dataset\results\bod-v3_rfcn_2000000'
    # dstpath = r'E:\bod-dataset\results\bod-v3_rfcn_2000000_nms'

    mergebase(srcpath,
              dstpath,
              py_cpu_nms)
def mergebypoly(srcpath, dstpath, dota=1):
    """
    srcpath: result files before merge and nms
    dstpath: result files after merge and nms
    """
    # srcpath = r'/home/dingjian/evaluation_task1/result/faster-rcnn-59/comp4_test_results'
    # dstpath = r'/home/dingjian/evaluation_task1/result/faster-rcnn-59/testtime'

    mergebase(srcpath,
              dstpath,
              detectron2_rota_nms, dota)
if __name__ == '__main__':
    # see demo for example
    mergebypoly(r'path_to_configure', r'path_to_configure')
    # mergebyrec()


import importlib
import os
import sys
from typing import TYPE_CHECKING

__version__ = "0.19.0.dev0"

# Alphabetical order of definitions is ensured in tests
# WARNING: any comment added in this dictionary definition will be lost when
# re-generating the file !
_SUBMOD_ATTRS = {
    "_commit_scheduler": [
        "CommitScheduler",
    ],
    "_inference_endpoints": [
        "InferenceEndpoint",
        "InferenceEndpointError",
        "InferenceEndpointStatus",
        "InferenceEndpointTimeoutError",
        "InferenceEndpointType",
    ],
    "_login": [
        "interpreter_login",
        "login",
        "logout",
        "notebook_login",
    ],
    "_multi_commits": [
        "MultiCommitException",
        "plan_multi_commits",
    ],
    "_snapshot_download": [
        "snapshot_download",
    ],
    "_space_api": [
        "SpaceHardware",
        "SpaceRuntime",
        "SpaceStage",
        "SpaceStorage",
        "SpaceVariable",
    ],
    "_tensorboard_logger": [
        "HFSummaryWriter",
    ],
    "_webhooks_payload": [
        "WebhookPayload",
        "WebhookPayloadComment",
        "WebhookPayloadDiscussion",
        "WebhookPayloadDiscussionChanges",
        "WebhookPayloadEvent",
        "WebhookPayloadMovedTo",
        "WebhookPayloadRepo",
        "WebhookPayloadUrl",
        "WebhookPayloadWebhook",
    ],
    "_webhooks_server": [
        "WebhooksServer",
        "webhook_endpoint",
    ],
    "community": [
        "Discussion",
        "DiscussionComment",
        "DiscussionCommit",
        "DiscussionEvent",
        "DiscussionStatusChange",
        "DiscussionTitleChange",
        "DiscussionWithDetails",
    ],
    "constants": [
        "CONFIG_NAME",
        "FLAX_WEIGHTS_NAME",
        "HUGGINGFACE_CO_URL_HOME",
        "HUGGINGFACE_CO_URL_TEMPLATE",
        "PYTORCH_WEIGHTS_NAME",
        "REPO_TYPE_DATASET",
        "REPO_TYPE_MODEL",
        "REPO_TYPE_SPACE",
        "TF2_WEIGHTS_NAME",
        "TF_WEIGHTS_NAME",
    ],
    "fastai_utils": [
        "_save_pretrained_fastai",
        "from_pretrained_fastai",
        "push_to_hub_fastai",
    ],
    "file_download": [
        "HfFileMetadata",
        "_CACHED_NO_EXIST",
        "cached_download",
        "get_hf_file_metadata",
        "hf_hub_download",
        "hf_hub_url",
        "try_to_load_from_cache",
    ],
    "hf_api": [
        "Collection",
        "CollectionItem",
        "CommitInfo",
        "CommitOperation",
        "CommitOperationAdd",
        "CommitOperationCopy",
        "CommitOperationDelete",
        "GitCommitInfo",
        "GitRefInfo",
        "GitRefs",
        "HfApi",
        "RepoUrl",
        "User",
        "UserLikes",
        "add_collection_item",
        "add_space_secret",
        "add_space_variable",
        "change_discussion_status",
        "comment_discussion",
        "create_branch",
        "create_collection",
        "create_commit",
        "create_commits_on_pr",
        "create_discussion",
        "create_inference_endpoint",
        "create_pull_request",
        "create_repo",
        "create_tag",
        "dataset_info",
        "delete_branch",
        "delete_collection",
        "delete_collection_item",
        "delete_file",
        "delete_folder",
        "delete_inference_endpoint",
        "delete_repo",
        "delete_space_secret",
        "delete_space_storage",
        "delete_space_variable",
        "delete_tag",
        "duplicate_space",
        "edit_discussion_comment",
        "file_exists",
        "get_collection",
        "get_dataset_tags",
        "get_discussion_details",
        "get_full_repo_name",
        "get_inference_endpoint",
        "get_model_tags",
        "get_repo_discussions",
        "get_space_runtime",
        "get_space_variables",
        "get_token_permission",
        "like",
        "list_datasets",
        "list_files_info",
        "list_inference_endpoints",
        "list_liked_repos",
        "list_metrics",
        "list_models",
        "list_repo_commits",
        "list_repo_files",
        "list_repo_likers",
        "list_repo_refs",
        "list_spaces",
        "merge_pull_request",
        "model_info",
        "move_repo",
        "pause_inference_endpoint",
        "pause_space",
        "preupload_lfs_files",
        "rename_discussion",
        "repo_exists",
        "repo_info",
        "repo_type_and_id_from_hf_id",
        "request_space_hardware",
        "request_space_storage",
        "restart_space",
        "resume_inference_endpoint",
        "run_as_future",
        "scale_to_zero_inference_endpoint",
        "set_space_sleep_time",
        "space_info",
        "super_squash_history",
        "unlike",
        "update_collection_item",
        "update_collection_metadata",
        "update_inference_endpoint",
        "update_repo_visibility",
        "upload_file",
        "upload_folder",
        "whoami",
    ],
    "hf_file_system": [
        "HfFileSystem",
        "HfFileSystemFile",
        "HfFileSystemResolvedPath",
    ],
    "hub_mixin": [
        "ModelHubMixin",
        "PyTorchModelHubMixin",
    ],
    "inference._client": [
        "InferenceClient",
        "InferenceTimeoutError",
    ],
    "inference._generated._async_client": [
        "AsyncInferenceClient",
    ],
    "inference_api": [
        "InferenceApi",
    ],
    "keras_mixin": [
        "KerasModelHubMixin",
        "from_pretrained_keras",
        "push_to_hub_keras",
        "save_pretrained_keras",
    ],
    "repocard": [
        "DatasetCard",
        "ModelCard",
        "RepoCard",
        "SpaceCard",
        "metadata_eval_result",
        "metadata_load",
        "metadata_save",
        "metadata_update",
    ],
    "repocard_data": [
        "CardData",
        "DatasetCardData",
        "EvalResult",
        "ModelCardData",
        "SpaceCardData",
    ],
    "repository": [
        "Repository",
    ],
    "utils": [
        "CacheNotFound",
        "CachedFileInfo",
        "CachedRepoInfo",
        "CachedRevisionInfo",
        "CorruptedCacheException",
        "DeleteCacheStrategy",
        "HFCacheInfo",
        "HfFolder",
        "cached_assets_path",
        "configure_http_backend",
        "dump_environment_info",
        "get_session",
        "logging",
        "scan_cache_dir",
    ],
    "utils.endpoint_helpers": [
        "DatasetFilter",
        "ModelFilter",
    ],
}

def _attach(package_name, submodules=None, submod_attrs=None):
    """Attach lazily loaded submodules, functions, or other attributes.

    Typically, modules import submodules and attributes as follows:

    ```py
    import mysubmodule
    import anothersubmodule

    from .foo import someattr
    ```

    The idea is to replace a package's `__getattr__`, `__dir__`, and
    `__all__`, such that all imports work exactly the way they would
    with normal imports, except that the import occurs upon first use.

    The typical way to call this function, replacing the above imports, is:

    ```python
    __getattr__, __dir__, __all__ = lazy.attach(
        __name__,
        ['mysubmodule', 'anothersubmodule'],
        {'foo': ['someattr']}
    )
    ```
    This functionality requires Python 3.7 or higher.

    Args:
        package_name (`str`):
            Typically use `__name__`.
        submodules (`set`):
            List of submodules to attach.
        submod_attrs (`dict`):
            Dictionary of submodule -> list of attributes / functions.
            These attributes are imported as they are used.

    Returns:
        __getattr__, __dir__, __all__

    """
    if submod_attrs is None:
        submod_attrs = {}

    if submodules is None:
        submodules = set()
    else:
        submodules = set(submodules)

    attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs}

    __all__ = list(submodules | attr_to_modules.keys())

    def __getattr__(name):
        if name in submodules:
            return importlib.import_module(f"{package_name}.{name}")
        elif name in attr_to_modules:
            submod_path = f"{package_name}.{attr_to_modules[name]}"
            submod = importlib.import_module(submod_path)
            attr = getattr(submod, name)

            # If the attribute lives in a file (module) with the same
            # name as the attribute, ensure that the attribute and *not*
            # the module is accessible on the package.
            if name == attr_to_modules[name]:
                pkg = sys.modules[package_name]
                pkg.__dict__[name] = attr

            return attr
        else:
            raise AttributeError(f"No {package_name} attribute {name}")

    def __dir__():
        return __all__

    if os.environ.get("EAGER_IMPORT", ""):
        for attr in set(attr_to_modules.keys()) | submodules:
            __getattr__(attr)

    return __getattr__, __dir__, list(__all__)

__getattr__, __dir__, __all__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS)

# WARNING: any content below this statement is generated automatically. Any manual edit
# will be lost when re-generating this file !
#
# To update the static imports, please run the following command and commit the changes.
# ```
# # Use script
# python utils/check_static_imports.py --update-file
#
# # Or run style on codebase
# make style
# ```
if TYPE_CHECKING:  # pragma: no cover
    from ._commit_scheduler import CommitScheduler  # noqa: F401
    from ._inference_endpoints import (
        InferenceEndpoint,  # noqa: F401
        InferenceEndpointError,  # noqa: F401
        InferenceEndpointStatus,  # noqa: F401
        InferenceEndpointTimeoutError,  # noqa: F401
        InferenceEndpointType,  # noqa: F401
    )
    from ._login import (
        interpreter_login,  # noqa: F401
        login,  # noqa: F401
        logout,  # noqa: F401
        notebook_login,  # noqa: F401
    )
    from ._multi_commits import (
        MultiCommitException,  # noqa: F401
        plan_multi_commits,  # noqa: F401
    )
    from ._snapshot_download import snapshot_download  # noqa: F401
    from ._space_api import (
        SpaceHardware,  # noqa: F401
        SpaceRuntime,  # noqa: F401
        SpaceStage,  # noqa: F401
        SpaceStorage,  # noqa: F401
        SpaceVariable,  # noqa: F401
    )
    from ._tensorboard_logger import HFSummaryWriter  # noqa: F401
    from ._webhooks_payload import (
        WebhookPayload,  # noqa: F401
        WebhookPayloadComment,  # noqa: F401
        WebhookPayloadDiscussion,  # noqa: F401
        WebhookPayloadDiscussionChanges,  # noqa: F401
        WebhookPayloadEvent,  # noqa: F401
        WebhookPayloadMovedTo,  # noqa: F401
        WebhookPayloadRepo,  # noqa: F401
        WebhookPayloadUrl,  # noqa: F401
        WebhookPayloadWebhook,  # noqa: F401
    )
    from ._webhooks_server import (
        WebhooksServer,  # noqa: F401
        webhook_endpoint,  # noqa: F401
    )
    from .community import (
        Discussion,  # noqa: F401
        DiscussionComment,  # noqa: F401
        DiscussionCommit,  # noqa: F401
        DiscussionEvent,  # noqa: F401
        DiscussionStatusChange,  # noqa: F401
        DiscussionTitleChange,  # noqa: F401
        DiscussionWithDetails,  # noqa: F401
    )
    from .constants import (
        CONFIG_NAME,  # noqa: F401
        FLAX_WEIGHTS_NAME,  # noqa: F401
        HUGGINGFACE_CO_URL_HOME,  # noqa: F401
        HUGGINGFACE_CO_URL_TEMPLATE,  # noqa: F401
        PYTORCH_WEIGHTS_NAME,  # noqa: F401
        REPO_TYPE_DATASET,  # noqa: F401
        REPO_TYPE_MODEL,  # noqa: F401
        REPO_TYPE_SPACE,  # noqa: F401
        TF2_WEIGHTS_NAME,  # noqa: F401
        TF_WEIGHTS_NAME,  # noqa: F401
    )
    from .fastai_utils import (
        _save_pretrained_fastai,  # noqa: F401
        from_pretrained_fastai,  # noqa: F401
        push_to_hub_fastai,  # noqa: F401
    )
    from .file_download import (
        _CACHED_NO_EXIST,  # noqa: F401
        HfFileMetadata,  # noqa: F401
        cached_download,  # noqa: F401
        get_hf_file_metadata,  # noqa: F401
        hf_hub_download,  # noqa: F401
        hf_hub_url,  # noqa: F401
        try_to_load_from_cache,  # noqa: F401
    )
    from .hf_api import (
        Collection,  # noqa: F401
        CollectionItem,  # noqa: F401
        CommitInfo,  # noqa: F401
        CommitOperation,  # noqa: F401
        CommitOperationAdd,  # noqa: F401
        CommitOperationCopy,  # noqa: F401
        CommitOperationDelete,  # noqa: F401
        GitCommitInfo,  # noqa: F401
        GitRefInfo,  # noqa: F401
        GitRefs,  # noqa: F401
        HfApi,  # noqa: F401
        RepoUrl,  # noqa: F401
        User,  # noqa: F401
        UserLikes,  # noqa: F401
        add_collection_item,  # noqa: F401
        add_space_secret,  # noqa: F401
        add_space_variable,  # noqa: F401
        change_discussion_status,  # noqa: F401
        comment_discussion,  # noqa: F401
        create_branch,  # noqa: F401
        create_collection,  # noqa: F401
        create_commit,  # noqa: F401
        create_commits_on_pr,  # noqa: F401
        create_discussion,  # noqa: F401
        create_inference_endpoint,  # noqa: F401
        create_pull_request,  # noqa: F401
        create_repo,  # noqa: F401
        create_tag,  # noqa: F401
        dataset_info,  # noqa: F401
        delete_branch,  # noqa: F401
        delete_collection,  # noqa: F401
        delete_collection_item,  # noqa: F401
        delete_file,  # noqa: F401
        delete_folder,  # noqa: F401
        delete_inference_endpoint,  # noqa: F401
        delete_repo,  # noqa: F401
        delete_space_secret,  # noqa: F401
        delete_space_storage,  # noqa: F401
        delete_space_variable,  # noqa: F401
        delete_tag,  # noqa: F401
        duplicate_space,  # noqa: F401
        edit_discussion_comment,  # noqa: F401
        file_exists,  # noqa: F401
        get_collection,  # noqa: F401
        get_dataset_tags,  # noqa: F401
        get_discussion_details,  # noqa: F401
        get_full_repo_name,  # noqa: F401
        get_inference_endpoint,  # noqa: F401
        get_model_tags,  # noqa: F401
        get_repo_discussions,  # noqa: F401
        get_space_runtime,  # noqa: F401
        get_space_variables,  # noqa: F401
        get_token_permission,  # noqa: F401
        like,  # noqa: F401
        list_datasets,  # noqa: F401
        list_files_info,  # noqa: F401
        list_inference_endpoints,  # noqa: F401
        list_liked_repos,  # noqa: F401
        list_metrics,  # noqa: F401
        list_models,  # noqa: F401
        list_repo_commits,  # noqa: F401
        list_repo_files,  # noqa: F401
        list_repo_likers,  # noqa: F401
        list_repo_refs,  # noqa: F401
        list_spaces,  # noqa: F401
        merge_pull_request,  # noqa: F401
        model_info,  # noqa: F401
        move_repo,  # noqa: F401
        pause_inference_endpoint,  # noqa: F401
        pause_space,  # noqa: F401
        preupload_lfs_files,  # noqa: F401
        rename_discussion,  # noqa: F401
        repo_exists,  # noqa: F401
        repo_info,  # noqa: F401
        repo_type_and_id_from_hf_id,  # noqa: F401
        request_space_hardware,  # noqa: F401
        request_space_storage,  # noqa: F401
        restart_space,  # noqa: F401
        resume_inference_endpoint,  # noqa: F401
        run_as_future,  # noqa: F401
        scale_to_zero_inference_endpoint,  # noqa: F401
        set_space_sleep_time,  # noqa: F401
        space_info,  # noqa: F401
        super_squash_history,  # noqa: F401
        unlike,  # noqa: F401
        update_collection_item,  # noqa: F401
        update_collection_metadata,  # noqa: F401
        update_inference_endpoint,  # noqa: F401
        update_repo_visibility,  # noqa: F401
        upload_file,  # noqa: F401
        upload_folder,  # noqa: F401
        whoami,  # noqa: F401
    )
    from .hf_file_system import (
        HfFileSystem,  # noqa: F401
        HfFileSystemFile,  # noqa: F401
        HfFileSystemResolvedPath,  # noqa: F401
    )
    from .hub_mixin import (
        ModelHubMixin,  # noqa: F401
        PyTorchModelHubMixin,  # noqa: F401
    )
    from .inference._client import (
        InferenceClient,  # noqa: F401
        InferenceTimeoutError,  # noqa: F401
    )
    from .inference._generated._async_client import AsyncInferenceClient  # noqa: F401
    from .inference_api import InferenceApi  # noqa: F401
    from .keras_mixin import (
        KerasModelHubMixin,  # noqa: F401
        from_pretrained_keras,  # noqa: F401
        push_to_hub_keras,  # noqa: F401
        save_pretrained_keras,  # noqa: F401
    )
    from .repocard import (
        DatasetCard,  # noqa: F401
        ModelCard,  # noqa: F401
        RepoCard,  # noqa: F401
        SpaceCard,  # noqa: F401
        metadata_eval_result,  # noqa: F401
        metadata_load,  # noqa: F401
        metadata_save,  # noqa: F401
        metadata_update,  # noqa: F401
    )
    from .repocard_data import (
        CardData,  # noqa: F401
        DatasetCardData,  # noqa: F401
        EvalResult,  # noqa: F401
        ModelCardData,  # noqa: F401
        SpaceCardData,  # noqa: F401
    )
    from .repository import Repository  # noqa: F401
    from .utils import (
        CachedFileInfo,  # noqa: F401
        CachedRepoInfo,  # noqa: F401
        CachedRevisionInfo,  # noqa: F401
        CacheNotFound,  # noqa: F401
        CorruptedCacheException,  # noqa: F401
        DeleteCacheStrategy,  # noqa: F401
        HFCacheInfo,  # noqa: F401
        HfFolder,  # noqa: F401
        cached_assets_path,  # noqa: F401
        configure_http_backend,  # noqa: F401
        dump_environment_info,  # noqa: F401
        get_session,  # noqa: F401
        logging,  # noqa: F401
        scan_cache_dir,  # noqa: F401
    )
    from .utils.endpoint_helpers import (
        DatasetFilter,  # noqa: F401
        ModelFilter,  # noqa: F401
    )


"""
This module contains functions that help evaluate trained models.
"""
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, TimeSeriesSplit

def split(df, label_colname, test_size, seed):
    """
    Splits a dataset into training and testing dataframes.
    """
    X = df.drop(columns=[label_colname]).values
    y = df[label_colname].values
    X_train, X_test, y_train, y_test = \
        train_test_split(X, y, test_size=test_size, random_state=seed)

    df_train = pd.DataFrame(np.column_stack((X_train, y_train)),
                            columns=df.columns)
    df_test = pd.DataFrame(np.column_stack((X_test, y_test)),
                            columns=df.columns)
    return df_train, df_test

def time_split(df, n_splits):
    """
    Splits a dataframe ordered by a datetime. Training sets are supersets of
    earlier sets.

    The data will be partitioned into n_splits + 1 segments. The first split
    uses the first segment as the training set and the second segment as the
    test set. The second split uses the first and second segment as the
    training set and the third segment as the test set etc.
    """
    splitter = TimeSeriesSplit(n_splits)
    splits = splitter.split(df.values)
    return [(df.iloc[train_i], df.iloc[test_i]) for train_i, test_i in splits]


import cv2

vid_capture = cv2.VideoCapture(0)

# frame_width = int(vid_capture.get(3))

vid_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
vid_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
frame_width = 1280
# frame_height = int(vid_capture.get(4))
frame_height = 720
frame_size = (frame_width, frame_height)
fps = 30
frames = 100

fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
video_writer = cv2.VideoWriter('../../media/usb/output.avi', fourcc, fps, frame_size)

cap = cv2.VideoCapture(0)

for i in range(frames):
    ret, frame = cap.read()
    # cv2.imshow('frame', frame)
    if not ret:
        break
    video_writer.write(frame)

video_writer.release()
cap.release()


import os
import json
import numpy as np
from soundfile import SoundFile

def gen_json():
    ls = os.listdir('./tokens')
    data = map(lambda v: v.split('.')[0], ls)

    with open('tokens.json', 'w') as f:
        data = json.dumps(list(data))
        f.write(data)
    print('ok')

def gen_blank_audio():
    with SoundFile('tokens/_.wav', 'w', 44100, 1) as f:
        f.write(np.zeros(11025))

if __name__ == '__main__':
    gen_json()


from kivy.uix.screenmanager import ScreenManager, SlideTransition

import decks.starting
import decks.summer
import decks.test
import decks.terraforming

import galaxy_gen

import numpy as np

stats = {
    'male_baby_count':0,'male_baby_approval':0,
    'female_baby_count':0,'female_baby_approval':0,
    'male_child_count':0,'male_child_approval':0,
    'female_child_count':0,'female_child_approval':0,
    'male_teen_count':0,'male_teen_approval':0,
    'female_teen_count':0,'female_teen_approval':0,

    'male_settler_count':45,'male_settler_approval':50,
    'female_settler_count':45,'female_settler_approval':50,
    'male_farmer_count':5,'male_farmer_approval':50,
    'female_farmer_count':5,'female_farmer_approval':50,

    'habitat_modules':20,'habitat_condition':100,'habitat_space_used':10,

    'greenhouse_modules':10,'greenhouse_condition':100,'greenhouse_space_used':2,'greenhouse_fertility':100,

    'food_reserves':500,'food_storage':1000,'food_production':200,'food_consumption':100,

    'atmosphere_percentage':0,
    'ocean_percentage':0,'arable_percentage':0,

    'year':0,
    'day':1,
    'hour':0,

    'current_card_id':''
}

#galaxy_stats = galaxy_gen.stats_gen()
#print(galaxy_stats)

sm = ScreenManager(transition=SlideTransition())

main_deck = decks.starting.deck.copy()

all_unused_cards = decks.terraforming.deck.copy() | decks.summer.deck.copy()

# Create an empty dictionary that will hold all_used_cards.
all_used_cards = {}

# Create the 'on deck' deck, where cards go once selected, but before actually added to the main deck.
to_be_added = {}


from twython import Twython
import random

quotes = [  'Quote example!'
         ]

APP_KEY = ""  # get these from making a twitter dev account
APP_SECRET = ""
OAUTH_TOKEN = ""
OAUTH_TOKEN_SECRET = ""
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
print(auth)
twitter = Twython(APP_KEY, APP_SECRET,
OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
credentials = twitter.verify_credentials()
twitter.update_status(status=random.choice(quotes))

#can be run from command line, I ran mine using chron on a raspberry pi 3
#I liked twython the most out of all the twitter packages I tried


import pytest

from leetcode.triplets_sum import Solution

@pytest.mark.parametrize('arr,ans', [
  ([-2, -1, 1, 0], [[-1, 0, 1]]),
  ([-2, -1, 1, 2, 3, -3, 0], [[-2, 0, 2], [-1, 0, 1], [-3, 0, 3], [-2, -1, 3], [-3, 1, 2]]),
])
def test_triplets_sum(arr, ans):
  res = Solution.threeSum(arr)
  assert len(res) == len(ans)
  for a in ans:
    assert a in res


# -*- coding: utf-8 -*-
# __author__ = 'qingmei'
# last_modify: 2018.08.15

from biocluster.agent import Agent
from biocluster.tool import Tool
from biocluster.core.exceptions import OptionError
import os
from bson.objectid import ObjectId

class RegionAnnoAgent(Agent):
    """
    基因注释接口
    一个controller和一个tool,一个api
    对应脚本cmd: region-gene.pl cmd: eff-enrich.R
    region_path,前三列只要是chrid start end就可以，位置信息有重复也没关系
    """
    def __init__(self, parent):
        super(RegionAnnoAgent, self).__init__(parent)
        options = [
            {"name": "main_id", "type": "string"},  #
            {"name": "task_id", "type": "string"},  #
            {"name": "pop_summary_path", "type": "infile", "format": "dna_evolution.pop_summary"},
            # {"name": "pop_summary_path", "type": "string"},     # 已经是绝对路径，待写成infile核查
            {"name": "region_path", "type": "infile", "format": "dna_evolution.bed"},    # sg_anno_params的region_path
            {"name": "update_info", "type": "string"},
            {"name": "go_summary_path", "type": "infile", "format": "dna_evolution.pop_enrich"},
            {"name": "genome_version_id", "type": "string"},
            {"name": "pathway_path", "type": "string"}  # 对象存储路径
        ]
        self.add_option(options)
        self.step.add_steps("region_anno")
        self.on('start', self.stepstart)
        self.on('end', self.stepfinish)

    def stepstart(self):
        self.step.region_anno.start()
        self.step.update()

    def stepfinish(self):
        self.step.region_anno.finish()
        self.step.update()

    def check_options(self):
        """
        重写参数检测函数
        :return:
        """
        if not self.option('pop_summary_path'):
            raise OptionError('必须输入pop_summary_path')
        if not self.option('region_path'):
            raise OptionError('必须输入region_path')
        if not self.option('main_id'):
            raise OptionError('必须输入main_id')
        if not self.option('task_id'):
            raise OptionError('必须输入task_id')
        if not self.option('genome_version_id'):
            raise OptionError('必须输入genome_version_id')
        if not self.option("pathway_path"):
            raise OptionError("请设置pathway_path")

    def set_resource(self):
        """
        设置所需资源，需在之类中重写此方法 self._cpu ,self._memory
        :return:
        """
        self._cpu = 2
        self._memory = "6G"

class RegionAnnoTool(Tool):
    def __init__(self, config):
        super(RegionAnnoTool, self).__init__(config)
        self._version = "v1.0.1"
        self.perl_path = 'miniconda2/bin/perl '
        self.R_path = 'program/R-3.3.1/bin/Rscript '
        self.region_gene_path = self.config.PACKAGE_DIR + '/dna_evolution/region-gene.pl'
        self.effR_path = self.config.PACKAGE_DIR + '/dna_evolution/eff-enrich.R'
        self.set_environ(LD_LIBRARY_PATH=self.config.SOFTWARE_DIR + '/gcc/5.4.0/lib64')
        self.image_magick = self.config.SOFTWARE_DIR + "/program/ImageMagick/bin/convert"
        self.ko_path = self.config.SOFTWARE_DIR + '/database/KEGG/kegg_2017-05-01/kegg/pathway/ko/'
        self.parafly = "program/parafly-r2013-01-21/src/ParaFly"

    # def get_select_region(self):
    #     """
    #     把传进来的region还原成文件
    #     eg：chr1-123-234;chr2-345-567;
    #     """
    #     region_list = self.option('select_region').split(';')
    #     with open(self.work_dir + '/select.region', 'w') as fw:
    #         fw.write('#chr\tstart\tend\n')
    #         for i in region_list:
    #             line_list = i.split('-')
    #             fw.write('\t'.join(line_list) + '\n')
    #     self.logger.info('~~~~~~select.region文件生成成功')

    def run_region_gene(self):
        """
        输入pop.summary select(三列信息，chrid start end)
        运行eff-enrich.R,计算注释统计
        """
        cmd = "{} {}".format(self.perl_path, self.region_gene_path)
        cmd += " -a {} -i {}".format(self.option('pop_summary_path').prop['path'],
                                     self.option('region_path').prop['path'])
        cmd += " -o {}".format(self.work_dir + "/select_region")
        self.logger.info('开始运行region_gene提取')
        self.run_cmd(cmd, "region_gene")

    def run_eff_detail(self, type_):
        """
        """
        cmd = "{} {}".format(self.R_path, self.effR_path)
        cmd += " --input {}".format(self.work_dir + "/select_region." + type_ + ".stat")
        cmd += " --output {}".format(self.output_dir + "/select_region." + type_ + ".stat")
        if type_ == 'eggnog':
            cmd += " --eggnog"
        else:
            cmd += " --top 1"
        self.logger.info('开始运行effrich.R注释统计:' + type_)
        self.run_cmd(cmd, "eff_detail_" + type_)

    def run_get_picture(self):
        """
        根据ko号找到对应的所有ko的pdf和png文件-- 添加如果存在pathway_dir就将该文件夹删除 add by hongdong 20180301
        :return:
        """
        if os.path.isdir(self.output_dir + '/pathway_dir'):
            os.system('rm -r %s' % os.path.join(self.output_dir, '/pathway_dir'))
        self.num = 0
        cmd_list = []
        os.system("mkdir {}".format(self.output_dir + '/pathway_dir'))
        all_ko = os.listdir(self.ko_path)
        with open(self.work_dir + "/select_region.kegg.stat")as fr:
            for line in fr:
                tmp = line.strip().split('\t')
                ko_png = tmp[0] + '.png'
                if ko_png in all_ko:
                    ko_path = os.path.join(self.ko_path, ko_png)
                    os.link(ko_path, self.output_dir + '/pathway_dir/' + ko_png)
                    pdf_path = os.path.join(self.output_dir + '/pathway_dir', tmp[0] + '.pdf')
                    cmd = self.image_magick + ' -flatten -quality 100 -density 130 -background white ' + ko_path + ' ' + pdf_path
                    cmd_list.append(cmd)
                else:
                    self.set_error("ko{} png文件在本地数据库{}中没有，请核实!".format(tmp[0], self.ko_path))
        with open(self.work_dir + "/cmd.list", "w") as fw:
            for i in range(len(cmd_list)):
                fw.write(cmd_list[i] + "\n")
        cmd = self.parafly + " -c {} -CPU 10".format(self.work_dir + "/cmd.list")
        cmd_obj = self.add_command("cmd_list", cmd).run()
        self.wait(cmd_obj)
        if cmd_obj.return_code == 0:
            self.logger.info("cmd list执行成功")
        else:
            self.set_error("cmd list运行出错!")

    def run_cmd(self, cmd, cmd_name):
        """
        执行cmd
        """
        command = self.add_command(cmd_name, cmd).run()
        self.wait()
        if command.return_code == 0:
            self.logger.info("{}运行完成".format(cmd_name))
        else:
            self.set_error("{}运行失败".format(cmd_name))
            raise Exception("{}运行失败".format(cmd_name))

    def check_exists(self, file_path):
        """
        用于检查文件及文件夹是否存在
        """
        if not os.path.exists(file_path):
            raise Exception("文件或文件夹{}不存在！".format(file_path))

    def run(self):
        """
        运行
        :return:
        """
        super(RegionAnnoTool, self).run()
        # self.get_select_region()
        self.run_region_gene()
        self.run_eff_detail("kegg")
        self.run_eff_detail("go")
        self.run_eff_detail("eggnog")
        if os.path.exists(self.output_dir + "/select_region.kegg.stat.detail"):
            self.logger.info('kegg')
            # 若结果文件产生了，就证明kegg.stat文件不为空且存在。就运行picture
            self.run_get_picture()
        self.set_db()
        # self.end()

    def set_db(self):
        """
        更新主表的chr_list和path:marker.filtered.marker
        self.filtered_marker_path
        """
        region_id = ObjectId(self.option("main_id"))
        genome_version_id = ObjectId(self.option('genome_version_id'))
        self.logger.info("开始region_anno的导表！")
        api = self.api.api("dna_evolution.region_anno")
        task_id = self.option('task_id')
        # api.get_update_chrlist(marker_id, self.target_dir_ + "/pop.filtered.marker",
        #                        self.target_dir_ + "/pop.filtered.detail.info")
        api.add_sg_region_anno_detail(region_id, self.option('pop_summary_path').prop['path'], genome_version_id)
        api.sg_region_anno_go_stat(task_id, region_id, self.output_dir + "/select_region.go.stat.detail",
                                   self.option('go_summary_path').prop['path'])
        api.sg_region_anno_kegg_stat(task_id, region_id, self.output_dir + "/select_region.kegg.stat.detail",
                                     self.output_dir + "/pathway_dir",
                                     os.path.join(self.option("pathway_path"), "region_anno/pathway_dir"))
        api.sg_region_anno_eggnog_stat(task_id, region_id, self.output_dir + "/select_region.eggnog.stat.detail")
        self.logger.info("设置region_anno的导表成功！")
        self.end()


import requests
import time
import sys
import csv

from requests.packages.urllib3.exceptions import InsecureRequestWarning #this is to ignore insecure HTTPS request to cloud (it doesnt recongize meraki dashboard)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

##Meraki Constants
MERAKI_URL = 'https://dashboard.meraki.com/api/v0/'
headers = {'x-cisco-meraki-api-key': format(str('KEY OBSCURED')),
           'Content-Type': 'application/json'}
OrgKey = 'KEY OBSCURED'

counter = 0

print("Start of Script")
print("\nGathering Organization Info from J.CREW Meraki Organization # : " + OrgKey)

networks = requests.get(MERAKI_URL + 'organizations' + '/' + OrgKey + '/' + 'networks', headers=headers,
                        verify=False).json()

totalnetworks = len(networks)

print("Organization Info Retrieved")

with open('PatrickCSVOutput.csv','w') as csvfile:
 filewriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL,lineterminator='\n')
 filewriter.writerow(['Network Name', 'Device Desc', 'Device VLAN', 'Device MAC', 'Device IP'])
 csvfile.flush()

 for networks in networks:
    counter = counter + 1
    sys.stdout.write("\r ---Pulling info from : " + networks['name'] + "     ("+str(counter)+"/"+str(totalnetworks)+")")
    time.sleep(0.25)
    sys.stdout.flush()

    if 'STR-' in networks['name']:

        devices = requests.get(MERAKI_URL + 'organizations' + '/' + OrgKey +
                               '/' + 'networks' + '/' + networks['id'] + '/' +
                               'devices', headers=headers, verify=False).json()

        for devices in devices:

                if 'MS' in devices['model']:
                    print("\n Now getting Information from " + devices['model'] +
                          " " + devices['serial'])

                    clients = requests.get(MERAKI_URL + 'devices' + '/' + devices['serial'] +
                                           '/' + 'clients?timespan=192000', headers=headers, verify=False).json()
                    # print(clients)
                    try:

                        for clients in clients:
                            # print(clients)
                            if '.15' in str(clients['ip']):
                                filewriter.writerow(
                                    [str(networks['name']), str(clients['description']), str(clients['vlan']),
                                     str(clients['mac']), str(clients['ip'])])

                                print("Network Name : " + networks['name'])
                                print("Device MAC : " + clients['mac'])
                                print("Device Desc : " + str(clients['description']))
                                print("Device mdnsName : " + str(clients['mdnsName']))
                                print("Device dhcpHostname : " + str(clients['dhcpHostname']))
                                print("Device VLAN : " + str(clients['vlan']))
                                print("Device IP : " + str(clients['ip'] + "\n"))

                    except KeyError:
                         print("-Invalid Client Information received, Check Network " + networks['name'])
                    break

print("\nScript is Complete")

csvfile.close()


from __future__ import division

import json
import os

import cv2
import numpy as np
import torch
import torch.distributed as dist
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data.sampler import RandomSampler

from datasets.base_dataset import BaseDataset, BaseTransform, ExemplarTransform
from datasets.transforms import RandomColorJitter

def build_custom_exemplar_dataloader(cfg, training, distributed=True):
    rank = dist.get_rank()

    normalize_fn = transforms.Normalize(mean=cfg["pixel_mean"], std=cfg["pixel_std"])

    if training:
        hflip = cfg.get("hflip", False)
        vflip = cfg.get("vflip", False)
        rotate = cfg.get("rotate", False)
        gamma = cfg.get("gamma", False)
        gray = cfg.get("gray", False)
        transform_fn = BaseTransform(
            cfg["input_size"], hflip, vflip, rotate, gamma, gray
        )
    else:
        transform_fn = BaseTransform(cfg["input_size"], False, False, False, False)

    exemplar_fn = ExemplarTransform(cfg["input_size"])

    if training and cfg.get("colorjitter", None):
        colorjitter_fn = RandomColorJitter.from_params(cfg["colorjitter"])
    else:
        colorjitter_fn = None

    if rank == 0:
        print("building CustomDataset from: {}".format(cfg["meta_file"]))

    dataset = CustomDataset(
        cfg["img_dir"],
        cfg["density_dir"],
        cfg["meta_file"],
        cfg["exemplar"],
        transform_fn=transform_fn,
        exemplar_fn=exemplar_fn,
        normalize_fn=normalize_fn,
        colorjitter_fn=colorjitter_fn,
    )

    if distributed:
        sampler = DistributedSampler(dataset)
    else:
        sampler = RandomSampler(dataset)

    data_loader = DataLoader(
        dataset,
        batch_size=cfg["batch_size"],
        num_workers=cfg["workers"],
        pin_memory=True,
        sampler=sampler,
    )

    return data_loader

class CustomDataset(BaseDataset):
    def __init__(
        self,
        img_dir,
        density_dir,
        meta_file,
        cfg_exemplar,
        transform_fn,
        exemplar_fn,
        normalize_fn,
        colorjitter_fn=None,
    ):
        self.img_dir = img_dir
        self.density_dir = density_dir
        self.meta_file = meta_file
        self.cfg_exemplar = cfg_exemplar
        self.transform_fn = transform_fn
        self.exemplar_fn = exemplar_fn
        self.normalize_fn = normalize_fn
        self.colorjitter_fn = colorjitter_fn

        # construct metas
        with open(meta_file, "r+") as f_r:
            self.metas = []
            for line in f_r:
                meta = json.loads(line)
                self.metas.append(meta)

        # construct exemplar_metas
        exemplar_metas = []
        with open(cfg_exemplar["meta_file"], "r+") as f_r:
            for line in f_r:
                meta = json.loads(line)
                exemplar_metas.append(meta)
        if cfg_exemplar["num_exemplar"] > len(exemplar_metas):
            raise ValueError(
                "num_exemplar must smaller than the length of exemplar_metas!"
            )
        else:
            exemplar_metas = exemplar_metas[0 : cfg_exemplar["num_exemplar"]]

        # construct exemplar list
        exemplar_imgs = []
        exemplar_boxes = []
        for meta in exemplar_metas:
            image = cv2.imread(os.path.join(cfg_exemplar["img_dir"], meta["filename"]))
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            height, width = image.shape[:2]
            # resize to a fix size
            box = meta["box"]
            if self.exemplar_fn:
                image, box = self.exemplar_fn(image, box, (height, width))
            image = transforms.ToTensor()(image)
            box = torch.tensor(box, dtype=torch.float64)
            if cfg_exemplar["norm"] and self.normalize_fn:
                image = self.normalize_fn(image)
            exemplar_imgs.append(image.unsqueeze(0))
            exemplar_boxes.append(box.unsqueeze(0))
        self.exemplar_imgs = torch.cat(exemplar_imgs, dim=0)  # n x c x h x w
        self.exemplar_boxes = torch.cat(exemplar_boxes, dim=0)  # n x c x h x w

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

    def __getitem__(self, index):
        meta = self.metas[index]
        # read img
        img_name = meta["filename"]
        img_path = os.path.join(self.img_dir, img_name)
        image = cv2.imread(img_path)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        height, width = image.shape[:2]
        # read density
        density_name = meta["density"]
        density_path = os.path.join(self.density_dir, density_name)
        density = np.load(density_path)
        # transform
        if self.transform_fn:
            image, density, _, _ = self.transform_fn(
                image, density, [], [], (height, width)
            )
        if self.colorjitter_fn:
            image = self.colorjitter_fn(image)
        image = transforms.ToTensor()(image)
        density = transforms.ToTensor()(density)
        if self.normalize_fn:
            image = self.normalize_fn(image)
        return {
            "filename": img_name,
            "height": height,
            "width": width,
            "image": image,
            "density": density,
            "exemplar_imgs": self.exemplar_imgs,
            "exemplar_boxes": self.exemplar_boxes,
        }


"""HeavyDB data types and SQL dtypes compatibility."""
import ibis.expr.datatypes as dt

sql_to_ibis_dtypes = {
    'BIGINT': dt.int64,
    'BOOL': dt.Boolean,
    'DATE': dt.date,
    'DECIMAL': dt.Decimal(18, 9),
    'DOUBLE': dt.double,
    'FLOAT': dt.float32,
    'INT': dt.int32,
    'LINESTRING': dt.linestring,
    'MULTIPOLYGON': dt.multipolygon,
    'NULL': dt.Null,
    'NUMERIC': dt.Decimal(18, 9),
    'POINT': dt.point,
    'POLYGON': dt.polygon,
    'SMALLINT': dt.int16,
    'STR': dt.string,
    'TIME': dt.time,
    'TIMESTAMP': dt.timestamp,
    'TINYINT': dt.int8,
}

sql_to_ibis_dtypes_str = {
    'BIGINT': 'int64',
    'BOOLEAN': 'Boolean',
    'BOOL': 'Boolean',
    'CHAR': 'string',
    'DATE': 'date',
    'DECIMAL': 'decimal',
    'DOUBLE': 'double',
    'INT': 'int32',
    'INTEGER': 'int32',
    'FLOAT': 'float32',
    'NUMERIC': 'float64',
    'REAL': 'float32',
    'SMALLINT': 'int16',
    'STR': 'string',
    'TEXT': 'string',
    'TIME': 'time',
    'TIMESTAMP': 'timestamp',
    'TINYINT': 'int8',
    'VARCHAR': 'string',
    'POINT': 'point',
    'LINESTRING': 'linestring',
    'POLYGON': 'polygon',
    'MULTIPOLYGON': 'multipolygon',
}

ibis_dtypes_str_to_sql = {
    'boolean': 'boolean',
    'date': 'date',
    'decimal': 'decimal',
    'double': 'double',
    'float32': 'float',
    'float64': 'double',
    'int8': 'tinyint',
    'int16': 'smallint',
    'int32': 'int',
    'int64': 'bigint',
    'linestring': 'linestring',
    'multipolygon': 'multipolygon',
    'point': 'point',
    'polygon': 'polygon',
    'string': 'text',
    'time': 'time',
    'timestamp': 'timestamp',
}

# example: {dt.int64: 'int64'}
ibis_dtypes_to_str = {}
for sql_type, ibis_type in sql_to_ibis_dtypes.items():
    ibis_dtypes_to_str[ibis_type] = str(ibis_type)


import cv2
import re
from flask import Flask, render_template, request, send_file

from image_manipulation import alter_image

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    colora = request.form['color_picker1'].lower()
    colorb = request.form['color_picker2'].lower()
    k = int(request.form['quantity'])
    # Check if k is proper
    if k not in range(2, 256):
        return "Pick a number of colors between 2 and 255.", 400
    # Check if colors properly specified
    if re.match(r'^#?([0-9a-f]{6})$', colora) is None or re.match(r'^#?([0-9a-f]{6})$', colorb) is None:
        return "Provide color in hex format (e.g. #aa12ff).", 400
    # Check if file is empty
    if not file:
        return "No file provided.", 400
    # Check file size
    if len(file.read()) > 20 * 1024 * 1024:  # Max file size: 20MB
        return "File is too large. Max file size 20MB.", 400
    file.seek(0)  # Reset file pointer to beginning
    image = alter_image(file, colora, colorb, k)
    # Save the result to a temporary file on the server
    result_file = 'result.png'
    cv2.imwrite("./static/" + result_file, image)
    # Render the HTML template with the result file name
    return render_template('home.html', result_file=result_file)

@app.route('/download')
def download():
    result_file = 'static/result.png'
    return send_file(result_file, as_attachment=True)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)


from django.urls import path
from django.contrib.auth.decorators import login_required

from .views import BlogListView, BlogCreateView, BlogPostDeleteView, BlogDetailView, BlogUpdateView

app_name = 'blog'
urlpatterns = [
    path('', login_required(BlogListView.as_view()), name='home'),
    path('create/', login_required(BlogCreateView.as_view()), name='create'),
    path('delete/<int:pk>', login_required(BlogPostDeleteView.as_view()), name='delete'),
    path('details/<slug:slug>', login_required(BlogDetailView.as_view()), name='details'),
    path('update/<slug:slug>', login_required(BlogUpdateView.as_view()), name='update'),
]


"""
Testing utilities backported from recent Django versions, for testing with
older Django versions.

"""
from __future__ import with_statement

from cStringIO import StringIO
import urllib
from urlparse import urlparse

from django.conf import settings, UserSettingsHolder
from django.core.handlers.wsgi import WSGIRequest
from django.http import SimpleCookie
from django.test.client import (
    encode_multipart, FakePayload, BOUNDARY, MULTIPART_CONTENT, CONTENT_TYPE_RE)
from django.utils.encoding import smart_str
from django.utils.functional import wraps
from django.utils.http import urlencode

class override_settings(object):
    """
    Acts as either a decorator, or a context manager. If it's a decorator it
    takes a function and returns a wrapped function. If it's a contextmanager
    it's used with the ``with`` statement. In either event entering/exiting
    are called before and after, respectively, the function/block is executed.

    """
    def __init__(self, **kwargs):
        self.options = kwargs
        self.wrapped = settings._wrapped

    def __enter__(self):
        self.enable()

    def __exit__(self, exc_type, exc_value, traceback):
        self.disable()

    def __call__(self, func):
        @wraps(func)
        def inner(*args, **kwargs):
            with self:
                return func(*args, **kwargs)
        return inner

    def enable(self):
        override = UserSettingsHolder(settings._wrapped)
        for key, new_value in self.options.items():
            setattr(override, key, new_value)
        settings._wrapped = override

    def disable(self):
        settings._wrapped = self.wrapped

class RequestFactory(object):
    """
    Class that lets you create mock Request objects for use in testing.

    Usage:

    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})

    Once you have a request object you can pass it to any view function,
    just as if that view had been hooked up using a URLconf.
    """
    def __init__(self, **defaults):
        self.defaults = defaults
        self.cookies = SimpleCookie()
        self.errors = StringIO()

    def _base_environ(self, **request):
        """
        The base environment for a request.
        """
        environ = {
            'HTTP_COOKIE':       self.cookies.output(header='', sep='; '),
            'PATH_INFO':         '/',
            'QUERY_STRING':      '',
            'REMOTE_ADDR':       '127.0.0.1',
            'REQUEST_METHOD':    'GET',
            'SCRIPT_NAME':       '',
            'SERVER_NAME':       'testserver',
            'SERVER_PORT':       '80',
            'SERVER_PROTOCOL':   'HTTP/1.1',
            'wsgi.version':      (1,0),
            'wsgi.url_scheme':   'http',
            'wsgi.errors':       self.errors,
            'wsgi.multiprocess': True,
            'wsgi.multithread':  False,
            'wsgi.run_once':     False,
        }
        environ.update(self.defaults)
        environ.update(request)
        return environ

    def request(self, **request):
        "Construct a generic request object."
        return WSGIRequest(self._base_environ(**request))

    def _get_path(self, parsed):
        # If there are parameters, add them
        if parsed[3]:
            return urllib.unquote(parsed[2] + ";" + parsed[3])
        else:
            return urllib.unquote(parsed[2])

    def get(self, path, data={}, **extra):
        "Construct a GET request"

        parsed = urlparse(path)
        r = {
            'CONTENT_TYPE':    'text/html; charset=utf-8',
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
            'REQUEST_METHOD': 'GET',
            'wsgi.input':      FakePayload('')
        }
        r.update(extra)
        return self.request(**r)

    def post(self, path, data={}, content_type=MULTIPART_CONTENT,
             **extra):
        "Construct a POST request."

        if content_type is MULTIPART_CONTENT:
            post_data = encode_multipart(BOUNDARY, data)
        else:
            # Encode the content so that the byte representation is correct.
            match = CONTENT_TYPE_RE.match(content_type)
            if match:
                charset = match.group(1)
            else:
                charset = settings.DEFAULT_CHARSET
            post_data = smart_str(data, encoding=charset)

        parsed = urlparse(path)
        r = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE':   content_type,
            'PATH_INFO':      self._get_path(parsed),
            'QUERY_STRING':   parsed[4],
            'REQUEST_METHOD': 'POST',
            'wsgi.input':     FakePayload(post_data),
        }
        r.update(extra)
        return self.request(**r)

    def head(self, path, data={}, **extra):
        "Construct a HEAD request."

        parsed = urlparse(path)
        r = {
            'CONTENT_TYPE':    'text/html; charset=utf-8',
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
            'REQUEST_METHOD': 'HEAD',
            'wsgi.input':      FakePayload('')
        }
        r.update(extra)
        return self.request(**r)

    def options(self, path, data={}, **extra):
        "Constrict an OPTIONS request"

        parsed = urlparse(path)
        r = {
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
            'REQUEST_METHOD': 'OPTIONS',
            'wsgi.input':      FakePayload('')
        }
        r.update(extra)
        return self.request(**r)

    def put(self, path, data={}, content_type=MULTIPART_CONTENT,
            **extra):
        "Construct a PUT request."

        if content_type is MULTIPART_CONTENT:
            post_data = encode_multipart(BOUNDARY, data)
        else:
            post_data = data

        # Make `data` into a querystring only if it's not already a string. If
        # it is a string, we'll assume that the caller has already encoded it.
        query_string = None
        if not isinstance(data, basestring):
            query_string = urlencode(data, doseq=True)

        parsed = urlparse(path)
        r = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE':   content_type,
            'PATH_INFO':      self._get_path(parsed),
            'QUERY_STRING':   query_string or parsed[4],
            'REQUEST_METHOD': 'PUT',
            'wsgi.input':     FakePayload(post_data),
        }
        r.update(extra)
        return self.request(**r)

    def delete(self, path, data={}, **extra):
        "Construct a DELETE request."

        parsed = urlparse(path)
        r = {
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
            'REQUEST_METHOD': 'DELETE',
            'wsgi.input':      FakePayload('')
        }
        r.update(extra)
        return self.request(**r)


"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import *
from django.contrib import admin
from django.views.generic import RedirectView
from reading import views
from django.conf.urls.static import static
from django.conf import settings
admin.autodiscover()

urlpatterns = [
    url(r'^$', views.index),
    url(r'^admin/', include(admin.site.urls)),
    # url(r'^blog/', include('blog.urls')),
    url(r'^search/', views.search),
    url(r'^download/', views.download),
    url(r'^register/', views.register),
    url(r'^login/', views.userlogin),
    url(r'^logout/', views.userlogout),
    url(r'^changepassword/', views.changepassword),
    url(r'^uploadfile/', views.uploadfile),
    url(r'^upload/', views.upload),
    url(r'^dotask/', views.dotask),
    url(r'^contact/', views.contact),
    url(r'^createtask/', views.createtask),
    url(r'^task/', views.task),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)