from sys import platform
from os import system
from imp import load_source
import time
import numpy as np

# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import

# This import registers the 3D projection, but is otherwise unused.
#from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import
'''
# This is boilerplate for importing source, replaces from 'imp import load_source
import importlib.machinery
import importlib.util
loader = importlib.machinery.SourceFileLoader('WalabotAPI', 'C:/Program Files/Walabot/WalabotSDK/python/WalabotAPI.py')
spec = importlib.util.spec_from_loader(loader.name, loader)
WalabotAPI = importlib.util.module_from_spec(spec)
loader.exec_module(WalabotAPI)'''

WalabotAPI = load_source('WalabotAPI','C:/Program Files/Walabot/WalabotSDK/python/WalabotAPI.py')
WalabotAPI.Init()
# Configure Walabot database install location (for windows)
WalabotAPI.SetSettingsFolder()

# Bug with Qt if matplotlib is imported before WalabotAPI.SetSettingsFolder() is called
import matplotlib.pyplot as plt

def PrintSensorTargets(targets):
    system('cls' if platform == 'win32' else 'clear')
    if targets:
        for i, target in enumerate(targets):
            print (('Target #{}:\ntype: {}\nangleDeg: {}\nx: {}\ny: {}\nz: {}'+
            '\nwidth: {}\namplitude: {}\n').format(i + 1, target.type,
            target.angleDeg, target.xPosCm, target.yPosCm, target.zPosCm,
            target.widthCm, target.amplitude))
    else:
        print ('No Target Detected')

def PrintFormatted(image):
    for theta in image:
        print(theta)
        '''
        for phi in theta:
            for r in phi:
                '''

def spher2cart(p, theta, phi):
    x = p*np.sin(phi)*np.cos(theta)
    y = p*np.sin(phi)*np.sin(theta)
    z = p*np.cos(phi)
    return x, y, z

def InWallApp():
    # WalabotAPI.SetArenaX - input parameters
    rArenaMin, rArenaMax, rArenaRes = 5, 100, 10
    # WalabotAPI.SetArenaY - input parameters
    thetaArenaMin, thetaArenaMax, thetaArenaRes = -45, 45, 5
    # WalabotAPI.SetArenaZ - input parameters
    phiArenaMin, phiArenaMax, phiArenaRes = -90, 0, 5
    '''# Configure Walabot database install location (for windows)
    WalabotAPI.SetSettingsFolder()'''
    # 1) Connect: Establish communication with walabot.
    WalabotAPI.ConnectAny()
    # 2) Configure: Set scan profile and arena
    # Set Profile - to Short-range.
    WalabotAPI.SetProfile(WalabotAPI.PROF_SENSOR)
    # Set arena by Cartesian coordinates, with arena resolution
    WalabotAPI.SetArenaR(rArenaMin, rArenaMax, rArenaRes)
    WalabotAPI.SetArenaTheta(thetaArenaMin, thetaArenaMax, thetaArenaRes)
    WalabotAPI.SetArenaPhi(phiArenaMin, phiArenaMax, phiArenaRes)
    # Walabot filtering disable
    WalabotAPI.SetDynamicImageFilter(WalabotAPI.FILTER_TYPE_NONE)
    # 3) Start: Start the system in preparation for scanning.
    WalabotAPI.Start()
    # calibrates scanning to ignore or reduce the signals
    WalabotAPI.StartCalibration()
    while True:
        system('cls' if platform == 'win32' else 'clear')

        appStatus, calibrationProcess = WalabotAPI.GetStatus()
        # 5) Trigger: Scan (sense) according to profile and record signals
        # to be available for processing and retrieval.
        WalabotAPI.Trigger()
        # 6) Get action: retrieve the last completed triggered recording
        #targets = WalabotAPI.GetImagingTargets()
        rasterImage, X, Y, Z, power = WalabotAPI.GetRawImage()
        # print targets foundca

        #PrintSensorTargets(targets)
        PrintFormatted(rasterImage)
        voxel_test(np.array(rasterImage) // 35)

        time.sleep(1)

    # 7) Stop and Disconnect.
    WalabotAPI.Stop()
    WalabotAPI.Disconnect()
    print ('Terminate successfully')

def voxel_test(voxels):
    '''# prepare some coordinates
    x, y, z = np.indices((8, 8, 8))

    # draw cuboids in the top left and bottom right corners, and a link between them
    cube1 = (x < 3) & (y < 3) & (z < 3)
    cube2 = (x >= 5) & (y >= 5) & (z >= 5)
    link = abs(x - y) + abs(y - z) + abs(z - x) <= 2

    # combine the objects into a single boolean array
    voxels = cube1 | cube2 | link

    # set the colors of each object
    colors = np.empty(voxels.shape, dtype=object)
    colors[link] = 'red'
    colors[cube1] = 'blue'
    colors[cube2] = 'green' '''

    # and plot everything
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.voxels(voxels, edgecolor='k')

    plt.show()

if __name__ == '__main__':
    InWallApp()


#!/usr/bin/env python
## Simple talker demo that published std_msgs/Strings messages
## to the 'mann' topic

import rospy
from std_msgs.msg import Int16
global add
def nodeA():
	pub = rospy.Publisher('mann', Int16, queue_size=10)
	rospy.init_node('nodeA', anonymous=True)
	rate = rospy.Rate(0.5)
	data=Int16()
	data.data=5
	add=Int16()
	add.data=4
	while not rospy.is_shutdown():
		rospy.loginfo(data)
		pub.publish(data)
		data.data = data.data + add.data
		rate.sleep()

if __name__ == '__main__':
    try:
        nodeA()
    except rospy.ROSInterruptException:
        pass


import numpy as np
import pandas as pd
from collections import OrderedDict, defaultdict

df = pd.read_csv("MLB/batter_all.csv", encoding='latin-1')

player_dict = dict(zip(df['mlb_name'], df['mlb_pos']))

players = {'player_name': df['mlb_name'],
           'player_position': df['mlb_pos'],
           'team': df['mlb_team_long']}

df['mlb_team_long'] = list(map((lambda x:x.upper()), df['mlb_team_long']))

class Players(object):
    """Basic Player Information - Name, Team, Position, Hand...
    """
    #players_df = pd.read_csv("MLB/batter_all.csv", encoding='latin-1')

    def __init__(self, data, column_titles, column_names):
        self.data = data
        self.column_titles = column_titles
        self.column_names = column_names

    def create_df(self):
        self.dataframe = pd.DataFrame(np.column_stack([[x for x in self.data[self.column_names].values]]),
                                      columns = self.column_titles)
        return self.dataframe

    def create_dict(self, player_col):
        i=1
        player_list, player_dict_list, player_dict_list_full = [],[],[]
        player_dict, player_dict1, player_dictionary, dick = {},{},{},{}
        for player in self.data[player_col]:
            while i <= len(self.column_names):
                if i < len(self.column_names) and i > 1:
                    player_dict = {self.column_titles[i]: list(self.data[self.column_names[i]][self.data['mlb_name'] == player].astype('str'))[0]}
                    player_list.append(player_dict)
                    player_dict1[self.column_titles[i]] = list(self.data[self.column_names[i]][self.data['mlb_name'] == player].astype('str'))[0]
                    i+=1
                if i == 1:
                    player_dict = {self.column_titles[i]: list(self.data[self.column_names[i]][self.data['mlb_name'] == player].astype('str'))[0]}
                    player_list.append(player_dict)
                    player_dict1[self.column_titles[i]] = list(self.data[self.column_names[i]][self.data['mlb_name'] == player].astype('str'))[0]
                    i+=1
                if i == len(self.column_names):
                    #player_dict_list_full would be good for Team seperation
                    player_dict_list_full.append(player_dict1)
                    dick[player] = player_dict1
                    player_dictionary[player] = player_list
                    player_list = []
                    player_dict1 = {}
                    i+=1
            i=1

        self.dick = dick
        self.player_dic_lib = player_dictionary
        return player_dict_list_full, player_dictionary, dick

    def right_handed_batters(self):
        right_handed = {}
        right, hand = [], []
        for k, [v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15] in self.dick.items():
            if self.dick[k][v4] == 'R':
                right.append(k)
                hand.append(self.dick[k][v4])
                right_handed[k] = {v1:self.dick[k][v1],
                            v2:self.dick[k][v2],
                            v3:self.dick[k][v3],
                            v4:self.dick[k][v4],
                            v5:self.dick[k][v5],
                            v6:self.dick[k][v6],
                            v7:self.dick[k][v7],
                            v8:self.dick[k][v8],
                            v9:self.dick[k][v9],
                            v10:self.dick[k][v10],
                            v11:self.dick[k][v11],
                            v12:self.dick[k][v12],
                            v13:self.dick[k][v13],
                            v14:self.dick[k][v14],
                            v15:self.dick[k][v15]}

        self.right_handed = right_handed
        self.right_batters = right
        return right_handed

    def left_handed_batters(self):
        left_handed = {}
        left, hand = [], []
        for k, [v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15] in self.dick.items():
            if self.dick[k][v4] == 'L':
                left.append(k)
                hand.append(self.dick[k][v4])
                left_handed[k] = {v1:self.dick[k][v1],
                           v2:self.dick[k][v2],
                           v3:self.dick[k][v3],
                           v4:self.dick[k][v4],
                           v5:self.dick[k][v5],
                           v6:self.dick[k][v6],
                           v7:self.dick[k][v7],
                           v8:self.dick[k][v8],
                           v9:self.dick[k][v9],
                           v10:self.dick[k][v10],
                           v11:self.dick[k][v11],
                           v12:self.dick[k][v12],
                           v13:self.dick[k][v13],
                           v14:self.dick[k][v14],
                           v15:self.dick[k][v15]}

        self.left_handed = left_handed
        self.left_batters = left
        return left_handed

    def switch_handed_batters(self):
        switch_handed = {}
        switch, hand = [], []
        for k, [v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15] in self.dick.items():
            if self.dick[k][v4] == 'S':
                switch.append(k)
                hand.append(self.dick[k][v4])
                switch_handed[k] = {v1:self.dick[k][v1],
                             v2:self.dick[k][v2],
                             v3:self.dick[k][v3],
                             v4:self.dick[k][v4],
                             v5:self.dick[k][v5],
                             v6:self.dick[k][v6],
                             v7:self.dick[k][v7],
                             v8:self.dick[k][v8],
                             v9:self.dick[k][v9],
                             v10:self.dick[k][v10],
                             v11:self.dick[k][v11],
                             v12:self.dick[k][v12],
                             v13:self.dick[k][v13],
                             v14:self.dick[k][v14],
                             v15:self.dick[k][v15]}

        self.switch_handed = switch_handed
        self.switch_batters = switch
        return switch_handed

    def right_handed_pitchers(self, cat_name, cat_value):
        right_handed_pitcher = {}
        right, hand = [], []
        cat1, cat2 = self.find_length_cat(cat_name)
        vars = self.create_dict_vars(cat1)
        for k, vars in self.dick.items():
            if self.dick[k][cat_value] == cat_name:
                right.append(k)
                hand.append(self.dick[k][cat_value])
                right_handed_pitcher[k] = vars

        self.right_handed_pitcher = right_handed_pitcher
        self.right_pitchers = right
        return right_handed_pitcher

    def find_length_cat(self, cat_name):
        for k,v in self.player_dic_lib.items():
            cat_len = len(v)
            for j,vs in enumerate(v):
                if list(vs.values())[0] == cat_name:
                    cat_num = j
        return cat_len, cat_num

    def create_dict_vars(self, cat_len):
        vars = []
        for i in range(1,cat_len+1):
            vars.append('v' + str(i))
        return vars

player_frame = Players(data = df, column_names = ['mlb_name', 'mlb_pos', 'mlb_team_long', 'TEAM', 'bats', 'LG_batter_Std',
                                                  'OBP_batter_Std', 'SLG_batter_Std', 'OPS_batter_Std', 'ISO_batter_Std',
                                                  'oppOPS_batter_Std', 'TAv_batter_Std', 'VORP_batter_Std', 'FRAA_batter_Std',
                                                  'BWARP_batter_Std', 'BASES_VS_AB_batter_Std'],
                               column_titles = ['player_name', 'player_position', 'team', 'team_ini', 'bat_hand', 'league',
                                                'batter_OBP', 'batter_SLG', 'batter_OPS', 'batter_ISO', 'batter_oppOPS',
                                                'batter_TAv', 'batter_VORP', 'batter_FRAA', 'batter_BWARP', 'batter_BASES_VS_AB'])

player_frames = player_frame.create_df()
player_dic = player_frame.create_dict('mlb_name')

player_dict_tot_list = player_dic[0]
player_dict_tot = player_dic[1]
player_dict_stats = player_dic[2]

righty = player_frame.right_handed_batters()
lefty = player_frame.left_handed_batters()
switch = player_frame.switch_handed_batters()

pitchers = player_frame.right_handed_pitchers('P', 'player_position')

test = player_frame.find_length_cat('P')
test1 = player_frame.create_dict_vars(15)


import cv2
import numpy as np
import pyautogui
cap = cv2.VideoCapture(0)

green_lower = np.array([36, 25, 25])
green_upper = np.array([70, 255,255])

lower_red = np.array([0,50,50])
upper_red = np.array([10,255,255])

prev_y1 = 0
prev_y2 = 0

while True:
    ret, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    mask_1 = cv2.inRange(hsv, green_lower, green_upper)
    mask_2 = cv2.inRange(hsv, lower_red, upper_red)
    contours_1, hierarchy_1 = cv2.findContours(mask_1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contours_2, hierarchy_2 = cv2.findContours(mask_2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for c1 in contours_1:
        area_1 = cv2.contourArea(c1)
        if area_1 > 3000:
            x1, y1, w1, h1 = cv2.boundingRect(c1)
            cv2.rectangle(frame, (x1,y1), (x1+w1, y1+h1), (255, 255, 255), 2)
            if y1+20 < prev_y1:
                pyautogui.press('up')
            prev_y1 = y1

    for c2 in contours_2:
        area_2 = cv2.contourArea(c2)
        if area_2 > 4000:
            x2, y2, w2, h2 = cv2.boundingRect(c2)
            cv2.rectangle(frame, (x2,y2), (x2+w2, y2+h2), (0,0,0), 2)
            if y2 + 20 < prev_y1:
                pyautogui.press('down')
            prev_y1 = y2

    cv2.imshow("Controling Up and Down Key",frame)
    if cv2.waitKey(10) == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()


from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^check_angent_status/(?P<ip>[0-9a-zA-Z\.]+)/(?P<plat_id>\w+)$', views.check_angent_status),
    # url(r'^fetch_ptables/(?P<ip>[0-9a-zA-Z\.]+)$', views.fetch_ptables),
    url(r'^search_by_ip', views.search_by_ip),
    url(r'^submit_iptables', views.submit_iptables),

]


from pathlib import Path

import numpy as np
import pygame as pg

from core import animation_snake
from core.tiles import Tiles
from core.tools import GameState, Point

class GameOver(GameState):
    def __init__(self):
        super(GameOver, self).__init__()
        sound_folder = Path("../sounds/")
        self.game_over_sound = pg.mixer.Sound(str(sound_folder / "gameOver.mp3"))

        self.board_size = 26
        self.snake_speed = 0.01
        self.tiles = Tiles(self.board_size)

        # "Snake" written in Silverfinster
        title = np.array([[0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0],
                          [0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0],
                          [0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0],
                          [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0]],
                         dtype=np.int32)

        # find out coordinates of the "Snake" pixels
        title_path = list()
        title_offset = 2

        for y in range(0, 4):
            for x in range(0, self.board_size):
                if title[y][x]:
                    title_path.append(Point(x, y + title_offset))

        # Title Snake
        data = {
            'speed': 0.05,
            'tiles': self.tiles,
            'path': title_path,
            'length': len(title_path)
        }
        self.title_snake = animation_snake.Snake(**data)

        self.path = list()

        for i in range(16):
            self.path.append(Point(i, 10))

        message = "RETRY"
        data = {
            'speed': self.snake_speed,
            'tiles': self.tiles,
            'path': self.path,
            'length': len(message) + 1,
            'message': message
        }
        self.retry_snake = animation_snake.Snake(**data)

    def startup(self, persistent):
        self.persist = persistent
        self.game_over_sound.play()

    def get_event(self, event):
        if event.type == pg.QUIT:
            self.quit = True
        if event.type == pg.VIDEORESIZE:
            self.tiles.update_window_size(event.w, event.h)
        if event.type == pg.MOUSEBUTTONDOWN:
            if self.retry_snake.clicked_snake(event.pos):
                self.done = True
                self.next_state = "MENU"

    def update(self, dt):
        self.title_snake.update(dt)
        self.retry_snake.update(dt)

    def draw(self, surface):
        surface.fill(pg.Color("black"))
        self.tiles.draw(surface)
        self.title_snake.draw(surface)
        self.retry_snake.draw(surface)


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

# Copyright 2011-2017, Nigel Small
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import division, print_function

from datetime import datetime
import shlex
from os.path import expanduser
from timeit import default_timer as timer
from textwrap import dedent

import click
from neo4j.v1 import GraphDatabase, ServiceUnavailable, CypherError, TransactionError
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.styles import style_from_pygments
from pygments.lexers.graph import CypherLexer
from pygments.styles.default import DefaultStyle
from pygments.token import Token

from n4.table import Table
from .data import TabularResultWriter, CSVResultWriter, TSVResultWriter
from .meta import title, description, quick_help, full_help

HISTORY_FILE = expanduser("~/.n4_history")

class Console(object):

    multi_line = False
    watcher = None

    tx_colour = "yellow"
    err_colour = "reset"
    meta_colour = "blue"
    prompt_colour = "blue"

    def __init__(self, uri, auth, secure=True, verbose=False):
        try:
            self.driver = GraphDatabase.driver(uri, auth=auth, encrypted=secure)
        except ServiceUnavailable as error:
            raise ConsoleError("Could not connect to {} ({})".format(uri, error))
        self.uri = uri
        self.history = FileHistory(HISTORY_FILE)
        self.prompt_args = {
            "history": self.history,
            "lexer": PygmentsLexer(CypherLexer),
            "style": style_from_pygments(DefaultStyle, {
                Token.Prompt: "#ansi{}".format(self.prompt_colour),
                Token.TxCounter: "#ansi{} bold".format(self.tx_colour),
            })
        }
        self.result_writer = TabularResultWriter()
        if verbose:
            from .watcher import watch
            self.watcher = watch("neo4j.bolt")

        self.commands = {

            "//": self.set_multi_line,

            "/?": self.help,
            "/h": self.help,
            "/help": self.help,

            "/x": self.exit,
            "/exit": self.exit,

            "/csv": self.set_csv_result_writer,
            "/table": self.set_tabular_result_writer,
            "/tsv": self.set_tsv_result_writer,

            "/config": self.config,
            "/kernel": self.kernel,

        }
        self.session = None
        self.tx = None
        self.tx_counter = 0

    def loop(self):
        click.echo(title, err=True)
        click.echo("Connected to {}".format(self.uri).rstrip(), err=True)
        click.echo(err=True)
        click.echo(dedent(quick_help), err=True)
        while True:
            try:
                source = self.read().strip()
            except KeyboardInterrupt:
                continue
            except EOFError:
                return 0
            try:
                self.run(source)
            except ServiceUnavailable:
                return 1

    def run(self, source):
        try:
            if not source:
                pass
            elif source.startswith("/"):
                self.run_command(source)
            elif source.upper() == "BEGIN":
                self.begin_transaction()
            elif source.upper() == "COMMIT":
                self.commit_transaction()
            elif source.upper() == "ROLLBACK":
                self.rollback_transaction()
            elif self.tx is None:
                with self.driver.session() as session:
                    self.run_cypher(session, source, {})
            else:
                self.run_cypher(self.tx, source, {})
                self.tx_counter += 1
        except CypherError as error:
            if error.classification == "ClientError":
                pass
            elif error.classification == "DatabaseError":
                pass
            elif error.classification == "TransientError":
                pass
            else:
                pass
            click.secho("{}: {}".format(error.title, error.message), err=True)
        except TransactionError:
            click.secho("Transaction error", err=True, fg=self.err_colour)

    def rollback_transaction(self):
        if self.session:
            try:
                self.session.rollback_transaction()
                click.secho(u"(Transaction ROLLBACK at {})".format(datetime.now()),
                            err=True, fg=self.tx_colour, bold=True)
            finally:
                self.tx = None
                self.tx_counter = 0
                self.session.close()
                self.session = None
        else:
            click.secho(u"No current transaction", err=True, fg=self.err_colour)

    def commit_transaction(self):
        if self.session:
            try:
                self.session.commit_transaction()
                click.secho(u"(Transaction COMMIT at {})".format(datetime.now()),
                            err=True, fg=self.tx_colour, bold=True)
            finally:
                self.tx = None
                self.tx_counter = 0
                self.session.close()
                self.session = None
        else:
            click.secho(u"No current transaction", err=True, fg=self.err_colour)

    def begin_transaction(self):
        if self.tx is None:
            self.session = self.driver.session()
            self.tx = self.session.begin_transaction()
            self.tx_counter = 1
            click.secho(u"(Transaction BEGIN at {})".format(datetime.now()),
                        err=True, fg=self.tx_colour, bold=True)
        else:
            click.secho(u"Transaction already open", err=True, fg=self.err_colour)

    def read(self):
        if self.multi_line:
            self.multi_line = False
            return prompt(u"", multiline=True, **self.prompt_args)

        def get_prompt_tokens(_):
            tokens = []
            if self.tx is None:
                tokens.append((Token.Prompt, "\n-> "))
            else:
                tokens.append((Token.Prompt, "\n-("))
                tokens.append((Token.TxCounter, "{}".format(self.tx_counter)))
                tokens.append((Token.Prompt, ")-> "))
            return tokens

        return prompt(get_prompt_tokens=get_prompt_tokens, **self.prompt_args)

    def run_cypher(self, context, statement, parameters):
        t0 = timer()
        result = context.run(statement, parameters)
        total = 0
        if result.keys():
            self.result_writer.write_header(result)
            more = True
            while more:
                total += self.result_writer.write(result, 50)
                more = result.peek() is not None
        summary = result.summary()
        t1 = timer() - t0
        if len(summary.server.address) == 4:  # IPv6
            server_address = "[{}]:{}".format(*summary.server.address)
        else:                                 # IPv4
            server_address = "{}:{}".format(*summary.server.address)
        click.secho(u"({} record{} from {} in {:.3f}s)".format(
            total, "" if total == 1 else "s", server_address, t1),
            err=True, fg=self.meta_colour, bold=True)

    def run_command(self, source):
        assert source
        terms = shlex.split(source)
        command_name = terms[0]
        try:
            command = self.commands[command_name]
        except KeyError:
            click.secho("Unknown command: " + command_name, err=True, fg=self.err_colour)
        else:
            kwargs = {}
            for term in terms[1:]:
                key, _, value = term.partition("=")
                kwargs[key] = value
            command(**kwargs)

    def set_multi_line(self, **kwargs):
        self.multi_line = True

    @classmethod
    def help(cls, **kwargs):
        click.echo(description, err=True)
        click.echo(err=True)
        click.echo(full_help.replace("\b\n", ""), err=True)

    @classmethod
    def exit(cls, **kwargs):
        exit(0)

    def set_csv_result_writer(self, **kwargs):
        self.result_writer = CSVResultWriter()

    def set_tabular_result_writer(self, **kwargs):
        self.result_writer = TabularResultWriter()

    def set_tsv_result_writer(self, **kwargs):
        self.result_writer = TSVResultWriter()

    def config(self, **kwargs):
        with self.driver.session() as session:
            result = session.run("CALL dbms.listConfig")
            table = None
            last_category = None
            for record in result:
                name = record["name"]
                category, _, _ = name.partition(".")
                if category != last_category:
                    if table is not None:
                        table.echo(header_style={"fg": "cyan"})
                        click.echo()
                    table = Table(["name", "value"], field_separator=u" = ", padding=0, auto_align=False, header=0)
                table.append((name, record["value"]))
                last_category = category
            table.echo(header_style={"fg": self.meta_colour})

    def kernel(self, **kwargs):
        with self.driver.session() as session:
            result = session.run("CALL dbms.queryJmx", {"query": "org.neo4j:instance=kernel#0,name=Kernel"})
            table = Table(["key", "value"], field_separator=u" = ", padding=0, auto_align=False, header=0)
            for record in result:
                attributes = record["attributes"]
                for key, value_dict in sorted(attributes.items()):
                    value = value_dict["value"]
                    if key.endswith("Date") or key.endswith("Time"):
                        try:
                            value = datetime.fromtimestamp(value / 1000).isoformat(" ")
                        except:
                            pass
                    table.append((key, value))
            table.echo(header_style={"fg": self.meta_colour})

class ConsoleError(Exception):

    pass


# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
# Copyright (C) 2019 Northwestern University.
#
# Invenio-Cli is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.

"""Invenio module to ease the creation and management of applications."""

import os
from pathlib import Path

import click

from .helpers.cli_config import CLIConfig
from .helpers.commands import Commands, ContainerizedCommands, LocalCommands
from .helpers.cookiecutter_wrapper import CookiecutterWrapper
from .helpers.docker_helper import DockerHelper

@click.group()
@click.version_option()
def cli():
    """Initialize CLI context."""

@cli.command()
@click.argument('flavour', type=click.Choice(['RDM'], case_sensitive=False),
                default='RDM', required=False)
@click.option('-t', '--template', required=False,
              help='Cookiecutter path or git url to template')
@click.option('-c', '--checkout', required=False,
              help='Branch, tag or commit to checkout if --template is a git url')  # noqa
def init(flavour, template, checkout):
    """Initializes the application according to the chosen flavour."""
    click.secho('Initializing {flavour} application...'.format(
        flavour=flavour), fg='green')

    template_checkout = (template, checkout)
    cookiecutter_wrapper = CookiecutterWrapper(flavour, template_checkout)

    try:
        click.secho("Running cookiecutter...", fg='green')
        project_dir = cookiecutter_wrapper.cookiecutter()

        click.secho("Writing invenio-cli config file...", fg='green')
        saved_replay = cookiecutter_wrapper.get_replay()
        CLIConfig.write(project_dir, flavour, saved_replay)

        click.secho("Creating logs directory...", fg='green')
        os.mkdir(Path(project_dir) / "logs")

    except Exception as e:
        click.secho(str(e), fg='red')

    finally:
        cookiecutter_wrapper.remove_config()

@cli.command()
@click.option('--pre', default=False, is_flag=True,
              help='If specified, allows the installation of alpha releases')
@click.option('--lock/--skip-lock', default=True, is_flag=True,
              help='Lock dependencies or avoid this step')
def install(pre, lock):
    """Installs the  project locally.

    Installs dependencies, creates instance directory,
    links invenio.cfg + templates, copies images and other statics and finally
    builds front-end assets.
    """
    cli_config = CLIConfig()
    commands = LocalCommands(cli_config)
    commands.install(pre=pre, lock=lock)

@cli.command()
@click.option('-f', '--force', default=False, is_flag=True,
              help='Force recreation of db tables, ES indices, queues...')
def services(force):
    """Starts DB, ES, queue and cache services and ensures they are setup.

    --force destroys and resets services
    """
    cli_config = CLIConfig()
    commands = LocalCommands(cli_config)
    commands.services(force=force)

@cli.command()
@click.option('--pre', default=False, is_flag=True,
              help='If specified, allows the installation of alpha releases')
@click.option('-f', '--force', default=False, is_flag=True,
              help='Force recreation of db tables, ES indices, queues...')
@click.option('--install-js/--no-install-js', default=True, is_flag=True,
              help="(re-)Install JS dependencies, defaults to True")
def containerize(pre, force, install_js):
    """Setup and run all containers (docker-compose.full.yml).

    Think of it as a production compilation build + running.
    """
    cli_config = CLIConfig()
    commands = ContainerizedCommands(
        cli_config,
        DockerHelper(cli_config.get_project_shortname(), local=False)
    )

    commands.containerize(pre=pre, force=force, install=install_js)

@cli.command()
@click.option('--local/--containers', default=True, is_flag=True,
              help='Which environment to build, it defaults to local')
def demo(local):
    """Populates instance with demo records."""
    cli_config = CLIConfig()
    commands = Commands(cli_config, local)
    commands.demo()

@cli.command()
@click.option('--host', '-h',  default='127.0.0.1',
              help='bind address')
@click.option('--port', '-p',  default=5000,
              help='bind port')
def run(host, port):
    """Starts the local development server.

    NOTE: this only makes sense locally so no --local option
    """
    cli_config = CLIConfig()
    commands = LocalCommands(cli_config)
    commands.run(host=host, port=str(port))

@cli.command()
@click.option('--install-js/--no-install-js', default=False, is_flag=True,
              help='(re-)Install JS dependencies, defaults to False')
def update(install_js):
    """Updates the current application static/assets files."""
    cli_config = CLIConfig()
    commands = LocalCommands(cli_config)
    commands.update_statics_and_assets(install=install_js)

@cli.command()
@click.option('-v', '--verbose', default=False, is_flag=True, required=False,
              help='Verbose mode will show all logs in the console.')
def destroy(verbose):
    """Removes all associated resources (containers, images, volumes)."""
    cli_config = CLIConfig()
    commands = Commands(cli_config, False)
    commands.destroy()

@cli.command()
def stop():
    """Stops containers."""
    cli_config = CLIConfig()
    commands = Commands(cli_config, False)
    commands.stop()

@cli.command()
@click.option('-v', '--verbose', default=False, is_flag=True, required=False,
              help='Verbose mode will show all logs in the console.')
def upgrade(verbose):
    """Upgrades the current application to the specified newer version."""
    click.secho('TODO: Implement upgrade command', fg='red')


from string import ascii_lowercase
from field_generator import *

class Game:
    def __init__(self, fields, players):
        """
        creates the field ( matrix )
        players and the fields ( the ships )
        """
        self.fields = fields
        self._players = players
        self._current = 0
        self.matrix = [[["~" for _ in range(10)] for _ in range(10)] for _ in range(2)]

    def get_player(self, show=False):
        """
        return the opposite player and the current player
        """
        if show:
            print("Field of Player {}".format(1 if self._current else 2))
        else:
            return self._current + 1

    def shoot_at(self, tupl):
        """
        calls other function to check either user missed or shot
        """
        if not self.fields.shoot_at(tupl, self._current):
            if self._current:
                self._current = 0
            else:
                self._current = 1

    def field_with_ships(self):
        """
        prints field with ships
        """
        count = 0
        curr = self.matrix[self._current]
        for i in self.fields.ships[self._current]:
            if i.vertical:
                if i.bool:
                    count += 1
                for g in range(i.length):
                    if not i.hit[g]:
                        curr[i.bow[0]][i.bow[1] + g] = "X"
            else:
                if i.bool:
                    count += 1
                for g in range(i.length):
                    if not i.hit[g]:
                        curr[i.bow[0] + g][i.bow[1]] = "X"

        print("{} of {} destroyed!".format(10 - count, len(self.fields.ships[self._current])))
        if count == 0:
            print("player {} wins!".format(self._players[self._current].name))
            exit()
        for miss in self.fields.missed[self._current]:
            curr[miss[0]][miss[1]] = "o"
        print("    a b c d e f g h i j")
        print()
        for item in range(len(curr)):
            if item == 9:
                print(item + 1, end="  ")
            else:
                print(item + 1, end="   ")
            for let in curr[item]:
                print(let, end=" ")
            print()

        print()

class Player:
    """
    creates the players
    """

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

class Field:
    """
    works with ships and gives the result of where the
    player shot and if he did returns it
    """

    def __init__(self, ships):
        self.ships = ships
        self.missed = [[], []]

    def shoot_at(self, tupl, index):
        for i in self.ships[index]:
            if i.vertical:
                if i.bow[0] == tupl[0]:
                    for ln in range(i.length):
                        if i.bow[1] + ln == tupl[1]:
                            if i.hit[ln]:
                                i.hit[ln] = False
                            if not i.hit.count(True):
                                i.bool = False
                            return True
            else:
                if i.bow[1] == tupl[1]:
                    for ln in range(i.length):
                        if i.bow[0] + ln == tupl[0]:
                            if i.hit[ln]:
                                i.hit[ln] = False
                            if not i.hit.count(True):
                                i.bool = False
                            return True
        self.missed[index].append(tupl)
        return False

class Ship:
    """
    creates ship object which has information about location,length,and the information of each point in the peace
    """

    def __init__(self, bow, length, vertical=1):
        self.bow = bow
        self.length = length
        self.bool = 1
        self.vertical = vertical
        self.hit = [True for _ in range(length)]

class Play:
    """
    Runs the game
    """
    obj1 = main()
    obj2 = main()

    @staticmethod
    def start_game():
        player1 = input("Enter Name for player 1: ")
        player2 = input("Enter Name for player 2: ")
        ships1 = []
        for i in Play.obj1:
            ships1.append(Ship((i[0]), i[1], i[2]))
        ships2 = []
        for i in Play.obj2:
            ships2.append(Ship((i[0]), i[1], i[2]))

        game1 = Game(Field((ships1, ships2)), (Player(player1), Player(player2)))
        print("Game Battleship")
        while True:

            game1.get_player(True)
            game1.field_with_ships()
            coordinates = input(" Player {}, enter move: ".format(game1.get_player()))
            try:
                a, b = int(ascii_lowercase.index(coordinates[0])), int(coordinates[1::]) - 1
                assert ((a >= 0) and (a < 10)) and ((b >= 0) and (b < 10))
                game1.shoot_at((b, a))
            except (ValueError, IndexError, AssertionError):
                print("You Entered Wrong Data\nTry again: press enter to continue")
                input()

    @staticmethod
    def display_created_fields():
        """
        if you need, it displays fields of players
        """
        field_1 = [[" " for _ in range(10)] for _ in range(10)]
        field_2 = [[" " for _ in range(10)] for _ in range(10)]
        for g in Play.obj1:
            if g[2]:
                for i in range(g[1]):
                    field_1[g[0][0]][g[0][1] + i] = "#"
            else:
                for i in range(g[1]):
                    field_1[g[0][0] + i][g[0][1]] = "#"
        for i in field_1:
            print(i)
        print()
        for g in Play.obj2:
            if g[2]:
                for i in range(g[1]):
                    field_2[g[0][0]][g[0][1] + i] = "#"
            else:
                for i in range(g[1]):
                    field_2[g[0][0] + i][g[0][1]] = "#"
        for i in field_2:
            print(i)

if __name__ == '__main__':
    Play.start_game()
    # uncomment to see the fields before game
    # Play.display_created_fields()


import xlrd
loc ="E:\saurabh\project\\saurabha_bunary.xlsx"
wb=xlrd.open_workbook(loc)
sheet=wb.sheet_by_index(0)
sheet.cell_value(0,0)
r = sheet.nrows
for i in range(r):
    for j in range(sheet.ncols):
        print(int(str(int(sheet.cell_value(i,j))),2))
    print()


with open('./valve_original.ppm', 'r') as ppm:
	data = ppm.read()
	values = data.split()

	tmp = '\n'.join(values[0:11])
	values = values[11:-1]

pixels = [values[n:n+3] for n in range(0, len(values), 3)]

for pixel in pixels:

	gray = round((int(pixel[0])+ int(pixel[1]) + int(pixel[2]))/3)
	pixel[0] = gray
	pixel[1] = gray
	pixel[2] = gray

pixels = ' '.join([str(item) for sublist in pixels for item in sublist])

print(tmp)

f = open('./test_gray.ppm', 'r+')
f.write(tmp+" " +pixels)
f.close()


class MusicPlayerRemote:

    """
    DATEN ÜBERTRAGUNG

    import pickle
    pickle.dumps({'foo': 'bar'})
    pickle.loads()
    {'foo': 'bar'}

    """

    def __init__(self, ip="127.0.0.1", port=0, showLog=False):
        """
        :type ip: str
        :param ip: the IP of the Musicplayer

        :type port: int
        :param port: the IP of the Musicplayer

        standart: searching on the current pc
        """

        if not port:
            globalMPports.readFile()
            if globalMPports.ports:
                port = globalMPports.ports[0]

        self.cl = Client(ip=ip, port=port, react=self.react, printLog=showLog)

        self.recieved = False

        # DATA VARS NO TOUCHING

        self._title = "" # Cur title
        self._time = 0.0 # Cur time
        self._duration = 0.0 # Duration of cur title
        self._vol = 0.0 # Volume (Windows)
        self._volp = 0.0 # Volume (Player)

        # TEMPORARY
        self._file = "" # a tmp file str from the last requested id

        self._playlistLen = 0
        self._playlist = []

    # control

    def stop(self):
        """
        stops the remote control

        :rtype: bool
        :return: succsess
        """

    def start(self):
        """
        starts the connection

        :rtype: bool
        :return: succsess
        """

    def react(self, dataRaw):
        """
        reacts to the data sent from the server

        :param dataRaw: data
        :type dataRaw: str
        """

        data = dataRaw.split("_")

        if data[0] == "get":
            if data[1] == "title":
                self._title = data[2]
            elif data[1] == "time":
                self._time = data[2]
            elif data[1] == "duration":
                self._duration = data[2]
            elif data[1] == "vol":
                self._vol = data[2]
            elif data[1] == "volp":
                self._volp = data[2]
            elif data[1] == "file":
                self._file = data[2]
            elif data[1] == "playlistlen":
                self._playlistLen = data[2]
            else:
                return

            self.recieved = True

    def get(self, var, wait=True):
        """
        do the waiting and recieving the info

        :param var: the data for waiting
        :type var: str
        :param wait: wait till reci?
        :type wait: bool
        """

        self.recieved = False
        self.cl.send("get_" + var)
        while not self.recieved and wait:
            time.sleep(0.1)

    # GET

    # GET (Interface)
    def getTitle(self):
        """
        :rtype: str
        :return: returns the title
        """
        self.get("title")
        return self._title
    title = property(getTitle)

    def getTime(self):
        """
        :rtype: float
        :return: the time (current playtime) in sec
        """
        self.get("time")
        return self._time
    time = property(getTime)

    def getDuration(self):
        """
        :rtype: float
        :return: the time (current playtime) in sec
        """
        self.get("duration")
        return self._duration
    duration = property(getDuration)

    def getVol(self):
        """
        :rtype: float
        :return: the cur windows vol
        """
        self.get("vol")
        return self._vol
    vol = property(getVol)

    def getVolp(self):
        """
        :rtype: float
        :return: the cur player vol
        """
        self.get("volp")
        return self._volp
    volp = property(getVolp)

    # GET (Programming)
    def getFileById(self, num):
        """
        :param num: the id of the playlist position
        :type num: int

        :return: the fileID of the playlist postion
        :rtype: str
        """
        self.get("file")
        return self._file

    def getPlaylistLen(self):
        """
        :return: length of playlist
        :rtype: int
        """
        self.get("playlistlen")
        return self._playlistLen

    def getPlaylist(self):
        """
        :return: the playlist
        :rtype: list
        """

        plLen = self.getPlaylistLen()
        self._playlist = []
        for x in range(plLen):
            self._playlist.append(self.getFileById(x))

        return self._playlist
    playlist = property(getPlaylist)

    def getMusicNameByFile(self, file):
        pass
    def getMusicFileByFile(self, file):
        pass
    def getMusicPathByFile(self, file):
        pass
    def getMusicFullnameByFile(self, file):
        pass

    # SET

    # SET (Player)

    def setPlayingStatus(self, status=2):
        pass
    def setMuteStatus(self, status=2):
        pass

    def playNext(self):
        pass
    def delById(self, num):
        pass
    def delByFile(self, file):
        pass

    def queueById(self):
        pass
    def queueByFile(self):
        pass

    def setVol(self, vol):
        pass
    def setVolp(self, vol):
        pass

    def stopPlayer(self):
        pass

    # SET (Programming)

    def addMusic(self):
        pass
    def setPlaying(self, file):
        pass
    def makePlaylist(self):
        pass

    def printRemote(self):
        pass
    def printHeadRemote(self):
        pass
    def printBodyRemote(self):
        pass
    def printFootRemote(self):
        pass

    def directReact(self, i):
        pass
    def directInput(self, i):
        pass

# noinspection PyTypeChecker
class MusicPlayerBetterRemoteControl(threading.Thread):
    def __init__(self, systray=True, random=True, expandRange=2, stop_del=False, scanner_active=True, balloonTip=True,
                 killMeAfterEnd=True, remote=True, remotePort=4554, selfprint=False):
        super().__init__()

        self.debug = False

        self.music = {"all_files": 0, "all_dirs": 0, "active": []}
        self.find_music_out = {}

        self.systray = None
        self.systrayon = systray
        self.balloonTip = balloonTip
        self.killMeAfterEnd = killMeAfterEnd
        self.remote = True
        self.remotePort = remotePort
        self.selfprint = selfprint

        self.volume = Volume.getVolume()
        self.volumep = 0.5

        # stop the musicplayer while hovering over file 1 and pressing 'del'-button
        self.stop_del = stop_del
        self.randomizer = random
        self.scanner_active = scanner_active
        # noinspection PyGlobalUndefined
        global musicrun
        musicrun = True

        self.starttime = 0
        self.hardworktime = 0
        self.musicrun = True
        self.playlist = []
        self.pershuffel = False

        self.running = False
        self.playing = False
        self.exitn = False
        self.allowPrint = False
        self.autorefresh = True

        self.player = pyglet.media.Player()
        self.timer = TimerC()
        self.scanner = Scanner(self.react)
        self.spl = SplatoonC()

        self.skip_del = False
        self.paused = False
        self.pause_type = ""
        self.muted = False
        self.mute_vol = 1
        self.con_main = "pl"
        self.con_main_last = None
        self.con_cont = "set"
        self.change = ""

        self.last_print = 0
        self.last_print_auto = 0

        self.cur_Input = ""
        self.cur_Pos = 0
        self.expandRange = expandRange

        self.searching = False
        self.searchlist = []
        self.cur_Search = ""

        self.notifications = []

        self.tmp_pl_input_1 = []
        self.tmp_pl_input_2 = []
        self.tmp_pl_output_1 = []
        self.tmp_pl_output_2 = []

        self.musiclist = {"names": []}
        self.multiplaylists = {}
        self.genre = []
        self.musicDir = ""

    def addMusic(self, key, cusPath=False, genre=False, noList=False, printStaMSG=True, printEndMSG=True,
                 makeNoti=False):  # key (AN, LIS)

        """
        adds music

        :param key: the key of the id (normal id, mpl id)
        :param cusPath: defines the path for a custom path (ignores the key)
        :param genre: forces a genre input (?)
        :param noList: only allows key to be a normal id
        :param printStaMSG: clears the screen and prints the start msg
        :param printEndMSG: prints the finished msg
        :param makeNoti: make a notification after finishing
        :return: success
        """

    def resetInterface(self):
        """
        resets interface
        :return:
        """

    def make_playlist(self):
        """
        makes the playlist

        :return:
        """

    def shufflePL(self, first=False):
        """
        reroll everthing

        :param first: also the current playing
        :return:
        """

    def refresh(self, title=False, printme=True):
        """
        refresh the following
        :param title:
        :param printme:
        :return:
        """

    def showBalloonTip(self):
        """
        do we need it?
        :return:
        """

    def rerollThis(self):
        """
        reroll the current position (stream/control)

        :return:
        """

    def sortPL(self):
        """
        sorts the PL
        :return:
        """

    def sortPL_name(self):
        """
        sorts the pl by name
        :return:
        """
    def sortPL_an(self):
        """
        sorts the PL by an
        :return:
        """
    # Options

    def play(self):
        """
        play
        :return:
        """

    def pause(self):
        """
        pause
        :return:
        """

    def switch(self):
        if self.paused:
            self.play()
        else:
            self.pause()

    def switchmute(self):
        if self.muted:
            self.unmute()
        else:
            self.mute()

    def mute(self):
        """
        mutes the player
        :return:
        """

    def unmute(self):
        """
        unmutes the player
        :return:
        """

    def stop(self):
        """
        stops the REMOTE player
        :return:
        """

    def next(self, skipthis=False):
        """
        play the next

        :param skipthis: ?
        :return:
        """

    def DelById(self, num):
        """
        del the file by id

        :param num:
        :return:
        """

    def DelByFile(self, plfile):
        """
        del the file by file name
        :param plfile:
        :return:
        """

    def vol(self, vol):
        """
        changes the windows volume
        :param vol:
        :return:
        """

    def volp(self, vol):
        """
        changes the player volume
        :param vol:
        :return:
        """

    def queueById(self, pos):
        """
        queue the track by pos (?)
        :param pos:
        :return:
        """

    def queueByFile(self, plfile):
        """
        queue the track by file-name
        :param plfile:
        :return:
        """

    def refreshSearch(self):
        """
        refresh the search (CLIENT)
        TODO remake from org server code
        :return:
        """

        self.cur_Pos = 0

        if self.cur_Search != "":
            namelist = []

            for x in self.playlist:
                namelist.append(self.music[x]["name"])

            found = Search(self.cur_Search, namelist)

            searchlist_name = []
            for x in found:
                searchlist_name.append(namelist[x])

            searchlist_name.sort()

            music_dir = self.music.copy()

        else:
            searchlist_name = []
            for fileX in self.playlist:
                searchlist_name.append(self.music[fileX]["name"])
            searchlist_name.sort()

        self.tmp_pl_input_1 = []
        self.tmp_pl_input_2 = []
        for name in searchlist_name:
            if len(searchlist_name) / 2 > len(self.tmp_pl_input_1):
                self.tmp_pl_input_1.append(name)
            else:
                self.tmp_pl_input_2.append(name)

        def work1():
            music_dir = self.music.copy()

            new_playlist = []
            for name in self.tmp_pl_input_1:
                for num_file in range(1, music_dir["all_files"] + 1):
                    try:
                        if name == music_dir["file" + str(num_file)]["name"]:
                            new_playlist.append("file" + str(num_file))
                            del music_dir["file" + str(num_file)]
                            break
                    except KeyError:
                        pass
            self.tmp_pl_output_1 = new_playlist

        def work2():
            music_dir = self.music.copy()

            new_playlist = []
            for name in self.tmp_pl_input_2:
                for num_file in range(1, music_dir["all_files"] + 1):
                    try:
                        if name == music_dir["file" + str(num_file)]["name"]:
                            new_playlist.append("file" + str(num_file))
                            del music_dir["file" + str(num_file)]
                            break
                    except KeyError:
                        pass
            self.tmp_pl_output_2 = new_playlist

        t1 = threading.Thread(target=work1)
        t2 = threading.Thread(target=work2)

        t1.start()
        t2.start()

        t1.join()
        t2.join()

        new_playlist = self.tmp_pl_output_1 + self.tmp_pl_output_2

        self.searchlist = new_playlist.copy()

    def run(self):
        """
        starts the connection
        :return:
        """

    def notificate(self, msg, title=None, screentime=5, maxTime=None):
        """
        make a notification
        :param msg:
        :param title:
        :param screentime:
        :param maxTime:
        :return:
        """

    def return_head_info(self):
        """
        returns the head info (CLIENT)
        :return:
        """
        # Info-Container

        outputList = ["Musicplayer: \n"]

        if self.getCur()["antype"]:
            outputList.append(
                "Playing: \n%s \nFrom %s" % (self.getCur()["andata"]["title"], self.getCur()["andata"]["animeName"]))
        else:
            outputList.append("Playing: \n%s" % self.getCur()["name"])

            outputList.append("Time: %s\\%s" % (self.timer.getTimeFor(), TimeFor(self.getCur()["loaded"].duration)))
        if self.muted:
            # output.append(int((console_data["pixx"]/2)-3)*"|"+"Muted"+int((console_data["pixx"]/2)-2)*"|")
            l1 = ""
            l2 = ""
            pre = ""
            outputList.append(
                pre + int((console_data["pixx"] / 2) - 3) * l1 + "Muted" + int((console_data["pixx"] / 2) - 2) * l2)

        return outputList

    def return_head_noti(self):
        """
        returns the head noti (CLIENT)
        :return:
        """
        # notification

        outputList = []

        oldNoti = self.notifications.copy()
        delMSG = []
        delNOT = []
        titleUsed = False

        def workAmsg(msgID):
            nonlocal titleUsed
            if oldNoti[notiID]["msgs"][msgID]["starttime"] + oldNoti[notiID]["msgs"][msgID][
                "screentime"] < time.time():  # invalid msg time
                delMSG.append((notiID, msgID))
            else:
                if oldNoti[notiID]["title"] and not titleUsed:
                    titleUsed = True
                    outputList.append(oldNoti[notiID]["title"] + ":")
                outputList.append(oldNoti[notiID]["msgs"][msgID]["msg"])

        def workANote(notiID):
            nonlocal titleUsed
            if oldNoti[notiID]["maxTime"]:
                if time.time() > oldNoti[notiID]["maxTime"] + oldNoti[notiID]["maxTimestart"]:  # invalid: MAXTIME
                    delNOT.append(notiID)
            else:
                titleUsed = False
                # if len(oldNoti[notiID]["msgs"]) == 1:
                #    workAmsg(0)
                for msgID in range(0, len(oldNoti[notiID]["msgs"])):
                    workAmsg(msgID)

                if len(oldNoti[notiID]["msgs"]) == 0:
                    delNOT.append(notiID)

        # if len(oldNoti) == 0:
        #    workANote(0)
        for notiID in range(0, len(oldNoti)):
            workANote(notiID)

        for x in range(-1, -len(delMSG) - 1, -1):
            del self.notifications[delMSG[x][0]]["msgs"][delMSG[x][1]]
        for x in range(-1, -len(delNOT) - 1, -1):
            del self.notifications[delNOT[x]]

        return outputList

    def print_head_info(self):
        for line in self.return_head_info():
            print(line)

    def print_head_noti(self):
        for line in self.return_head_noti():
            print(line)

    def print_head(self):
        # Info-Container

        self.print_head_info()

        if self.return_head_noti():
            print("\n" + console_data["pixx"] * "-" + "\n")
            self.print_head_noti()

        # sys.stdout.write(console_data[0]*"-")

    def return_body(self):
        """
        returns the body (CLIENT)
        :return:
        """
        outputList = []

        # Main-Container

        if self.con_main == "pl":
            outputList.append("Playlist: (%s)\n" % str(len(self.playlist)))

            search_done = False
            for now in range(self.expandRange):
                if not search_done:
                    if self.cur_Pos == now:
                        if self.expandRange >= len(self.playlist) - 1:
                            for word_num in range(0, len(self.playlist)):
                                if word_num + 1 < 10:
                                    word_num_str = str(word_num + 1) + "  "
                                elif word_num + 1 < 100:
                                    word_num_str = str(word_num + 1) + " "
                                else:
                                    word_num_str = str(word_num + 1)

                                if self.cur_Pos == word_num:
                                    if not self.debug:
                                        if len(self.music[self.playlist[word_num]]["name"]) > 108:
                                            outputList.append(" " + word_num_str + " * " + getPartStr(
                                                self.music[self.playlist[word_num]]["name"], 0, 108) + "...")
                                        else:
                                            outputList.append(
                                                " " + word_num_str + " * " + self.music[self.playlist[word_num]][
                                                    "name"])
                                    else:
                                        outputList.append(
                                            " " + word_num_str + " * " + self.music[self.playlist[word_num]][
                                                "name"] + "0" +
                                            self.playlist[word_num])
                                else:
                                    if not self.debug:
                                        if len(self.music[self.playlist[word_num]]["name"]) > 108:
                                            outputList.append(" " + word_num_str + "   " + getPartStr(
                                                self.music[self.playlist[word_num]]["name"], 0, 108) + "...")
                                        else:
                                            outputList.append(
                                                " " + word_num_str + "   " + self.music[self.playlist[word_num]][
                                                    "name"])
                                    else:
                                        outputList.append(
                                            " " + word_num_str + "   " + self.music[self.playlist[word_num]][
                                                "name"] + "1" +
                                            self.playlist[word_num])
                        elif 2 * self.expandRange + 1 >= len(self.playlist):
                            for word_num in range(0, 2 * self.expandRange + 1):  # + 1?
                                if word_num + 1 < 10:
                                    word_num_str = str(word_num + 1) + "  "
                                elif word_num + 1 < 100:
                                    word_num_str = str(word_num + 1) + " "
                                else:
                                    word_num_str = str(word_num + 1)

                                if self.cur_Pos == word_num:
                                    try:
                                        if not self.debug:
                                            if len(self.music[self.playlist[word_num]]["name"]) > 108:
                                                outputList.append(" " + word_num_str + " * " + getPartStr(
                                                    self.music[self.playlist[word_num]]["name"], 0, 108) + "...")
                                            else:
                                                outputList.append(
                                                    " " + word_num_str + " * " + self.music[self.playlist[word_num]][
                                                        "name"])
                                        else:
                                            outputList.append(
                                                " " + word_num_str + " * " + self.music[self.playlist[word_num]][
                                                    "name"] + "2" + self.playlist[word_num])
                                    except IndexError:
                                        pass
                                else:
                                    try:
                                        if not self.debug:
                                            if len(self.music[self.playlist[word_num]]["name"]) > 108:
                                                outputList.append(" " + word_num_str + "   " + getPartStr(
                                                    self.music[self.playlist[word_num]]["name"], 0, 108) + "...")
                                            else:
                                                outputList.append(
                                                    " " + word_num_str + "   " + self.music[self.playlist[word_num]][
                                                        "name"])
                                        else:
                                            outputList.append(
                                                " " + word_num_str + "   " + self.music[self.playlist[word_num]][
                                                    "name"] + "3" + self.playlist[word_num])
                                    except IndexError:
                                        pass
                        else:
                            for word_num in range(0, 2 * self.expandRange + 1):  # + 1? # Anfang
                                if word_num + 1 < 10:
                                    word_num_str = str(word_num + 1) + "  "
                                elif word_num + 1 < 100:
                                    word_num_str = str(word_num + 1) + " "
                                else:
                                    word_num_str = str(word_num + 1)
                                if self.cur_Pos == word_num:
                                    if not self.debug:
                                        if len(self.music[self.playlist[word_num]]["name"]) > 108:
                                            outputList.append(" " + word_num_str + " * " + getPartStr(
                                                self.music[self.playlist[word_num]]["name"], 0, 108) + "...")
                                        else:
                                            outputList.append(
                                                " " + word_num_str + " * " + self.music[self.playlist[word_num]][
                                                    "name"])
                                    else:
                                        outputList.append(
                                            " " + word_num_str + " * " + self.music[self.playlist[word_num]][
                                                "name"] + "4" +
                                            self.playlist[word_num])
                                else:
                                    if not self.debug:
                                        if len(self.music[self.playlist[word_num]]["name"]) > 108:
                                            outputList.append(" " + word_num_str + "   " + getPartStr(
                                                self.music[self.playlist[word_num]]["name"], 0, 108) + "...")
                                        else:
                                            outputList.append(
                                                " " + word_num_str + "   " + self.music[self.playlist[word_num]][
                                                    "name"])
                                    else:
                                        outputList.append(
                                            " " + word_num_str + "   " + self.music[self.playlist[word_num]][
                                                "name"] + "5" +
                                            self.playlist[word_num])
                        search_done = True
                        break

                    elif self.cur_Pos == len(self.playlist) - now - 1 and self.cur_Pos >= self.expandRange:  # Ende
                        for word_num in range(self.cur_Pos - self.expandRange - 2 + now, self.cur_Pos + 1 + now):
                            if word_num < 0:
                                continue
                            # outputList.append(word_num, self.curPos, now, self.expandRange)
                            if word_num + 1 < 10:
                                word_num_str = str(word_num + 1) + "  "
                            elif word_num + 1 < 100:
                                word_num_str = str(word_num + 1) + " "
                            else:
                                word_num_str = str(word_num + 1)
                            if self.cur_Pos == word_num:
                                if not self.debug:
                                    if len(self.music[self.playlist[word_num]]["name"]) > 108:
                                        outputList.append(" " + word_num_str + " * " + getPartStr(
                                            self.music[self.playlist[word_num]]["name"], 0, 108) + "...")
                                    else:
                                        outputList.append(
                                            " " + word_num_str + " * " + self.music[self.playlist[word_num]]["name"])
                                else:
                                    outputList.append(
                                        " " + word_num_str + " * " + self.music[self.playlist[word_num]]["name"] + "6" +
                                        self.playlist[word_num])
                            else:
                                if not self.debug:
                                    if len(self.music[self.playlist[word_num]]["name"]) > 108:
                                        outputList.append(" " + word_num_str + "   " + getPartStr(
                                            self.music[self.playlist[word_num]]["name"], 0, 108) + "...")
                                    else:
                                        outputList.append(
                                            " " + word_num_str + "   " + self.music[self.playlist[word_num]]["name"])
                                else:
                                    outputList.append(
                                        " " + word_num_str + "   " + self.music[self.playlist[word_num]]["name"] + "7" +
                                        self.playlist[word_num])
                        search_done = True
                        break

            if not search_done:  # Mitte
                for word_num in range(self.cur_Pos - self.expandRange, self.cur_Pos + self.expandRange + 1):
                    if word_num + 1 < 10:
                        word_num_str = str(word_num + 1) + "  "
                    elif word_num + 1 < 100:
                        word_num_str = str(word_num + 1) + " "
                    else:
                        word_num_str = str(word_num + 1)
                    if self.cur_Pos == word_num:
                        if not self.debug:
                            if len(self.music[self.playlist[word_num]]["name"]) > 108:
                                outputList.append(
                                    " " + word_num_str + " * " + getPartStr(self.music[self.playlist[word_num]]["name"],
                                                                            0,
                                                                            108) + "...")
                            else:
                                outputList.append(
                                    " " + word_num_str + " * " + self.music[self.playlist[word_num]]["name"])
                        else:
                            outputList.append(
                                " " + word_num_str + " * " + self.music[self.playlist[word_num]]["name"] + "10" +
                                self.playlist[word_num])
                    else:
                        if not self.debug:
                            if len(self.music[self.playlist[word_num]]["name"]) > 108:
                                outputList.append(
                                    " " + word_num_str + "   " + getPartStr(self.music[self.playlist[word_num]]["name"],
                                                                            0,
                                                                            108) + "...")
                            else:
                                outputList.append(
                                    " " + word_num_str + "   " + self.music[self.playlist[word_num]]["name"])
                        else:
                            outputList.append(
                                " " + word_num_str + "   " + self.music[self.playlist[word_num]]["name"] + "11" +
                                self.playlist[word_num])

        elif self.con_main == "details":
            outputList.append("Details:\n")
            outputList.append("Duration: " + str(TimeFor(self.music["file1"]["loaded"].duration)))

            if self.music[self.playlist[self.cur_Pos]]["antype"]:
                outputList.append("Title: " + str(self.music[self.playlist[self.cur_Pos]]["andata"]["title"]))
                outputList.append(
                    "Interpreter: " + str(self.music[self.playlist[self.cur_Pos]]["andata"]["interpreter"]))
                outputList.append("Musictype: " + str(self.music[self.playlist[self.cur_Pos]]["andata"]["musictype"]))
                outputList.append("Animename: " + str(self.music[self.playlist[self.cur_Pos]]["andata"]["animeName"]))
                outputList.append("Season: " + str(self.music[self.playlist[self.cur_Pos]]["andata"]["animeSeason"]))
                outputList.append("Type: " + str(self.music[self.playlist[self.cur_Pos]]["andata"]["animeType"]) +
                                  str(self.music[self.playlist[self.cur_Pos]]["andata"]["animeTypeNum"]))

            outputList.append("Filename: " + self.music[self.playlist[self.cur_Pos]]["name"])
            outputList.append("Album: " + self.music[self.playlist[self.cur_Pos]]["loaded"].info.album.decode())
            outputList.append("Author: " + self.music[self.playlist[self.cur_Pos]]["loaded"].info.author.decode())
            outputList.append("Comment: " + self.music[self.playlist[self.cur_Pos]]["loaded"].info.comment.decode())
            outputList.append("Copyright: " + self.music[self.playlist[self.cur_Pos]]["loaded"].info.copyright.decode())
            outputList.append("Genre: " + self.music[self.playlist[self.cur_Pos]]["loaded"].info.genre.decode())
            outputList.append("Title: " + self.music[self.playlist[self.cur_Pos]]["loaded"].info.title.decode())
            outputList.append("Track: " + str(self.music[self.playlist[self.cur_Pos]]["loaded"].info.track))
            outputList.append("Year: " + str(self.music[self.playlist[self.cur_Pos]]["loaded"].info.year))

        elif self.con_main == "info":
            outputList.append("Infos:\n")

            outputList.append("\nPlayer:\n")

            outputList.append("Vol: " + str(Volume.getVolume()))
            outputList.append("Volplayer: " + str(self.volumep))
            outputList.append("Muted: " + str(self.muted))
            outputList.append("Playing: " + str(self.playing))
            outputList.append("Paused: " + str(self.paused))
            outputList.append("Loaded-Key: " + str(self.music["active"]))

            if self.debug:
                outputList.append("\nDebugging Details:\n")

                outputList.append("Cur-Pos: " + str(self.cur_Pos))
                outputList.append("Autorefresh: " + str(self.autorefresh))

                outputList.append("File:\n")
                outputList.append("Filename: " + self.music[self.playlist[self.cur_Pos]]["file"])
                outputList.append("Path: " + self.music[self.playlist[self.cur_Pos]]["path"])

                outputList.append("\nOther:\n")

                outputList.append("Scanner-Status: " + str(self.scanner.is_alive()))
                outputList.append("Timer direct: " + str(self.timer.getTime()))
                outputList.append("Last print: " + str(self.last_print))

        elif self.con_main == "spl":
            outputList += self.spl.returnmain()
            # self.spl.printit(False)

        elif self.con_main == "search":
            # outputList.append(self.searchlist)
            outputList.append("Search: (%s)\n" % str(len(self.searchlist)))

            search_done = False
            for now in range(self.expandRange):
                if not search_done:
                    if self.cur_Pos == now:
                        if self.expandRange >= len(self.searchlist) - 1:
                            for word_num in range(0, len(self.searchlist)):
                                if word_num + 1 < 10:
                                    word_num_str = str(word_num + 1) + "  "
                                elif word_num + 1 < 100:
                                    word_num_str = str(word_num + 1) + " "
                                else:
                                    word_num_str = str(word_num + 1)

                                if self.cur_Pos == word_num:
                                    if not self.debug:
                                        if len(self.music[self.searchlist[word_num]]["name"]) > 108:
                                            outputList.append(" " + word_num_str + " * " + getPartStr(
                                                self.music[self.searchlist[word_num]]["name"], 0, 108) + "...")
                                        else:
                                            outputList.append(
                                                " " + word_num_str + " * " + self.music[self.searchlist[word_num]][
                                                    "name"])
                                    else:
                                        outputList.append(
                                            " " + word_num_str + " * " + self.music[self.searchlist[word_num]][
                                                "name"] + "0" + self.searchlist[word_num])
                                else:
                                    if not self.debug:
                                        if len(self.music[self.searchlist[word_num]]["name"]) > 108:
                                            outputList.append(" " + word_num_str + "   " + getPartStr(
                                                self.music[self.searchlist[word_num]]["name"], 0, 108) + "...")
                                        else:
                                            outputList.append(
                                                " " + word_num_str + "   " + self.music[self.searchlist[word_num]][
                                                    "name"])
                                    else:
                                        outputList.append(
                                            " " + word_num_str + "   " + self.music[self.searchlist[word_num]][
                                                "name"] + "1" + self.searchlist[word_num])
                        elif 2 * self.expandRange + 1 >= len(self.searchlist):
                            for word_num in range(0, 2 * self.expandRange + 1):  # + 1?
                                if word_num + 1 < 10:
                                    word_num_str = str(word_num + 1) + "  "
                                elif word_num + 1 < 100:
                                    word_num_str = str(word_num + 1) + " "
                                else:
                                    word_num_str = str(word_num + 1)

                                if self.cur_Pos == word_num:
                                    try:
                                        if not self.debug:
                                            if len(self.music[self.searchlist[word_num]]["name"]) > 108:
                                                outputList.append(" " + word_num_str + " * " + getPartStr(
                                                    self.music[self.searchlist[word_num]]["name"], 0, 108) + "...")
                                            else:
                                                outputList.append(
                                                    " " + word_num_str + " * " + self.music[self.searchlist[word_num]][
                                                        "name"])
                                        else:
                                            outputList.append(
                                                " " + word_num_str + " * " + self.music[self.searchlist[word_num]][
                                                    "name"] + "2" + self.searchlist[word_num])
                                    except IndexError:
                                        pass
                                else:
                                    try:
                                        if not self.debug:
                                            if len(self.music[self.searchlist[word_num]]["name"]) > 108:
                                                outputList.append(" " + word_num_str + "   " + getPartStr(
                                                    self.music[self.searchlist[word_num]]["name"], 0, 108) + "...")
                                            else:
                                                outputList.append(
                                                    " " + word_num_str + "   " + self.music[self.searchlist[word_num]][
                                                        "name"])
                                        else:
                                            outputList.append(
                                                " " + word_num_str + "   " + self.music[self.searchlist[word_num]][
                                                    "name"] + "3" + self.searchlist[word_num])
                                    except IndexError:
                                        pass
                        else:
                            for word_num in range(0, 2 * self.expandRange + 1):  # + 1? # Anfang
                                if word_num + 1 < 10:
                                    word_num_str = str(word_num + 1) + "  "
                                elif word_num + 1 < 100:
                                    word_num_str = str(word_num + 1) + " "
                                else:
                                    word_num_str = str(word_num + 1)
                                if self.cur_Pos == word_num:
                                    if not self.debug:
                                        if len(self.music[self.searchlist[word_num]]["name"]) > 108:
                                            outputList.append(" " + word_num_str + " * " + getPartStr(
                                                self.music[self.searchlist[word_num]]["name"], 0, 108) + "...")
                                        else:
                                            outputList.append(
                                                " " + word_num_str + " * " + self.music[self.searchlist[word_num]][
                                                    "name"])
                                    else:
                                        outputList.append(
                                            " " + word_num_str + " * " + self.music[self.searchlist[word_num]][
                                                "name"] + "4" + self.searchlist[word_num])
                                else:
                                    if not self.debug:
                                        if len(self.music[self.searchlist[word_num]]["name"]) > 108:
                                            outputList.append(" " + word_num_str + "   " + getPartStr(
                                                self.music[self.searchlist[word_num]]["name"], 0, 108) + "...")
                                        else:
                                            outputList.append(
                                                " " + word_num_str + "   " + self.music[self.searchlist[word_num]][
                                                    "name"])
                                    else:
                                        outputList.append(
                                            " " + word_num_str + "   " + self.music[self.searchlist[word_num]][
                                                "name"] + "5" + self.searchlist[word_num])
                        search_done = True
                        break

                    elif self.cur_Pos == len(self.searchlist) - now - 1 and self.cur_Pos >= self.expandRange:  # Ende
                        for word_num in range(self.cur_Pos - self.expandRange - 2 + now, self.cur_Pos + 1 + now):
                            if word_num < 0:
                                continue
                            # outputList.append(word_num, self.curPos, now, self.expandRange)
                            if word_num + 1 < 10:
                                word_num_str = str(word_num + 1) + "  "
                            elif word_num + 1 < 100:
                                word_num_str = str(word_num + 1) + " "
                            else:
                                word_num_str = str(word_num + 1)
                            if self.cur_Pos == word_num:
                                if not self.debug:
                                    if len(self.music[self.searchlist[word_num]]["name"]) > 108:
                                        outputList.append(" " + word_num_str + " * " + getPartStr(
                                            self.music[self.searchlist[word_num]]["name"], 0, 108) + "...")
                                    else:
                                        outputList.append(
                                            " " + word_num_str + " * " + self.music[self.searchlist[word_num]]["name"])
                                else:
                                    outputList.append(
                                        " " + word_num_str + " * " + self.music[self.searchlist[word_num]][
                                            "name"] + "6" + self.searchlist[word_num])
                            else:
                                if not self.debug:
                                    if len(self.music[self.searchlist[word_num]]["name"]) > 108:
                                        outputList.append(" " + word_num_str + "   " + getPartStr(
                                            self.music[self.searchlist[word_num]]["name"], 0, 108) + "...")
                                    else:
                                        outputList.append(
                                            " " + word_num_str + "   " + self.music[self.searchlist[word_num]]["name"])
                                else:
                                    outputList.append(
                                        " " + word_num_str + "   " + self.music[self.searchlist[word_num]][
                                            "name"] + "7" + self.searchlist[word_num])
                        search_done = True
                        break

            if not search_done:  # Mitte
                for word_num in range(self.cur_Pos - self.expandRange, self.cur_Pos + self.expandRange + 1):
                    if word_num + 1 < 10:
                        word_num_str = str(word_num + 1) + "  "
                    elif word_num + 1 < 100:
                        word_num_str = str(word_num + 1) + " "
                    else:
                        word_num_str = str(word_num + 1)
                    if self.cur_Pos == word_num:
                        if not self.debug:
                            if len(self.music[self.searchlist[word_num]]["name"]) > 108:
                                outputList.append(
                                    " " + word_num_str + " * " + getPartStr(
                                        self.music[self.searchlist[word_num]]["name"],
                                        0, 108) + "...")
                            else:
                                outputList.append(
                                    " " + word_num_str + " * " + self.music[self.searchlist[word_num]]["name"])
                        else:
                            outputList.append(
                                " " + word_num_str + " * " + self.music[self.searchlist[word_num]]["name"] + "10" +
                                self.searchlist[word_num])
                    else:
                        if not self.debug:
                            if len(self.music[self.searchlist[word_num]]["name"]) > 108:
                                outputList.append(
                                    " " + word_num_str + "   " + getPartStr(
                                        self.music[self.searchlist[word_num]]["name"],
                                        0, 108) + "...")
                            else:
                                outputList.append(
                                    " " + word_num_str + "   " + self.music[self.searchlist[word_num]]["name"])
                        else:
                            outputList.append(
                                " " + word_num_str + "   " + self.music[self.searchlist[word_num]]["name"] + "11" +
                                self.searchlist[word_num])
        return outputList

    def print_body(self):
        for line in self.return_body():
            print(line)

    def return_foot(self):
        """
        returns the foot (CLIENT)
        :return:
        """

        outputList = []

        if self.con_cont == "set":
            outputList.append("Commands:\n")

            if not self.paused:
                outputList.append(
                    "Pause (P), Delthis (DEL), Next (N), Reroll all (RE), Reroll this (RT), Queue this (QU), Details (DEA)")
            elif self.paused:
                outputList.append(
                    "Play (P), Delthis (DEL), Next (N), Reroll all (RE), Reroll this (RT), Queue this (QU), Details (DEA)")

            if self.con_main == "spl":
                outputList += self.spl.returncom()
                # self.spl.printcom()

            outputList.append("\nInput:\n%s" % self.cur_Input)

        elif self.con_cont == "search":
            outputList.append("Commands: (with UPPER LETTERs)\n")

            outputList.append("Play this (P), Delthis (DEL), Queue this (QU)")

            outputList.append("\nInput: %s" % self.cur_Input.upper())

            outputList.append("\nSearch: (with lower letters)\n")
            outputList.append("Input: %s" % self.cur_Search)

        elif self.con_cont == "conf":
            outputList.append("Confirm\n")
            outputList.append("Y/N")

        elif self.con_cont == "cont":
            outputList.append("Continue?\n")
            outputList.append("Press something")

        elif self.con_cont == "volp":
            outputList.append("Change Volume (Player):\n")
            outputList.append("Current: " + str(self.volumep))

            outputList.append("\n" + self.cur_Input)

        elif self.con_cont == "volw":
            self.volume = Volume.getVolume()
            outputList.append("Change Volume (Windows):\n")
            outputList.append("Current: " + str(self.volume))

            outputList.append("\n" + self.cur_Input)

        elif self.con_cont == "spe":
            outputList.append("Change Effectduration (Spl):\n")
            outputList.append("Current: " + str(self.spl.Effect))

            outputList.append("\n" + self.cur_Input)

        elif self.con_cont == "add":
            outputList.append("Add new Music:\n")

            cur = ""
            for mus in self.music["active"]:
                cur += mus + ", "
            cur = cur.rstrip(", ")

            outputList.append("Current: " + cur)

            outputList.append("\n" + self.cur_Input)

        return outputList

    def print_foot(self):
        for line in self.return_foot():
            print(line)

    def returnit(self):
        outputList = []

        # Head-Container (Info + Noti)
        outputList += self.return_head_info()

        if self.return_head_noti():
            outputList += ["\n" + console_data["pixx"]*"-" + "\n"]
            outputList += self.return_head_noti()

        outputList += ["\n" + console_data["pixx"]*"-" + "\n"]

        # Main-Container
        outputList += self.return_body()

        outputList += ["\n" + console_data["pixx"]*"-" + "\n"]
        # Control-Container
        outputList += self.return_foot()

        return outputList

    def printit(self):
        """
        prints the output (CLIENT)
        :return:
        """
        cls()
        for line in self.returnit():
            print(line)

    def react(self, inp):
        """
        direct input from scanner

        :param inp: input from scanner
        :return:
        """

    def input(self, i):
        """
        the tasks

        :param i: input
        :return:
        """

    def getCur(self):
        """
        returns the cur track
        :return:
        """


import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions

def pytest_addoption(parser):
    parser.addoption(
        '--browser', action='store', default='chrome', help='Launch specific browser (possible Chrome or Firefox)'
    )
    parser.addoption(
        '--headless', action='store_true', default=False, help='Launch in headless mode'
    )
    parser.addoption(
        '--language', action='store', default='en-gb', help='Choose shop language'
    )

@pytest.fixture(scope='function')
def browser(request):
    _browser = request.config.getoption('browser').lower()
    _language = request.config.getoption('language')
    _is_headless = request.config.getoption('headless')
    if _browser == 'chrome':
        __chrome_options = ChromeOptions()
        __chrome_options.add_experimental_option('prefs', {'intl.accept_languages': _language})
        __chrome_options.headless = _is_headless
        browser = webdriver.Chrome(options=__chrome_options)
    elif _browser == 'firefox':
        __firefox_options = FirefoxOptions()
        __firefox_options.set_preference('intl.accept_languages', _language)
        __firefox_options.headless = _is_headless
        browser = webdriver.Firefox(options=__firefox_options)
    else:
        raise pytest.UsageError('Browser should be Chrome (default) or Firefox')

    # Add sent language to browser object for using in tests
    browser.language = _language

    yield browser

    browser.quit()


import torch
import numpy as np
from functools import reduce
from operator import mul

############################################
# set default data type to double; for GPU
# training use float
############################################
torch.set_default_dtype(torch.float64)
torch.set_default_tensor_type(torch.DoubleTensor)
# torch.set_default_dtype(torch.float32)
# torch.set_default_tensor_type(torch.FloatTensor)

VERBOSE = 1 # set to 1 to display epoch and batch losses in the training process

FINE_TUNE = 0 # set to 1 for fine-tuning a pre-trained model

############################################
# set the network architecture
############################################
N_H = 1 # the number of hidden layers
D_H = 5 # the number of neurons of each hidden layer

############################################
# for activation function definition
############################################
BENT_DEG = 0.0001

############################################
# set loss function definition
############################################
TOL_INIT = 0.02
TOL_SAFE = 0.02
TOL_LIE = 0.01
TOL_BOUNDARY = 0.05

TOL_NORM_LIE = 0
WEIGHT_LIE = 1
WEIGHT_NORM_LIE = 0

DECAY_LIE = 1
DECAY_INIT = 1
DECAY_UNSAFE = 1

############################################
# for optimization method tunning: LBFGS
############################################
LBFGS_NUM_ITER = 1
LBFGS_TOL_GRAD = 1e-05
LBFGS_TOL_CHANGE = 1e-09
LBFGS_NUM_HISTORY = 100
LBFGS_LINE_SEARCH_FUN = None

TOL_OPTIMIZER_RESET = -1
SHRINK_RATE_FACTOR = 2
FRACTION_INSTABLE_BATCH = 1000000000000000000000
NUM_BATCH_ITR = 5

############################################
# number of training epochs
############################################
EPOCHS = 10

############################################
# my own scheduling policy:
# rate = alpha / (1 + beta * epoch^gamma)
############################################
ALPHA = 0.1 # initial learning rate
BETA = 0 # if beta equals 0 then constant rate = alpha
GAMMA = 0 # when beta is nonzero, larger gamma gives faster drop of rate

############################################
# training termination flags
############################################
LOSS_OPT_FLAG = 1e-16
TOL_MAX_GRAD = 6

############################################
# for training set generation
############################################
TOL_DATA_GEN = 1e-16

DATA_EXP_I = np.array([5, 5])
    # for sampling from initial; length = prob.DIM
DATA_LEN_I = np.power(2, DATA_EXP_I)
    # the number of samples for each dimension of domain
BLOCK_EXP_I = np.array([3, 3])
    # 0 <= BATCH_EXP <= DATA_EXP
BLOCK_LEN_I = np.power(2, BLOCK_EXP_I)
    # number of batches for each dimension

DATA_EXP_U = np.array([5, 5]) # for sampling from initial; length = prob.DIM
DATA_LEN_U = np.power(2, DATA_EXP_U) # the number of samples for each dimension of domain
BLOCK_EXP_U = np.array([3, 3]) # 0 <= BATCH_EXP <= DATA_EXP
BLOCK_LEN_U = np.power(2, BLOCK_EXP_U) # number of batches for each dimension

DATA_EXP_D = np.array([8, 8]) # for sampling from initial; length = prob.DIM
DATA_LEN_D = np.power(2, DATA_EXP_D) # the number of samples for each dimension of domain
BLOCK_EXP_D = np.array([6, 6]) # 0 <= BATCH_EXP <= DATA_EXP
BLOCK_LEN_D = np.power(2, BLOCK_EXP_D) # number of batches for each dimension

############################################
# number of mini_batches
############################################
BATCHES_I = reduce(mul, list(BLOCK_LEN_I))
BATCHES_U = reduce(mul, list(BLOCK_LEN_U))
BATCHES_D = reduce(mul, list(BLOCK_LEN_D))

BATCHES = max(BATCHES_I, BATCHES_U, BATCHES_D)

############################################
# for plotting
############################################
PLOT_EXP_B = np.array([8, 8]) # sampling from domain for plotting the boundary of barrier using contour plot
PLOT_LEN_B = np.power(2, PLOT_EXP_B) # the number of samples for each dimension of domain, usually larger than superp.DATA_LEN_D

PLOT_EXP_V = np.array([6, 6]) # sampling from domain for plotting the vector field
PLOT_LEN_V = np.power(2, PLOT_EXP_V) # the number of samples for each dimension of domain, usually equal to PLOT_LEN_P

PLOT_EXP_P = np.array([6, 6]) # sampling from domain for plotting the scattering sampling points, could be equal to PLOT_EXP_V
PLOT_LEN_P = np.power(2, PLOT_EXP_P) # the number of samples for each dimension of domain

PLOT_VEC_SCALE = None


import pymysql
from django.shortcuts import render
from django.shortcuts import HttpResponse
from . import models
import json
import requests

# Create your views here.

def index(request):
    return render(request,'index.html')

def luolidia(request):
    dia=''
    dialog=[]

    if request.method == 'POST':
        dia=request.POST.get('dialogue')
        dialog.append(dia)

        url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg={}'.format(dia)
        res = requests.get(url)
        res1 = json.loads(res.text)
        res2=res1['content'].replace('{br}', '\n').replace('菲菲','小萝莉').replace('晨风机器人','小萝莉')
        dialog.append(res2)
    return render(request,'luolidia.html',{'data':dialog})

def zyddia(request):
    dia=''
    dialog=[]

    if request.method == 'POST':
        dia=request.POST.get('dialogue')
        dialog.append(dia)

        url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg={}'.format(dia)
        res = requests.get(url)
        res1 = json.loads(res.text)
        res2=res1['content'].replace('{br}', '\n').replace('菲菲','zyd').replace('晨风机器人','沙雕zyd')
        dialog.append(res2)
    return render(request,'zyddia.html',{'data':dialog})