# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Utilities for reading or working with Camera geometry files
"""
import logging

import numpy as np
from astropy import units as u
from astropy.coordinates import Angle, SkyCoord
from astropy.table import Table
from astropy.utils import lazyproperty
from scipy.spatial import cKDTree as KDTree
from scipy.sparse import lil_matrix, csr_matrix
import warnings

from ctapipe.utils import get_table_dataset
from ctapipe.utils.linalg import rotation_matrix_2d
from ctapipe.coordinates import CameraFrame

__all__ = [
    "CameraGeometry",
    "UnknownPixelShapeWarning"
]

logger = logging.getLogger(__name__)

class CameraGeometry:
    """`CameraGeometry` is a class that stores information about a
    Cherenkov Camera that us useful for imaging algorithms and
    displays. It contains lists of pixel positions, areas, pixel
    shapes, as well as a neighbor (adjacency) list and matrix for each pixel.
    In general the neighbor_matrix attribute should be used in any algorithm
    needing pixel neighbors, since it is much faster. See for example
    `ctapipe.image.tailcuts_clean`

    The class is intended to be generic, and work with any Cherenkov
    Camera geometry, including those that have square vs hexagonal
    pixels, gaps between pixels, etc.

    You can construct a CameraGeometry either by specifying all data,
    or using the `CameraGeometry.guess()` constructor, which takes metadata
    like the pixel positions and telescope focal length to look up the rest
    of the data. Note that this function is memoized, so calling it multiple
    times with the same inputs will give back the same object (for speed).

    Parameters
    ----------
    self: type
        description
    camera_name: str
         Camera name (e.g. NectarCam, LSTCam, ...)
    pix_id: array(int)
        pixels id numbers
    pix_x: array with units
        position of each pixel (x-coordinate)
    pix_y: array with units
        position of each pixel (y-coordinate)
    pix_area: array(float)
        surface area of each pixel, if None will be calculated
    neighbors: list(arrays)
        adjacency list for each pixel
    pix_type: string
        either 'rectangular' or 'hexagonal'
    pix_rotation: value convertable to an `astropy.coordinates.Angle`
        rotation angle with unit (e.g. 12 * u.deg), or "12d"
    cam_rotation: overall camera rotation with units
    """

    _geometry_cache = {}  # dictionary CameraGeometry instances for speed

    def __init__(self, camera_name, pix_id, pix_x, pix_y, pix_area, pix_type,
                 pix_rotation="0d", cam_rotation="0d",
                 neighbors=None, apply_derotation=True, frame=None):

        if pix_x.ndim != 1 or pix_y.ndim != 1:
            raise ValueError(f'Pixel coordinates must be 1 dimensional, got {pix_x.ndim}')

        assert len(pix_x) == len(pix_y), 'pix_x and pix_y must have same length'
        self.n_pixels = len(pix_x)
        self.camera_name = camera_name
        self.pix_id = pix_id
        self.pix_x = pix_x
        self.pix_y = pix_y
        self.pix_area = pix_area
        self.pix_type = pix_type
        self.pix_rotation = Angle(pix_rotation)
        self.cam_rotation = Angle(cam_rotation)
        self._neighbors = neighbors
        self.frame = frame

        if neighbors is not None:
            if isinstance(neighbors, list):
                lil = lil_matrix((self.n_pixels, self.n_pixels), dtype=bool)
                for pix_id, neighbors in enumerate(neighbors):
                    lil[pix_id, neighbors] = True
                self._neighbors = lil.tocsr()
            else:
                self._neighbors = csr_matrix(neighbors)

        if self.pix_area is None:
            self.pix_area = self.guess_pixel_area(
                pix_x, pix_y, pix_type
            )

        if apply_derotation:
            # todo: this should probably not be done, but need to fix
            # GeometryConverter and reco algorithms if we change it.
            self.rotate(cam_rotation)

        # cache border pixel mask per instance
        self.border_cache = {}

    def __eq__(self, other):
        if self.camera_name != other.camera_name:
            return False

        if self.n_pixels != other.n_pixels:
            return False

        if self.pix_type != other.pix_type:
            return False

        if self.pix_rotation != other.pix_rotation:
            return False

        return all([
            (self.pix_x == other.pix_x).all(),
            (self.pix_y == other.pix_y).all(),
        ])

    def guess_radius(self):
        '''
        Guess the camera radius as mean distance of the border pixels from
        the center pixel
        '''
        border = self.get_border_pixel_mask()
        cx = self.pix_x.mean()
        cy = self.pix_y.mean()

        return np.sqrt(
            (self.pix_x[border] - cx)**2
            + (self.pix_y[border] - cy)**2
        ).mean()

    def transform_to(self, frame):
        '''
        Transform the pixel coordinates stored in this geometry
        and the pixel and camera rotations to another camera coordinate frame.

        Parameters
        ----------
        frame: ctapipe.coordinates.CameraFrame
            The coordinate frame to transform to.
        '''
        if self.frame is None:
            self.frame = CameraFrame()

        coord = SkyCoord(x=self.pix_x, y=self.pix_y, frame=self.frame)
        trans = coord.transform_to(frame)

        # also transform the unit vectors, to get rotation / mirroring
        uv = SkyCoord(x=[1, 0], y=[0, 1], unit=u.m, frame=self.frame)
        uv_trans = uv.transform_to(frame)
        rot = np.arctan2(uv_trans[0].y, uv_trans[1].y)
        det = np.linalg.det([uv_trans.x.value, uv_trans.y.value])

        cam_rotation = rot + det * self.cam_rotation
        pix_rotation = rot + det * self.pix_rotation

        return CameraGeometry(
            camera_name=self.camera_name,
            pix_id=self.pix_id,
            pix_x=trans.x,
            pix_y=trans.y,
            pix_area=self.pix_area,
            pix_type=self.pix_type,
            pix_rotation=pix_rotation,
            cam_rotation=cam_rotation,
            neighbors=None,
            apply_derotation=False,
            frame=frame,
        )

    def __hash__(self):
        return hash((
            self.camera_name,
            self.pix_x[0].to_value(u.m),
            self.pix_y[0].to_value(u.m),
            self.pix_type,
            self.pix_rotation.deg,
        ))

    def __len__(self):
        return self.n_pixels

    def __getitem__(self, slice_):
        return CameraGeometry(
            camera_name=" ".join([self.camera_name, " sliced"]),
            pix_id=self.pix_id[slice_],
            pix_x=self.pix_x[slice_],
            pix_y=self.pix_y[slice_],
            pix_area=self.pix_area[slice_],
            pix_type=self.pix_type,
            pix_rotation=self.pix_rotation,
            cam_rotation=self.cam_rotation,
            neighbors=None,
            apply_derotation=False,
        )

    @classmethod
    def guess_pixel_area(cls, pix_x, pix_y, pix_type):
        """
        Guess pixel area based on the pixel type and layout.
        This first uses `guess_pixel_width` and then calculates
        area from the given pixel type.

        Note this will not work on cameras with varying pixel sizes.
        """

        dist = cls.guess_pixel_width(pix_x, pix_y)

        if pix_type.startswith('hex'):
            area = 2 * np.sqrt(3) * (dist / 2)**2
        elif pix_type.startswith('rect'):
            area = dist ** 2
        else:
            raise KeyError("unsupported pixel type")

        return np.ones(pix_x.shape) * area

    @lazyproperty
    def pixel_width(self):
        '''
        in-circle diameter for hexagons, edge width for square pixels

        This is calculated from the pixel area.
        '''

        if self.pix_type.startswith('hex'):
            width = 2 * np.sqrt(self.pix_area / (2 * np.sqrt(3)))
        elif self.pix_type.startswith('rect'):
            width = np.sqrt(self.pix_area)
        else:
            raise KeyError("unsupported pixel type")

        return width

    @staticmethod
    def guess_pixel_width(pix_x, pix_y):
        """
        Calculate pixel diameter by looking at the minimum distance between pixels

        Note this will not work on cameras with varying pixel sizes or gaps

        Returns
        -------
            in-circle diameter for hexagons, edge width for square pixels
        """
        return np.min(np.sqrt((pix_x[1:] - pix_x[0])**2 + (pix_y[1:] - pix_y[0])**2))

    @lazyproperty
    def _pixel_circumferences(self):
        """ pixel circumference radius/radii based on pixel area and layout

        """

        if self.pix_type.startswith('hex'):
            circum_rad = np.sqrt(2.0 * self.pix_area / 3.0 / np.sqrt(3))
        elif self.pix_type.startswith('rect'):
            circum_rad = np.sqrt(self.pix_area / 2.0)
        else:
            raise KeyError("unsupported pixel type")

        return circum_rad

    @lazyproperty
    def _kdtree(self):
        """
        Pre-calculated kdtree of all pixel centers inside camera

        Returns
        -------
        kdtree

        """

        pixel_centers = np.column_stack([self.pix_x.to_value(u.m),
                                         self.pix_y.to_value(u.m)])
        return KDTree(pixel_centers)

    @lazyproperty
    def _all_pixel_areas_equal(self):
        """
        Pre-calculated kdtree of all pixel centers inside camera

        Returns
        -------
        True if all pixels are of equal size, False otherwise

        """
        return ~np.any(~np.isclose(self.pix_area.value, self.pix_area[0].value), axis=0)

    @classmethod
    def from_name(cls, camera_name='NectarCam', version=None):
        """
        Construct a CameraGeometry using the name of the camera and array.

        This expects that there is a resource in the `ctapipe_resources` module
        called "[array]-[camera].camgeom.fits.gz" or "[array]-[camera]-[
        version].camgeom.fits.gz"

        Parameters
        ----------
        camera_name: str
            Camera name (e.g. NectarCam, LSTCam, ...)
        version:
            camera version id (currently unused)

        Returns
        -------
        new CameraGeometry
        """

        if version is None:
            verstr = ''
        else:
            verstr = f"-{version:03d}"

        tabname = "{camera_name}{verstr}.camgeom".format(
            camera_name=camera_name, verstr=verstr
        )
        table = get_table_dataset(tabname, role='dl0.tel.svc.camera')
        return CameraGeometry.from_table(table)

    def to_table(self):
        """ convert this to an `astropy.table.Table` """
        # currently the neighbor list is not supported, since
        # var-length arrays are not supported by astropy.table.Table
        return Table([self.pix_id, self.pix_x, self.pix_y, self.pix_area],
                     names=['pix_id', 'pix_x', 'pix_y', 'pix_area'],
                     meta=dict(PIX_TYPE=self.pix_type,
                               TAB_TYPE='ctapipe.instrument.CameraGeometry',
                               TAB_VER='1.1',
                               CAM_ID=self.camera_name,
                               PIX_ROT=self.pix_rotation.deg,
                               CAM_ROT=self.cam_rotation.deg,
                               ))

    @classmethod
    def from_table(cls, url_or_table, **kwargs):
        """
        Load a CameraGeometry from an `astropy.table.Table` instance or a
        file that is readable by `astropy.table.Table.read()`

        Parameters
        ----------
        url_or_table: string or astropy.table.Table
            either input filename/url or a Table instance
        kwargs: extra keyword arguments
            extra arguments passed to `astropy.table.read()`, depending on
            file type (e.g. format, hdu, path)

        """

        tab = url_or_table
        if not isinstance(url_or_table, Table):
            tab = Table.read(url_or_table, **kwargs)

        return cls(
            camera_name=tab.meta.get('CAM_ID', 'Unknown'),
            pix_id=tab['pix_id'],
            pix_x=tab['pix_x'].quantity,
            pix_y=tab['pix_y'].quantity,
            pix_area=tab['pix_area'].quantity,
            pix_type=tab.meta['PIX_TYPE'],
            pix_rotation=Angle(tab.meta['PIX_ROT'] * u.deg),
            cam_rotation=Angle(tab.meta['CAM_ROT'] * u.deg),
        )

    def __repr__(self):
        return (
            "CameraGeometry(camera_name='{camera_name}', pix_type='{pix_type}', "
            "npix={npix}, cam_rot={camrot}, pix_rot={pixrot})"
        ).format(
            camera_name=self.camera_name,
            pix_type=self.pix_type,
            npix=len(self.pix_id),
            pixrot=self.pix_rotation,
            camrot=self.cam_rotation
        )

    def __str__(self):
        return self.camera_name

    @lazyproperty
    def neighbors(self):
        '''A list of the neighbors pixel_ids for each pixel'''
        return [np.where(r)[0].tolist() for r in self.neighbor_matrix]

    @lazyproperty
    def neighbor_matrix(self):
        return self.neighbor_matrix_sparse.A

    @lazyproperty
    def neighbor_matrix_sparse(self):
        if self._neighbors is not None:
            return self._neighbors
        else:
            return self.calc_pixel_neighbors(diagonal=False)

    def calc_pixel_neighbors(self, diagonal=False):
        '''
        Calculate the neighbors of pixels using
        a kdtree for nearest neighbor lookup.

        Parameters
        ----------
        diagonal: bool
            If rectangular geometry, also add diagonal neighbors
        '''
        neighbors = lil_matrix((self.n_pixels, self.n_pixels), dtype=bool)

        if self.pix_type.startswith('hex'):
            max_neighbors = 6
            # on a hexgrid, the closest pixel in the second circle is
            # the diameter of the hexagon plus the inradius away
            # in units of the diameter, this is 1 + np.sqrt(3) / 4 = 1.433
            radius = 1.4
            norm = 2  # use L2 norm for hex
        else:

            # if diagonal should count as neighbor, we
            # need to find at most 8 neighbors with a max L2 distance
            # < than 2 * the pixel size, else 4 neigbors with max L1 distance
            # < 2 pixel size. We take a conservative 1.5 here,
            # because that worked on the PROD4 CHEC camera that has
            # irregular pixel positions.
            if diagonal:
                max_neighbors = 8
                norm = 2
                radius = 1.95
            else:
                max_neighbors = 4
                radius = 1.5
                norm = 1

        for i, pixel in enumerate(self._kdtree.data):
            # as the pixel itself is in the tree, look for max_neighbors + 1
            distances, neighbor_candidates = self._kdtree.query(
                pixel, k=max_neighbors + 1, p=norm
            )

            # remove self-reference
            distances = distances[1:]
            neighbor_candidates = neighbor_candidates[1:]

            # remove too far away pixels
            inside_max_distance = distances < radius * np.min(distances)
            neighbors[i, neighbor_candidates[inside_max_distance]] = True

        # filter annoying deprecation warning from within scipy
        # scipy still uses np.matrix in scipy.sparse, but we do not
        # explicitly use any feature of np.matrix, so we can ignore this here
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=PendingDeprecationWarning)
            if (neighbors.T != neighbors).sum() > 0:
                warnings.warn(
                    'Neighbor matrix is not symmetric. Is camera geometry irregular?'
                )

        return neighbors.tocsr()

    @lazyproperty
    def neighbor_matrix_where(self):
        """
        Obtain a 2D array, where each row is [pixel index, one neighbour
        of that pixel].

        Returns
        -------
        ndarray
        """
        coo = self.neighbor_matrix_sparse.tocoo()
        return np.column_stack([coo.row, coo.col])

    @lazyproperty
    def pixel_moment_matrix(self):
        """
        Pre-calculated matrix needed for higher-order moment calculation,
        up to 4th order.

        Note this is *not* recalculated if the CameraGeometry is modified.

        this matrix M can be multiplied by an image and normalized by the sum to
        get the moments:

        .. code-block:: python3

            M = geom.pixel_moment_matrix()
            moms = (M @ image)/image.sum()

        Returns
        -------
        array:
            x, y, x**2, x*y, y^2, x^3, x^2*y,x*y^2, y^3, x^4, x^3*y, x^2*y2,
            x*y^3, y^4

        """

        x = self.pix_x.value
        y = self.pix_y.value

        return np.row_stack([x, y,
                             x ** 2, x * y, y ** 2,
                             x ** 3, x ** 2 * y, x * y ** 2, y ** 3,
                             x ** 4, x ** 3 * y, x ** 2 * y ** 2, x * y ** 3,
                             y ** 4])

    def rotate(self, angle):
        """rotate the camera coordinates about the center of the camera by
        specified angle. Modifies the CameraGeometry in-place (so
        after this is called, the pix_x and pix_y arrays are
        rotated.

        Notes
        -----

        This is intended only to correct simulated data that are
        rotated by a fixed angle.  For the more general case of
        correction for camera pointing errors (rotations,
        translations, skews, etc), you should use a true coordinate
        transformation defined in `ctapipe.coordinates`.

        Parameters
        ----------

        angle: value convertable to an `astropy.coordinates.Angle`
            rotation angle with unit (e.g. 12 * u.deg), or "12d"

        """
        rotmat = rotation_matrix_2d(angle)
        rotated = np.dot(rotmat.T, [self.pix_x.value, self.pix_y.value])
        self.pix_x = rotated[0] * self.pix_x.unit
        self.pix_y = rotated[1] * self.pix_x.unit
        self.pix_rotation -= Angle(angle)
        self.cam_rotation -= Angle(angle)

    def info(self, printer=print):
        """ print detailed info about this camera """
        printer(f'CameraGeometry: "{self}"')
        printer('   - num-pixels: {}'.format(len(self.pix_id)))
        printer(f'   - pixel-type: {self.pix_type}')
        printer('   - sensitive-area: {}'.format(self.pix_area.sum()))
        printer(f'   - pix-rotation: {self.pix_rotation}')
        printer(f'   - cam-rotation: {self.cam_rotation}')

    @classmethod
    def make_rectangular(cls, npix_x=40, npix_y=40, range_x=(-0.5, 0.5),
                         range_y=(-0.5, 0.5)):
        """Generate a simple camera with 2D rectangular geometry.

        Used for testing.

        Parameters
        ----------
        npix_x : int
            number of pixels in X-dimension
        npix_y : int
            number of pixels in Y-dimension
        range_x : (float,float)
            min and max of x pixel coordinates in meters
        range_y : (float,float)
            min and max of y pixel coordinates in meters

        Returns
        -------
        CameraGeometry object

        """
        bx = np.linspace(range_x[0], range_x[1], npix_x)
        by = np.linspace(range_y[0], range_y[1], npix_y)
        xx, yy = np.meshgrid(bx, by)
        xx = xx.ravel() * u.m
        yy = yy.ravel() * u.m

        ids = np.arange(npix_x * npix_y)
        rr = np.ones_like(xx).value * (xx[1] - xx[0]) / 2.0

        return cls(camera_name=-1,
                   pix_id=ids,
                   pix_x=xx,
                   pix_y=yy,
                   pix_area=(2 * rr) ** 2,
                   neighbors=None,
                   pix_type='rectangular',
                   )

    def get_border_pixel_mask(self, width=1):
        '''
        Get a mask for pixels at the border of the camera of arbitrary width

        Parameters
        ----------
        width: int
            The width of the border in pixels

        Returns
        -------
        mask: array
            A boolean mask, True if pixel is in the border of the specified width
        '''
        if width in self.border_cache:
            return self.border_cache[width]

        # filter annoying deprecation warning from within scipy
        # scipy still uses np.matrix in scipy.sparse, but we do not
        # explicitly use any feature of np.matrix, so we can ignore this here
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=PendingDeprecationWarning)

            if width == 1:
                n_neighbors = self.neighbor_matrix_sparse.sum(axis=1).A1
                max_neighbors = n_neighbors.max()
                mask = n_neighbors < max_neighbors
            else:
                n = self.neighbor_matrix
                mask = (n & self.get_border_pixel_mask(width - 1)).any(axis=1)

        self.border_cache[width] = mask
        return mask

    def position_to_pix_index(self, x, y):
        '''
        Return the index of a camera pixel which contains a given position (x,y)
        in the camera frame. The (x,y) coordinates can be arrays (of equal length),
        for which the methods returns an array of pixel ids. A warning is raised if the
        position falls outside the camera.

        Parameters
        ----------
        x: astropy.units.Quantity (distance) of horizontal position(s) in the camera frame
        y: astropy.units.Quantity (distance) of vertical position(s) in the camera frame

        Returns
        -------
        pix_indices: Pixel index or array of pixel indices. Returns -1 if position falls
                    outside camera
        '''

        if not self._all_pixel_areas_equal:
            logger.warning(" Method not implemented for cameras with varying pixel sizes")

        points_searched = np.dstack([x.to_value(u.m), y.to_value(u.m)])
        circum_rad = self._pixel_circumferences[0].to_value(u.m)
        kdtree = self._kdtree
        dist, pix_indices = kdtree.query(points_searched, distance_upper_bound=circum_rad)
        del dist
        pix_indices = pix_indices.flatten()

        # 1. Mark all points outside pixel circumeference as lying outside camera
        pix_indices[pix_indices == self.n_pixels] = -1

        # 2. Accurate check for the remaing cases (within circumference, but still outside
        # camera). It is first checked if any border pixel numbers are returned.
        # If not, everything is fine. If yes, the distance of the given position to the
        # the given position to the closest pixel center is translated to the distance to
        # the center of a non-border pixel', pos -> pos', and it is checked whether pos'
        # still lies within pixel'. If not, pos lies outside the camera. This approach
        # does not need to know the particular pixel shape, but as the kdtree itself,
        # presumes all camera pixels being of equal size.
        border_mask = self.get_border_pixel_mask()
        # get all pixels at camera border:
        borderpix_indices = np.where(border_mask)[0]
        borderpix_indices_in_list = np.intersect1d(borderpix_indices, pix_indices)
        if borderpix_indices_in_list.any():
            # Get some pixel not at the border:
            insidepix_index = np.where(~border_mask)[0][0]
            # Check in detail whether location is in border pixel or outside camera:
            for borderpix_index in borderpix_indices_in_list:
                index = np.where(pix_indices == borderpix_index)[0][0]
                # compare with inside pixel:
                xprime = (points_searched[0][index, 0]
                          - self.pix_x[borderpix_index].to_value(u.m)
                          + self.pix_x[insidepix_index].to_value(u.m))
                yprime = (points_searched[0][index, 1]
                          - self.pix_y[borderpix_index].to_value(u.m)
                          + self.pix_y[insidepix_index].to_value(u.m))
                dist_check, index_check = kdtree.query([xprime, yprime],
                                                       distance_upper_bound=circum_rad)
                del dist_check
                if index_check != insidepix_index:
                    pix_indices[index] = -1

        # print warning:
        for index in np.where(pix_indices == -1)[0]:
            logger.warning(" Coordinate ({} m, {} m) lies outside camera"
                           .format(points_searched[0][index, 0],
                                   points_searched[0][index, 1]))

        return pix_indices if len(pix_indices) > 1 else pix_indices[0]

    @staticmethod
    def simtel_shape_to_type(pixel_shape):
        if pixel_shape == 1:
            return 'hexagonal', Angle(0, u.deg)

        if pixel_shape == 2:
            return 'rectangular', Angle(0, u.deg)

        if pixel_shape == 3:
            return 'hexagonal', Angle(30, u.deg)

        raise ValueError(f'Unknown pixel_shape {pixel_shape}')

class UnknownPixelShapeWarning(UserWarning):
    pass


from reaper_python import *
import C3toolbox
import sys
import os
sys.argv=["Main"]
import Tkinter

global level_var
global form

def execute(selected):
    global level_var
    global form
    level = str(level_var.get())

    C3toolbox.startup()
    C3toolbox.single_pedal(C3toolbox.array_levels[level][0], 20, selected)
    #instrument, level, fix, selected
    window.close()
    form.destroy()

def launch():
    global level_var
    global form

    C3toolbox.startup()
    form = Tkinter.Tk()
    form.wm_title('Reduce double pedal kicks to single pedal kicks')

    helpLf = Tkinter.Frame(form)
    helpLf.grid(row=0, column=1, sticky='NS', padx=5, pady=5)

    OPTIONS = ["Expert", "Hard", "Medium", "Easy"]

    level_var = Tkinter.StringVar(helpLf)
    level_var.set(OPTIONS[0]) # default value

    levelOpt = apply(Tkinter.OptionMenu, (helpLf, level_var) + tuple(OPTIONS))
    levelOpt.grid(row=0, column=1, columnspan=1, sticky="WE", pady=3)

    allBtn = Tkinter.Button(helpLf, text="Reduce all", command= lambda: execute(0))
    allBtn.grid(row=0, column=2, rowspan=1, sticky="WE", padx=5, pady=2)

    selBtn = Tkinter.Button(helpLf, text="Reduce selected", command= lambda: execute(1))
    selBtn.grid(row=0, column=3, rowspan=1, sticky="WE", padx=5, pady=2)

    logo = Tkinter.Frame(form, bg="#000")
    logo.grid(row=1, column=0, columnspan=10, sticky='WE', \
                 padx=0, pady=0, ipadx=0, ipady=0)

    path = os.path.join( sys.path[0], "banner.gif" )
    img = Tkinter.PhotoImage(file=path)
    imageLbl = Tkinter.Label(logo, image = img, borderwidth=0)
    imageLbl.grid(row=0, column=0, rowspan=2, sticky='E', padx=0, pady=0)

    form.mainloop()

if __name__ == '__main__':
    #launch()
    C3toolbox.startup()
    C3toolbox.reduce_chords('PART GUITAR', 'x', 0)


# -*- coding: utf-8 -*-
#!/usr/bin/env python

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

################################################################################
# Send image for age and gender computation only if there are
# some movement into the video stream.
################################################################################

import cv2
import numpy as np
import angus
import StringIO
import json

# Threshold 1: how many gray level diff is needed for a pixel "change": 0-255
t1 = 10
# Threshold 2: how many changed pixel are needed for considering the image
t2 = 50*50 # square of 50x50 pixels

# Read input webcam at 2 fps
cam = cv2.VideoCapture(0)
cam.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 640)
cam.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 480)
cam.set(cv2.cv.CV_CAP_PROP_FPS, 2)

win_diff = "Movement"
win_sent = "Sent"
cv2.namedWindow(win_diff, cv2.CV_WINDOW_AUTOSIZE)
cv2.namedWindow(win_sent, cv2.CV_WINDOW_AUTOSIZE)

# Read consecutive images
img1 = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
img2 = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)

# Connect to Angus.ai
conn = angus.connect()
serv = conn.services.get_service("age_and_gender_estimation")

# Main loop
while True:
  # Compute the difference between two consecutive images
  diff_img = cv2.absdiff(img1, img2)
  # Threshold the value
  ret, view = cv2.threshold(diff_img, t1, 255, cv2.THRESH_BINARY)

  # Display the diff
  cv2.imshow(win_diff, view)

  # If there are enough difference in the image, send it to Angus.ai
  if np.sum(view)/255 > t2:
    # Display last sent image
    cv2.imshow(win_sent, img2)
    ret, buff = cv2.imencode(".jpg", img2)
    buff = StringIO.StringIO(np.array(buff).tostring())
    job = serv.process({"image": buff})
    print(json.dumps(job.result, indent=4))

  # Read the next image
  img1 = img2
  img2 = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)

  # Wait key and exit if necessary
  if cv2.waitKey(1) & 0xFF == ord('q'):
    cv2.destroyWindow(win_diff)
    cv2.destroyWindow(win_sent)
    break


import time
import traceback

def update_log_fun(dict, func):
    print('update log...')
    file = open('historylog.txt', 'a+')
    file.write(str(dict)+'\n')
    file.write(str(func)+'\n')
    file.close()
    print('finish')

def update_log_time(t0, t1):
    file = open('historylog.txt', 'a+')
    file.write('The progess begins at '+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t0)))
    file.write(',ends at '+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t1))+'.\n')
    file.write('It takes %s s to finish' % (t1-t0)+'.\n\n')
    file.close()

def get_time():
    return time.clock(), time.time()

def update_log_error():
    file = open('historylog.txt', 'a+')
    file.write(traceback.format_exc()+'\n\n')
    file.close


"""
Base Indicator Class for deriving your own indicators
to use within an ``analysis_engine.algo.BaseAlgo``
"""

import uuid
# import analysis_engine.consts as ae_consts
# import analysis_engine.utils as ae_utils
import spylunking.log.setup_logging as log_utils

log = log_utils.build_colorized_logger(name=__name__)

class BaseIndicator:
    """BaseIndicator"""

    def __init__(
            self,
            config_dict,
            path_to_module=None,
            name=None,
            verbose=False):
        """__init__

        Create the object

        :param config_dict:
        :param name:
        :param path_to_module: work in progress -
            this will allow loading indicators from
            outside the repo like the derived algorithm
            classes
            :param verbose:
        """
        self.name = name
        self.config = config_dict
        self.path_to_module = path_to_module
        self.verbose = verbose

        if not self.name:
            self.name = 'ind_{}'.format(
                str(uuid.uuid4()).replace('-', ''))

        if not self.config:
            raise Exception(
                'please provide a config_dict for loading '
                'the buy and sell rules for this indicator')

    # end of __init__

    def get_path_to_module(
            self):
        """get_path_to_module"""
        return self.path_to_module
    # end of get_path_to_module

    def get_name(
            self):
        """get_name"""
        return self.name
    # end of get_name

    def process(
            self,
            algo_id,
            ticker,
            dataset):
        """process

        Derive custom indicator processing to determine buy and sell
        conditions before placing orders. Just implement your own
        ``process`` method.

        Please refer to the TA Lib guides for details on building indicators:

        - Overlap Studies
          https://mrjbq7.github.io/ta-lib/func_groups/overlap_studies.html
        - Momentum Indicators
          https://mrjbq7.github.io/ta-lib/func_groups/momentum_indicators.html
        - Volume Indicators
          https://mrjbq7.github.io/ta-lib/func_groups/volume_indicators.html
        - Volatility Indicators
          https://mrjbq7.github.io/ta-lib/func_groups/volatility_indicators.html
        - Price Transform
          https://mrjbq7.github.io/ta-lib/func_groups/price_transform.html
        - Cycle Indicators
          https://mrjbq7.github.io/ta-lib/func_groups/cycle_indicators.html
        - Pattern Recognition
          https://mrjbq7.github.io/ta-lib/func_groups/pattern_recognition.html
        - Statistic Functions
          https://mrjbq7.github.io/ta-lib/func_groups/statistic_functions.html
        - Math Transform
          https://mrjbq7.github.io/ta-lib/func_groups/math_transform.html
        - Math Operators
          https://mrjbq7.github.io/ta-lib/func_groups/math_operators.html

        :param algo_id: string - algo identifier label for debugging datasets
            during specific dates
        :param ticker: string - ticker
        :param dataset: ``pd.DataFrame`` to process
        """
        log.info(
            '{} process - start'.format(
                self.name))
        log.info(
            '{} process - end'.format(
                self.name))
    # end of process

# end of BaseIndicator


#!/usr/bin/env python
# coding: utf-8

"""
    This script should be called with 1 argument.
    The 1st argument is the ABSOLUTE path of the top directory for the flight campaign.

    /media/spectors/HDD320/lidar/20201218_fresh    <<----- This is it!
    ----------------------------/20201218_fresh/2_planned_mision
    ----------------------------/20201218_fresh/3_planned_mision
    ----------------------------/20201218_fresh/     .....
    ----------------------------/20201218_fresh/6_planned_mision

    There can be other sub-directories present, but only those where
    "puck_data"+"hi_freq_apx" is present will be processed.

    The output is moved to out_dir and the file names get a shortened name of the original directory.
    e.g. 2_planedmiso_low_freq_apx.pcap
    The shortened names are stored along the original in the translation_table text file
    e.g. original_name:orignal_me
    This translation table has to be used by subsequent scripts to understand from where each data comes.
"""

import os, logging, datetime, sys, re, time
from collections import OrderedDict

def shorten_string(text_string):
    """
    Function to remove all duplicates from string
    and keep the order of characters same
    https://www.geeksforgeeks.org/remove-duplicates-given-string-python/
    """
    return "".join(OrderedDict.fromkeys(text_string))

log_dir = 'p_logging'
key_files = ["puck_data", "hi_freq_apx"]
root_names = ["ext_events_apx", "hi_freq_apx", "low_freq_apx", "puck_data", "puck_tele"]
out_dir = 'p_00_joined_pcap_files'
out_base_len = len(out_dir)
transl_table_fn = 'p_transl_table.txt'

data_dirs = []

this_script = sys.argv[0]

if len(sys.argv)<=1:
    print("ERROR\n\nPlease provide the absolute path of the campaign's top directory.\n\nEXITING")
    sys.exit(0)
else:
    top_dir = sys.argv[1].rstrip(os.path.sep)

try:
    os.chdir(top_dir)
    if os.getcwd() != top_dir:
        print("Something went wrong.")
        print(f"cwd: {os.getcwd}")
        sys.exit(0)

    if log_dir not in os.listdir():
        os.mkdir(log_dir)
    while out_dir in os.listdir():
        print(f"{out_dir} already existing.")
        time.sleep(0.1)
        out_dir = f"{out_dir[:out_base_len]}_{str(datetime.datetime.now()).replace(':', '.').replace(' ', '_')}"
    os.mkdir(out_dir)
    print(f"Created {out_dir} for storing the output.")
    logging.basicConfig(format='<%(asctime)s>   <%(levelname)-8s>   <%(message)s>',
                        level=logging.DEBUG,
                        filename=os.path.join(top_dir, log_dir, f'{datetime.date.today().strftime("%Y.%m.%d")}_{this_script}.log'),
                        datefmt='%Y-%m-%d %H:%M:%S')
    logging.info(f"{this_script} has started and received a valid top directory name")
    potential_directories = sorted([sub_dir for sub_dir in os.listdir() if os.path.isdir(os.path.join(top_dir, sub_dir))])
    logging.info("The following potential directories have been found:")
    for sub_dir in potential_directories:
        matches = dict((k, 0) for i, k in enumerate(key_files))
        for kf in key_files:
            matches[kf] = len(re.findall(kf, " ".join(os.listdir(os.path.join(top_dir, sub_dir)))))
        if min(matches.values()) > 0:
            data_dirs.append(sub_dir)
        logging.info(f"....{sub_dir}: {matches}")
    logging.info("....------")
    to_ignore = []
    for d_dir in data_dirs:
        if out_dir[:out_base_len] in d_dir:
            logging.info(f"....Ignoring {d_dir}")
            to_ignore.append(d_dir)
    for d_dir in to_ignore:
        data_dirs.remove(d_dir)
    logging.info("The following directories have data and will be processed:")
    for sub_dir in data_dirs:
        logging.info(f"....{sub_dir}")
    logging.info("....------")

    if transl_table_fn in os.listdir():
        logging.info("Old translation table has been found. Will try to delete.")
        try: os.remove(transl_table_fn)
        except OSError as e:
            logging.info(e)
            logging.info("Failed. Aborting.")
            sys.exit(0)
        logging.info("Succeeded. Continuing.")
    logging.info(f"The output will be written to {out_dir}")
    for sub_dir in data_dirs:
        short_sub_dir = shorten_string(sub_dir)
        with open(transl_table_fn, "a") as fh:
            fh.write(f"{sub_dir}:{short_sub_dir}")
            fh.write("\n")
        logging.info("")
        logging.info(f"....Processing directory: {sub_dir} (Output shortened to {short_sub_dir}).")
        #files are split when capturing. need to merge them first
        for name in root_names:
            to_join = sorted([os.path.join(sub_dir, fn) for fn in os.listdir(sub_dir) if name in fn])
            command = f"mergecap -F pcap -a {' '.join(to_join)} -w {os.path.join(out_dir, f'{short_sub_dir}_{name}')}.pcap"
            logging.info(f"........{command}")
            #print(f"........{command}")
            os.system(command)
        logging.info(f"....Finished processing directory {sub_dir}.")
        logging.info("")
    logging.info("--------------------------------------")
    logging.info(f"The script{this_script} succesfully executed.")
    logging.info(f"Output written to {out_dir}.")
    logging.info(f"Check {transl_table_fn} for file-naming help.")
    logging.info("Exiting.")
    for i in range(10):
        logging.info("")
except Exception as e:
    print(f"failed: {e}")
sys.exit(0)


def square(a):
    return a ** 2

def factorial(x):
    start = 1
    sum = 1
    while start <= x:
        sum = sum * start
        start += 1
    return sum

def count_elements(items):
    count = 0
    for item in items:
        count += 1
    return count

def member(x, xs):
    is_member = False

    for member in xs:
        if member == x:
            is_member = True
            break

    return is_member

def grades_that_pass(students, grades, limit):
    grade_index = 0
    result = []

    for student in students:
        if grades[grade_index] >= limit:
            result = result + [student]
        grade_index += 1
    return result


#!/usr/bin/python

# -*- coding: utf-8 -*-

from __future__ import print_function

import cmd
import os
import sys

import ipaddr
import threading

import gobject
import dbus
import dbus.mainloop.glib

import fcntl    # For lockf()

import logging

DBUS_NAME = 'com.legrandelectric.RemoteAccess.TundevManager'    # The name of bus we are creating in D-Bus
DBUS_OBJECT_ROOT = '/com/legrandelectric/RemoteAccess/TundevManager'    # The root under which we will create a D-Bus object with the username of the account for the tunnelling device for D-Bus communication, eg: /com/legrandelectric/RemoteAccess/TundevManager/1000 to communicate with a TundevBinding instance running for the UNIX account 1000 (/home/1000)
DBUS_SERVICE_INTERFACE = 'com.legrandelectric.RemoteAccess.TundevManager'    # The name of the D-Bus service under which we will perform input/output on D-Bus

class TunnellingDevShell(cmd.Cmd):
    """ Tundev CLI shell offered to tunnelling devices """

    def __init__(self, shell_user_name, logger, lockfilename = None):
        """ Constructor
        \param shell_user_name The user account we are using on the RDV server
        \param logger A logging.Logger to use for log messages
        \param lockfilename The lockfile to grabbed during the whole life duration of the shell
        """
        cmd.Cmd.__init__(self) # cmd is a Python old-style class so we cannot use super()

        self.tunnel_mode = 'L3' # By default, use L3 tunnel mode

        self.username = shell_user_name
        self.logger = logger

        self.prompt = self.username + '$ '

        self._vtun_server_tunnel = None # The vtun tunnel service
        self.lan_ip_address = None
        self.lan_ip_prefix = None
        self.dns_list = None
        self.hostname = None

        self._dbus_loop = gobject.MainLoop()    # Get a reference to the mainloop
        self._bus = dbus.SystemBus()    # Get a reference to the D-Bus system bus
        dbus_manager_object = DBUS_OBJECT_ROOT
        self._dbus_manager_proxy = self._bus.get_object(DBUS_SERVICE_INTERFACE, dbus_manager_object)
        self._dbus_manager_iface = dbus.Interface(self._dbus_manager_proxy, DBUS_SERVICE_INTERFACE)

        self._tundevbinding_dbus_path = None
        self._dbus_binding_proxy = None
        self._dbus_binding_iface = None

        gobject.threads_init() # Allow the mainloop to run as an independent thread
        dbus.mainloop.glib.threads_init()

        self._dbus_loop_thread = threading.Thread(target = self._loopHandleDbus) # Start handling D-Bus messages in a background thread
        self._dbus_loop_thread.setDaemon(True) # D-Bus loop should be forced to terminate when main program exits
        self._dbus_loop_thread.start()
        self._bus.watch_name_owner(DBUS_NAME, self._handleBusOwnerChanged) # Install a callback to run when the bus owner changes

        if not lockfilename is None:
            self._shell_lockfilename = lockfilename
            self._shell_lockfile_fd = open(self._shell_lockfilename, 'w')
            try:
                self.logger.debug('Acquiring lock on ' + lockfilename)
                fcntl.flock(self._shell_lockfile_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except IOError:
                raise Exception('CannotGetLockfile')
            print(str(os.getpid()), file=self._shell_lockfile_fd)
            print(self.username, file=self._shell_lockfile_fd)

    # D-Bus related methods
    def _loopHandleDbus(self):
        """ This method should be run within a thread... This thread's aim is to run the Glib's main loop while the main thread does other actions in the meantime
        This methods will loop infinitely to receive and send D-Bus messages and will only stop looping when the Glib's main loop is stopped using .quit()
        """
        self.logger.debug("Starting dbus mainloop")
        self._dbus_loop.run()
        self.logger.debug("Stopping dbus mainloop")

    def _handleBusOwnerChanged(self, new_owner):
        """ Callback called when our D-Bus bus owner changes
        """
        if new_owner == '':
            self.logger.warn('Lost remote D-Bus manager process on bus name ' + DBUS_NAME)
            raise Exception('LostMasterProcess')
        else:
            pass # Owner exists

    def _get_vtun_shell_config(self):
        """ Retrieve from the remote TundevBindingDBusService, a tundev shell output string

        \return A list of strings containing in each entry, a line for the tundev shell output
        """

        self._assert_registered_to_manager()
        return self._dbus_binding_iface.GetAssociatedClientTundevShellConfig()

    def _register_to_manager(self):
        """ Register to the manager, we will then have a binding allocated for our shell on the manager

        Create a new D-Bus interface object to talk to the newly instanciated binding and store it into self._dbus_binding_iface
        """
        if self.lan_ip_address is None or  self.lan_ip_prefix is None:
            raise Exception('LanIpShouldBeProvidedBeforeRegistrationToManager')
        dns_list = ''
        if self.dns_list is not None:
            dns_list = ' '.join(str(dns) for dns in self.dns_list)  # Convert from Python list to space-separated value string
        hostname = self.hostname
        if hostname is None:
            hostname=''
        self._tundevbinding_dbus_path = self._dbus_manager_iface.RegisterTundevBinding(self.username, self.tunnel_mode, str(self.lan_ip_address) + '/' + str(self.lan_ip_prefix), dns_list, hostname, self._shell_lockfilename)
        # Now create a proxy and interface to be abled to communicate with this binding
        self.logger.debug('Registered to binding with D-Bus object path: "' + str(self._tundevbinding_dbus_path) + '"')
        self._dbus_binding_proxy = self._bus.get_object(DBUS_SERVICE_INTERFACE, self._tundevbinding_dbus_path)
        self._dbus_binding_iface = dbus.Interface(self._dbus_binding_proxy, DBUS_SERVICE_INTERFACE)

    def _is_registered_on_manager(self):
        """ Check if we already have a binding allocated to us on the manager

        \return True if there is a binding allocated to us on the manager
        """
        return not self._tundevbinding_dbus_path is None

    def _assert_registered_to_manager(self):
        """ Make sure we have already a valid registration to the manager
        """
        if not self._is_registered_on_manager():
            self._register_to_manager()

    def _stop_remote_vtun_server(self):
        """ Request the remote TunDevManager to stop the vtund server that handles the tunnelling for this tunnelling device

        Note: we will not do anything is there is no binding allocated to us on the manager
        """
        if self._is_registered_on_manager():    # Only request the stop if there is already a binding allocated to us
            self._dbus_binding_iface.StopTunnelServer()

    def _start_remote_vtun_server(self):
        """ Request the remote TunDevManager to start the vtund server that will perform tunnelling for this tunnelling device
        """
        self._assert_registered_to_manager()
        self._dbus_binding_iface.StartTunnelServer()

    # Shell commands

    def do_get_role(self, args):
        """Usage: get_role

Returns the role of the user account running the current shell, which can be 'master' or 'onsite'"""
        pass    # Virtual, implemented in MasterDevShell and OnsiteDevShell

    def do_get_tunnel_mode(self, args):
        """Usage: get_tunnel_mode

Get the current tunnel mode"""
        if self.tunnel_mode is None:
            print('(unknown)')
        else:
            print(self.tunnel_mode)

    def do_set_tunnelling_dev_dns_server_list(self, args):
        """Usage: set_tunnelling_dev_dns_server_list {dns1} [{dns2}...]

Publish the LAN IP addresses of the tunnelling dev's DNS servers
Argument address should contain a list of IP addresses separated by a spaces
eg: "192.168.1.2 8.8.8.8\""""
        try:
            self.dns_list = [ipaddr.IPv4Address(dns_str) for dns_str in args.split()]
        except ValueError:
            print('Invalid DNS list: ' + args, file=sys.stderr)

    def do_set_tunnelling_dev_lan_ip_address(self, args):
        """Usage: set_tunnelling_dev_lan_ip_address {address}

Publish the LAN IP address of the tunnelling dev
Argument address should contain the IP address and the CIDR prefix separated by a character '/'
eg: "192.168.1.2/24\""""
        try:
            ipv4 = ipaddr.IPv4Network(args)
            self.lan_ip_address = ipv4.ip
            self.lan_ip_prefix = ipv4._prefixlen
        except ValueError:
            print('Invalid IP network: ' + args, file=sys.stderr)

    def do_set_tunnelling_dev_hostname(self, args):
        """Usage: set_tunnelling_dev_hostname '{hostname}'

Publish the hostname of the tunnelling dev
Argument is the hostname string, the string should be surrounded by single quotes, and within the hostname, single quotes and backslashes should be escaped with a backslash
eg: 'lionel\'s onsite'"""
        hostname = args.strip()	# Remove leading and trailing whitespaces
        if len(hostname)<2:
            self.hostname = hostname
        elif hostname[0]!="'" or hostname[-1]!="'":
            self.hostname = hostname
        else:
            try:
                self.hostname = hostname[1:-1].decode('string_escape')
            except:
                print('Invalid hostname: ' + args, file=sys.stderr)

    def do_echo(self, command):
        """Usage: echo {string}

Echo the string provided as parameter back to the console"""
        print(command)

    def do_drop_vtun(self, command):
        """Usage: drop_vtun

Asks the RDV server to drop the vtun tunnel to the tunnelling dev executing this command"""

        self._stop_remote_vtun_server()

    def do_debug_mode(self, args):
        """Usage: debug_mode {on|off}

Switch/exit debug mode (outputs much more feedback on the console in debug mode (debug level rather than warning level))"""
        if args == 'on':
            self.logger.setLevel(logging.DEBUG)
        elif args == 'off':
            self.logger.setLevel(logging.WARNING)
        else:
            print('Unsupported debug mode: ' + args, file=sys.stderr)

    def do_exit(self, args):
        """Usage: exit

Terminates this command-line session"""
        self._dbus_manager_iface.UnregisterTundevBinding(self.username)
        return True

    def do_logout(self, args):
        """Usage: logout

Terminates this command-line session"""
        return self.do_exit(args)

    def do_EOF(self, args):
        """Send EOF (^D) to terminates this command-line session"""
        return self.do_exit(args)

    def _vtun_config_to_str(self):
        """ Dump the vtun parameters on the tunnelling dev side (client side of the tunnel)

        \return A multi-line config used for shell output
        """
        result = '\n'.join(self._get_vtun_shell_config())
        return result;

dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) # Use Glib's mainloop as the default loop for all subsequent code


import sqlite3
from time import strptime, strftime

conn = sqlite3.connect("/home/annalie/Projects/Django/books_project/mysite/db.sqlite3")

c1 = conn.cursor()
c2 = conn.cursor()

for row in c1.execute('SELECT id, transaction_date FROM books_transaction'):
    my_sql = 'UPDATE books_transaction SET transaction_date = \'{0}\' WHERE ID = {1}'.format(strftime('%Y-%m-%d %H:%M:%S.0',strptime(row[1], '%d/%m/%Y')),row[0])
    # print(my_sql)
    c2.execute(my_sql)

conn.commit()
# c2.commit()

c1.close()
c2.close()


import sys
from operator import itemgetter

# Node class definition
class Node(object):
    def __init__(self, value):
        self.value = value  # Splitting value
        self.left = None    # left child
        self.right = None   # right child

    # Function to return a list of all the offsprings of a node
    def get_offsprings(self):
        result = []
        stack = [self]
        node = None
        while stack:
            if node is None:
                node = stack.pop()
            if node is not None:
                result.append(node.value)
                stack.append(node.right)
                node = node.left
        return result

    # Get the leftmost offspring
    def get_leftmost(self):
        if not(self.left):
            return self.value
        else:
            return self.left.get_leftmost()

    # Get rightmost offspring
    def get_rightmost(self):
        if not(self.right):
            return self.value
        else:
            return self.right.get_rightmost()

# Store new point function, parameters, two lists
def add_new_point(lst, number):
    lst.append(number)

# Returns the median POINT of a list,
# if even elements,
# returns the bigger one as I took the picture as an example
# Sort list before use
def median(lst):
    lst_len = len(lst)
    if lst_len == 0:
        return None
    index = (lst_len - 1) // 2
    if (lst_len % 2):
        return (lst[index])
    else:
        return (lst[index + 1])

# Function to build the tree, returns the root at the end,
# takes in a list of points and 0 in the beginning
def build_kd_tree(P, depth):
    if len(P) == 0:
        return None
    elif len(P) == 1:
        return Node(P[0])

    axis = depth % no_dimensions
    P.sort(key=itemgetter(axis))            # Sort the list on the desired axis
    med_value = median(P)                   # Get the median on that axis
    rounded_middle = int(len(P)/2)          # Rounded down middle

    v_left = build_kd_tree(P[:(rounded_middle)], (depth+1))
    v_right = build_kd_tree(P[(rounded_middle+1):], (depth+1))

    median_point = Node(med_value)
    median_point.left = v_left
    median_point.right = v_right
    return median_point

# Function to recursively check if the given point
# is in the rectangle, same as in Task31
# Takes in 3 lists, that is points,
# and a number which indicates the current axis to check
# Returns True or False
def within_range(point_A, point_B, point_C, i):
    if (int(point_A[i]) >= int(point_B[i])
            and int(point_A[i]) <= int(point_C[i])):
        i = i + 1
        if i == (len(point_A)):  # Base case
            return True
        # If the point is within the range,
        # call the function again on the next axis
        else:
            return (True and within_range(point_A, point_B, point_C, i))
    else:
        return False

# Function to recursively check if the given point is in the (hyper)sphere
# First list is the Point to check,
# second is the centre of the sphere, third parameter is the radius
# Returns True or False
def within_range_sphere(point_A, centre, radius):
    total = 0
    for d in range(len(point_A)):
        total = total + (point_A[d]-centre[d])**2
    if total <= radius**2:
        return True
    else:
        return False

# Function to create MinMax lists
# Input: list of Points
# Output: List of tuples, first element is the min, second is max
def create_minmax(points):
    dims = len(points[0])  # Get the dimension of the space
    min_max = []         # Initialise list
    for i in range(dims):
        maximum = points[0][i]
        minimum = maximum
        for j in range(1, len(points)):
            if points[j][i] >= maximum:
                maximum = points[j][i]
            if points[j][i] <= minimum:
                minimum = points[j][i]
        min_max.append([minimum, maximum])
    return min_max

# Check if two regions intersect
# Generate minMax lists before, pass it as parameters
def intersect(minmax1, minmax2):
    for d in range(len(minmax1)):
        if not (
                minmax2[d][0] <= minmax1[d][0] <= minmax2[d][1]
                or minmax2[d][0] <= minmax1[d][1] <= minmax2[d][1]
                or minmax1[d][0] <= minmax2[d][0] <= minmax1[d][1]
                or minmax1[d][0] <= minmax2[d][1] <= minmax1[d][1]):
            return False
    return True

# Fully contained within
# Uses MinMax, generate before
def fully_contained(minmax1, minmax2):
    for d in range(len(minmax1)):
        if not (minmax2[d][0] <= minmax1[d][0]
                and minmax2[d][1] >= minmax1[d][1]):
            return False
    return True

def search_KD_tree(v, start_point, end_point, results):
    # Check if the node has to be returned
    if within_range(v.value, start_point, end_point, 0):
        results.append(v.value)

    if v.left:
        list1 = v.left.get_offsprings()
        minmax1 = create_minmax(list1)
        list2 = [start_point, end_point]
        minmax2 = create_minmax(list2)
        # Fully contained within goes here
        if (fully_contained(minmax1, minmax2)):
            results = results + v.left.get_offsprings()
        # Intersect
        elif(intersect(minmax1, minmax2)):
            results = (
                results
                + search_KD_tree(v.left, start_point, end_point, [])
            )
    # Other side of the tree
    if v.right:
        list1 = v.right.get_offsprings()
        minmax1 = create_minmax(list1)
        list2 = [start_point, end_point]
        minmax2 = create_minmax(list2)
        # Fully contained within goes here
        if (fully_contained(minmax1, minmax2)):
            results = results + v.right.get_offsprings()
        # Intersect
        elif (intersect(minmax1, minmax2)):
            results = (
                results
                + search_KD_tree(v.right, start_point, end_point, [])
            )
    return results

if __name__ == "__main__":
    # Initialisation
    list_of_points = []  # Array for the input numbers

    # Read the first line
    first_line = sys.stdin.readline()
    info = [int(i) for i in first_line.strip().split()]
    no_elements, no_dimensions, no_queries = info

    # Read numbers
    for i in range(no_elements):
        line = sys.stdin.readline()
        input_point = [int(i) for i in line.strip().split()]
        add_new_point(list_of_points, input_point)

    # Create tree
    root = build_kd_tree(list_of_points, 0)

    # Read queries
    for _ in range(no_queries):
        # String manipulations
        line = sys.stdin.readline()
        line = line.strip()
        line = line.replace('[', '')
        line = line.replace(']', '')
        input_point = line.split(' ')
        centre = []

        for i in range(no_dimensions):
            centre.append(int(input_point[i]))
        radius = int(input_point[no_dimensions])

        # Now we create the circumscribed hypercube around the hypersphere
        start = []
        for i in range(no_dimensions):
            start.append(centre[i]-radius)

        end = []
        for i in range(no_dimensions):
            end.append(centre[i]+radius)

        # And call the function on the hypercube,
        # will include unwanted values for now
        points = search_KD_tree(root, start, end, [])
        for p in points:
            if within_range_sphere(p, centre, radius):
                # Print elements that are in the hypersphere
                print(str(p).replace(',', ''), end=" ")
        print("")


#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
from pyembed.markdown import PyEmbedMarkdown
from fontawesome_markdown import FontAwesomeExtension
from embedly_cards import EmbedlyCardExtension
from markdown_newtab import NewTabExtension

MD_EXTENSIONS = [PyEmbedMarkdown(),
                 'superscript',
                 FontAwesomeExtension(),
                 'fenced_code',
                 'smarty',
                 'codehilite(css_class=highlight, linenums=False)',
                 'extra',
                 EmbedlyCardExtension(),
                 NewTabExtension(),
                 ]

AUTHOR = u'Low And Slow Team'
SITENAME = u'Low And Slow Team'
SITEURL = 'http://localhost:8000'

THEME = 'themes/voidy-bootstrap'
#Extra stylesheets, for bootstrap overrides or additional styling
STYLESHEET_FILES = ("pygments/solarizeddark.css", "voidybootstrap_LAST.css",)
CUSTOM_SITE_HEADERS = ("jumbotron_empty.html",)

TIMEZONE = 'America/New_York'

DEFAULT_LANG = u'en'

DATE_FORMATS = {
    'en': ('en_US.utf8','%Y-%B-%d'),
}

CACHE_CONTENT = False
LOAD_CONTENT_CACHE = False
CACHE_PATH = 'cache'

PATH = 'content'
STATIC_PATHS= ['images', 'images/reviews',
               'css',
               'js',
               'pdfs',
               'favicon/favicon.ico',
               'deploy',]

SIDEBAR = 'sidebar.html'
SIDEBAR_HIDE_CATEGORIES = True
SIDEBAR_HIDE_TAGS = False

DEFAULT_PAGINATION = 10

DISPLAY_PAGES_ON_MENU = False
MENUITEMS = [('News', '/category/news/'),
             ('About', '/pages/about/'),
             ]

PAGE_URL = 'pages/{slug}/'
PAGE_SAVE_AS = 'pages/{slug}/index.html'
#PAGE_ORDER_BY = 'page_order'

ARTICLE_URL = 'posts/{date:%Y}/{date:%b}/{date:%d}/{slug}.html'
ARTICLE_SAVE_AS = 'posts/{date:%Y}/{date:%b}/{date:%d}/{slug}.html'
ARTICLE_ORDER_BY = 'date'

CATEGORY_URL = "category/{slug}"
CATEGORY_SAVE_AS = "category/{slug}/index.html"

TAG_URL = "tag/{slug}/"
TAG_SAVE_AS = "tag/{slug}/index.html"

AUTHOR_URL = ''
AUTHOR_SAVE_AS = ''

YEAR_ARCHIVE_SAVE_AS = 'posts/{date:%Y}/index.html'
MONTH_ARCHIVE_SAVE_AS = 'posts/{date:%Y}/{date:%b}/index.html'

NEWEST_FIRST_ARCHIVES = True
REVERSE_CATEGORY_ORDER = True

#Thumbnailer settings
IMAGE_PATH = 'images'
THUMBNAIL_DIR = 'images/t'
THUMBNAIL_SIZES = {
    '100x': '100x?',
    '200x': '200x?',
}
THUMBNAIL_KEEP_NAME = True

PLUGIN_PATHS = ['plugins']
PLUGINS = [
    'categorytpl',
    'embedly_cards',
    'feed_summary',
    'google_embed',
    'gravatar',
    'liquid_tags.img',
    'liquid_tags.include_code',
    'liquid_tags.video',
    'liquid_tags.youtube',
    'minification',
    'pelican-open_graph',
    'pelican-page-order',
    'pelican_gist',
#    'photos',
    'series',
    'subcategory',
    'summary',
    'thumbnailer',
  #  'touch',
    'pin_to_top',
]

# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True


import requests
from datetime import date, timedelta

def get_trending_repositories(top_size=20, days=7):
    url = "https://api.github.com/search/repositories"
    start_date = date.today() - timedelta(days)
    params = {'q': 'created:>{}'.format(start_date), 'sort': 'stars', 'per_page': top_size}
    response = requests.get(url, params)
    return response.json()["items"]

if __name__ == '__main__':
    trending_repositories = get_trending_repositories()
    print("Список интересных репозиториев:")
    for repository in trending_repositories:
        print("Репозиторий {}  имеет {} звёзд, {} открытых задач, и доступен по ссылке: {}".format(
            repository['name'], repository['stargazers_count'], repository['open_issues'], repository['html_url']))


import matplotlib.pyplot as plt
from obspy import read
from obspy.signal.trigger import recursive_sta_lta, trigger_onset

from seisnn.io import get_dir_list

predict_pkl_dir = "/mnt/tf_data/pkl/2017_02"
predict_pkl_list = get_dir_list(predict_pkl_dir)
for i, pkl in enumerate(predict_pkl_list):
    trace = read(pkl).traces[0]
    df = trace.stats.sampling_rate
    cft = recursive_sta_lta(trace.data, int(0.5 * df), int(1. * df))
    on_of = trigger_onset(cft, 1, 0.5)

    # Plotting the results
    ax = plt.subplot(211)
    plt.plot(trace.data, 'k')
    ymin, ymax = ax.get_ylim()
    plt.vlines(on_of[:, 0], ymin, ymax, color='r', linewidth=2)
    plt.vlines(on_of[:, 1], ymin, ymax, color='b', linewidth=2)
    plt.subplot(212, sharex=ax)
    plt.plot(cft, 'k')
    plt.hlines([3.5, 0.5], 0, len(cft), color=['r', 'b'], linestyle='--')
    plt.axis('tight')
    plt.show()


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 22 00:50:22 2018

@author: liyz
"""
import numpy as np

class Particle():

    def __init__(self, idn):
        self.id = idn
        self.position = np.zeros(2)
        self.velocity = np.zeros(2)
        self.pbest = np.zeros(2)
        self.gbest = np.zeros(2)

    def update_pbest(self, func):

        fitness = func(self.position)
        fbest = func(self.pbest)
        if fitness < fbest:
            self.pbest = self.position.copy()
            fbest = func(self.pbest)
        return fbest

    def update_velocity(self, c, v, **kw):

        if 'weight' in kw.keys():
            self.velocity = kw['weight'] * self.velocity + \
                c[0] * np.random.rand() * (self.pbest - self.position) + \
                c[1] * np.random.rand() * (self.gbest - self.position)
        elif 'constrictor' in kw.keys():
            self.velocity = kw['constrictor'] *(self.velocity + \
                c[0] * np.random.rand() * (self.pbest - self.position) + \
                c[1] * np.random.rand() * (self.gbest - self.position))
        else:
            self.velocity = self.velocity + \
                c[0] * np.random.rand() * (self.pbest - self.position) + \
                c[1] * np.random.rand() * (self.gbest - self.position)
        # limitition of velocity
        self.velocity[np.where(self.velocity > v[1])] = v[1]
        self.velocity[np.where(self.velocity < v[0])] = v[0]

    def update_position(self, x):
        self.position += self.velocity

        # limitation of position
        self.position[np.where(self.position > x[1])] = x[1]
        self.position[np.where(self.position < x[0])] = x[0]


__author__ = 'waterkid'
#from ring.models import *
from ring.models import *
from ring.achievement_judger import *
import datetime

# the function need the start date and the end date
# we only judge the achievement in the new data
def achievement_judge_in_sport(openid, st, en):
    list = get_interval_sport(openid, st.replace(hour = 0, minute = 0, second = 0), en.replace(hour = 23, minute = 59, second = 59))
    achievements = achievement_judger_in_sport_everyday(list)
    for id in achievements:
        set_achievements(openid, id)
    sport_data = get_interval_sport(openid, st.replace(hour = 0, minute = 0, second = 0) - timedelta(days = 7), en.replace(hour = 23, minute = 59, second = 59))
    if (achievement_judger_lack_of_steps(sport_data, 7)):
        set_achievements(openid, 10)
    sport_data = get_interval_sport(openid, st.replace(hour = 0, minute = 0, second = 0) - timedelta(days = 30), en.replace(hour = 23, minute = 59, second = 59))
    if (achievement_judger_lack_of_steps(sport_data, 30)):
        set_achievements(openid, 11)
    achievement_judge_continous_sport_in_sunrise(openid, st, en)
    list = get_interval_sport(openid, st.replace(hour = 0, minute = 0, second = 0) - timedelta(hours = 6), en.replace(hour = 23, minute = 59, second = 59))
    if achievement_judger_sport_in_dark(list):
        set_achievements(openid, 8)

def achievement_judge_in_sleeping(openid, st, en):
    current_date = st
    while (current_date <= en):
        list = get_interval_sleep(openid, current_date.replace(hour = 0, minute = 0, second = 0), current_date.replace(hour = 23, minute = 59, second = 59))
        achievements = achievement_judger_in_sleeping_everyday(list)
        for i in achievements:
            set_achievements(openid, i)
        current_date += timedelta(1)

def achievement_judge_continous_sport_in_sunrise(openid, st, en):
    list = []
    for i in range(6):
        tmp = len(get_interval_sport(openid, st.replace(hour = 6, minute = 0, second = 0) - timedelta(days = 6 - i), st.replace(hour = 6, minute = 59, second = 59) - timedelta(days = 6 - i)))
        list.append((tmp > 0))
    for i in range((en - st).days + 1):
        tmp = len(get_interval_sport(openid, st.replace(hour = 6, minute = 0, second = 0) + timedelta(days = i), st.replace(hour = 6, minute = 59, second = 59) - timedelta(days = i)))
        list.append((tmp > 0))
    if achievement_judger_continuous_true(list, 7):
        set_achievements(openid, 7)

# the function need the start date and the end date
# we only judge the achievement in the new data
# the judge rule consume that (doing nothing, taking off the ring) is kinds of sport and not kind of sleep
def achievement_judge_main(openid, st, en):
    #print(st.strftime('%Y-%m-%d'), str(en))
    #print(datetime.datetime.strptime(str(st), '%Y-%m-%d'))
    #st = date(2016, 10, 1)
    #en = date(2017, 12, 31)
    #st = datetime.datetime.strptime(str(st), '%Y-%m-%d')#.replace(tzinfo=timezone.utc)
    #en = datetime.datetime.strptime(str(en), '%Y-%m-%d')
    #datetime.datetime.strptime(str(date),'%Y-%m-%d')
    achievement_judge_in_sleeping(openid, st, en)
    achievement_judge_in_sport(openid, st, en)
    #achievement_judge_in_sport(openid, date(2016, 10, 1), date(2017, 12, 31))
    #achievement_judge_in_sleeping(openid, date(2016, 10, 1), date(2017, 12, 31))
    #achievement_judge_in_sport(openid, datetime.datetime(2016, 10, 1, 0, 0), datetime.datetime(2017, 12, 31, 23, 59))
    #achievement_judge_in_sleeping(openid, datetime.datetime(2016, 10, 1, 0, 0), datetime.datetime(2017, 12, 31, 23, 59))
    #rejudge(openid)

# rejudge for a user in all his data
def rejudge(openid):
    reset_achievements(openid)
    achievement_judge_in_sport(openid, datetime.datetime(2016, 10, 1, 0, 0), datetime.datetime(2017, 12, 31, 23, 59))
    achievement_judge_in_sleeping(openid, datetime.datetime(2016, 10, 1, 0, 0), datetime.datetime(2017, 12, 31, 23, 59))

if __name__=="__main__":
    achievement_judge_main('oryQ3s9vA7FHE1LxkkVIhJxbEHqI', date(year = 2015,month = 11,day = 1), date(year = 2020,month = 1,day = 1))


from inspect import Signature, Parameter
import logging

def make_sig(**fields):
    params = [Parameter(name, Parameter.KEYWORD_ONLY, default=attrs['default_value'])
              for name, attrs
              in fields.items()]
    return Signature(params)

class BaseModelType(type):
    def __new__(cls, clsname, bases, clsdict):
        clsdict['__signature__'] = make_sig(**clsdict.get('_fields', {}))
        return super().__new__(cls, clsname, bases, clsdict)

class BaseModel(metaclass=BaseModelType):
    _fields = {}
    log = logging.getLogger("PyBall.models")

    def __init__(self, **kwargs):
        for name in self._fields:
            default_value = self._fields[name]['default_value']
            raw_value = kwargs.get(name, default_value)
            field_type = self._fields[name]['field_type']
            if isinstance(field_type, list):
                value = [field_type[0](**x) for x in raw_value]
            elif issubclass(field_type, BaseModel):
                value = field_type(**raw_value)
            else:
                value = raw_value
            setattr(self, name, value)

        extra_fields = kwargs.keys() - self._fields.keys()
        if extra_fields:
            self.log.warn("Extra fields found: {}. Upgrade PyBall to access new data fields."
                          .format(', '.join(extra_fields)))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 13 22:54:07 2019

@author: xudachengthu

partially from file:///Users/xudachengthu/Desktop/GH/threshold.html
    and file:///Users/xudachengthu/Desktop/GH/process.html

batch dispose data

/Users/xudachengthu/Downloads/GHdataset/first-problem.h5 --the file downloaded from crowdAI
"""

import numpy as np
import tensorflow as tf
import h5py
import forward
import backward

fipt = "/Users/xudachengthu/Downloads/GHdataset/first-problem.h5"
fopt = "/Users/xudachengthu/Downloads/GHdataset/submission/first-submission-thres.h5"

fipt = "/Users/xudachengthu/Downloads/GHdataset/playground/playground-data.h5"
fopt = "/Users/xudachengthu/Downloads/GHdataset/playground/first-submission-thres.h5"

def restore_model(wf):
    with tf.Graph().as_default():
        x = tf.placeholder(tf.float32, [1, forward.INPUT_NODE])
        y = forward.forwardpro(x, None)
        '''
        ema = tf.train.ExponentialMovingAverage(backward.MOVING_AVERAGE_DECAY)
        ema_restore = ema.variables_to_restore()
        saver = tf.train.Saver(ema_restore)
        '''
        saver = tf.train.Saver()

        with tf.Session() as sess:
            ckpt = tf.train.get_checkpoint_state(backward.MODEL_SAVE_PATH)
            if ckpt and ckpt.model_checkpoint_path:
                saver.restore(sess, ckpt.model_checkpoint_path)

                pf_prob = sess.run(y, feed_dict={x: wf})
                #pf_sign = tf.add(tf.div(tf.sign(tf.subtract(y,0.5)),2),0.5)
                pf_value = np.where(pf_prob > 0.5)[1] + 1
                return pf_value
            else:
                print("No checkpoint file found")
                return -1

def process_submit():
    opd = [('EventID', '<i8'), ('ChannelID', '<i2'), ('PETime', 'f4'), ('Weight', 'f4')]
    with h5py.File(fipt) as ipt, h5py.File(fopt, "w") as opt:
        ent = ipt['Waveform']
        l = len(ent)
        print(l)
        dt = np.zeros(l*500, dtype=opd)
        start = 0
        end = 0
        count = 0
        for i in range(l):
            wr = ent[i]
            pf = restore_model(np.array(wr['Waveform'], dtype=np.float32).reshape([1,1029]) * (1./1000))
            if not len(pf):
                pf = np.array([300])
            end = start + len(pf)
            dt['PETime'][start:end] = pf
            dt['Weight'][start:end] = 1
            dt['EventID'][start:end] = wr['EventID']
            dt['ChannelID'][start:end] = wr['ChannelID']
            start = end
            count = count + 1
            if count == int(l / 100) + 1:
                print(int((i+1) / (l / 100)), end='% ')
                count = 0
        dt = dt[np.where(dt['EventID'] > 0)]
        opt.create_dataset('Answer', data=dt, compression='gzip')

def main():
    process_submit()

if __name__ == '__main__':
    main()


import ConfigParser
import os.path as Path
import os

from . import exceptions

class Settings(object):
    """
    This class handles settings for Resin Python SDK.

    Attributes:
        HOME_DIRECTORY (str): home directory path.
        CONFIG_SECTION (str): section name in configuration file.
        CONFIG_FILENAME (str): configuration file name.
        _setting (dict): default value to settings.

    """

    HOME_DIRECTORY = Path.expanduser('~')
    CONFIG_SECTION = 'Settings'
    CONFIG_FILENAME = 'resin.cfg'

    _setting = {
        'pine_endpoint': 'https://api.resin.io/ewa/',
        'api_endpoint': 'https://api.resin.io/',
        'data_directory': Path.join(HOME_DIRECTORY, '.resin'),
        # cache time : 1 week in milliseconds
        'image_cache_time': (1 * 1000 * 60 * 60 * 24 * 7),
        # token refresh interval: 1 hour in milliseconds
        'token_refresh_interval': (1 * 1000 * 60 * 60)
    }

    _setting['cache_directory'] = Path.join(_setting['data_directory'],
                                            'cache')

    def __init__(self):
        if Path.isdir(self._setting['data_directory']):
            if Path.isfile(Path.join(self._setting['data_directory'],
                                     self.CONFIG_FILENAME)):
                self.__read_settings()
            else:
                self.__write_settings()
        else:
            # data directory doesn't exist
            self.__write_settings()

    def __write_settings(self):
        config = ConfigParser.ConfigParser()
        config.add_section(self.CONFIG_SECTION)
        for key in self._setting:
            config.set(self.CONFIG_SECTION, key, self._setting[key])
        if not Path.isdir(self._setting['data_directory']):
            os.makedirs(self._setting['data_directory'])
        with open(Path.join(self._setting['data_directory'],
                            self.CONFIG_FILENAME), 'wb') as config_file:
            config.write(config_file)

    def __read_settings(self):
        config_reader = ConfigParser.ConfigParser()
        config_reader.read(Path.join(self._setting['data_directory'],
                                     self.CONFIG_FILENAME))
        config_data = {}
        options = config_reader.options(self.CONFIG_SECTION)
        for option in options:
            try:
                config_data[option] = config_reader.get(self.CONFIG_SECTION,
                                                        option)
            except:
                config_data[option] = None
        self._setting = config_data

    def has(self, key):
        """
        Check if a setting exists.

        Args:
            key (str): setting.

        Returns:
            bool: True if exists, False otherwise.

        """

        self.__read_settings()
        if key in self._setting:
            return True
        return False

    def get(self, key):
        """
        Get a setting value.

        Args:
            key (str): setting.

        Returns:
            str: setting value.

        Raises:
            InvalidOption: If getting a non-existent setting.

        """

        try:
            self.__read_settings()
            return self._setting[key]
        except KeyError:
            raise exceptions.InvalidOption(key)

    def get_all(self):
        """
        Get all settings.

        Returns:
            dict: all settings.

        """

        self.__read_settings()
        return self._setting

    def set(self, key, value):
        """
        Set value for a setting.

        Args:
            key (str): setting.
            value (str): setting value.

        """

        self._setting[key] = str(value)
        self.__write_settings()

    def remove(self, key):
        """
        Remove a setting.

        Args:
            key (str): setting.

        Returns:
            bool: True if successful, False otherwise.

        """

        # if key is not in settings, return False
        result = self._setting.pop(key, False)
        if result is not False:
            self.__write_settings()
            return True
        return False


class Enemy:
    def __init__(self,hp=0):
        self.hp = hp#传入实例变量

    @property               #将实例变量设置为私有的属性，重写ｈｐ方法
    def hp(self):
        return self.__hp

    @hp.setter#给这私有属性　安排一个　特定的修改方式
    def hp(self,value):
        if not 0 <= value <= 100:
            raise Exception("血量异常",0 <= value <= 100,value)
        else:
            self.__hp = value

    @hp.getter
    def get_hp(self):
        print("get self")
        return self.__hp

while 1:
    try:
        hp = int(input("输入敌人血量："))
        enemy01 = Enemy(hp)
        print(enemy01.hp)     #这个私有的属性　通过我定义的　方法访问
        break
    except Exception as error:
        print(error.args)


import os
import cv2

import config as cf

def inspect_image():

    for i_frame in range(150, 600):
        for i_view in range(4, 8):
            # txt
            if 0:
                length = {"B": 0, "C": 0}
                for i_file in ["B", "C"]:
                    pathFile = "%sv%d/image%d_%s.txt" % (cf.pathVideo_, i_view, i_frame, i_file)
                    if not os.path.exists(pathFile):
                        print("File not exists: %s" % pathFile)

                    file = open(pathFile, 'r')
                    length[i_file] = len(file.readlines())
                    file.close()
                if length["B"] != length["C"]:
                    print("frame: %d, view: %d" % (i_frame, i_view))
                    print(length)
            # image
            if 1:
                pathFile = "%s%d/%d-%d.bmp" % (cf.pathVideo_, i_view, i_frame, i_view)
                if not os.path.exists(pathFile):
                    print("File not exists: %s" % pathFile)
                else:
                    image = cv2.imread(pathFile)
                    if image is None:
                        print("File error opening: %s" % pathFile)

    print("Finish inspecting.")

if __name__ == "__main__":
    assert False, "aborted"


"""
Custom serializers suitable to translated models.
"""
from django.core.exceptions import FieldDoesNotExist
from rest_framework import serializers
from parler.utils.i18n import get_language

# Similar to DRF itself, expose all fields in the same manner.
from parler_rest.fields import TranslatedFieldsField, TranslatedField, TranslatedAbsoluteUrlField  # noqa

class TranslatableModelSerializerMixin(object):
    """
    Mixin class to be added to a :class:`rest_framework.serializers.ModelSerializer` .
    """

    def save(self, **kwargs):
        """
        Extract the translations and save them after main object save.

        By default all translations will be saved no matter if creating
        or updating an object. Users with more complex needs might define
        their own save and handle translation saving themselves.
        """
        translated_data = self._pop_translated_data()
        instance = super(TranslatableModelSerializerMixin, self).save(**kwargs)
        self.save_translations(instance, translated_data)
        return instance

    def _pop_translated_data(self):
        """
        Separate data of translated fields from other data.
        """
        translated_data = {}
        for field_name, field in self.get_fields().items():
            if isinstance(field, (TranslatedField, TranslatedFieldsField)):
                key = field.source or field_name
                translations = self.validated_data.pop(key, None)
                if translations:
                    translated_data[key] = translations
        return translated_data

    def save_translations(self, instance, translated_data):
        """
        Save translation data into translation objects.
        """
        for meta in self.Meta.model._parler_meta:
            for field_name, translations in translated_data.items():
                for lang_code, translation in translations.items():
                    model_field = instance._get_translated_model(lang_code, auto_create=True, meta=meta)
                    if meta.rel_name == field_name:
                        for trans_field, value in translation.items():
                            setattr(model_field, trans_field, value)
                    elif field_name in meta.get_translated_fields():
                        setattr(model_field, field_name, translation)

        # Go through the same hooks as the regular model,
        # instead of calling translation.save() directly.
        instance.save_translations()

class TranslatableModelSerializer(TranslatableModelSerializerMixin, serializers.ModelSerializer):
    """
    Serializer that saves :class:`TranslatedFieldsField` automatically.
    """
    pass

class TranslatableFlatModelSerializer(TranslatableModelSerializerMixin, serializers.ModelSerializer):
    """
    Serializer that returns a flat model and saves the translations to the activated language.
    """

    def _pop_translated_data(self):
        translated_data = {}
        language_code = self.validated_data.pop('language_code', None) or get_language()
        translated_fields = self._pop_translatable_fields()
        for meta in self.Meta.model._parler_meta:
            translations = {}
            if translated_fields:
                translations[language_code] = translated_fields
                translated_data[meta.rel_name] = translations
        return translated_data

    def _pop_translatable_fields(self):
        """
        Separate translated fields and value from the shared object data.
        """
        translated_fields = {}
        fields = (field for field in self.Meta.model._parler_meta.get_all_fields()
                  if field in self.validated_data)
        for field in fields:
            translated_fields[field] = self.validated_data.pop(field)
        return translated_fields

    def build_field(self, field_name, info, model_class, nested_depth):
        """
        Build fields for translatable fields when not explicitly defined
        """
        field = None
        if field_name not in ('id', 'master'):
            try:
                field = model_class._parler_meta.root_model._meta.get_field(field_name)
            except FieldDoesNotExist:
                pass
        if field is not None:
            return self.build_standard_field(field_name, field)
        return super(TranslatableFlatModelSerializer, self).build_field(
         field_name, info, model_class, nested_depth)


# -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 14:19:52 2019

@author: Ivan Garrido Marquez
"""
import argparse
import tools_for_SBD as sbdt
#from nltk.corpus import brown
import sentence_boundary_detector as sbd
#import nltk
try:
   import cPickle as pickle
except:
   import pickle

#functions to calculate evaluation metrics
def precision(tp,tn,fp,fn):
    return tp/(tp+fp)

def recall(tp,tn,fp,fn):
    return tp/(tp+fn)

def f1measure(tp,tn,fp,fn):
    return 2*(((tp/(tp+fp))*(tp/(tp+fn)))/((tp/(tp+fp))+(tp/(tp+fn))))

def f1measurePR(prec,rec):
    return 2*((prec*rec)/(prec+rec))

def accuracy(tp,tn,fp,fn):
    return (tp+tn)/(tp+tn+fp+fn)

clss_algo="tree"
#clss_algo="mlp"
accu=[]
precs=[]
recs=[]
f1=[]
#for each index
for i in range(0,100,50):
    #select(format name of) the classifier
    classifier="classifiers/"+clss_algo+"_classifier_model_SBD_training_set_matrix_k2_n50_i"+str(i)+"_pickle_pickle.bin"
    #create a new sentence boundary detector with the chosen classifier
    class_file=open(classifier,'rb')
    sbdf=pickle.load(class_file)
    #evaluate for all the rest vectors
    #for every other vector_file
    tp=0
    tn=0
    fp=0
    fn=0
    for test_i in range(0,500,50):
    #if the index is not the one chosen for the classifier
        #print(test_i)
        if test_i!=i:
            #load both files matrix and labels
            matrixf=open("training_set/training_set_matrix_k2_n50_i"+str(test_i)+"_pickle.bin",'rb')
            labelsf=open("training_set/training_set_labels_k2_n50_i"+str(test_i)+"_pickle.bin",'rb')
            test_matrix_slice=pickle.load(matrixf)
            test_labels_slice=pickle.load(labelsf)
            #for each vector in vector_file
            ti=0
            for vector in test_matrix_slice:
                #classify the vector
                prediction=sbdf.predict(vector.reshape(1,-1))
                #verify the prection vs the original label
                #count the tp, fp, tn, fn
                if test_labels_slice[ti]==0:
                    if test_labels_slice[ti]==prediction[0]:
                        tn+=1
                    else:
                        fn+=1
                if test_labels_slice[ti]==1:
                    if test_labels_slice[ti]==prediction[0]:
                        tp+=1
                    else:
                        fp+=1
                ti+=1
#compute evaluation metrics
            ac=accuracy(tp,tn,fp,fn)
            accu.append(ac)
            ps=precision(tp,tn,fp,fn)
            precs.append(ps)
            re=recall(tp,tn,fp,fn)
            recs.append(re)
            f1z=f1measure(tp,tn,fp,fn)
            f1.append(f1z)
        #print(f1)
#output results
print(accu)
print(precs)
print(recs)
print(f1)


import numpy as np
import matplotlib.pyplot as plt
from itertools import product
from scipy.ndimage import gaussian_filter
from scipy.stats import truncnorm, lognorm
import nibabel as nib

## Ensure repeatability during testing
np.random.seed(12345)

## Constants
euler = 0.5772

"""
The idea here is to create 128x128 images with a dose sensitive region where doses in that region are drawn from two distributions
with different means. We then construct a cox model to sample srvival times. The model will depend heavily on another covariate
such that we can remove the dependence on the dose sensitive region or make it stronger.
"""

def generateNoise(shape, blocksize=1, mean=0.0, scale=1.0):
    """
    Generates images with noise. The blocksize is the overall size of the 'pixels' filled with noise.
    For simplicity, blocksize should be a multiple of the image size. It will work even if not, but might look weird
    """
    if blocksize == 1:
        noise = np.random.normal(loc=mean, scale=scale, size=shape)
    else:
        noise = np.zeros(shape) ## has to be the right shape
        for ix,iy in product(range(0, int(shape[0]), blocksize), range(0, int(shape[1]), blocksize)):
            noise[ix:ix+blocksize, iy:iy+blocksize] = np.random.normal(loc=mean, scale=scale)

    # We probably want to do a gaussian blur on the noise now
    noise = gaussian_filter(noise, blocksize)

    return noise

def genSDImage(loc, scale, amp):
    """
    Generates a standard deviation image where the sd is gaussian distributed in space. loc is the y-coordinate where the maximum
    standard deviation is wanted
    """
    sd = np.zeros(imageSize)
    gaus = lambda x,mu,s : np.exp(-(x - mu)**2/(2.0*s**2))
    for i in range(0,imageSize[0]):
        sd[i,:] = gaus(i, loc, scale)

    sd *= amp
    sd[np.where(sd < 1.0)] = 1.0

    return sd

def generateDose(shape, region, bgdose=50.0, std=10.0, enhancement=2.0):
    """
    Generate a dose distribution of the correct shape, with background dose and an enhanced dose in a specified region.
    shape is the tuple image shape, eg (128,128). region is a list of indices where we want the enhancement.
    """
    mean = np.ones(shape) * bgdose
    stdImg = genSDImage(np.min(region[0]), (np.max(region[0]) - np.min(region[0]))/2, std)

    # plt.imshow(stdImg)
    # plt.show()

    mean[region] += enhancement

    bg = np.random.normal(loc=0.0, scale=stdImg)
    bg += mean
    ## smooth the dose a bit by convolving with a gaussian
    bg = gaussian_filter(bg, 10)

    return bg

def T(alpha, lam, N, betas, covSamples):
    """
    Return sampled survival times for a given set of covariates.

    """
    recipAlpha = 1.0 / alpha

    topline = alpha * np.log(np.random.uniform(size=N))
    # print(covSamples[0] )
    bottomline = lam * np.exp(betas[0]*covSamples[0] + betas[1]*covSamples[1])

    samples = recipAlpha * np.log(1.0 - (topline/bottomline))

    return samples

## Definitions for the images
imageSize = (128,128)
regionCentre = (64,64) ## These two match the distributions in the Chen paper
regionSize = (50,50)

## Define indices for the region in the centre
region = np.ogrid[int(regionCentre[0] - regionSize[0]/2):int(regionCentre[0] + regionSize[0]/2), int(regionCentre[1] - regionSize[1]/2):int(regionCentre[1] + regionSize[1]/2)]

def ChenPaperPermutationTest(doses, labels):
    pass

def example():
    ## Example calculation.
    noise = generateNoise(imageSize, blocksize=4, mean=0.0, scale=1.0)

    dose = generateDose(imageSize, region, bgdose=60.0, enhancement=-2.0)
    dose += noise

    plt.imshow(dose)
    plt.colorbar()
    plt.show()

    noise = generateNoise(imageSize, blocksize=4, mean=0.0, scale=1.0)
    eventDose = generateDose(imageSize, region, bgdose=10.0, enhancement=-2.0)
    eventDose += noise

    print(np.mean(dose[region]), np.mean(eventDose[region]))

    # deadImage = nib.Nifti1Image(deadArray, np.eye(4))
    # nib.save(deadImage, sampleImagesDirectory + "generated{0}.nii".format(n))

if __name__ == "__main__":

    # example()

    ## constants for the Cox regression
    stdDev = 12.5
    mean = 15.6 ## std and mean survival time

    alpha = np.pi / (np.sqrt(6) * stdDev)
    lam = alpha * np.exp(-euler -(alpha * mean))

    uniformDose = 2.0 ## This makes it a bit more like the heart dose from Alan's paper
    ## Change uniformDose to 60 to replicate Chen paper

    ## Generate some doses with and without enhancement
    NNoE = 500
    NwE  = 500 ## two groups with 50 images each

    ## Create some arrays to hold the data
    noEnhancementGroup  = np.zeros((NNoE, *imageSize))
    withEnhancementGroup = np.zeros((NwE, *imageSize))

    for i in range(NNoE):
        noEnhancementGroup[i,:,:] = np.abs(generateDose(imageSize, region, bgdose=uniformDose, enhancement=0.0))# + generateNoise(imageSize, blocksize=4, mean=0.0, scale=1.0)

    for i in range(NwE):
        withEnhancementGroup[i,:,:] = generateDose(imageSize, region, bgdose=uniformDose, enhancement=2.0)# + generateNoise(imageSize, blocksize=4, mean=0.0, scale=1.0)

    combinedDose = np.vstack((noEnhancementGroup, withEnhancementGroup))
    N = combinedDose.shape[0]

    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)
    ax1.imshow(noEnhancementGroup[0,:,:])
    ax2.imshow(withEnhancementGroup[0,:,:])
    plt.show()

    ## Now generate some survival times. Assume a covariate which is something like tumour size - a truncated normal with mean about 20. The other covariate is the per-voxel dose.abs
    ## Assume equal betas to begin with. beta = 5E-3

    covariate1 = truncnorm.rvs(-1, np.inf, loc=20, scale=20, size=combinedDose.shape[0])

    # plt.hist(covariate1, bins=100)
    # plt.show()

    covariate2 = np.zeros(combinedDose.shape[0])
    for i in range(covariate2.shape[0]):
        thisDose = combinedDose[i, :,:]
        covariate2[i] = np.mean(thisDose[region])

    # plt.hist(covariate2)
    # plt.show()

    betaCov1 = 1.0E-3
    betaCov2 = 5E-2

    betas = [betaCov1, betaCov2]

    sampledTimes = T(alpha, lam, N, betas, [covariate1 ,covariate2])
    plt.hist(sampledTimes)
    plt.show()

    ## Specify a time to select dead/alive
    timePoint = 12.0
    labels = sampledTimes < 12.0
    labels = labels.astype(np.int32)
    # print(labels.astype(np.int32))

    originalLabels = np.hstack((np.zeros(NNoE), np.ones(NwE)))

    with open("coxData.txt", 'w') as coxData:
        coxData.write("time,status,t,d,hiLo\n")
        for i in range(N):
            coxData.write("{0},{1},{2:.2f},{3:.2f},{4}\n".format(int(sampledTimes[i]), labels[i], covariate1[i], covariate2[i], originalLabels[i]) )
    matrix = np.eye(4)
    with open("simulationCovariates.txt", 'w') as cv, open("simulationIds.txt", 'w') as pid, open("studentStatus.txt", 'w') as sts:
        for i,(time,status,tsize) in enumerate(zip(sampledTimes, originalLabels, covariate1)):
            cv.write("{0}\t{1}\t{2:.2f}\n".format(int(time),status,tsize))
            sts.write("{0}\n".format(status))
            pid.write("{0}.nii\n".format(i))
            thisImage = nib.Nifti1Image(np.rot90(combinedDose[i,:,:], k=1), matrix)
            nib.save(thisImage, "generatedImages\\{0}.nii".format(i))


def move(location, style):
    if style == 0:
        return location
    elif style == 1:
        location[0] -= 1
        return location
    elif style == 2:
        location[1] += 1
        return location
    elif style == 3:
        location[0] += 1
        return location
    elif style == 4:
        location[1] -= 1
        return location

def score(location):
    score = [0] * A
    for tt in range(A):
        if abs(location[0] - AP[tt][1]+1) + abs(location[1] - AP[tt][0]+1) <= AP[tt][2]:
            score[tt] = AP[tt][3]
    return score

def cal(score1, score2):
    result = 0
    if A ==1:
        return max(score1[0], score2[0])
    for i in range(A):
        for j in range(A):
            if i == j:
                pass
            else:
                if score1[i] + score2[j] > result:
                    result = score1[i] + score2[j]
    return result

T = int(input())
for _ in range(T):
    M, A = map(int, input().split())
    move1 = list(map(int, input().split()))
    move2 = list(map(int, input().split()))
    AP = []
    for t in range(A):
        AP.append(list(map(int, input().split())))
    user1 = [0,0]
    user2 = [9,9]
    result = 0
    result += cal(score(user1),score(user2))

    for __ in range(M):
        user1 = move(user1, move1[__])
        user2 = move(user2, move2[__])
        result += cal(score(user1), score(user2))
    print("#%d %d" % (_ + 1, result))


from NanoCore import *

# modeling tool
atoms = io.read_xsf('model.xsf')

# simulation object
sim = s2.Siesta(atoms)

# set simulation options
sim.set_option('kgrid', [1,9,1])
sim.set_option('kshift', [0.0,0.0,0.0])
sim.set_option('MixingWt', 0.05)
sim.set_option('LDOS', 1)            # activate LDOS option
sim.set_option('LDOSE', (-1.0, 1.0)) # LDOS energy range (min, max)

# run siesta
sim.run()

# post-process by siesta scripts
v1, v2, v3 = atoms.get_cell()    # define grid range
v2 = 3*Vector(v2)

origin = Vector(-0.2,-0.2,-0.2)  # define the origin
origin -= 0.5*Vector(v1)

nmesh = [150,150,350]             # the number of gridpoints along v1/2/3

s2.get_ldos(v1, v2, v3, origin, nmesh)


import sys
class Solution(object):
    def calculateMinimumHP(self,dungeon):

        rows = len(dungeon)
        cols = len(dungeon[0])

        mat = []
        for i in range(0,rows):
            mat.append([sys.maxint]* cols)
        mat[rows - 1][cols - 1] = 1
        #print "rows" , rows,"cols", cols
        #print mat[0][0]
        for i in range(rows - 1,-1,-1):
            for j in range(cols - 1,-1,-1):
                #print "inside", i , j , mat[i][j]
                #print "mat 0 0" , mat[0][0]
                if(i - 1 >= 0):
                    val = mat[i][j] - dungeon[i][j]
                    #print val
                    if(val < mat[i - 1][j] and val > 0):
                        mat[i - 1][j] = val
                 #       print i,j,"in if"
                    elif(val <= 0):
                        mat[i - 1][j] = 1
                #        print i,j,"in elif"
                if(j - 1 >= 0):
                    val = mat[i][j] - dungeon[i][j]
                    if(val < mat[i][j - 1] and val > 0):
                        mat[i][j - 1] = val
                    elif(val <= 0):
                        mat[i][j - 1] = 1
               # print mat[i][j]
       # print mat[0][0], mat[0][1]
        val = mat[0][0] - dungeon[0][0]
        if(val > 0):
            return val
        else:
            return 1