import re
import shutil
import os

from random import getrandbits

from flask import Request, render_template

from paths import APP_DIR
from configuration import read_config
config = read_config()

def render_template_themed(name, **kwargs):
    return render_template(os.path.join(config['template'], name).replace("\\", "/"), **kwargs)

def get_real_ip(request):
    try:
        if request.headers.getlist("X-Forwarded-For"):
            ip = request.headers.getlist("X-Forwarded-For")[0]
        elif request.headers.getlist("X-Real-Ip"):
            ip = request.headers.getlist("X-Real-Ip")[0]
        else:
            ip = request.remote_addr
        return ip
    except:
        return "0.0.0.0"

def camelCaseSplit(text):
    """
    This function splits camel case into separate words
    :param text: Input text
    :return: array of words
    """
    matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', text)
    return [m.group(0) for m in matches]

def grouped(l, n):
    # Yield successive n-sized chunks from l.
    for i in range(0, len(l), n):
        yield l[i:i + n]

class ProxiedRequest(Request):
    def __init__(self, environ, populate_request=True, shallow=False):
        super(Request, self).__init__(environ, populate_request, shallow)
        # Support SSL termination. Mutate the host_url within Flask to use https://
        # if the SSL was terminated.
        x_forwarded_proto = self.headers.get('X-Forwarded-Proto')
        if x_forwarded_proto == 'https':
            self.url = self.url.replace('http://', 'https://')
            self.host_url = self.host_url.replace('http://', 'https://')
            self.base_url = self.base_url.replace('http://', 'https://')
            self.url_root = self.url_root.replace('http://', 'https://')

def disk_usage():
    '''
    BRO
    Returns disk usage in bytes in a form of a list (total, used, free)
    '''
    return shutil.disk_usage(APP_DIR)

def human_readable_bytes(num, suffix='B'):
    '''
    BRO
    Converts bytes into
    '''
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

def media_numbered_name(base_name, filter_model):
    i = 0
    found = False
    while not found:
        i += 1
        new_name = "{}_{}".format(base_name, str(i).zfill(3))
        check = filter_model.select().where(filter_model.name == new_name)
        if not check:
            found = True
            return new_name

from PIL import Image

def resize_and_crop(img, size, crop_type='top'):
    """
    Resize and crop an image to fit the specified size.
    args:
        img_path: path for the image to resize.
        size: `(width, height)` tuple.
        crop_type: can be 'top', 'middle' or 'bottom', depending on this
            value, the image will cropped getting the 'top/left', 'midle' or
            'bottom/rigth' of the image to fit the size.
    raises:
        Exception: if can not open the file in img_path of there is problems
            to save the image.
        ValueError: if an invalid `crop_type` is provided.
    """
    # Get current and desired ratio for the images
    size = [int(size[0]), int(size[1])]
    img_ratio = img.size[0] / float(img.size[1])
    ratio = size[0] / float(size[1])
    #The image is scaled/cropped vertically or horizontally depending on the ratio
    if ratio > img_ratio:
        img = img.resize((size[0], int(size[0] * img.size[1] / img.size[0])),
                Image.ANTIALIAS)
        # Crop in the top, middle or bottom
        if crop_type == 'top':
            box = (0, 0, img.size[0], size[1])
        elif crop_type == 'middle':
            box = (0, (int(img.size[1] - size[1]) / 2), int(img.size[0]), int((img.size[1] + size[1]) / 2))
        elif crop_type == 'bottom':
            box = (0, img.size[1] - size[1], img.size[0], img.size[1])
        else :
            raise ValueError('ERROR: invalid value for crop_type')
        img = img.crop(box)
    elif ratio < img_ratio:
        img = img.resize((int(size[1] * img.size[0] / img.size[1]), size[1]),
                Image.ANTIALIAS)
        # Crop in the top, middle or bottom
        if crop_type == 'top':
            box = (0, 0, size[0], img.size[1])
        elif crop_type == 'middle':
            box = (int((img.size[0] - size[0]) / 2), 0, int((img.size[0] + size[0]) / 2), int(img.size[1]))
        elif crop_type == 'bottom':
            box = (img.size[0] - size[0], 0, img.size[0], img.size[1])
        else :
            raise ValueError('ERROR: invalid value for crop_type')
        img = img.crop(box)
    else :
        img = img.resize((size[0], size[1]),
                Image.ANTIALIAS)
        # If the scale is the same, we do not need to crop
    return img

def random_string(length=30):
    return '%0x' % getrandbits(length * 4)

def random_image_name(filename, data=None):
    existing = []
    for f in os.listdir(APP_DIR):
        name, ext = os.path.splitext(f)
        existing.append(name)
    name, ext = os.path.splitext(filename)
    while True:
        new_name = random_string()
        if new_name not in existing:
            return new_name+ext


def regrid(ds_in, target_ds,  method='bilinear', reuse_weight=True):
    import xesmf as xe
    """Convenience function for one-time regridding"""
    if reuse_weight:
        regridder = xe.Regridder(ds_in, target_ds, method, periodic=True, reuse_weights=True)
    else:
        regridder = xe.Regridder(ds_in, target_ds, method, periodic=True, reuse_weights=False)
    ds_out = regridder(ds_in)
    if not reuse_weight:
        regridder.clean_weight_file()
    return ds_out


from mandelbrot import Mandelbrot, Scalar, Complex

px = 10
py = 10
dp = 32
cx = Scalar(10,0) # -1.0
cy = Scalar(10,0) #  0.3
w  = Scalar(4,0) #  0.1
h  = w.clone()
fn = "mandelbrot-{0}x{1}x{2}.png".format(px,py,dp)

pos = Complex(cx,cy)
man = Mandelbrot()
man.setPosition(pos)
man.setWindowSize(w,h)
man.setPixels(px,py)
man.render(dp)
man.write(fn)


# 指定GPU及显存使用
import os
import tensorflow as tf
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2"
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.6
set_session(tf.Session(config=config))
# _________________________________________________________________________________________________________
from keras.layers import Input, Dense, LSTM, Masking, Embedding, Dropout
from keras.models import Model, load_model
from keras.layers.merge import Dot, Concatenate
from keras.callbacks import ModelCheckpoint, EarlyStopping
from utils.file_pickle import get_pickle_data
from sklearn.model_selection import train_test_split
import numpy as np

class LstmPunishModel:
    def __init__(self, case_inputShape, embedding_weights):
        case_input = Input(shape=case_inputShape, name='case_input')
        case_x = Embedding(input_dim=len(embedding_weights), output_dim=100,
                          weights=[embedding_weights], input_length=case_inputShape[-1])(case_input)
        case_x = Masking(mask_value=0)(case_x)
        case_x = LSTM(100)(case_x)
        # case_x = Dense(20, activation='selu', )(case_x)
        case_x = Dropout(0.5)(case_x)
        output = Dense(8, activation='softmax', name='output')(case_x)

        self.model = Model(inputs=[case_input], outputs=[output])
        self.model.compile(optimizer='rmsprop',
                      loss='categorical_crossentropy',
                      metrics=['accuracy'])

    def fit(self, x_train_case, y_train, validation_data=None):
        print(np.array(x_train_case).shape)
        # early_stopping = EarlyStopping(monitor='val_loss', patience=1, verbose=0, mode='auto')
        modle_check_point = ModelCheckpoint(filepath='../data_model/lstm_punish_model3_dropout.h5')
        self.model.fit({'case_input': np.array(x_train_case)},
                       {'output': np.array(y_train)},
                       callbacks=None,
                       batch_size=100, epochs=10, validation_data=validation_data, validation_split=0.1)

    def predict(self, x_test):
        return self.model.predict(np.array(x_test))

    def save(self, filename):
        self.model.save(filename)
data = get_pickle_data('../data_feature/train_punish2.pkl')
embedding_weights = get_pickle_data('../data_result/word_embedding.pkl')['embedding_weights']
data_x = data['train_x']
data_y = data['train_y']
del data
model = LstmPunishModel(case_inputShape=data_x[0].shape,
                        embedding_weights=embedding_weights)

model.fit(x_train_case=[data for data in data_x],
          y_train=data_y)


"""This module allow to extract data from .BSP files (provided by JPL)
and integrate them in the frames stack.

See the `NAIF website <https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/>`__
for more informations about the format and content of these files.

For the module to work properly, the .bsp files should be sourced via the `env.jpl.bsp`
configuration variable.

The following configuration will provide access to the Solar System, Mars, Jupiter, Saturn and
their respective major satellites

.. code-block:: python

    from beyond.config import config

    config.update({
        "env": {
            "jpl": [
                "/path/to/de430.bsp",
                "/path/to/mar097.bsp",
                "/path/to/jup310.bsp",
                "/path/to/sat360xl.bsp"
            ]
        }
    })

This module rely heavily on the jplephem library, which parse the binary .BSP format

In addition to .BSP files, you can provide files in the
`PCK text format <https://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/>`__ (generally with a
``.tpc`` extension), which contain informations about masses and dimensions of most of the solar
system bodies.

These files allows to convert to keplerian elements with correct physical constants
(mainly µ).

.. code-block:: python

    config.update({
        "env": {
            "jpl": [
                "/path/to/de430.bsp",
                "/path/to/mar097.bsp",
                "/path/to/jup310.bsp",
                "/path/to/sat360xl.bsp",
                "/path/to/pck00010.tpc",
                "/path/to/gm_de431.tpc"
            ]
        }
    })

Examples of both .bsp and .tcp files are available in the ``tests/data/jpl`` folder.

To display the content of a .bsp file you can use::

    $ python -m beyond.env.jpl <file>...
"""

import numpy as np
from pathlib import Path

from ..config import config
from ..errors import UnknownBodyError, JplConfigError, JplError
from ..orbits import Orbit
from ..utils.node import Node
from ..propagators.base import AnalyticalPropagator
from ..dates import Date
from ..constants import Body as ConstantBody, G
from .solarsystem import EarthPropagator

from jplephem.spk import SPK, S_PER_DAY
from jplephem.names import target_names

__all__ = ["get_body", "get_orbit", "list_bodies", "create_frames"]

class Body(ConstantBody):
    """
    """

    def propagate(self, date):
        return get_orbit(self.name, date)

class Target(Node):
    """Class representing the relations between the different segments
    of .bsp files

    It helps dynamically build the Frames objects
    """

    def __init__(self, name, index):
        super().__init__(name.title().replace(" ", ""))
        self.full_name = name
        self.index = index

class GenericBspPropagator(AnalyticalPropagator):
    """Generic propagator
    """

    BASE_FRAME = "EME2000"

    @classmethod
    def propagate(cls, date):

        frame_name = cls.src.name
        if frame_name == "Earth":
            frame_name = cls.BASE_FRAME

        date = date.change_scale("TDB")

        return Orbit(
            date,
            Bsp().get(cls.src, cls.dst, date),
            form="cartesian",
            frame=frame_name,
            propagator=cls(),
        )

class Bsp:
    """Singleton for reading .bsp files from JPL (DE405, DE430, DE431, etc.)

    with caching mechanism
    """

    _instance = None

    def __new__(cls, *args, **kwargs):

        if cls._instance is None:
            cls._instance = super().__new__(cls, *args, **kwargs)
            cls._instance.open()

        return cls._instance

    def open(self):
        """Open the files
        """
        segments = []

        files = config.get("env", "jpl", fallback=[])

        if not files:
            raise JplConfigError("No JPL file defined")

        # Extraction of segments from each .bsp file
        for filepath in files:

            filepath = Path(filepath)

            if filepath.suffix.lower() != ".bsp":
                continue

            segments.extend(SPK.open(str(filepath)).segments)

        if not segments:
            raise JplError("No segment loaded")

        # list of available segments
        self.segments = dict(((s.center, s.target), s) for s in segments)

        # This variable will contain the Target of reference from which
        # all relations between frames are linked
        targets = {}

        for center_id, target_id in self.segments.keys():

            center_name = target_names.get(center_id, "Unknown")
            target_name = target_names.get(target_id, "Unknown")

            # Retrieval of the Target object representing the center if it exists
            # or creation of said object if it doesn't.
            center = targets.setdefault(center_id, Target(center_name, center_id))
            target = targets.setdefault(target_id, Target(target_name, target_id))

            # Link between the Target objects (see Node2)
            center + target

        # We take the Earth target and make it the top of the structure.
        # That way, it is easy to link it to the already declared earth-centered reference frames
        # from the `frames.frame` module.
        self.top = targets[399]

    def get(self, center, target, date):
        """Retrieve the position and velocity of a target with respect to a center

        Args:
            center (Target):
            target (Target):
            date (Date):
        Return:
            numpy.array: length-6 array position and velocity (in m and m/s) of the
                target, with respect to the center
        """

        if (center.index, target.index) in self.segments:
            pos, vel = self.segments[
                center.index, target.index
            ].compute_and_differentiate(date.jd)
            sign = 1
        else:
            # When we wish to get a segment that is not available in the files (such as
            # EarthBarycenter with respect to the Moon, for example), we take the segment
            # representing the inverse vector if available and reverse it
            pos, vel = self.segments[
                target.index, center.index
            ].compute_and_differentiate(date.jd)
            sign = -1

        # In some cases, the pos vector contains both position and velocity
        if len(pos) == 3:
            # The velocity is given in km/days, so we convert to km/s
            # see: https://github.com/brandon-rhodes/python-jplephem/issues/19 for clarifications
            pv = np.concatenate((pos, vel / S_PER_DAY))
        elif len(pos) == 6:
            pv = np.array(pos)
        else:
            raise JplError("Unknown state vector format")

        return sign * pv * 1000

class Pck(dict):
    """Parser of PCK file containing orientation and shape models for solar system bodies
    """

    def __new__(cls, *args, **kwargs):

        # Caching mechanism
        if not hasattr(cls, "_instance"):
            cls._instance = super().__new__(cls, *args, **kwargs)
            cls._instance.parse()

        return cls._instance

    @classmethod
    def parse_float(cls, txt):
        if "d" in txt:
            # Exponent
            txt = txt.replace("d", "e")

        return float(txt)

    def parse(self):

        self.clear()

        # Parsing of multiple files provided in the configuration variable
        for filepath in config["env"]["jpl"]:

            filepath = Path(filepath)

            if filepath.suffix.lower() != ".tpc":
                continue

            with filepath.open() as fp:
                lines = fp.read().splitlines()

            datablock = False

            # Checking for header
            if lines[0].strip() != "KPL/PCK":
                raise JplError("Unknown file format")

            try:
                for i, line in enumerate(lines):

                    # Seek the beginning of a data block
                    if line.strip() == "\\begindata":
                        datablock = True
                        continue

                    # End of a datablock
                    if line.strip() == "\\begintext":
                        datablock = False
                        continue

                    # Variable extraction
                    if datablock and line.strip().lower().startswith("body"):

                        # retrieval of body ID, parameter name and value
                        line = line.strip().lower().lstrip("body")
                        body_id, _, param = line.partition("_")
                        key, _, value = param.partition("=")

                        # If possible, retrieval of the name of the body
                        # if not, use the ID as name
                        name = target_names.get(int(body_id), body_id).title().strip()

                        # If already existing, check out the dictionary describing the body
                        # characteristics
                        body_dict = self.setdefault(name, {})

                        # Extraction of interesting data
                        value = value.strip()

                        # List of value scattered on multiple lines
                        if not value.endswith(")"):
                            for next_line in lines[i + 1 :]:
                                value += " " + next_line.strip()
                                if next_line.strip().endswith(")"):
                                    break

                        value = [self.parse_float(v) for v in value[1:-2].split()]

                        body_dict[key.upper().strip()] = value
            except Exception as e:
                raise JplError("Parsing error on file '{}'".format(filepath)) from e

    def __getitem__(self, name):
        """Retrieve infos for a given body, if available.

        If not, use default values of 0
        """

        if name == "Solar System Barycenter":
            name = "Sun"

        try:
            obj = super().__getitem__(name)
        except KeyError:
            obj = {}

        kwargs = {
            "name": name.title(),
            "equatorial_radius": 0,
            "mass": 0,
        }

        # Shape
        if "RADII" in obj:
            kwargs["equatorial_radius"] = obj["RADII"][0] * 1000.0
            kwargs["flattening"] = 1 - (obj["RADII"][2] / obj["RADII"][0])

        # mass
        if "GM" in obj:
            kwargs["mass"] = obj["GM"][0] * 1e9 / G

        return Body(**kwargs)

# Cache containing all the propagators used
_propagator_cache = {}

def get_orbit(name, date):
    """Retrieve the orbit of a solar system object

    Args:
        name (str): The name of the body desired. For exact nomenclature, see
            :py:func:`list_bodies`
        date (Date): Date at which the state vector will be extracted
    Return:
        Orbit: Orbit of the desired object, in the reference frame in which it is declared in
            the .bsp file
    """

    # On-demand Propagator and Frame generation

    if name not in [x.name for x in Bsp().top.list]:
        raise UnknownBodyError(name)

    for a, b in Bsp().top.steps(name):
        if b.name not in _propagator_cache:

            # Creation of the specific propagator class
            propagator = type(
                "%sBspPropagator" % b.name,
                (GenericBspPropagator,),
                {"src": a, "dst": b},
            )

            # Retrieve informations for the central body. If unavailable, create a virtual body with
            # dummy values
            center = Pck()[b.full_name.title()]

            # Register the Orbit as a frame
            propagator.propagate(date).as_frame(b.name, center=center)
            _propagator_cache[b.name] = propagator

    if Bsp().top not in _propagator_cache:
        _propagator_cache[Bsp().top.name] = EarthPropagator()

    return _propagator_cache[name].propagate(date)

def list_bodies():
    """List bodies provided by the .bsp files

    Yield:
        Target
    """
    for x in Bsp().top.list[:-1]:
        yield x

def create_frames(until=None):
    """Create frames available in the JPL files

    Args:
        until (str): Name of the body you want to create the frame of, and all frames in between.
                     If ``None`` all the frames available in the .bsp files will be created

    Example:

    .. code-block:: python

        # All frames between Earth and Mars are created (Earth, EarthBarycenter,
        # SolarSystemBarycenter, MarsBarycenter and Mars)
        create_frames(until='Mars')

        # All frames between Earth and Phobos are created (Earth, EarthBarycenter,
        # SolarSystemBarycenter, MarsBarycenter and Phobos)
        create_frames(until='Phobos')

        # All frames available in the .bsp files are created
        create_frames()

    """

    now = Date.now()

    if until:
        get_orbit(until, now)
    else:
        for body in list_bodies():
            get_orbit(body.name, now)

def get_body(name):
    """Retrieve the Body structure of a JPL .bsp file object

    Args:
        name (str)
    Return:
        :py:class:`~beyond.constants.Body`
    """

    return Pck()[name]

if __name__ == "__main__":  # pragma: no cover

    import sys

    config.update({"eop": {"missing_policy": "pass"}})

    for file in sys.argv[1:]:
        print(file)
        print("*" * len(file))
        for segment in SPK.open(file).segments:

            start = Date(segment.start_jd - Date.JD_MJD)
            end = Date(segment.end_jd - Date.JD_MJD)

            center = target_names.get(segment.center, "Unknown")
            target = target_names.get(segment.target, "Unknown")
            print(
                "from {start:{fmt}} to {end:{fmt}} : {center} -> {target}".format(
                    start=start, end=end, center=center, target=target, fmt="%Y-%m-%d"
                )
            )
        print()


import csv
import ast
from collections import Counter
def read_file_and_find_word_frequency(filesname):
    line_count = 0
    all_words = []
    for filename in filesname :
        with open('./clean/'+filename+'.csv', mode='r', encoding='utf-8') as csv_file:
            csv_reader = csv.DictReader(csv_file)
            # scaning for all word
            for row in csv_reader:
                x = row["clean-default"]
                y = row["clean"]
                if "not" in x or "no" in x:
                    print(f"[{line_count}]{y}\n[{line_count}]____{x}")
                x = ast.literal_eval(x)
                x = [n.strip() for n in x]
                x = unique(x) # find unique words in any comments
                all_words.extend(x)
                line_count += 1
    print(f"Processed {line_count} lines.")
    print(f"Was found {len(all_words)} words. ")
    print("Finding words frequence.")
    bf = dict(Counter(all_words)) # counting words
    print(f"Was found {len(bf)} unique words. ")
    print("Ranking words frequence.")
    af = {k: bf[k] for k in sorted(bf, key=bf.get, reverse=True)} #sort asending
    i = 1
    for element in af:
        count = af.get(element,'')
        print(f"{i}.{element} : {count}")
        if(count==1):
            break
        i += 1

def unique(list1):

    # insert the list to the set
    list_set = set(list1)
    # convert the set to the list
    unique_list = (list(list_set))
    return unique_list

'''
def unique(list1):

    # intilize a null list
    unique_list = []

    # traverse for all elements
    for x in list1:
        # check if exists in unique_list or not
        if x not in unique_list:
            unique_list.append(x)
    return unique_list'''

patong = ["patong_google_clean","patong_trip_clean"]
promthep = ["promthep_google_clean","promthep_trip_clean"]
wat = ["wat_google_clean","wat_trip_clean"]
read_file_and_find_word_frequency(patong)


import re

from genshi.builder import tag

from trac.core import *
from trac.web import IRequestHandler
from trac.web.chrome import INavigationContributor, ITemplateProvider, \
        add_stylesheet, add_javascript

class Task(object):
    def __init__(self, data):
        for k in data:
            if k.startswith('due_'):
                date = data[k].split('/')
                data[k] = date[1] + '/' + date[0] + '/' + date[2]
            self.__setattr__(k, data[k])
        self.complete = float(self. totalhours)/float(self.estimatedhours)
        self.complete = int(self.complete*100)

class QGanttPlugin(Component):
    #implements(INavigationContributor, IRequestHandler, ITemplateProvider)
    implements(IRequestHandler, ITemplateProvider)

    def _get_tickets(self, mid):
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        sql = "SELECT t.id, t.owner, t.summary, ts.name, ts.value \
              FROM ticket as t, ticket_custom as ts WHERE t.status != 'closed' \
              AND t.id = ts.ticket AND milestone = '%s' ORDER BY t.id DESC;" % mid
        cursor.execute(sql)
        tickets = cursor.fetchall() or []
        return tickets

    def _get_data(self, mid):
        tickets = self._get_tickets(mid)
        tmp = {}
        for id, owner, name, key, value in tickets:
            if not tmp.has_key(id):
                tmp[id] = {'id': id, 'assignee': owner}
            tmp[id]['name'] = name
            tmp[id][key] = value

        tasks = []
        for k in tmp:
            tasks.append(Task(tmp[k]))
        return tasks

    # INavigationContributor methods
    #def get_active_navigation_item(self, req):
    #    return 'helloworld!'
    #
    #def get_navigation_items(self, req):
    #    yield ('mainnav', 'qgantt',
    #           tag.a('QGantt', href=req.href.qgantt()))

    # IRequestHandler methods
    def match_request(self, req):
        page = re.match(r'/qgantt/(\w+)$', req.path_info)
        xml = re.match(r'/qgantt/(\w+)\.xml$', req.path_info)
        if page:
            req.args['mid'] = page.group(1)
            req.args['type'] = 'page'
            return True
        if xml:
            req.args['mid'] = xml.group(1)
            req.args['type'] = 'xml'
            return True

    def process_request(self, req):
        data = {}
        add_stylesheet(req, 'qg/css/jsgantt.css')
        add_javascript(req, 'qg/js/jsgantt.js')
        # This tuple is for Genshi (template_name, data, content_type)
        # Without data the trac layout will not appear.

        #data.update({'tickets': self._get_tickets()})
        mid = req.args.get('mid')
        if req.args.get('type') == 'page':
            data.update({'project': '%s.xml' % mid, 'milestone': mid})
            return 'gantt_page.html', data, 'text/html'
        if req.args.get('type') == 'xml':
            data.update({'tickets': self._get_data(mid), \
                         'milestone': mid, 'mid': 1})
            return 'project.xml', data, 'application/xml'

    # ITemplateProvider methods
    # Used to add the plugin's templates and htdocs
    def get_templates_dirs(self):
        from pkg_resources import resource_filename
        return [resource_filename(__name__, 'templates')]

    def get_htdocs_dirs(self):
        """Return a list of directories with static resources (such as style
        sheets, images, etc.)

        Each item in the list must be a `(prefix, abspath)` tuple. The
        `prefix` part defines the path in the URL that requests to these
        resources are prefixed with.

        The `abspath` is the absolute path to the directory containing the
        resources on the local file system.
        """
        from pkg_resources import resource_filename
        return [('qg', resource_filename(__name__, 'htdocs'))]


import simple_siamese.hyperparameters as hp
import numpy as np

def sigmoid(z):
  return 1. / (1. + np.exp(-z))

def binary_cross_entropy(h, y):
  return -y * np.log(h) + (1 - y) * np.log(1 - h)

def activation(prev, weights, bias):
  prev_copy = np.r_[np.ones(prev.shape[1])[np.newaxis], prev]
  weights_copy = np.c_[bias, weights]
  return sigmoid(np.matmul(weights_copy, prev_copy))

def numpy_feedforward(x_1, x_2, twin_weights, joined_weights,
                      twin_bias, joined_bias):
  # activation value matrices of the two twin networks and the joined network
  a_1 = np.ndarray(hp.TWIN_L, dtype=np.matrix)
  a_2 = np.ndarray(hp.TWIN_L, dtype=np.matrix)
  a_d = np.ndarray(hp.JOINED_L, dtype=np.matrix)

  # transposing horizontal input vectors (or matrices) into feature vectors
  if len(x_1.shape) == 1:
    a_1[0] = x_1[np.newaxis].T
    a_2[0] = x_2[np.newaxis].T
  else:
    a_1[0] = x_1.T
    a_2[0] = x_2.T

  # forward propagation of twins
  for i in range(1, hp.TWIN_L):
    a_1[i] = activation(a_1[i - 1], twin_weights[i - 1], twin_bias[i - 1])
    a_2[i] = activation(a_2[i - 1], twin_weights[i - 1], twin_bias[i - 1])

  # element wise squared diffrence of two twin network becomes the joined input
  a_d[0] = np.square(a_1[hp.TWIN_L - 1] - a_2[hp.TWIN_L - 1])

  # forward propagation of the joined network
  for i in range(1, hp.JOINED_L):
    a_d[i] = activation(a_d[i - 1], joined_weights[i - 1], joined_bias[i - 1])

  return a_1, a_2, a_d

def regularize(weights, bias, gradients, layers):
  for n in range(1, layers):
    regularization_offset = hp.REG_CONST \
        * np.concatenate((bias[n - 1], weights[n - 1]), axis=1)
    gradients[n - 1] += regularization_offset
    gradients[n - 1][0] -= regularization_offset[0]

def cost_derivatives(x_1, x_2, y, twin_weights, twin_bias,
                     joined_weights, joined_bias):
  # zero initializes cost and gradients
  modelcost = np.float(0)
  twin1_transformations_derivatives = np.ndarray(hp.TWIN_L - 1, dtype=np.ndarray)
  twin2_transformations_derivatives = np.ndarray(hp.TWIN_L - 1, dtype=np.ndarray)
  twin_weights_gradients = np.ndarray(hp.TWIN_L - 1, dtype=np.matrix)
  joined_transformations_derivatives = np.ndarray(hp.JOINED_L - 1, dtype=np.ndarray)
  joined_weights_gradients = np.ndarray(hp.JOINED_L - 1, dtype=np.matrix)
  for i in range(1, hp.TWIN_L):
    twin_weights_gradients[i - 1] = np.matrix(
        np.zeros((hp.TWIN_NET[i], hp.TWIN_NET[i-1] + 1)))
  for i in range(1, hp.JOINED_L):
    joined_weights_gradients[i - 1] = np.matrix(
        np.zeros((hp.JOINED_NET[i], hp.JOINED_NET[i - 1] + 1)))

  # sum up the derivatives of cost for each sample
  for i in range(0, hp.SAMPLE_SIZE):
    (a_1, a_2, a_d) = numpy_feedforward(x_1[i], x_2[i], twin_weights,
                                        joined_weights, twin_bias, joined_bias)
    modelcost += binary_cross_entropy(a_d[hp.JOINED_L - 1], y[i])

    # backpropagate through joined network
    joined_transformations_derivatives[hp.JOINED_L - 2] = \
        a_d[hp.JOINED_L - 1] - y[i]

    for n in reversed(range(0, hp.JOINED_L - 2)):
      # n is the n + 1 layer in the network
      next_layer_transforms_gradients = joined_transformations_derivatives[n + 1]
      next_layer_weights = joined_weights[n + 1]
      this_layer_activations_gradients = a_d[n + 1] * (1 - a_d[n + 1])
      joined_transformations_derivatives[n] = \
          np.matmul(next_layer_weights.T, next_layer_transforms_gradients) \
          * this_layer_activations_gradients
    joined_input_derivatives = np.matmul(joined_weights[0].T, \
                                         joined_transformations_derivatives[0])

    # backpropagate through twin networks
    outlayer = hp.TWIN_L - 1
    a_1_out = a_1[outlayer]
    a_2_out = a_2[outlayer]
    twin1_transformations_derivatives[hp.TWIN_L - 2] = \
        2 * (a_1_out - a_2_out) * a_1_out * (1 - a_1_out) \
        * joined_input_derivatives
    twin2_transformations_derivatives[hp.TWIN_L - 2] = \
        2 * (a_1_out - a_2_out) * a_2_out * (1 - a_2_out) \
        * joined_input_derivatives
    for n in reversed(range(0, hp.TWIN_L - 2)):
      twin1_transformations_derivatives[n] = \
          np.matmul(twin_weights[n + 1].T, twin1_transformations_derivatives[n + 1]) \
          * (a_1[n + 1] * (1 - a_1[n + 1]))
      twin2_transformations_derivatives[n] = \
          np.matmul(twin_weights[n + 1].T, twin2_transformations_derivatives[n + 1]) \
          * (a_2[n + 1] * (1 - a_2[n + 1]))

    # calculate gradients of weights in relation to their transformations
    for n in range(1, hp.JOINED_L):
      ad_concat_1 = np.r_[np.ones(a_d[n - 1].shape[1])[np.newaxis], a_d[n - 1]]
      joined_weights_gradients[n - 1] += \
          np.matmul(joined_transformations_derivatives[n - 1], ad_concat_1.T)
    for n in range(1, hp.TWIN_L):
      a1_concat_1 = np.r_[np.ones(a_1[n - 1].shape[1])[np.newaxis], a_1[n - 1]]
      a2_concat_1 = np.r_[np.ones(a_2[n - 1].shape[1])[np.newaxis], a_2[n - 1]]
      twin_weights_gradients[n - 1] += \
          np.add(np.matmul(twin1_transformations_derivatives[n - 1], a1_concat_1.T)
          , np.matmul(twin2_transformations_derivatives[n - 1], a2_concat_1.T))

  # take their mean
  modelcost /= hp.SAMPLE_SIZE
  for n in range(1, hp.JOINED_L):
    joined_weights_gradients[n - 1] /= hp.SAMPLE_SIZE
  for n in range(1, hp.TWIN_L):
    twin_weights_gradients[n - 1] /= hp.SAMPLE_SIZE

  #regularize(twin_weights, twin_bias, twin_weights_gradients, hp.TWIN_L)
  #regularize(deep_weights, deep_bias, deep_weights_gradients, hp.DEEP_L)
  return modelcost, twin_weights_gradients, joined_weights_gradients

def numerical_derivative_approximation(x_1, x_2, y, twin_weights, twin_bias,
      joined_weights, joined_bias, i, j, l, joined=True):
  # make two copies of the weights and biases
  twin_weights_copy_1 = np.ndarray(hp.TWIN_L - 1, dtype=np.matrix)
  twin_bias_copy_1 = np.ndarray(hp.TWIN_L - 1, dtype=np.ndarray)
  joined_weights_copy_1 = np.ndarray(hp.JOINED_L - 1, dtype=np.matrix)
  joined_bias_copy_1 = np.ndarray(hp.JOINED_L - 1, dtype=np.ndarray)
  twin_weights_copy_2 = np.ndarray(hp.TWIN_L - 1, dtype=np.matrix)
  twin_bias_copy_2 = np.ndarray(hp.TWIN_L - 1, dtype=np.ndarray)
  joined_weights_copy_2 = np.ndarray(hp.JOINED_L - 1, dtype=np.matrix)
  joined_bias_copy_2 = np.ndarray(hp.JOINED_L - 1, dtype=np.ndarray)
  for n in range(1, hp.TWIN_L):
    twin_weights_copy_1[n - 1] = twin_weights[n - 1]
    twin_bias_copy_1[n - 1] = twin_bias[n - 1]
    twin_weights_copy_2[n - 1] = twin_weights[n - 1]
    twin_bias_copy_2[n - 1] = twin_bias[n - 1]
  for n in range(1, hp.JOINED_L):
    joined_weights_copy_1[n - 1] = joined_weights[n - 1]
    joined_bias_copy_1[n - 1] = joined_bias[n - 1]
    joined_weights_copy_2[n - 1] = joined_weights[n - 1]
    joined_bias_copy_2[n - 1] = joined_bias[n - 1]

  # check which set of weights to change
  if joined:
    bias_copy_1 = joined_bias_copy_1
    bias_copy_2 = joined_bias_copy_2
    weights_copy_1 = joined_weights_copy_1
    weights_copy_2 = joined_weights_copy_2
  else:
    bias_copy_1 = twin_bias_copy_1
    bias_copy_2 = twin_bias_copy_2
    weights_copy_1 = twin_weights_copy_1
    weights_copy_2 = twin_weights_copy_2

  # copy and modify the weight/bias matrices at (i, j, l)
  if j == 0:
    new_bias_1 = np.ndarray.copy(bias_copy_1[l])
    new_bias_2 = np.ndarray.copy(bias_copy_2[l])
    new_bias_1[i] += hp.NUMERICAL_DELTA
    new_bias_2[i] -= hp.NUMERICAL_DELTA
    bias_copy_1[l] = new_bias_1
    bias_copy_2[l] = new_bias_2
  else:
    new_weights_1 = np.ndarray.copy(weights_copy_1[l])
    new_weights_2 = np.ndarray.copy(weights_copy_2[l])
    # j - 1 due to lack of biases
    new_weights_1[i][j - 1] += hp.NUMERICAL_DELTA
    new_weights_2[i][j - 1] -= hp.NUMERICAL_DELTA
    weights_copy_1[l] = new_weights_1
    weights_copy_2[l] = new_weights_2

  # forward propagate
  (_, _, out_1) = numpy_feedforward(x_1, x_2, twin_weights_copy_1,
                            joined_weights_copy_1, twin_bias_copy_1,
                            joined_bias_copy_1)
  (_, _, out_2) = numpy_feedforward(x_1, x_2, twin_weights_copy_2,
                            joined_weights_copy_2, twin_bias_copy_2,
                            joined_bias_copy_2)

  # calculate costs for both sets of weights
  last = hp.JOINED_L - 1
  cost_1 = np.average(binary_cross_entropy(out_1[last], y))
  cost_2 = np.average(binary_cross_entropy(out_2[last], y))
  # print("numerical costs: " + str(cost_1) + ", " + str(cost_2))
  return (cost_1 - cost_2) \
      / (2 * hp.NUMERICAL_DELTA)

def num_approx_aggregate(x1, x2, y, twin_weights, twin_bias, joined_weights,
                         joined_bias):
  twin_weights_gradients = np.ndarray(hp.TWIN_L - 1, dtype=np.matrix)
  joined_weights_gradients = np.ndarray(hp.JOINED_L - 1, dtype=np.matrix)
  for l in range(hp.TWIN_L - 1):
    mat = np.zeros(shape=(hp.TWIN_NET[l + 1], hp.TWIN_NET[l] + 1))
    for i in range(hp.TWIN_NET[l + 1]):
      for j in range(hp.TWIN_NET[l] + 1):
        mat[i][j] =  numerical_derivative_approximation(x1, x2, y, twin_weights,
                                                       twin_bias, joined_weights
                                                       , joined_bias, i, j, l,
                                                       joined=False)
    twin_weights_gradients[l] = mat
  for l in range(hp.JOINED_L - 1):
    mat = np.zeros(shape=(hp.JOINED_NET[l + 1], hp.JOINED_NET[l] + 1))
    for i in range(hp.JOINED_NET[l + 1]):
      for j in range(hp.JOINED_NET[l] + 1):
        mat[i][j] = numerical_derivative_approximation(x1, x2, y, twin_weights,
                                                       twin_bias, joined_weights
                                                       , joined_bias, i, j, l,
                                                       joined=True)
    joined_weights_gradients[l] = mat
  return twin_weights_gradients, joined_weights_gradients


class Solution:
    def widthOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0

        current_depth = 0
        left_pos = 0
        ret = 0

        queue = [(root, 0, 0)]
        for node, depth, pos in queue:
            if node:
                queue.append((node.left, depth + 1, pos * 2))
                queue.append((node.right, depth + 1, pos * 2 + 1))

                if current_depth != depth:
                    current_depth = depth
                    left_pos = pos
                ret = max(pos - left_pos + 1, ret)

        return ret


import numpy as np
from keras.layers import *
import Loader_mnist as ld
from sklearn.model_selection import train_test_split
from keras import models
from keras.layers import *
from keras import losses ,optimizers
from keras import backend as K
from keras import metrics
import numpy as np

from functools import *

# setting
iter = 200

# data
path = r"data\mnist\train.csv"
x , y = ld.Loadmnist(path, True )

y = np.eye(10)[y]

xTrain , xTest , yTrain , yTest = train_test_split( x ,y , test_size = 0.3 )

num_b, num_h , num_w , num_c = xTrain.shape

input = Input( (num_h , num_w , 1) )

# custom metric
def pred_overhalf(y_true, y_pred):
    print(type())
    return K.count_params( filter( lambda x : x > 0.5 , y_pred ) )

# model - funtional
x = Conv2D( 64 , (3,3) , activation = "relu")(input)
x = MaxPool2D( padding = "same" )(x)
x = Flatten()(x)
x = Dense( 128 , activation = 'sigmoid' )(x)
output = Dense( 10 , activation = 'sigmoid')(x)

model_ver1 = models.Model( input , output )
model_ver1.compile( optimizer = optimizers.Adam() , loss = losses.categorical_crossentropy , metrics = [metrics.mae , metrics.categorical_accuracy])

 # model - funtional

conv1 = Conv2D( 64 , (3,3) , activation = "relu")
maxpool1 = MaxPool2D( padding = "same" )
flat = Flatten()
d1  =Dense( 128 , activation = 'sigmoid' )
d2 = Dense( 10 , activation = 'sigmoid')

modelpipe = [input , conv1 , maxpool1 , flat , d1 , d2 ]

linked_m1 = reduce( lambda f,s : s(f) , modelpipe )

model_ver2 = models.Model( input , linked_m1 )
model_ver2.compile(optimizer = optimizers.SGD() , loss = losses.categorical_crossentropy , metrics = ['acc' ])

history = model_ver2.fit( xTrain, yTrain , batch_size = 64 , epochs = 3 , validation_split = 0.2)

score = model_ver2.evaluate( xTest , yTest )

acclist = history.history['acc']

print("done")


class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self, head=None):
        self.head = head

    def add_end(self, value):
        current = self.head
        while current.next is not None:
            current = current.next
        current.next = Node(value)

    def add_start(self, value):
        new = Node(value)
        new.next = self.head
        self.head = new

    def add_nth(self, value, n):
        current = self.head
        new = Node(value)
        for i in range(n-1):
            previous = current
            current = current.next
        previous.next = new
        new.next = current

    def delete_nth(self, n):
        current = self.head
        for i in range(n-1):
            previous = current
            current = current.next
        previous.next = current.next

    def reverse(self):
        current = self.head
        previous = None
        while current is not None:
            next_node = current.next # the next node in the original list
            current.next = previous
            previous = current
            current = next_node
        self.head = previous

    def reverse_recursive(self, head): # revisit this later
        if head is None or head.next is None:
            self.head = head # when we reach the final element (excluding None), we make it the head
            return
        else:
            self.reverse_recursive(head.next)
            q = head.next
            q.next = head
            head.next = None

    def show(self):
        current = self.head
        list_str = "{}->".format(current.value)
        while current.next is not None:
            current = current.next
            list_str += "{}->".format(current.value)
        list_str += "Null"
        return list_str

    def __repr__(self):
        return self.show()

    def show_recursive(self, head):
        if head.next is None:
            return
        else:
            print(head.value) # swap these to lines to reverse the order of printing
            self.show_recursive(head.next)

head = Node(1)
myLinkedList = LinkedList(head)
myLinkedList.add_end(2)
myLinkedList.add_end(3)
myLinkedList.add_end(4)
# myLinkedList.reverse()
# myLinkedList.reverse_recursive(head)
print(myLinkedList)
# print(myLinkedList.show())


import requests
from ip_pool import api_settings

with open(api_settings.FILE_NAME,'r') as f:
    # ip_list = [item.split(',')[0] for item in f.readlines()]
    ip_list = ['111.72.25.96:9999']

    for ip in ip_list:
        try:
            proxies = {
                'http': 'http://' + ip,
                'https': 'https://' + ip,
            }

            res = requests.get('https://httpbin.org/get',
                               proxies=proxies,
                               timeout=10)
            res.encoding = 'utf-8'
            print('>>>>>>>>>>>', res.content.decode())
        except Exception as e:
            print(e)


from rest_framework import serializers

from .models import Comment, Review

class ReviewSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(
        read_only=True,
        slug_field='username'
    )

    title = serializers.SlugRelatedField(
        many=False, read_only=True, slug_field="description"
    )

    def validate(self, data):
        author = self.context['request'].user
        title = self.context['view'].kwargs.get('title_id')
        method = self.context.get('request').method == 'POST'
        if (method
           and Review.objects.filter(title=title, author=author).exists()):
            raise serializers.ValidationError(
                'Можно написть только один отзыв'
            )
        return data

    class Meta:
        model = Review
        fields = '__all__'

class CommentSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(
        many=False,
        slug_field='username',
        read_only=True
    )

    review = serializers.SlugRelatedField(
        many=False,
        read_only=True,
        slug_field='text'
    )

    class Meta:
        model = Comment
        fields = '__all__'


#!/usr/bin/python
# Track SCP  for a specified time for hotbox tests.

# The *with* keyword is standard in Python 2.6, but has to be explicitly imported in Python 2.5
from __future__ import with_statement

import time
from katcorelib import standard_script_options, verify_and_connect,  start_session, user_logger
import katpoint
from katpoint import wrap_angle
import numpy as np

# Set up standard script options
parser = standard_script_options(usage="%prog [options] hotload or coldload",
                                 description='Perform a mesurement of system tempreture using hot and cold on sky loads'
                                             'Over 6 frequency ranges. Note also some **required** options below.')
# Add experiment-specific options
parser.add_option('-t', '--track-duration', type='float', default=30.0,
                  help='Length of time for each loading, in seconds (default=%default)')
parser.add_option('-m', '--max-duration', type='float',default=-1,
                  help='Maximum duration of script, in seconds (the default is to observing all sources once)')

# Set default value for any option (both standard and experiment-specific options)
parser.set_defaults(description='Hotload and Coldload observation',dump_rate = 1.0/0.512)
# Parse the command line
opts, args = parser.parse_args()

if  not opts.description == 'Hotload and Coldload observation' :  opts.description = 'Hotload and Coldload observation:'+ opts.description

nd_off     = {'diode' : 'coupler', 'on' : 0., 'off' : 0., 'period' : -1.}
nd_coupler = {'diode' : 'coupler', 'on' : opts.track_duration, 'off' : 0., 'period' : 0.}

#if len(args) == 0:
#    raise ValueError("Please specify the sources to observe as arguments, either as "
#                     "description strings or catalogue filenames")

with verify_and_connect(opts) as kat:
    moon = kat.sources.lookup['moon']
    with start_session(kat, **vars(opts)) as session:
        session.standard_setup(**vars(opts))
        session.nd_params = nd_off
        session.capture_start()
        once = True
        start_time = time.time()
        while once or  time.time() < start_time + opts.max_duration :
            once = False
            moon =  katpoint.Target('Moon, special')
            antenna = katpoint.Antenna('ant1, -30:43:17.3, 21:24:38.5, 1038.0, 12.0, 18.4 -8.7 0.0, -0:05:30.6 0 -0:00:03.3 0:02:14.2 0:00:01.6 -0:01:30.6 0:08:42.1, 1.22')  # find some way of getting this from session
            moon.antenna = antenna
            off1_azel = katpoint.construct_azel_target(wrap_angle(moon.azel()[0] + np.radians(10) ),moon.azel()[1] )
            off1_azel.antenna = antenna
            off1      = katpoint.construct_radec_target(off1_azel.radec()[0],off1_azel.radec()[1])
            off1.antenna = antenna
            off1.name = 'off1'

            off2_azel = katpoint.construct_azel_target(wrap_angle(moon.azel()[0] - np.radians(10) ),moon.azel()[1] )
            off2_azel.antenna = antenna
            off2      = katpoint.construct_radec_target(off2_azel.radec()[0],off2_azel.radec()[1])
            off2.antenna =  antenna
            off2.name = 'off2'
            sources = katpoint.Catalogue(add_specials=False)
            sources.add(moon)
            sources.add(off2)
            sources.add(off1)
            txtlist = ', '.join(  [ "'%s'" % (target.name,)  for target in sources])
            user_logger.info("Calibration targets are [%s]" %(txtlist))
            for target in sources:
                session.nd_params = nd_off
                for nd in [nd_coupler]:
                    session.nd_params = nd_off
                    session.track(target, duration=0) # get onto the source
                    user_logger.info("Now capturing data - diode %s on" % nd['diode'])
                    session.label('%s'%(nd['diode']))
                    if not session.fire_noise_diode(announce=True, **nd) : user_logger.error("Noise Diode did not Fire , (%s did not fire)" % nd['diode']  )
                session.nd_params = nd_off
                user_logger.info("Now capturing data - noise diode off")
                session.label('track')
                session.track(target, duration=opts.track_duration)
        if opts.max_duration and time.time() > start_time + opts.max_duration:
            user_logger.info('Maximum script duration (%d s) exceeded, stopping script' % (opts.max_duration,))


# -*- coding=utf-8 -*-

import win32gui
import win32con
import time

# 需要win32gui支持，下载地址https://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/

class TestTaskbarIcon:
    def __init__(self):

        # 注册一个窗口类
        wc = win32gui.WNDCLASS()
        hinst = wc.hInstance = win32gui.GetModuleHandle(None)
        wc.lpszClassName = "PythonTaskbarDemo"
        wc.lpfnWndProc = {win32con.WM_DESTROY: self.OnDestroy,}
        classAtom = win32gui.RegisterClass(wc)
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        self.hwnd = win32gui.CreateWindow( classAtom, "Taskbar Demo", style,
                0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT,
                0, 0, hinst, None)
        hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
        nid = (self.hwnd, 0, win32gui.NIF_ICON, win32con.WM_USER+20, hicon, "Demo")
        win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid)

    def showMsg(self, title, msg):
        # 原作者使用Shell_NotifyIconA方法代替包装后的Shell_NotifyIcon方法
        # 据称是不能win32gui structure, 我稀里糊涂搞出来了.
        # 具体对比原代码.
        nid = (self.hwnd, # 句柄
                0, # 托盘图标ID
                win32gui.NIF_INFO, # 标识
                0, # 回调消息ID
                0, # 托盘图标句柄
                "TestMessage", # 图标字符串
                msg, # 气球提示字符串
                0, # 提示的显示时间
                title, # 提示标题
                win32gui.NIIF_INFO # 提示用到的图标
                )
        win32gui.Shell_NotifyIcon(win32gui.NIM_MODIFY, nid)

    def OnDestroy(self, hwnd, msg, wparam, lparam):
        nid = (self.hwnd, 0)
        win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, nid)
        win32gui.PostQuitMessage(0) # Terminate the app.

def notify(title, msg):
     t = TestTaskbarIcon()
     t.showMsg(title, get_current_time() + "\n当前价格 :  " + msg)
     time.sleep(5)
     win32gui.DestroyWindow(t.hwnd)

def get_current_time():
    return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))

if __name__ == '__main__':
    notify("出来吧", "奥特曼!")


'''
Normal method
'''

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = pd.read_csv('data.csv')

x = data.iloc[:,0].values
y = data.iloc[:,2].values
no_train_ex = len(y)

temp = []
for d in x:
    temp.append([1,d])
temp2 = []
for d in y:
    temp2.append([d])

# X --- size = m x 2
X = np.array(temp)
Y = np.array(temp2)

theta = np.linalg.inv(np.transpose(X)@X) @ np.transpose(X)@Y

from sklearn.linear_model import LinearRegression
reg = LinearRegression()
reg.fit(X,Y)

plt.scatter(x,y,color='b')
plt.plot(x,reg.predict(X),'g')
plt.plot(x,X@theta,color='r')
plt.show()


# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 15:50:51 2019

@author: Lucil
"""

from collections import Counter

## Define feature extractor to create local feature vector phi:
def feature_extractor(sentence, t_prev, t_pres, index):
    dic = {}
    word = sentence[index]
    dic[(word, t_pres)] = 1
    if index == 0:
        dic[('start', t_pres)] = 1
    else:
        dic[(t_prev, t_pres)] = 1
        dic[('pre_w '+sentence[index - 1], t_pres)] = 1
    if index <len(sentence)-1:
        dic[('aft_w '+sentence[index + 1], t_pres)] = 1
    else:
        dic[(t_pres, 'end')] = 1
    return dic

## Define global feature_vector function:
def feature_vector(sentence, tag):
    for j in range(len(sentence)):
        if j == 0:
            v = feature_extractor(sentence,'start',tag[j],j)
        else:
            v = Counter(v) +Counter(feature_extractor(sentence, tag[j-1], tag[j], j))
            v = dict(v)
    return v

def product(alpha, f):
    s = 0
    for key in f.keys():
        if key in alpha.keys():
            s = s+ alpha[key]*f[key]
    return s

##Viterbi algorithm
def Viterbi(alpha, sentence, tags):
    n = len(sentence)
    score = [0]*n
    state = [0]*n
    y = [0]*n
    curr_state_score = {}
    curr_state = {}
    last_state_score = {}

    for tag_ in tags:
        curr_state_score[tag_] = product(alpha, feature_extractor(sentence, 'start', tag_, 0))
        curr_state[tag_] = 'start'
    score[0] = curr_state_score.copy()
    state[0] = curr_state.copy()
    for i in range(1, n):
        last_state_score = curr_state_score.copy()
        for tag_c in tags:
            dic = {}
            for tag_l in tags:
                dic[tag_l] = last_state_score[tag_l]+product(alpha, feature_extractor(sentence, tag_l, tag_c, i))
            curr_state_score[tag_c] = max(dic.values())
            curr_state[tag_c] = max(dic, key=dic.get)
        score[i] = curr_state_score.copy()
        state[i] = curr_state.copy()
    y[-1] = max(curr_state_score, key = curr_state_score.get)
    for i in reversed(range(n-1)):
        curr_state = state[i+1]
        y[i] =  curr_state[y[i+1]]
    return y

## Perceptron algorithm
def perceptron(training_set, tags, T, avg = False):
    n = len(training_set)
    alpha = {}
    l = []
    for t in range(T):
        for i in range(n):
            tagged_s = training_set[i]
            tag = [tup[1] for tup in tagged_s ]
            sentence = [tup[0] for tup in tagged_s]
            z = Viterbi(alpha, sentence, tags)
            #print (z)
            if z != tag:
                alpha = Counter(alpha) + Counter(feature_vector(sentence, tag)) - Counter(feature_vector(sentence, z))
                alpha = dict(alpha)
                if avg == True:
                    l.append(alpha)
    if avg == True:
        for al in l:
            alpha = Counter(alpha) + Counter(al)
        alpha = dict(alpha)
        alpha = {k: v /(T*n) for k, v in alpha.items()}
    return alpha


from django.urls import path
from . import views
urlpatterns = [
    path('', views.home_page, name='home_page'),
    path('signup', views.sign_up, name='sign_up'),
    path('login', views.loginpage, name='login'),
    path('logout', views.logoutpage, name='logout'),
    path('dashbord/customer', views.customer, name='customer'),
    path('dashbord/rooms', views.room, name='rooms'),
    path('dashbord', views.dashbord, name='dashbord'),
    path('dashbord/rooms/available', views.available, name='available'),
    path('dashbord/rooms/available/updatetime/<str:pk>', views.updatetime, name='updatetime'),
    path('dashbord/rooms/CreateRoom', views.CreateRoom, name='CreateRoom'),
    path('dashbord/rooms/UpdateRoom/<str:Room_id>/', views.UpdateRoom, name='UpdateRoom'),
    path('dashbord/rooms/DeleteRoom/<str:pk>/', views.DeleteRoom, name='DeleteRoom'),
    path('dashbord/rooms/RoomBooking/', views.RoomBooking, name='RoomBooking'),
    path('dashbord/rooms/RoomBooking/Reservation/<str:pk>/', views.reservation, name='Reservation'),
    path('dashbord/myprofile', views.myprofile, name='myprofile'),

]


from numpy import linspace,sin,pi,int16,concatenate
#from scipy.io.wavfile import write
import cloudstorage as gcs
import struct

def note_switch(x):
    return {
    'A' : 440,
    'A#' : 466,
    'B' : 494,
    'C' : 523,
    'C#' : 554,
    'D' : 587,
    'D#' : 622,
    'E' : 659,
    'E#' : 6,
    'F' : 698,
    'F#' : 740,
    'G' : 784,
    'G#' : 831,
    'p': 0,
    }[x]

allowed_sign = [ 'A','A#', 'B','C','C#', 'D', 'D#', 'E','E#', 'F', 'F#', 'G', 'G#', 'p' ]

#class which represent a melody
class Melody:
    def __init__(self, melody_string):
        self.listNotes = []
        self.string = melody_string

        melody_string = melody_string.replace(" ", "")
        melody_string = melody_string.replace("\n", "")
        melody_string = melody_string.replace("\t", "")
        melody_list = melody_string.split(',')
        for i in melody_list:
            self.listNotes.append(Note(i))

    def update(melody_string):
        self.string = melody_string
        melody_string = melody_string.replace(" ", "")
        melody_string = melody_string.replace("\n", "")
        melody_string = melody_string.replace("\t", "")
        melody_list = melody_string.split(',')
        for i in melody_list:
            self.listNotes.append(Note(i))

#class which represent a music ton
class Note:
    def __init__(self, Note_string):
        if Note_string in allowed_sign:
            self.frequency = note_switch(Note_string)
        else:
            self.frequency = -1

#synthesize a note
def note_synthesis(freq, len, amp=10000, rate=44100):
    t = linspace(0,len,len*rate)
    data = sin(2*pi*freq*t)*amp
    return data.astype(int16) # two byte integers

#synthesize a melody
def melody_synthesis(melody, amp=10000, rate=44100):
    if isinstance(melody,Melody):
        m = note_synthesis( melody.listNotes[0].frequency , 0.25, amp=10000)
        for i in melody.listNotes[1:]:
            if i.frequency != -1 :
                m = concatenate( (m ,note_synthesis(i.frequency, 0.25, amp=10000) ) )
        return m
    raise TypeError(repr(melody) + " is not a Melody object !")

#write a melody on wave format on gcs
def write_melody(m,buff):

        sounds = melody_synthesis(m,amp=10000, rate=44100)
        writeWaveHeader(buff, my_fmt, len(sounds))
        for i in sounds:
            buff.write(struct.pack('<h',i) )

#constant for the wave header
my_fmt = {
    'Format' : 1,
    'Channel': 1,
    'SamplesPerSec' : 44100,
    'AvgBytePerSec' : 44100*2,
    'BitsPerBlock' : 2,
    'BitsPerSample': 16,
    'BlockAlign' : 0,
}

#write into file the wave headers
def writeWaveHeader(file, fmt ,data_len ):

    file_size = data_len * 2 - 8
    fmt_len = 16

    file.write("RIFF")
    file.write(struct.pack('<L', file_size))
    file.write("WAVEfmt ")
    file.write(struct.pack('<L', fmt_len))
    file.write(struct.pack('<H', fmt['Format']) )
    file.write(struct.pack('<H', fmt['Channel']) )
    file.write(struct.pack('<L', fmt['SamplesPerSec']) )
    file.write(struct.pack('<L', fmt['AvgBytePerSec']) )
    file.write(struct.pack('<H', fmt['BitsPerBlock']) )
    file.write(struct.pack('<H', fmt['BitsPerSample']) )

    file.write("data")
    file.write(struct.pack('<L', data_len*2 - 44))

#test programm
#s_melody = 'A, D, C, G#,E, A#, F'
#m = Melody(s_melody)

#write_melody(m, '2_test_melody.wav')
#write('test_melody.wav',44100,res) # writing the sound to a file


try:
    import sys
    import ovh
    import requests
    import toml
except:
    print("Install: pip3 install ovh requests toml")

class OvhDynHostUpdater:

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

    def __read_config_file(self):
        config_file = open(self.config_filename)
        entries = toml.load(config_file)
        self.domain_name = entries["domain_name"]
        self.application_key = entries["application_key"]
        self.application_secret = entries["application_secret"]
        self.consumer_key = entries["consumer_key"]

    def update_ip(self):
        try:
            self.__read_config_file()

            client = ovh.Client(
                endpoint='ovh-eu',  # Endpoint of API OVH Europe
                application_key=self.application_key,
                application_secret=self.application_secret,
                consumer_key=self.consumer_key,
            )

            service_id = client.get('/domain/zone/' + self.domain_name + '/dynHost/record', subDomain='server')[0]

            client.put('/domain/zone/' + self.domain_name + '/dynHost/record/' + str(service_id),
                       ip=OvhDynHostUpdater.get_my_ip(),
                       subDomain='server')

            client.post('/domain/zone/' + self.domain_name + '/refresh')

            print("Ip updated")
        except:
            print("Error occured, ip not updated")

    @staticmethod
    def get_my_ip():
        """Returns my public ip"""
        response = requests.get('https://api.ipify.org?format=json').text
        ip = eval(response)['ip']
        print("Retrieved ip: " + ip)
        return ip

if __name__ == '__main__':
    try:
        OvhDynHostUpdater(sys.argv[1]).update_ip()
    except:
        print("Usage: python3 ovh_dynhost_updater.py credentials.toml")
        print("Remember to first generate token in https://api.ovh.com/createToken/index.cgi?GET=/*&PUT=/*&POST=/*&DELETE=/*")


#aeb rename

import os

#put directly here
os.chdir('chimes')

files = os.listdir('.') #list all files in directory

#put class here
classes = 'ch'
#this gets the number of files
number_files = len(files)

#start the sound with 1
count = 0

for f in os.listdir():
	# detach the exstention from the name of the file
	file_name, file_ext = os.path.splitext(f)
	#counts up over the files
	if count != number_files:
		count = count + 1
		#the new file name
		print ('{}_{}{}'.format(count, classes, file_ext))
		new_name = '{}-{}{}'.format(count, classes, file_ext)
		#save the new file name
		os.rename(f, new_name)


class Person:
  def __init__(self, name='no name', mail='no address', age=0):
    self.name = name
    self.mail = mail
    self.age = age

  def say(self):
    print('name:' + self.name + ' mail:' + self.mail + ' age:' + str(self.age))

class Member(Person):
  def say(self):
    print('My name is ' + self.name + '. I am ' + str(self.age) + "year's old. ")
    print('  please send mail to "' + self.mail + '".')

me = Person('taro', 'taro@yamada', 39)
me.say()
you = Member('hanako', 'hanako@flower', 45)
you.say()


from django.urls import path

from . import views

from django.contrib.auth import views as v

urlpatterns = [
	#Leave as empty string for base url
	path('',views.store, name="store"),
	path('cart/',views.cart, name="cart"),
	path('about/',views.about,name='about'),
	path('contact/',views.contact,name='contact'),

	path('checkout/', views.checkout, name="checkout"),
	path('signup/',views.signup,name='signup'),

	#path('login/',views.login,name='login'),
	path('view1/',views.view1,name='v28'),
	path('profile/',views.profile,name='profile'),
	path('addpro/',views.addproduct,name="addpro"),

	path('dsh/',views.dashboard,name='dsh'),
	path('log/',v.LoginView.as_view(template_name='store/login1.html'),name='log'),
	path('lgo/',v.LogoutView.as_view(template_name='store/logout.html'),name='lgot'),

]


#!bin/env python

from tkinter import *
from tkinter import ttk
import tkinter as tk
import time
import math
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(21, GPIO.IN)

def calculate_elapse(channel):              # callback function
    global pulse, start_timer, elapse
    pulse+=1                                # increase pulse by 1 whenever interrupt occurred
    elapse = time.time() - start_timer      # elapse for every 1 complete rotation made!
    start_timer = time.time()               # let current time equals to start_timer

def calculate_speed(r_cm):
    global pulse,elapse,rpm,dist_km,dist_meas,km_per_sec,km_per_hour
    if elapse !=0:                          # to avoid DivisionByZero error
        rpm = 1/elapse * 60
        circ_cm = (2*math.pi)*r_cm
        dist_km = circ_cm/100000            # convert cm to km
        km_per_sec = dist_km / elapse       # calculate KM/sec
        km_per_hour = km_per_sec * 3600     # calculate KM/h
        dist_meas = dist_km*pulse           # measure distance traversed in kilometer
        return km_per_hour

def init_interrupt():
    GPIO.add_event_detect(21, GPIO.FALLING, callback = calculate_elapse, bouncetime = 20)

def start_calculations(n, g, w):          #parameters are age,gender,weight
    init_interrupt()
    start = time.time()
    calories_burned = 0
    print(n,g,w)

    while True:
        a.update()
        heart_rate = 60.0
        calculate_speed(30.04)                 # call this function with wheel radius as parameter
        print('rpm:{0:.0f}-RPM kmh:{1:.0f}-KMH dist_meas:{2:.2f}m pulse:{3}'.format(rpm,km_per_hour,dist_meas,pulse))
        time.sleep(0.1)
        total_time = time.time() - start
        update_RPM_data(round(rpm,2), round(km_per_hour,2),round(dist_meas,2), round(total_time,1))
        time.sleep(0.1)

        if (g == 'm'):
            calories_burned = ((0.2017*n)+(0.1988*w)+(0.6309*heart_rate-55.0969))*(total_time/(60*4.184))

        if (g == 'f'):
            calories_burned = ((0.074*n)+(0.1263*w)+(0.4472*heart_rate-20.4022))*(total_time/(60*4.184))

        update_calorie_heart(round(calories_burned,2), round(heart_rate,2))
        time.sleep(.1)

def click():
    name = name_entry.get()
    gender = gender_box.get()
    age = age_box.get()
    weight = weight_box.get()

    age = float(age)
    weight = float(weight)

    if gender == 'Female':
        gender = 'f'
    if gender == 'Male':
        gender = 'm'

    live_window(name, age)
    start_calculations(age, gender, weight)

def live_window(x,y):          #parameters are name, age
    enter_name.destroy()
    enter_gender.destroy()
    enter_age.destroy()
    enter_weight.destroy()     #destroy all whidgets
    enter_button.destroy()
    name_entry.destroy()
    gender_entry.destroy()
    age_entry.destroy()
    weight_entry.destroy()

    create_live_whidgets(x,y)
    place_live_whidgets()

def update_RPM_data(r,s,d,t):             #parameters are rpm, speed, distance, time
    a.rpm_data_label["text"] = r
    a.speed_data_label["text"] = s
    a.distance_data_label["text"] = d
    a.elapsed_data_time["text"] = t

def update_calorie_heart(c, h):               #parameter is calories and heart rate
    a.calorie_data_label["text"] = c
    a.heart_data_label["text"] = h

def create_live_whidgets(x,y):
    y = int(y)
    a.first_frame         = tk.LabelFrame(a, text='Power Levels', font='Helvetica 22', bd=border, bg=frameBG, fg=frameTC)
    a.power_label         = tk.Label(a.first_frame, text="power :", font=frameFont, bg=frameBG, fg=frameTC) #create power labels
    a.voltage_label       = tk.Label(a.first_frame, text="voltage :", font=frameFont, bg=frameBG, fg=frameTC)
    a.current_label       = tk.Label(a.first_frame, text="current :", font=frameFont, bg=frameBG, fg=frameTC)
    a.battery_label       = tk.Label(a.first_frame, text="battery :", font=frameFont, bg=frameBG, fg=frameTC)
    a.power_data_label    = tk.Label(a.first_frame, width=10, text="   ", font=frameFont, bg=frameBG, fg=frameTC) #create rpm labels
    a.voltage_data_label  = tk.Label(a.first_frame, width=10, text="   ", font=frameFont, bg=frameBG, fg=frameTC)
    a.current_data_label  = tk.Label(a.first_frame, width=10, text="    ", font=frameFont, bg=frameBG, fg=frameTC)
    a.battery_data_label  = tk.Label(a.first_frame, width=10, text="    ", font=frameFont, bg=frameBG, fg=frameTC)
    a.power_unit_label    = tk.Label(a.first_frame, text="W", font=frameFont, bg=frameBG, fg=frameTC) #create rpm labels
    a.voltage_unit_label  = tk.Label(a.first_frame, text="V", font=frameFont, bg=frameBG, fg=frameTC)
    a.current_unit_label  = tk.Label(a.first_frame, text="A", font=frameFont, bg=frameBG, fg=frameTC)
    a.battery_unit_label  = tk.Label(a.first_frame, text="%", font=frameFont, bg=frameBG, fg=frameTC)

    a.second_frame        = tk.LabelFrame(a, text='Speed Levels', font='Helvetica 22', bd=border, bg=frameBG, fg=frameTC)
    a.rpm_label           = tk.Label(a.second_frame, text="RPM :", font=frameFont, bg=frameBG, fg=frameTC)
    a.speed_label         = tk.Label(a.second_frame, text="speed :", font=frameFont, bg=frameBG, fg=frameTC)
    a.distance_label      = tk.Label(a.second_frame, text="distance :", font=frameFont, bg=frameBG, fg=frameTC)
    a.elapsed_time        = tk.Label(a.second_frame, text="time elapsed :", font=frameFont, bg=frameBG, fg=frameTC)
    a.rpm_data_label      = tk.Label(a.second_frame, width=10, text="      ", font=frameFont, bg=frameBG, fg=frameTC)
    a.speed_data_label    = tk.Label(a.second_frame, width=10,text="  ", font=frameFont, bg=frameBG, fg=frameTC)
    a.distance_data_label = tk.Label(a.second_frame, width=10,text=" ", font=frameFont, bg=frameBG, fg=frameTC)
    a.elapsed_data_time   = tk.Label(a.second_frame, width=10, text="   ", font=frameFont, bg=frameBG, fg=frameTC)
    a.rpm_unit_label      = tk.Label(a.second_frame, text="rpm", font=frameFont, bg=frameBG, fg=frameTC)
    a.speed_unit_label    = tk.Label(a.second_frame, text="kmph", font=frameFont, bg=frameBG, fg=frameTC)
    a.distance_unit_label = tk.Label(a.second_frame, text="km", font=frameFont, bg=frameBG, fg=frameTC)
    a.elapsed_unit_time   = tk.Label(a.second_frame, text="s", font=frameFont, bg=frameBG, fg=frameTC)

    a.third_frame         = tk.LabelFrame(a, text='User Info', font='Helvetica 22', bd=border, bg=frameBG, fg=frameTC)
    a.name_label          = tk.Label(a.third_frame, text="name :", font=frameFont, bg=frameBG, fg=frameTC)
    a.age_label           = tk.Label(a.third_frame, text="age :", font=frameFont, bg=frameBG, fg=frameTC)
    a.heart_label         = tk.Label(a.third_frame, text="heart rate :", font=frameFont, bg=frameBG, fg=frameTC)
    a.calorie_label       = tk.Label(a.third_frame, text="calories burned :", font=frameFont, bg=frameBG, fg=frameTC)
    a.name_data_label     = tk.Label(a.third_frame, width=10, text=x, font=frameFont, bg=frameBG, fg=frameTC)
    a.age_data_label      = tk.Label(a.third_frame, width=10, text=y, font=frameFont, bg=frameBG, fg=frameTC)
    a.heart_data_label    = tk.Label(a.third_frame, width=10, text="   ", font=frameFont, bg=frameBG, fg=frameTC)
    a.calorie_data_label  = tk.Label(a.third_frame, width=10, text="kcal", font=frameFont, bg=frameBG, fg=frameTC)
    a.heart_unit_label    = tk.Label(a.third_frame, text="bpm", font=frameFont, bg=frameBG, fg=frameTC)

def place_live_whidgets():
    a.first_frame.grid(row=1, column=1)
    a.power_label.grid(row=1, column=1)
    a.voltage_label.grid(row=2, column=1)
    a.current_label.grid(row=3, column=1)
    a.battery_label.grid(row=4, column=1)
    a.power_data_label.grid(row=1, column=2)
    a.voltage_data_label.grid(row=2, column=2)
    a.current_data_label.grid(row=3, column=2)
    a.battery_data_label.grid(row=4, column=2)
    a.power_unit_label.grid(row=1, column=3)
    a.voltage_unit_label.grid(row=2, column=3)
    a.current_unit_label.grid(row=3, column=3)
    a.battery_unit_label.grid(row=4, column=3)

    a.second_frame.grid(row=1, column=2)
    a.rpm_label.grid(row=1, column=1)
    a.speed_label.grid(row=2, column=1)
    a.distance_label.grid(row=3, column=1)
    a.elapsed_time.grid(row=4, column=1)
    a.rpm_data_label.grid(row=1, column=2)
    a.speed_data_label.grid(row=2, column=2)
    a.distance_data_label.grid(row=3, column=2)
    a.elapsed_data_time.grid(row=4, column=2)
    a.rpm_unit_label.grid(row=1, column=3)
    a.speed_unit_label.grid(row=2, column=3)
    a.distance_unit_label.grid(row=3, column=3)
    a.elapsed_unit_time.grid(row=4, column=3)

    a.third_frame.grid(row=1, column=3)
    a.name_label.grid(row=1, column=1)
    a.age_label.grid(row=2, column=1)
    a.heart_label.grid(row=3, column=1)
    a.calorie_label.grid(row=4, column=1)
    a.name_data_label.grid(row=1, column=2)
    a.age_data_label.grid(row=2, column=2)
    a.heart_data_label.grid(row=3, column=2)
    a.calorie_data_label.grid(row=4, column=2)
    a.heart_unit_label.grid(row=3, column=3)

border=5
frameBG='#000033'
frameTC='#FFFFFF'
frameFont='Helvetica 20'

dist_meas = 0.00
km_per_hour = 0
rpm = 0
elapse = 0
pulse = 0
start_timer = time.time()

a = Tk()                                 #create window
a.pack_propagate(0)
a.minsize(420, 200)                      #size window
a.title("Current Statistics")            #title window
a.configure(background=frameBG)        #background color

gender_box = StringVar(a)
gender_choices = ['Female', 'Male']

age_box = StringVar(a)
age_choices = [i for i in range(13,100)]

weight_box = StringVar(a)
weight_choices = [i for i in range(20,140)]

enter_name = Label(a, text="Name", font='Helvetica 20', bg=frameBG, fg=frameTC)   #create text variable
enter_name.grid(row=1, column=1)

name_entry = Entry(a, bd = 1, font='Helvetica 20')                   #create text entry box
name_entry.grid(row=1, column=2)

enter_gender = Label(a, text="M/F", font='Helvetica 20', bg=frameBG, fg=frameTC)   #create text variable
enter_gender.grid(row=2, column=1)

gender_entry = OptionMenu(a, gender_box, *gender_choices)                   #create text entry box
gender_entry.grid(row=2, column=2)
gender_box.set('Female')

enter_age = Label(a, text="Age", font='Helvetica 20', bg=frameBG, fg=frameTC)   #create text variable
enter_age.grid(row=3,column=1)

age_entry = OptionMenu(a, age_box, *age_choices)                   #create text entry box
age_entry.grid(row=3, column=2)
age_box.set('13')

enter_weight = Label(a, text="Weight(kg)", font='Helvetica 20', bg=frameBG, fg=frameTC)   #create text variable
enter_weight.grid(row=4, column=1)

weight_entry = OptionMenu(a, weight_box, *weight_choices)                   #create text entry box
weight_entry.grid(row=4, column=2)
weight_box.set(20)

enter_button = Button(a, text = "ENTER", command=click, height = 3, width = 15) #create button
enter_button.grid(row=5, column=2)

a.mainloop()


import os
import cv2
import numpy as np
import time

save_dir = "D:/Desktop/WriteData/test/"
#file_dir = "D:/Desktop/WriteData/image/"
file_dir = "D:/Desktop/New_testdata/2/"

for file in os.listdir(file_dir):

    img = cv2.imread(file_dir + file)
    img = cv2.resize(img,(32, 32))
    if img is None:
        continue
    b = img[:,:,0].flatten()
    #print(b)
    g = img[:,:,1].flatten()
    #print(g)
    r = img[:,:,2].flatten()
    #print(r)
    label = [2]

    out = np.array(list(label) + list(r) + list(g) + list(b),np.uint8)
    print(out)
    out.tofile("D:/Desktop/WriteData/test/out.bin")

time.sleep(5)

print("All set!")


#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import os
#dictionary_directory_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dictionary')
name = input("作りたい辞書の名前を入力してください:")

file_path = os.path.abspath(__file__)

# Define path
PATH1 = file_path.replace('tools/gram_maker_by_input.py', 'dictionary/cmudict-en-us.dict') # pocketsphinxの元の辞書の絶対パス
PATH2 = file_path.replace('tools/gram_maker_by_input.py', 'dictionary/{}.dict').format(name) # pocketsphinxの作りたい辞書の絶対パス
PATH3 = file_path.replace('tools/gram_maker_by_input.py', 'dictionary/{}.gram').format(name) # pocketsphinxの作りたい文法辞書の絶対パス

if os.path.exists(PATH2):
	print("同じ辞書名が存在します。")
	print("終了")
	print("===============================================================")
else:
	print('文章を入力してください + Enter')
	print('(終了する場合はCtrl-C)')
	print("===============================================================")
	sentence_list = [] # 標準入力した文を格納するリスト
	word_list = [] # 文に含まれている単語を格納するリスト
	try:
		while 1:
			sentence = input() # ファイルに追加する文章を標準入力
			sentence = sentence.lower() # 全文小文字化
			sentence = sentence.rstrip() # 改行コード削除
			sentence_list.append(sentence)

	except KeyboardInterrupt:
		new_words_list = []
		for s in sentence_list:
			new_words_list += s.split(' ')
		# 重複している単語を省いてword_listに単語を格納する
		for word in new_words_list:
			if word not in word_list:
				word_list.append(word)

		# pocketsphinxの元の辞書の単語のみをリストword1に格納
		with open(PATH1) as f1:
			lines1 = f1.readlines()
		word1 = []
		for l1 in lines1:
			word1.append(l1.split(' ')[0])

		nothing_words = [] # 辞書になかった単語
		nothing_sentences = []
		write_sentence = [] # 辞書に書き込んだ文章

		for w in word_list:
			if w not in word1:
				nothing_words.append(w)

		# 文法辞書(.gram)に書き込み
		with open(PATH3, "a") as f3:
			f3.write("#JSGF V1.0;\n")
			f3.write("grammar {};\n".format(name))
			f3.write("public <rule> = <command>;\n")
			f3.write("<command> = ")

			start = False
			nothing_words_flag = False
			for s in sentence_list:
				if nothing_words != []:
					for n in nothing_words:
						if n in s:
							nothing_words_flag = True
				if nothing_words_flag == False:
				    # 最初の１回目のときのみ、"start == False"
					if start == False:
						start = True
						f3.write(s)
					# 2回目以降は文頭に " | " をつける
					else:
						f3.write(' | ' + s)
					write_sentence.append(s)
				# 知らない単語が含まれた文章のときelseに入り、nothing_sentencesに格納
				else:
					nothing_sentences.append(s)
				nothing_words_flag = False
			f3.write(";")

		# 単語辞書(.dict)に書き込み
		write_word_list = []
		ws_list = []
		with open(PATH2, "a") as f2:
			for ws in write_sentence:
				ws_list += ws.split(' ')

			for wsl in ws_list:
				if wsl not in write_word_list:
					write_word_list.append(wsl)

			for w in write_word_list:
				w_index = word1.index(w)
				f2.write(lines1[w_index])
				if w + '(2)' in word1:
					w_index = word1.index(w + '(2)')
					f2.write(lines1[w_index])
				elif w + '(3)' in word1:
					w_index = word1.index(w + '(3)')
					f2.write(lines1[w_index])
				elif w + '(4)' in word1:
					w_index = word1.index(w + '(4)')
					f2.write(lines1[w_index])

		with open(PATH2) as f:
			lines = f.readlines()

		lines = sorted(lines)

		with open(PATH2, 'w') as f2:
			for l in lines:
				f2.write(l)

	if nothing_sentences != []:
		print("追加できなかった文章は")
		for j in nothing_sentences:
			print(j)

	# 見つからなかった単語の表示
	if nothing_words != []:
		print("見つからなかった単語は")
		for j in nothing_words:
			print(j)


import json
import logging

from apps.backtesting.legacy_postgres import POSTGRES
from apps.backtesting.rebalancing.price_providers import PriceProvider

class Allocation:

    def __init__(self, amount, asset, portion, timestamp, counter_currency, db_interface, unit_price=None, value=None):
        self.amount = amount
        self.asset = asset
        self.portion = portion

        if unit_price is not None:
            self.unit_price = unit_price
        else:
            self.unit_price = PRICE_PROVIDER.get_price(asset, timestamp,
                                                       counter_currency=counter_currency,
                                                       db_interface=db_interface)

        if value is not None:
            self.value = value
        else:
            self.value = amount * self.unit_price if self.unit_price is not None else None

        try:
            assert self.value == self.unit_price * self.amount or self.value == None
        except:
            logging.warning(f'Numerical error in allocation, allocation value  is {self.value}, '
                            f'and unit_price*amount is {self.unit_price}*self.amount')

        self.timestamp = timestamp
        self.counter_currency = counter_currency

        if counter_currency != 'USDT':
            self.unit_price_usdt = PRICE_PROVIDER.get_price(asset, timestamp,
                                                            counter_currency='USDT',
                                                            db_interface=db_interface)
        else:
            self.unit_price_usdt = self.unit_price

        self.value_usdt = self.amount * self.unit_price_usdt if self.unit_price_usdt is not None else None
        return

    def to_dict(self, prefix=''):
        return {
            f'{prefix}amount': self.amount,
            f'{prefix}asset': self.asset,
            f'{prefix}portion': self.portion,
            f'{prefix}unit_price': self.unit_price,
            f'{prefix}value': self.value,
            f'{prefix}unit_price_usdt': self.unit_price_usdt,
            f'{prefix}value_usdt': self.value_usdt,
            f'{prefix}timestamp': self.timestamp
        }

class PortfolioSnapshot:
    '''
    A snapshot of a multi-asset portfolio at timestamp. Contains a list of assets with corresponding allocations.
    '''

    def __init__(self, timestamp, allocations_data, db_interface, counter_currency, load_from_json=True):
        self._timestamp = timestamp
        self._allocations_by_asset = {}
        self.db_interface = db_interface
        if load_from_json:
            self._parse_json_allocations(allocations_data, counter_currency)
        else:
            self._allocations = allocations_data
        self._fill_internals()
        self._counter_currency = counter_currency

    def _parse_json_allocations(self, allocations_data, counter_currency):
        self._allocations = []
        allocations_dict = json.loads(allocations_data)
        for item in allocations_dict:
            # figure out the value of this particular item
            allocation = Allocation(**item, unit_price=None, value=None, timestamp=self._timestamp,
                                    counter_currency=counter_currency, db_interface=self.db_interface)
            self._allocations.append(allocation)

    def _fill_internals(self):
        self._held_assets = set()
        self._portion_sum = 0
        self._total_value = 0
        self._total_value_usdt = 0
        for allocation in self._allocations:
            self._held_assets.add(allocation.asset)
            self._portion_sum += float(allocation.portion)
            self._total_value += allocation.value
            self._total_value_usdt += allocation.value_usdt
            self._allocations_by_asset[allocation.asset] = allocation

    def get_allocation(self, asset):
        return self._allocations_by_asset.get(asset, Allocation(amount=0, asset=asset, portion=0,
                                                                timestamp=self._timestamp,
                                                                counter_currency=self._counter_currency,
                                                                db_interface=self.db_interface))

    def total_value(self, counter_currency):
        if counter_currency == 'BTC':
            return self._total_value
        elif counter_currency == 'USDT':
            return self._total_value_usdt

    @property
    def held_assets(self):
        return self._held_assets

    @property
    def portion_sum(self):
        return self._portion_sum

    def report(self):
        logging.info(f'At timestamp {self._timestamp}, portfolio stats are:')
        logging.info(f'    -> total value: {self._total_value}, portion sum: {self._portion_sum}')
        for allocation in self._allocations:
            logging.info(f'       {allocation.amount} {allocation.asset} worth {allocation.value} BTC, {allocation.portion*100:2}% total')

    def update_to_timestamp(self, timestamp):
        '''
        Returns a new PortfolioSnapshot with prices and values of individual assets updated to target timestamp.
        :param timestamp: timestamp to which to update the portfolio
        :return: a new instance of PortfolioSnapshot with updated asset values
        '''
        updated_allocations = []
        for allocation in self._allocations:
            new_price = PRICE_PROVIDER.get_price(allocation.asset, timestamp,
                                                 counter_currency=allocation.counter_currency,
                                                 db_interface=self.db_interface)
            new_allocation = Allocation(amount=allocation.amount, asset=allocation.asset, portion=allocation.portion,
                                        timestamp=timestamp, counter_currency=allocation.counter_currency,
                                        unit_price=new_price, value=new_price * allocation.amount, db_interface=self.db_interface)
            updated_allocations.append(new_allocation)

        return PortfolioSnapshot(timestamp, updated_allocations, load_from_json=False, db_interface=self.db_interface,
                                 counter_currency=self._counter_currency)

    def to_dict(self):
        return {asset: self.get_allocation(asset).to_dict() for asset in self.held_assets}

PRICE_PROVIDER = PriceProvider()


import urllib.request    #this loads a library you will need.  Put this line at the top of your file.

def readHtml(toDoList):
    response = urllib.request.urlopen("http://research.cs.queensu.ca/home/cords2/todo.txt")
    html = response.readline()
    toDoList = None

    while len(html) != 0:
        data = html.decode("utf-8").split(',')
        #print ("This is the input", data)
        data[1] = int(data[1])
        toDoList = addToHead(toDoList,data)
        html = response.readline()

    return toDoList

def addToHead(linkedList, value):
    newnode = {}
    newnode["data"] = value
    #set the next pointer of this new node to the head of the list, linkedList
    #newnode is now the head of the list, so we return this node (which is
    #connected to the rest of the list
    newnode["next"] = linkedList
    return newnode

def insertBefore(linkedList, ptr, value):
    #My version of addtoMiddle since we know the ptr we want to add it before.
    #Create a new node for the information to add to the linkedList
    node = {}
    node['data'] = value

    #This pointer will keep moving on until the value after ptr2 matches the ptr from sortLists.
    #Create a new pointer that points to the head of the list
    ptr2 = linkedList

    if ptr == ptr2:
        linkedList = addToHead(linkedList, value)
        return linkedList

    while ptr2['next'] != ptr:
        ptr2 = ptr2['next']

    #Connect the ptr2 to the node
    ptr2['next'] = node
    node['next'] = ptr
    return linkedList

'''
Prints the list.  We need to visit each node and print the data.  We cannot just print
the list using a print statement!!!  If you do, you will see a big mess.
'''
def printList(linkedList):
    ptr = linkedList
    while ptr != None:
        print(ptr['data'], "->", end="")
        ptr = ptr['next']
    print("None")

#INPUT: The toDoList linked list and the task to be added
#OUTPUT: The newTask placed in the toDoList
def sortAdd(toDoList, newTask):
    #Start the pointer at the head
    ptr = toDoList

    #If the list is empty, just add whatever value
    if ptr == None:
        return addToHead(toDoList, newTask)

    #If the value after the pointer is none, this will not be triggered. When it only has one value, this won't be triggered.
    #Now, we want to give that a second check in case the value the pointer is at is being checked.

    #This function is checking if the 'time to finish' from the linked list is more than the 'time to finish' of the newTask
    while ptr['next'] != None:
        if ptr['data'][1] > newTask[1]:
            #Place the newTask before the pointer if the 'time to finish' from the pointer is more than the 'time to finish' of the newTask.
            return insertBefore(toDoList, ptr, newTask)

        elif ptr['data'][1] == newTask[1]:

            if ptr['data'][0] > newTask[0]:

                return insertBefore(toDoList, ptr, newTask)
        ptr = ptr['next']

    #Force check to see if the ptr exactly is over the newTask
    if ptr['data'][1] > newTask[1]:
        return insertBefore(toDoList, ptr, newTask)

    #If it hasn't been returned yet, create a new node that'll be the new end in case the newTask is higher than everything.
    node = {}
    node['data'] = newTask
    node['next'] = None
    ptr['next'] = node
    return toDoList
#INPUT: The two linkedList to move pointers around.
#The instruction carrying the taskDone in it (with a little formatting).
#OUTPUT: The didItList head without 'taskDone' and didItList with 'taskDone' in it.
def doToDid(toDoList,didItList, taskDone):

    taskDone.remove(taskDone[0])
    toDoPTR = toDoList
    didItPTR = didItList
    #Move the pointer to where the 'taskDone' is.
    if toDoPTR['data'][0] == taskDone[0]:
        print("The first value matches!")
    while toDoPTR != None:

        if toDoPTR['next'] == None:
            print("Ok")
            #return toDoList, didItList
        else:
            if toDoPTR['next']['data'][0] == taskDone[0]:
                printList(toDoPTR)
                #if next next is none then toDoPTR['next'] is the last value
                #This means that toDoPTR['next'] should now point to none

                if toDoPTR['next']['next'] == None:
                    if didItList != None:
                        toDoPTR['next']['next'] = didItList
                        toDoPTR['next'] = None
                        printList(didItList)
                        printList(toDoList)
                    else:
                        toDoPTR['next']['next'] = didItList
                        didItList = toDoPTR['next']
                        toDoPTR['next'] = None
                        printList(didItList)
                        printList(toDoList)
                else:
                    #I can't change the toDoList at toDoPTR['next'] to toDoPTR['next']['next']
                    didItPTR = toDoPTR['next']
                    pass

        toDoPTR = toDoPTR['next']

#INPUT: The toDoList and the command from before since it has all the info we need
#OUTPUT: The head of the toDoList with the new task added.
def addToDo(linkedList, instruction):

    #A little formatting before calling our sortAdd function. This removes the command
    instruction.remove(instruction[0])
    linkedList = sortAdd(linkedList, instruction)
    return linkedList

#INPUT: None
#OUTPUT: The commands in the form of a list of lists to be read out by driveDriver
def readDriver():

    response = urllib.request.urlopen("http://research.cs.queensu.ca/home/cords2/driver.txt")
    html = response.readline()
    data = []
    while len(html) != 0 and html != "":

        html = response.readline()

        data.append(html.decode("utf-8").split(','))

    return data

#INPUT: The two linked lists
#OUTPUT: All the commands finished
def driveDriver(toDoList, didItList):
    instructions = readDriver()
    for eachCom in instructions:
        if eachCom[0] == "PrintDidIt\n":
            print("Printing DidIt List. . .")
            printList(didItList)
        elif eachCom[0] == "ExecuteTask\n":
            print("The task", eachCom[1], "was done by", eachCom[2])
        elif eachCom[0] == "PrintToDo\n":
            print("Printing ToDo List. . .")
            printList(toDoList)
        elif eachCom[0] == "AddTask": #Turn into an integer to compare the integers from toDoList
            print("Adding Task:", eachCom[1])
            eachCom[2] = int(eachCom[2])
            toDoList = addToDo(toDoList, eachCom)
            printList(toDoList)
        else:
            print(eachCom[0],"That ain't no command I ever heard of")

def main():
    #creating empty lists
    toDoList = None
    toDoList = readHtml(toDoList)
    didItList = None
    driveDriver(toDoList, didItList)
main()


import tensorflow as tf
from deeplearning_ai.L4_ConvolutionalNeuralNetworks.h410_utils import *
import numpy as np

def total_cost(J_content, J_style, alpha = 10, beta = 40):
    """
    Computes the total cost function

    Arguments:
    J_content -- content cost coded above
    J_style -- style cost coded above
    alpha -- hyperparameter weighting the importance of the content cost
    beta -- hyperparameter weighting the importance of the style cost

    Returns:
    J -- total cost as defined by the formula above.
    """

    ### START CODE HERE ### (≈1 line)
    J = alpha* J_content + beta * J_style
    ### END CODE HERE ###

    return J

tf.reset_default_graph()

with tf.Session() as test:
    np.random.seed(3)
    J_content = np.random.randn()
    J_style = np.random.randn()
    J = total_cost(J_content, J_style)
    print("J = " + str(J))


import ConfigParser
import logging
import errno,sys,os,re, mmap
from lxml import etree

class FakeSecHead(object):
    def __init__(self, fp):
        self.fp = fp
        self.sechead = '[asection]\n'

    def readline(self):
        if self.sechead:
            try:
                return self.sechead
            finally:
                self.sechead = None
        else:
            return self.fp.readline()

def check_if_test_completed_successfully(test_name, report_file):
    report = etree.parse(report_file)
    status_ok = etree.XPath("//SECANT/" + test_name + "[@status=\"OK\"]")
    status_skip = etree.XPath("//SECANT/" + test_name + "[@status=\"SKIP\"]")
    status_fail = etree.XPath("//SECANT/" + test_name + "[@status=\"FAIL\"]")
    return_str = ''
    if status_ok(report):
        return_str = '' # True, finished successfully withou errors
    elif status_skip(report):
        return_str = 'Test has been skipped due to unsuccessful SSH accesss'
    elif status_fail(report):
        get_text = etree.XPath("text()")
        return_str = get_text(status_fail(report)[0])
    return return_str

def getSettingsFromBashConfFile(config_file, key):
    cp = ConfigParser.SafeConfigParser()
    try:
        cp.readfp(FakeSecHead(open(config_file)))
    except IOError as e:
        raise IOError('Cannot open secant.conf file: ' + os.path.split(os.getcwd())[-1])
    key = key.lower()
    return [x[1] for x in cp.items('asection') if x[0] == key][0]

def setLogging():
    secant_conf_path = os.environ.get('SECANT_CONFIG_DIR', '/etc/secant') + '/' + 'secant.conf'

    debug = ""
    with open(secant_conf_path, 'r+') as f:
        data = mmap.mmap(f.fileno(), 0)
        mo = re.search(r'(DEBUG)=((true\b)|(false\b))', data)
        if mo:
            debug = mo.group(2)

    log_level = logging.DEBUG

    if debug == "false":
        log_level = logging.INFO

    logging.basicConfig(format='%(asctime)s %(message)s', filename=getSettingsFromBashConfFile(secant_conf_path, 'log_file'),level=log_level, datefmt='%Y-%m-%d %H:%M:%S')


from importlib import import_module
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.urls import reverse
from ..member.utils import get_id_token_payload

class UserProfile(models.Model):
    """Data for a user of the smh_app."""

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    subject = models.CharField(
        max_length=64, blank=True, null=True, help_text='Subject for identity token', db_index=True)
    picture_url = models.TextField(
        blank=True, help_text="The URL of the User's image (from VMI)")
    user_type = models.CharField(
        max_length=255,
        blank=True,
        choices=(('', 'Other'), ('M', 'Member'), ('O', 'Organization Agent')),
        default="M",
        help_text="What kind of user is this? This controls what dashboard the user sees.",
    )

    def __str__(self):
        return self.user.username

    @property
    def name(self):
        return ' '.join([self.user.first_name or '', self.user.last_name or '']).strip()

    @property
    def id_token_payload(self):
        return get_id_token_payload(self.user)

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    """If the User is being created and does not have a UserProfile model, create one."""
    if created or not hasattr(instance, 'userprofile'):
        UserProfile.objects.create(user=instance)
    instance.userprofile.save()

@receiver(post_save, sender=UserProfile)
def create_user_profile_connect_to_hixny_notification(sender, instance, created, **kwargs):
    """Create Notifications related to the ResourceRequest, while deleting existing notifications"""
    Notification = import_module('apps.notifications.models').Notification
    if instance.user_type == 'O':   # Org agent
        # Delete any Hixny connection notifications for this UserProfile
        Notification.objects.filter(
            notify_id=instance.user.id, actor_id=instance.user.id,
            message__contains='Hixny').delete()
    elif created:
        # Create a notification to connect to Hixny
        Notification.objects.filter(
            notify_id=instance.user.id, actor_id=instance.user.id,
            message__contains='Hixny').delete()
        Notification.objects.create(
            notify=instance.user,
            actor=instance.user,
            instance=instance,
            message="Connect your account to <b>Hixny</b> (Health Information Exchange of New York)",
            actions=[{
                'url': reverse('social:begin', args=['sharemyhealth']),
                'method': 'get',
                'text': "Connect Now"
            }],
        )


#!/usr/bin/python
#Rev. 23/12/2015

#split_in_two
#usage eg: python csvsplit.py m025.csv 4002

import csv     # imports the csv module
import sys      # imports the sys module

ifile = open(sys.argv[1], 'rb') # opens the csv file

serial=sys.argv[2] # e.g. '4001'

ofile_h  = open('rx.l.'+serial+'.h.csv', "w")

ofile_v  = open('rx.l.'+serial+'.v.csv', "w")

writer_h = csv.writer(ofile_h, delimiter=',', quotechar='"')
writer_v = csv.writer(ofile_v, delimiter=',', quotechar='"')

try:
    reader = csv.reader(ifile)  # creates the reader object
    writer_h.writerow(["#RxL_SN" + serial + "_calculated_noise_H_chan"])
    writer_h.writerow(["# f (Hz)",   "T_e_cal (K)"])
    writer_v.writerow(["#RxL_SN" + serial + "_calculated_noise_V_chan"])
    writer_v.writerow(["# f (Hz)",   "T_e_cal (K)"])
    reader.next()
    for row in reader:   # iterates the rows of the file in orders
         writer_h.writerow([row[0], row[1]])
         writer_v.writerow([row[0], row[2]])
finally:
    ifile.close()      # closing
    ofile_h.close()      # closing
    ofile_v.close()      # closing