'''
ftp文件服务程序
fork server 训练
＠liu
2019-01-17
'''
import os, sys
from socket import *
import time

#将文件处理过程封装
class FtpServer():
    def __init__(self,connfd):
        self.connfd = connfd

    def do_list(self,connfd):
        print("执行List")
        #获取文件列表
        file_list = os.listdir(FILES)
        if not file_list:
            self.connfd.send("文件库目录为空".encode())
            return
        else:
            self.connfd.send(b"ok")
            time.sleep(0.1)
        files = ""
        for file in file_list:
            if file[0] != "." and os.path.isfile(FILES + file):#判断不是隐藏文件(._)
                files = files +file + "#"
                print(files)
        self.connfd.send(files.encode())

    def do_get(self, filename):
        try:
            fd = open(FILES+filename, 'rb')
        except Exception:
            self.connfd.send("文件不存在".encode())
            return

        self.connfd.send(b"ok")
        time.sleep(0.1)
        #循环发送文件内容
        while True:
            data = fd.read(1024)
            #到文件结尾
            if not data:
                time.sleep(0.1)
                self.connfd.send(b"##")
                break
            self.connfd.send(data)
    def do_put(self, filename):
        if os.path.exists(FILES+filename):
            self.connfd.send("文件存在".encode())
            return
        try:
            fd = open(FILES+filename, 'wb')
        except:
            self.connfd.send("上传失败".encode())
            return
        else:
            self.connfd.send(b'ok')
        while True:
            data = self.connfd.recv(1024)
            if data == b"##":
                break
            fd.write(data)
        fd.close()
        print("文件接收上传完毕")

#IP地址
HOST = '0.0.0.0'
PORT = 8888
ADDR =(HOST, PORT)
FILES = "/home/tarena/abc/"
#封装并发网络模型
def main():
#创建服务端套接字
    s = socket()
    s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    s.bind(ADDR)
    s.listen(5)
    print("listen to 8888.....")

    while True:
        try:
            connfd, addr = s.accept()
        except KeyboardInterrupt:#客户端退出
            s.close()
            sys.exit("服务器退出！")
        except Exception as e:
            print("服务端异常：",e)
            continue
        print("连接到客户端：",addr)
        #创建子进程
        pid = os.fork()
        if pid == 0:
            p = os.fork()#创建２级子进程　避免僵尸进程
            if p == 0:
                s.close()
                #根据客户端请求执行操作 1查找　2下载文件　3上传文件 q 退出
                ftp = FtpServer(connfd)#实例化对象
                while True:
                    #接收请求
                    data = connfd.recv(1024).decode()
                    print("服务端接收data:",data)
                    if not data or data[0] == "Q":#如果客户端空格回车　或者输入Q
                        connfd.close()
                        sys.exit("客户端退出")
                    elif data[0]== "L":
                        ftp.do_list(connfd)
                    elif data[0] == 'G':
                        filename = data.split(" ")[-1]
                        print("服务端接收的文件名:",filename)
                        ftp.do_get(filename)
                    elif data[0] == 'P':
                        filename = data.split(" ")[-1]
                        print("服务端接收上传的文件名:",filename)
                        ftp.do_put(filename)
            else:
                os._exit(0)
        else:
            connfd.close()
            os.wait()
main()


from Tug.Artefacts.Map import Map
from Tug.Artefacts.Map.Destination import Destination
from Tug.Artefacts.Reference import Reference
from Tug import Artefacts
from Tug.Util.Publish import File

def Create(structure):
    # Somewhere to hold the destinations
    destinations = []

    # Loop over all the items
    for key, value in structure.items():
        # What type of object do we have?
        if(isinstance(value, Destination)):
            # Object is already a destination
            destinations.append(value)

        elif(isinstance(value, dict)):
            # Object is a dictionary, create another map
            final = None
            for artefact in Create(value):
                yield artefact
                final = artefact

            # Create destination for map
            destinations.append(Destination(key, Artefacts.ARTEFACT_MAP, Reference(final.checksum, final.size)))

        else:
            # Object must be a file (probably)
            final = None
            for artefact in File.Create(value):
                yield artefact
                final = artefact

            # Create destination for file
            destinations.append(Destination(key, Artefacts.ARTEFACT_FILE, Reference(final.checksum, final.size)))

    # Create the actual map
    yield Map(destinations)


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

"""
This module deals with hexagonal twin structure.
"""

from pprint import pprint
import numpy as np
from phonopy.structure.atoms import atom_data, symbol_map
from phonopy.structure.cells import Supercell, shape_supercell_matrix
from twinpy.properties.hexagonal import (get_hcp_atom_positions,
                                         check_cell_is_hcp)
from twinpy.properties.twinmode import TwinIndices
from twinpy.structure.lattice import CrystalLattice
from twinpy.interfaces.phonopy import (get_phonopy_structure,
                                       get_cell_from_phonopy_structure)

def get_supercell(cell, supercell_matrix):
    ph_cell = get_phonopy_structure(cell)
    sup_mat = shape_supercell_matrix(supercell_matrix)
    sup = Supercell(ph_cell, supercell_matrix=sup_mat)
    sup_cell = get_cell_from_phonopy_structure(sup)
    return sup_cell

def get_numbers_from_symbols(symbols:list):
    """
    Get atomic numbers from symbols.

    Args:
        symbols: Atomic symbols.
    """
    numbers = [ symbol_map[symbol] for symbol in symbols ]
    return numbers

def get_symbols_from_numbers(numbers:list):
    """
    Get symbols from atomic numbers.

    Args:
        numbers: Atomic numbers.
    """
    symbols = [ atom_data[number][1] for number in numbers ]
    return symbols

def check_same_cells(first_cell:tuple,
                     second_cell:tuple,
                     raise_error:bool=False,
                     atol:float=1e-6) -> bool:
    """
    Check first cell and second cell are same.

    Args:
        first_cell: First cell.
        second_cell: Second cell.
        raise_error: If True, raise assrtion error.

    Returns:
        bool: Return True if two cells are same.
    """
    is_lattice_same = np.allclose(first_cell[0], second_cell[0], atol=atol)
    is_scaled_positions_same = np.allclose(
            first_cell[1], second_cell[1], atol=atol)
    is_symbols_same = (first_cell[2] == second_cell[2])
    is_same = (is_lattice_same
               and is_scaled_positions_same
               and is_symbols_same)
    if not is_same and raise_error:
        np.testing.assert_allclose(first_cell[0], second_cell[0], atol=atol)
        np.testing.assert_allclose(first_cell[1], second_cell[1], atol=atol)
        assert (first_cell[2] == second_cell[2])

    return is_same

def get_atom_positions_from_lattice_points(lattice_points:np.array,
                                           atoms_from_lp:np.array) -> np.array:
    """
    Get atom positions by embedding primitive atoms to lattice points.
    Both lattice points and atom positions must be cartesian coordinates.

    Args:
        lattice_points: Lattice points.
        atoms_from_lp: Atoms from lattice_points.

    Returns:
        np.array: atom positions
    """
    scaled_positions = []
    for lattice_point in lattice_points:
        atoms = lattice_point + atoms_from_lp
        scaled_positions.extend(atoms.tolist())
    return np.array(scaled_positions)

class _BaseTwinStructure():
    """
    Base structure class which is inherited
    ShearStructure class and TwinBoundaryStructure class.
    """

    def __init__(
           self,
           lattice:np.array,
           symbol:str,
           twinmode:str,
           wyckoff:str='c',
           ):
        """
        Setup.

        Args:
            lattice: Lattice.
            symbol: Element symbol.
            twinmode: Twin mode.
            wyckoff: No.194 Wycoff letter ('c' or 'd').

        Todo:
            Check it is best to use 'deepcopy'.
        """
        atoms_from_lp = get_hcp_atom_positions(wyckoff)
        symbols = [symbol] * 2
        crylat = CrystalLattice(lattice=lattice)
        check_cell_is_hcp(cell=(lattice, atoms_from_lp, symbols))
        self._hexagonal_lattice = lattice
        self._a, _, self._c = crylat.abc
        self._r = self._c / self._a
        self._symbol = symbol
        self._wyckoff = wyckoff
        self._atoms_from_lattice_points = \
                get_hcp_atom_positions(wyckoff=self._wyckoff)
        self._natoms = 2
        self._twinmode = None
        self._indices = None
        self._set_twinmode(twinmode=twinmode)
        self._xshift = None
        self._yshift = None
        self._expansion_ratios = np.ones(3)
        self._output_structure = \
                {'lattice': self._hexagonal_lattice,
                 'lattice_points': {
                     'white': np.array([0.,0.,0.])},
                 'atoms_from_lattice_points': {
                     'white': self._atoms_from_lattice_points},
                 'symbols': [self._symbol] * 2}

    def _set_twinmode(self, twinmode:str):
        """
        Set parent.

        Args:
            twinmode: Twinmode.
        """
        self._twinmode = twinmode
        self._indices = TwinIndices(twinmode=self._twinmode,
                                    lattice=self._hexagonal_lattice,
                                    wyckoff=self._wyckoff)

    @property
    def r(self):
        """
        Lattice ratio r  = c / a .
        """
        return self._r

    @property
    def symbol(self):
        """
        Symbol.
        """
        return self._symbol

    @property
    def wyckoff(self):
        """
        Wyckoff letter.
        """
        return self._wyckoff

    @property
    def atoms_from_lattice_points(self):
        """
        Atoms from lattice points.
        """
        return self._atoms_from_lattice_points

    @property
    def hexagonal_lattice(self):
        """
        Hexagonal lattice.
        """
        return self._hexagonal_lattice

    @property
    def xshift(self):
        """
        Structure x shift.
        """
        return self._xshift

    @property
    def yshift(self):
        """
        Structure y shift.
        """
        return self._yshift

    @property
    def natoms(self):
        """
        Number of atoms.
        """
        return self._natoms

    @property
    def twinmode(self):
        """
        Twinmode.
        """
        return self._twinmode

    @property
    def indices(self):
        """
        Indices of twinmode.
        """
        return self._indices

    @property
    def expansion_ratios(self):
        """
        Expansion ratios which is applied when you run 'get_cell_for_export'.
        """
        return self._expansion_ratios

    def set_expansion_ratios(self, expansion_ratios:np.array):
        """
        Set expansion ratios which is applied
        when you run 'get_cell_for_export'.

        Args:
        """
        _expansion_ratios = expansion_ratios.copy()
        if not isinstance(expansion_ratios, np.ndarray):
            _expansion_ratios = np.array(_expansion_ratios)
        assert _expansion_ratios.shape == (3,), \
                 "Shape of expansion_ratios is {}, which must be (3,)".format(
                         np.array(_expansion_ratios).shape)
        self._expansion_ratios = _expansion_ratios

    @property
    def output_structure(self):
        """
        Built structure.
        """
        return self._output_structure

    def get_cell_for_export(self,
                            get_lattice:bool=False,
                            move_atoms_into_unitcell:bool=True,
                            ) -> tuple:
        """
        Get cell for export.

        Args:
            get_lattice: Get lattice points not crystal structure.
            move_atoms_into_unitcell: if True, move atoms to unitcell.

        Returns:
            tuple: Output cell.

        Notes:
            Lattice matrix is expanded using expansion_ratios.
            You have to run set_expansion_ratios before run this function
            if you want to expand lattice.
        """
        _dummy = {'white': 'H', 'white_tb': 'Li',
                  'black': 'He', 'black_tb': 'Be'}
        scaled_positions = []
        if get_lattice:
            symbols = []
            for color in self._output_structure['lattice_points']:
                posi = self._output_structure['lattice_points'][color]
                sym = [_dummy[color]] * len(posi)
                scaled_positions.extend(posi.tolist())
                symbols.extend(sym)
            print("replacing lattice points to elements:")
            print("    'white'   : 'H'")
            print("    'white_tb': 'Li'")
            print("    'black'   : 'He'")
            print("    'black_tb': 'Be'")
        else:
            for color in self._output_structure['lattice_points']:
                posi = get_atom_positions_from_lattice_points(
                    self._output_structure['lattice_points'][color],
                    self._output_structure['atoms_from_lattice_points'][color])
                scaled_positions.extend(posi.tolist())
            scaled_positions = np.round(np.array(scaled_positions), decimals=8)

            if move_atoms_into_unitcell:
                scaled_positions %= 1.

            symbols = self._output_structure['symbols']

        lattice = np.transpose(
                      np.transpose(self._output_structure['lattice'])
                      * self._expansion_ratios)

        return (lattice,
                scaled_positions,
                symbols)


#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author: Li jinjing <lijinjing@gmail.com>
class Solution:
    def findLength(self, A: List[int], B: List[int]) -> int:
        m = len(A)
        n = len(B)
        ans = 0
        dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
        for i in range(1, m+1):
            for j in range(1, n+1):
                if A[i-1] == B[j-1]:
                    dp[i][j] = dp[i-1][j-1] + 1
                    ans = max(ans, dp[i][j])
        return ans

c = Solution()
print(c.findLength2([3,2,1,4,7],[1,2,3,2,1]))


from PIL import Image
import numpy as np
from scipy.ndimage import filters, measurements, morphology

def ganssian_filter():
    # gaussian filter
    img = np.array(Image.open("E:/Mory/rose.jpg").convert("L"))
    img2 = filters.gaussian_filter(img, 5)

    # for RGB img
    img_RGB = np.array(Image.open("E:/Mory/rose.jpg"))
    img2_RGB = np.zeros(img_RGB.shape)
    for i in range(3):
        img2_RGB[:, :, i] = filters.gaussian_filter(img_RGB[:, :, i], 5)
    img2_RGB = np.uint8(img2_RGB)

    return img2, img2_RGB

def sobel_derivative():
    img = np.array(Image.open("E:/Mory/rose.jpg").convert('L'))

    # sobel derivative filters
    img_x = np.zeros(img.shape)
    filters.sobel(img, 1, img_x)

    img_y = np.zeros(img.shape)
    filters.sobel(img, 0, img_y)

    magnitude = np.sqrt(img_x ** 2 + img_y ** 2)
    return magnitude

def gaussian_derivative():
    img = np.array(Image.open("E:/Mory/rose.jpg").convert('L'))

    sigma = 5  # standard deviation
    img_x = np.zeros(img.shape)
    filters.gaussian_filter(img, (sigma, sigma), 1, output=img_x)

    img_y = np.zeros(img.shape)
    filters.gaussian_filter(img, (sigma, sigma), 0, output=img_y)

    return img_x, img_y

def binary_image():
    img = np.array(Image.open("E:/Mory/object.png").convert('L'))
    img = 1 * (img < 128)

    labels, nb_objects = measurements.label(img)
    print("Number of objects:", nb_objects)


"""
Copyright (C) 2014 The HDF Group
Copyright (C) 2014 John Evans

This example code illustrates how to access and visualize a LaRC MOPITT grid
HDF-EOS2 file in Python.

If you have any questions, suggestions, or comments on this example, please use
the HDF-EOS Forum (http://hdfeos.org/forums).  If you would like to see an
example of any other NASA HDF/HDF-EOS data product that is not listed in the
HDF-EOS Comprehensive Examples page (http://hdfeos.org/zoo), feel free to
contact us at eoshelp@hdfgroup.org or post it at the HDF-EOS Forum
(http://hdfeos.org/forums).

Usage:  save this script and run

    python MOP03_CO_Profiles_Day_vertical_lvl178.py

The HDF file must either be in your current working directory or in a directory
specified by the environment variable HDFEOS_ZOO_DIR.

The netcdf library must be compiled with HDF4 support in order for this example
code to work.  Please see the README for details.
"""

import os

import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np

USE_NETCDF4=False

def run(FILE_NAME):

    DATAFIELD_NAME = 'CO Profiles Day'

    if USE_NETCDF4:
        from netCDF4 import Dataset
        nc = Dataset(FILE_NAME)
        data = nc.variables[DATAFIELD_NAME][:, 178, :].astype(np.float64)
        lat = nc.variables['Latitude'][:]
        lon = nc.variables['Longitude'][:]
        pres = nc.variables['Pressure Grid'][:]

    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)

        # Read dataset.
        data3D = hdf.select(DATAFIELD_NAME)
        data = data3D[:, 178, :].astype(np.float64)

        # Read coordinates.
        lat = hdf.select('Latitude')[:]
        lon = hdf.select('Longitude')[:]
        pres = hdf.select('Pressure Grid')[:]

    # Replace the fill value with NaN
    data[data == -9999] = np.nan
    data = np.ma.masked_array(data, np.isnan(data))

    # Contour the data on a grid of longitude vs. pressure
    latitude, pressure = np.meshgrid(lat, pres)
    plt.contourf(latitude, pressure, data.T)
    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1} at Longitude={2} degrees east'.format(basename, DATAFIELD_NAME, lon[178]))
    plt.xlabel('Latitude (degrees_north)')
    plt.ylabel('Pressure Level (hPa)')
    cb = plt.colorbar()
    cb.set_label('ppbv')

    fig = plt.gcf()
    #  plt.show()
    pngfile = "{0}.py.v.png".format(basename)
    fig.savefig(pngfile)

if __name__ == "__main__":

    # If a certain environment variable is set, look there for the input
    # file, otherwise look in the current directory.
    hdffile = 'MOP03-20000303-L3V1.0.1.hdf'
    try:
        hdffile = os.path.join(os.environ['HDFEOS_ZOO_DIR'], hdffile)
    except KeyError:
        pass

    run(hdffile)


"""city URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

from django.urls import path, re_path
# from api import views
from api.views import version, course, degreecourse, shoppingcar, coupon, payment, settlement

urlpatterns = [
    # re_path('^degree_course/$', course.DegreeCourse.as_view()),
    re_path('^version/$', version.Version.as_view()),

    # a.查看所有学位课并打印学位课名称以及授课老师
    re_path('^degree_course/$', degreecourse.DegreeCourse.as_view()),

    # b.查看所有学位课并打印学位课名称以及学位课的奖学金 (b和c共用一个url)
    # d. 查看id=1的学位课对应的所有模块名称
    re_path('^degree_course/(?P<key>\w+)/$',
            degreecourse.DegreeCourse.as_view()),

    # c.展示所有的专题课
    re_path('^course/$', course.Course.as_view()),

    # e.获取id =
    # 1的专题课，并打印：课程名、级别(中文)、why_study、what_to_study_brief、所有recommend_courses
    re_path('^course/(?P<key>\w+)/$', course.Course.as_view()),

    # f.获取id = 1的专题课，并打印该课程相关的所有常见问题

    # g.获取id = 1的专题课，并打印该课程相关的课程大纲

    # h.获取id = 1的专题课，并打印该课程相关的所有章节

    # 优惠券
    re_path('^coupon/$', coupon.Coupon.as_view()),
    re_path('^coupon/(?P<pk>\d+)/$', coupon.CouponDetail.as_view()),
    re_path('^coupon_global/$', coupon.CouponGlobal.as_view()),
    re_path('^coupon_global/(?P<pk>\d+)/$', coupon.CouponGlobal.as_view()),

    # 购物车
    re_path('^shoppingcar/$',
            shoppingcar.ShoppingCar.as_view({'get': 'list', 'post': 'create'})),

    # 结算中心
    re_path('^payment/$',
            payment.Payment.as_view({'get': 'list', 'post': 'create'})),

    # 结算
    re_path('^settlement/$',
            settlement.Settlement.as_view({'get': 'list', 'post': 'create'})),

]


#At this code you can see how to simulate an event and find the value of pi. Beware that expanding the number of events will get better results.

#Let's say we have an empty square which has an arc of quarter circle.
#Radius of circle is 1 unit thus area of quarter circle goes to pi/4 square units.
#Also side of square is 1 unit thus area of square goes to 1 square units.

#The probablity of a random point being inside of the circle is P = Area of Quarter Circle / Area of Square = Pi / 4

#For N samples, M points; M for N samples: M = N*PI/4

from random import random
import numpy as np

points = int(input("How many points do you want to simulate?(Remember more points get better results)"))

inside = 0

for i in range(points):
    x = random()
    y = random()
    if (x**2+y**2)**0.5<1:
        inside=inside+1

simulated_pi = 4.0*(float(inside)/points)
print("The value of simulated pi for {} points is {}".format(points,simulated_pi))
print("The difference between real pi and our simulated pi is: {}".format(np.pi-simulated_pi))


from keras.models import Sequential
from keras.layers.convolutional import Convolution3D
from keras.layers.recurrent_convolutional import LSTMConv2D
from keras.layers.normalization import BatchNormalization
import numpy as np
from pylab import *

# We create a layer whose take movies as input
# of shape (time, width, height, channel) and that return a movie
# with identical shape.

seq = Sequential()
seq.add(LSTMConv2D(nb_filter=40, nb_row=3, nb_col=3,
                   input_shape=(None, 40, 40, 1),
                   border_mode="same", return_sequences=True))
seq.add(BatchNormalization())

seq.add(LSTMConv2D(nb_filter=40, nb_row=3, nb_col=3,
                   border_mode="same", return_sequences=True))
seq.add(BatchNormalization())

seq.add(LSTMConv2D(nb_filter=40, nb_row=3, nb_col=3,
                   border_mode="same", return_sequences=True))
seq.add(BatchNormalization())

seq.add(LSTMConv2D(nb_filter=40, nb_row=3, nb_col=3,
                   border_mode="same", return_sequences=True))
seq.add(BatchNormalization())

seq.add(Convolution3D(nb_filter=1, kernel_dim1=1, kernel_dim2=3,
                      kernel_dim3=3, activation='sigmoid',
                      border_mode="same", dim_ordering="tf"))

seq.compile(loss="binary_crossentropy", optimizer="adadelta")

# Generating artificial data:
# We are going to create a movie with
# square of size one or two by two pixels moving linearly
# trought time. For convenience we first create
# a movie with bigger width and height, and at the end
# we cut it to 40x40

time = 15
row = 80
col = 80
filters = 1
training = 1200
train = np.zeros((training, time, row, col, 1), dtype=np.float)
gt = np.zeros((training, time, row, col, 1), dtype=np.float)

for i in range(training):

    # add from 3 to 7 moving squares
    n = np.random.randint(3, 8)

    for j in range(n):
        # Initial position
        xstart = np.random.randint(20, 60)
        ystart = np.random.randint(20, 60)
        # Direction of motion
        directionx = np.random.randint(0, 3) - 1
        directiony = np.random.randint(0, 3) - 1

        # Size of the square
        w = np.random.randint(2, 4)

        for t in range(time):
            x_shift = xstart + directionx * t
            y_shift = ystart + directiony * t
            train[i, t, x_shift - w: x_shift + w,
                  y_shift - w: y_shift + w, 0] += 1

            # Make it more robust by adding noise.
            # The idea is that if during predict time,
            # the value of the pixel is not exactly one,
            # we need to train the network to be robust and stille
            # consider it is a pixel belonging to a square.
            if np.random.randint(0, 2):
                noise_f = (-1)**np.random.randint(0, 2)
                train[i, t, x_shift - w - 1: x_shift + w + 1,
                      y_shift - w - 1: y_shift + w + 1, 0] += noise_f * 0.1

            # Shitf the ground truth by 1
            x_shift = xstart + directionx * (t + 1)
            y_shift = ystart + directiony * (t + 1)
            gt[i, t, x_shift - w: x_shift + w,
               y_shift - w: y_shift + w, 0] += 1

# Cut to a forty's sized window
train = train[::, ::, 20:60, 20:60, ::]
gt = gt[::, ::, 20:60, 20:60, ::]
train[train >= 1] = 1
gt[gt >= 1] = 1

# Train the network
seq.fit(train[:1000], gt[:1000], batch_size=10,
        nb_epoch=300, validation_split=0.05)

# Testing the network on one movie
# feed it with the first 7 positions and then
# predict the new positions
which = 1004
track = train[which][:7, ::, ::, ::]

for j in range(16):
    new_pos = seq.predict(track[np.newaxis, ::, ::, ::, ::])
    new = new_pos[::, -1, ::, ::, ::]
    track = np.concatenate((track, new), axis=0)

# And then compare the predictions
# to the ground truth
track2 = train[which][::, ::, ::, ::]
for i in range(15):
    fig = figure(figsize=(10, 5))

    ax = fig.add_subplot(121)

    if i >= 7:
        ax.text(1, 3, "Predictions !", fontsize=20, color="w")
    else:
        ax.text(1, 3, "Inital trajectory", fontsize=20)

    toplot = track[i, ::, ::, 0]

    imshow(toplot)
    ax = fig.add_subplot(122)
    text(1, 3, "Ground truth", fontsize=20)

    toplot = track2[i, ::, ::, 0]
    if i >= 2:
        toplot = gt[which][i - 1, ::, ::, 0]

    imshow(toplot)
    savefig("%i_animate.png" % (i + 1))


from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

def plot(x, y, min, max, bins):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    hist, xedges, yedges = np.histogram2d(x, y, bins=bins, range=[[min, max], [min, max]])

    # Construct arrays for the anchor positions of the 16 bars.
    # Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
    # ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid
    # with indexing='ij'.
    xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
    xpos = xpos.flatten('F')
    ypos = ypos.flatten('F')
    zpos = np.zeros_like(xpos)

    # Construct arrays with the dimensions for the 16 bars.
    dx = 0.5 * np.ones_like(zpos)
    dy = dx.copy()
    dz = hist.flatten()

    ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')

    plt.show()


#!/usr/bin/python2

import sys

arr = []
for arr_i in xrange(6):
    arr_temp = map(int,raw_input().strip().split(' '))
    arr.append(arr_temp)

centers = []
tops = []
bottoms = []
for i in range(1,5):
    for j in range(1,5):
        top = []
        bottom = []
        centers.append(arr[i][j])
        top.extend([arr[i-1][j-1], arr[i-1][j], arr[i-1][j+1]])
        bottom.extend([arr[i+1][j-1], arr[i+1][j], arr[i+1][j+1]])
        tops.append(top)
        bottoms.append(bottom)

sums = []
tops_bots = zip(tops,bottoms)
for i in xrange(len(centers)):
    top_sum = sum(tops_bots[i][0][:])
    bot_sum = sum(tops_bots[i][1][:])
    tot = centers[i] + top_sum + bot_sum
    sums.append(tot)


import streamlit as st
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image

st.title('Aula do dia 16/04')

image = Image.open('peppers.png')

imagem_color_arr = np.array(image)

img_gray = np.mean(imagem_color_arr, axis=2)

st.text(img_gray.shape)

# limiar = st.slider('Limiar?', 0, 255, 25)

# st.text(limiar)

img_gray = np.mean(imagem_color_arr, axis=2)

num_color = st.selectbox("Quantas cores?", \
    (2, 4, 8, 16, 32, 64, 128))

if num_color == 2:
    img_gray[img_gray < 127]  = 0
    img_gray[img_gray >= 127]  = 255

else:
    aux = int(255//num_color) + 1

    for i in range(num_color):
        if(i == 0):
            img_gray[img_gray < aux]
            img_gray[img_gray > (255 - aux)] = 255
        else:
            img_gray[((aux * i) < img_gray) & (img_gray < (aux * i+1))] = aux * i

new_image = Image.fromarray(img_gray)
st.image([new_image.convert("L"), image], caption=['Cinza', 'colorida'], width=480,)


# Test script on part of the data: python3 ../scripts/learning_kernel.py train.csv test.csv
# Usage on all data : python3 ../scripts/learning_kernel.py LLCP2015.csv_preprocessing.csv_transformed_train.csv LLCP2015.csv_preprocessing.csv_transformed_test.csv

# Train model on training set with cross-validation using grid search for best parameters.

import pandas as pd
import numpy as np
import sys

# http://stackoverflow.com/questions/4931376/generating-matplotlib-graphs-without-a-running-x-server
# fig.savefig('temp.png')
import matplotlib as mpl

mpl.use('Agg')
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn import model_selection
import time
from sklearn.linear_model import SGDClassifier
from sklearn.kernel_approximation import RBFSampler
from sklearn.pipeline import Pipeline

# https://github.com/scikit-learn/scikit-learn/issues/6943#issuecomment-229003483
from sklearn.externals.joblib import parallel

parallel.MIN_IDEAL_BATCH_DURATION = 1.
parallel.MAX_IDEAL_BATCH_DURATION = parallel.MIN_IDEAL_BATCH_DURATION * 10

def get_X_Y_from_csv(csv_name):
    df = pd.read_csv(csv_name)
    array = df.values
    X = array[:, 1:]
    Y = array[:, 0]
    return X, Y

def estimator_separate_train_test(train, test):
    X, Y = get_X_Y_from_csv(train)
    n = X.shape[0]
    Xtest, Ytest = get_X_Y_from_csv(test)
    rbf_feature = RBFSampler()
    X_features = rbf_feature.fit_transform(X)
    clf = SGDClassifier(class_weight="balanced")
    clf.fit(X_features, Y)
    Ypredict = clf.predict(X_features)

    Xtest_features = rbf_feature.transform(Xtest)
    Ytest_predict = clf.predict(Xtest_features)

    print('score on training and test sets: {:.2f} {:.2f}'.format(clf.score(X_features, Y),
                                                                  clf.score(Xtest_features, Ytest)))
    print('f1 score on training and test sets:{:.2f} {:.2f}'.format(metrics.f1_score(Y, Ypredict),
                                                                    metrics.f1_score(Ytest, Ytest_predict)))
    print('Precision on training and test sets:{:.2f} {:.2f}'.format(metrics.precision_score(Y, Ypredict),
                                                                     metrics.precision_score(Ytest, Ytest_predict)))
    print('Recall on training and test sets: {:.2f} {:.2f}'.format(metrics.recall_score(Y, Ypredict),
                                                                   metrics.recall_score(Ytest, Ytest_predict)))

def grid_search(train, test):
    param_grid = {'rbf__gamma': np.logspace(-4, 3, 7), 'rbf__n_components': [200, 1000, 5000],
                  'sgd__class_weight': [None, 'balanced'], 'sgd__alpha': np.logspace(-6, -1, 5)}
    # Note: 'balanced' performs better than 'None', which yields model with f1 = 0.
    rbf = RBFSampler()
    sgd = SGDClassifier(verbose=100)
    pipe = Pipeline(steps=[('rbf', rbf), ('sgd', sgd)])
    clf = model_selection.GridSearchCV(pipe, param_grid=param_grid, scoring='f1', n_jobs=1, error_score='raise',
                                       verbose=100)
    X, Y = get_X_Y_from_csv(train)
    Xtest, Ytest = get_X_Y_from_csv(test)
    clf.fit(X, Y)

    # print best results and stats for each value of rbf__n_components.
    results = clf.cv_results_
    bestresults = dict()
    for i in range(len(results['param_rbf__n_components'])):
        n = results['param_rbf__n_components'][i]
        if n not in bestresults.keys():
            bestresults[n] = [results['mean_test_score'][i], results['std_test_score'][i],
                              results['mean_train_score'][i], results['mean_fit_time'][i], results['params'][i]]
        elif results['mean_test_score'][i] > bestresults[n][0]:
            bestresults[n] = [results['mean_test_score'][i], results['std_test_score'][i],
                              results['mean_train_score'][i], results['mean_fit_time'][i], results['params'][i]]

    print("Best parameters found for each n on development set:")
    for n in bestresults.keys():
        print('f1 score on test and train set: {:.2f} (+/-{:.2f}), {:.2f}, time: {:.2f} seconds, for {!r}'.format(
            bestresults[n][0], bestresults[n][1], bestresults[n][2], bestresults[n][3], bestresults[n][4]))
    print()
    print("Detailed classification report:")
    print()
    Ypredict = clf.predict(Xtest)
    print(metrics.classification_report(Ytest, Ypredict))

def main(train, test):
    start = time.time()
    # estimator_separate_train_test(train, test)
    grid_search(train, test)
    print('It took %.2f seconds.' % (time.time() - start))

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])


from binascii import hexlify
from io import BytesIO
from .Globals import *
from .ParsingUtils import bytes_to_int
from django.db import models

class ScriptPubKey(models.Model):
    hex = models.CharField()
    asm = models.CharField()
    type = models.CharField()

    def __repr__(self):
        return "{{ \n hex: {}\n asm: {}\n type: {}\n }}".format(
            self.hex, self.asm, self.type
        )

    def to_dict(self):
        return dict(
            hex=self.hex,
            asm=self.asm,
            type=self.type
        )

    @classmethod
    def parse(cls, binary):
        script_pubkey_hex = hexlify(binary).decode('ascii')
        stream = BytesIO(binary)
        elements = []
        byte = stream.read(1)
        while byte != b'':
            num = bytes_to_int(byte)
            if 0 < num <= 75:
                elements.append(hexlify(stream.read(num)).decode('ascii'))
            else:
                elements.append(OP_CODES[num])
            byte = stream.read(1)

        script = ''
        for element in elements:
            script += element + ' '

        script_type = cls.findScriptType(script.strip())
        return cls(script_pubkey_hex, script.strip(), script_type)

    @staticmethod
    def findScriptType(script):
        if ScriptPubKey.isPayToPubKey(script):
            return 'pubkey'
        elif ScriptPubKey.isPayToPubKeyHash(script):
            return 'pubkeyhash'
        elif ScriptPubKey.isPayToScriptHash(script):
            return 'scripthash'
        else:
            return RuntimeError('Unknown Script Type')

    @staticmethod
    def isPayToPubKey(script):
        elements = script.split(' ')
        if elements is None or len(elements) != 1:
            return False
        if elements[0] != 'OP_CHECKSIG':
            return False
        return True

    @staticmethod
    def isPayToPubKeyHash(script):
        elements = script.split(' ')
        if elements is None or len(elements) != 5:
            return False
        if elements[0] != 'OP_DUP' or elements[1] != 'OP_HASH160':
            return False
        if elements[2] is None or len(elements[2]) != LEGACY_ADDRESS_SIZE*2:
            return False
        if elements[3] != 'OP_EQUALVERIFY' or elements[4] != 'OP_CHECKSIG':
            return False
        return True

    @staticmethod
    def isPayToScriptHash(script):
        elements = script.split(' ')
        if elements is None or len(elements) != 3:
            return False
        if elements[0] != 'OP_HASH160':
            return False
        if elements[1] is None or len(elements[1]) != LEGACY_ADDRESS_SIZE*2:
            return False
        if elements[2] != 'OP_EQUAL':
            return False
        return True


import os,sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image

'''
Script to ingest a simc nadir nav file and refine the surface reflector sample location by looking for the max power return.
The output format is identical to the simc nav file.
Note: the sample location won't always correspond to the nadir return.

python findSurface.py [study_area] [window_size] [smoothing_width] [rad_path] [nav_path]

[study_area]: name of the study area, no spaces
[window_size]: desired window size (# of samples), centered on the simc predicted nadir surface return (20-30 are good values)
[smoothing_width]: desired smoothing window width (10-20 are good values)
[rad_path]: path to an archive of radargrams in the PDS .IMG format (e.g., S_01294501_RGRAM.IMG)
[nav_path]: path to the simc-produced nadir nav files (e.g., s_01294501_geom_nadir.csv)

Author: Stefano Nerozzi
Created: 08/Jun/2022
Updated: 28/Jun/2022
'''

# Read and set up arguments
study_area = sys.argv[1]
win_init = int(sys.argv[2])
mavg_size = int(sys.argv[3])
rad_path = sys.argv[4]
nav_path = sys.argv[5]
seis_flag = sys.argv[6]

# Initialize some constants and parameters
r = 3600  # Rows = samples in a trace
c = 0  # Columns = Traces in a radargram
profile = rad_path.split('/')[-1]  # Extract file name
profile = profile.split('_')[1]  # Extract profile number
win_final = win_init  # Initialize second pass window size

# Read the radargram
data = np.fromfile(rad_path, dtype="float32")
c = len(data)//r  # Calculate number of traces
data[data <= 0] = 1e-10  # Turn 0 or negative values into very tiny ones
data = np.reshape(data, (r, c))  # Reshape data into a typical radargram
data_dB = 10 * np.log10(data)  # Change data scale from linear to dB

# Read the simc nav file
nav_data = pd.read_csv(nav_path, sep = ',')  # Read Lat, Lon, predicted nadir surface location from simc nav output file
nad_sample = nav_data['NadirLine'].astype('int')  # Get predicted nadir sample number
nad_sample[nad_sample < 0] = 1800  # Place negative sample numbers into the middle of the radargram

# Find max power surface return near predicted nadir location
sample_maxp_init = np.zeros(c).astype('int')  # Initialize max power sample location array, initial pass
sample_maxp_smooth = np.zeros(c).astype('int')  # Initialize max power sample location array, smoothed by moving avg
sample_maxp_final = np.zeros(c).astype('int')  # Initialize max power sample location array, final pass

try:
    for i in range(c):  # Cycle through every trace
        if (nad_sample[i] - int(win_init / 2) < 0):  # Case where surface is near the top of the radargram
            sample_maxp_init[i] = np.argmax(data_dB[0 : (nad_sample[i] + int(win_init / 2)),i], axis = 0)
        elif (nad_sample[i] + int(win_init / 2) > r):  # Case where surface is near the bottom of the radargram
            sample_maxp_init[i] = np.argmax(data_dB[(nad_sample[i] - int(win_init / 2)) : r,i], axis = 0)
        else: # Case where window does not reach top or bottom of the radargram
            sample_maxp_init[i] = np.argmax(data_dB[(nad_sample[i] - int(win_init / 2)) : (nad_sample[i] + int(win_init / 2)),i], axis = 0)
        sample_maxp_init[i] = int(nad_sample[i] + sample_maxp_init[i] - (win_init / 2))  # Find actual location of max power samples

    sample_maxp_smooth = np.convolve(sample_maxp_init, np.ones((mavg_size,))/mavg_size, mode='same').astype(int)  # Moving average to smooth out the jitter
    for i in range(mavg_size//2):  # Correct the first and last mavg_size/2 samples because they were averaged to zeroes
        sample_maxp_smooth[i] = (sample_maxp_smooth[i] * (mavg_size/(mavg_size//2+i))).astype(int)  # First mavg_size/2 samples
        sample_maxp_smooth[(c-i-1)] = (sample_maxp_smooth[(c-i-1)] * (mavg_size/(mavg_size//2+i+1))).astype(int)  # Last mavg_size/2 samples

    win_final = np.abs(nad_sample - sample_maxp_smooth)*2 + mavg_size//2

    for i in range(c):  # Cycle through every trace a second time with a narrow window
        if (nad_sample[i] - int(win_final[i] / 2) < 0):  # Case where surface is near the top of the radargram
            sample_maxp_final[i] = np.argmax(data_dB[0 : (nad_sample[i] + int(win_final[i] / 2)),i], axis = 0)
        elif (nad_sample[i] + int(win_final[i] / 2) > r):  # Case where surface is near the bottom of the radargram
            sample_maxp_final[i] = np.argmax(data_dB[(nad_sample[i] - int(win_final[i] / 2)) : r,i], axis = 0)
        else: # Case where window does not reach top or bottom of the radargram
            sample_maxp_final[i] = np.argmax(data_dB[(nad_sample[i] - int(win_final[i] / 2)) : (nad_sample[i] + int(win_final[i] / 2)),i], axis = 0)
        sample_maxp_final[i] = int(nad_sample[i] + sample_maxp_final[i] - (win_final[i] / 2))  # Find actual location of max power samples

except Exception as err:
    print(err)
    print('Profile ' + profile + ': Fucking bananas!')

nav_data['NadirLine'] = sample_maxp_final  # Substitute sample locations

# Export cluttersim-like nav file with new sample locations
nav_data['SpacecraftLat'] = nav_data['SpacecraftLat'].map(lambda x: '%.6f' % x)  # Keep original float precision because pandas is stupid
nav_data['SpacecraftLon'] = nav_data['SpacecraftLon'].map(lambda x: '%.6f' % x)  # Keep original float precision because pandas is stupid
nav_data['NadirHgt'] = nav_data['NadirHgt'].map(lambda x: '%.3f' % x)  # Keep original float precision because pandas is stupid
nav_data.to_csv(study_area + '/s_' + profile + '_nadir_maxp_rtrn.csv', index = False)

# Export Seisware horizon
if (seis_flag == "y"):
    seis_data = pd.DataFrame(index=range(c))  # Create new dataframe with one row for each trace
    seis_data['Line Name'] = ('S_' + profile)  # Assign the same profile name for each row
    seis_data['Shot'] = range(1, c+1)  # Use shot, not trace, because trace is for 3D volumes
    seis_data['Time'] = nav_data['NadirLine'] * 37.5e-2  # Multiply sample by 37.5 ns, then by the 1e4 fake time multiplier for Seisware, and 1e3 to get ms
    seis_data['Horizon Name'] = 'autopicked_surface'
    seis_data.to_csv(study_area + '/seisware_surface/S_' + profile + '_surf.csv', index = False)  #, sep=' '

# The following code is for test purposes
'''
noise_floor = np.median(data_dB[:20,:])  # Find a noise floor from median power of first 20 rows
data_dB_scaled = data_dB - noise_floor  # Scale image array by noise floor
maxdB = np.median(np.amax(data_dB_scaled, axis = 0))  # Calculate radargram maximum power from median of maximum power of each trace
data_dB_im = data_dB_scaled / maxdB * 255  # Scale image by maximum power and 255 to turn into a grayscale image
data_dB_im[np.where(data_dB_im < 0)] = 0.  # Get rid of negative pixel values
data_dB_im[np.where(data_dB_im > 255)] = 255.  # Get rid of pixel values over 255

imarray = np.zeros((r,c,3), 'uint8')  # Create empty surf index and power arrays
imarray[:,:,0] = imarray[:,:,1] = imarray[:,:,2] = data_dB_im[:,:]  # Add scaled radargram grayscale image as base

# Indicate first pass max power along track as blue
imarray[sample_maxp_init, np.arange(c),0] = 0
imarray[sample_maxp_init, np.arange(c),1] = 0
imarray[sample_maxp_init, np.arange(c),2] = 255

# Indicate second pass max power along track as red
imarray[sample_maxp_final, np.arange(c),0] = 255
imarray[sample_maxp_final, np.arange(c),1] = 0
imarray[sample_maxp_final, np.arange(c),2] = 0

# Indicate nadir position as yellow
imarray[nad_sample, np.arange(c),0] = 255
imarray[nad_sample, np.arange(c),1] = 255
imarray[nad_sample, np.arange(c),2] = 0

im = Image.fromarray(imarray)
im.save(study_area + "/" + profile +".png")
'''

print("Done processing profile " + profile)


from myds import HashTable

if __name__ == '__main__':
    H = HashTable()

    H[1] = 10
    H[54]="cat"
    H[26]="dog"
    H[93]="lion"
    H[17]="tiger"
    H[77]="bird"
    H[31]="cow"
    H[44]="goat"
    H[55]="pig"
    H[20]="chicken"

    print(H.get(1))
    print(H.slots)
    print(H.data)


ROTATING_ART = 0 # 00000000

MOVING_ART = 2 # 00000010

FONT_ART = 5 # 00000101

FACADE_ART = 9 # 00001001

STATIC_ART = 1 # 00000001
STATIC_ART_2 = 17 # only in eye candy. # 00010001

# We use number values instead of flags right now because right now additional parsing of flags is no necessary
# (There is no not rotating moving font art, fonts are always 5, facade always 9, etc..)
# flag & 0x0001 = isNotRotating
# flag & 0x0002 = isMoving
# flag & 0x0004 = isFont
# flag & 0x0008 = isFacade
# flag & 0x0010 = ??? # only in eye candy


from django.shortcuts import render, redirect, get_object_or_404

from home.models.category import Category
from home.models.project import Project, Project_Pictures, Report_Project, Donation, Rate_Project
from home.models.comment import Comment, Report_Comment
from users.models import Profile
from django.contrib.auth.models import User
from home.forms import ProjectForm, ImageForm, CommentForm, DonationForm, RatingForm
from taggit.models import Tag
from django.template.defaultfilters import slugify
from django.forms.formsets import formset_factory
from django.forms import modelformset_factory
from django.http import JsonResponse
import datetime
import sys
from django.db.models import Sum, Count, Avg, Q
from django.http import Http404

def create_project(request):
    projects = Project.objects.order_by('id')
    common_tags = Project.tags.most_common()[:4]
    form = ProjectForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            project = form.save(commit=False)
            project.slug = slugify(project.title)
            project.user_id = request.user
            project.save()
            form.save_m2m()
            pictures = request.FILES.getlist("photos")
            for picture in pictures:
                Project_Pictures.objects.create(
                    project_id=project,
                    picture=picture
                )

            return redirect("project_details", id=project.id)
    categories = Category.objects.all()
    context = {
        'projects': projects,
        'common_tags': common_tags,
        'form': form,
        'categories': categories
    }
    return render(request, 'project/project_form.html', context)

def project_details(request, id):
    project = get_object_or_404(Project, id=id)
    pictures = Project_Pictures.objects.all().filter(project_id=project)
    comments = Comment.objects.all().filter(project_id=project)
    rate = Rate_Project.objects.all().filter(project_id=project).aggregate(rate=Avg('rate'))
    tags = project.tags.names()
    similar_projects = Project.objects.filter(tags__name__in=tags).order_by('id')[1:5]
    commented_users = {}
    profiles = {}
    for comment in comments:
        profiles[comment.id] = Profile.objects.get(user=comment.user_id)
    comment_form = CommentForm()
    donation_form = DonationForm()
    rating_form = RatingForm()
    donation = Donation.objects.all().filter(project_id=project).aggregate(amount=Sum('amount'))
    categories = Category.objects.all()
    is_deletable = 0
    if donation['amount'] is None:
        donation['amount'] = 0
    if donation['amount'] < project.total_target / 4:
        is_deletable = 1
    context = {
        'project':project,
        'pictures':pictures,
        'comments':comments,
        'commented_users':commented_users,
        'profiles':profiles,
        'comment_form':comment_form,
        'donation_form':donation_form,
        'rating_form':rating_form,
        'donation':donation,
        'rate':rate['rate'],
        'current_user':request.user,
        'is_deletable':is_deletable,
        'similar_projects':similar_projects,
        'categories': categories,

    }
    return render(request, 'project/project_details.html', context)

# def search(request):
#     q = request.GET.get("q")
#     projects = Project.objects.filter(Q(title__icontains=q))
#
#     return render(request, 'project/search.html', {"projects": projects})
#

def project_comment(request, id):
    if request.user.is_authenticated:
        user = request.user
        profile = Profile.objects.get(user=user)
        project = Project.objects.get(id=id)
        comment = Comment.objects.create(project_id=project, user_id=user, text=request.POST.get('text'),
                                         time=datetime.datetime.now())
        # return JsonResponse({'message':'It worked fine'})
        # return HttpResponseRedirect(request.path_info)
        return render(request, 'project/project_comment.html', {'comment': comment, 'user': user, 'profile': profile})
    else:
        raise Http404

def project_report(request, id):
    if request.user.is_authenticated:
        user = request.user
        project = Project.objects.get(id=id)
        report = Report_Project.objects.create(project_id=project, user_id=user, message=request.POST.get('text'))
        return JsonResponse({'message': 'It worked fine'})
        # return HttpResponseRedirect(request.path_info)
        # return render(request, 'project/project_comment.html', {'comment': comment, 'user': user})
    else:
        raise Http404

def comment_report(request, id):
    if request.user.is_authenticated:
        user = request.user
        cid = request.POST.get('id')
        comment = Comment.objects.get(id = cid)
        report = Report_Comment.objects.create(comment_id = comment, user_id = user, message = request.POST.get('text'))
        return JsonResponse({'message':'Your report submited successfully!'})
        #return HttpResponseRedirect(request.path_info)
        #return render(request, 'project/project_comment.html', {'comment': comment, 'user': user})
    else:
        raise Http404
#   if request.method == 'POST':
#     cf = CommentForm(request.POST or None)
#     if cf.is_valid():
#       text = request.POST.get('text')
#       comment = Comment.objects.create(project_id = project, user_id = request.user, text = text)
#       comment.save()
#       return redirect(post.get_absolute_url())
#     else:
#       cf = CommentForm()

#     context ={
#       'comment_form':cf,
#       }
#     return render(request, 'socio / post_detail.html', context)

def tagged(request, slug):
    tag = get_object_or_404(Tag, slug=slug)
    # Filter posts by tag name
    posts = Post.objects.filter(tags=tag)
    categories = Category.objects.all()
    context = {
        'tag': tag,
        'posts': posts,
        'categories': categories
    }
    return render(request, 'home.html', context)

def project_donation(request, id):
    if request.user.is_authenticated:
        user = request.user
        project = Project.objects.get(id=id)
        donation = Donation.objects.create(project_id=project, user_id=user, amount=request.POST.get('amount'))
        donation = Donation.objects.all().filter(project_id=project).aggregate(amount=Sum('amount'))
        return JsonResponse({'donation':donation})
        # return render(request, 'project/project_details.html', {'donation': donation})
    else:
        raise Http404

def project_delete(request, id):
    if request.user.is_authenticated:
        project = Project.objects.get(id = id).delete()
        return redirect("home")
    else:
        raise Http404

def project_rating(request, id):
    if request.user.is_authenticated:
        user = request.user
        project = Project.objects.get(id=id)
        Rate_Project.objects.filter(Q(project_id=project) & Q(user_id=user)).delete()
        rate = Rate_Project.objects.create(project_id=project, user_id=user, rate=request.POST.get('rate'))
        rate = Rate_Project.objects.all().filter(project_id=project).aggregate(rate=Avg('rate'))
        return JsonResponse({'rate': rate})
    else:
        raise Http404

def project(request):
    return render(request, "project/project.html")

def search(request):
    search_proj=request.POST.get('search_proj')

    project_title =Project.objects.filter(Q(title__contains=search_proj))[:1]
    if project_title:
         print(project_title)
         # print(search_proj)
         return redirect("project_details", id=project_title[0].id)
    else:
        #  search_proj = ' '
        # return render(request,"home/index.html")
        return redirect("home")

def categories(request, id):
    projects = Project.objects.all().filter(category=id)
    categories = Category.objects.all()

    context = {
        "projects": projects,
        "categories": categories,
    }

    return render(request, 'project/categories.html', context)

# def search(request):
#     proj_name = request.GET.get('search2')
#     if proj_name:
#         project = Project.objects.filter(Q(title=proj_name))[:1]
#     else:
#         proj_name = ' '
#     return project_details(request, project)


from flask import Flask, jsonify, request,render_template
from flask_cors import cross_origin
import os,random,string,base64
import util

basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)

@app.route('/')
@cross_origin()
def hello():
    return render_template('Search.html')

@app.route('/predict', methods=['POST'])
@cross_origin()
def predict():
    # 获取POST来的图片
    img = request.files['photo']
    # 产生随机图片名 存储到/temp_save/ 生成热力图的对应url
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))
    imgName = ran_str+'_'+img.filename
    path_save = basedir+"/temp_save/"
    path_heatmap = basedir+"/temp_heatmap"
    file_path_save = path_save+imgName
    file_path_heatmap = path_heatmap+imgName
    img.save(file_path_save)
    # 调取ZM的API 传图片url 获取类别int 获取类名和热力图字节流转字符流
    classification=util.temp_func(file_path_save,file_path_heatmap)
    with open(file_path_save, 'rb') as f:
            heatmap_base64 = base64.b64encode(f.read())
    heatmap_base64=heatmap_base64.decode('utf-8')
    # 打包进json 发回前端

    return render_template("Search.html",n=classification,u=heatmap_base64)


"""
// Time Complexity : Average case O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

// Your code here along with comments explaining your approach
Algorithm Explanation
The main twist here is to consider the modified form of bsearch when we come across blank character,
- check for first non blank character in the left and the right -> update the mid accordingly
- follow the normal bsearch comparing string with arr[mid]
"""

def sparse_search(arr,search_word):
    def bsearch(arr,low,high,search_word):
        while low <  high:
            mid = (low + high) // 2
            if arr[mid] == '':
            #check for the nearest possible word which is non blank while checking on the left and the right
                left = mid - 1
                right = mid + 1
                while True:
                        if left < low and right > high: #word not found
                            return -1

                        if left>=low and arr[left]:
                            mid = left
                            break
                        if right<= high and arr[right]:
                            mid = right
                            break

                        left -=1
                        right+=1

            if arr[mid] in search_word:
                return mid
            elif arr[mid] > search_word:
                high = mid - 1
            else:
                low = mid + 1

        return -1

    return bsearch(arr,0,len(arr)-1,search_word)

if __name__ == '__main__':
    print(sparse_search(["for", "geeks", "", "", "", "", "ide", "practice", "", "", "", "quiz"],"geeks"))
    print(sparse_search(["for", "geeks", "", "", "", "", "ide", "practice", "", "", "", "quiz"],"ds"))
    print(sparse_search(["for", "geeks", "", "", "", "", "ide", "practice", "", "", "", "quiz"],"practice"))


#!/usr/bin/env  python
import rospy
from std_msgs.msg import Float64

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_PlatformController(object):
    def setupUi(self, PlatformController):
        PlatformController.setObjectName(_fromUtf8("PlatformController"))
        PlatformController.setEnabled(True)
        PlatformController.resize(690, 532)
        PlatformController.setWindowTitle(_fromUtf8(""))
        self.dockWidgetContents = QtGui.QWidget()
        self.dockWidgetContents.setObjectName(_fromUtf8("dockWidgetContents"))
        self.dial_lf = QtGui.QDial(self.dockWidgetContents)
        self.dial_lf.setGeometry(QtCore.QRect(390, 150, 180, 180))
        self.dial_lf.setMinimum(-400)
        self.dial_lf.setMaximum(400)
        self.dial_lf.setSingleStep(1)
        self.dial_lf.setObjectName(_fromUtf8("dial_lf"))
        self.dial_ri = QtGui.QDial(self.dockWidgetContents)
        self.dial_ri.setGeometry(QtCore.QRect(130, 150, 180, 180))
        self.dial_ri.setMinimum(-90)
        self.dial_ri.setMaximum(90)
        self.dial_ri.setSingleStep(1)
        self.dial_ri.setObjectName(_fromUtf8("dial_ri"))
        self.widget = QtGui.QWidget(self.dockWidgetContents)
        self.widget.setGeometry(QtCore.QRect(230, 10, 231, 121))
        self.widget.setObjectName(_fromUtf8("widget"))
        self.verticalLayout_2 = QtGui.QVBoxLayout(self.widget)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.label_7 = QtGui.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_7.setFont(font)
        self.label_7.setLineWidth(2)
        self.label_7.setTextFormat(QtCore.Qt.AutoText)
        self.label_7.setAlignment(QtCore.Qt.AlignCenter)
        self.label_7.setObjectName(_fromUtf8("label_7"))
        self.verticalLayout_2.addWidget(self.label_7)
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.label_5 = QtGui.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_5.setFont(font)
        self.label_5.setLineWidth(2)
        self.label_5.setTextFormat(QtCore.Qt.AutoText)
        self.label_5.setObjectName(_fromUtf8("label_5"))
        self.horizontalLayout.addWidget(self.label_5)
        self.label_ri_val_read = QtGui.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_ri_val_read.setFont(font)
        self.label_ri_val_read.setMouseTracking(False)
        self.label_ri_val_read.setAcceptDrops(True)
        self.label_ri_val_read.setFrameShape(QtGui.QFrame.StyledPanel)
        self.label_ri_val_read.setLineWidth(2)
        self.label_ri_val_read.setText(_fromUtf8(""))
        self.label_ri_val_read.setTextFormat(QtCore.Qt.AutoText)
        self.label_ri_val_read.setObjectName(_fromUtf8("label_ri_val_read"))
        self.horizontalLayout.addWidget(self.label_ri_val_read)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.label_4 = QtGui.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_4.setFont(font)
        self.label_4.setLineWidth(2)
        self.label_4.setTextFormat(QtCore.Qt.AutoText)
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.horizontalLayout_2.addWidget(self.label_4)
        self.label_lf_val_read = QtGui.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_lf_val_read.setFont(font)
        self.label_lf_val_read.setMouseTracking(False)
        self.label_lf_val_read.setAcceptDrops(True)
        self.label_lf_val_read.setFrameShape(QtGui.QFrame.StyledPanel)
        self.label_lf_val_read.setLineWidth(2)
        self.label_lf_val_read.setText(_fromUtf8(""))
        self.label_lf_val_read.setTextFormat(QtCore.Qt.AutoText)
        self.label_lf_val_read.setObjectName(_fromUtf8("label_lf_val_read"))
        self.horizontalLayout_2.addWidget(self.label_lf_val_read)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtGui.QHBoxLayout()
        self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
        self.label_6 = QtGui.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_6.setFont(font)
        self.label_6.setFrameShape(QtGui.QFrame.NoFrame)
        self.label_6.setLineWidth(2)
        self.label_6.setTextFormat(QtCore.Qt.AutoText)
        self.label_6.setObjectName(_fromUtf8("label_6"))
        self.horizontalLayout_3.addWidget(self.label_6)
        self.label_baseline_val_read = QtGui.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_baseline_val_read.setFont(font)
        self.label_baseline_val_read.setMouseTracking(False)
        self.label_baseline_val_read.setAcceptDrops(True)
        self.label_baseline_val_read.setFrameShape(QtGui.QFrame.StyledPanel)
        self.label_baseline_val_read.setLineWidth(2)
        self.label_baseline_val_read.setText(_fromUtf8(""))
        self.label_baseline_val_read.setTextFormat(QtCore.Qt.AutoText)
        self.label_baseline_val_read.setObjectName(_fromUtf8("label_baseline_val_read"))
        self.horizontalLayout_3.addWidget(self.label_baseline_val_read)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.widget1 = QtGui.QWidget(self.dockWidgetContents)
        self.widget1.setGeometry(QtCore.QRect(130, 340, 161, 51))
        self.widget1.setObjectName(_fromUtf8("widget1"))
        self.horizontalLayout_4 = QtGui.QHBoxLayout(self.widget1)
        self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
        self.label_2 = QtGui.QLabel(self.widget1)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setLineWidth(2)
        self.label_2.setTextFormat(QtCore.Qt.AutoText)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.horizontalLayout_4.addWidget(self.label_2)
        self.label_ri_val = QtGui.QLabel(self.widget1)
        self.label_ri_val.setMinimumSize(QtCore.QSize(80, 40))
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_ri_val.setFont(font)
        self.label_ri_val.setMouseTracking(False)
        self.label_ri_val.setAcceptDrops(True)
        self.label_ri_val.setFrameShape(QtGui.QFrame.StyledPanel)
        self.label_ri_val.setLineWidth(2)
        self.label_ri_val.setText(_fromUtf8(""))
        self.label_ri_val.setTextFormat(QtCore.Qt.AutoText)
        self.label_ri_val.setObjectName(_fromUtf8("label_ri_val"))
        self.horizontalLayout_4.addWidget(self.label_ri_val)
        self.widget2 = QtGui.QWidget(self.dockWidgetContents)
        self.widget2.setGeometry(QtCore.QRect(90, 440, 521, 51))
        self.widget2.setObjectName(_fromUtf8("widget2"))
        self.horizontalLayout_6 = QtGui.QHBoxLayout(self.widget2)
        self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
        self.label = QtGui.QLabel(self.widget2)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setLineWidth(2)
        self.label.setTextFormat(QtCore.Qt.AutoText)
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalLayout_6.addWidget(self.label)
        self.hs_baseline = QtGui.QSlider(self.widget2)
        self.hs_baseline.setMinimum(50)
        self.hs_baseline.setMaximum(520)
        self.hs_baseline.setOrientation(QtCore.Qt.Horizontal)
        self.hs_baseline.setObjectName(_fromUtf8("hs_baseline"))
        self.horizontalLayout_6.addWidget(self.hs_baseline)
        self.label_baseline_val = QtGui.QLabel(self.widget2)
        self.label_baseline_val.setEnabled(False)
        self.label_baseline_val.setMinimumSize(QtCore.QSize(80, 0))
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_baseline_val.setFont(font)
        self.label_baseline_val.setMouseTracking(False)
        self.label_baseline_val.setAcceptDrops(True)
        self.label_baseline_val.setFrameShape(QtGui.QFrame.StyledPanel)
        self.label_baseline_val.setLineWidth(2)
        self.label_baseline_val.setText(_fromUtf8(""))
        self.label_baseline_val.setTextFormat(QtCore.Qt.AutoText)
        self.label_baseline_val.setObjectName(_fromUtf8("label_baseline_val"))
        self.horizontalLayout_6.addWidget(self.label_baseline_val)
        self.widget3 = QtGui.QWidget(self.dockWidgetContents)
        self.widget3.setGeometry(QtCore.QRect(400, 340, 161, 52))
        self.widget3.setObjectName(_fromUtf8("widget3"))
        self.horizontalLayout_5 = QtGui.QHBoxLayout(self.widget3)
        self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
        self.label_3 = QtGui.QLabel(self.widget3)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setLineWidth(2)
        self.label_3.setTextFormat(QtCore.Qt.AutoText)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.horizontalLayout_5.addWidget(self.label_3)
        self.label_lf_val = QtGui.QLabel(self.widget3)
        self.label_lf_val.setMinimumSize(QtCore.QSize(80, 40))
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_lf_val.setFont(font)
        self.label_lf_val.setMouseTracking(False)
        self.label_lf_val.setAcceptDrops(True)
        self.label_lf_val.setFrameShape(QtGui.QFrame.StyledPanel)
        self.label_lf_val.setLineWidth(2)
        self.label_lf_val.setTextFormat(QtCore.Qt.AutoText)
        self.label_lf_val.setObjectName(_fromUtf8("label_lf_val"))
        self.horizontalLayout_5.addWidget(self.label_lf_val)
        self.dial_lf.raise_()
        self.dial_ri.raise_()
        self.hs_baseline.raise_()
        self.label.raise_()
        self.label_2.raise_()
        self.label_3.raise_()
        self.label_lf_val.raise_()
        self.label_ri_val.raise_()
        self.label_4.raise_()
        self.label_lf_val_read.raise_()
        self.label_ri_val_read.raise_()
        self.label_5.raise_()
        self.label_6.raise_()
        self.label_baseline_val_read.raise_()
        self.label_7.raise_()
        self.label_baseline_val.raise_()
        self.label_7.raise_()

        PlatformController.setWidget(self.dockWidgetContents)

        self.retranslateUi(PlatformController)
        QtCore.QMetaObject.connectSlotsByName(PlatformController)

        ###############################
        self.update_gui()
        self.baseline_sub = rospy.Subscriber('/baseline/position', Float64, self.baseline_callback)
        self.left_sub = rospy.Subscriber('/left/pan/angle', Float64, self.left_callback)
        self.right_sub = rospy.Subscriber('/right/pan/angle', Float64, self.right_callback)

        self.baseline_pub = rospy.Publisher('/baseline/move', Float64, queue_size=10)
        self.left_angle_pub = rospy.Publisher('/left/pan/move', Float64, queue_size=10, latch=True)
        self.right_angle_pub = rospy.Publisher('/right/pan/move', Float64, queue_size=10, latch=True)

    def baseline_callback(self,msg):
        val = str('%.2f'%(msg.data))
        self.label_baseline_val_read.setText(val)

    def left_callback(self,msg):
        val = str('%.2f'%(msg.data))
        self.label_lf_val_read.setText(val)

    def right_callback(self,msg):
        val = str('%.2f'%(msg.data))
        self.label_ri_val_read.setText(val)

    '''
    the update code
    '''
    def update_gui(self):
        self.hs_baseline.valueChanged.connect(self.update_baseline)
        self.dial_lf.valueChanged.connect(self.update_left)
        self.dial_ri.valueChanged.connect(self.update_right)

    # Define the update methods for the gui
    def update_baseline(self):
        val = self.hs_baseline.value()
        self.label_baseline_val.setText(str(val))
        self.baseline_pub.publish(val)

    def update_left(self):
        val = str(self.dial_lf.value())
        self.label_lf_val.setText(val)
        angle = Float64()
        angle.data = self.dial_lf.value()
        self.left_angle_pub.publish(angle)

    def update_right(self):
        val = str(self.dial_ri.value())
        self.label_ri_val.setText(val)
        angle = Float64()
        angle.data = self.dial_ri.value()
        self.right_angle_pub.publish(angle)

    def retranslateUi(self, PlatformController):
        self.label_7.setText(_translate("PlatformController", "Encoder Reading", None))
        self.label_5.setText(_translate("PlatformController", "Right :", None))
        self.label_4.setText(_translate("PlatformController", "Left :", None))
        self.label_6.setText(_translate("PlatformController", "Baseline :", None))
        self.label_2.setText(_translate("PlatformController", "Right :", None))
        self.label.setText(_translate("PlatformController", "Baseline", None))
        self.label_3.setText(_translate("PlatformController", "Left :", None))
        self.label_lf_val.setText(_translate("PlatformController", " ", None))

if __name__ == "__main__":
    import sys
    rospy.init_node('follower')
    app = QtGui.QApplication(sys.argv)
    PlatformController = QtGui.QDockWidget()
    ui = Ui_PlatformController()
    ui.setupUi(PlatformController)
    PlatformController.show()
    sys.exit(app.exec_())


import logging
from typing import List, Optional, Union

from sqlalchemy import func, or_
from sqlalchemy.orm import Session

from empire.server.api.v2.shared_dto import OrderDirection
from empire.server.api.v2.tag.tag_dto import TagOrderOptions, TagSourceFilter
from empire.server.core.db import models
from empire.server.core.hooks import hooks

log = logging.getLogger(__name__)

class TagService(object):
    def __init__(self, main_menu):
        self.main_menu = main_menu

    def get_by_id(self, db: Session, tag_id: int):
        return db.query(models.Tag).filter(models.Tag.id == tag_id).first()

    def get_all(
        self,
        db: Session,
        tag_types: Optional[List[TagSourceFilter]],
        q: str,
        limit: int = -1,
        offset: int = 0,
        order_by: TagOrderOptions = TagOrderOptions.updated_at,
        order_direction: OrderDirection = OrderDirection.desc,
    ):
        query = db.query(models.Tag, func.count(models.Tag.id).over().label("total"))

        tag_types = tag_types or []
        sub = []
        if TagSourceFilter.agent_task in tag_types:
            sub.append(db.query(models.agent_task_tag_assc.c.tag_id.label("tag_id")))
        if TagSourceFilter.plugin_task in tag_types:
            sub.append(db.query(models.plugin_task_tag_assc.c.tag_id.label("tag_id")))
        if TagSourceFilter.agent in tag_types:
            sub.append(db.query(models.agent_tag_assc.c.tag_id.label("tag_id")))
        if TagSourceFilter.listener in tag_types:
            sub.append(db.query(models.listener_tag_assc.c.tag_id.label("tag_id")))
        if TagSourceFilter.download in tag_types:
            sub.append(db.query(models.download_tag_assc.c.tag_id.label("tag_id")))
        if TagSourceFilter.credential in tag_types:
            sub.append(db.query(models.credential_tag_assc.c.tag_id.label("tag_id")))

        subquery = None
        if len(sub) > 0:
            subquery = sub[0]
            if len(sub) > 1:
                subquery = subquery.union(*sub[1:])
            subquery = subquery.subquery()

        if subquery is not None:
            query = query.join(subquery, subquery.c.tag_id == models.Tag.id)

        if q:
            query = query.filter(
                or_(
                    models.Tag.name.like(f"%{q}%"),
                )
            )

        if order_by == TagOrderOptions.name:
            order_by_prop = func.lower(models.Tag.name)
        elif order_by == TagOrderOptions.created_at:
            order_by_prop = models.Tag.created_at
        else:
            order_by_prop = models.Tag.updated_at

        if order_direction == OrderDirection.asc:
            query = query.order_by(order_by_prop.asc())
        else:
            query = query.order_by(order_by_prop.desc())

        if limit > 0:
            query = query.limit(limit).offset(offset)

        results = query.all()

        total = 0 if len(results) == 0 else results[0].total
        results = list(map(lambda x: x[0], results))

        return results, total

    def add_tag(
        self,
        db: Session,
        taggable: Union[
            models.Listener,
            models.Agent,
            models.AgentTask,
            models.PluginTask,
            models.Credential,
            models.Download,
        ],
        tag_req,
    ):
        tag = models.Tag(name=tag_req.name, value=tag_req.value, color=tag_req.color)
        taggable.tags.append(tag)
        db.flush()

        hooks.run_hooks(hooks.AFTER_TAG_CREATED_HOOK, db, tag, taggable)

        return tag

    def update_tag(
        self,
        db: Session,
        db_tag: models.Tag,
        taggable: Union[
            models.Listener,
            models.Agent,
            models.AgentTask,
            models.PluginTask,
            models.Credential,
            models.Download,
        ],
        tag_req,
    ):
        db_tag.name = tag_req.name
        db_tag.value = tag_req.value
        db_tag.color = tag_req.color
        db.flush()

        hooks.run_hooks(hooks.AFTER_TAG_UPDATED_HOOK, db, db_tag, taggable)

        return db_tag

    def delete_tag(
        self,
        db: Session,
        taggable: Union[
            models.Listener,
            models.Agent,
            models.AgentTask,
            models.PluginTask,
            models.Credential,
            models.Download,
        ],
        tag_id: int,
    ):
        if tag_id in [tag.id for tag in taggable.tags]:
            taggable.tags = [tag for tag in taggable.tags if tag.id != tag_id]
            db.query(models.Tag).filter(models.Tag.id == tag_id).delete()


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

"""
Created on 2020-11-18 10:22
@Author  : Justin Jiang
@Email   : jw_jiang@pku.edu.com
"""

def firstUniqChar(s):
    record = dict()
    duplicate = dict()
    for idx, word in enumerate(s):
        if word in duplicate:
            continue
        elif word not in record and word not in duplicate:
            record[word] = idx
        elif word in record and word not in duplicate:
            record.pop(word)
            duplicate[word] = 1
    if len(record) == 0:
        return -1
    result = sorted(record, key=lambda x: record.get(x))
    return record.get(result[0])

if __name__ == '__main__':
    s = "leetcode"
    print(firstUniqChar(s))  # 0
    s = "loveleetcode"
    print(firstUniqChar(s))  # 2
    s = "aadadaad"
    print(firstUniqChar(s))  # -1


import sqlite3

def create_genre_table():
    with sqlite3.connect("films.db") as db:
        cursor = db.cursor()
        sql = """create table genre
                 (GenreID integer,
                 GenreName text,
                 primary key(GenreID))"""
        cursor.execute(sql)
        db.commit

def create_film_table():
    with sqlite3.connect("films.db") as db:
        cursor = db.cursor()
        cursor.execute("PRAGMA foreign_keys = ON")
        sql = """create table film
                 (FilmID integer,
                 FilmName text,
                 GenreID integer,
                 primary key(FilmID),
                 foreign key(GenreID) references genre(GenreID))"""
        cursor.execute(sql)
        db.commit

if __name__ == "__main__":
    create_genre_table()
    create_film_table()


# Copyright © 2017 Ondrej Martinsky, All rights reserved
# http://github.com/omartinsky/pybor
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from yc_date import *
from pandas import *
import enum, os

class DCC(enum.Enum):
    ACT365 = 0
    ACT360 = 1

    def get_denominator(self):
        if self == DCC.ACT360:
            return 360.
        elif self == DCC.ACT365:
            return 365.
        assert False

class CalculationType(enum.Enum):
    PLAIN = 0
    AVERAGING = 1
    NONE = 2

class CouponFreq(enum.Enum):
    CONTINUOUS = 0
    DAILY = 1
    QUARTERLY = 2
    ZERO = 3

class Convention:
    def __init__(self, reset_frequency, calculation_frequency, payment_frequency, dcc):
        assert_type(reset_frequency, Tenor)
        assert_type(calculation_frequency, Tenor)
        assert_type(payment_frequency, Tenor)
        assert_type(dcc, DCC)
        self.reset_frequency = reset_frequency
        self.calculation_frequency = calculation_frequency
        self.payment_frequency = payment_frequency
        self.dcc = dcc

class Conventions:
    def __init__(self):
        self.map = dict()

    def FromSpreadsheet(excel_file):
        conventions = Conventions()
        conventions.map = dict()
        assert os.path.exists(excel_file)
        xl = ExcelFile(excel_file)
        dataframe = xl.parse('Conventions', index_col='Index', parse_cols='A:E')
        for index, row in dataframe.iterrows():
            conv = Convention(
                reset_frequency = Tenor(row['Reset Frequency']),
                calculation_frequency = Tenor(row['Calculation Period Frequency']),
                payment_frequency = Tenor(row['Payment Frequency']),
                dcc = enum_from_string(DCC, row['Day Count Convention']),
            )
            assert index not in conventions.map
            conventions.map[index] = conv
        return conventions

    def get(self, convention_name):
        if convention_name not in self.map:
            raise BaseException("Unable to get convention %s" % convention_name)
        return self.map[convention_name]

global_conventions = Conventions.FromSpreadsheet('conventions.xlsx')


from nacl.encoding import HexEncoder
from nacl.public import PrivateKey, PublicKey, Box
from nacl.secret import SecretBox

from spfs.mixins import DictLikeMixin

class Identity(DictLikeMixin):
    def __init__(self, name, private_key, data=None):
        self.name = name
        self.data = data or {}

        if isinstance(private_key, PrivateKey):
            self.private_key_obj = private_key
            self.private_key = private_key.encode().hex()
        else:
            self.private_key = private_key
            self.private_key_obj = PrivateKey(self.private_key, HexEncoder())

        self.secret_box = SecretBox(bytes.fromhex(self.private_key))
        self.boxes = {}

    def get_box(self, other_public_key):
        if other_public_key not in self.boxes:
            opk = PublicKey(other_public_key, HexEncoder())
            self.boxes[other_public_key] = Box(self.private_key_obj, opk)
        return self.boxes[other_public_key]

    def as_dict(self):
        return {
            'name': self.name,
            'private_key': self.private_key,
            'data': self.data
        }

class IdentityManager:
    def __init__(self, wallet):
        self.wallet = wallet
        self.identities = {}

        self.retrieve()

    def retrieve(self):
        for name, identity_data in self.wallet['identities'].items():
            private_key = identity_data['private_key']
            data = identity_data['data']
            self.identities[name] = Identity(name, private_key, data)

    def create(self, name):
        private_key = PrivateKey.generate()
        identity = Identity(name, private_key)
        self.identities[name] = identity
        return identity

    def persist(self):
        for name, identity in self.identities.items():
            self.wallet['identities'][name] = identity.as_dict()
        return self.wallet.persist()


Import('cc mesg_format')

# we don't need any 3rd party libs here so let's make a new env
env = Environment(CC=cc,
        CFLAGS='-std=gnu99 -march=native -O3 -fPIC'.split())
for k, v in mesg_format.items():
    env[k] = v

sources = Glob('*.c')
sources = [s for s in sources if 'test.c' not in s.name]

mlog = env.SharedLibrary('mlog', sources)
test = env.Program('test', sources+['test.c'])
env.Alias('install', [env.Install('lib', mlog),
                      env.Install('include', 'mlog.h')])
env.Alias('all', [mlog, test])


from flask import Flask, jsonify

application = Flask(__name__)

actions = [
    {
        'id': 1,
        'title': u'Assets created',
        'description': u'A CC Assets has been created.',
        'done': False
    },
    {
        'id': 2,
        'title': u'Assets modified',
        'description': u'A CC Assets has been modified.',
        'done': False
    },
    {
        'id': 3,
        'title': u'Assets removed',
        'description': u'A CC Assets has been removed.',
        'done': False
    }
]

@application.route('/actions', methods=['GET'])
def get_actions():
    return jsonify({'actions': actions})

@application.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    application.run()


import pytest
from time import sleep
from pages.games.game769 import GameHappyElements

def test01(option_bo):
    "检查docker内进程是否都在"
    bo = option_bo
    assert bo.exist_docker_process("streamr") is True
    assert bo.exist_docker_process("servr") is True
    assert bo.exist_docker_process("qemu") is True
    assert bo.exist_docker_process("pulseaudio") is True

def test02(option_bo):
    "串流前ls进程守护"
    bo = option_bo
    bo.kill_process_in_docker("streamr")
    sleep(1)
    assert bo.exist_docker_process("streamr") is True

@pytest.fixture(scope="function")
def bo_end_ls(option, option_bo):
    game = GameHappyElements(option)
    bo = option_bo
    yield game, bo
    game.end_ls()

def test03(bo_end_ls):
    "串流中ls进程守护"
    game, bo = bo_end_ls
    bo.kill_process_in_docker("streamr")
    sleep(1)
    assert bo.exist_docker_process("streamr") is True
    assert game.click_success()

def test04(option_bo):
    "串流前gsm进程守护"
    bo = option_bo
    bo.kill_process_in_docker("servr")
    sleep(1)
    assert bo.exist_docker_process("servr") is True

def test05(bo_end_ls):
    "串流中gsm进程守护"
    game, bo = bo_end_ls
    bo.kill_process_in_docker("servr")
    sleep(1)
    assert bo.exist_docker_process("servr") is True
    assert game.click_success()

def test06(option_bo):
    "串流前avd进程守护"
    bo = option_bo
    bo.kill_process_in_docker("qemu")
    sleep(10)
    assert bo.exist_docker_process("qemu") is True
    sleep(50)

def test07(option, bo_end_ls):
    "串流中avd进程守护"
    game, bo = bo_end_ls
    bo.kill_process_in_docker("qemu")
    sleep(10)
    assert game.verifyAlert("结束串流##") is True
    assert bo.exist_docker_process("qemu") is True
    sleep(50)
    game = GameHappyElements(option)
    assert game.click_success()

@pytest.fixture(scope="function")
def bo_end_rebuild(option, option_bo):
    bo = option_bo
    yield bo
    bo.rebuild_docker()

def test08(bo_end_rebuild):
    "串流前pulseaudio进程守护"
    bo = bo_end_rebuild
    bo.kill_process_in_docker("pulseaudio")
    sleep(1)
    assert bo.exist_docker_process("pulseaudio") is True

def test09(option, bo_end_rebuild):
    "串流中pulseaudio进程守护"
    GameHappyElements(option)
    bo = bo_end_rebuild
    bo.kill_process_in_docker("pulseaudio")
    sleep(1)
    assert bo.exist_docker_process("pulseaudio") is True


import numpy as np

from basepair.modisco.core import Pattern
from pytest import raises

def test_pattern():
    p = Pattern("test",
                np.random.randn(10, 4),
                dict(t=np.random.randn(10, 4)),
                dict(t=np.random.randn(10, 4)))
    assert p.tasks() == ['t']
    print(p)
    p.get_consensus()
    p.seq = np.abs(p.seq)
    p.get_seq_ic()
    p.copy()
    p.copy()

    p.rc()
    len(p)

    with raises(Exception):
        p = Pattern("test",
                    np.random.randn(10, 4),
                    dict(t=np.random.randn(10, 4)),
                    dict(t=np.random.randn(11, 4)))

    with raises(Exception):
        p = Pattern("test",
                    np.random.randn(10, 4),
                    [5] * 10,
                    np.random.randn(10, 4))

def test_pad():
    a = np.zeros((20, 4))
    a[12] = 1
    a_short = a[5:15]
    assert a_short[7][0] == 1
    assert a[12][0] == 1
    assert a[13][0] == 0

    p = Pattern("test",
                a_short,
                dict(t=a_short),
                dict(t=a_short),
                dict(t=a))

    assert np.all(p.profile['t'] == a)
    assert p.len_profile() == 20

    assert p.pad(10).len_profile() == 20
    assert len(p.pad(10)) == 10

    assert len(p.pad(10)) == 10
    assert p.shift(-2).profile['t'][10][0] == 1
    assert p.shift(-2).contrib['t'][5][0] == 1
    pnew = p.shift(1).rc().shift(1).rc()
    assert np.allclose(p.seq, pnew.seq)
    assert np.allclose(p.contrib['t'], pnew.contrib['t'])
    assert np.allclose(p.profile['t'], pnew.profile['t'])

def dont_test_parse_hdf4():
    from basepair.modisco.results import ModiscoResult
    mr = ModiscoResult("/s/project/avsec/basepair/modisco/modisco.h5")
    mr.open()

    mr.f.ls()
    metacluster = "metacluster_0"
    pattern = "pattern_0"
    pattern_grp = mr.get_pattern_grp(metacluster, pattern)
    p = Pattern.from_hdf5_grp(pattern_grp, "m0_p0")
    pt = p.trim_seq_ic(0.08)
    assert len(pt) == len(pt.contrib['Klf4'])
    p = mr.get_pattern("metacluster_0/pattern_0")
    import matplotlib.pyplot as plt
    p.plot(kind='all')
    p.plot(kind=['seq', 'contrib/Klf4'])
    p.plot(kind='seq')

    plt.show()
    mr.plot_pattern("metacluster_0/pattern_0", kind=['seq', 'contrib/Klf4'])


from django.shortcuts import render
from django.http import HttpResponse
from . import models
from . import forms
# Create your views here.

def bmipage(request):
    f1=forms.MyForms()
    return render(request,"bmi.html",{'form':f1})

def getdata(request):
    if request.method=='GET':
         weight=request.GET['weight']
         height=request.GET['height']
         w=float(weight)
         h=float(height)
         bmi=w/(h*h)
         return render(request,"calculate.html",{"weight":w,"height":h,"b1":bmi})
    if request.method=='POST':
         weight=request.POST['weight']
         height=request.POST['height']
         w=float(weight)
         h=float(height)
         bmi=w/(h*h)
         return render(request,"calculate.html",{"weight":w,"height":h,"b1":bmi})


import struct

def int_to_float(num_bits: int, value: int) -> float:
    """
    Convert an integer to the equivalent floating point value.
    """
    if num_bits == 32:
        unpack_fmt = '>f'
    elif num_bits == 64:
        unpack_fmt = '>d'
    else:
        raise Exception(f"Unhandled bit size: {num_bits}")

    return struct.unpack(unpack_fmt, value.to_bytes(num_bits // 8, 'big'))[0]

def get_bit_size(_type: str) -> int:
    if _type in {'i32', 'f32'}:
        return 32
    elif _type in {'i64', 'f64'}:
        return 64
    else:
        raise ValueError(f"Unsupported type: {_type}")


import os
import subprocess
import contextlib
import time

MAIN_DIRECTORY = os.path.join(os.path.dirname(__file__), '../')

@contextlib.contextmanager
def start_project(env=None, **kwargs):
    inherited_env = os.environ.copy()
    if env:
        inherited_env.update(env)
    process = subprocess.Popen('docker-compose up', env=inherited_env,
                               shell=True, cwd=MAIN_DIRECTORY, **kwargs)
    print(f'Project running! PID: {process.pid}')
    try:
        yield process
    finally:
        terminate_process = subprocess.Popen('docker-compose down',
                                             shell=True, cwd=MAIN_DIRECTORY)
        print('Waiting project stop to run...')
        terminate_process.wait()


# -*- coding: utf-8 -*-
"""
Group a bunch of modules together and switch between them.

In `i3status.conf` groups can be configured. The active one of these groups is
shown in the i3bar.  The active group can be changed by a user click.  If the
click is not used by the group module then it will be passed down to the
displayed module.

Modules can be i3status core modules or py3status modules.

Additionally the active group can be cycled through automatically.

Configuration parameters:
    button_next: Button that when clicked will switch to display next module.
        Setting to `0` will disable this action. (default 4)
    button_prev: Button that when clicked will switch to display previous
        module.  Setting to `0` will disable this action. (default 5)
    color: If the active module does not supply a color use this if set.
        Format as hex value eg `'#0000FF'` (default None)
    cycle: Time in seconds till changing to next module to display.
        Setting to `0` will disable cycling. (default 0)
    fixed_width: Reduce the size changes when switching to new group
        (default True)
    format: Format for module output. (default "{output}")

Format of status string placeholders:
    {output} Output of current active module

Example:

```
# Create a disks group that will show space on '/' and '/home'
# Change between disk modules every 30 seconds
...
order += "group disks"
...

group disks {
    cycle = 30
    format = "Disks: {output}"

    disk "/" {
        format = "/ %avail"
    }

    disk "/home" {
        format = "/home %avail"
    }
}
```

@author tobes
"""

from time import time

class Py3status:
    # available configuration parameters
    button_next = 4
    button_prev = 5
    color = None
    cycle = 0
    fixed_width = True
    format = "{output}"

    class Meta:
        include_py3_module = True

    def __init__(self):
        self.items = []
        self.active = 0
        self.initialized = False

    def _init(self):
        # if no items don't cycle
        if not self.items:
            self.cycle = 0
        self._cycle_time = time() + self.cycle
        self.initialized = True

    def _get_output(self):
        if not self.items:
            return
        if not self.fixed_width:
            return self._get_current_output(self.active)
        current = None
        widths = []
        for i in range(len(self.items)):
            output = self._get_current_output(i)
            if not output:
                continue
            if i == self.active:
                current = output
            widths.append(len(output['full_text']))
        if widths:
            width = max(widths)
            current['full_text'] += ' ' * (width - len(current['full_text']))
        return current

    def _get_current_output(self, item):
        output = None
        current = self.items[item]
        module_info = self.py3_module.helper_get_module_info(current)
        if module_info:
            output = module_info['module'].get_latest()[0]
        return output

    def _get_current_module_name(self):
        if not self.items:
            return
        return self.items[self.active]

    def _next(self):
        self.active = (self.active + 1) % len(self.items)

    def _prev(self):
        self.active = (self.active - 1) % len(self.items)

    def group(self, i3s_output_list, i3s_config):
        """
        Display a output of current module
        """

        # hide if no contents
        # FIXME the module shouldn't even run if no content
        if not self.items:
            return {
                'cached_until': time() + 36000,
                'full_text': '',
            }

        ready = self.initialized
        if not ready:
            self._init()

        if self.cycle and time() >= self._cycle_time:
            self._next()
            self._cycle_time = time() + self.cycle
        output = '?'
        color = None
        current_output = self._get_output()

        if current_output:
            output = current_output['full_text']
            color = current_output.get('color')
        update_time = self.cycle or 1000

        # on the first run contained items may not be displayed so make sure we
        # check them again to ensure all is correct
        if not ready:
            update_time = 0.1

        response = {
            'cached_until': time() + update_time,
            'full_text': self.format.format(output=output)
        }
        if color:
            response['color'] = color
        elif self.color:
            response['color'] = self.color
        return response

    def on_click(self, i3s_output_list, i3s_config, event):
        """
        Switch the displayed module or pass the event on to the active module
        """
        if not self.items:
            return
        # reset cycle time
        self._cycle_time = time() + self.cycle
        if self.button_next and event['button'] == self.button_next:
            self._next()
        if self.button_prev and event['button'] == self.button_prev:
            self._prev()

        # pass the event to the current module
        module_name = self._get_current_module_name()
        self.py3_module.helper_trigger_event(module_name, event)

if __name__ == "__main__":
    """
    Test this module by calling it directly.
    """
    from time import sleep
    x = Py3status()
    config = {}

    while True:
        print(x.group([], config))
        sleep(1)