import requests
import json
import random
import time

def get_context():
    context_list = [
        "/imagine prompt genetic, sticker art design, kawaii illustration, white background",
    ]
    text = random.choice(context_list)
    return text

def chat(chanel_list,authorization_list):
    for authorization in authorization_list:
        header = {
            "Authorization": authorization,
            "Content-Type": "application/json",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36",
        }
        for chanel_id in chanel_list:
            msg = {
                "content": get_context(),
                "nonce": "82329451214{}33232234".format(random.randrange(0, 1000)),
                "tts": False,
            }
            url = "https://discord.com/api/v9/channels/{}/messages".format(chanel_id)
            try:
                res = requests.post(url=url, headers=header, data=json.dumps(msg))
                print(res.content)
            except:
                pass
            continue
        time.sleep(random.randrange(1, 3))

if __name__ == "__main__":
    chanel_list = ["989739763957391370"]
    authorization_list = ["MTA1MjU3NTI2NDc4MzIxNjY4MQ.Gl3Z8K.ndJKKWPxhlHk0hxwqmwg69KjZiikIrqZ8Zj5t4"]
    chat(chanel_list,authorization_list)

    '''
    while True:
        try:
            chat(chanel_list,authorization_list)
            sleeptime = random.randrange(5, 10)
            time.sleep(sleeptime)
        except:
            break
    '''


class WordDictionary:

    def __init__(self):
        self.root = TrieNode(None)

    def addWord(self, word: str) -> None:
        node = self.root
        for c in word:
            if c not in node.children:
                node.children[c] = TrieNode(c)
            node = node.children[c]
        node.is_word = True

    def search(self, word: str) -> bool:
        return self.dfs(word, 0, self.root)

    # . 일때는 하나 건너뛰고 grand children을 모두 보면 됨
    def dfs(self, word, index, node):
        if index == len(word):
            return node.is_word

        c = word[index]
        if c == ".":
            for key in node.children:
                if self.dfs(word, index + 1, node.children[key]):
                    return True
            return False
        else:
            if c not in node.children:
                return False
            return self.dfs(word, index + 1, node.children[c])

class TrieNode:
    def __init__(self, val):
        self.val = val
        self.is_word = False
        self.children = {}

# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)


room_map = [ [1, 1, 1, 1, 1],
             [1, 0, 0, 0, 1],
             [1, 0, 1, 0, 1],
             [1, 0, 0, 0, 1],
             [1, 0, 0, 0, 1],
             [1, 0, 0, 0, 1],
             [1, 1, 1, 1, 1]
             ]

WIDTH = 800
HEIGHT = 600

top_left_x = 100
top_left_y = 150

DEMO_OBJECTS = [images.floor, images.pillar]

room_height = 7
room_width = 5

def draw():
    for y in range(room_height):
        for x in range(room_width):
            image_to_draw = DEMO_OBJECTS[room_map[y][x]]
            screen.blit(image_to_draw,
                    (top_left_x + (x*30),#each square of image is 30 pixels. tells where to place the image based off of window size
                    top_left_y + (y*30) - image_to_draw.get_height()))

#for y in range(7):
    #for x in range(5):
        #print(room_map[y][x], end="")#using end="" so all items from one complete run of the x loop show on the same line
    #print()

#istress = ["Mayday!"]
#for y in range(3):
    #print(distress)


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    \file Grid.py

    \brief Object to store a pointcloud in a regular grid.

    \copyright Copyright (c) 2021 Visual Computing group of Ulm University,
                Germany. See the LICENSE file at the top-level directory of
                this distribution.

    \author pedro hermosilla (pedro-1.hermosilla-casajus@uni-ulm.de)
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import os
import sys
import tensorflow as tf

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_MODULE_DIR = os.path.dirname(BASE_DIR)
sys.path.append(os.path.join(ROOT_MODULE_DIR, "tf_ops"))

from IEProtLibModule import compute_keys
from IEProtLibModule import build_grid_ds

class Grid:
    """Class to represent a point cloud distributed in a regular grid.

    Attributes:
        batchSize_ (int): Size of the batch.
        cellSizes_ (float tensor d): Cell size.
        pointCloud_ (PointCloud): Point cloud.
        aabb_ (AABB): AABB.
        numCells_ (int tensor d): Number of cells of the grids.
        curKeys_ (int tensor n): Keys of each point.
        sortedKeys_ (int tensor n): Keys of each point sorted.
        sortedIndices_ (int tensor n): Original indices to the original
            points.
        fastDS_ (int tensor BxCXxCY): Fast access data structure.
    """

    def __init__(self, pPointCloud, pAABB, pCellSizes):
        """Constructor.

        Args:
            pPointCloud (PointCloud): Point cloud to distribute in the grid.
            pAABB (AABB): Bounding boxes.
            pCellSizes (tensor float n): Size of the grid cells in each dimension.
        """
        #Save the attributes.
        self.batchSize_ = pAABB.batchSize_
        self.cellSizes_ = pCellSizes
        self.pointCloud_ = pPointCloud
        self.aabb_ = pAABB

        #Compute the number of cells in the grid.
        aabbSizes = self.aabb_.aabbMax_ - self.aabb_.aabbMin_
        batchNumCells = tf.cast(tf.math.ceil(aabbSizes/self.cellSizes_), tf.int32)
        self.numCells_ = tf.maximum(tf.reduce_max(batchNumCells, axis=0), 1)

        #Compute the key for each point.
        self.curKeys_ = compute_keys(self.pointCloud_, self.aabb_, self.numCells_,
            self.cellSizes_)

        #Sort the keys.
        self.sortedKeys_, self.sortedIndices_ = tf.math.top_k(self.curKeys_,
            tf.shape(self.curKeys_)[0])

        #Compute the invert indexs.
        _, ptIndexs = tf.math.top_k(self.sortedIndices_,
            tf.shape(self.sortedIndices_)[0])
        self.invertedIndices_ = tf.reverse(ptIndexs, [0])

        #Get the sorted points and batch ids.
        self.sortedPts_ = tf.gather(self.pointCloud_.pts_, self.sortedIndices_)
        self.sortedBatchIds_ = tf.gather(self.pointCloud_.batchIds_, self.sortedIndices_)

        #Build the fast access data structure.
        self.fastDS_ = build_grid_ds(self.sortedKeys_, self.numCells_, self.batchSize_)


import yaml
import numpy as np
import os
import sys
import itertools
from pprint import pprint
import copy
import importlib

from typing import Union, Any, List, Callable, Dict, Iterable

def load_yaml_config(
    filename: str,
    path: str,
    walk: bool = False,
    verbose: bool = True,
    post_process: Callable = None,
    post_process_kwargs: Dict = {},
    unpack: bool = False,
    **kwargs
) -> Union[str, Union[Dict, Any]]:
    """Load a yaml configuration file with some additional functionality
    For example do::
        $  data = load_yaml_config(filename=path_to_dir, path=path_to_yaml, walk=True/False,
        $  post_process=dataset_from_config, **kwargs)

    This loader adds additional constructors which can be used in your yaml file.
    These include the joining of strings witj !join:
    ::
        For example;     !join [str1, str2] -> 'str1tr2'

    Or the joining with underscores with !usjoin:
    ::
        !usjoin[str1, str2] -> 'str1_str2'

    Or the joining of paths with !pathjoin:
    ::
        !pathjoin[str1, str2] -> 'str1/str2'

    Similarly one can inject string or int into the configuration from an external source using !kwargs:
    ::
        In python:
        load_yaml_config(..., **{'item1': {'item12': 2)
        In yaml file
        !kwargs [item1,item12]

    Finally, one can initialise classes using the !class constructor:
    ::
        !class [path.to.module]

    Parameters
    ----------
    filename : str
        filename of the .yaml file
    path : str
        path to a folder containg the .yaml file.
        If walk==True, one can place .yaml in a nested folder
    walk : bool
        Walk through the nested folder
    verbose : bool
        Allow print statements
    post_process : Callable
        Place here a factory function that accepts the yaml input configuration.
        Identical as post_process(load_yaml_config).
    post_process_kwargs : Dict
        Any kwargs you want to provide to the postp_process Callable
    unpack : bool
        Whether or not to unpack to yaml configuration dict before applying it to post_process()
    kwargs : dict
        kwargs will be used by the !kwargs constructor to inject parameters from your code flow
        into the configuration.

    Returns
    -------
    Any
    """

    # search directory
    if walk:
        for root, subFolders, files in os.walk(path):
            if (filename + ".yaml") in files:
                path = os.path.join(root)
                break
    filepath = os.path.join(path, filename + ".yaml")

    # join strings
    def join(loader, node):
        seq = loader.construct_sequence(node)
        return "".join([str(i) for i in seq])

    # join with underscore
    def usjoin(loader, node):
        seq = loader.construct_sequence(node)
        return "_".join([str(i) for i in seq])

    # join path
    def pathjoin(loader, node):
        seq = loader.construct_sequence(node)
        return os.path.join(*[str(i) for i in seq])

    # replace by kwarg value
    def get_kwarg(loader, node):
        seq = loader.construct_sequence(node)
        kwarg = copy.deepcopy(kwargs)
        output_str = str()
        for k, key in enumerate(seq):  # nested dictionary
            output_str = ".".join((output_str, key))
            if key in kwarg:
                kwarg = kwarg[key]
                if (k + 1) == len(seq):
                    output_str = kwarg
        return output_str

    # replace by class
    def get_class(loader, node):
        seq = loader.construct_sequence(node)
        assert len(seq) == 1
        loc_rdot = seq[0].rfind(".")
        module = safe_import_module(seq[0][:loc_rdot])
        return getattr(module, seq[0][loc_rdot + 1 :])

    # add custom custructors
    yaml.add_constructor("!join", join)  # join strings
    yaml.add_constructor("!usjoin", usjoin)  # join strings with underscores
    yaml.add_constructor("!pathjoin", pathjoin)  # join paths
    yaml.add_constructor("!kwarg", get_kwarg)  # join paths
    yaml.add_constructor("!class", get_class)  # join paths

    # load yaml
    with open(filepath, "r") as ymlfile:
        cfg = yaml.load(ymlfile, Loader=yaml.Loader)

    # verbose
    if verbose:
        pprint(cfg)

    # custom post process if needed
    if post_process is not None:
        if unpack:
            cfg = post_process(**cfg, **post_process_kwargs)
        else:
            cfg = post_process(cfg, **post_process_kwargs)

    return cfg

def reformat_yaml(
    cfg: Union[List[Any], Dict[str, Any]]
) -> List[Union[np.ndarray, Any]]:
    """Reformat yaml list to numpy if possible

    Parameters
    ----------
        cfg : List[Any]
            loaded yaml configuration

    Returns
    ----------
        Reformatted yaml
    """
    if isinstance(cfg, list):
        tmp_cfg = cfg
        if any(isinstance(i, list) for i in tmp_cfg):  # nested
            tmp_cfg = [val for i in tmp_cfg for val in i]
        if np.all([(isinstance(i, int) | isinstance(i, float)) for i in tmp_cfg]):
            cfg = np.array(cfg)
    return cfg

def reformat_yaml_iter(
    cfg: Union[List[Any], Dict[str, Any]]
) -> List[Union[np.ndarray, Any]]:
    """Reformat yaml list to numpy if possible in an iterative fasion

    Parameters
    ----------
        cfg : Union[List[Any], Dict[str,Any]]
            loaded yaml configuration

    Returns
    ----------
        Reformatted yaml
    """
    """Reformat yaml list to numpy if possible in iterative fashion"""
    for k, v in cfg.items():
        if isinstance(v, dict):
            reformat_yaml_iter(v)
        else:
            cfg[k] = reformat_yaml(v)
    return cfg

def load_yaml(filepath: str) -> Dict:
    """Load yaml file

    Parameters
    ----------
        filepath : str
            filepath to yaml file

    Returns
    ----------
        Dictionary
    """
    # load file
    with open(filepath, "r") as ymlfile:
        cfg = yaml.load(ymlfile, Loader=yaml.Loader)

    return cfg

def str_in_list(lst: List, string: str) -> List[int]:
    """Get indices of a string in a list

    Parameters
    ----------
    lst : list
        list of strings
    string : str
        string to search for

    Returns
    -------
    List[int]
    """
    if isinstance(string, (list, np.ndarray)):
        return [str_in_list(lst, _string) for _string in string]
    indices = [i for i in range(len(lst)) if lst[i] == string]
    return indices

def listnp_combine(
    lst: List, method: str = "concatenate", axis: int = 0, allow_error: bool = False
) -> np.ndarray:
    """Concatenate or stack a list of numpy along with error handling

    Parameters
    ----------
    lst : list
        list of np arrays
    method : str
        'concatenate' or 'stack'
    axis : int
        axis to concat or stack over
    allow_error : bool
        allow for error handling. If op does not succes, list is provided

    Returns
    -------
    np.array OR list of np.array in case of error
    """

    def combine(lst):
        if isinstance(lst, list):
            lst = np.array(lst)
        if method == "concatenate":
            npstack = np.concatenate(lst, axis=axis)
        elif method == "stack":
            npstack = np.stack(lst, axis=axis)
        else:
            print("method for concatenating not supported in listnp_stack in utils.py.")
            sys.exit()
        return npstack

    if len(np.shape(lst[0])) == 0:
        return np.array(lst)
    else:
        if allow_error:
            try:
                npcombine = combine(lst)
            except ValueError:  # if cant combine
                npcombine = copy.deepcopy(lst)
        else:
            npcombine = combine(lst)
    return npcombine

def listdictnp_combine(
    lst: List,
    method: str = "concatenate",
    axis: int = 0,
    keep_nested: bool = False,
    allow_error: bool = False,
) -> Dict[str, Union[np.ndarray, List]]:
    """Concatenate or stack a list of dictionaries contains numpys along with error handling

    Parameters
    ----------
    lst : list
        list of dicts containings np arrays
    method : str
        'concatenate' or 'stack'
    axis : int
        axis to concat or stack over
    keep_nested : bool
        keep nested structure of list or not
    allow_error : bool
        allow for error handling. If op does not succes, list is provided

    Returns
    -------
    np.array OR list of np.array in case of error
    """
    for k in range(len(lst)):
        assert (
            lst[0].keys() == lst[k].keys()
        ), "Dict keys do not match in listdictnp_combine fct"
    # get keys
    keys = lst[0].keys()
    output_dict = dict()

    for key in keys:
        # merge nested list
        if keep_nested:
            tmp = [None] * len(lst)
            for k in range(len(lst)):
                tmp[k] = lst[k][key]
        else:
            tmp = list()
            for k in range(len(lst)):
                tmp = [*tmp, *lst[k][key]]

        # convert to numpy if possible
        output_dict[key] = listnp_combine(
            tmp, method=method, axis=axis, allow_error=allow_error
        )
    return output_dict

def unique_list(seq: List) -> List:
    """Get unique entries in a list

    Parameters
    ----------
        seq: list
            sequence you want to unique-fy

    Returns
    -------
        list of unique values
    """
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

def flatten_nested_lst(nested_lst: List[List]) -> List:
    """Flatten a nested list

    Parameters
    ----------
        nested_lst : list
            A nested list

    Returns
    -------
        flattened list
    """
    return [item for sublist in nested_lst for item in sublist]

def any2str(obj: Any) -> str:
    """Convert anything to a string

    Parameters
    ----------
        obj : Any
            anything to convert to a str rep

    Returns
    -------
        string
    """
    if isinstance(obj, str):
        return obj
    elif (
        isinstance(obj, int)
        | isinstance(obj, np.ndarray)
        | isinstance(obj, np.int64)
        | isinstance(obj, dict)
        | isinstance(obj, bool)
        | isinstance(obj, list)
    ):
        return str(obj)
    elif obj is None:
        return "None"
    else:
        print("Instance not supported in any2str()")
        sys.exit()

def filter_data(
    data: Iterable, sel_vect: Union[List[int], np.ndarray], squeeze: bool = False
) -> Iterable:
    """Filter any sequential data object based on indices

    Parameters
    ----------
    data : Iterable
        Iterable object to be filtered
    sel_vect : List[int] or np.ndarray
        indices to filter
    squeeze : bool
        squeeze output when numpy

    Returns
    -------
        Filtered iterable
    """
    # inits
    from dabstract.abstract import abstract

    if isinstance(sel_vect, (np.int64, int)):
        sel_vect = np.array([sel_vect])
    # do different filtering depending on input
    if isinstance(data, list):
        out = [data[k2] for k2 in sel_vect]
        if squeeze:
            out = out[0]
    elif isinstance(data, np.ndarray):
        out = data[
            sel_vect,
        ]
        if squeeze:
            out = out.squeeze()
    elif isinstance(data, tuple):
        tmp = list(data)
        out = [tmp[k2] for k2 in sel_vect]
        if squeeze:
            out = out[0]
    elif isinstance(data, dict):
        out = dict()
        for key in data:
            out[key] = filter_data(data[key], sel_vect, squeeze=squeeze)
    elif isinstance(data, abstract):
        out = data
    elif hasattr(data, "__getitem__"):
        out = data[sel_vect]
    elif data is None:
        out = None
    else:
        print("Not supported data format in filter_data fct")
        sys.exit()
    return out

def safe_import_module(module_string: str) -> object:
    """Import module with error handling

    Parameters
    ----------
        module_string : str
            module string to import

    Returns
    ----------
        imported module
    """
    try:
        return importlib.import_module(module_string)
    except ImportError:
        return object()

def combs_numpy(values: Union[List, np.ndarray]) -> np.ndarray:
    """All possible combinations of numpy entries

    Parameters
    ----------
    values : Union[List, np.ndarray]
        All unique examples to get combinations from

    Returns
    -------
    np.ndarray
    """
    return np.unique(
        np.array(
            list(itertools.product(*[values[:, k] for k in range(values.shape[1])]))
        ),
        axis=0,
    )

def combs_list(values: Union[List, np.ndarray]) -> List:
    """All possible combinations of list entries

    Parameters
    ----------
    values : Union[List, np.ndarray]
        All unique examples to get combinations from

    Returns
    -------
    List
    """
    return list(itertools.product(*values))

# def combs_size_numpy(values: Union[List, np.ndarray], size: int) -> np.ndarray:
#     """Size of all possible combinations of numpy entries
#
#     Parameters
#     ----------
#     values : Union[List, np.ndarray]
#         Any object you want the length from
#
#     Returns
#     -------
#     int
#     """
#
#     return np.array([comb for comb in itertools.combinations(values, size)])

def pprint_ext(str: str, dict: Dict, np_precision: int = 2) -> None:
    """pprint with np precision specification and title

    Parameters
    ----------
    str : str
        title to print
    dict : Dict
        Dictionary to print
    np_precision : int
        precision of numpy print
    """
    np.set_printoptions(precision=np_precision, suppress=True)
    print(str)
    pprint(dict)

def safe_len(var: Any) -> int:
    """safely get length

    Parameters
    ----------
    var : Any
        Any object you want the length from

    Returns
    -------
    int
    """
    try:
        return len(var)
    except TypeError:
        return 1

def stringlist2ind(strlist: List[str]) -> np.ndarray:
    """list to unique indices

    Parameters
    ----------
    strlist : List[str]
        List of strings to indices

    Returns
    -------
    List[int]
    """
    subdb_ext = unique_list(strlist)
    group_np = np.zeros((len(strlist)))
    for k in range(len(strlist)):
        group_np[k] = subdb_ext.index(strlist[k])
    return group_np.astype(np.int)

def list_intersection(lst1: List, lst2: List) -> List:
    """Intersect the values of two lists

    Parameters
    ----------
    lst1 : List
        First list
    lst2 : List
        Second list

    Returns
    -------
    Intersected list
    """
    return [value for k, value in enumerate(lst1) if value in lst2]

def list_difference(lst1: List, lst2: List) -> List:
    """Get difference between the values of two lists

    Parameters
    ----------
    lst1 : List
        First list
    lst2 : List
        Second list

    Returns
    -------
    Difference list
    """
    return [value for k, value in enumerate(lst1) if not value in lst2] + [
        value for k, value in enumerate(lst2) if not value in lst1
    ]

def get_class(name: str, module_location: str, *args, **kwargs):
    """Load a class given the name, module location and it's args and kwargs

    Parameters
    ----------
    name : str
        class name
    module_location : str
        class location

    Returns
    -------
    Instance
    """
    module = safe_import_module(module_location)
    assert hasattr(module, name), name + " is not a part of module " + module_location
    return getattr(module, name)(*args, **kwargs)

def get_fct(name: str, module_location: str):
    """Load a fct given the name, module location and it's args and kwargs

    Parameters
    ----------
    name : str
        function name
    module_location : str
        function location

    Returns
    -------
    Callable
    """
    module = safe_import_module(module_location)
    assert hasattr(module, name), name + " is not a part of module " + module_location
    return getattr(module, name)


import torch
import torch.nn as nn
import torch.nn.functional as F

from config import Config

class BaseNN(nn.Module):
    """Superclass for the Actor and Critic classes"""
    def __init__(self):
        super(BaseNN, self).__init__()
        self.config = Config()
        self.to(self.config.device)
        torch.manual_seed(self.config.seed)
        self.module_list = nn.ModuleList()

    def create_fc_layer(self, nodes_in, nodes_out):
        layer = nn.Linear(nodes_in, nodes_out)
        self.reset_parameters(layer)
        self.module_list.append(layer)

    def reset_parameters(self, layer):
        layer.weight.data.uniform_(-3e-3, 3e-3)

class Actor(BaseNN):
    """Build an actor (policy) network that maps states -> actions."""
    def __init__(self):
        super(Actor, self).__init__()
        for nodes_in, nodes_out in self.layers_nodes():
            self.create_fc_layer(nodes_in, nodes_out)

    def layers_nodes(self):
        nodes = []
        nodes.append(self.config.state_size)
        nodes.extend(self.config.actor_layers)
        nodes.append(self.config.action_size)
        nodes_in = nodes[:-1]
        nodes_out = nodes[1:]
        return zip(nodes_in, nodes_out)

    def forward(self, x):
        for layer in self.module_list[:-1]:
            x = F.relu(layer(x))
        x = self.module_list[-1](x)
        return torch.tanh(x)

class Critic(BaseNN):
    """Build a critic (value) network that maps
       (state, action) pair -> Q-values.
    """
    def __init__(self):
        super(Critic, self).__init__()
        for nodes_in, nodes_out in self.layers_nodes():
            self.create_fc_layer(nodes_in, nodes_out)
        if self.config.batch_normalization:
            self.bn = nn.BatchNorm1d(self.module_list[1].in_features)

    def layers_nodes(self):
        nodes = []
        nodes.append(self.config.state_size * self.config.num_agents)
        nodes.extend(self.config.critic_layers)
        nodes.append(1)
        nodes_in = nodes[:-1]
        nodes_in[1] += self.config.num_agents * self.config.action_size
        nodes_out = nodes[1:]
        return zip(nodes_in, nodes_out)

    def forward(self, state, action):
        x = F.relu(self.module_list[0](state))
        x = torch.cat((x, action), dim=1)
        if self.config.batch_normalization:
            x = self.bn(x)
        for layer in self.module_list[1:-1]:
            x = F.relu(layer(x))
        x = self.module_list[-1](x)
        return torch.sigmoid(x)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : output_data_es_to_column.py
# @Author: Cedar
# @Date  : 2020/4/21
# @Desc  :

from datetime import datetime
from elasticsearch import Elasticsearch
import hashlib

es = Elasticsearch(hosts="http://192.168.2.56:9200/")

body = {
    "query": {
        "match_all": {}
    }
}
query = es.search(index="qiluyidianhao", doc_type="qiluyidianhao",
                  body=body, size=100, scroll='5m')

results = query['hits']['hits']  # es查询出的结果第一页
total = query['hits']['total']  # es查询出的结果总量
scroll_id = query['_scroll_id']  # 游标用于输出es查询出的所有结果

for item in results:
    title = item['_source']['title']
    if len(item['_source']['title']) < 1:
        title = 'None'
    print(title + '=' + item['_source']['listpage_url'])

for i in range(0, int(total/100)+1):
    # scroll参数必须指定否则会报错
    query_scroll = es.scroll(scroll_id=scroll_id, scroll='5m')['hits']['hits']
    for item in query_scroll:
        title = item['_source']['title']
        if len(item['_source']['title']) < 1:
            title = 'None'
        print(title + '=' + item['_source']['listpage_url'])


from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import time
values = [2,3,4,5,11,23,12,11,11]
def square(n):
   time.sleep(1)
   return n * n
def main():
   threads=[]
   executor =  ProcessPoolExecutor(max_workers=3)
   for val in values:
      th = executor.submit(square, val)
      threads.append(th)
   for th in threads:
      print(th.result())

# def main():
#    #with ThreadPoolExecutor(max_workers = 3) as executor:
#    with ProcessPoolExecutor(max_workers=3) as executor:
#       results = executor.map(square, values)
#    for result in results:
#       print(result)
if __name__ == '__main__':
   main()


"""added RecipePost

Revision ID: ddb9bdfbd0c1
Revises: 9a0f7f572088
Create Date: 2023-11-02 10:59:12.620005

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'ddb9bdfbd0c1'
down_revision = '9a0f7f572088'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('posts',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('post_message', sa.String(), nullable=True),
    sa.Column('recipe_id', sa.Integer(), nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['recipe_id'], ['recipes.id'], name=op.f('fk_posts_recipe_id_recipes')),
    sa.ForeignKeyConstraint(['user_id'], ['users.id'], name=op.f('fk_posts_user_id_users')),
    sa.PrimaryKeyConstraint('id', name=op.f('pk_posts'))
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('posts')
    # ### end Alembic commands ###


import torch
import torch.cuda
from torch.utils.data import DataLoader
import os
import glob
import numpy as np

def masked_loss(y_pred, y, tau = 0.5):
    dy = torch.abs(y_pred.view(y.size()) - y)
    dy = torch.where(y >= 0.0, dy, torch.zeros(dy.size()))
    dy = torch.where(y_pred > y, (1 - tau) * dy, tau * dy)
    return dy.mean()

def quantile_loss(y_pred, y, quantiles):
    l = torch.tensor(0.0)
    for i, q in enumerate(quantiles):
        l += masked_loss(y_pred[:, i, :, :], y, q)
    return l

def load_most_recent(model, output_path):
    model_files = glob.glob(os.path.join(output_path, "model_*.pt"))
    if len(model_files) == 0:
        print("No model found in {}.".format(output_path))
        return None
    indices = np.array([int(os.path.basename(m).split("_")[1].split(".")[0]) for m in model_files])
    print(indices)
    i = np.argmax(indices)

    print("Loading most recent model {}.".format(model_files[i]))
    cuda = torch.cuda.is_available()
    if cuda:
        model.load_state_dict(torch.load(model_files[i]))
    else:
        model.load_state_dict(torch.load(model_files[i], map_location = "cpu"))

    model.eval()

def train_network(data_set,
                  model,
                  optimizer,
                  criterion,
                  output_path,
                  n_epochs ,
                  dataset_callback = None):

    if not os.path.exists(output_path):
        os.makedirs(output_path)

    cuda = torch.cuda.is_available()
    if cuda:
        print("Running on GPU.")
        model.cuda()
        torch.set_default_tensor_type('torch.cuda.FloatTensor')
    else:
        print("Running on CPU.")

    log_file = os.path.join(output_path, "training_log.txt")
    if os.path.isfile(log_file):
        log_file = open(log_file, mode = "r+", buffering = 1)
    else:
        log_file = open(log_file, mode = "w", buffering = 1)

    for i in range(n_epochs):

        dataset_callback(data_set)
        data_loader = DataLoader(data_set, batch_size = 128, shuffle = True)

        epoch_loss = 0.0

        for j, (x, y) in enumerate(data_loader):

            if cuda:
                x = x.cuda()
                y = y.cuda()

            y_pred = model(x)
            optimizer.zero_grad()
            loss = criterion(y_pred, y)
            loss.backward()
            optimizer.step()

            epoch_loss += loss.float()

            print("Epoch {0}, batch {1}: {2}".format(i, j, loss.float()))

        log_file.write("{0}\n".format(epoch_loss))
        model_files = glob.glob(os.path.join(output_path, "model_*.pt"))
        i_m = len(model_files)
        filename = os.path.join(output_path, "model_{0}.pt".format(i_m))
        torch.save(model.state_dict(), filename)


# -*- encoding: utf-8 -*-
import itertools
import sys
from supriya.tools.systemtools.SupriyaObject import SupriyaObject

class ResponseManager(SupriyaObject):
    """
    Handles OSC responses from scsynth.

    ::

        >>> from supriya import osctools
        >>> from supriya import responsetools
        >>> manager = responsetools.ResponseManager

    ::

        >>> message = osctools.OscMessage(
        ...     '/status.reply', 1, 0, 0, 2, 4,
        ...     0.040679048746824265, 0.15118031203746796,
        ...     44100.0, 44100.00077873274,
        ...     )
        >>> manager.handle_message(message)
        StatusResponse(
            actual_sample_rate=44100.00077873274,
            average_cpu_usage=0.040679048746824,
            group_count=2,
            peak_cpu_usage=0.151180312037468,
            synth_count=0,
            synthdef_count=4,
            target_sample_rate=44100.0,
            ugen_count=0
            )

    ::

        >>> message = osctools.OscMessage('/b_info', 1100, 512, 1, 44100.0)
        >>> manager.handle_message(message)[0]
        BufferInfoResponse(
            buffer_id=1100,
            frame_count=512,
            channel_count=1,
            sample_rate=44100.0
            )

    ::

        >>> message = osctools.OscMessage('/n_set', 1023, '/one', -1, '/two', 0)
        >>> manager.handle_message(message)
        NodeSetResponse(
            node_id=1023,
            items=(
                NodeSetItem(
                    control_index_or_name='/one',
                    control_value=-1
                    ),
                NodeSetItem(
                    control_index_or_name='/two',
                    control_value=0
                    ),
                )
            )

    ::

        >>> message = osctools.OscMessage('/b_setn', 1, 0, 8, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
        >>> manager.handle_message(message)
        BufferSetContiguousResponse(
            items=(
                BufferSetContiguousItem(
                    starting_sample_index=0,
                    sample_values=(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
                    ),
                ),
            buffer_id=1
            )

    ::

        >>> message = osctools.OscMessage('/g_queryTree.reply', 0, 0, 1, 1, 2, 1001, 0, 1000, 1, 1002, 0)
        >>> manager.handle_message(message)
        QueryTreeResponse(
            node_id=0,
            query_tree_group=QueryTreeGroup(
                node_id=0,
                children=(
                    QueryTreeGroup(
                        node_id=1,
                        children=(
                            QueryTreeGroup(
                                node_id=1001,
                                children=()
                                ),
                            QueryTreeGroup(
                                node_id=1000,
                                children=(
                                    QueryTreeGroup(
                                        node_id=1002,
                                        children=()
                                        ),
                                    )
                                ),
                            )
                        ),
                    )
                )
            )

    ::

        >>> print(manager.handle_message(message))
        NODE TREE 0 group
            1 group
                1001 group
                1000 group
                    1002 group

    """

    ### PUBLIC METHODS ###

    @staticmethod
    def group_items(items, length):
        iterators = [iter(items)] * length
        if sys.version_info[0] == 2:
            iterator = itertools.izip(*iterators)
        else:
            iterator = zip(*iterators)
        return iterator

    @staticmethod
    def handle_message(message):
        address, contents = message.address, message.contents
        if address in _response_handlers:
            handler = _response_handlers[address]
            response = handler(address, contents)
            return response
        #print('UNHANDLED:', message)

    @staticmethod
    def handle_b_info(command, contents):
        from supriya.tools import responsetools
        responses = []
        for group in ResponseManager.group_items(contents, 4):
            response = responsetools.BufferInfoResponse(*group)
            responses.append(response)
        responses = tuple(responses)
        return responses

    @staticmethod
    def handle_b_set(command, contents):
        from supriya.tools import responsetools
        buffer_id, remainder = contents[0], contents[1:]
        items = []
        for group in ResponseManager.group_items(remainder, 2):
            item = responsetools.BufferSetItem(*group)
            items.append(item)
        items = tuple(items)
        response = responsetools.BufferSetResponse(
            buffer_id=buffer_id,
            items=items,
            )
        return response

    @staticmethod
    def handle_b_setn(command, contents):
        from supriya.tools import responsetools
        buffer_id, remainder = contents[0], contents[1:]
        items = []
        while remainder:
            starting_sample_index = remainder[0]
            sample_count = remainder[1]
            sample_values = tuple(remainder[2:2 + sample_count])
            item = responsetools.BufferSetContiguousItem(
                starting_sample_index=starting_sample_index,
                sample_values=sample_values,
                )
            items.append(item)
            remainder = remainder[2 + sample_count:]
        items = tuple(items)
        response = responsetools.BufferSetContiguousResponse(
            buffer_id=buffer_id,
            items=items,
            )
        return response

    @staticmethod
    def handle_c_set(command, contents):
        from supriya.tools import responsetools
        items = []
        for group in ResponseManager.group_items(contents, 2):
            item = responsetools.ControlBusSetItem(*group)
            items.append(item)
        response = responsetools.ControlBusSetResponse(
            items=tuple(items),
            )
        return response

    @staticmethod
    def handle_c_setn(command, contents):
        from supriya.tools import responsetools
        items = []
        while contents:
            starting_bus_id = contents[0]
            bus_count = contents[1]
            bus_values = tuple(contents[2:2 + bus_count])
            item = responsetools.ControlBusSetContiguousItem(
                starting_bus_id=starting_bus_id,
                bus_values=bus_values,
                )
            items.append(item)
            contents = contents[2 + bus_count:]
        items = tuple(items)
        response = responsetools.ControlBusSetContiguousResponse(
            items=items,
            )
        return response

    @staticmethod
    def handle_d_removed(command, contents):
        from supriya.tools import responsetools
        synthdef_name = contents[0]
        response = responsetools.SynthDefRemovedResponse(
            synthdef_name=synthdef_name,
            )
        return response

    @staticmethod
    def handle_done(command, contents):
        from supriya.tools import responsetools
        arguments = contents
        response = responsetools.DoneResponse(action=tuple(arguments))
        return response

    @staticmethod
    def handle_fail(command, contents):
        from supriya.tools import responsetools
        failed_command = contents[0]
        failure_reason = contents[1:]
        if failure_reason:
            failure_reason = tuple(failure_reason)
        response = responsetools.FailResponse(
            failed_command=failed_command,
            failure_reason=failure_reason,
            )
        return response

    @staticmethod
    def handle_g_query_tree_reply(command, contents):
        def recurse(contents, control_flag):
            node_id = contents.pop(0)
            child_count = contents.pop(0)
            if child_count == -1:
                controls = []
                synthdef_name = contents.pop(0)
                if control_flag:
                    control_count = contents.pop(0)
                    for i in range(control_count):
                        control_name_or_index = contents.pop(0)
                        control_value = contents.pop(0)
                        control = responsetools.QueryTreeControl(
                            control_name_or_index=control_name_or_index,
                            control_value=control_value,
                            )
                        controls.append(control)
                controls = tuple(controls)
                result = responsetools.QueryTreeSynth(
                    node_id=node_id,
                    synthdef_name=synthdef_name,
                    controls=controls,
                    )
            else:
                children = []
                for i in range(child_count):
                    children.append(recurse(contents, control_flag))
                children = tuple(children)
                result = responsetools.QueryTreeGroup(
                    node_id=node_id,
                    children=children,
                    )
            return result
        from supriya.tools import responsetools
        contents = list(contents)
        control_flag = bool(contents.pop(0))
        query_tree_group = recurse(contents, control_flag)
        response = responsetools.QueryTreeResponse(
            node_id=query_tree_group.node_id,
            query_tree_group=query_tree_group,
            )
        return response

    @staticmethod
    def handle_n_info(command, contents):
        from supriya.tools import responsetools
        arguments = (command,) + contents
        response = responsetools.NodeInfoResponse(*arguments)
        return response

    @staticmethod
    def handle_n_set(command, contents):
        from supriya.tools import responsetools
        node_id, remainder = contents[0], contents[1:]
        items = []
        for group in ResponseManager.group_items(remainder, 2):
            item = responsetools.NodeSetItem(*group)
            items.append(item)
        response = responsetools.NodeSetResponse(
            node_id=node_id,
            items=tuple(items),
            )
        return response

    @staticmethod
    def handle_n_setn(command, contents):
        from supriya.tools import responsetools
        node_id, remainder = contents[0], contents[1:]
        items = []
        while remainder:
            control_index_or_name = remainder[0]
            control_count = remainder[1]
            control_values = tuple(remainder[2:2 + control_count])
            item = responsetools.NodeSetContiguousItem(
                control_index_or_name=control_index_or_name,
                control_values=control_values,
                )
            items.append(item)
            remainder = remainder[2 + control_count:]
        items = tuple(items)
        response = responsetools.NodeSetContiguousResponse(
            node_id=node_id,
            items=items,
            )
        return response

    @staticmethod
    def handle_status_reply(command, contents):
        from supriya.tools import responsetools
        arguments = contents[1:]
        (
            ugen_count,
            synth_count,
            group_count,
            synthdef_count,
            average_cpu_usage,
            peak_cpu_usage,
            target_sample_rate,
            actual_sample_rate,
            ) = arguments
        response = responsetools.StatusResponse(
            actual_sample_rate=actual_sample_rate,
            average_cpu_usage=average_cpu_usage,
            group_count=group_count,
            peak_cpu_usage=peak_cpu_usage,
            synth_count=synth_count,
            synthdef_count=synthdef_count,
            target_sample_rate=target_sample_rate,
            ugen_count=ugen_count,
            )
        return response

    @staticmethod
    def handle_synced(command, contents):
        from supriya.tools import responsetools
        arguments = contents
        response = responsetools.SyncedResponse(*arguments)
        return response

    @staticmethod
    def handle_tr(command, contents):
        from supriya.tools import responsetools
        arguments = contents
        response = responsetools.TriggerResponse(*arguments)
        return response

_response_handlers = {
    '/b_info': ResponseManager.handle_b_info,
    '/b_set': ResponseManager.handle_b_set,
    '/b_setn': ResponseManager.handle_b_setn,
    '/c_set': ResponseManager.handle_c_set,
    '/c_setn': ResponseManager.handle_c_setn,
    '/d_removed': ResponseManager.handle_d_removed,
    '/done': ResponseManager.handle_done,
    '/fail': ResponseManager.handle_fail,
    '/g_queryTree.reply': ResponseManager.handle_g_query_tree_reply,
    '/n_end': ResponseManager.handle_n_info,
    '/n_go': ResponseManager.handle_n_info,
    '/n_info': ResponseManager.handle_n_info,
    '/n_move': ResponseManager.handle_n_info,
    '/n_off': ResponseManager.handle_n_info,
    '/n_on': ResponseManager.handle_n_info,
    '/n_set': ResponseManager.handle_n_set,
    '/n_setn': ResponseManager.handle_n_setn,
    '/status.reply': ResponseManager.handle_status_reply,
    '/synced': ResponseManager.handle_synced,
    '/tr': ResponseManager.handle_tr,
    }


from django.shortcuts import render
from django.http import HttpResponse
from .models import Flight, Airport, FlyAtWill
# from datetime import datetime
from django.db.models import Q
from django.db import connection, transaction
import datetime

# Create your views here.

def FlyAtWillPage(request):
    return render(request, 'FlyAtWill.html')

def RecommendPage(request):
    return render(request, 'recommend.html')

def TransferPage(request):
    return render(request, 'transfer.html')

def SearchFlight(request):
    depart_city = request.POST['From']
    arrival_city = request.POST['To']

    query_search = "SELECT f.flightno, f.airlinecode, dept.iatacode, arr.iatacode, f.depttime, f.arrtime \
                    FROM Flight f JOIN Airport dept ON f.deptiata=dept.iatacode \
                    JOIN Airport arr ON f.arriata=arr.iatacode \
                    WHERE dept.city = %s AND arr.city = %s"

    # depart_buf = Airport.objects.filter(city=depart_city)
    # arrival_buf = Airport.objects.filter(city=arrival_city)
    depart_buf = Airport.objects.raw("SELECT * FROM Airport WHERE city = %s", [depart_city])
    arrival_buf = Airport.objects.raw("SELECT * FROM Airport WHERE city = %s", [arrival_city])

    depart_airport_list = []
    arrival_airport_list = []
    for row in depart_buf:
        depart_airport_list.append(row.iatacode)
    for row in arrival_buf:
        arrival_airport_list.append(row.iatacode)

    # depart_date and return_date are string type.
    depart_date = request.POST['Depart']
    return_date = request.POST['Return']

    depart_day_tmp = datetime.datetime.strptime(depart_date, '%Y-%m-%d')
    depart_day = depart_day_tmp.weekday() + 1

    cursor = connection.cursor()
    if return_date:
        return_day_tmp = datetime.datetime.strptime(return_date, '%Y-%m-%d')
        return_day = return_day_tmp.weekday() + 1
        return_result = Flight.objects.none()
        if return_day == 1:
            cursor.execute(query_search + " AND f.monday = 1", [arrival_city, depart_city])
            return_result = cursor.fetchall()
        elif return_day == 2:
            cursor.execute(query_search + " AND f.tuesday = 1", [arrival_city, depart_city])
            return_result = cursor.fetchall()
        elif return_day == 3:
            cursor.execute(query_search + " AND f.wednesday = 1", [arrival_city, depart_city])
            return_result = cursor.fetchall()
        elif return_day == 4:
            cursor.execute(query_search + " AND f.thursday = 1", [arrival_city, depart_city])
            return_result = cursor.fetchall()
        elif return_day == 5:
            cursor.execute(query_search + " AND f.friday = 1", [arrival_city, depart_city])
            return_result = cursor.fetchall()
        elif return_day == 6:
            cursor.execute(query_search + " AND f.saturday = 1", [arrival_city, depart_city])
            return_result = cursor.fetchall()
        elif return_day == 7:
            cursor.execute(query_search + " AND f.sunday = 1", [arrival_city, depart_city])
            return_result = cursor.fetchall()

    # if return_date:
    #     return_day_tmp = datetime.strptime(return_date, '%Y-%m-%d')
    #     return_day = return_day_tmp.weekday() + 1
    #
    #     return_result = Flight.objects.none()
    #     for arrival_airport in arrival_airport_list:
    #         for depart_airport in depart_airport_list:
    #             if return_day == 1:
    #                 return_result = return_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                     WHERE deptiata = %s AND arriata = %s AND monday=1", \
    #                                                     [arrival_airport, depart_airport]))
    #             elif return_day == 2:
    #                 return_result = return_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                     WHERE deptiata = %s AND arriata = %s AND tuesday=1", \
    #                                                    [arrival_airport, depart_airport]))
    #             elif return_day == 3:
    #                 return_result = return_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                     WHERE deptiata = %s AND arriata = %s AND wednesday=1", \
    #                                                    [arrival_airport, depart_airport]))
    #             elif return_day == 4:
    #                 return_result = return_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                     WHERE deptiata = %s AND arriata = %s AND thursday=1", \
    #                                                    [arrival_airport, depart_airport]))
    #             elif return_day == 5:
    #                 return_result = return_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                     WHERE deptiata = %s AND arriata = %s AND friday=1", \
    #                                                    [arrival_airport, depart_airport]))
    #             elif return_day == 6:
    #                 return_result = return_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                     WHERE deptiata = %s AND arriata = %s AND saturday=1", \
    #                                                    [arrival_airport, depart_airport]))
    #             elif return_day == 7:
    #                 return_result = return_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                     WHERE deptiata = %s AND arriata = %s AND sunday=1", \
    #                                                    [arrival_airport, depart_airport]))

    one_way_result = Flight.objects.none()
    if depart_day == 1:
        cursor.execute(query_search + " AND f.monday=1", [depart_city, arrival_city])
        one_way_result = cursor.fetchall()
    elif depart_day == 2:
        cursor.execute(query_search + " AND f.tuesday=1", [depart_city, arrival_city])
        one_way_result = cursor.fetchall()
    elif depart_day == 3:
        cursor.execute(query_search + " AND f.wednesday=1", [depart_city, arrival_city])
        one_way_result = cursor.fetchall()
    elif depart_day == 4:
        cursor.execute(query_search + " AND f.thursday=1", [depart_city, arrival_city])
        one_way_result = cursor.fetchall()
    elif depart_day == 5:
        cursor.execute(query_search + " AND f.friday=1", [depart_city, arrival_city])
        one_way_result = cursor.fetchall()
    elif depart_day == 6:
        cursor.execute(query_search + " AND f.saturday=1", [depart_city, arrival_city])
        one_way_result = cursor.fetchall()
    elif depart_day == 7:
        cursor.execute(query_search + " AND f.sunday=1", [depart_city, arrival_city])
        one_way_result = cursor.fetchall()

    # for arrival_airport in arrival_airport_list:
    #     for depart_airport in depart_airport_list:
    #         if depart_day == 1:
    #             # tmp = Flight.objects.filter(Q(deptiata=depart_airport) & Q(arriata=arrival_airport) & Q(monday=1))
    #             # one_way_result = one_way_result | tmp
    #             # cursor.execute("SELECT flightno, airlinecode, deptiata, arriata, depttime, arrtime \
    #             #                 FROM Flight \
    #             #                 WHERE deptiata = depart_airport AND arriata = arrival_airport AND monday=1")
    #             # one_way_result = cursor.fetchall()
    #             one_way_result = Flight.objects.raw("SELECT * FROM Flight \
    #                                                 WHERE deptiata = %s AND arriata = %s AND monday=1", \
    #                                                 [depart_airport, arrival_airport])
    #         elif depart_day == 2:
    #             one_way_result = one_way_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                 WHERE deptiata = %s AND arriata = %s AND tuesday=1", \
    #                                                 [depart_airport, arrival_airport]))
    #         elif depart_day == 3:
    #             one_way_result = one_way_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                 WHERE deptiata = %s AND arriata = %s AND wednesday=1", \
    #                                                 [depart_airport, arrival_airport]))
    #         elif depart_day == 4:
    #             one_way_result = one_way_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                 WHERE deptiata = %s AND arriata = %s AND thursday=1", \
    #                                                 [depart_airport, arrival_airport]))
    #         elif depart_day == 5:
    #             one_way_result = one_way_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                 WHERE deptiata = %s AND arriata = %s AND friday=1", \
    #                                                 [depart_airport, arrival_airport]))
    #         elif depart_day == 6:
    #             one_way_result = one_way_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                 WHERE deptiata = %s AND arriata = %s AND saturday=1", \
    #                                                 [depart_airport, arrival_airport]))
    #         elif depart_day == 7:
    #             one_way_result = one_way_result.union(Flight.objects.raw("SELECT * FROM Flight \
    #                                                 WHERE deptiata = %s AND arriata = %s AND sunday=1", \
    #                                                 [depart_airport, arrival_airport]))

    if return_date:
        return render(request, 'return_result.html', {'one_way_result': one_way_result, 'return_result': return_result})
    else:
        return render(request, 'one_way_result.html', {'one_way_result': one_way_result})

    # feature_list = SentenceProcess(request.POST['To'])

def SentenceProcess(sentence):
    low_weight = 0.1
    high_weight = 10
    background_vocalbulary = ["I", "want", "to", "go", "a", "the", "an", "place", "with", "of", "A", "that", "has", ",",\
                              "and", "city", "food", "China", "is", "located", "at", "lots"]
    word_list = sentence.split()
    sen_dict = {}
    for word in word_list:
        if word in background_vocalbulary:
            sen_dict[word] = low_weight
        else:
            sen_dict[word] = high_weight
    output = []
    for key in sen_dict:
        if sen_dict[key] != low_weight and len(output) < 5:
            output.append(key)
    return output

def RecommendFlight(request):
    depart_city = request.POST['From']
    user_preference = request.POST['Preference']
    feature_list = SentenceProcess(user_preference)
    recommend_results = FlyAtWill.objects.all()
    for feature in feature_list:
        recommend_results = recommend_results.filter(characteristics__icontains=feature)

    arrival_city = {}
    for row in recommend_results:
        if row.cityName != depart_city:
            arrival_city[row.cityName] = row.description

    recommend_flights = []
    to_be_del_keys = []
    for key in arrival_city:
        query_search = "SELECT f.flightno, f.airlinecode, dept.iatacode, arr.iatacode, f.depttime, f.arrtime, f.monday, f.tuesday, f.wednesday, f.thursday, f.friday, f.saturday, f.sunday \
                        FROM Flight f JOIN Airport dept ON f.deptiata=dept.iatacode \
                        JOIN Airport arr ON f.arriata=arr.iatacode \
                        WHERE dept.city = %s AND arr.city = %s"
        cursor = connection.cursor()
        cursor.execute(query_search, [depart_city, key])
        tmp_result = cursor.fetchall()
        if tmp_result:
            recommend_flights.append(tmp_result)
        else:
            to_be_del_keys.append(key)
    for key in to_be_del_keys:
        del arrival_city[key]

    return render(request, 'recommend_result.html', {'arrival_city': arrival_city, 'recommend_flights': recommend_flights})

def Transfer(request):
    depart_city = request.POST['From']
    arrival_city = request.POST['To']
    depart_buf = Airport.objects.raw("SELECT * FROM Airport WHERE city = %s", [depart_city])
    arrival_buf = Airport.objects.raw("SELECT * FROM Airport WHERE city = %s", [arrival_city])

    depart_airport_list = []
    arrival_airport_list = []
    for row in depart_buf:
        depart_airport_list.append(row.iatacode)
    for row in arrival_buf:
        arrival_airport_list.append(row.iatacode)

    # query_transfer = "CALL oneStop('%s','%s')" % (depart_airport_list[0], arrival_airport_list[0])
    cursor = connection.cursor()
    cursor.execute("CALL oneStop(%s, %s)", [depart_airport_list[0], arrival_airport_list[0]])
    sr = cursor.fetchall()
    # sr = Flight.objects.raw(query_transfer)
    return render(request, 'transfer_result.html', {'sr': sr})

def search(request):
    # return HttpResponse('<input type="text" />')
    return render(request, 'search.html')

def search_result(request):
    sr = {}
    print('DeptIATA: ', request.POST.get('dept'))
    dept = request.POST.get('dept')
    print('ArrIATA: ', request.POST.get('arr'))
    arr = request.POST.get('arr')
    print('Date: ', request.POST.get('date'))
    query_sent = "SELECT * FROM Flight"
    if len(dept)>0 and len(arr)>0:
        # sr = Flight.objects.raw("SELECT * FROM Flight WHERE DeptIATA=%s and ArrIATA=%s",[dept, arr])
        query_sent = query_sent + " WHERE DeptIATA='%s' AND ArrIATA='%s'" % (dept,arr)
        sr = Flight.objects.raw(query_sent)
    elif len(dept)>0:
        query_sent = query_sent + " WHERE DeptIATA='%s'" % dept
        sr = Flight.objects.raw(query_sent)
    elif len(arr)>0:
        query_sent = query_sent + " WHERE ArrIATA='%s'" % arr
        sr = Flight.objects.raw(query_sent)
    else:
        return render(request,'search_result.html',{'msg': 'Invalid input! Please check!'})
    if sum(1 for tmp in sr) > 0:
        return render(request,'search_result.html',{'msg': 'Result is listed below', 'sr': sr})
    else:
        return render(request,'search_result.html',{'msg': 'No records found!'})

def manage(request):
    sr = {}
    filter_num = 0

    if request.method == "GET":
        return render(request, 'manage.html')
    flightno = request.POST.get('flightno')
    airlinecode = request.POST.get('airlinecode')
    deptiata = request.POST.get('deptiata')
    arriata = request.POST.get('arriata')
    depttime = request.POST.get('depttime')
    arrtime = request.POST.get('arrtime')
    aircraft = request.POST.get('aircraft')
    distance = request.POST.get('distance')
    otd = request.POST.get('otd')
    avgdelay = request.POST.get('avgdelay')
    monday = request.POST.get('monday')
    tuesday = request.POST.get('tuesday')
    wednesday= request.POST.get('wednesday')
    thursday= request.POST.get('thursday')
    friday = request.POST.get('friday')
    saturday = request.POST.get('saturday')
    sunday= request.POST.get('sunday')
    query_sent = "SELECT * FROM Flight WHERE 1=1"
    if flightno == '*':
        sr = Flight.objects.raw(query_sent)
        return render(request, 'manage.html', {'msg': 'Got the records!', 'sr': sr})
    if flightno!='':
        query_sent = query_sent + " AND FlightNo='%s'" %flightno
        filter_num+=1
    if airlinecode!='':
        query_sent = query_sent + " AND AirlineCode='%s'" %airlinecode
        filter_num += 1
    if deptiata!='':
        query_sent = query_sent + " AND DeptIATA='%s'" %deptiata
        filter_num += 1
    if arriata!='':
        query_sent = query_sent + " AND ArrIATA='%s'" %arriata
        filter_num += 1
    if depttime!='':
        depttime_sql = datetime.datetime.strptime(depttime,'%H:%M')
        query_sent = query_sent + " AND DeptTime='%s'" %depttime_sql
        filter_num += 1
    if arrtime!='':
        arrtime_sql = datetime.datetime.strptime(arrtime,'%H:%M')
        query_sent = query_sent + " AND ArrTime='%s'" %arrtime_sql
        filter_num += 1
    if aircraft!='':
        query_sent = query_sent + " AND Aircraft='%s'" %aircraft
        filter_num += 1
    if distance!='':
        query_sent = query_sent + " AND Distance=%s" %distance
        filter_num += 1
    if otd!='':
        query_sent = query_sent + " AND OTD='%s'" %otd
        filter_num += 1
    if avgdelay!='':
        query_sent = query_sent + " AND AvgDelay=%s" %avgdelay
        filter_num += 1
    if monday!='':
        query_sent = query_sent + " AND Monday=%s" %monday
        filter_num += 1
    if tuesday!='':
        query_sent = query_sent + " AND Tuesday=%s" %tuesday
        filter_num += 1
    if wednesday!='':
        query_sent = query_sent + " AND Wednesday=%s" %wednesday
        filter_num += 1
    if thursday!='':
        query_sent = query_sent + " AND Thursday=%s" %thursday
        filter_num += 1
    if friday!='':
        query_sent = query_sent + " AND Friday=%s" %friday
        filter_num += 1
    if saturday!='':
        query_sent = query_sent + " AND Saturday=%s" %saturday
        filter_num += 1
    if sunday!='':
        query_sent = query_sent + " AND Sunday=%s" %sunday
        filter_num += 1
    sr = Flight.objects.raw(query_sent)
    if sum(1 for tmp in sr)>0 and filter_num!= 0:
        return render(request, 'manage.html', {'msg': 'Got the records!', 'sr': sr})
    else:
        return render(request, 'manage.html', {'msg': 'No records found'})

def delete(request):
    flightno_del = request.GET.get('nid')
    with connection.cursor() as cur:
        cur.execute("DELETE FROM Flight WHERE FlightNo=%s",[flightno_del])
        transaction.commit()
    return render(request, 'manage.html', {'msg': 'Delete succeed!'})

def insert(request):
    if request.method == "GET":
        return render(request, 'insert.html')
    else:
        flightno = request.POST.get('flightno')
        airlinecode = request.POST.get('airlinecode')
        deptiata = request.POST.get('deptiata')
        arriata = request.POST.get('arriata')
        depttime_s = request.POST.get('depttime')
        arrtime_s = request.POST.get('arrtime')
        aircraft = request.POST.get('aircraft')
        distance = request.POST.get('distance')
        otd = request.POST.get('otd')
        avgdelay = request.POST.get('avgdelay')
        monday = request.POST.get('monday')
        tuesday = request.POST.get('tuesday')
        wednesday = request.POST.get('wednesday')
        thursday = request.POST.get('thursday')
        friday = request.POST.get('friday')
        saturday = request.POST.get('saturday')
        sunday = request.POST.get('sunday')
        if flightno!='' and airlinecode!='' and deptiata!='' and arriata!='' and \
                depttime_s!='' and arrtime_s!='' and aircraft!='' and distance!='' and \
                otd!='' and avgdelay!='' and monday!='' and tuesday!='' and \
                wednesday!='' and thursday!='' and friday!='' and saturday!='' and \
                sunday!='':
            depttime = datetime.datetime.strptime(depttime_s, '%H:%M')
            arrtime = datetime.datetime.strptime(arrtime_s, '%H:%M')
            with connection.cursor() as cur:
                cur.execute("INSERT INTO Flight VALUE (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",[flightno,airlinecode,deptiata,arriata,depttime,arrtime,aircraft,int(distance),otd,int(avgdelay),bool(monday),bool(tuesday),bool(wednesday),bool(thursday),bool(friday),bool(saturday),bool(sunday)])
                transaction.commit()
            return render(request, 'insert.html',{'msg': 'Record has been successfully inserted!'})
        else:
            return render(request, 'insert.html',{'msg': 'Invalid inputs! Please check!'})

def update(request):
    flight_up = {}
    if request.method == "GET":
        flightno_up = request.GET.get('nid')
        flight_up = Flight.objects.raw("SELECT * FROM Flight WHERE FlightNo=%s",[flightno_up])
        return render(request, 'update.html', {'f': flight_up})
    else:
        flightno = request.POST.get('flightno')
        airlinecode = request.POST.get('airlinecode')
        deptiata = request.POST.get('deptiata')
        arriata = request.POST.get('arriata')
        depttime_s = request.POST.get('depttime')
        arrtime_s = request.POST.get('arrtime')
        aircraft = request.POST.get('aircraft')
        distance = request.POST.get('distance')
        otd = request.POST.get('otd')
        avgdelay = request.POST.get('avgdelay')
        monday = request.POST.get('monday')
        tuesday = request.POST.get('tuesday')
        wednesday = request.POST.get('wednesday')
        thursday = request.POST.get('thursday')
        friday = request.POST.get('friday')
        saturday = request.POST.get('saturday')
        sunday = request.POST.get('sunday')
        if flightno != '' and airlinecode != '' and deptiata != '' and arriata != '' and \
                depttime_s != '' and arrtime_s != '' and aircraft != '' and distance != '' and \
                otd != '' and avgdelay != '' and monday != '' and tuesday != '' and \
                wednesday != '' and thursday != '' and friday != '' and saturday != '' and \
                sunday != '':
            depttime = datetime.datetime.strptime(depttime_s, '%H:%M')
            arrtime = datetime.datetime.strptime(arrtime_s, '%H:%M')
            #insrow = "UPDATE Flight SET"
            #insrow = insrow + " AirlineCode='%s'" %airlinecode
            #insrow = insrow + " DeptIATA='%s'" % deptiata
            with connection.cursor() as cur:
                cur.execute("UPDATE Flight SET AirlineCode=%s, DeptIATA=%s, \
                            ArrIATA=%s, DeptTime=%s, ArrTime=%s, \
                            Aircraft=%s, Distance=%s, OTD=%s, \
                            AvgDelay=%s, Monday=%s, Tuesday=%s, \
                            Wednesday=%s, Thursday=%s, Friday=%s, \
                            Saturday=%s, Sunday=%s WHERE FlightNo=%s",[airlinecode,deptiata,arriata,depttime,arrtime,\
                            aircraft,int(distance),otd,int(avgdelay),bool(monday),bool(tuesday),bool(wednesday),\
                                            bool(thursday),bool(friday),bool(saturday),bool(sunday),flightno])
                transaction.commit()
            return render(request, 'manage.html', {'msg': 'Record has been successfully updated!'})
        else:
            return render(request, 'update.html', {'f': flight_up, 'msg': 'Invalid input!'})


# In union class you assing multiple type.
# None : is also a datatype.

from typing import Union
PerType = Union[float, int]
# per : int | float = 88   # It is alternative of above code
percentages : list[PerType] = [88, 99.9, 50, 51,65,70]

grades : list[str] = []

for per in percentages:
    grade : str = ""

    if (per >= 0) and (per < 33):
        grade = "Fail"
    elif (per >= 33) and (per < 40):
        grade = "E"
    elif (per >= 40) and (per < 50):
        grade = "D"
    elif (per >= 50) and (per < 60):
        grade = "C"
    elif (per >= 60) and (per <70) :
        grade = "B"
    elif (per >= 70) and (per <80) :
        grade = "A"
    elif (per >=80) and (per <= 100):
        grade = "A+"

    grades.append(grade)

print(percentages)
print(grade)


import random
import time

import numpy as np
import pandas as pd
from sklearn import model_selection
from sklearn.externals import joblib
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.preprocessing import (Imputer, LabelEncoder, OneHotEncoder,
                                   StandardScaler)

import db_setup

pd.set_option('display.max_columns', 20)
pd.set_option('expand_frame_repr', True)

model_names = ['dt.joblib', 'knn.joblib']
categoricals = []  # going to one-hot encode categorical variables

dt = None
knn = None

def load_data():
    """
    gets data from MySQL table and convert it to dataframe
    """

    global df
    global categoricals
    global labels

    db_setup.init_db()

    pd.set_option('display.max_columns', 20)
    pd.set_option('expand_frame_repr', True)

    db_setup.cursor.execute(db_setup.statement)
    df = pd.read_sql(db_setup.statement, con=db_setup.db)

    labels = db_setup.all_labels()

    for col, col_type in df.dtypes.items():
        if col_type == 'O':
            categoricals.append(col)
        else:
            # fill NA's with 0 for ints/floats, too generic
            df[col].fillna(0, inplace=True)

def prepare_data():
    """
    encodes label dataframe using one-hot encoding
    """

    global x_train
    global y_train
    global categoricals
    global df
    global y_labels

    x_train = df.drop(['id', 'label'], axis=1)
    y_labels = df['label']

    # get_dummies effectively creates one-hot encoded variables
    y_train = pd.get_dummies(y_labels, columns=categoricals, dummy_na=True)
    y_train.drop(['NaN'], axis=1, errors='ignore')

def get_columns():
    """
    :return: column of dataframes
    """

    global categoricals

    load_data()
    prepare_data()

    columns = []
    for col in x_train.columns:
        columns.append(col)

    # print(columns)
    return columns

def cross_val_model(model):
    """
    :param model: sklearn classifier

    :return: result of cross_val function
    """

    global x_train
    global y_train
    global labels
    global y_labels

    load_data()
    prepare_data()

    return cross_val(model, x_train, y_train)

def cross_val(model, x_data, y_data):
    """
    :param model: sklearn classifier
    :param x_data, y_data: features and label data respectively

    performs k-fold cross validation on custom data

    :return: tuple of accuracy, confusion matrix, and cv_result
    """

    validation_size = 0.25
    seed = 3

    x_train, x_validation, y_train, y_validation = model_selection.train_test_split(x_data, y_data,
                                                                                test_size=validation_size,
                                                                                random_state=seed)
    # print(x_train.shape)
    # print(x_validation.shape)
    # print(y_train.shape)
    # print(y_validation.shape)

    # testing options and resetting random seed
    seed = 3
    scoring = 'accuracy'

    # checks accuracy of ML method and outputs accuracy percentage current_dataset n_splits times
    # scores machine learning model on the current_dataset
    K = 10
    kfold = model_selection.KFold(n_splits=K, random_state=seed, shuffle=True)
    cv_results = model_selection.cross_val_score(
        model, x_train, y_train, cv=kfold, scoring=scoring)

    # print(('Mean: %s  SD: %f') % (cv_results.mean(), cv_results.std()))
    # print(cv_results)
    start = time.time()

    # fit training data into classifier
    model.fit(x_train, y_train)
    print("Trained in " + str(time.time() - start) + " seconds")

    # get predictions from machine learning model
    predictions = model.predict(x_validation)
    print(predictions)
    # # print(y_train)

    label_prediction = []
    y_val = []

    for i in range(len(predictions)):
        if predictions[i].any():
            label_prediction.append(decode(predictions[i]))

            # iloc for integer-location based indexing
            y_val.append(y_validation.iloc[i]
                         [y_validation.iloc[i] == 1].index[0])

    # check how accurate the model is using the predictions
    accuracy = accuracy_score(y_val, label_prediction, normalize=True)

    # print(y_val)
    # print(label_prediction)

    # print("Accuracy = " + str(accuracy))
    # print("")

    # confusion matrix
    confusion_mat = confusion_matrix(y_val, label_prediction)
    return (accuracy, confusion_mat, cv_results)

def accuracy_by_class(model, x_data, y_data):
    """
    :param model: sklearn classifier
    :param x_data, y_data: features and label data respectively

    performs k-fold cross validation on custom data

    :return: accuracy of cross-validation
    """

    global x_train
    global y_train

    x_validation = x_data
    y_validation = y_data

    # testing options and resetting random seed
    seed = 3
    scoring = 'accuracy'

    # checks accuracy of ML method and outputs accuracy percentage current_dataset n_splits times
    # scores machine learning model on the current_dataset
    K = 10
    kfold = model_selection.KFold(n_splits=K, random_state=seed,
                                  shuffle=True)
    start = time.time()

    # fit training data into classifier
    model.fit(x_train, y_train)
    print("Trained in " + str(time.time() - start) + " seconds")

    # get predictions from machine learning model
    predictions = model.predict(x_validation)
    # print(predictions)
    # # print(y_train)

    label_prediction = []
    y_val = []

    for i in range(len(predictions)):
        if predictions[i].any():
            label_prediction.append(decode(predictions[i]))

            # iloc for integer-location based indexing
            y_val.append(y_validation.iloc[i]
                         [y_validation.iloc[i] == 1].index[0])

    # print(y_val)
    # print(label_prediction)

    # check how accurate the model is using the predictions
    accuracy = accuracy_score(y_val, label_prediction, normalize=True)

    # print("Accuracy = " + str(accuracy))
    # print("")

    # confusion matrix
    confusion_mat = confusion_matrix(y_val, label_prediction)
    return accuracy

# def decode_predictions(predictions):
#     """
#     :param prediction: encoded array of prediction

#     :return: tuple of label prediction, and encoded predictions
#     """

#     label_prediction = []
#     y_val = []

#     for i in range(len(predictions)):
#         if predictions[i].any():
#             label_prediction.append(decode(predictions[i]))

#             # iloc for integer-location based indexing
#             y_val.append(y_validation.iloc[i]
#                          [y_validation.iloc[i] == 1].index[0])

#     return label_predictions, y_val

def train():
    """
    trains model based on data
    """

    global dt
    global knn

    load_data()
    prepare_data()
    load_models()

    start = time.time()

    if dt and knn:
        dt.fit(x_train, y_train)
        knn.fit(x_train, y_train)

        print("Trained in " + str(time.time() - start) + " seconds")
    else:
        print("No model available to train")

def decode(prediction):
    """
    :param prediction: encoded array of prediction

    returns string value of prediction based on encoded array

    :return: decoded prediction
    """

    db_setup.init_db()

    if (not np.any(prediction)):
        result_text = "Electronic Device"
    else:
        result = (np.where(prediction == 1))[0]
        result = result[0]

        # print(result)
        result_text = db_setup.all_labels()[result]

    db_setup.close_db()
    return result_text

def predict(pred_data):
    """
    :param pred_data: array of data to predicted

    load models from file system using joblib and predicts using pred_data

    :return: encoded prediction
    """

    global dt
    global knn

    load_models()

    print(pred_data)

    # prediction gotten from classifiers if models can be loaded
    if dt and knn:
        dt_dict = {"prediction": decode(dt.predict(pred_data)[0])}
        knn_dict = {"prediction": decode(knn.predict(pred_data)[0])}

        prediction = ""

        if (dt_dict["prediction"] == knn_dict["prediction"]):
            prediction = dt_dict["prediction"] or knn_dict["prediction"]
        else:
            roll = random.randint(1, 100)

            if roll <= 50:
                prediction = dt_dict["prediction"]
            elif roll >= 51:
                prediction = knn_dict["prediction"]

        print(prediction)
        return prediction
    else:
        return "No prediction"

def load_models():
    """
    load models from file system using joblib
    """

    global dt
    global knn

    try:
        dt = joblib.load('../models/'+str(model_names[0]))
        knn = joblib.load('../models/'+str(model_names[1]))
        print('Models loaded')

    except Exception as e:
        print('No model here')
        print(str(e))
        return

def save_models():
    """
    save models to file system using joblib
    """

    global dt
    global knn

    if dt or knn:
        joblib.dump(dt, model_names[0])
        joblib.dump(knn, model_names[1])
        print("Models Saved")
    else:
        return "Can't save model"


import platform
import sys
import threading
import tkinter as tk

import checker
import interop
import settings

NAME_MAPPING = [
    'NUL', 'SOH', 'STX', 'ETX', 'EOT',
    'ENQ', 'ACK', 'BEL',  'BS', 'TAB',
    'LF',   'VT',  'FF',  'CR',  'SO',
    'SI',  'DLE', 'DC1', 'DC2', 'DC3',
    'DC4', 'NAK', 'SYN', 'ETB', 'CAN',
    'EM',  'SUB', 'ESC',  'FS',  'GS',
    'RS',   'US', '???', 'RPG', 'APG',
    'END', 'STR', 'LFT',  'UP', 'RGT',
    'DWN'
]

class InputWindow(tk.Toplevel):
    def __init__(self, text, validator):
        super().__init__()
        self.validator = validator
        self.result = None

        self.hint_label = tk.Label(self, text=text)
        self.hint_label.pack(side=tk.TOP)

        self.input_entry = tk.Entry(self)
        self.input_entry.pack(side=tk.BOTTOM)
        self.input_entry.bind('<Key>', self.reset)
        self.input_entry.bind('<Return>', self.check)
        self.input_entry.focus()

    def reset(self, _event):
        self.input_entry.config(bg='white')

    def check(self, _event):
        text = self.input_entry.get()
        if self.validator(text):
            self.result = text
            self.destroy()
        else:
            self.input_entry.config(bg='red')

    @classmethod
    def run(cls, text, validator):
        window = InputWindow(text, validator)
        window.wait_window()
        return window.result

import logging
logging.basicConfig(level=logging.INFO)

class ConfigButton(tk.Button):
    def __init__(self, parent, text, row, column, command):
        super().__init__(parent, text=text, command=self.command)
        self.grid(row=row, column=column, sticky=tk.NSEW)
        self.real_command = command

    def command(self):
        self.config(state=tk.DISABLED)

        def run():
            try:
                self.real_command()
            except Exception as e:
                logging.exception('oops')
            finally:
                self.config(state=tk.NORMAL)

        threading.Thread(target=run).start()

# noinspection PyMethodMayBeStatic
class Application(tk.Tk):
    def __init__(self, chkr):
        super().__init__()

        self.checker = chkr
        self.title('POE Hacks')
        self.geometry('640x280')
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(1, weight=1)

        # Welcome, configure decoration, logout key
        self.sign_in_label = tk.Label(self, text='POE Hacks', font=('Arial', 16))
        self.sign_in_label.grid(row=0, column=0)

        self.config_deco_button = ConfigButton(self, '', 0, 1, self.config_deco)
        self.setting_deco()

        self.config_logout_button = ConfigButton(self, '', 0, 2, self.config_logout)
        self.setting_logout()

        self.toggle_checks_button = tk.Button(self, text='Toggle\nChecks', fg='green', command=self.toggle_checks)
        self.toggle_checks_button.grid(row=0, column=3)

        # Added actions
        self.action_list = tk.Listbox(self)
        self.action_list.grid(row=1, column=0, columnspan=4, sticky=tk.NSEW)
        self.action_list.bind('<BackSpace>', self.delete_action)
        self.action_list.bind('<Delete>', self.delete_action)
        for action in self.checker.settings.actions:
            self.action_list.insert(tk.END, action)

        # Add actions
        self.quit_button = tk.Button(self, text='Quit', command=self.destroy)
        self.quit_button.grid(row=2, column=0, sticky=tk.NSEW)

        self.add_logout_screen_button = ConfigButton(
            self,
            'Add auto\nlogout on\nscreen change',
            2, 1, self.config_logout_screen
        )
        self.add_key_screen_button = ConfigButton(
            self,
            'Add auto\nkey press on\nscreen change',
            2, 2, self.config_key_screen
        )
        self.add_key_key_button = ConfigButton(
            self,
            'Add auto\nkey press on\nkey press',
            2, 3, self.config_key_key
        )

        # Status bar
        self.status_label = tk.Label(self, bd=1, relief=tk.SUNKEN, anchor=tk.S)
        self.status_label.grid(row=3, column=0, columnspan=4, sticky=tk.EW)
        self.status()

    def status(self, text=None):
        if not text:
            text = 'Checks are running!'

        self.status_label.config(text=text)

    # SETTING DECORATION

    def config_deco(self):
        self.status('Please right-click on the first decoration in POE')
        p = interop.wait_mouse(2)
        c = interop.get_color(*p)
        self.checker.settings.decoration.p1 = p
        self.checker.settings.decoration.c1 = c

        self.status('Now right-click on the second decoration in POE')
        p = interop.wait_mouse(2)
        c = interop.get_color(*p)
        self.checker.settings.decoration.p2 = p
        self.checker.settings.decoration.c2 = c

        self.status()
        self.setting_deco()

    def setting_deco(self):
        point = self.checker.settings.decoration.p1
        self.config_deco_button.config(
            text='Configure\nDecoration',
            fg='red' if point == (0, 0) else 'green',
            state=tk.NORMAL
        )

    # SETTING LOGOUT

    def config_logout(self):
        self.status('Please press the key to use for logging out')
        self.checker.settings.logout_key = interop.wait_key()
        self.status()
        self.setting_logout()

    def setting_logout(self):
        key = self.checker.settings.logout_key
        self.config_logout_button.config(
            text=f'Logout\nKey ({key})' if key else 'Logout\nKey',
            fg='green' if key else 'red',
            state=tk.NORMAL
        )

    # TOGGLING CHECKS ON / OFF

    def toggle_checks(self):
        if self.checker.toggle():
            self.toggle_checks_button.config(fg='green')
        else:
            self.toggle_checks_button.config(fg='red')

    # ADDING LOGOUT ON SCREEN CHANGE

    def config_logout_screen(self):
        self.status('Right-click the life point to detect for logging out')
        point = interop.wait_mouse(2)
        color = interop.get_color(*point)
        self.add_action(settings.ScreenLogout(point, color))
        self.status()

    # ADDING KEY ON SCREEN CHANGE

    def config_key_screen(self):
        self.status('Press the key to auto use')
        key = interop.wait_key()
        self.status('Right-click the life/mana point to detect for using a key')
        point = interop.wait_mouse(2)
        color = interop.get_color(*point)
        self.status('Please fill in the delay dialog')
        delay = int(InputWindow.run('Enter flask delay (in ms)', lambda t: t.isdigit()) or 1000)
        self.add_action(settings.ScreenKey(point, color, key, delay))
        self.status()

    # ADDING KEY ON KEY PRESS

    def config_key_key(self):
        self.status('Press the key to detect for using another key')
        detect = interop.wait_key()
        self.status('Press the key to auto use')
        use = interop.wait_key()
        self.status('Please fill in the delay dialog')
        delay = int(InputWindow.run('Enter flask delay (in ms)', lambda t: t.isdigit()) or 1000)
        self.add_action(settings.KeyKey(detect, use, delay))
        self.status()

    # CREATING A NEW ACTION

    def add_action(self, action):
        self.checker.settings.actions.append(action)
        self.action_list.insert(tk.END, action)

    def delete_action(self, _event):
        index = self.action_list.curselection()
        if not index:
            return

        index = index[0]
        del self.checker.settings.actions[index]
        self.action_list.delete(index)

        if index == len(self.checker.settings.actions):
            index -= 1
        self.action_list.selection_set(index)

def main():
    if platform.architecture()[0].startswith('32'):
        # https://docs.microsoft.com/en-us/windows/desktop/api/psapi/nf-psapi-enumprocessmodules
        # If this function is called from a 32-bit application running on WOW64, it can only enumerate
        # the modules of a 32-bit process. If the process is a 64-bit process, this function fails and
        # the last error code is ERROR_PARTIAL_COPY (299).
        print('refusing to run with python 32 bits', file=sys.stderr)
        return 1

    if not interop.is_admin():
        interop.elevate(__file__)
        return -1

    with checker.Checker('poe.key') as c:
        Application(c).mainloop()

if __name__ == '__main__':
    quit(main())


import os
os.system('cls')
schoolName= str(input(" Enter the organization name:  "))
print(f"Welcome {schoolName}\n\n")
totalstudent = int(input("Enter the total number of student :\n  "))

def studentInfo():
    print (f" The data is taken for {i+1} sutdent ")
    studentName=(str(input("Enter the name of student :  ")))
    studentClass = int(input("Enter the class of  student :  "))
    studentRoll = int(input(' Enter the roll number of student:  '))
    output1(studentName,studentClass,studentRoll)

def output1(studentName,studentClass,studentRoll):
    print(f" The name of {i+1} student is {studentName} .")
    print(f"The  class of {i+1} student is {studentClass}")
    print(f"The roll of {i+1} student is {studentRoll}")

def output2(totalMarks,totalSubject):
    print(f" The total marks of student is {totalMarks}")
    percentage = totalMarks//totalSubject
    print(f"The percentage of student is { percentage}")
    if percentage >= 90 and percentage <=100:
        print(" You got  A+")
    elif percentage >= 80 and percentage <90:
        print(" You got  A")
    elif percentage >= 70 and percentage <80:
        print(" You got  B+")
    elif percentage >= 60 and percentage <70:
        print(" You got  B")
    elif percentage >= 50 and percentage <60:
        print(" You got  C+")
    elif percentage>= 40 and percentage < 50:
        print("You got C.")
    else:
        print("You are fail in examination.")

marks=[]
for i in range(totalstudent):
    studentInfo()
    totalSubject=(int (input('Enter the total subject :  ')  ))
    for j in range(totalSubject):
        marks.append(int(input (f"Enter the marks of  {j+1} subject :  ")))
    totalMarks= sum(marks)
    output2(totalMarks,totalSubject)


import numpy as np
import cv2
import yaml
rect = []
mot = False
hai = False
ba = False
bon = False
park =[]
i = -1
def write_data():
    global park
    with open('vidCrsShow.yml', 'w') as stream:
        yaml.dump(park, stream,default_flow_style=False)
    with open(r'vidCrsShow.yml', 'r') as infile, open(r'vi.yml', 'w') as outfile:
        data = infile.read()
        data = data.replace("'", "")
        outfile.write(data)

def on_mouse(event,x,y,flags,params):
    global rect,mot,hai,ba,bon
    if event == cv2.EVENT_LBUTTONDOWN:
        if mot == True and hai == True and ba == True and bon == True:
            mot = False
            hai = False
            ba = False
            bon = False
            rect = []

        if mot == False:
            rect.append([x,y])
            print (rect)
            mot = True
        elif hai == False:
            rect.append([x,y])
            print (rect)
            hai = True
        elif ba == False:
            rect.append([x,y])
            print (rect)
            ba = True
        elif bon == False:
            rect.append([x,y])
            print (rect)
            bon = True

cap = cv2.VideoCapture('test_video.mp4')
waitTime = 50

#Reading the first frame
(grabbed, frame) = cap.read()

while(cap.isOpened()):

    (grabbed, frame) = cap.read()
    cv2.namedWindow('frame')
    cv2.setMouseCallback('frame', on_mouse)
    #drawing rectangle
    if mot == True and hai == True and ba == True and bon == True:
        i = i+1
        abc = str(rect)
        if ( i == 0):
            park = [{'id': i, 'points': abc}]#, {'id': 1, 'points': 2}]
        else:
            park.append({'id': i, 'points': abc})
            print(park)
        mot = False
        hai = False
        ba = False
        bon = False
        rect = []
    if (i == 3):
        write_data()

    cv2.imshow('frame',frame)

    key = cv2.waitKey(waitTime)

    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()


from django.db.models import Count
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics, filters
from .models import Yakfile
from yakker.permissions import AuthorOrReadOnly
from .serializers import YakfileSerializer

class ListYakfile(generics.ListAPIView):
    """
    Class-based view to list all yakfiles.
    """
    queryset = Yakfile.objects.annotate(
        post_count=Count('author__post', distinct=True),
        follower_count=Count('author__followed_user', distinct=True),
        following_count=Count('author__author', distinct=True)
    ).order_by('-created_at')
    permission_classes = [AuthorOrReadOnly]
    serializer_class = YakfileSerializer
    filter_backends = [
        filters.OrderingFilter,
        DjangoFilterBackend,
    ]
    filterset_fields = [
        # check who's following the user
        'author__author__followed_user__yakfile',
        # check who the user is following
        'author__followed_user__author__yakfile'
    ]
    ordering_fields = [
        'post_count',
        'follower_count',
        'following_count',
        'author__followed_user__created_at',
        'author__author__created_at',
    ]

class DetailYakfile(generics.RetrieveUpdateAPIView):
    """
    Class-based detailed view to retrieve or update a profile
    if you're the owner.
    """
    queryset = Yakfile.objects.annotate(
        post_count=Count('author__post', distinct=True),
        follower_count=Count('author__followed_user', distinct=True),
        following_count=Count('author__author', distinct=True)
    ).order_by('-created_at')
    permission_classes = [AuthorOrReadOnly]
    serializer_class = YakfileSerializer


class Solution:
    def cherryPickup(self, grid: List[List[int]]) -> int:
        coordinates = []
        cache = {}

        def cherryPickupRec(row_i=0, r1_col=0, r2_col=len(grid[0])-1):
            if (row_i >= len(grid)):
                return 0

            if tuple([row_i, r1_col, r2_col]) in cache:
                return cache[tuple([row_i, r1_col, r2_col])]

            curr_picked = grid[row_i][r1_col] + grid[row_i][r2_col] if r1_col != r2_col else grid[row_i][r1_col]

            r1_next_cols = []
            r2_next_cols = []
            for i in range(-1, 2, 1):
                if 0 <= r1_col + i < len(grid[0]):
                    r1_next_cols.append(r1_col + i)
                if 0 <= r2_col + i < len(grid[0]):
                    r2_next_cols.append(r2_col + i)

            max_picked = []
            for r1_next_col in r1_next_cols:
                for r2_next_col in r2_next_cols:
                    max_picked.append(curr_picked + cherryPickupRec(row_i + 1, r1_next_col, r2_next_col))
            cache[tuple([row_i, r1_col, r2_col])] = max(max_picked)
            return cache[tuple([row_i, r1_col, r2_col])]

        return cherryPickupRec()

2022/Oct/21st, at 18 13 - cherry pickup ii.py


from fastai2.vision.all import *

# REPLACE THIS MODEL WITH MOST UP TO DATE VERSION
# find the latest version at https://labs.deep-insights.ai/models/latest.pkl
MODEL = 'latest.pkl'

LBL_PATHO = 'Non-COVID'
LBL_COV = 'COVID'

# when loading the model for inference, the fastai learner requires
# that the functions which were used during training exist
# in the same namespace, even if not used, hence the definition here
def get_lbl(fname):
    """return the label of given image"""
    lbl = fname.parent.name
    if lbl == 'P':
        return LBL_PATHO
    elif lbl == 'C':
        return LBL_COV
    else:
        raise ValueError(f'could not extract label from {fname}')

def in_valid(fname):
    """return True if file in validationset, else False"""
    return fname.parent.parent.name == 'valid'

LEARN = load_learner(MODEL)

CATEGORIES = LEARN.dls.vocab  # classes in order of output neurons

def predict(img):
    """img: str or Path to image
    returns {category: probability}
    """
    y_hat, idx, probs = LEARN.predict(img)
    probabilities = [p.item() for p in probs]
    return dict(zip(CATEGORIES, probabilities))

if __name__ == "__main__":
    img = '<TODO: add img path to img in repo, (relative path names are great)'
    print(f'classifying image {img}:')
    print(predict(img))


'''udp套接字服务端
    udp服务端不需要对客户端的状态进行判断
    有人请求就回应，没有请求就什么也不做
    （无连接协议）

    UDP不会粘包，但是会丢包，超出接收大小的部分会直接丢弃
    '''
import socket
s1 = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s1.bind(('0.0.0.0',12346))
f = open('dict.txt','r')

while True:
    data,addr = s1.recvfrom(300)
    if not data:
        break
    print('message from %s:%s'%(addr,data.decode()))
    for line in f:
        list1=line.split(' ')
        if data.decode() == list1[0]:
            jieguo=' '.join(list1[1:-1]).strip()
            print(jieguo)
    s1.sendto(jieguo.encode(),addr)
s1.close()


class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        if not nums:
            return None
        n = len(nums)
        first = 0
        last = n - 1
        if nums[0] > target:
            return 0
        if nums[n-1] < target:
            return n
        while first <= last:
            mid = int((first + last) / 2)
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                last = mid - 1
            else:
                first = mid + 1
        return first