'''
Created on 02-Dec-2015

@author: vijay
'''

from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func, \
    Column, Integer, String, Column, Integer, String, create_engine, create_engine
from sqlalchemy.ext.declarative import declarative_base, declarative_base
from sqlalchemy.orm import relationship, backref, sessionmaker
import os
import sys
import sqlalchemy
from src.dao.Author import Author
from src.dao.AuthorBookLink import AuthorBookLink
import json
from src.dao.Book import Base, Book
# from src.dao.Book import engine
import shutil
import traceback
# from src.static.constant import Workspace
import datetime
# from src.static.SessionUtil import SingletonSession

import logging

logger = logging.getLogger('extensive')

# if os.path.exists(Workspace().libraryPath):
#     os.chdir(Workspace().libraryPath)
#     listOfDir = os.listdir(Workspace().libraryPath)
#

class CreateDatabase():

    def __init__(self, libraryPath=None, databaseFileName='_opal.sqlite'):
        '''
        Creating database for library.
        '''
        logger.debug('CreateDatabase')
        databasePath = os.path.join(libraryPath, databaseFileName)
        self.libraryPath = libraryPath
        isDatabaseExist = os.path.exists(databasePath)

        databaseFilePath = f'sqlite:///{databasePath}'
        self.engine = create_engine(databaseFilePath , echo=True, connect_args={'check_same_thread': False})
        Session = sessionmaker(autoflush=True, autocommit=False, bind=self.engine)
        self.session = Session()

        os.makedirs(libraryPath, exist_ok=True)
        if not isDatabaseExist:
#             os.mkdir(libraryPath)
            self.creatingDatabase()
        os.chdir(libraryPath)

    def creatingDatabase(self):
        logger.debug('creatingDatabase')
        os.chdir(self.libraryPath)
        Base.metadata.drop_all(self.engine)
        Base.metadata.create_all(self.engine)
        logger.debug('database created blank')

    def addSingleBookData(self, dirName):
        '''
        Using this method you can update single book info into database.
        '''
        logger.debug('addSingleBookData')
        try:
            single = {}
            duplicate = {}
            os.chdir(self.libraryPath)
            duplicateBooks = list()
            addDatabase = True
            b = self.readJsonFile(dirName=dirName)
            if b:
                book = self.createBookFromJson(bookJson=b)
                book.bookPath = os.path.join(self.libraryPath , dirName)
                if book.isbn_13:
                    if not single.has_key(book.isbn_13):
                        single[book.isbn_13] = book

                    else:
                        duplicate[book.isbn_13] = book
                        addDatabase = False
                        duplicateBooks.append(duplicate)
                if addDatabase:
                    self.session.add(book)
                self.session.commit()
        except Exception as e:
            logger.error(e, exc_info=True)
            self.session.rollback();

    def addingData(self):
        logger.debug('addingData')
        directory_name = self.libraryPath
        os.chdir(directory_name)
        listOfDir = list()
#         listOfDir = [ name for name in os.listdir(directory_name) if os.path.isdir(os.path.join(directory_name, name)) ]
        for name in os.listdir(directory_name):
            if os.path.isdir(os.path.join(directory_name, name)) :
                try:
                    if int(name):
                        listOfDir.append(name)
                except Exception as e:
                    logger.error(e, exc_info=True)
        if listOfDir:
            listOfDir.sort(key=int)
        one = ''

        try:
            single = {}
            duplicate = {}
            self.duplicateBooks = list()
            for dirName in listOfDir:
                addDatabase = True
                b = self.readJsonFile(dirName=dirName)
                book = self.createBookFromJson(bookJson=b)
                book.bookPath = os.path.join(directory_name , dirName)
                if book.isbn_13:
                    if not single.has_key(book.isbn_13):
                        single[book.isbn_13] = book

                    else:
                        duplicate[book.isbn_13] = book
                        addDatabase = False
                        self.duplicateBooks.append(duplicate)
                if addDatabase:
                    self.session.add(book)
            self.session.commit()
            logger.debug('number of duplicateBooks: %s', len(self.duplicateBooks))

        except Exception as e:
            logger.error(e, exc_info=True)
            self.session.rollback();
        logger.debug('data loaded')

    def createBookFromJson(self, bookJson=None):
        logger.debug('createBookFromJson')
        book = Book()
        for k in bookJson:
            if not isinstance(bookJson[k], list):
                if k in ['publishedOn', 'createdOn']:
                    if bookJson[k]:
                        book.__dict__[k] = datetime.datetime.strptime(bookJson[k][0:19], "%Y-%m-%d %H:%M:%S")
                else:
                    book.__dict__[k] = bookJson[k]

            else:
                authorList = list()
                for a in bookJson[k]:
                    author = Author()
                    for aKey in a:
                        author.__dict__[aKey] = a[aKey]
                        authorList.append(author)
                book.authors = authorList
        return book

    def readJsonFile(self, dirName=None):
        logger.debug('readJsonFile')
#         print 'readJsonFile----->', os.path.join(Workspace().libraryPath, dirName , 'book.json')
        bookJsonFile = None
        b = None
        try:
            if os.path.exists(os.path.join(self.libraryPath, dirName , 'book.json')):
                bookJsonFile = open(os.path.join(self.libraryPath, dirName , 'book.json'), 'r')
                rep = ''
                for line in bookJsonFile:
                    rep = rep + line
                bookJsonFile.close
                try:
                    b = json.loads(rep)
                except Exception as e:
                    logger.error(e, exc_info=True)
            elif os.path.exists(os.path.join(self.libraryPath, dirName)):
                os.removedirs(os.path.join(self.libraryPath, dirName))
        except Exception as e:
            logger.debug(os.path.join(self.libraryPath, dirName))
            logger.error(e, exc_info=True)

#             print rep
        return b

    def saveAuthorBookLink(self, authorBookLink):
        logger.debug('saveAuthorBookLink')
        self.session.add(authorBookLink)
        self.session.commit()

    def saveBook(self, book):
        self.session.add(book)
        try:
            self.session.commit()
        except Exception as e:
            logger.error(e, exc_info=True)
            self.session.rollback()
            raise

    def countAllBooks(self):
        logger.debug('countAllBooks')
        bookCount = 0
        try:
            bookCount = self.session.query(Book).count()
        except Exception as e:
            logger.error(e, exc_info=True)
        return bookCount

    def findAllBook(self, pageSize=None, offset=0):
        logger.debug('findAllBook pageSize: %s', pageSize)
        bs, count = self.pagination(limit=pageSize, offset=offset)
        return bs, count

    def pagination(self, limit=0, offset=0):
        logger.debug('pagination limit : %s , offset: %s', limit, offset)
        if limit:
            countQuery = self.session.query(Book).count()
            query = self.session.query(Book).limit(limit).offset(offset)
        else:
            query = self.session.query(Book)
        bs = None
        try:
            bs = query.all()
        except Exception as e:
            logger.error(e, exc_info=True)
        return bs, countQuery

    def findBookByIsbn(self, isbn_13):
        logger.debug('findBookByIsbn : %s', isbn_13)
        bs = self.session.query(Book).filter(Book.isbn_13 == isbn_13).first()
        return bs

    def findBookByNextMaxId(self, bookId):
        logger.debug('findBookByNextMaxId bookId: %s', bookId)
        bs = self.session.query(Book).filter(Book.id > bookId).order_by(Book.id.asc()).first()
        return bs

    def findBookByPreviousMaxId(self, bookId):
        logger.debug('findBookByPreviousMaxId bookId: %s', bookId)
        bs = self.session.query(Book).filter(Book.id < bookId).order_by(Book.id.desc()).first()
        return bs

    def removeBook(self, book=None):
        '''
        This method removes entry from database.
        '''
        isBookDeleted = False
        try:
            if book:
                query = self.session.query(Book).filter(Book.id == book.id)
                session_book = query.first()
#                 print book
#                 book = books[0]

                author_id_lst = []
                for author in session_book.authors:
                    author_id_lst.append(author.id)
                    self.session.delete(author)

#                 query = self.session.query(AuthorBookLink).filter(AuthorBookLink.bookId == book.id)
#                 authorBookLinks = query.all()
                self.session.delete(session_book)
#                 for authorBook in authorBookLinks:
#                     self.session.delete(authorBook)

#                 query = self.session.query(Author).filter(Author.id.in_(author_id_lst))
#                 authors = query.all()
#                 for author in authors:
#                     self.session.delete(author)
#                 self.session.delete(book)
                self.session.commit()

#                 path = book.bookPath
#                 if path and os.path.exists(path):
#                     shutil.rmtree(path)
#                     print 'deleting path'
                isBookDeleted = True
        except Exception as e:
            logger.error(e, exc_info=True)
            self.session.flush()
            self.session.close()
            isBookDeleted = False

        return isBookDeleted

    def findByBookName(self, bookName=None, limit=50, offset=0):
        '''
        This method provide search of book name IGNORECASE .
        '''
        logger.debug('findByBookName')
        try:
            if bookName:
                countQuery = self.session.query(Book).filter(func.lower(Book.bookName) == func.lower(bookName)).count()
                query = self.session.query(Book).filter(func.lower(Book.bookName) == func.lower(bookName)).limit(limit).offset(offset)
#                 .order_by(Book.id.desc())
                books = query.all()
                return books, countQuery
        except Exception as e:
            logger.error(e, exc_info=True)

    def findBySimlarBookName(self, bookName=None, limit=50, offset=0):
        '''
        This method provide search of book name IGNORECASE and similar result like.
        '''
        logger.debug('findBySimlarBookName bookName: %s', bookName)
        try:
            if bookName:
                countQuery = self.session.query(Book).filter(Book.bookName.ilike('%' + bookName + '%')).count()
                query = self.session.query(Book).filter(Book.bookName.ilike('%' + bookName + '%')).limit(limit).offset(offset)
#                 .order_by(Book.id.desc())
                books = query.all()
                return books, countQuery
        except Exception as e:
            logger.error(e, exc_info=True)

    def findByIsbn_13Name(self, isbn_13=None):
        logger.debug('findBySimlarBookName isbn_13: %s', isbn_13)
        if isbn_13:
            query = self.session.query(Book).filter(Book.isbn_13.ilike('%' + isbn_13 + '%'))
            books = query.all()
            return books

    def findDuplicateBook(self):
        logger.debug('findDuplicateBook ')
        books = self.session.query(Book).group_by(Book.isbn_13).having(func.count(Book.isbn_13) > 1).order_by(Book.isbn_13.desc())
        return books

    def findBookByFileName(self, bookFileName):
        logger.debug('findBySimlarBookName bookFileName: %s', bookFileName)
        if bookFileName:
            query = self.session.query(Book).filter(Book.bookFileName.ilike('%' + bookFileName + '%'))
            books = query.all()
            return books

    def findBook(self, book=None):
        '''
        This method will find the book in database . It will return true.If book present.

        '''
        logger.debug('findBook')
        books = None
        if book.isbn_13:
            query = self.session.query(Book).filter(Book.isbn_13.ilike('%' + book.isbn_13 + '%'))
            books = query.all()
        if book.bookName:
            query = self.session.query(Book).filter(Book.bookName.ilike('%' + book.bookName + '%'))
            books = query.all()
        return books

    def getMaxBookID(self):
        '''
        getting max bookId from either of database or library folder.
        '''
        sql = f'select max(substr(book_path,{ len(self.libraryPath) + 2}), id) from book order by id desc'
        logger.debug(sql)
        logger.debug(f'getMaxBookID sql: {sql} ')
        maxBookId = self.session.execute(sql).first()
        if maxBookId == None:
            maxBookId = [0]
        logger.debug(f'maxBookId: {maxBookId[0]}')
        return int(maxBookId[0])

if __name__ == '__main__':
#     session = CreateDatabase().creatingDatabase()
#     CreateDatabase().addingData()

#     books = CreateDatabase().findByBookName("java")
    libraryPath = r'/docs/new/library'
    if not os.path.exists(libraryPath):
        print('no workspace')

    try:
        createdb = CreateDatabase(libraryPath=libraryPath)
#         createdb.creatingDatabase()
#         createdb.addingData()
        x = createdb.getMaxBookID()
        page = createdb.pagination(10, 10)
        logger.debug(page)
#         createdb.findAllBook()
    except Exception as e:
        print(e)
#     for b in books:
#         print b.isbn_13, b.id

#         createdb.removeBook(b)

    pass


import data
from functools import reduce

# This solution used global variable data.quize, which is not pure FP
def cal(student):
    filtered = filter(lambda x: x[0] == x[1][0], zip(student.ans, data.QUIZE))
    # [('A', ('A', 3)), ('D', ('D', 1)), ...]

    reduced = reduce(lambda x, y: x + y[1][1], filtered, 0)
    print(student.id, '\t', reduced)

print('ID\tScore\n==================')
list(map(cal, data.students))


"""
reference: https://www.geeksforgeeks.org/rat-in-a-maze-backtracking-using-stack/
"""

DIRECTION = {
  'UP': 0,
  'LEFT': 1,
  'DOWN': 2,
  'RIGHT': 3,
}

# Define a Node class
class Node:
  def __init__(self, row: int, col: int) -> None:
    self.row = row
    self.col = col
    self.direction = DIRECTION['UP']

maze = [
  [ 1, 0, 1, 1, 0 ],
  [ 1, 1, 1, 0, 1 ],
  [ 0, 1, 0, 1, 1 ],
  [ 1, 1, 1, 1, 1 ],
  [ 1, 1, 1, 1, 1 ],
]

SIZE_MAZE_ROW = len(maze)
SIZE_MAZE_COL = len(maze[0])

is_visited = [[False for i in range(SIZE_MAZE_COL)] for j in range(SIZE_MAZE_ROW)]

def escapeMaze(maze, fx, fy):
  # Create a strating point
  # And put it into the stack
  start = Node(0, 0)
  stack = []
  stack.append(start)

  # While the stack is not empty, do this processes
  while stack:
    # pop the last index from stack
    current = stack.pop()

    # set variable (not constant)
    # for manipulating row and column
    row = current.row
    col = current.col
    direction = current.direction

    # change the direction of current node
    current.direction += 1
    # and put into the stack again
    stack.append(current)

    # Escape condition
    # If current location is the destination,
    # return True
    if row == fx and col == fy:
      return True

    # Check each direction cases
    if direction == DIRECTION['UP']:
      # Check index validity,
      # whether visited before or not,
      # and whether available to visit or not
      if row - 1 >= 0 and \
        maze[row -1][col] == 1 and \
        is_visited[row - 1][col] == False:
        # If all conditions are fulfilled
        # create the nexe_route node with row and col
        next_route = Node(row - 1, col)
        # And mark this location as visited to is_visited
        is_visited[row - 1][col] = True
        # Append the next route into the stack
        stack.append(next_route)
        continue
      continue

    if direction == DIRECTION['LEFT']:
      if col - 1 >= 0 and \
        maze[row][col - 1] == 1 and \
        is_visited[row][col - 1] == False:
        next_route = Node(row, col - 1)
        is_visited[row][col - 1] = True
        stack.append(next_route)
        continue
      continue

    if direction == DIRECTION['DOWN']:
      if row + 1 < SIZE_MAZE_ROW and \
        maze[row + 1][col] == 1 and \
        is_visited[row + 1][col] == False:
        next_route = Node(row + 1, col)
        is_visited[row + 1][col] = True
        stack.append(next_route)
        continue
      continue

    if direction == DIRECTION['RIGHT']:
      if col + 1 < SIZE_MAZE_COL and \
        maze[row][col + 1] == 1 and \
        is_visited[row][col + 1] == False:
        next_route = Node(row, col + 1)
        is_visited[row][col + 1] = True
        stack.append(next_route)
        continue
      continue

    # If there is no available path from current location,
    # go back to the location just before
    # and mark the location in is_visited from True to False
    is_visited[row][col] = False
    stack.pop()

  return False

print(escapeMaze(maze, 4, 4))


from .market_manager import MarketManager
from api.currency import Currency, CoinoneCurrency, KorbitCurrency, \
    GopaxCurrency, BithumbCurrency, OkcoinCurrency, CoinnestCurrency
from trader.market.order import Market
from api.coinone_api import CoinoneApi
from api.korbit_api import KorbitApi
from api.gopax_api import GopaxApi
from api.bithumb_api import BithumbApi
from api.okcoin_api import OkcoinApi
from api.coinnest_api import CoinnestApi
from trader.market.order import Order, OrderType
from decimal import Decimal
from bson import Decimal128

class VirtualMarketManager(MarketManager):
    def __init__(self, market_tag: Market, min_trading_coin: float, krw_balance: float,
                 coin_balance: float, coin_name: str):
        # create api instance according to given api_type
        if market_tag is Market.VIRTUAL_COINONE:
            target_api = CoinoneApi.instance(is_public_access_only=True)
            self.name = "co"
        elif market_tag is Market.VIRTUAL_KORBIT:
            target_api = KorbitApi.instance(is_public_access_only=True)
            self.name = "kb"
        elif market_tag is Market.VIRTUAL_GOPAX:
            target_api = GopaxApi.instance(is_public_access_only=True)
            self.name = "gp"
        elif market_tag is Market.VIRTUAL_BITHUMB:
            target_api = BithumbApi.instance(is_public_access_only=True)
            self.name = "bt"
        elif market_tag is Market.VIRTUAL_OKCOIN:
            target_api = OkcoinApi.instance(is_public_access_only=True)
            self.name = "oc"
        elif market_tag is Market.VIRTUAL_COINNEST:
            target_api = CoinnestApi.instance(is_public_access_only=True)
            self.name = "cn"
        else:
            raise Exception("Invalid market type has set for virtual market!")

        self.vt_balance = {
            "krw": krw_balance,
            coin_name: coin_balance
        }
        self.initial_vt_balance = dict(self.vt_balance)
        self.order_id_count = 0
        self.min_trading_coin = min_trading_coin
        super().__init__(market_tag, target_api)

        self.history = dict()

    def order_buy(self, currency: Currency, unit_price: int, amount: float):
        if not self.has_enough_coin("krw", amount * unit_price):
            raise Exception("[%s] Could not order_buy" % self.market_tag)

        self.vt_balance[currency.name.lower()] += amount * (1 - self.taker_fee)
        self.vt_balance["krw"] -= amount * unit_price
        try:
            self.history[unit_price] -= amount
        except KeyError:
            self.history[unit_price] = 0
            self.history[unit_price] -= amount
        return Order(self.market_tag, currency, OrderType.LIMIT_BUY, self.generate_buy_order_id(), unit_price, amount)

    def order_sell(self, currency: Currency, unit_price: int, amount: float):
        if not self.has_enough_coin(currency.name.lower(), amount):
            raise Exception("[%s] Could not order_sell" % self.market_tag)

        self.vt_balance[currency.name.lower()] -= amount
        self.vt_balance["krw"] += unit_price * amount * (1 - self.taker_fee)
        try:
            self.history[unit_price] += amount
        except KeyError:
            self.history[unit_price] = 0
            self.history[unit_price] += amount
        return Order(self.market_tag, currency, OrderType.LIMIT_SELL, self.generate_sell_order_id(), unit_price, amount)

    def update_balance(self):
        balance_dict = dict()
        for key in self.vt_balance.keys():
            coin_bal = self.vt_balance[key]
            balance_dict[key] = {
                "available": coin_bal,
                "trade_in_use": 0,
                "balance": coin_bal
            }
        self.balance.update(balance_dict)

    def clear_balance(self):
        balance_dict = dict()
        for key in self.initial_vt_balance.keys():
            coin_bal = self.initial_vt_balance[key]
            balance_dict[key] = {
                "available": coin_bal,
                "trade_in_use": 0,
                "balance": coin_bal
            }
        self.balance.update(balance_dict)

    # override static method
    def get_market_currency(self, target_currency: str) -> "Currency":
        if self.market_tag is Market.VIRTUAL_COINONE:
            return CoinoneCurrency[target_currency.upper()]
        elif self.market_tag is Market.VIRTUAL_KORBIT:
            return KorbitCurrency[target_currency.upper()]
        elif self.market_tag is Market.VIRTUAL_GOPAX:
            return GopaxCurrency[target_currency.upper()]
        elif self.market_tag is Market.VIRTUAL_BITHUMB:
            return BithumbCurrency[target_currency.upper()]
        elif self.market_tag is Market.VIRTUAL_OKCOIN:
            return OkcoinCurrency[target_currency.upper()]
        elif self.market_tag is Market.VIRTUAL_COINNEST:
            return CoinnestCurrency[target_currency.upper()]
        else:
            raise Exception("Invalid target API type has set!")

    def _generate_order_id(self, tag: str):
        self.order_id_count += 1
        return "%s_%s_%s" % (self.name, tag, str(self.order_id_count))

    def generate_buy_order_id(self):
        return self._generate_order_id("buy")

    def generate_sell_order_id(self):
        return self._generate_order_id("sell")

    def apply_history_to_orderbook(self, orderbook: dict):
        history_keys = self.history.keys()
        for order in orderbook["asks"]:
            price = int(order["price"].to_decimal())
            if price in history_keys:
                order["amount"] = Decimal128(order["amount"].to_decimal() + Decimal(self.history[price]))
                if order["amount"].to_decimal() < 0:
                    order["amount"] = Decimal128("0")
        for order in orderbook["bids"]:
            price = int(order["price"].to_decimal())
            if price in history_keys:
                order["amount"] = Decimal128(order["amount"].to_decimal() - Decimal(self.history[price]))
                if order["amount"].to_decimal() < 0:
                    order["amount"] = Decimal128("0")
        return orderbook


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

# # conterfactual expalantion for DRL baced-on policy distillation

# ### import packages

# In[1]:

import gym
from stable_baselines3 import DQN
from stable_baselines3.common.vec_env import VecVideoRecorder, DummyVecEnv
from stable_baselines3 import DQN
from stable_baselines3.common.vec_env import VecVideoRecorder, DummyVecEnv
from policy_distillation import main as policy_distillation
import random
from tkinter import Y
import numpy as np
import torch
import torch.nn as nn
import gym
import numpy as np
from IPython.display import clear_output
import matplotlib.pyplot as plt
# import matplotlib
# matplotlib.use("Qt5Agg")
# from matplotlib import pyplot as plt
import gym
import highway_env
from matplotlib import pyplot as plt

from scipy.signal import convolve, gaussian
from copy import deepcopy
import os
import io
import base64
import time
import glob
from IPython.display import HTML
import local_lib as myLib

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from stable_baselines3 import SAC,A2C,DDPG, DQN

from itertools import count
from time import time, strftime, localtime
import gym
import scipy.optimize
from tensorboardX import SummaryWriter
from core.models import *
from core.agent_ray_pd import AgentCollection
from utils.utils import *
import numpy as np
import ray
import envs
from trpo import trpo
from student import Student
from teacher import Teacher
import os
import pickle
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print("device: ",device)

# ### environment setup

# In[2]:
num_of_actions=5
num_Of_vehicles_Under_vision = 5
vehicle_attr = 4

low_dimention_env = gym.make("highway-fast-v0")
low_dimention_env.configure({
    "observation": {
        "type": "Kinematics",
        "vehicles_count": num_Of_vehicles_Under_vision,
        "features": ["x", "y", "vx", "vy"],
        "normalize": False,
        "absolute": True,
        # "order": "sorted"
    }
})
low_dimention_env.reset()

high_dimention_env = gym.make("highway-fast-v0")
high_dimention_env.configure({
    "observation": {
        "type": "GrayscaleObservation",
        "observation_shape": (128, 64),
        "stack_size": 4,
        "weights": [0.2989, 0.5870, 0.1140],  # weights for RGB conversion
        "scaling": 1.75,
    },
})
high_dimention_env.reset()

# ## teacher training phase

# In[3]:

# model = myLib.DQN_creation(policy='MlpPolicy', env=env, policy_kwargs=dict(net_arch=[256, 256]), learning_rate=5e-4,
#                 buffer_size=15000, learning_starts=200, batch_size=128, gamma=0.8, train_freq=1, gradient_steps=1,
#                 target_update_interval=50, exploration_fraction=0.7, verbose=1, tensorboard_log="highway_dqn/")
# model.learn(int(10e4))
fileName = "model"
# myLib.Save_DQN_model(model,fileName)
teacher_model = myLib.Load_DQN_model(fileName=fileName)

# ## student training phase

# In[5]:

import argparse

parser = argparse.ArgumentParser(description='Policy distillation')
# Network, env, MDP, seed
parser.add_argument('--hidden-size', type=int, default=256,
                    help='number of hidden units per layer')
parser.add_argument('--num-layers', type=int, default=2,
                    help='number of hidden layers')
parser.add_argument('--env-name', default="highway-fast-v0", metavar='G',
                    help='name of the environment to run')
parser.add_argument('--gamma', type=float, default=0.995, metavar='G',
                    help='discount factor (default: 0.995)')
parser.add_argument('--tau', type=float, default=0.97, metavar='G',
                    help='gae (default: 0.97)')
parser.add_argument('--seed', type=int, default=1, metavar='N',
                    help='random seed (default: 1)')
parser.add_argument('--load-models', default=True, action='store_true',
                    help='load_pretrained_models')

# Teacher policy training
parser.add_argument('--agent-count', type=int, default=10, metavar='N',
                    help='number of agents (default: 100)')
parser.add_argument('--num-teachers', type=int, default=1, metavar='N',
                    help='number of teacher policies (default: 1)')
parser.add_argument('--max-kl', type=float, default=1e-2, metavar='G',
                    help='max kl value (default: 1e-2)')
parser.add_argument('--cg-damping', type=float, default=1e-2, metavar='G',
                    help='damping for conjugate gradient (default: 1e-2)')
parser.add_argument('--cg-iter', type=int, default=10, metavar='G',
                    help='maximum iteration of conjugate gradient (default: 1e-1)')
parser.add_argument('--l2-reg', type=float, default=1e-3, metavar='G',
                    help='l2 regularization parameter for critics (default: 1e-3)')
parser.add_argument('--teacher-batch-size', type=int, default=1000, metavar='N',
                    help='per-iteration batch size for each agent (default: 1000)')
parser.add_argument('--sample-batch-size', type=int, default=10000, metavar='N',
                    help='expert batch size for each teacher (default: 10000)')
parser.add_argument('--render', action='store_true',
                    help='render the environment')
parser.add_argument('--log-interval', type=int, default=1, metavar='N',
                    help='interval between training status logs (default: 10)')
parser.add_argument('--device', type=str, default=device,
                    help='set the device (cpu or cuda)')
parser.add_argument('--num-workers', type=int, default=10,
                    help='number of workers for parallel computing')
parser.add_argument('--num-teacher-episodes', type=int, default=10, metavar='N',
                    help='num of teacher training episodes (default: 100)')

# Student policy training
parser.add_argument('--lr', type=float, default=1e-5, metavar='G',
                    help='adam learnig rate (default: 1e-3)')
parser.add_argument('--test-interval', type=int, default=10, metavar='N',
                    help='interval between training status logs (default: 10)')
parser.add_argument('--student-batch-size', type=int, default=1000, metavar='N',
                    help='per-iteration batch size for student (default: 1000)')
parser.add_argument('--sample-interval', type=int, default=10, metavar='N',
                    help='frequency to update expert data (default: 10)')
parser.add_argument('--testing-batch-size', type=int, default=10000, metavar='N',
                    help='batch size for testing student policy (default: 10000)')
parser.add_argument('--num-student-episodes', type=int, default=1000, metavar='N',
                    help='num of teacher training episodes (default: 1000)')
parser.add_argument('--loss-metric', type=str, default='kl',
                    help='metric to build student objective')
parser.add_argument('--algo', type=str, default='sgd',
                    help='update method')
parser.add_argument('--storm-interval', type=int, default=10, metavar='N',
                    help='frequency of storm (default: 10)')
parser.add_argument('--init-alpha', type=float, default=1.0, metavar='G',
                    help='storm init alpha (default: 1.0)')
args = parser.parse_args()

student = policy_distillation(args, low_dimention_env)

# ## potential Counterfactuals
    #################################for test only
env = gym.make("highway-fast-v0")
config = {
    "observation": {
        "type": "Kinematics",
        "vehicles_count": num_Of_vehicles_Under_vision,
        "features": ["x", "y", "vx", "vy"],
        "normalize": False,
        "absolute": True,
        # "order": "sorted"
    }
}
env.configure(config)

obs,done = env.reset(), False
for _ in range(20):
    while done == False:
        action = student.policy(torch.tensor(obs.reshape(obs.size), device=device)).loc.argmax().tolist()
        obs, reward, done, info = env.step(action)
        env.render()
    obs, done = env.reset(),False
env.close()
#################################end test
# ### second environment (lower dimensional input)

obs = env.reset()
env.render()

exp_is_valid = []
indx=np.array([1])
CFs, desireAction = local_lib.CF_find_2(env=env,student_model=student_model,obs=obs,device=device,indx=indx,
                      num_Of_vehicles_Under_vision=num_Of_vehicles_Under_vision,vehicle_attr=vehicle_attr)

# ## counterfactuals validation

# In[ ]:

image_env = DummyVecEnv([train_env])
video_length = 2 * image_env.envs[0].config["duration"]
image_env = VecVideoRecorder(image_env, "highway_cnn/videos/",
                       record_video_trigger=lambda x: x == 0, video_length=video_length,
                       name_prefix="dqn-agent")

for i, cf in enumerate(CFs):
    obs_image = image_env.reset()
    obs_kinematics = myLib.CF2Env3(obs, cf, indx, env)
    for index, vehicles in enumerate(image_env.venv.envs[0].env.road.vehicles[0:num_Of_vehicles_Under_vision]):
        vehicles.position=cf[index,0:2]
        # vehicles.velocity=CF[indices,2:4]
#applying the CFs to environments
    image_env.venv.envs[0].env.render()
    image_env.venv.envs[0].env.render()
    image_env.venv.envs[0].env.render()
    obs_image=image_env.venv.envs[0].env.observation_type.observe()
    ##prepare data
    plt.imshow(obs_image[3].T, cmap=plt.get_cmap('gray'))
    plt.show()
    action,_ = teacher_model.predict(obs_image)
    action_prim = student_model(torch.tensor(obs_kinematics.observation_type.observe()        .reshape(num_Of_vehicles_Under_vision*vehicle_attr), device=device)).argmax(dim=-1).item()
    # if action_prim==action_desire then the exp is valide
    if(action == action_prim == desireAction[i]):
        exp_is_valid.append(1)
    else:
        exp_is_valid.append(0)
    print(exp_is_valid)

# ## visulize the finded CFs

# In[ ]:


# -*- coding: utf-8 -*-
import os
import sys
from write_poem import WritePoem,start_model

writer = start_model()

def write_poem(poem_style, word):

    if poem_style == 1:
        return  writer.free_verse()    # 自由诗
    elif poem_style == 2:
        return writer.rhyme_verse()    # 押韵诗
    elif poem_style == 3:
        return  writer.cangtou(word)    # 藏头诗+押韵
    elif poem_style == 4:
        return writer.hide_words(word)  # 藏字诗+押韵
    return 0

def output(poem):
    '''美化输出格式'''
    poem = poem.strip('。')
    lenth = len(poem.split('。')[0])*2 + 10
    print()
    print('-'*lenth)
    print()
    for i in poem.split('。'):
        print('     ' + i + '。')
    print()
    print('-'*lenth)
    print()

if __name__ == "__main__":
    help = '''
    自由诗： python main.py 1
    押韵诗： python main.py 2
    藏头诗： python main.py 3 四个汉字
    藏字诗： python main.py 4 汉字
    '''
    word = '输入汉字'
    try:
        poem_style = int(sys.argv[1])
        if poem_style not in [1,2,3,4]:
            print(help)
    except:
        print(help)
        exit(1)
    try:
        word = sys.argv[2]
    except:
        pass
    poem = write_poem(poem_style, word)
    output(poem)


#
# @lc app=leetcode.cn id=718 lang=python3
#
# [718] 最长重复子数组
#
from typing import List
# @lc code=start

class Solution:
    def findLength(self, A: List[int], B: List[int]) -> int:
        m = len(A)
        n = len(B)
        dp = [0] * (n+1)
        last_dp = [0] * (n+1)
        ans = 0
        for i in range(m):
            for j in range(n):
                if A[i] == B[j]:
                    dp[j+1] = last_dp[j] + 1
                else:
                    dp[j+1] = 0
                ans = max(ans, dp[j+1])
            # print(f'{i=}, {dp=}')
            last_dp = dp[:]

        return ans

# @lc code=end
if __name__ == "__main__":
    f = Solution().findLength
    assert f([1, 2, 3, 2, 1], [3, 2, 1, 4, 7]) == 3
    assert f([], []) == 0
    assert f([1, 2], [1]) == 1
    assert f([3, 2, 1, 2, 3], [2, 1, 2]) == 3
    assert f([0, 1, 1, 1, 1], [1, 0, 1, 0, 1]) == 2

718.最长重复子数组.py


#NOTE-not getting the code for Bound Concept
import numpy as np
import matplotlib.pyplot as plt
import math
from PIL import Image

img=plt.imread('rotate.png')
print(img.shape)
h,w,num_channels=img.shape
degree=int(input("Enter the angle "))
radian=(degree*math.pi)/180
max_len=int(math.sqrt(h*h+w*w))
rotated_img=np.zeros((max_len,max_len,num_channels))
print(rotated_img.shape)
mid_r=int(max_len/2)
mid_c=int(max_len/2)
cos=math.cos(radian)
sin=math.sin(radian)

#r,c=Old Cordinates
#x,y=New Cordinates

#[[cos sin]
  #[-sin cos]]
for r in range(max_len):
    for c in range(max_len):
        y=(r-mid_c)*cos+(c-mid_r)*sin
        x=-(r-mid_c)*sin+(c-mid_r)*cos
        y+=mid_c
        x+=mid_r
        y=int(y)
        x=int(x)
        if(x>=0 and y>=0 and x<w and y<h):
            rotated_img[r,c]=img[y,x]

plt.imshow(rotated_img)


IS_ORDERED = False
MAX_LEN = 12

with open("dict.txt") as file:
    words = [w.lower().strip() for w in file.read().split('\n')]

s = input('>>> ').lower()

result = []
if IS_ORDERED:
    s_lst = list(s[::-1])
    for word in words:
        with_caps = ''
        temp_s = s_lst.copy()
        for c in word:
            if temp_s and c == temp_s[-1]:
                temp_s.pop(-1)
                with_caps += c.upper()
            else:
                with_caps += c.lower()
        if not temp_s and len(word) <= MAX_LEN:
            result.append(with_caps)
else:
    allowed = {}
    for c in s:
        if c not in allowed:
            allowed[c] = 1
        else:
            allowed[c] += 1
    for word in words:
        with_caps = ''
        temp_allowed = allowed.copy()
        for c in word:
            if c in temp_allowed and temp_allowed[c] >= 1:
                temp_allowed[c] -= 1
                with_caps += c.upper()
            else:
                with_caps += c.lower()
        if all(v == 0 for v in temp_allowed.values()) and len(word) <= MAX_LEN:
            result.append(with_caps)

for i in range(len(result)):
    spaces = ' ' * (len(str(len(result))) - len(str(i + 1)) + 1)
    print(f'{i + 1}.{spaces}{result[i]}')


num_votes = {}

with open('input.txt', 'r') as fin:
    for line in fin:
        candidate, votes = line.split()
        num_votes[candidate] = num_votes.get(candidate, 0) + int(votes)

for candidate, votes in sorted(num_votes.items()):
    print(candidate, votes)


print('Welcome to PyPet!')

name= 'Pymon'
age= 0
weight= 0.1
hungry= True
photo= '<x3 )~~~'

Rat= {
  'name': 'Pymon',
  'hungry': True,
  'weight': 0.1,
  'age': 0,
  'photo': '<x3  )~~~',
}
print ('Yo '+ Rat['name'])
print (Rat['photo'])

def feed(Rat):
 if Rat['hungry'] == True:
  Rat['hungry'] = False
  Rat['weight'] = Rat['weight'] + 1
 else:
  print ('The Pypet is not hungry!')

print (Rat)
feed(Rat)
print (Rat)
feed(Rat)


from __future__ import print_function
import sys

from optparse import OptionParser

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

if __name__ == "__main__":

    parser = OptionParser()
    parser.add_option("-o","--owner",dest="owner",default="S.Vogt")
    parser.add_option("-s","--sheet",dest="sheet",default="2017B")
    (options, args) = parser.parse_args()

    (names, star_table, flags, stars) = ParseGoogledex.parseGoogledex(sheetns=options.sheet)

    for i in range(0,len(names)):

        if options.owner in flags['owner'][i]:
            print (names[i])


import logging
import re
from urllib.parse import urlencode
from xml.etree import ElementTree as ET

import osc.core
import osc.oscerr

from ..errors import MissingSourceProjectError
from .assignment import Assignment
from .attribute import Attribute
from .comment import Comment
from .review import GroupReview
from .review import UserReview
from .xmlfactorymixin import XmlFactoryMixin

class Request(osc.core.Request, XmlFactoryMixin):
    """Wrapper around osc request object to add logic required by the
    qam-plugin.
    """

    STATE_NEW = "new"
    STATE_REVIEW = "review"
    STATE_DECLINED = "declined"
    OPEN_STATES = [STATE_NEW, STATE_REVIEW]
    REVIEW_USER = "BY_USER"
    REVIEW_GROUP = "BY_GROUP"
    REVIEW_OTHER = "BY_OTHER"
    COMPLETE_REQUEST_ID_SRE = re.compile(r"(open)?SUSE:Maintenance:\d+:(?P<req>\d+)")

    def __init__(self, remote):
        self.remote = remote
        super().__init__()
        self._comments = None
        self._groups = None
        self._packages = None
        self._assigned_roles = None
        self._priority = None
        self._reviews = []
        self._attributes = {}
        self._issues = []
        self._incident = None

    def active(self):
        return self.state == "new" or self.state == "review"

    @property
    def incident_priority(self):
        if not self._priority:
            self._priority = self.remote.priorities.for_request(self)
        return self._priority

    @property
    def incident(self):
        if not self._incident:
            self._incident = self.src_project.split(":")[-1]
        return self._incident

    @property
    def assigned_roles(self):
        if not self._assigned_roles:
            self._assigned_roles = Assignment.infer(self.remote, self)
        return self._assigned_roles

    @property
    def comments(self):
        if not self._comments:
            self._comments = self.remote.comments.for_request(self) or [Comment.none]
        return self._comments

    @property
    def maker(self):
        for history in self.statehistory:
            if history.description == "Request created":
                self._creator = self.remote.users.by_name(history.who)
                break
        else:
            self._creator = "Unknown"
        return self._creator

    @property
    def issues(self):
        """Bugs that should be fixed as part of this request"""
        if not self._issues:
            self._issues = self.remote.bugs.for_request(self)
        return self._issues

    @property
    def groups(self):
        # Maybe use a invalidating cache as a trade-off between current
        # information and slow response.
        return [
            review.reviewer
            for review in self.review_list()
            if isinstance(review, GroupReview)
        ]

    @property
    def packages(self):
        """Collects all packages of the actions that are part of the request."""
        if not self._packages:
            packages = set()
            for action in self.actions:
                pkg = action.src_package
                if pkg != "patchinfo":
                    packages.add(pkg)
            self._packages = packages
        return self._packages

    @property
    def src_project(self):
        """Will return the src_project or an empty string if no src_project
        can be found in the request.

        """
        for action in self.actions:
            if hasattr(action, "src_project"):
                prj = action.src_project
                if prj:
                    return prj
                else:
                    logging.info("This project has no source project: %s", self.reqid)
                    return ""
        return ""

    def attribute(self, attribute):
        """Load the specified attribute for this request.

        As requests right now can not contain attributes the attribute will be
        loaded from the corresponding source-project.
        """
        if attribute not in self._attributes:
            attributes = self.remote.projects.get_attribute(self.src_project, attribute)
            if len(attributes) == 1:
                attributes = attributes[0]
            self._attributes[attribute] = attributes
        return self._attributes[attribute]

    def review_action(self, params, user=None, group=None, comment=None):
        if not user and not group:
            raise AttributeError("group or user required for this action.")
        if user:
            params["by_user"] = user.login
        if group:
            params["by_group"] = group.name
        url_params = urlencode(params)
        url = "/".join([self.remote.requests.endpoint, self.reqid])
        url += "?" + url_params
        self.remote.post(url, comment)

    def review_assign(self, group, reviewer, comment=None):
        params = {"cmd": "assignreview", "reviewer": reviewer.login}
        self.review_action(params, group=group, comment=comment)

    def review_unassign(self, group, reviewer, comment=None):
        """Will undo the assignment by the group"""
        params = {"cmd": "assignreview", "revert": 1, "reviewer": reviewer.login}
        self.review_action(params, group=group, comment=comment)

    def review_accept(self, user=None, group=None, comment=None):
        comment = self._format_review_comment(comment)
        params = {"cmd": "changereviewstate", "newstate": "accepted"}
        self.review_action(params, user, group, comment)

    def review_add(self, user=None, group=None, comment=None):
        """Will add a new reviewrequest for the given user or group."""
        comment = self._format_review_comment(comment)
        params = {"cmd": "addreview"}
        self.review_action(params, user, group, comment)

    def review_decline(self, user=None, group=None, comment=None, reasons=None):
        """Will decline the reviewrequest for the given user or group.

        :param user: The user declining the request.

        :param group: The group the request should be declined for.

        :param comment: A comment that will be added to describe why the
            request was declined.

        :param reason: A L{oscqam.reject_reasons.RejectReason} that
            explains why the request was declined.
            The reason will be added as an attribute to the Maintenance
            incident.
        """
        if reasons:
            reason = self._build_reject_attribute(reasons)
            self.remote.projects.set_attribute(self.src_project, reason)
        comment = self._format_review_comment(comment)
        params = {"cmd": "changereviewstate", "newstate": "declined"}
        self.review_action(params, user, group, comment)

    def _build_reject_attribute(self, reasons):
        reject_reason = self.attribute(Attribute.reject_reason)
        reason_values = list(
            map(lambda reason: "{0}:{1}".format(self.reqid, reason.flag), reasons)
        )
        if not reject_reason:
            reject_reason = Attribute.preset(
                self.remote, Attribute.reject_reason, *reason_values
            )
        else:
            for r in reason_values:
                reject_reason.value.append(r)
        return reject_reason

    def review_reopen(self, user=None, group=None, comment=None):
        """Will reopen a reviewrequest for the given user or group."""
        params = {"cmd": "changereviewstate", "newstate": "new"}
        self.review_action(params, user, group, comment)

    def _format_review_comment(self, comment):
        if not comment:
            return None
        return "[oscqam] {comment}".format(comment=comment)

    def review_list(self):
        """Returns all reviews as a list."""
        if not self._reviews:
            for review in self.reviews:
                if review.by_group:
                    self._reviews.append(GroupReview(self.remote, review))
                elif review.by_user:
                    self._reviews.append(UserReview(self.remote, review))
        return self._reviews

    def review_list_open(self):
        """Return only open reviews."""
        return [r for r in self.review_list() if r.state in Request.OPEN_STATES]

    def review_list_accepted(self):
        return [r for r in self.review_list() if r.state.lower() == "accepted"]

    def add_comment(self, comment):
        """Adds a comment to this request."""
        endpoint = "/comments/request/{id}".format(id=self.reqid)
        self.remote.post(endpoint, comment)

    def get_template(self, template_factory):
        """Return the template associated with this request."""
        if not self.src_project:
            raise MissingSourceProjectError(self)
        return template_factory(self)

    @classmethod
    def filter_by_project(cls, request_substring, requests):
        return [r for r in requests if request_substring in r.src_project]

    @classmethod
    def parse(cls, remote, xml):
        et = ET.fromstring(xml)
        requests = []
        for request in et.iter(remote.requests.endpoint):
            try:
                req = Request(remote)
                req.read(request)
                requests.append(req)
            except osc.oscerr.APIError as e:
                logging.error(e.msg)
                pass
            except osc.oscerr.WrongArgs as e:
                # Temporary workaround, as OBS >= 2.7 can return requests with
                # acceptinfo-elements that old osc can not handle.
                if not (osc.core.get_osc_version() < "0.152"):
                    raise
                if "acceptinfo" not in str(e):
                    raise
                else:
                    logging.error("Server version too high for osc-client: %s" % str(e))
                    pass
        return requests

    @classmethod
    def parse_request_id(cls, request_id):
        """Extract the request_id from a string if required.

        The method will extract the request-id of a complete request string
        (e.g. SUSE:Maintenance:123:45678 has a request id of 45678) if
        needed.

        """
        reqid = cls.COMPLETE_REQUEST_ID_SRE.match(request_id)
        if reqid:
            return reqid.group("req")
        return request_id

    def __eq__(self, other):
        project = self.actions[0].src_project
        other_project = other.actions[0].src_project
        return self.reqid == other.reqid and project == other_project

    def __hash__(self):
        hash_parts = [self.reqid]
        if self.src_project:
            hash_parts.append(self.src_project)
        hashes = [hash(part) for part in hash_parts]
        return sum(hashes)

    def __str__(self):
        return "{0}".format(self.reqid)


# coding: utf-8
# wxpay sdk
# Author: www.debug5.com

import hashlib
import hmac
import copy
import uuid
import requests
import sys

import xml.etree.ElementTree as ElementTree

try:
    reload(sys)
    sys.setdefaultencoding('utf-8')
except:
    pass

PY2 = sys.version_info[0] == 2
if not PY2:
    # Python 3.x and up
    text_type = str
    string_types = (str,)
    xrange = range

    def as_text(v):  ## 生成unicode字符串
        if v is None:
            return None
        elif isinstance(v, bytes):
            return v.decode('utf-8', errors='ignore')
        elif isinstance(v, str):
            return v
        else:
            raise ValueError('Unknown type %r' % type(v))

    def is_text(v):
        return isinstance(v, text_type)

else:
    # Python 2.x
    text_type = unicode
    string_types = (str, unicode)
    xrange = xrange

    def as_text(v):
        if v is None:
            return None
        elif isinstance(v, unicode):
            return v
        elif isinstance(v, str):
            return v.decode('utf-8', errors='ignore')
        else:
            raise ValueError('Invalid type %r' % type(v))

    def is_text(v):
        return isinstance(v, text_type)

_DEFAULT_TIMEOUT = 8000  # 微秒

class WXPayConstants(object):
    # SUCCESS, FAIL
    SUCCESS = "SUCCESS"
    FAIL = "FAIL"

    # 签名类型
    SIGN_TYPE_HMACSHA256 = "HMAC-SHA256"
    SIGN_TYPE_MD5 = "MD5"

    # 字段
    FIELD_SIGN = "sign"
    FIELD_SIGN_TYPE = "sign_type"

    # URL
    MICROPAY_URL = "https://api.mch.weixin.qq.com/pay/micropay"
    UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder"
    ORDERQUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery"
    REVERSE_URL = "https://api.mch.weixin.qq.com/secapi/pay/reverse"
    CLOSEORDER_URL = "https://api.mch.weixin.qq.com/pay/closeorder"
    REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund"
    REFUNDQUERY_URL = "https://api.mch.weixin.qq.com/pay/refundquery"
    DOWNLOADBILL_URL = "https://api.mch.weixin.qq.com/pay/downloadbill"
    REPORT_URL = "https://api.mch.weixin.qq.com/payitil/report"
    SHORTURL_URL = "https://api.mch.weixin.qq.com/tools/shorturl"
    AUTHCODETOOPENID_URL = "https://api.mch.weixin.qq.com/tools/authcodetoopenid"

    # Sandbox URL
    SANDBOX_MICROPAY_URL = "https://api.mch.weixin.qq.com/sandboxnew/pay/micropay"
    SANDBOX_UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/sandboxnew/pay/unifiedorder"
    SANDBOX_ORDERQUERY_URL = "https://api.mch.weixin.qq.com/sandboxnew/pay/orderquery"
    SANDBOX_REVERSE_URL = "https://api.mch.weixin.qq.com/sandboxnew/secapi/pay/reverse"
    SANDBOX_CLOSEORDER_URL = "https://api.mch.weixin.qq.com/sandboxnew/pay/closeorder"
    SANDBOX_REFUND_URL = "https://api.mch.weixin.qq.com/sandboxnew/secapi/pay/refund"
    SANDBOX_REFUNDQUERY_URL = "https://api.mch.weixin.qq.com/sandboxnew/pay/refundquery"
    SANDBOX_DOWNLOADBILL_URL = "https://api.mch.weixin.qq.com/sandboxnew/pay/downloadbill"
    SANDBOX_REPORT_URL = "https://api.mch.weixin.qq.com/sandboxnew/payitil/report"
    SANDBOX_SHORTURL_URL = "https://api.mch.weixin.qq.com/sandboxnew/tools/shorturl"
    SANDBOX_AUTHCODETOOPENID_URL = "https://api.mch.weixin.qq.com/sandboxnew/tools/authcodetoopenid"

class WXPayUtil(object):

    @staticmethod
    def dict2xml(data):
        """dict to xml

        @:param data: Dictionary
        @:return: string
        """
        # return as_text( xmltodict.unparse({'xml': data_dict}, pretty=True) )
        root = ElementTree.Element('xml')
        for k in data:
            v = data[k]
            child = ElementTree.SubElement(root, k)
            child.text = str(v)
        return as_text(ElementTree.tostring(root, encoding='utf-8'))

    @staticmethod
    def xml2dict(xml_str):
        """xml to dict

        @:param xml_str: string in XML format
        @:return: Dictionary
        """
        # return xmltodict.parse(xml_str)['xml']
        root = ElementTree.fromstring(xml_str)
        assert as_text(root.tag) == as_text('xml')
        result = {}
        for child in root:
            tag = child.tag
            text = child.text
            result[tag] = text
        return result

    @staticmethod
    def generate_signature(data, key, sign_type=WXPayConstants.SIGN_TYPE_MD5):
        """生成签名

        :param data: dict
        :param key: string. API key
        :param sign_type: string
        :return string
        """
        key = as_text(key)
        data_key_list = data.keys()
        data_key_list = sorted(data_key_list)  # 排序！
        combine_str = as_text('')
        for k in data_key_list:
            v = data[k]
            if k == WXPayConstants.FIELD_SIGN:
                continue
            if v is None or len(str(v)) == 0:
                continue
            combine_str = combine_str + as_text(str(k)) + as_text('=') + as_text(str(v)) + as_text('&')
        combine_str = combine_str + as_text('key=') + key
        if sign_type == WXPayConstants.SIGN_TYPE_MD5:
            return WXPayUtil.md5(combine_str)
        elif sign_type == WXPayConstants.SIGN_TYPE_HMACSHA256:
            return WXPayUtil.hmacsha256(combine_str, key)
        else:
            raise Exception("Invalid sign_type: {}".format(sign_type))

    @staticmethod
    def is_signature_valid(data, key, sign_type=WXPayConstants.SIGN_TYPE_MD5):
        """ 验证xml中的签名

        :param data: dict
        :param key: string. API key
        :param sign_type: string
        :return: bool
        """
        if WXPayConstants.FIELD_SIGN not in data:
            return False
        sign = WXPayUtil.generate_signature(data, key, sign_type)
        if sign == data[WXPayConstants.FIELD_SIGN]:
            return True
        return False

    @staticmethod
    def generate_signed_xml(data, key, sign_type=WXPayConstants.SIGN_TYPE_MD5):
        """ 生成带有签名的xml

        :param data: dict
        :param key: string. API key
        :param sign_type: string
        :return: xml
        """
        key = as_text(key)
        new_data_dict = copy.deepcopy(data)
        sign = WXPayUtil.generate_signature(data, key, sign_type)
        new_data_dict[WXPayConstants.FIELD_SIGN] = sign
        return WXPayUtil.dict2xml(new_data_dict)

    @staticmethod
    def generate_nonce_str():
        """ 生成随机字符串

        :return string
        """
        r = uuid.uuid1().hex.replace('-', '')
        return as_text(r)

    @staticmethod
    def md5(source):
        """ generate md5 of source. the result is Uppercase and Hexdigest.

        @:param source: string
        @:return: string
        """
        hash_md5 = hashlib.md5(as_text(source).encode('utf-8'))
        return hash_md5.hexdigest().upper()

    @staticmethod
    def hmacsha256(source, key):
        """ generate hmacsha256 of source. the result is Uppercase and Hexdigest.

        @:param source: string
        @:param key: string
        @:return: string
        """
        return hmac.new(as_text(key).encode('utf-8'), as_text(source).encode('utf-8'),
                        hashlib.sha256).hexdigest().upper()

class SignInvalidException(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

class WXPay(object):

    def __init__(self, app_id, mch_id, key, cert_pem_path, key_pem_path, timeout=_DEFAULT_TIMEOUT,
                 sign_type=WXPayConstants.SIGN_TYPE_MD5, use_sandbox=False, plat_type=None):
        """ 初始化

        :param timeout: 网络请求超时时间，单位毫秒
        """
        self.app_id = app_id
        self.mch_id = mch_id
        self.key = key
        self.cert_pem_path = cert_pem_path
        self.key_pem_path = key_pem_path
        self.timeout = timeout
        self.sign_type = sign_type
        self.use_sandbox = use_sandbox
        self.plat_type = plat_type

    def fill_request_data(self, data):
        """data中添加 appid、mch_id、nonce_str、sign_type、sign

        :param data: dict
        :return: dict
        """
        new_data_dict = copy.deepcopy(data)
        new_data_dict['appid'] = self.app_id
        new_data_dict['mch_id'] = self.mch_id
        new_data_dict['nonce_str'] = WXPayUtil.generate_nonce_str()
        if self.plat_type == '1':
            new_data_dict = scene_info
        if self.sign_type == WXPayConstants.SIGN_TYPE_MD5:
            new_data_dict['sign_type'] = WXPayConstants.SIGN_TYPE_MD5
        elif self.sign_type == WXPayConstants.SIGN_TYPE_HMACSHA256:
            new_data_dict['sign_type'] = WXPayConstants.SIGN_TYPE_HMACSHA256
        else:
            raise Exception("Invalid sign_type: {}".format(self.sign_type))

        new_data_dict['sign'] = WXPayUtil.generate_signature(new_data_dict, self.key, self.sign_type)
        return new_data_dict

    def is_response_signature_valid(self, data):
        """检查微信响应的xml数据中签名是否合法，先转换成dict

        :param data: dict类型
        :return: bool
        """
        return WXPayUtil.is_signature_valid(data, self.key, self.sign_type)

    def is_pay_result_notify_signature_valid(self, data):
        """支付结果通知中的签名是否合法

        :param data: dict
        :return: bool
        """
        sign_type = data.get(WXPayConstants.FIELD_SIGN, WXPayConstants.SIGN_TYPE_MD5)
        if len(sign_type.trim()) == 0:
            sign_type = WXPayConstants.SIGN_TYPE_MD5
        if sign_type not in [WXPayConstants.SIGN_TYPE_MD5, WXPayConstants.SIGN_TYPE_HMACSHA256]:
            raise Exception("invalid sign_type: {} in pay result notify".format(sign_type))
        return WXPayUtil.is_signature_valid(data, self.key, sign_type)

    def request_with_cert(self, url, data, timeout=None):
        """ """
        req_body = WXPayUtil.dict2xml(data).encode('utf-8')
        req_headers = {'Content-Type': 'application/xml'}
        _timeout = self.timeout if timeout is None else timeout
        resp = requests.post(url,
                             data=req_body,
                             headers=req_headers,
                             timeout=_timeout / 1000.0,
                             cert=(self.cert_pem_path, self.key_pem_path),
                             verify=True)
        resp.encoding = 'utf-8'
        return resp.text

        # if resp.status_code == 200:
        #     # print as_text(resp.text)
        #     return as_text(resp.text)
        # raise Exception('HTTP response code is not 200')

    def request_without_cert(self, url, data, timeout=None):
        """ 不带证书的请求

        :param url: string
        :param data: dict
        :param timeout: int. ms
        :return:
        """
        req_body = WXPayUtil.dict2xml(data).encode('utf-8')
        req_headers = {'Content-Type': 'application/xml'}
        _timeout = self.timeout if timeout is None else timeout
        resp = requests.post(url,
                             data=req_body,
                             headers=req_headers,
                             timeout=_timeout / 1000.0)
        resp.encoding = 'utf-8'
        return as_text(resp.text)

        # if resp.status_code == 200:
        #     # print as_text(resp.text)
        #     return as_text(resp.text)
        # raise Exception('HTTP response code is not 200')

    def process_response_xml(self, resp_xml):
        """ 处理微信支付返回的 xml 格式数据

        :param resp_xml:
        :return:
        """
        resp_dict = WXPayUtil.xml2dict(resp_xml)
        if 'return_code' in resp_dict:
            return_code = resp_dict.get('return_code')
        else:
            raise Exception('no return_code in response data: {}'.format(resp_xml))

        if return_code == WXPayConstants.FAIL:
            return resp_dict
        elif return_code == WXPayConstants.SUCCESS:
            if self.is_response_signature_valid(resp_dict):
                return resp_dict
            else:
                raise SignInvalidException('invalid sign in response data: {}'.format(resp_xml))
        else:
            raise Exception('return_code value {} is invalid in response data: {}'.format(return_code, resp_xml))

    def micropay(self, data, timeout=None):
        """ 提交刷卡支付

        :param data: dict
        :param timeout: int
        :return: dict
        """
        _timeout = self.timeout if timeout is None else timeout
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_MICROPAY_URL
        else:
            url = WXPayConstants.MICROPAY_URL

        resp_xml = self.request_without_cert(url, self.fill_request_data(data), _timeout)
        return self.process_response_xml(resp_xml)

    def unifiedorder(self, data, timeout=None):
        """ 统一下单

        :param data: dict
        :param timeout: int
        :return: dict
        """
        _timeout = self.timeout if timeout is None else timeout
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_UNIFIEDORDER_URL
        else:
            url = WXPayConstants.UNIFIEDORDER_URL
        resp_xml = self.request_without_cert(url, self.fill_request_data(data), _timeout)
        return self.process_response_xml(resp_xml)

    def orderquery(self, data, timeout=None):
        """ 查询订单

        :param data: dict
        :param timeout: int
        :return: dict
        """
        _timeout = self.timeout if timeout is None else timeout
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_ORDERQUERY_URL
        else:
            url = WXPayConstants.ORDERQUERY_URL
        resp_xml = self.request_without_cert(url, self.fill_request_data(data), _timeout)
        return self.process_response_xml(resp_xml)

    def reverse(self, data, timeout=None):
        """ 撤销订单

        :param data: dict
        :param timeout: int
        :return: dict
        """
        _timeout = self.timeout if timeout is None else timeout
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_REVERSE_URL
        else:
            url = WXPayConstants.REVERSE_URL
        resp_xml = self.request_with_cert(url, self.fill_request_data(data), _timeout)
        return self.process_response_xml(resp_xml)

    def closeorder(self, data, timeout=None):
        """ 关闭订单

        :param data: dict
        :param timeout: int
        :return: dict
        """
        _timeout = self.timeout if timeout is None else timeout
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_CLOSEORDER_URL
        else:
            url = WXPayConstants.CLOSEORDER_URL
        resp_xml = self.request_without_cert(url, self.fill_request_data(data), _timeout)
        return self.process_response_xml(resp_xml)

    def refund(self, data, timeout=None):
        """ 申请退款

        :param data: dict
        :param timeout: int
        :return: dict
        """
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_REFUND_URL
        else:
            url = WXPayConstants.REFUND_URL
        _timeout = self.timeout if timeout is None else timeout
        resp_xml = self.request_with_cert(url, self.fill_request_data(data), _timeout)
        return self.process_response_xml(resp_xml)

    def refundquery(self, data, timeout=None):
        """ 查询退款

        :param data: dict
        :param timeout: int
        :return: dict
        """
        _timeout = self.timeout if timeout is None else timeout
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_REFUNDQUERY_URL
        else:
            url = WXPayConstants.REFUNDQUERY_URL
        resp_xml = self.request_without_cert(url, self.fill_request_data(data), _timeout)
        return self.process_response_xml(resp_xml)

    def downloadbill(self, data, timeout=None):
        """ 下载对账单。官方文档中指出成功时返回对账单数据，失败时返回XML格式数据。
        这里做一层封装，都返回dict。

        :param data: dict
        :param timeout: int
        :return: dict
        """
        _timeout = self.timeout if timeout is None else timeout
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_DOWNLOADBILL_URL
        else:
            url = WXPayConstants.DOWNLOADBILL_URL
        resp = self.request_without_cert(url, self.fill_request_data(data), _timeout).strip()
        if resp.startswith('<'):  # 是XML，下载出错了
            resp_dict = WXPayUtil.xml2dict(resp)
        else:  # 下载成功，加一层封装
            resp_dict = {'return_code': 'SUCCESS', 'return_msg': '', 'data': resp}
        return resp_dict

    def report(self, data, timeout=None):
        """ 交易保障

        :param data: dict
        :param timeout: int
        :return: dict
        """
        _timeout = self.timeout if timeout is None else timeout
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_REPORT_URL
        else:
            url = WXPayConstants.REPORT_URL
        resp_xml = self.request_without_cert(url, self.fill_request_data(data), _timeout)
        resp_dict = WXPayUtil.xml2dict(resp_xml)
        return resp_dict

    def shorturl(self, data, timeout=None):
        """ 转换短链接

        :param data: dict
        :param timeout: int
        :return: dict
        """
        _timeout = self.timeout if timeout is None else timeout
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_SHORTURL_URL
        else:
            url = WXPayConstants.SHORTURL_URL
        resp_xml = self.request_without_cert(url, self.fill_request_data(data), _timeout)
        return self.process_response_xml(resp_xml)

    def authcodetoopenid(self, data, timeout=None):
        """ 授权码查询OPENID接口

        :param data: dict
        :param timeout: int
        :return: dict
        """
        _timeout = self.timeout if timeout is None else timeout
        if self.use_sandbox:
            url = WXPayConstants.SANDBOX_AUTHCODETOOPENID_URL
        else:
            url = WXPayConstants.AUTHCODETOOPENID_URL
        resp_xml = self.request_without_cert(url, self.fill_request_data(data), _timeout)
        return self.process_response_xml(resp_xml)


from collections import deque

tools = deque(map(int, input().split()))
substances = deque(map(int, input().split()))
challenges = deque(map(int, input().split()))

while tools and substances and challenges:
    tool = tools[0]
    substance = substances[-1]
    result = tool * substance

    if result in challenges:
        challenges.remove(result)
        tools.popleft()
        substances.pop()
    else:
        tool += 1
        tools.append(tool)
        tools.popleft()
        substance -= 1
        if substance > 0:
            substances[-1] = substance
        else:
            substances.pop()

if len(challenges) == 0:
    print("Harry found an ostracon, which is dated to the 6th century BCE.")
else:
    print("Harry is lost in the temple. Oblivion awaits him.")

if tools:
    print("Tools:", ', '.join(map(str, tools)))
if substances:
    print("Substances:", ', '.join(map(str, reversed(substances))))
if challenges:
    print("Challenges:", ', '.join(map(str, challenges)))


from __future__ import absolute_import, division, print_function

import itertools

from ..components import Actor
from ..schedulers import _ActorRunner, ThreadedScheduler
from future.builtins import super

class Concat(Actor):

    _system_actor = True

    def __init__(self, n_ports, name='concat'):
        super().__init__(name=name)
        for i in range(n_ports):
            self.inports.append('in_{}'.format(i))
        self.outports.append('out')
        self._last_connected = -1

    def get_run_args(self):
        return (), {}

    def run(self, *args, **kwargs):
        res = tuple((port.pop() for port in self.inports))
        return {'out': res}

    def connect_input(self, port, i=None):
        """
        Connects i-th input. If i is None, the last value + 1 is used.

        Args:
            port (OutPort): output port to connect
            i (int): input port index
        """

        if i is None:
            i = self._last_connected + 1
        self._last_connected = i
        self.inports['in_{}'.format(i)].connect(port)

class MultiConcat(Actor):

    _system_actor = True

    def __init__(self, name='multiconcat'):
        super().__init__(name=name)
        self._port_names = []
        self._last_connected = -1

    def get_run_args(self):
        return (), {}

    def run(self, *args, **kwargs):
        res = {}
        for inport, outport in zip(self.inports, itertools.cycle(self.outports)):
            res.setdefault(outport.name, [])
            res[outport.name].append(inport.pop())
        return res

    def add_and_connect(self, actor):
        if self._last_connected > -1:
            assert self._port_names == [port.name for port in actor.outports]
        self._last_connected += 1
        i = self._last_connected
        for port in actor.outports:
            self.inports.append('{}_{}'.format(port.name, i))
            self.inports.at(-1).connect(port)
            if i == 0:
                self.outports.append(port.name)
                self._port_names.append(port.name)

class Map(Actor):
    """
    Maps a given actor on input token elements.

    The mapped actor is assumed to have a single input and a single output port.

    Args:
        actor (Actor): Actor class to be mapped to inputs
        args (list): positional arguments for actor.__init__
        kwargs (dict): keyword arguments for actor.__init__
        scheduler (Scheduler): scheduler to use, default is not to change the scheduler
        name (string): actor name

    Ports:
        in (iterable): contains items to be passed to the mapped actor
        out (tuple): items after applying the map actor
    """

    _system_actor = True

    def __init__(self, actor_class, args=(), kwargs={}, scheduler=None, name='map'):
        super().__init__(name=name)
        self.actor_class = actor_class
        self.actor_args = args
        self.actor_kwargs = kwargs
        self.map_scheduler = scheduler
        # get port names from an actor instance
        actor = self.actor_class(*self.actor_args, **self.actor_kwargs)
        for pname in actor.inports.keys():
            self.inports.append(pname)
        for pname in actor.outports.keys():
            self.outports.append(pname)

    def get_run_args(self):
        return (), {}

    def run(self, *args, **kwargs):
        # run is not a classfunction for Map
        # bacause it needs to change the workflow
        if self.map_scheduler is None:
            # self.schduler is set by the calling scheduler
            map_scheduler = self.scheduler.copy()
        elif isinstance(self.map_scheduler, (_ActorRunner, ThreadedScheduler)):
            # we need a copy of an existing scheduler
            map_scheduler = self.map_scheduler.copy()
        else:
            # in this case, we assume self.map_scheduler is a class
            map_scheduler = self.map_scheduler()
        # destinations = [port for port in self.outports['out'].connections]
        # disconnect the output port
        # for port in destinations:
        #     self.outports['out'].disconnect(port)
        # create the map actors, connect and put inputs
        map_actors = []
        concat_actor = MultiConcat()
        # items will iterate over all ports inputs, i.e. will contain n-th actor input
        # TODO ensure equal input lengths
        for items in zip(*(port.pop() for port in self.inports)):
            # get actor instance
            actor = self.actor_class(*self.actor_args, **self.actor_kwargs)
            map_actors.append(actor)
            concat_actor.add_and_connect(actor)
            # put the input data item
            for port, value in zip(actor.inports, items):
                # value is a single input item of the port
                map_scheduler.put_value(port, value)
        # run the mapping sub-workflows
        # map_workflow = concat_actor.get_workflow()
        # result = map_scheduler.run_workflow(map_workflow)
        map_scheduler.execute()

        result = {port.name: port.pop() for port in concat_actor.outports}
        return result

class PassWID(Actor):
    """
    Pass input argument with hostname and process ID attached
    """
    def __init__(self, name='passwid'):
        super().__init__(name=name)
        self.inports.append('inp')
        self.outports.append('out')

    def get_run_args(self):
        return (self.inports['inp'].pop(), ), {}

    @staticmethod
    def run(*args, **kwargs):
        from os import getpid
        from socket import gethostname
        return {'out':
                    {'inp': args[0],
                     'host': gethostname(),
                     'pid': getpid()}}


from matplotlib import pyplot as plt
# 可视化

plt.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文

fig = plt.figure()
plt.text(0.66, 0.41, "戴")

plt.show()

import re

data = "如果放到POST中将出错"

import jieba
jieba.suggest_freq(("中", "将"), True)
seg_list = jieba.cut(data,  HMM=False)

seg_list1 = jieba.cut_for_search(data)
print("Full mode:", "/ ".join(seg_list))
print("Full mode:", "/ ".join(seg_list1))
result = jieba.tokenize(data)
print(result)
for i in result:
    print(i)


from sklearn.base import TransformerMixin, BaseEstimator
from scipy import sparse
import numpy as np

class CentroidClass(TransformerMixin, BaseEstimator):

    def __init__(self, classes=None):
        if classes is None:
            raise ValueError("need to give the classes labels")
        self.classes = classes
        self.n_classes = len(classes)

    def combine_vectors(self, X, y):
        n, bop_size = X.shape
        class_X = sparse.lil_matrix((self.n_classes, bop_size))
        class_counter = np.zeros(self.n_classes)
        for i in range(n):
            lbl = y[i]
            k = np.where(lbl == self.classes)[0]
            class_X[k] += X[i]
            class_counter[k] += 1

        for i in range(self.n_classes):
            class_X[i] /= class_counter[i]
        return class_X

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        return X

    def fit_transform(self, X, y=None, **fit_params):
        if y is None:
            raise ValueError("need labels to generate class based")
        return self.combine_vectors(X, y)


import numba

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        a = head
        b = head
        for i in range(n):
            b = b.next
        if b==None:
            head=head.next
            return head
        while b.next != None:
            a = a.next
            b = b.next
        a.next = a.next.next
        return head


from flask import Flask, request, jsonify, abort
import json
from review_classifier import classifier
import sys

app = Flask(__name__)

@app.route('/predict', methods = ["post", "get"])
def predict_review():
    """
    :return: response in json
    """

    # Response for a GET
    if request.method == "GET":
        text = request.args.get('text')
        predicted = classifier([text])
    # Response for a POST
    if request.method == "POST":

        if request.headers['Content-type'] != "application/json":
            abort(400)
        data = json.loads(request.data, strict = False)
        text = data['text']
        predicted = classifier([text])

    return jsonify({'predicted': predicted,'text': text})

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


from django.shortcuts import render
from index.models import Slider, Nav, MustBuy, Shop, Show, FoodType,CartModel

# Create your views here.

def home(request):
    datas = Slider.objects.all()
    navs_data = Nav.objects.all()
    must_buy = MustBuy.objects.all()
    shop = Shop.objects.all()
    shows = Show.objects.all()
    data={
        'datas':datas,
        'navs_data': navs_data,
        'must_buy': must_buy,
        'shops': shop,
        'shows': shows

    }
    return render(request, 'home/home.html', data)

def allgoods_sum():
    carts_goods = CartModel.objects.filter(is_select=True)
    sum = 0
    for cart_good in carts_goods:
        goods_price = float(cart_good.goods.price) * int(cart_good.c_num)
        sum += goods_price
    return sum


from matplotlib import pyplot
import regex
import numpy as np

with open("./training_output_losses.txt", "r") as file:
    text = file.read()

losses = regex.findall(r"(Test|Average) Loss: ([0-9.]*)", text)
trainings = []
tests = []

for match in losses:
    matchtype, loss_str = match
    if matchtype == "Average":
        trainings.append((len(trainings) + 1, float(loss_str)))
    elif matchtype == "Test":
        tests.append((len(trainings), float(loss_str)))
    else:
        print(match)
        quit()

trainxs, trainys = zip(*trainings)
testxs, testys = zip(*tests)
basexs, baseys = [0, len(trainings) + 1], [1.283, 1.283]

pyplot.plot(trainxs, trainys)
pyplot.plot(testxs, testys)
pyplot.plot(basexs, baseys)

pyplot.title("Loss by Epochs")
pyplot.xlabel("Epochs")
pyplot.ylabel("MSE loss")
pyplot.legend(["Training Loss", "Test Loss", "Baseline"])
print(testys)
pyplot.show()


man = '👱♂Парни'
woman = '👩  Девушки'
interested_man = '👱♂Показать парней'
interested_woman = '👩  Показать девушек'
reg_man = '👱♂Парень'
reg_woman = '👩 Девушка'
back = '⬅ Назад'
back_settings = '⬅ Назад в настройки'
back_search_gender = 'Назад к поиску гендера'
back_name = 'Назад к выбору имени'
back_age = 'Назад к выбору возраста'
back_photo = 'Назад к выбору фото'
further = '➡ Далее'
age_1 = 'от 18 до 20'
age_2 = 'От 21 до 24'
age_3 = 'От 25 до 29'
age_4 = 'От 30 до 35'
age_5 = 'От 36 до 40'
age_6 = 'От 40 и старше'
no_choice = '❌ Заменить обе анкеты'
start_reg = '➡ Начать регистрацию'
start_menu = '🌟 Начать раунд'
start_round = '🔥 Начать {} раунд'
sender_like = '❤ Входящие лайки'
settings = '⚙ Настройки'
open_contact = '🤔  Как открыть контакт?'
choice_round = 'Что такое 👑 Выбор раунда'
price_prem = '👑  Купить премиум'
remove_restrictions = '🔓 Снять ограничения раундов'
settings_1 = '1⃣ Пол поиска'
settings_2 = '2⃣ Возраст поиска'
settings_3 = '3⃣ Мой пол'
settings_4 = '4⃣ Имя'
settings_5 = '5⃣ Мой Возраст'
settings_6 = '6⃣ Способ связи'
settings_7 = '7⃣ Фото'
settings_8 = '8⃣ Премиум'
setting_list = [settings_1, settings_2, settings_3, settings_4, settings_5, settings_6, settings_7, settings_8]
choice_telegram = 'Telegram'
choice_instagram = 'Instagram'
choice_whatsapp = 'Whatsapp'
other = 'Другое'
back_social = 'Назад в соц-сети'
choice_list = [choice_telegram, choice_instagram, choice_whatsapp, other]
back_itog = 'Back itog'


# -*- coding: utf-8 -*-
# @Author: Theo Lemaire
# @Email: theo.lemaire@epfl.ch
# @Date:   2017-02-15 15:59:37
# @Last Modified by:   Theo Lemaire
# @Last Modified time: 2020-02-03 21:21:58

''' Plot the effective variables as a function of charge density with color code. '''

import numpy as np
import logging
import matplotlib.pyplot as plt

from PySONIC.plt import plotEffectiveVariables
from PySONIC.utils import logger
from PySONIC.parsers import MechSimParser

# Set logging level
logger.setLevel(logging.INFO)

def main():

    parser = MechSimParser()
    parser.addNeuron()
    parser.addNColumns()
    parser.addNLevels()
    parser.defaults['neuron'] = 'RS'
    parser.defaults['radius'] = np.nan
    parser.defaults['freq'] = np.nan
    parser.defaults['amp'] = np.nan
    args = parser.parse()
    for k in ['charge', 'embedding', 'Cm0', 'Qm0', 'fs', 'mpi', 'pltscheme', 'plot']:
        del args[k]
    logger.setLevel(args['loglevel'])

    # Restrict radius, frequency and amplitude to single values
    for k in ['radius', 'freq', 'amp']:
        if len(args[k]) > 1:
            logger.error(f'multiple {k} values not allowed')
        val = args[k][0]
        if np.isnan(val):
            args[k] = None
        else:
            args[k] = val

    for pneuron in args['neuron']:
        plotEffectiveVariables(
            pneuron, a=args['radius'], f=args['freq'], A=args['amp'],
            zscale=args['cscale'], cmap=args['cmap'], ncolmax=args['ncol'], nlevels=args['nlevels'])

    plt.show()

if __name__ == '__main__':
    main()


import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
import sqlite3

subjects = ["", "El gran santiago", ""]
labels_recorded = []
conn = sqlite3.connect("records.sqlite")
c = conn.cursor()

def recordDetection(label):
    if(label not in labels_recorded):
        labels_recorded.append(label)
        try:
            c.execute("INSERT INTO records (id,identifier, site, cam_code) VALUES (NULL, '" + label + "', 'Door office 1' , 'CodeCAM')")
            conn.commit()
            #conn.close()
        except sqlite3.IntegrityError:
            print('ERROR: ID already exists in PRIMARY KEY column {}'.format(id_column))

def draw_rectangle(img, rect):
    (x, y, w, h) = rect
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

def draw_text(img, text, x, y):
    return cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)

def detect_face(img):
    gray = img
    #cascada entrenada para detectar rostros frontales.
    face_cascade_profile = cv2.CascadeClassifier('trainer-haar-files/haarcascade_profileface.xml')
    face_cascade_frontal = cv2.CascadeClassifier('trainer-haar-files/haarcascade_frontalface_alt.xml')

    faces_frontal = face_cascade_frontal.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);
    detected = False;

    if (len(faces_frontal) > 0):
        return faces_frontal
        detected = True

    if (detected is not True):
        faces_profile_right = face_cascade_profile.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);
        if (len(faces_profile_right) > 0):
            return faces_profile_right
            detected = True

    if (detected is False):
        return None

def predict(test_img):
    img = test_img.copy()
    faces = detect_face(img)

    if(faces is not None):
        for face in faces:
            rect = (x, y, w, h) = face
            label = face_recognizer.predict(img[y:y+w, x:x+h])
            #label_text = subjects[label[0]] + " " + str(label[1])
            label_text = subjects[label[0]]
            draw_rectangle(img, rect)
            draw_text(img, label_text, rect[0], rect[1]-5)
            recordDetection(label_text)

    return img

#stest_img1 = cv2.imread("test-data/test1.jpg")
#predicted_img1 = predict(test_img1)
#create a figure of 2 plots (one for each test image)

face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer.setThreshold(40)
face_recognizer.read("trainer.yml")

cap = cv2.VideoCapture(1)
w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print("Resolution : " + str(w) + "x" + str(h), 0, 0)

while(True):
    ret, frame = cap.read()
    test_img1 = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    predicted_img1 = predict(test_img1)

    cv2.imshow("frame", predicted_img1)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


# Check if the scribbles are connected
#
#

import numpy as np

class depth_first_search():
    """
    My implementation of the depth first search
    """
    def __init__(self):
        # Check separate scribbles
        self.reset()
        self.set_kernel(3)

    def reset(self):
        """

        :return:
        """
        self.queue = np.ones([1,3])*-1
        self.nbr_of_separate_scribbles_for_same_instance = 1

    def set_kernel(self,kernel_size):
        """

        :param kernel_size:
        :return:
        """
        self.kernel = kernel_size

    def manage_queue_entries(self, possible_new_neighbor_nodes):
        """"""
        self.queue         = np.vstack((self.queue, possible_new_neighbor_nodes))   # Add to queue
        _, order_for_queue = np.unique(self.queue, axis = 0, return_index=True)     # Keep only unique coord
        self.queue         = self.queue[order_for_queue]

    def manage_queue_exists(self):
        """"""
        new_coords = self.queue[1:][-1].astype(np.int)
        self.queue = self.queue[:-1]
        return  new_coords[0], new_coords[1]

    def update_masks(self, h_pos,w_pos):
        """"""
        self.Mask_w_obj_id[h_pos,w_pos] = 0
        self.Mask_w_scribble_id[h_pos,w_pos] = self.nbr_of_separate_scribbles_for_same_instance

    def list_coord_to_highligh(self):
        """"""
        H_coords, W_coords = np.where(self.Mask_w_obj_id == 1)  # list coordinates of the highlighted elements
        return H_coords[0], W_coords[0]

    def node_to_visit_in_depth_first_search_wise(self, obj_id, h_pos, w_pos):
        """

        :param idx:
        :return:
        """
        # Check neighbors value
        neighbor_values = np.zeros([self.kernel*self.kernel, self.kernel])  # array [h_pos, w_pos, value] to be expected
        low_boundary    = int((1 - self.kernel) / 2)
        high_boundary   = int(1 + ((self.kernel - 1) / 2))
        filter_res      = - 1
        neigh_idx       = 0

        for hdx in range(low_boundary, high_boundary):
            for wdx in range(low_boundary, high_boundary):
                neighbor_values[neigh_idx] = np.array([hdx + h_pos, wdx + w_pos,
                                                       self.Mask_w_obj_id[hdx + h_pos, wdx + w_pos]])

                filter_res += self.Mask_w_obj_id[hdx + h_pos, wdx + w_pos]
                neigh_idx  +=1

        neighbor_values = np.vstack((neighbor_values[:4], neighbor_values[5:]))
        self.update_masks(h_pos,w_pos) # Set the value of visited nodes to 0, so that i don't revisit them

        if filter_res > 0:  # connected to a new node
            # check which nodes a connected to the current note
            neighbor_nodes = neighbor_values[neighbor_values[:,-1] == 1]
            self.manage_queue_entries(neighbor_nodes)
            next_h_node_coord, next_w_node_coord = self.manage_queue_exists()
            # Keep following depth first the search
            return obj_id, next_h_node_coord, next_w_node_coord

        else:
            if len(self.queue) == 1: # mean no more values in the queue
                # Check if all nodes have been visited
                if self.Mask_w_obj_id.max() != 0: # Not all nodes have been visited
                    self.nbr_of_separate_scribbles_for_same_instance +=1
                    next_h_node_coord, next_w_node_coord = self.list_coord_to_highligh()
                    return obj_id, next_h_node_coord, next_w_node_coord

                else:
                    return obj_id, False, False # Just return last obj_id but let the other values as is

            else:   # not all nodes in the queue have been visited... backtrace until the end
                next_h_node_coord, next_w_node_coord = self.manage_queue_exists()
                return obj_id, next_h_node_coord, next_w_node_coord

    def extract_scribbles_properly(self, array_w_scribbles):
        """
        Extract scribbles as one element if smaller scribbles compose it and are connected to one another
        input: array
        :return:
        """
        obj_ids = np.unique(array_w_scribbles)[1:]  #--> first element is expected to be the id for no scirbbles
        Dict = {}
        for obj_id in obj_ids:
            # print('OBJ_ID:', obj_id)
            self.obj_id = obj_id
            self.reset()

            self.Mask_w_obj_id_or   = (array_w_scribbles==obj_id).astype(np.int)                    # highlight an obj id in the array
            self.Mask_w_obj_id      = np.pad(self.Mask_w_obj_id_or.copy(),((1,1),(1,1)), 'constant', constant_values=((0,0),(0,0))) # Serves also as history for visited nodes
            self.Mask_w_scribble_id = np.zeros_like(self.Mask_w_obj_id)                             # Keep track of the scribbles belonging the same scribble id for the same obj id

            start_H_coord, start_W_coord = self.list_coord_to_highligh()

            while self.Mask_w_obj_id.max() != 0:
                # print('Max:',self.Mask_w_obj_id.sum())
                obj_id, start_H_coord, start_W_coord = self.node_to_visit_in_depth_first_search_wise(obj_id,
                                                                                start_H_coord,
                                                                                start_W_coord)

            Mask_w_scribble_id_unpad = self.Mask_w_scribble_id[1:-1,1:-1]

            Mask_w_scribble_id_unpad_ordered = self.order_scribbles_based_on_size(Mask_w_scribble_id_unpad)

            Dict["Obj_id_{}".format(obj_id)] = Mask_w_scribble_id_unpad_ordered

        return Dict

    def order_scribbles_based_on_size(self,Mask_w_scribble_id):
        new_order_array  = np.array([-1])
        max_scribble_idx = Mask_w_scribble_id.max()
        Mask_w_scribble_id_ordered = np.zeros_like(Mask_w_scribble_id)

        # Store size
        for idx in range(1,max_scribble_idx+1):
            nbr_of_elements = (Mask_w_scribble_id == idx).sum()
            new_order_array = np.hstack((new_order_array, nbr_of_elements))

        # extract order based on largest to smallest
        new_order_array = new_order_array[1:]
        new_values_for_scribble = np.argsort(new_order_array)[::-1]+1

        for s_idx in range(1,len(new_values_for_scribble)+1):
            Mask_w_scribble_id_ordered[Mask_w_scribble_id == new_values_for_scribble[s_idx-1]] = s_idx

        return Mask_w_scribble_id_ordered

# Test the module
if "__main__" == __name__ :
    # toy_example = np.array([[3, 3, 2, 0, 1, 0],
    #                         [3, 3, 3, 1, 0, 1],
    #                         [1, 0, 0, 1, 0, 2],
    #                         [0, 1, 1, 0, 2, 1],
    #                         [0, 0, 2, 2, 1, 2],
    #                         [0, 0, 2, 1, 1, 1]])

    toy_example = np.array([[1, 0, 1, 1, 0, 0],
                            [0, 0, 0, 0, 0, 1],
                            [0, 1, 1, 1, 1, 0],
                            [1, 1, 0, 0, 0, 0],
                            [0, 1, 0, 1, 1, 0],
                            [0, 0, 0, 0, 0, 1]])

    # toy_example = (toy_example*2)-1
    # toy_example[0,0] = 0
    # print(toy_example)

    dfs = depth_first_search()
    Dict = dfs.extract_scribbles_properly(toy_example)
    print(Dict)


import sys
import Adafruit_DHT
import RPi.GPIO as GPIO
import time

LED_PIN = 12
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED_PIN, GPIO.OUT)

sensor_args = { '11': Adafruit_DHT.DHT11,
				'22': Adafruit_DHT.DHT22,
				'2302': Adafruit_DHT.AM2302,}

if len(sys.argv) == 4 and sys.argv[1] in sensor_args:
	sensor = sensor_args[sys.argv[1]]
	pin = sys.argv[2]
	temp = float(sys.argv[3])
else:
	print('usage: sudo ./Adafruit_DHT.py [11|22|2302] GPIOpin#')
	print('example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO #4')
	GPIO.cleanup()
	sys.exit(1)

try:
	while True:
		humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
		if temperature is not None:
			if float(temperature) > temp:
				GPIO.output(LED_PIN, GPIO.HIGH)
			else:
				GPIO.output(LED_PIN, GPIO.LOW)
		else:
			print('Failed to get reading. Try again!')
			GPIO.cleanup()
			sys.exit(1)
except KeyboardInterrupt:
	print("Exception: KeyboardInterrupt")
finally:
	GPIO.cleanup()


### 1 - NORMALIZA RGB
def normaliza_RGB(R=0, G=0, B=0, r=0, g=0, b=0):
    r = R / (R + G + B)
    g = G / (R + G + B)
    b = B / (R + G + B)

    if (r, g, b) == (255, 255, 255):
        return r + g + b

### 2 - RGB PARA HSV
import colorsys
colorsys.rgb_to_hsv(.3, .4, .2)
(0.25, 0.5, 0.4)

### 3 - HSV PARA RGB
import colorsys
colorsys.hsv_to_rgb(0.25, 0.5, 0.4)
(0.3, 0.4, 0.2)

### 4 - RGB PARA CMYK
RGB_SCALE = 255
CMYK_SCALE = 100

def rgb_para_cmyk (r, g, b):
    if (r, g, b) == (0, 0, 0):
        #preto
        return 0, 0, 0, CMYK_SCALE

    # rgb [0, 255] -> cmyk [0, 1]
    c = 1 - r / RGB_SCALE
    m = 1 - g / RGB_SCALE
    y = 1 - b / RGB_SCALE

    #valor do k [0, 1]
    min_cmy = min(c, m, y)
    c = (c - min_cmy) / (1 - min_cmy)
    m = (m - min_cmy) / (1 - min_cmy)
    y = (y - min_cmy) / (1 - min_cmy)
    k = min_cmy

    return c * CMYK_SCALE, m * CMYK_SCALE, y * CMYK_SCALE, k * CMYK_SCALE

### 5 - CMYK PARA RGB
def cmyk_para_rgb(c, m, y, k, cmyk_scale, rgb_scale=255):
    r = rgb_scale * (1.0 - c / float(cmyk_scale)) * (1.0 - k / float(cmyk_scale))
    g = rgb_scale * (1.0 - m / float(cmyk_scale)) * (1.0 - k / float(cmyk_scale))
    b = rgb_scale * (1.0 - y / float(cmyk_scale)) * (1.0 - k / float(cmyk_scale))
    return r, g, b

### 6 - RGB PARA GRAYSCALE
def rgb_para_grayscale(I, R=0, G=0, B=0):
    if (R, G, B) == (10, 20, 30):
        I = (R+G+B) / 3
        return I


import time
from picamera2 import Picamera2, Preview
import numpy as np
#from libcamera import controls
#from picamera2.encoders import H264Encoder
from gpiozero import LightSensor
# Set the video size and frame rate
main_size = (1280, 720)
lores_size = (320, 240)
framerate = 30
ldr = LightSensor(12)
import RPi.GPIO as GPIO
# Initialize the camera
picam2 = Picamera2()
#GPIO.setmode(GPIO.BCM)
#GPIO.setwarnings(False)
GPIO.setup(20, GPIO.OUT)
video_config = picam2.create_video_configuration(
    main={"size": main_size, "format": "RGB888"},
    lores={"size": lores_size, "format": "YUV420"})

config = picam2.create_preview_configuration(lores={"size": lores_size, "format": "YUV420"})
picam2.configure(config)

###picam2.configure(video_config)

#encoder = H264Encoder(1000000, framerate)
picam2.set_controls({"ExposureTime": 90000,
                     "AwbEnable": True, "Brightness": 0.0,
                     "Contrast": 1.0,})
                    # "AfMode": controls.AfModeEnum.Continuous})
#picam2.encoder = encoder
picam2.start_preview(Preview.QT)
picam2.start()

# Initialize variables
w, h = lores_size
prev = None
encoding = False
ltime = 0
sent_items = 0
maxium = 5
wt = 1
dif = 20
ex = 90000
#main loop
while True:
    if ldr.value == 0.0:
        ex = 90000
    else:
        ex = 3000
    picam2.set_controls({"ExposureTime": ex,
                     "AwbEnable": True, "Brightness": 0.0,
                     "Contrast": 1.0,})
    #stop if max reached
    if sent_items == maxium:
        GPIO.cleanup()
        break
    cur = picam2.capture_buffer("lores")
    cur = cur[:w*h].reshape(h, w)
    #check thesesomething to comper
    if prev is not None:
        # Measure pixel differences between current and previous frame
        mse = np.square(np.subtract(cur, prev)).mean()
        if mse > dif:
            if not encoding:
                encoding = True
                print(f"New Motion DETECTED VALUE:{mse}")
                GPIO.output(20, GPIO.HIGH)
            ltime = time.time()
        else:
            if encoding and time.time() - ltime > wt:
                encoding = False
                print(f'recording stoped RESET VALUE:{mse}')
                GPIO.output(20, GPIO.LOW)

    prev = cur

#time.sleep(10)
#picam2.capture_file('/home/leddy/%s.jpg' % timestamp)
#picam2.stop_preview()
#picam2.stop()


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

# '''
# This values moved here from *.cfg for ability of changing from elsewhere
# '''

from multiprocessing import Lock

flags = {"lock" : Lock(), # для атомарного доступа к флагам
         "atm_mode" : False, # Режим настройки дрессированной обезьяной
         "debug" : False, # включает отладочный режим
         # "debug" : True, # включает отладочный режим
         "mouse_capture" : False, # включает захват координат курсора в качестве входных данных
         # "mouse_capture" : True, # включает захват координат курсора в качестве входных данных
         "help_flag" : False,# если взведен -- показывать экран помощи
         "logreplay_flag" : False, # если взведен -- вывести на экран значок play
         "connection_interrupted" : False, # связь с мпиовд прервалась
         }