from collections import namedtuple
import random

Word = namedtuple('Word', ['character', 'count'])

class ParseLengthError(Exception):
    pass

class NotParsedYetException(Exception):
    pass

class MarkovChain(object):
    """Hold the a chain in memory"""

    def __init__(self, order=4):
        """
        Create a new MarkovChain

        :param: order - Number of characters per word
        """

        self.order = int(order)

        if self.order <= 0:
            raise ValueError("Order must be greater than zero!")

        self._chain = {}
        self._start_words = []
        self._parsed = False
        self._existing_corpus = set()

    def _add_word_to_chain(self, word, new_character):

        if word not in self._chain:
            self._chain[word] = []

        for index, existing_words in enumerate(self._chain[word]):
            if existing_words.character == new_character:

                # Increment the existing character
                self._chain[word][index] = Word(
                    new_character,
                    existing_words.count + 1
                )

                return

        # Not found, add a new one
        self._chain[word].append(
            Word(new_character, 1)
        )

    def _get_random_word(self, key):
        """Get a weighted random Word from the chain"""

        possible_words = []

        for word in self._chain[key]:
            # HACK: Do this better
            for _ in range(word.count):
                possible_words.append(word.character)

        return random.choice(possible_words)

    def clean_text(self, raw_text):

        words = raw_text.split(" ")

        return " ".join(
            filter(lambda x: not x.startswith("@"), words)
        )

    def parse(self, raw_text):
        """Add text to the current chain.

        :param: raw_text - Input string"""

        safe_text = self.clean_text(raw_text)

        if safe_text in self._existing_corpus:
            return

        self._existing_corpus.add(safe_text)

        all_words = safe_text.split(" ")
        self._start_words.append(
            " ".join(all_words[:self.order])
        )

        self._parsed = True

        words = []

        for word in safe_text.split(" "):
            if word.startswith("@"):
                continue

            if len(words) == self.order:
                word_key = " ".join(words)
                self._add_word_to_chain(word_key, word)
                del words[0]
            words.append(word)

    def get_text(self, length=400):
        """Get text from this chain"""

        if not self._parsed:
            return ""

        if not self._chain.keys():
            return ""

        word_buffer = []
        current_length = 0

        # Start with a random key from the chain
        # Add it to the output
        # Take one of the Letters in values and use it
        # Then take the current latest

        key = random.choice(self._start_words)
        word_buffer.append(key)

        current_length += len(key)

        while len(word_buffer) < length:
            try:
                next_word = self._get_random_word(key)
                word_buffer.append(next_word)
                # HACK: Fix this later
                words = " ".join(word_buffer).split(" ")
                key = " ".join(words[-self.order:])
            except (KeyError, IndexError):
                break

        return " ".join(word_buffer)


# 判断第几天——用元组的方式
import datetime

def is_run_year(year):
    # 默认平年
    run_num = 0

    # 判断闰年的方法
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        run_num = 1

    return run_num

def main():
    # 让用户输入年份
    input_date = input('请输入一个日期（如，2020-02-11）：')

    # 解析用户输入的日期
    date = datetime.datetime.strptime(input_date, '%Y-%m-%d')
    year = date.year
    month = date.month
    day = date.day

    # 调用判断闰年的函数
    run_num = is_run_year(year)

    # 用字典数据类型解题
    day_months_dictonary = {
        1: 31,
        2: 28,
        3: 31,
        4: 30,
        5: 31,
        6: 30,
        7: 31,
        8: 31,
        9: 30,
        10: 31,
        11: 30,
        12: 31
    }

    days = 0
    days = days + day
    for i in range(1, month):
        days = days + day_months_dictonary[i]

    if run_num == 1 and month > 2:
        days = days + run_num

    print('{}是全年的第{}天'.format(input_date, days))

if __name__ == '__main__':
    main()


from django.urls import path

from . import views

urlpatterns = [
    path('', views.loginPage, name='loginPage'),
    path('usuario/',views.usuarioPage,name='usuario'),
    path('cadastro/',views.cadastroPage, name='cadastro'),
    path('edituser/',views.editUserPage,name='edituser'),
    path('logout/',views.logout_view,name='logout'),
    path('consolidados/',views.consolidadosPage,name='consolidados'),
]


import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier

# Initial data pre processing
def data_pre_process_initial(train, test):
    train.drop('AnimalID', axis=1, inplace=True)

    ## Outcome Subtype

    # Initializing Outcome Subtypes
    train['Aggressive'] = 0
    train['At Vet'] = 0
    train['Barn'] = 0
    train['Behavior'] = 0
    train['Court/Investigation'] = 0
    train['Enroute'] = 0
    train['Foster'] = 0
    train['In Foster'] = 0
    train['In Kennel'] = 0
    train['In Surgery'] = 0
    train['Medical'] = 0
    train['Offsite'] = 0
    train['Partner'] = 0
    train['Rabies Risk'] = 0
    train['SCRP'] = 0
    train['Suffering'] = 0

    # Updating Outcome Subtypes
    train.ix[train.OutcomeSubtype == 'Aggressive', 'Aggressive'] = 1
    train.ix[train.OutcomeSubtype == 'At Vet', 'At Vet'] = 1
    train.ix[train.OutcomeSubtype == 'Barn', 'Barn'] = 1
    train.ix[train.OutcomeSubtype == 'Behavior', 'Behavior'] = 1
    train.ix[train.OutcomeSubtype == 'Court/Investigation', 'Court/Investigation'] = 1
    train.ix[train.OutcomeSubtype == 'Enroute', 'Enroute'] = 1
    train.ix[train.OutcomeSubtype == 'Foster', 'Foster'] = 1
    train.ix[train.OutcomeSubtype == 'In Foster', 'In Foster'] = 1
    train.ix[train.OutcomeSubtype == 'In Kennel', 'In Kennel'] = 1
    train.ix[train.OutcomeSubtype == 'In Surgery', 'In Surgery'] = 1
    train.ix[train.OutcomeSubtype == 'Medical', 'Medical'] = 1
    train.ix[train.OutcomeSubtype == 'Offsite', 'Offsite'] = 1
    train.ix[train.OutcomeSubtype == 'Partner', 'Partner'] = 1
    train.ix[train.OutcomeSubtype == 'Rabies Risk', 'Rabies Risk'] = 1
    train.ix[train.OutcomeSubtype == 'SCRP', 'SCRP'] = 1
    train.ix[train.OutcomeSubtype == 'Suffering', 'Suffering'] = 1

    # Name availability
    train['Name_bool'] = pd.isnull(train['Name']).astype(int)
    test['Name_bool'] = pd.isnull(test['Name']).astype(int)

    # OutcomeType
    train.ix[train.OutcomeType == 'Return_to_owner', 'Target'] = 0
    train.ix[train.OutcomeType == 'Euthanasia', 'Target'] = 1
    train.ix[train.OutcomeType == 'Adoption', 'Target'] = 2
    train.ix[train.OutcomeType == 'Transfer', 'Target'] = 3
    train.ix[train.OutcomeType == 'Died', 'Target'] = 4

    # Animal Type Cat (Binary value)
    train.ix[train.AnimalType == 'Dog', 'AnimalType_cat'] = 0
    train.ix[train.AnimalType == 'Cat', 'AnimalType_cat'] = 1

    test.ix[test.AnimalType == 'Dog', 'AnimalType_cat'] = 0
    test.ix[test.AnimalType == 'Cat', 'AnimalType_cat'] = 1

    ## SexuponOutcome

    train.ix[train.SexuponOutcome == 'Intact Female', 'SexuponOutcome_cat'] = 0
    train.ix[train.SexuponOutcome == 'Spayed Female', 'SexuponOutcome_cat'] = 1
    train.ix[train.SexuponOutcome == 'Neutered Male', 'SexuponOutcome_cat'] = 2
    train.ix[train.SexuponOutcome == 'Intact Male', 'SexuponOutcome_cat'] = 3
    train.ix[train.SexuponOutcome == 'Unknown', 'SexuponOutcome_cat'] = 4

    test.ix[test.SexuponOutcome == 'Intact Female', 'SexuponOutcome_cat'] = 0
    test.ix[test.SexuponOutcome == 'Spayed Female', 'SexuponOutcome_cat'] = 1
    test.ix[test.SexuponOutcome == 'Neutered Male', 'SexuponOutcome_cat'] = 2
    test.ix[test.SexuponOutcome == 'Intact Male', 'SexuponOutcome_cat'] = 3
    test.ix[test.SexuponOutcome == 'Unknown', 'SexuponOutcome_cat'] = 4

    # Male / Female
    train.ix[train.SexuponOutcome == 'Intact Female', 'Type_sex'] = 1
    train.ix[train.SexuponOutcome == 'Spayed Female', 'Type_sex'] = 1
    train.ix[train.SexuponOutcome == 'Neutered Male', 'Type_sex'] = 2
    train.ix[train.SexuponOutcome == 'Intact Male', 'Type_sex'] = 2
    train.ix[train.SexuponOutcome == 'Unknown', 'Type_sex'] = 3

    test.ix[test.SexuponOutcome == 'Intact Female', 'Type_sex'] = 1
    test.ix[test.SexuponOutcome == 'Spayed Female', 'Type_sex'] = 1
    test.ix[test.SexuponOutcome == 'Neutered Male', 'Type_sex'] = 2
    test.ix[test.SexuponOutcome == 'Intact Male', 'Type_sex'] = 2
    test.ix[test.SexuponOutcome == 'Unknown', 'Type_sex'] = 3

    # Sprayed / Intact
    train.ix[train.SexuponOutcome == 'Intact Female', 'sprayed'] = 1
    train.ix[train.SexuponOutcome == 'Spayed Female', 'sprayed'] = 2
    train.ix[train.SexuponOutcome == 'Neutered Male', 'sprayed'] = 2
    train.ix[train.SexuponOutcome == 'Intact Male', 'sprayed'] = 1
    train.ix[train.SexuponOutcome == 'Unknown', 'sprayed'] = 3

    test.ix[test.SexuponOutcome == 'Intact Female', 'sprayed'] = 1
    test.ix[test.SexuponOutcome == 'Spayed Female', 'sprayed'] = 2
    test.ix[test.SexuponOutcome == 'Neutered Male', 'sprayed'] = 2
    test.ix[test.SexuponOutcome == 'Intact Male', 'sprayed'] = 1
    test.ix[test.SexuponOutcome == 'Unknown', 'sprayed'] = 3

    # AgeuponOutcome
    train['AgeuponOutcome_In_Days'] = 0
    train['Age_unit'] = ''

    test['AgeuponOutcome_In_Days'] = 0
    test['Age_unit'] = ''

    for i in range(0, train.shape[0]):
        try:
            train['AgeuponOutcome_In_Days'][i] = train['AgeuponOutcome'][i].split()[0]
        except AttributeError:
            train['AgeuponOutcome_In_Days'][i] = 0
        try:
            train['Age_unit'][i] = train['AgeuponOutcome'][i].split()[1]
        except AttributeError:
            train['Age_unit'][i] = 'day'

    for i in range(0, test.shape[0]):
        try:
            test['AgeuponOutcome_In_Days'][i] = test['AgeuponOutcome'][i].split()[0]
        except AttributeError:
            test['AgeuponOutcome_In_Days'][i] = 0
        try:
            test['Age_unit'][i] = test['AgeuponOutcome'][i].split()[1]
        except AttributeError:
            test['Age_unit'][i] = 'day'

    train.replace('year', 'years', inplace=True)
    train.replace('day', 'days', inplace=True)
    train.replace('month', 'months', inplace=True)
    train.replace('week', 'weeks', inplace=True)
    test.replace('year', 'years', inplace=True)
    test.replace('day', 'days', inplace=True)
    test.replace('month', 'months', inplace=True)
    test.replace('week', 'weeks', inplace=True)

    for i in range(0, train.shape[0]):
        if train['Age_unit'][i] == 'years':
            train['AgeuponOutcome_In_Days'][i] = train['AgeuponOutcome_In_Days'][i] * 365
        if train['Age_unit'][i] == 'months':
            train['AgeuponOutcome_In_Days'][i] = train['AgeuponOutcome_In_Days'][i] * 30
        if train['Age_unit'][i] == 'weeks':
            train['AgeuponOutcome_In_Days'][i] = train['AgeuponOutcome_In_Days'][i] * 7
    for i in range(0, test.shape[0]):
        if test['Age_unit'][i] == 'years':
            test['AgeuponOutcome_In_Days'][i] = test['AgeuponOutcome_In_Days'][i] * 365
        if test['Age_unit'][i] == 'months':
            test['AgeuponOutcome_In_Days'][i] = test['AgeuponOutcome_In_Days'][i] * 30
        if test['Age_unit'][i] == 'weeks':
            test['AgeuponOutcome_In_Days'][i] = test['AgeuponOutcome_In_Days'][i] * 7

    train['AgeuponOutcome_cat'] = 2
    test['AgeuponOutcome_cat'] = 2

    for i in range(0, train.shape[0]):
        if train['AgeuponOutcome_In_Days'][i] <= 480:
            train['AgeuponOutcome_cat'][i] = 1
        if 480 < train['AgeuponOutcome_In_Days'][i] <= 2555:
            train['AgeuponOutcome_cat'][i] = 2
        if 2555 < train['AgeuponOutcome_In_Days'][i]:
            train['AgeuponOutcome_cat'][i] = 3
    for i in range(0, test.shape[0]):
        if test['AgeuponOutcome_In_Days'][i] <= 480:
            test['AgeuponOutcome_cat'][i] = 1
        if 480 < test['AgeuponOutcome_In_Days'][i] < 2555:
            test['AgeuponOutcome_cat'][i] = 2
        if 2555 < test['AgeuponOutcome_In_Days'][i]:
            test['AgeuponOutcome_cat'][i] = 3

    # Breed split
    train['Breed1'] = ''
    train['Breed2'] = ''
    train['Breed11'] = ''

    test['Breed1'] = ''
    test['Breed2'] = ''
    test['Breed11'] = ''

    for i in range(0, test.shape[0]):
        try:
            test['Breed1'][i] = test['Breed'][i].split('/')[0]
        except IndexError:
            test['Breed1'][i] = test['Breed'][i]
        try:
            test['Breed2'][i] = test['Breed'][i].split('/')[1]
        except IndexError:
            test['Breed2'][i] = 'One_Breed'
    for i in range(0, train.shape[0]):
        try:
            train['Breed1'][i] = train['Breed'][i].split('/')[0]
        except IndexError:
            train['Breed1'][i] = train['Breed'][i]
        try:
            train['Breed2'][i] = train['Breed'][i].split('/')[1]
        except IndexError:
            train['Breed2'][i] = 'One_Breed'

    for i in range(0, test.shape[0]):
        try:
            test['Breed11'][i] = test['Breed1'][i].split(' Mix')[0]
        except IndexError:
            test['Breed11'][i] = test['Breed1'][i]
    for i in range(0, train.shape[0]):
        try:
            train['Breed11'][i] = train['Breed1'][i].split(' Mix')[0]
        except IndexError:
            train['Breed11'][i] = train['Breed1'][i]

    train['Breed11'] = train['Breed11'].str.upper()
    test['Breed11'] = test['Breed11'].str.upper()

    # Mix / Not Mix
    train['Is_Mixed'] = 0
    test['Is_Mixed'] = 0
    for i in range(0, train.shape[0]):
        if train['Breed'][i].find(' Mix') >= 0:
            train['Is_Mixed'][i] = 1

    for i in range(0, test.shape[0]):
        if test['Breed'][i].find(' Mix') >= 0:
            test['Is_Mixed'][i] = 1

    # Color split
    train['Color1'] = ''
    train['Color2'] = ''
    train['Color_prin1'] = ''
    train['Shade1'] = ''
    train['Color_prin2'] = ''
    train['Shade2'] = ''

    test['Color1'] = ''
    test['Color2'] = ''
    test['Color_prin1'] = ''
    test['Shade1'] = ''
    test['Color_prin2'] = ''
    test['Shade2'] = ''

    for i in range(0, train.shape[0]):
        train['Color1'][i] = train['Color'][i].split('/')[0]
        try:
            train['Color2'][i] = train['Color'][i].split('/')[1]
        except IndexError:
            train['Color2'][i] = ''
        train['Color_prin1'][i] = train['Color1'][i].split(' ')[0]
        try:
            train['Shade1'][i] = train['Color1'][i].split(' ')[1]
        except IndexError:
            train['Shade1'][i] = ''
        train['Color_prin2'][i] = train['Color2'][i].split(' ')[0]
        try:
            train['Shade2'][i] = train['Color2'][i].split(' ')[1]
        except IndexError:
            train['Shade2'][i] = ''

    for i in range(0, test.shape[0]):
        test['Color1'][i] = test['Color'][i].split('/')[0]
        try:
            test['Color2'][i] = test['Color'][i].split('/')[1]
        except IndexError:
            test['Color2'][i] = ''
        test['Color_prin1'][i] = test['Color1'][i].split(' ')[0]
        try:
            test['Shade1'][i] = test['Color1'][i].split(' ')[1]
        except IndexError:
            test['Shade1'][i] = ''
        test['Color_prin2'][i] = test['Color2'][i].split(' ')[0]
        try:
            test['Shade2'][i] = test['Color2'][i].split(' ')[1]
        except IndexError:
            test['Shade2'][i] = ''

    # Datetime
    train['year'] = pd.DatetimeIndex(train['DateTime']).year
    train['month'] = pd.DatetimeIndex(train['DateTime']).month
    train['day'] = pd.DatetimeIndex(train['DateTime']).day
    train['hour'] = pd.DatetimeIndex(train['DateTime']).hour
    train['minute'] = pd.DatetimeIndex(train['DateTime']).minute
    train['quarter'] = pd.DatetimeIndex(train['DateTime']).quarter
    train['weekofyear'] = pd.DatetimeIndex(train['DateTime']).weekofyear

    test['year'] = pd.DatetimeIndex(test['DateTime']).year
    test['month'] = pd.DatetimeIndex(test['DateTime']).month
    test['day'] = pd.DatetimeIndex(test['DateTime']).day
    test['hour'] = pd.DatetimeIndex(test['DateTime']).hour
    test['minute'] = pd.DatetimeIndex(test['DateTime']).minute
    test['quarter'] = pd.DatetimeIndex(test['DateTime']).quarter
    test['weekofyear'] = pd.DatetimeIndex(test['DateTime']).weekofyear

    return train.shape, test.shape

# Breed data pre processing according to breed popularity
def breed_data_pre_process(data_set):
    animal_breeds = ['LABRADOR RETRIEVER', 'GERMAN SHEPHERD', 'GOLDEN RETRIEVER', 'AMERICAN BULLDOG', 'BEAGLE',
                     'FRENCH BULLDOG',
                     'YORKSHIRE TERRIER', 'MINIATURE POODLE', 'ROTTWEILER', 'BOXER', 'German Shorthair Pointer',
                     'SIBERIAN HUSKY',
                     'DACHSHUND', 'Pinscher', 'GREAT DANES', 'MINIATURE SCHNAUZER', 'AUSTRALIAN SHEPHERD',
                     'CAVALIER KING CHARLES SPANIEL', 'SHIH TZU', 'PEMBROKE WELSH CORGI', 'POMERANIAN',
                     'BOSTON TERRIER',
                     'SHETLAND SHEEPDOG', 'HAVANESE', 'MASTIFF', 'BRITTANY', 'ENGLISH SPRINGER SPANIEL', 'CHIHUAHUA',
                     'BERNESE MOUNTAIN DOG', 'COCKER SPANIEL', 'MALTESE', 'VIZSLA', 'PUG', 'WEIMARANER', 'CANE CORSO',
                     'COLLIE',
                     'NEWFOUNDLAND', 'BORDER COLLIE', 'BASSET HOUND', 'RHODESIAN RIDGEBACK',
                     'WEST HIGHLAND WHITE TERRIER',
                     'CHESAPEAKE BAY RETRIEVER', 'BULLMASTIFF', 'BICHON FRISE', 'SHIBA INU', 'AKITA',
                     'SOFT COATED WHEATEN TERRIER', 'PAPILLON', 'BLOODHOUND', 'St. Bernard Smooth Coat',
                     'St. Bernard Rough Coat',
                     'BELGIAN MALINOIS', 'PORTUGUESE WATER DOG', 'AIREDALE TERRIER', 'ALASKAN MALAMUTE', 'BULL TERRIER',
                     'AUSTRALIAN CATTLE DOG', 'WHIPPET', 'SCOTTISH TERRIER', 'CHINESE SHARPEI',
                     'ENGLISH COCKER SPANIEL',
                     'SAMOYED', 'DALMATIAN', 'DOGUE DE BORDEAUX', 'MINIATURE PINSCHER', 'LHASA APSO',
                     'WIREHAIRED POINTING GRIFFON', 'GREAT PYRENEES', 'GERMAN WIREHAIRED POINTER', 'IRISH WOLFHOUND',
                     'CAIRN TERRIER', 'ITALIAN GREYHOUND', 'IRISH SETTER', 'CHOW CHOW', 'OLD ENGLISH SHEEPDOG',
                     'CHINESE CRESTED',
                     'CARDIGAN WELSH CORGI', 'AMERICAN STAFFORDSHIRE TERRIER', 'GREATER SWISS MOUNTAIN DOG',
                     'STAFFORDSHIRE BULL TERRIER', 'PEKINGESE', 'GIANT SCHNAUZER', 'BORDER TERRIER',
                     'BOUVIER DES FLANDRES',
                     'KEESHONDEN', 'COTON DE TULEAR', 'FLAT COAT RETRIEVER', 'BASENJI', 'NORWEGIAN ELKHOUND', 'BORZOI',
                     'TIBETAN TERRIER', 'STANDARD SCHNAUZER', 'ANATOLIAN SHEPHERD DOG', 'LEONBERGER',
                     'WIRE FOX TERRIER',
                     'BRUSSELS GRIFFON', 'ENGLISH SETTER', 'JAPANESE CHIN', 'BELGIAN TERVUREN',
                     'NOVA SCOTIA DUCK TOLLING RETRIEVER', 'AFGHAN HOUND', 'RAT TERRIER', 'SILKY TERRIER',
                     'NORWICH TERRIER',
                     'RUSSELL TERRIER', 'GORDON SETTER', 'NEAPOLITAN MASTIFF', 'BOYKIN SPANIEL', 'WELSH TERRIER',
                     'SCHIPPERKE',
                     'TOY FOX TERRIER', 'PARSON RUSSELL TERRIER', 'SPINONI ITALIANI', 'IRISH TERRIER', 'POINTER',
                     'TIBETAN SPANIEL', 'BLACK RUSSIAN TERRIER', 'TREEING WALKER COONHOUND', 'AMERICAN ESKIMO DOG',
                     'BEARDED COLLIE', 'BELGIAN SHEEPDOG', 'MINIATURE BULL TERRIER', 'SMOOTH FOX TERRIER',
                     'BLUETICK COONHOUND',
                     'KERRY BLUE TERRIER', 'AUSTRALIAN TERRIER', 'BOERBOEL', 'BLACK AND TAN COONHOUND',
                     'WELSH SPRINGER SPANIEL',
                     'ENGLISH TOY SPANIEL', 'BRIARD', 'NORFOLK TERRIER', 'SALUKI', 'TIBETAN MASTIFF', 'CLUMBER SPANIEL',
                     'XOLOITZCUINTLI', 'AFFENPINSCHER', 'MANCHESTER TERRIER', 'GERMAN PINSCHER', 'REDBONE COONHOUND',
                     'ICELANDIC SHEEPDO', 'LAKELAND TERRIER', 'BEAUCERON', 'PETIT BASSET GRIFFON VENDEEN',
                     'IRISH WATER SPANIEL',
                     'FIELD SPANIEL', 'BEDLINGTON TERRIER', 'GREYHOUND', 'IRISH RED AND WHITE SETTER', 'PLOTT',
                     'KUVASZOK',
                     'CURLY COAT RETRIEVER', 'SCOTTISH DEERHOUND', 'PORTUGUESE PODENGO PEQUENO', 'PULIK',
                     'SWEDISH VALLHUND',
                     'WIREHAIRED VIZSLA', 'AMERICAN WATER SPANIEL', 'SEALYHAM TERRIER', 'ENTLEBUCHER MOUNTAIN DOG',
                     'IBIZAN HOUND',
                     'LOWCHEN', 'CIRNECHI DE L ETNA', 'KOMONDOROK', 'POLISH LOWLAND SHEEPDOG', 'NORWEGIAN BUHUND',
                     'AMERICAN ENGLISH COONHOUND', 'SPANISH WATER DOG', 'GLEN OF IMAAL TERRIER', 'FINNISH LAPPHUND',
                     'CANAAN DOG',
                     'PHARAOH HOUND', 'DANDIE DINMONT TERRIER', 'SUSSEX SPANIEL', 'BERGAMASCO', 'SKYE TERRIER',
                     'PYRENEAN SHEPHERD', 'CHINOOK', 'FINNISH SPITZ', 'CESKY TERRIER', 'OTTERHOUND',
                     'AMERICAN FOXHOUND',
                     'NORWEGIAN LUNDEHUND', 'HARRIER', 'ENGLISH FOXHOUND']

    # 2013 Breed Popularity Calculation
    breed_popularity_scores_2013 = ['1', '2', '3', '5', '4', '11', '6', '8', '9', '7', '13', '14', '10', '12', '16',
                                    '17', '20', '18', '15', '24',
                                    '19', '23', '21', '25', '26', '30', '28', '22', '32', '29', '27', '34', '31', '33',
                                    '50', '35', '37', '44',
                                    '41', '39', '36', '43', '40', '40', '46', '45', '51', '38', '48', '47', '47', '60',
                                    '49', '56', '57', '52',
                                    '58', '59', '55', '54', '62', '67', '64', '65', '53', '63', '80', '69', '71', '73',
                                    '61', '66', '72', '70',
                                    '78', '68', '75', '76', '74', '79', '77', '83', '81', '82', '86', '-9999', '94',
                                    '85', '103', '99', '88',
                                    '90', '93', '98', '96', '84', '91', '87', '108', '97', '95', '-9999', '92', '89',
                                    '102', '105', '111', '121',
                                    '104', '109', '107', '100', '117', '123', '114', '106', '118', '101', '110', '112',
                                    '119', '125', '116',
                                    '128', '126', '122', '-9999', '113', '124', '135', '127', '129', '115', '132',
                                    '131', '139', '143', '120',
                                    '130', '133', '142', '134', '152', '138', '141', '140', '137', '148', '145', '149',
                                    '150', '163', '165',
                                    '153', '136', '147', '-9999', '144', '158', '155', '151', '154', '-9999', '159',
                                    '157', '166', '146', '-9999',
                                    '167', '171', '164', '160', '168', '162', '-9999', '161', '169', '156', '170',
                                    '174', '172', '176', '175',
                                    '173', '177']

    breed_popularity_2013 = pd.DataFrame(animal_breeds)
    breed_popularity_2013['Breed11'] = pd.DataFrame(animal_breeds)
    breed_popularity_2013['Breed_Popularity_2013'] = pd.DataFrame(breed_popularity_scores_2013)
    breed_popularity_2013.drop(0, axis=1, inplace=True)
    breed_popularity_2013['Breed11'] = breed_popularity_2013['Breed11'].str.upper()

    # 2014 Breed Popularity Calculation
    breed_popularity_scores_2014 = ['1', '2', '3', '4', '5', '9', '6', '7', '10', '8', '12', '13', '11', '14', '15',
                                    '16', '18', '19', '17', '22',
                                    '20', '23', '21', '25', '26', '27', '28', '24', '32', '30', '29', '34', '33', '35',
                                    '48', '36', '37', '40',
                                    '42', '39', '38', '41', '45', '44', '47', '46', '49', '43', '50', '51', '51', '60',
                                    '52', '57', '54', '53',
                                    '55', '56', '59', '58', '62', '68', '66', '63', '61', '67', '76', '75', '71', '72',
                                    '69', '74', '73', '70',
                                    '77', '65', '78', '84', '80', '79', '82', '83', '85', '81', '87', '31', '92', '86',
                                    '103', '102', '88', '90',
                                    '94', '104', '95', '91', '89', '93', '110', '99', '98', '111', '101', '97', '105',
                                    '100', '114', '108', '106',
                                    '109', '115', '116', '118', '125', '119', '122', '127', '112', '120', '121', '123',
                                    '129', '124', '130',
                                    '128', '139', '64', '126', '133', '138', '132', '131', '134', '135', '143', '142',
                                    '144', '136', '141', '148',
                                    '146', '149', '145', '150', '152', '137', '140', '147', '155', '154', '161', '163',
                                    '157', '166', '151',
                                    '158', '107', '160', '169', '153', '159', '165', '117', '168', '170', '172', '156',
                                    '113', '162', '173',
                                    '176', '164', '167', '175', '96', '177', '178', '171', '174', '182', '179', '180',
                                    '184', '181', '183']

    breed_popularity_2014 = pd.DataFrame(animal_breeds)
    breed_popularity_2014['Breed11'] = pd.DataFrame(animal_breeds)
    breed_popularity_2014['Breed_Popularity_2014'] = pd.DataFrame(breed_popularity_scores_2014)
    breed_popularity_2014.drop(0, axis=1, inplace=True)
    breed_popularity_2014['Breed11'] = breed_popularity_2014['Breed11'].str.upper()

    # 2015 Breed Popularity Calculation
    breed_popularity_scores_2015 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
                                    '16', '17', '18', '19',
                                    '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33',
                                    '34', '35', '36', '37',
                                    '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '50',
                                    '51', '52', '53', '54',
                                    '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68',
                                    '69', '70', '71', '72',
                                    '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86',
                                    '87', '88', '89', '90',
                                    '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103',
                                    '104', '105', '106', '107',
                                    '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119',
                                    '120', '121', '122',
                                    '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134',
                                    '135', '136', '137',
                                    '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149',
                                    '150', '151', '152',
                                    '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164',
                                    '165', '166', '167',
                                    '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179',
                                    '180', '181', '182',
                                    '183', '184']

    breed_popularity_2015 = pd.DataFrame(animal_breeds)
    breed_popularity_2015['Breed11'] = pd.DataFrame(animal_breeds)
    breed_popularity_2015['Breed_Popularity_2015'] = pd.DataFrame(breed_popularity_scores_2015)
    breed_popularity_2015.drop(0, axis=1, inplace=True)
    breed_popularity_2015['Breed11'] = breed_popularity_2015['Breed11'].str.upper()

    # Joining Breeds Popularity Scores to the dataset depending on the breeds
    data_set = pd.merge(data_set, breed_popularity_2013, on='Breed11', how='left')
    data_set = pd.merge(data_set, breed_popularity_2014, on='Breed11', how='left')
    data_set = pd.merge(data_set, breed_popularity_2015, on='Breed11', how='left')

    data_set['Breed_Popularity_2013'] = data_set['Breed_Popularity_2013'].fillna(-9999).astype(float)
    data_set['Breed_Popularity_2014'] = data_set['Breed_Popularity_2014'].fillna(-9999).astype(float)
    data_set['Breed_Popularity_2015'] = data_set['Breed_Popularity_2015'].fillna(-9999).astype(float)

    return data_set

train_original = pd.read_csv('input/train.csv', delimiter=',')
test_original = pd.read_csv('input/test.csv', delimiter=',')
pd.options.mode.chained_assignment = None
test_ID = test_original['ID']
test_original.drop('ID', axis=1, inplace=True)

data_pre_process_initial(train_original, test_original)

# Removing outcome type columns from training data set
Target = train_original['Target']
train_original.drop('OutcomeSubtype', axis=1, inplace=True)
train_original.drop('Aggressive', axis=1, inplace=True)
train_original.drop('At Vet', axis=1, inplace=True)
train_original.drop('Barn', axis=1, inplace=True)
train_original.drop('Behavior', axis=1, inplace=True)
train_original.drop('Court/Investigation', axis=1, inplace=True)
train_original.drop('Enroute', axis=1, inplace=True)
train_original.drop('Foster', axis=1, inplace=True)
train_original.drop('In Foster', axis=1, inplace=True)
train_original.drop('In Kennel', axis=1, inplace=True)
train_original.drop('In Surgery', axis=1, inplace=True)
train_original.drop('Medical', axis=1, inplace=True)
train_original.drop('Offsite', axis=1, inplace=True)
train_original.drop('Partner', axis=1, inplace=True)
train_original.drop('Rabies Risk', axis=1, inplace=True)
train_original.drop('SCRP', axis=1, inplace=True)
train_original.drop('Suffering', axis=1, inplace=True)
train_original.drop('OutcomeType', axis=1, inplace=True)
train_original.drop('Target', axis=1, inplace=True)

train_2 = breed_data_pre_process(train_original)
test_2 = breed_data_pre_process(test_original)

train_select = pd.DataFrame(train_2.select_dtypes(include=['float64', 'int64', 'int32', 'float32']))
test_select = pd.DataFrame(test_2.select_dtypes(include=['float64', 'int64', 'int32', 'float32']))

train_select = train_select.fillna(-9999)
test_select = test_select.fillna(-9999)

target = Target.values
features_one = train_select[
    ['Name_bool', 'AgeuponOutcome_In_Days', 'year', 'hour', 'minute', 'quarter', 'weekofyear', 'Classement_2013',
     'Classement_2014', 'Classement_2015', 'Type_sex', 'SexuponOutcome_cat', 'AnimalType_cat']].values

forest = RandomForestClassifier(n_estimators=1000, random_state=1)
my_forest = forest.fit(features_one, target)

print(my_forest.score(features_one, target))

test_features = test_select[
    ['Name_bool', 'AgeuponOutcome_In_Days', 'year', 'hour', 'minute', 'quarter', 'weekofyear', 'Classement_2013',
     'Classement_2014', 'Classement_2015', 'Type_sex', 'SexuponOutcome_cat', 'AnimalType_cat']].values

my_prediction = my_forest.predict(test_features)
ID = np.array(test_ID.values).astype(int)
my_solution = pd.DataFrame(my_prediction, ID, columns=["OutcomeType"])

# Write solution to a csv file
my_solution["Adoption"] = 0
my_solution["Adoption"][my_solution["OutcomeType"] == 2] = 1
my_solution["Died"] = 0
my_solution["Died"][my_solution["OutcomeType"] == 4] = 1
my_solution["Euthanasia"] = 0
my_solution["Euthanasia"][my_solution["OutcomeType"] == 1] = 1
my_solution["Return_to_owner"] = 0
my_solution["Return_to_owner"][my_solution["OutcomeType"] == 0] = 1
my_solution["Transfer"] = 0
my_solution["Transfer"][my_solution["OutcomeType"] == 3] = 1
my_solution = my_solution.drop('OutcomeType', 1)

my_solution.to_csv("Random_Forest_BreedGroups.csv", index_label=["ID"])


from collections import defaultdict
def squirrelAndNut(tree, triples):
    d = defaultdict (set)
    while tree:
        n2 = tree.pop ()
        n1 = tree.pop ()
        d [n1].add (n2)
        d [n2].add (n1)
    def bfs (frm, to, onwy):
        p = defaultdict (lambda: -1)
        vstd = set ([frm])
        ndS = set ([frm])
        def chk ():
            aim = to
            while aim != frm:
                aim = p [aim]
                if aim == onwy: return True
            return False
        while ndS:
            nnd = set ()
            for nd in ndS:
                new = d [nd] - vstd
                for nd_ in new:
                    p [nd_] = nd
                    if nd_ == to: return chk ()
                vstd |= new
                nnd |= new
            ndS = nnd
        return False
    def bfs2 (frm, to, onwy):
        p1 = defaultdict (lambda: -1)
        p2 = defaultdict (lambda: -1)
        vstd1 = set ([frm])
        vstd2 = set ([to])
        ndS = set ([frm])
        nd2 = set ([to])
        def chk1 (x):
            if x == onwy: return True
            aim = x
            while aim != frm:
                aim = p1 [aim]
                if aim == onwy: return True
            return False
        def chk2 (x):
            if x == onwy: return True
            aim = x
            while aim != to:
                aim = p2 [aim]
                if aim == onwy: return True
            return False
        while ndS and nd2:
            nnd = set ()
            for nd in ndS:
                new = d [nd] - vstd1
                for nd_ in new:
                    p1 [nd_] = nd
                    if nd_ in vstd2: return chk1 (nd_) or chk2 (nd_)
                vstd1 |= new
                nnd |= new
            ndS = nnd.copy ()
            nnd = set ()
            for nd in nd2:
                new = d [nd] - vstd2
                for nd_ in new:
                    p2 [nd_] = nd
                    if nd_ in vstd1: return chk1 (nd_) or chk2 (nd_)
                vstd2 |= new
                nnd |= new
            nd2 = nnd.copy ()
        return False
    res = []
    for frm, to, onwy in triples:
        res.append (bfs2 (frm, to, onwy))
    return res
tree = [1, 2, 1, 3, 2, 4, 3, 5, 3, 6]
triples = [[4,6,3], [1,4,2], [5,6,1]]
print (squirrelAndNut (tree, triples))


"""
Support for Google Home bluetooth tacker.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.googlehome/
"""
import logging

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.components.device_tracker import (
    DOMAIN, PLATFORM_SCHEMA, DeviceScanner)
from homeassistant.const import CONF_HOST

REQUIREMENTS = ['ghlocalapi==0.3.5']

_LOGGER = logging.getLogger(__name__)

CONF_RSSI_THRESHOLD = 'rssi_threshold'

PLATFORM_SCHEMA = vol.All(
    PLATFORM_SCHEMA.extend({
        vol.Required(CONF_HOST): cv.string,
        vol.Optional(CONF_RSSI_THRESHOLD, default=-70): vol.Coerce(int),
    }))

async def async_get_scanner(hass, config):
    """Validate the configuration and return an Google Home scanner."""
    scanner = GoogleHomeDeviceScanner(hass, config[DOMAIN])
    await scanner.async_connect()
    return scanner if scanner.success_init else None

class GoogleHomeDeviceScanner(DeviceScanner):
    """This class queries a Google Home unit."""

    def __init__(self, hass, config):
        """Initialize the scanner."""
        from ghlocalapi.device_info import DeviceInfo
        from ghlocalapi.bluetooth import Bluetooth

        self.last_results = {}

        self.success_init = False
        self._host = config[CONF_HOST]
        self.rssi_threshold = config[CONF_RSSI_THRESHOLD]

        session = async_get_clientsession(hass)
        self.deviceinfo = DeviceInfo(hass.loop, session, self._host)
        self.scanner = Bluetooth(hass.loop, session, self._host)

    async def async_connect(self):
        """Initialize connection to Google Home."""
        await self.deviceinfo.get_device_info()
        data = self.deviceinfo.device_info
        self.success_init = data is not None

    async def async_scan_devices(self):
        """Scan for new devices and return a list with found device IDs."""
        await self.async_update_info()
        return list(self.last_results.keys())

    async def async_get_device_name(self, device):
        """Return the name of the given device or None if we don't know."""
        if device not in self.last_results:
            return None
        return '{}_{}'.format(self._host,
                              self.last_results[device]['btle_mac_address'])

    async def get_extra_attributes(self, device):
        """Return the extra attributes of the device."""
        return self.last_results[device]

    async def async_update_info(self):
        """Ensure the information from Google Home is up to date."""
        _LOGGER.debug('Checking Devices...')
        await self.scanner.scan_for_devices()
        await self.scanner.get_scan_result()
        ghname = self.deviceinfo.device_info['name']
        devices = {}
        for device in self.scanner.devices:
            if device['rssi'] > self.rssi_threshold:
                uuid = '{}_{}'.format(self._host, device['mac_address'])
                devices[uuid] = {}
                devices[uuid]['rssi'] = device['rssi']
                devices[uuid]['btle_mac_address'] = device['mac_address']
                devices[uuid]['ghname'] = ghname
                devices[uuid]['source_type'] = 'bluetooth'
        await self.scanner.clear_scan_result()
        self.last_results = devices


"""
Contains structures to search against in SMARTS format
5x substrucutes from Sebastian Wolf et al BMC Bioinform.

Future to test:
140x neutral losses from Ma, Yan, et al Anal. Chem.
"""

#SMARTS
target_structures = {
    'Hydroxyl': '[OX2H]',
    'Cyano': '[CX2]#[NX1]',
    'Amino': '[NX3;H2,H1;!$(NC=O)]',
    'Aldehyde': '[CX3H1](=O)[#6]',
    'Carboxylic': '[CX3](=O)[OX1H0-,OX2H1]',
}

#Formula
target_loss_forumula = {
    'Hydroxyl': 'H2O',
    'Cyano': 'CN',
    'Amino': 'NH2',
    'Aldehyde': 'COH',
    'Carboxylic': 'CO2H',
}

#Exact mass Da, float
target_nl_mass = {
    'Hydroxyl': 18.0106,
    'Cyano': 27.0109,
    'Amino': 17.0266,
    'Aldehyde': 30.0106,
    'Carboxylic': 46.0055,
}


import collections
import itertools
import math
import random

from psychopy import visual, core, sound, event

from kraepelin import kraepelin_experiment
from kraepelin_trigger import trigger_values
from quick20_trigger import send_trigger

#defined sounds
SoundNamedTuple = collections.namedtuple('SoundNamedTuple', [
	'introduction', 'inst_calc','post_cue', 'inst_cue_num', 'inst_progress_1', 'inst_progress_2', 'inst_progress_3',
	'firstblock_1', 'firstblock_2', 'firstblock_3', 'firstblock_4', 'inst_cue_value_1', 'inst_cue_value_2', 'inst_cue_value_3', 'inst_cue_value_4',
	'inst_cue_value_5', 'into_second', 'secondblock_1', 'secondblock_2', 'secondblock_3', 'secondblock_4', 'secondblock_5', 'secondblock_6',
	'secondblock_7', 'into_demo', 'finish_instruction', 'start_demo', 'finish_demo', 'confirmation', 'inst_fixa', 'summary_cue',
	'opening', 'end_demosession'])
sound_namedtuple = SoundNamedTuple(**{soundname:sound.Sound('sounds/'+soundname+'.wav') for soundname in SoundNamedTuple._fields})

#instruction start---------------------------------------------------------------------
def instruction(win):
	send_trigger(trigger_values.Demo_Inst)

	#components settings
	emphasisrect_dict = {
		key:visual.Rect(win, pos=stim.pos, width=200, height=200, lineColor='red', lineWidth=5)
		for key, stim in dict(msg_count=win.msg_count, matrixstim_left=win.matrixstim_left, matrixstim_right=win.matrixstim_right).items()
	}
	arrow = visual.ShapeStim(
		win, vertices=((-15,0),(-15,30),(15,30),(15,0),(30,0),(0,-30),(-30,0)),
		pos=(0,-200), lineColor='white',fillColor='white')
	demo_cor_ans = visual.TextStim(win, pos=(0, -300), height=80, bold=True)

	win.display_stimuli(
		[visual.TextStim(win, text=u'課題説明', height=80, bold=True)],
		sound=sound_namedtuple.introduction,
		wait_time=2.,
	)

#1st block-----------------------------------------------------------------------------
	win.msg_count.setText("0")
	win.msg_answer.setText("7")
	#set matrix
	win.matrixstim_left.set_random_matrix(6, 4)
	win.matrixstim_right.set_random_matrix(3, 8)

	win.display_stimuli(
		[win.msg_count],
		sound=sound_namedtuple.inst_progress_1,
		wait_time=1.
	)
	win.display_stimuli(
		[emphasisrect_dict['msg_count'], win.msg_count],
		sound=sound_namedtuple.inst_progress_2,
		wait_time=1.
	)
	win.display_stimuli(
		[win.msg_count],
		sound=sound_namedtuple.inst_progress_3,
		wait_time=1.
	)
	win.display_stimuli(
		[win.LRcue_dict[(True, False)]],
		wait_time=0.5,
	)
	win.display_stimuli(
		[],
		wait_time=0.5,
	)
	win.display_stimuli(
		[],
		sound=sound_namedtuple.post_cue,
		wait_time=1.
	)
	win.display_stimuli(
		[win.LRcue_dict[(True, False)]],
		sound=sound_namedtuple.inst_cue_num,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right],
		sound=sound_namedtuple.firstblock_1,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right, emphasisrect_dict['matrixstim_left']],
		sound=sound_namedtuple.firstblock_2,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right, emphasisrect_dict['matrixstim_right']],
		sound=sound_namedtuple.firstblock_3,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right, win.msg_answer],
		sound=sound_namedtuple.firstblock_4,
		wait_time=1.
	)
	win.display_stimuli(
		[],
		sound=sound_namedtuple.inst_cue_value_1,
		wait_time=1.
	)
	win.display_stimuli(
		[win.LRcue_dict[(True, False)]],
		sound=sound_namedtuple.inst_cue_value_2,
		wait_time=1.
	)
	win.display_stimuli(
		[win.LRcue_dict[(False, True)]],
		sound=sound_namedtuple.inst_cue_value_3,
		wait_time=1.
	)
	win.display_stimuli(
		[win.LRcue_dict[(True, True)]],
		sound=sound_namedtuple.inst_cue_value_4,
		wait_time=1.
	)
	win.display_stimuli(
		[win.LRcue_dict[(False, False)]],
		sound=sound_namedtuple.inst_cue_value_5,
		wait_time=1.
	)
#2nd block-----------------------------------------------------------------------------
	win.msg_count.setText("1")
	win.msg_answer.setText("13")
	demo_cor_ans.setText("3")
	#set matrix
	win.matrixstim_left.set_random_matrix(8, 4)
	win.matrixstim_right.set_random_matrix(5, 1)

	win.display_stimuli(
		[win.msg_count, emphasisrect_dict['msg_count']],
		sound=sound_namedtuple.into_second,
		wait_time=1.
	)
	win.display_stimuli(
		[win.LRcue_dict[(False, False)]],
		wait_time=0.5,
	)
	win.display_stimuli(
		[],
		wait_time=0.5,
	)
	win.display_stimuli(
		[],
		sound=sound_namedtuple.post_cue,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right],
		sound=sound_namedtuple.secondblock_1,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right, emphasisrect_dict['matrixstim_left']],
		sound=sound_namedtuple.secondblock_2,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right, emphasisrect_dict['matrixstim_right']],
		sound=sound_namedtuple.secondblock_3,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right],
		sound=sound_namedtuple.secondblock_4,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right, win.msg_answer],
		sound=sound_namedtuple.secondblock_5,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right, win.msg_answer, arrow],
		sound=sound_namedtuple.secondblock_6,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation, win.matrixstim_left, win.matrixstim_right, win.msg_answer, arrow, demo_cor_ans],
		sound=sound_namedtuple.secondblock_7,
		wait_time=1.
	)
	win.display_stimuli(
		[win.fixation],
		sound=sound_namedtuple.inst_fixa,
		wait_time=1.
	)

#summary------------------------------------------------------------------------------
	win.display_stimuli(
		[
			visual.TextStim(win, " V :  数字", bold=True, height=80, pos=(50,100)),
			visual.TextStim(win, " N :  個数", bold=True, height=80, pos=(50,-100))
		],
		sound=sound_namedtuple.summary_cue,
		wait_time=2.
	)
	win.display_stimuli(
		[],
		sound=sound_namedtuple.finish_instruction,
		wait_time=1.,
	)

#start demo---------------------------------------------------------------------------
def demo(kraepelin_window, block_length, log_name='result_demo.csv'):
	send_trigger(trigger_values.Demo_Start)

	kraepelin_window.display_stimuli(
		[visual.TextStim(kraepelin_window, text=u'練習', height=80, bold=True)],
		sound=sound_namedtuple.into_demo,
		wait_time = 1.,
	)
	kraepelin_window.display_stimuli(
		[],
		sound=sound_namedtuple.start_demo,
	)

	kraepelin_experiment(kraepelin_window, block_length, log_name=log_name)

	kraepelin_window.display_stimuli(
		[],
		sound=sound_namedtuple.finish_demo,
		wait_time=1.,
	)
	send_trigger(trigger_values.Demo_Fin)

#confirmation------------------------------------------------------------------------
def display_confirmation(kraepelin_window):
	key_list = ['num_1', 'num_2', 'num_3']

	for text, pos in zip([u'説明 → 1', u'練習 → 2', u'本番 → 3'], [(0, 200), (0, 0), (0, -200)]):
		visual.TextStim(kraepelin_window, text=text, height=80, bold=True, pos=pos).draw()
	kraepelin_window.flip()
	sound_namedtuple.confirmation.play()

	key = event.waitKeys(keyList=key_list)[0]
	sound_namedtuple.confirmation.stop()
	return key_list.index(key)

if __name__ == "__main__":
	import sys
	from psychopy import event
	from kraepelin_stimuli import KraepelinWindow
	from practice_tenkey import practice_tenkey

	logfile_name = sys.argv[1]

	#set global escape
	event.globalKeys.add(key='escape', func=core.quit)

	block_length = 2
	win = KraepelinWindow(size=(1920, 1080), units='pix', fullscr=True, allowGUI=False)
	demo_logfilename = lambda n : logfile_name+'_instruction_demo{}.csv'.format(n)

	#wait start
	visual.TextStim(win, text="Start!", height=80).draw()
	win.flip()
	event.waitKeys(keyList=['space'])

	#opening
	sound_namedtuple.opening.play()
	core.wait(sound_namedtuple.opening.getDuration())
	core.wait(1)
	#practice 10-key
	practice_tenkey(win)

	demo_trial = 1
	instruction(win)
	demo_result = demo_logfilename(demo_trial)
	demo(win, block_length, log_name = demo_result)
	while True:
		selection = display_confirmation(win)
		if selection == 0:
			instruction(win)
		elif selection == 1:
			demo_trial = demo_trial + 1
			demo_result = logfile_name + '_instruction_demo{}.csv'.format(demo_trial)
			demo(win, block_length, log_name=demo_result)
		else:
			break

	sound_namedtuple.end_demosession.play()
	core.wait(sound_namedtuple.end_demosession.getDuration())

	#wait end
	visual.TextStim(win, text="Finish!", height=80).draw()
	win.flip()
	event.waitKeys(keyList=['space'])


import elasticsearch
import hail as hl

HAIL_TYPE_TO_ES_TYPE_MAPPING = {
    hl.tint: "integer",
    hl.tint32: "integer",
    hl.tint64: "long",
    hl.tfloat: "double",
    hl.tfloat32: "float",
    hl.tfloat64: "double",
    hl.tstr: "keyword",
    hl.tbool: "boolean",
}

# https://hail.is/docs/devel/types.html
# https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html
def _elasticsearch_mapping_for_hail_type(dtype):
    if isinstance(dtype, hl.tstruct):
        return {"properties": {field: _elasticsearch_mapping_for_hail_type(dtype[field]) for field in dtype.fields}}

    if isinstance(dtype, (hl.tarray, hl.tset)):
        element_mapping = _elasticsearch_mapping_for_hail_type(dtype.element_type)

        if isinstance(dtype.element_type, hl.tstruct):
            element_mapping["type"] = "nested"

        return element_mapping

    if isinstance(dtype, hl.tlocus):
        return {"type": "object", "properties": {"contig": {"type": "keyword"}, "position": {"type": "integer"}}}

    if dtype in HAIL_TYPE_TO_ES_TYPE_MAPPING:
        return {"type": HAIL_TYPE_TO_ES_TYPE_MAPPING[dtype]}

    # tdict, ttuple, tinterval, tcall
    raise NotImplementedError

def _set_field_parameter(mapping, field, parameter, value):
    keys = field.split(".")
    ref = mapping
    for key in keys:
        ref = ref["properties"][key]

    ref[parameter] = value

def elasticsearch_mapping_for_table(table, disable_fields=None, override_types=None):
    """
    Creates an Elasticsearch mapping definition for a Hail table's row value type.

    https://www.elastic.co/guide/en/elasticsearch/guide/current/root-object.html
    """
    mapping = _elasticsearch_mapping_for_hail_type(table.key_by().row_value.dtype)

    if disable_fields:
        for field in disable_fields:
            _set_field_parameter(mapping, field, "enabled", False)

    if override_types:
        for field, field_type in override_types.items():
            _set_field_parameter(mapping, field, "type", field_type)

    return mapping

def struct_to_dict(struct):
    return {k: dict(struct_to_dict(v)) if isinstance(v, hl.utils.Struct) else v for k, v in struct.items()}

def export_table_to_elasticsearch(
    table,
    host,
    index_name,
    block_size=5000,
    id_field=None,
    mapping=None,
    num_shards=10,
    port=9200,
    verbose=True,
    es_config=None,
):
    es_client = elasticsearch.Elasticsearch(host, port=port)

    elasticsearch_config = {"es.write.operation": "index"}

    if es_config:
        elasticsearch_config = {**elasticsearch_config, **es_config}

    if id_field is not None:
        elasticsearch_config["es.mapping.id"] = id_field

    if not mapping:
        mapping = elasticsearch_mapping_for_table(table)

    # Delete the index before creating it
    if es_client.indices.exists(index=index_name):
        es_client.indices.delete(index=index_name)

    # TODO This is disabled by default in ES 6+
    mapping["_all"] = {"enabled": "false"}
    mapping["_meta"] = struct_to_dict(hl.eval(table.globals))

    # Hard code type name for all indices
    # Mapping types are removed in ES 7
    type_name = "documents"

    # https://www.elastic.co/guide/en/elasticsearch/reference/current/index-modules.html#index-modules-settings
    request_body = {
        # TODO Mapping types are removed in ES 7
        "mappings": {type_name: mapping},
        "settings": {
            "index.codec": "best_compression",
            "index.mapping.total_fields.limit": 10000,
            "index.number_of_replicas": 0,
            "index.number_of_shards": num_shards,
            "index.refresh_interval": -1,
        },
    }

    es_client.indices.create(index=index_name, body=request_body)

    hl.export_elasticsearch(table, host, port, index_name, type_name, block_size, elasticsearch_config, verbose)

    es_client.indices.forcemerge(index=index_name)


from torch import nn

class Generator(nn.Sequential):
    def __init__(self):
        super().__init__(
            # input is Z, going into a convolution
            nn.ConvTranspose2d(100, 512, 4, 1, 0, bias=False),
            nn.BatchNorm2d(512),
            nn.ReLU(True),
            # state size. 512 x 4 x 4
            nn.ConvTranspose2d(512, 256, 4, 2, 1, bias=False),
            nn.BatchNorm2d(256),
            nn.ReLU(True),
            # state size. 256 x 8 x 8
            nn.ConvTranspose2d(256, 128, 4, 2, 1, bias=False),
            nn.BatchNorm2d(128),
            nn.ReLU(True),
            # state size. 128 x 16 x 16
            nn.ConvTranspose2d(128, 64, 4, 2, 1, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(True),
            # state size. 64 x 32 x 32
            nn.ConvTranspose2d(64, 3, 4, 2, 1, bias=False),
            nn.Tanh()
            # state size. 3 x 64 x 64
        )

class Discriminator(nn.Sequential):
    def __init__(self):
        super().__init__(
            # input is 3 x 64 x 64
            nn.Conv2d(3, 64, 4, 2, 1, bias=False),
            nn.LeakyReLU(0.2, inplace=True),
            # state size. 64 x 32 x 32
            nn.Conv2d(64, 128, 4, 2, 1, bias=False),
            nn.BatchNorm2d(128),
            nn.LeakyReLU(0.2, inplace=True),
            # state size. 128 x 16 x 16
            nn.Conv2d(128, 256, 4, 2, 1, bias=False),
            nn.BatchNorm2d(256),
            nn.LeakyReLU(0.2, inplace=True),
            # state size. 256 x 8 x 8
            nn.Conv2d(256, 512, 4, 2, 1, bias=False),
            nn.BatchNorm2d(512),
            nn.LeakyReLU(0.2, inplace=True),
            # state size. 512 x 4 x 4
            nn.Conv2d(512, 1, 4, 1, 0, bias=False),
            nn.Sigmoid()
        )


# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def partition(self, head, x):
        # separate the list into 2 distinct lists and link them afterwards.
        # p1, p2 traverses the list and hd1 and hd2 are the heads of two lists
        hd1 = p1 = ListNode(0)
        hd2 = p2 = ListNode(0)
        while head:
            if head.val < x:
                p1.next = head
                p1 = p1.next
            else:
                p2.next = head
                p2 = p2.next
            head = head.next
        # join the lists
        p2.next = None
        p1.next = hd2.next
        return hd1.next

My = Solution()
n1 = ListNode(1)
n2 = ListNode(4)
n3 = ListNode(3)
n4 = ListNode(2)
n4 = ListNode(5)
n5 = ListNode(2)
n6 = ListNode(6)
n7 = ListNode(1)
n8 = ListNode(0)
n9 = ListNode(-1)
n10 = ListNode(7)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
n6.next = n7
n7.next = n8
n8.next = n9
n9.next = n10

x = 3
L = My.partition(n1, x)
while L:
    print(str(L.val) + " ")
    L = L.next


import requests
import json

config = json.load(open("configuration.json"))

print("bot.py ...")
newest_bot = requests.get("https://github.com/Jerrynicki/LifeBot/raw/"+config["update_branch"]+"/bot.py")
if newest_bot.status_code != 200:
    print("ERROR when updating\n\nStatus code from bot.py: "+str(newest_bot.status_code))
else:
    with open("bot.py","w") as newest_bot_file:
        newest_bot_file.write(newest_bot.text)
    print("Update successful.")


import os
import json
import subprocess
import sys

from pprint import pformat
from settings import MODELS_FOLDER

from logger import logger

def classify(image_path: str, dataset_name) -> dict:
    """
    Classifies a flower image to its type.
    :param image_path: The path to the flower image.
    :param dataset_name: The dataset name for the image to be classified
    :return: The image classification
    """
    graph_path = os.path.join(MODELS_FOLDER, f"{dataset_name}_graph.pb")
    labels_path = os.path.join(MODELS_FOLDER, f"{dataset_name}_labels.txt")

    # Validate model exists
    if not os.path.exists(graph_path):
        raise ValueError(f"Graph does not exist: {graph_path}")

    if not os.path.exists(labels_path):
        raise ValueError(f"Labels do not exist: {labels_path}")

    classification = subprocess_classification(graph_path, labels_path, image_path)

    return classification

def subprocess_classification(graph_path, labels_path, image_path):
    # Classify the image
    logger.info(f"Classifying: {image_path}, model path: {graph_path}")

    cmd = [
        sys.executable,
        "label_image.py",
        f"--graph={graph_path}",
        f'--image={image_path}',
        f"--labels={labels_path}",
        "--output_layer=final_result",
        "--input_layer=Placeholder"
    ]

    p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, err = p.communicate()

    if err is not None:
        raise RuntimeError(err)

    # Decode the output
    output = out.decode()
    logger.info(f"=========== Output start ===========\n{output}\n=========== Output end ===========")

    raw_classification = out.decode().split("\n\n")[-1].strip()

    # Check empty classification
    if output == '' or output is None:
        raise ValueError("Classification was not produced")

    # Parse the result
    classification = json.loads(raw_classification)
    logger.info(pformat(classification))

    return [x for x in classification[0].items()]


# -------------------------------------------------------------------------------
# Name:        textbox
# Purpose:     Allows text to be easily written to screen in pygame
# Author:      Tony
# Created:     25/08/2016
# Copyright:   (c) Tony 2016
# Licence:     Free to use
# -------------------------------------------------------------------------------

# ! /usr/bin/env python

""" Allows text to be easily written to screen in pygame
    Dependencies : pygame
"""
import sys
import pygame

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREY = (169, 169, 169)

class TextRectException(Exception):
    """ Class that raises an exception if error found while printing string """

    __slots__ = ['message', 'line', 'extra_msg']

    def __init__(self, message=None, line="", extra_msg=""):
        super(TextRectException, self).__init__(message)
        self.message = message
        self.line = line
        self.extra_msg = extra_msg
        sys.tracebacklimit = 0

    def __str__(self):
        if self.line:
            self.message = self.message + " in text beginning '" + " ".join(self.line.split()[:5]) + "'."
        if self.extra_msg:
            self.message = self.message + "\n" + self.extra_msg
        return self.message

class Textwrap:
    """ Allows text to be written easily to screen in pygame

        Text can contain the following in-text commands
        /B to toggle bold text
        /I to toggle Italic
        /S to toggle underscore
        /C(colour tuple) to change colour /C to revert to original colour
        /F(sysfont name, size) to change font /F to revert to original font
    """
    __slots__ = ['base', 'flags', 'current', 'surface_dicts', 'surface_sizes', 'surface_dict', 'curr_line', 'adjust']

    def __init__(self, rect, font, text_colour=WHITE,
                 background_colour=BLACK, justification=0, frame=0, frame_colour=BLACK, adjust=False):
        """ Create the text box inside which text will be printed

            rect:   rectangle to contain the writing - required
            font:   default font for text - required
            text_color: default colour for text
            background_color: colour of box background
            justification:  0(default)-left, 1-centred, 2-right.
                            add 10 for vertical centred
                            add 20 for vertical centred with room for dialogue buttons
            frame: 0(default)-no frame, otherwise thickness of frame
            frame_colour: Black(default) otherwise RGB colour triple
            adjust: Adjust height to fit contents

        """
        # Base values for instance stored in dictionary as follows
        # font:font object, base_font:font specified in print_text()
        # rect:size of text area, text_colour:foreground colour,
        # background_colour:background colour (None - transparent)
        # justification:0-left,1-centred,2-right.
        # v_justifcation:vertical justification,
        # frame:0-no frame otherwise thickness of frame, frame_colour:Frame colour,

        self.base = {"font": font, "base_font": font,
                     "rect": rect, "text_colour": text_colour,
                     "background_colour": background_colour,
                     "justification": justification, "v_justification": 0,
                     "frame": frame, "frame_colour": frame_colour}
        self.adjust = adjust

        self.set_frame(frame, frame_colour)
        self.set_justification(justification)

        self.flags = {}  # flags used with inline formatting commands
        self.current = {}  # Internal attributes used by class instance while setting text
        self.surface_dicts = []  # list of dictionaries of surfaces, one for each line
        self.surface_sizes = []  # {surface no: (width, height)} for each line also -1:(total_width, max_height)
        self.surface_dict = {}  # Dictionary of surfaces making up each line
        self.curr_line = ""  # Line being processed

        self.set_defaults()

    # -----------------------------------------------------------------------------------------------------------
    # Set attributes

    def set_rect(self, *args):
        """ Set text rectangle
            args can be pygame.Rect, tuple or 4 numbers """
        if isinstance(args[0], pygame.Rect):
            self.base["rect"] = args[0]
        else:
            self.base["rect"] = pygame.Rect(*args)

    def set_font(self, font):
        """ Set font
            font has to be a pygame.font.Font or SysFont """
        self.base["base_font"] = font

    def set_text_colour(self, *args):
        """ Set default colour for text
            three RGB values or colour tuple """
        if isinstance(args[0], tuple):
            self.base["text_colour"] = args[0]
        else:
            self.base["text_colour"] = tuple(args)

    def set_back_colour(self, *args):
        """ Set colour of box background
            three RGB values or colour tuple """
        if isinstance(args[0], tuple):
            self.base["background_colour"] = args[0]
        else:
            self.base["background_colour"] = tuple(args)

    def set_justification(self, justification):
        """ Set justification
            0(default)-left, 1-centred, 2-right.
            add 10 for vertical centred
            add 20 for vertical centred with room for dialogue buttons """
        if justification >= 10:
            self.base["justification"] = justification % 10
            self.base["v_justification"] = justification // 10

    def set_frame(self, frame=0, frame_colour=(0, 0, 0)):
        """ Set frame type
            0(default)-no frame, otherwise thickness of frame
            frame_colour: Black(default) otherwise colour triple """
        self.base["frame"] = frame
        self.base["frame_colour"] = frame_colour

    # -----------------------------------------------------------------------------------------------------------

    def set_defaults(self):
        # flags used with inline formatting commands
        # bold:bold mode on flag, underline:underline mode on flag, italic:italic mode on flag
        # setcolour:colour change flag, setfont:font change flag

        self.flags = {"bold": False, "underline": False,
                      "italic": False, "setcolour": False, "setfont": False}

        # Internal attributes used by class instance while setting text
        # font and text_colour may be changed inline
        # line_length and surface_no used to build surfaces for the lines

        self.current = {"font": self.base["base_font"],
                        "text_colour": self.base["text_colour"],
                        "line_length": 0, "surface_no": 0}

        # Text is split into lengths as required to fit and each line rendered
        # If text attributes are changed these are rendered separately
        # All rendered surfaces for the line are stored in a dictionary {surface no: rendered surface}
        # All dictionaries are stored in a list
        self.surface_dicts = []  # list of dictionaries of surfaces, one for each line
        self.surface_sizes = []  # {surface no: (width, height)} for each line also -1:(total_width, max_height)
        self.surface_dict = {}  # Dictionary of surfaces making up each line

    # Process and render text
    # Split into lines of required width and render.
    def print_text(self, text, font=None):
        """ Print text inside box using defined parameters

            text: text to print(may include inline modifiers)
            font: optional, default used if not specified

            Returns surface with text
        """
        if font is None:
            font = self.base["font"]
        self.base["base_font"] = font
        self.set_defaults()

        self._process_lines(text)
        surface = self._render_surfaces()
        return surface

    # self.surface_dicts holds all the dictionaries as a list
    # Processes all embedded codes and sends on parts with same attributes
    def _process_lines(self, text):
        """ Cut the text into lines to fit frame allowing for inline commands """

        self._reset_flags()
        self.surface_dicts = []
        process_dict = {'B': self._process_bold, 'C': self._process_colour,
                        'F': self._process_font, 'I': self._process_italic,
                        'S': self._process_underline}

        lines = text.splitlines()

        for line in lines:
            self.curr_line = line
            new_line = True

            while len(line) > 0:
                split_line = line.partition("\\")
                if len(split_line[0]) > 0:
                    self._render_line(split_line[0], self.current["font"], self.current["text_colour"], new_line)
                if split_line[1] == '\\':
                    line = process_dict.get(split_line[2][0], lambda args: None).__call__(split_line)
                    if line is None:
                        raise TextRectException("Unrecognized inline command '\\"
                                                + split_line[2][0] + "'", self.curr_line,
                                                r"Possible values are \B \C \F \I \S")
                else:
                    line = split_line[2]
                new_line = False
            self._line_surface()
        self._get_size()

    # Cut line to fit rectangle and render line or parts of line
    # The rendered parts for each line on screen are kept in a dictionary surface_dict
    # All dictionaries for the whole text are held in the list surface_dicts
    def _render_line(self, line, font, colour, state):
        """ Render all parts of each line """
        newline = state
        text_width = self.base["rect"].width - self.base["frame"] * 4  # max width for text
        if newline:
            self._start_line()
        self.do_line(line, font, colour, text_width)

    def do_line(self, line, font, colour, text_width):
        """ Fit line into current frame
            Start new lines if too long """
        if line == "":
            return
        if self.current["surface_no"] == 0:
            line = line.lstrip()
        excess = ""
        while self.current["line_length"] + font.size(line)[0] > text_width:
            pos = line.rfind(" ")
            if pos >= 0:
                excess = line[pos:] + excess
                line = line[:pos]
            elif font.size(line)[0] >= text_width:
                raise TextRectException("The word '" + line + "' is too long to fit specified rectangle",
                                        self.curr_line, "Needs at least "
                                        + str(font.size(line)[0] + self.base["frame"] * 4) + " for this font")
            else:
                line, excess = "", line + excess
        self.current["line_length"] += font.size(line)[0]
        self.surface_dict[self.current["surface_no"]] = font.render(line, True, colour)
        if excess:
            self._line_surface()
        else:
            self._continue_line()
        return self.do_line(excess, font, colour, text_width)

    def _start_line(self):
        """ Start a new line in rendered text """
        self.surface_dict = {}  # start dictionary at beginning of line
        self.current["surface_no"] = 0
        self.current["line_length"] = 0

    def _continue_line(self):
        """ Add surface to line dictionary """
        self.current["surface_no"] += 1

    def _line_surface(self):
        """ Append a complete line dictionary and start a new dictionary """
        if self.surface_dict:
            self.surface_dicts.append(self.surface_dict)
        self.surface_dict = {}
        self.current["surface_no"] = 0
        self.current["line_length"] = 0

    def _get_size(self):
        """ Get width and height of each surface in each line
            Store as (width, height) in self.surface_sizes {surface no: (width, height)}
            Calculate total width and maximum height of text for each line and store as key value -1 """

        self.surface_sizes = []
        for dictionary in self.surface_dicts:
            size_dict = {}
            for key in dictionary:
                size_dict[key] = (dictionary[key].get_width(), dictionary[key].get_height())
            size_dict[-1] = (sum([val[0] for val in size_dict.values()]), max([val[1] for val in size_dict.values()]))
            self.surface_sizes.append(size_dict)
        if self.adjust:
            self.base["rect"].height = self.total_height()

    def total_height(self):
        height = 0
        min_height = 1000
        if self.surface_sizes:
            for dictionary in self.surface_sizes:
                height += dictionary[-1][1]
                if min_height > dictionary[-1][1]:
                    min_height = dictionary[-1][1]
            return int(height + 2 * min_height)
        return height

    # Blit lines of text from dictionaries onto surface
    def _render_surfaces(self):
        """ Render all lines onto surface """

        rect = self.base["rect"]
        totals = [size_dict.get(-1, (0, 0)) for size_dict in self.surface_sizes]
        total_height = sum([val[1] for val in totals])
        text_left = self.base["frame"] * 2  # left margin for text

        surface = pygame.Surface(rect.size)
        if self.base["background_colour"] is None:
            surface.fill(BLACK)
            surface.set_colorkey(BLACK)
        else:
            surface.fill(self.base["background_colour"])

        self._do_frame(surface)

        if self.base["v_justification"] > 0:
            text_y = (rect.height - (self.base["v_justification"] - 1) * 40 - total_height) / 2
        else:
            text_y = 0

        number = 0
        for dictionary in self.surface_dicts:
            size_dict = self.surface_sizes[number]
            text_width, text_height, text_start = 0, 0, 0

            for key in dictionary:
                if key == 0:
                    text_width, text_height = size_dict[-1]
                    if self.base["justification"] == 1:
                        text_start = (rect.width - text_width) / 2
                    elif self.base["justification"] == 2:
                        text_start = rect.width - text_width - text_left
                    else:
                        text_start = text_left
                # Blit sections aligned by base
                surface.blit(dictionary[key], (text_start, text_y + text_height - size_dict[key][1]))
                text_start += size_dict[key][0]
            text_y += text_height
            number += 1
        return surface

    def _do_frame(self, surface):
        """ Draw frame for text """

        rect = self.base["rect"]
        frame = self.base["frame"]

        if self.base["frame"] > 0:
            frame_rect = (0, 0, rect.width, rect.height)
            self._draw_frame(surface, self.base["frame_colour"], frame_rect, frame, self.base["background_colour"])

    @staticmethod
    def _draw_frame(surface, frame_colour, frame_rect, frame, i_colour=WHITE):
        """ Draw framed rectangle - avoids problems with corner pixels not drawing """
        i_frame = (frame_rect[0] + frame // 2, frame_rect[1] + frame // 2, frame_rect[2] - frame,
                   frame_rect[3] - frame)
        pygame.draw.rect(surface, frame_colour, frame_rect)
        pygame.draw.rect(surface, i_colour, i_frame)

    # Procedures to handle embedded commands
    def _process_bold(self, s_line):
        """ process inline \\B """

        if self.flags["bold"] is False:
            self.flags["bold"] = True
            self.current["font"].set_bold(True)
        else:
            self.flags["bold"] = False
            self.current["font"].set_bold(False)
        return s_line[2][1:]

    def _process_underline(self, s_line):
        """ process inline \\S """

        if self.flags["underline"] is False:
            self.flags["underline"] = True
            self.current["font"].set_underline(True)
        else:
            self.flags["underline"] = False
            self.current["font"].set_underline(False)
        return s_line[2][1:]

    def _process_italic(self, s_line):
        """ process inline \\I """

        if self.flags["italic"] is False:
            self.flags["italic"] = True
            self.current["font"].set_italic(True)
        else:
            self.flags["italic"] = False
            self.current["font"].set_italic(False)
        return s_line[2][1:]

    def _process_colour(self, s_line):
        """ process inline \\C """

        if self.flags["setcolour"] is False:
            line = s_line[2]
            col_string = line[2:].split(")", 1)[0].split(",")
            self.current["text_colour"] = tuple(int(x) for x in col_string)
            self.flags["setcolour"] = True
            line = s_line[2][2:].split(")", 1)[1]
        else:
            self.current["text_colour"] = self.base["text_colour"]
            self.flags["setcolour"] = False
            line = s_line[2][1:]
        return line

    def _process_font(self, s_line):
        """ process inline \\F """

        if self.flags["setfont"] is False:
            line = s_line[2]
            font_string = line[2:].split(")", 1)[0].split(",")
            font_tuple = tuple(x for x in font_string)
            self.current["font"] = pygame.font.SysFont(font_tuple[0], int(font_tuple[1]))
            self.flags["setfont"] = True
            line = s_line[2][2:].split(")", 1)[1]
        else:
            self.current["font"] = self.base["base_font"]
            self.flags["setfont"] = False
            line = s_line[2][1:]
        return line

    # reset all flags to False
    def _reset_flags(self):
        """ Reset all flags to False """

        self.flags["bold"] = False
        self.flags["underline"] = False
        self.flags["italic"] = False
        self.flags["setcolour"] = False
        self.flags["setfont"] = False


__author__ = 'joe'

import datetime

class EntryFactory():

    def __init__(self):
        self.index = 0

    def getEntry(self, text, user):
        entry = Entry(text, user, self.index)
        self.index += 1
        return entry

class Entry:

    def __init__(self, text, user, index):
        self.text = text
        self.user = user
        self.index = index
        self.timestamp = datetime.datetime.now()


NO_OF_CHARS = 26

def missingChars(str):
    List = []
    for i in range(26):
        List.append(False)

    for c in str.lower():
        if not c == "":
            List[ord(c) - ord('a')] = True

    for i in range(26):
        if List[i]==False:
            # Python 3 code for printing on the same line printing
            print(chr(i+ ord('a')) , end =" ")

string="geeks"
missingChars(string)


import time
from rich.console import Console

console = Console(log_path=False)

if __name__ == "__main__":
    for i in range(7):
        time.sleep(0.23)
        console.log(f"i am at iteration {i}")
        console.log({c: i for c in "abcdefghjkl"})


with open("input.txt") as get_input:
    lines = []
    for line in get_input:
        lines.append(line)
    a = [int(x) for x in lines[0].strip().split(' ')]

def compare(left, right):
    if (left['max_prefix'] > left['total_sum'] + right['max_prefix']):
        max_prefix = left['max_prefix']
        max_prefix_b = left['max_prefix_b']
    else:
        max_prefix = left['total_sum'] + right['max_prefix']
        max_prefix_b = right['max_prefix_b']

    if (right['max_suffix'] > right['total_sum'] + left['max_suffix']):
        max_suffix = right['max_suffix']
        max_suffix_b = right['max_suffix_b']
    else:
        max_suffix = right['total_sum'] + left['max_suffix']
        max_suffix_b = left['max_suffix_b']

    total_sum = left['total_sum'] + right['total_sum']
    if (left['max_sum'] > left['max_suffix'] + right['max_prefix'] and left['max_sum'] > right['max_sum'] ):
        max_sum = left['max_sum']
        max_sum_b = left['max_sum_b']
    elif ( right['max_sum'] > left['max_suffix'] + right['max_prefix']):
        max_sum = right['max_sum']
        max_sum_b = right['max_sum_b']
    else:
        max_sum = left['max_suffix'] + right['max_prefix']
        max_sum_b = (left['max_suffix_b'], right['max_prefix_b'])

    return {'total_sum': total_sum,
            'max_sum': max_sum,
            'max_prefix': max_prefix,
            'max_suffix': max_suffix,
            'max_prefix_b': max_prefix_b,
            'max_suffix_b': max_suffix_b,
            'max_sum_b': max_sum_b
           }

def _max_subarray(a, low, high):
    if (low == high):
        return {'total_sum': a[low],
            'max_sum': a[low],
            'max_prefix': a[low],
            'max_suffix': a[low],
            'max_prefix_b': low,
            'max_suffix_b': low,
            'max_sum_b': (low, low)
           }

    mid = (low + high) // 2
    left = _max_subarray(a, low, mid)
    right = _max_subarray(a, mid + 1, high)
    return compare(left, right)

def max_subarray(a):
    cache = _max_subarray(a, 0, len(a) - 1)
    max_sum = max(cache['max_sum'], cache['max_prefix'], cache['max_suffix'])
    if (max_sum == cache['max_sum']):
        l, r = cache['max_sum_b']
    elif(max_sum == cache['max_prefix']):
        l, r = 0, cache['max_prefix_b']
    else:
        l, r = cache['max_suffix_b'], len(a) - 1
    return (max_sum, (l, r))

with open("output.txt", 'w') as wrt_out:
	max_sum, (l, r) = max_subarray(a)
	wrt_out.write(str(max_sum) + "\n")
	wrt_out.write(' '.join([str(x) for x in a[l:r+1]]))


import random
import sys
def Boop():
    number = random.randint(0,100)
    correct = False
    while correct == False:
        answer = int(input("Choose a number between 0 and 100: "))
        if answer > number:
            print("Number too high!")
        elif answer < number:
            print("Number too low!")
        elif answer == number:
            print("Correct!")
            correct = True
    Check = input("Do you wish to go again?: ")
    if Check == "Yes":
        Boop()
    else:
        print("End")
        sys.exit()
Boop()


'''
PING a server with count times and get the RTT list
'''
from subprocess import Popen, PIPE
import string
import re
import socket
import time

# server_ip = '104.155.15.0'
PING_PORT = 8717

# Customized Ping Message to a Ping Server using TCP
def ping(ip):
    # Connect to the server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, PING_PORT))
    # Send a PING message
    message = 'PING'
    ts_sent = time.time()
    len_sent = s.send(message)
    # Receive a response
    response = s.recv(len_sent)
    ts_recv = time.time()
    ## Compute rtt
    rtt = (ts_recv - ts_sent) * 1000
    s.close()
    return rtt

def extract_number(s,notfound='NOT_FOUND'):
    regex=r'[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?'
    return re.findall(regex,s)

def getRTT(ip, count):
	'''
	Pings a host and return True if it is available, False if not.
	'''
	cmd = ['ping', '-c', str(count), '-i', '1', ip]
	process = Popen(cmd, stdout=PIPE, stderr=PIPE)
	stdout, stderr = process.communicate()
	rttList = parsePingRst(stdout, count)
	return rttList

def getMnRTT(ip, count):
	rttList = getRTT(ip, count)
	if len(rttList) > 0:
		mnRTT = sum(rttList) / float(len(rttList))
	else:
		mnRTT = 500.0
	return mnRTT

def parsePingRst(pingString, count):
	rtts = []
	lines = pingString.splitlines()
	for line in lines:
		curline = line
		# print curline
		if "time=" in curline:
			curDataStr = curline.split(':', 2)[1]
			curData = extract_number(curDataStr)
			rtts.append(float(curData[-1]))
	return rtts

# if getRTT(server_ip, 5):
#	print '{} is available'.format(server_ip)
#else:
#	print '{} is not available'.format(server_ip)


import unittest
import sys

from grammar_tester.psparse import strip_token, parse_tokens, parse_links, parse_postscript, get_link_set, prepare_tokens
from grammar_tester.optconst import *
from grammar_tester.parsestat import parse_metrics

gutenberg_children_bug = \
"""
[(LEFT-WALL)(")(project.v)(gutenberg[?].n)('s.p)(alice[?].n)('s.p)(adventures.n)([in])(wonderland.n)
(,)(by)(lewis[!])(carroll[?].n)(")(()(edited.v-d)())]
[[0 2 1 (Wi)][0 1 0 (ZZZ)][2 9 2 (Os)][6 9 1 (Ds**x)][5 6 0 (YS)][4 5 0 (D*u)][3 4 0 (YS)]
[7 9 0 (AN)][9 11 1 (MXsx)][10 11 0 (Xd)][11 17 2 (Xc)][11 13 1 (Jp)][12 13 0 (AN)][13 16 1 (MXsp)]
[16 17 0 (Xca)][13 14 0 (ZZZ)][15 16 0 (Xd)]]
[0]
"""
gutenberg_children_bug2 = "[ebook # @number@ ][(LEFT-WALL)(release.n)(date.n)(:.j)(@date@[?].n)([)(ebook[?].a)([#])" \
                          "(@number@[?].n)(])][[0 3 2 (Xx)][0 2 1 (Wa)][1 2 0 (AN)][3 4 0 (Jp)][4 8 2 (MXs)]" \
                          "[5 8 1 (Xd)][6 8 0 (A)][8 9 0 (Xc)]][0]"

# cleaned_Gutenberg_Children bug list
cgch_bug_001 = \
"""
[ illustration : " i tell you what , you stay right here ! "[(LEFT-WALL)([[])(illustration.n-u)(:.v)(")([i])(tell.v)(you)(what)(,)(you)(stay.v)(right.a)(here)(!)(")][[0 14 4 (Xp)][0 9 3 (Xx)][0 6 2 (WV)][0 2 0 (Wd)][2 3 0 (Ss)][3 6 1 (I*v)][3 4 0 (ZZZ)][6 8 1 (QI)][6 7 0 (Ox)][9 11 1 (WV)][9 10 0 (Wd)][10 11 0 (Sp)][11 12 0 (Pa)][12 13 0 (MVp)][14 15 0 (ZZZ)]][0]
"""
# most people start at our web site which has the main pg search facility:
alice_bug_001 = \
"""
[(most)(people)(start)(at)([our])(web)(site)([which])([has])([the])
([main])([pg])([search])([facility:])]
[[0 1 0 (C26C33)][1 2 0 (C33C54)][2 3 0 (C54C22)][3 6 1 (C22C17)][5 6 0 (C23C17)]]
[0]
"""

# its business office is located at @number@ north @number@ west, salt lake city, ut @number@ , ( @number@ ) @number@ - @number@ , email business@pglaf.org.
alice_bug_002 = \
"""
[(LEFT-WALL)(its)(business.n-u)(office.n)(is.v)(located.v-d)(at)(@number@[?].n)(north.a)(@number@[?].a)
(west.a)(,)(salt.n-u)(lake.n)(city.n)(,)(ut[?].v)(@number@[?].a)(,)([(])
(@number@[?].a)())(@number@[?].a)(-.r)(@number@[?].a)(,)(email.s)(business@pglaf.org[?].n)(.)]
[[0 28 6 (Xp)][0 16 5 (WV)][0 11 4 (Xx)][0 5 3 (WV)][0 3 2 (Wd)][1 3 1 (Ds**x)][2 3 0 (AN)]
[3 4 0 (Ss*s)][4 5 0 (Pv)][5 9 1 (Pa)][5 6 0 (MVp)][6 7 0 (Jp)][7 8 0 (Mp)][9 10 0 (MVp)]
[11 15 3 (Xx)][15 16 0 (Wa)][11 14 2 (Wa)][12 14 1 (AN)][13 14 0 (AN)][16 27 5 (Os)][26 27 0 (AN)]
[17 26 4 (A)][17 18 0 (Xc)][20 26 3 (A)][20 21 0 (Xc)][22 26 2 (A)][22 23 0 (Xc)][24 26 1 (A)]
[24 25 0 (Xc)]]
[0]
"""

gutenberg_children_bug_002 = \
"""
[(LEFT-WALL)([a])(millennium.n-u)(fulcrum.n)(edition.n)([(])([c])([)])(1991[!])([by])
(duncan[?].n)(research.n-u)]
[[0 11 5 (Wa)][2 11 4 (AN)][3 11 3 (AN)][4 11 2 (AN)][8 11 1 (AN)][10 11 0 (AN)]]
[0]
"""

gutenberg_children_bug_002t = "[(LEFT-WALL)([a])(millennium.n-u)(fulcrum.n)(edition.n)([(])([c])([)])(1991[!])([by])" \
                              "(duncan[?].n)(research.n-u)]"

gutenberg_children_bug_002tr = [r"###LEFT-WALL###", "[a]", "millennium", "fulcrum", "edition", "[(]", "[c]", "[)]",
                                "1991", "[by]", "duncan", "research"]

gutenberg_children_bug_002l = "[[0 11 5 (Wa)][2 11 4 (AN)][3 11 3 (AN)][4 11 2 (AN)][8 11 1 (AN)][10 11 0 (AN)]][0]"

gutenberg_children_bug_002lr = [(0, 11), (2, 11), (3, 11), (4, 11), (8, 11), (10, 11)]

# class TokenString(str):
#     def __new__(cls, content):
#         obj = super(TokenString, cls).__new__(cls, content)
#         obj.brace_counter = 0
#         obj.brckt_counter = 0
#         obj.start_pos = 0
#         return obj
#
#     def line(self):
#         print("-> "+self[1:-1])
#
#
# def find_end_of_token(text, pos: int) -> int:
#
#     braces = 0
#     brackets = 0
#
#     while pos < len(text):
#
#         if text[pos] == r"(":
#             braces += 1
#
#         elif text[pos] == r")":
#             # if not "[)]"
#             if not brackets:
#                 braces -= 1
#
#             if not braces:
#                 return pos-1
#
#         elif text[pos] == r"[":
#             brackets += 1
#
#         elif text[pos] == r"]":
#             brackets -= 1
#
#         pos += 1

class TestPSParse(unittest.TestCase):

    # def test_ps_parse_tokens(self):
    #     ts = TokenString(gutenberg_children_bug_002t)
    #
    #     ts.line()
    #
    #     # tokens = [t for t in ts]
    #
    #     self.assertTrue(True)

    post_all_walls = "[(LEFT-WALL)(Dad[!])(was.v-d)(not.e)(a)(parent.n)(before)(.)(RIGHT-WALL)]" \
                     "[[0 7 2 (Xp)][0 1 0 (Wd)][1 2 0 (Ss*s)][2 5 1 (Osm)][2 3 0 (EBm)]" \
                     "[4 5 0 (Ds**c)][5 6 0 (Mp)][7 8 0 (RW)]][0]"
    post_no_walls = "[(eagle)(has)(wing)(.)][[0 2 1 (C04C01)][1 2 0 (C01C01)][2 3 0 (C01C05)]][0]"
    post_no_links = "[([herring])([isa])([fish])([.])][][0]"

    link_str = "[0 7 2 (Xp)][0 1 0 (Wd)][1 2 0 (Ss*s)][2 5 1 (Osm)][2 3 0 (EBm)][4 5 0 (Ds**c)][5 6 0 (Mp)][7 8 0 (RW)]"

    tokens_all_walls = "(LEFT-WALL)(Dad[!])(was.v-d)(not.e)(a)(parent.n)(before)(.)(RIGHT-WALL)"
    tokens_no_walls = "(eagle)(has)(wing)(.)"
    tokens_no_walls_no_period = "(eagle)(has)(wing)"

    @staticmethod
    def cmp_lists(list1: [], list2: []) -> bool:
        if list1 is None or list2 is None or len(list1) != len(list2):
            return False

        for i in range(0, len(list1)):
            if list1[i] != list2[i]:
                return False

        return True

    def test_strip_token(self):
        """ test_strip_token """
        # print(__doc__, sys.stderr)

        self.assertEqual(strip_token("strange[!]"), "strange")
        self.assertEqual(strip_token("strange.a"), "strange")
        self.assertEqual(strip_token("[strange]"), "[strange]")

    # @unittest.skip
    def test_parse_tokens(self):
        """ test_parse_tokens """
        # print(__doc__, sys.stderr)

        options = 0

        # No RIGHT-WALL, no CAPS
        options |= BIT_STRIP
        # tokens = parse_tokens(self.tokens_all_walls, options)
        # self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'dad', 'was', 'not', 'a',
        #                                         'parent', 'before', '.']))

        # Tokens without walls
        tokens = parse_tokens(self.tokens_no_walls, options)[0]
        self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'eagle', 'has', 'wing', '.']))

        # RIGHT-WALL and CAPS, no STRIP
        options |= (BIT_RWALL | BIT_CAPS)
        options &= ~BIT_STRIP
        tokens = parse_tokens(self.tokens_all_walls, options)[0]
        self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'Dad[!]', 'was.v-d', 'not.e', 'a',
                                                'parent.n', 'before', '.', '###RIGHT-WALL###']))

        # Tokens without walls
        tokens = parse_tokens(self.tokens_no_walls, options)[0]
        # print(tokens, file=sys.stdout)
        self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'eagle', 'has', 'wing', '.']))

    @unittest.skip
    def test_parse_tokens_no_left_wall(self):
        # NO_LWALL and CAPS, no STRIP
        options = 0
        options |= BIT_CAPS | BIT_NO_LWALL
        # options |= (BIT_NO_LWALL | BIT_CAPS)
        # options &= (~(BIT_STRIP | BIT_RWALL))
        tokens = parse_tokens(self.tokens_all_walls, options)[0]

        # print(tokens)

        self.assertTrue(self.cmp_lists(tokens, ['Dad[!]', 'was.v-d', 'not.e', 'a',
                                                'parent.n', 'before', '.']))

    @unittest.skip
    def test_parse_tokens_no_walls_no_period(self):
        options = 0
        options |= BIT_STRIP | BIT_NO_PERIOD | BIT_NO_LWALL
        tokens = parse_tokens(self.tokens_all_walls, options)[0]

        # print(tokens)

        self.assertTrue(self.cmp_lists(tokens, ['dad', 'was', 'not', 'a', 'parent', 'before']))

    @unittest.skip
    def test_parse_tokens_rwall_no_period(self):
        options = 0
        options |= BIT_STRIP | BIT_NO_PERIOD | BIT_RWALL
        tokens = parse_tokens(self.tokens_all_walls, options)[0]

        # print(tokens)

        self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'dad', 'was', 'not', 'a', 'parent', 'before',
                                                '###RIGHT-WALL###']))

    @unittest.skip
    def test_parse_tokens_no_period(self):
        options = 0
        options |= BIT_STRIP | BIT_NO_PERIOD | BIT_RWALL
        tokens = parse_tokens(self.tokens_no_walls, options)[0]

        # print(tokens)

        self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'eagle', 'has', 'wing']))

    # @unittest.skip
    def test_parse_no_period_if_no_period(self):
        options = 0
        options |= BIT_STRIP | BIT_NO_PERIOD | BIT_RWALL
        tokens = parse_tokens(self.tokens_no_walls_no_period, options)[0]

        # print(tokens)

        self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'eagle', 'has', 'wing']))

    # @unittest.skip
    def test_parse_links(self):
        """ test_parse_links """
        # print(__doc__, sys.stderr)

        links = parse_links(self.link_str, ['###LEFT-WALL###', 'dad', 'was', 'not', 'a', 'parent', 'before', '.'], 0)

        # [0 7 2 (Xp)][0 1 0 (Wd)][1 2 0 (Ss*s)][2 5 1 (Osm)][2 3 0 (EBm)][4 5 0 (Ds**c)][5 6 0 (Mp)][7 8 0 (RW)]
        self.assertTrue(self.cmp_lists(links, [  (0, 7),
                                                 (0, 1),
                                                 (1, 2),
                                                 (2, 5),
                                                 (2, 3),
                                                 (4, 5),
                                                 (5, 6) ]))

    # @unittest.skip
    def test_parse_postscript_all_walls(self):
        """ test_parse_postscript """
        # print(__doc__, sys.stderr)

        options = 0
        options |= (BIT_RWALL | BIT_CAPS)
        options &= ~BIT_STRIP
        tokens, links = parse_postscript(self.post_all_walls, options, sys.stdout)
        pm = parse_metrics(tokens)
        self.assertEqual(1.0, pm.completely_parsed_ratio)
        self.assertEqual(0.0, pm.completely_unparsed_ratio)
        self.assertEqual(1.0, pm.average_parsed_ratio)

    # @unittest.skip
    def test_parse_postscript_no_walls(self):
        """ test_parse_postscript """
        # print(__doc__, sys.stderr)

        options = 0
        options |= (BIT_RWALL | BIT_CAPS)
        options &= ~BIT_STRIP

        tokens, links = parse_postscript(self.post_no_walls, options, sys.stdout)
        pm = parse_metrics(tokens)
        self.assertEqual(1.0, pm.completely_parsed_ratio)
        self.assertEqual(0.0, pm.completely_unparsed_ratio)
        self.assertEqual(1.0, pm.average_parsed_ratio)

    # @unittest.skip
    def test_parse_postscript_no_links(self):
        """ test_parse_postscript """
        # print(__doc__, sys.stderr)

        options = 0
        options |= (BIT_RWALL | BIT_CAPS)
        options &= ~BIT_STRIP

        tokens, links = parse_postscript(self.post_no_links, options, sys.stdout)
        pm = parse_metrics(tokens)
        self.assertEqual(0.0, pm.completely_parsed_ratio)
        self.assertEqual(1.0, pm.completely_unparsed_ratio)
        self.assertEqual(0.0, pm.average_parsed_ratio)

    # @unittest.skip
    def test_parse_postscript_gutenchildren_bug(self):
        """ test_parse_postscript """
        # print(__doc__, sys.stderr)

        options = 0
        # options |= (BIT_RWALL | BIT_CAPS)
        # options &= ~BIT_STRIP

        tokens, links = parse_postscript(gutenberg_children_bug, options, sys.stdout)

        self.assertEqual(18, len(tokens))

        pm = parse_metrics(tokens)

        self.assertEqual(0.0, pm.completely_parsed_ratio)
        self.assertEqual(0.0, pm.completely_unparsed_ratio)
        self.assertEqual(0.9411764705882353, float(pm.average_parsed_ratio))
        # self.assertEqual(16.0/17.0, pm.average_parsed_ratio)

    @unittest.skip
    def test_parse_gutenchildren_bug_002(self):
        options = BIT_NO_LWALL | BIT_NO_PERIOD | BIT_STRIP

        tokens = parse_tokens(gutenberg_children_bug_002t, options)[0]

        self.assertEqual(tokens, gutenberg_children_bug_002tr)

    @unittest.skip
    def test_parse_postscript_gutenchildren_bug_002(self):

        options = BIT_NO_LWALL | BIT_NO_PERIOD | BIT_STRIP

        tokens, links = parse_postscript(gutenberg_children_bug_002, options, sys.stdout)

        print(tokens)

        self.assertEqual(12, len(tokens))
        self.assertEqual(6, len(links))

        # pm = parse_metrics(tokens)
        #
        # self.assertEqual(0.0, pm.completely_parsed_ratio)
        # self.assertEqual(0.0, pm.completely_unparsed_ratio)
        # self.assertEqual(0.94117647, float(pm.average_parsed_ratio))

        # self.assertEqual(16.0/17.0, pm.average_parsed_ratio)

    # @unittest.skip
    def test_parse_postscript_alice_bug_001(self):
        """ test_parse_postscript """
        # print(__doc__, sys.stderr)

        options = 0
        # options |= (BIT_RWALL | BIT_CAPS)
        options &= ~BIT_STRIP

        tokens, links = parse_postscript(alice_bug_001, options, sys.stdout)

        self.assertEqual(15, len(tokens))

        for link in links:
            self.assertTrue(link[0]<15 and link[1]<15, str(link))

        # self.assertEqual(["most", "people", "start", "at", "our", "web", "site", "which", "has", "the", "main", "pg",
        #                   "search", "facility:"], tokens)

    def test_parse_postscript_alice_bug_002(self):
        options = 0
        # options |= (BIT_RWALL | BIT_CAPS)
        options &= ~BIT_STRIP

        tokens, links = parse_postscript(alice_bug_002, options, sys.stdout)

        self.assertEqual(29, len(tokens), tokens)

    def test_get_link_set(self):
        # post_all_walls = "[(LEFT-WALL)(Dad[!])(was.v-d)(not.e)(a)(parent.n)(before)(.)(RIGHT-WALL)]" \
        #                  "[[0 7 2 (Xp)][0 1 0 (Wd)][1 2 0 (Ss*s)][2 5 1 (Osm)][2 3 0 (EBm)]" \
        #                  "[4 5 0 (Ds**c)][5 6 0 (Mp)][7 8 0 (RW)]][0]"
        expected_set = {(1, 2), (2, 5), (2, 3), (4, 5), (5, 6)}
        options = BIT_NO_LWALL | BIT_NO_PERIOD | BIT_STRIP | BIT_PARSE_QUALITY
        tokens, links = parse_postscript(self.post_all_walls, options, sys.stdout)
        result_set = get_link_set(tokens, links, options)

        print(expected_set)
        print(result_set)

        self.assertTrue(result_set == expected_set)

    def test_prepare_tokens_both_walls_period_no_options(self):
        token_list = ['###LEFT-WALL###', 'dad', 'was', 'not', 'a', 'parent', 'before', '.', '###RIGHT-WALL###']
        token_list_no_walls = ['dad', 'was', 'not', 'a', 'parent', 'before', '.']
        token_list_no_period = ['###LEFT-WALL###', 'dad', 'was', 'not', 'a', 'parent', 'before', '###RIGHT-WALL###']
        token_list_words_only = ['dad', 'was', 'not', 'a', 'parent', 'before']

        # Should take no action
        options = 0 | BIT_RWALL
        result_list = prepare_tokens(token_list, options)
        self.assertEqual(token_list, result_list, "Lists are not the same!!!")

        # Should return a list with no walls only word-tokens and period
        options = 0 | BIT_NO_LWALL
        result_list = prepare_tokens(token_list, options)
        self.assertEqual(token_list_no_walls, result_list, "Lists are not the same!!!")

        # Should return a list with walls, word-tokens and period
        options = 0 | BIT_RWALL | BIT_NO_PERIOD
        result_list = prepare_tokens(token_list, options)
        self.assertEqual(token_list_no_period, result_list, "Lists are not the same!!!")

        # Should return a list with no walls and no period
        options = 0 | BIT_NO_LWALL | BIT_NO_PERIOD
        result_list = prepare_tokens(token_list, options)
        self.assertEqual(token_list_words_only, result_list, "Lists are not the same!!!")

        tokens_period_in_brackets = ["dad", "[has]", "[a]", "[telescope]", "[.]"]
        options = 0 | BIT_NO_LWALL | BIT_NO_PERIOD
        result_list = prepare_tokens(tokens_period_in_brackets, options)
        self.assertEqual(["dad", "[has]", "[a]", "[telescope]"], result_list, "Lists are not the same!!!")

        tokens_only_period_unboxed = ["[dad]", "has", "[binoculars]", "."]
        options = 0 | BIT_NO_LWALL | BIT_NO_PERIOD
        result_list = prepare_tokens(tokens_only_period_unboxed, options)
        self.assertEqual(["[dad]", "has", "[binoculars]"], result_list, "Lists are not the same!!!")

if __name__ == '__main__':
    unittest.main()


def skrot(message):
    S = list(map(ord, "ALGORYTM"))
    if message[-1] == "\n":
        message = message[:-1]
    to_fill = 8 - (len(message) % 8)
    message = message + ("." * to_fill)
    for start in range(0, len(message), 8):
        for j in range(8):
            S[j] = (S[j] + ord(message[start+j])) % 128
    result = ""
    for j in range(8):
        result += chr(65 + S[j] % 26)
    return result

def endecryptA(signature, d, n):
    if signature[-1] == "\n":
        signature = signature[:-1]
    result = ""
    for elem in list(map(int, signature.split())):
        result += chr((elem * d) % n)
    return result

signatures = open("podpisy.txt")
msgs = open("wiadomosci.txt")

for i in range(11):
    if skrot(msgs.readline()) == endecryptA(signatures.readline(), 3, 200):
        print(i+1, end=" ")

print()


from django.shortcuts import render, get_object_or_404

from django.utils import timezone
from django.shortcuts import redirect

from .models import Customer
# Create your views here.

def viewAll(request):
    customers = Customer.objects.all()

    if request.method == 'POST':
        results = Customer.objects.all()

        name = request.POST.get('name', None)
        print(results)
        if name:
            print('GOT NAME')
            results = results.filter(first_name__iexact=name)

            print(results)

        return render(request, 'CustomerAnalysis/base.html', {'matching_customers' : results, 'customers': customers})
    else:
        return render(request, 'CustomerAnalysis/base.html', {'customers': customers})