from django.contrib import admin
from .models import *
from django.contrib.admin import SimpleListFilter
import datetime
from dateutil.relativedelta import relativedelta

class AgeFilter(SimpleListFilter):
    title = 'Age'
    parameter_name = 'dob'

    def lookups(self, request, model_admin):
        return (
            ('adult', 'Equal or Above 23'),
            ('child', 'Below 23')
        )

    def queryset(self, request, queryset):
        if self.value() == 'adult':
            return queryset.filter(dob__lte=(datetime.datetime.now().date() - relativedelta(years=23)))
        elif self.value() == 'child':
            return queryset.filter(dob__gt=(datetime.datetime.now().date() - relativedelta(years=23)))

# Register your models here.
class profileAdmin(admin.ModelAdmin):
    list_display = ('pk', 'mobile', 'dl', 'dp', 'idProof', 'user', 'dob', 'rating', 'isOwner', 'isVerifiedRenter', 'isMobileVerified', 'otp')
    date_hierarchy = 'created'
    search_fields = ('^user__username', )
    list_filter = ('isOwner', 'isVerifiedRenter', 'isMobileVerified', AgeFilter)
    list_editable = ('isOwner', 'isVerifiedRenter')

class userReviewCommentAdmin(admin.ModelAdmin):
    list_display = ('pk', 'text', 'rating', 'profile', 'reviewer')
    date_hierarchy = 'created'

class UserAdmin(admin.ModelAdmin):
    list_display = ('pk', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined')

admin.site.register(profile, profileAdmin)
admin.site.register(userReviewComment, userReviewCommentAdmin)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)


import sys
from dataclasses import dataclass
from enum import Enum, auto
from typing import List, MutableSet

class Direction(Enum):
    Left = auto()
    Right = auto()
    Up = auto()
    Down = auto()

@dataclass
class Move():
    direction: Direction
    steps: int

@dataclass
class Coordinate():
    x: int
    y: int
    def __hash__(self) -> int:
        return hash((self.x, self.y))

@dataclass
class Coordinate_update():
    x_update: int
    y_update: int

tail_movement_set: MutableSet[tuple] = set()
current_knot_positions: List[Coordinate] = [Coordinate(0, 0) for _ in range(10)]
current_head_coordinate: Coordinate = Coordinate(0, 0)
current_tail_coordinate: Coordinate = Coordinate(0, 0)

def parseInput() -> List[Move]:
    head_move_list: List[Move] = []
    for line in sys.stdin:
        direction, steps = line.split(' ')
        direction_state: Direction = None
        if direction == 'L':
            direction_state = Direction.Left
        elif direction == 'R':
            direction_state = Direction.Right
        elif direction == 'U':
            direction_state = Direction.Up
        elif direction == 'D':
            direction_state = Direction.Down
        else:
            print(f'Why is it reaching here: {direction}')
        move = Move(direction=direction_state, steps=int(steps))
        head_move_list.append(move)
    return head_move_list

def are_knots_touching(index: int) -> bool:
    next_index = index + 1
    current_head_x, current_head_y = current_knot_positions[index].x, current_knot_positions[index].y
    current_tail_x, current_tail_y = current_knot_positions[next_index].x, current_knot_positions[next_index].y
    if current_head_x == current_tail_x:
        if current_head_y == current_tail_y + 1 or current_head_y == current_tail_y - 1:
            return True
        else:
            return False
    if current_tail_y == current_head_y:
        if current_head_x == current_tail_x + 1 or current_head_x == current_tail_x - 1:
            return True
        else:
            return False
    if (current_tail_x == current_head_x + 1 and (current_tail_y == current_head_y + 1 or current_tail_y == current_head_y - 1)) or (current_tail_x == current_head_x - 1 and (current_tail_y == current_head_y + 1 or current_tail_y == current_head_y - 1)):
        return True
    else:
        return False

def how_to_update_y(index: int):
    next_index = index + 1
    current_head_x, current_head_y = current_knot_positions[index].x, current_knot_positions[index].y
    current_tail_x, current_tail_y = current_knot_positions[next_index].x, current_knot_positions[next_index].y
    # print(f'Adding coordinates: head: {current_head_coordinate}, tail: {current_tail_coordinate}')
    if current_head_x == current_tail_x:
        if current_head_y > current_tail_y + 1:
            current_knot_positions[next_index].y += 1
        elif current_head_y < current_tail_y - 1:
            current_knot_positions[next_index].y += -1
    elif current_head_y == current_tail_y:
        if current_head_x > current_tail_x + 1:
            current_knot_positions[next_index].x += 1
        elif current_head_x < current_tail_x - 1:
            current_knot_positions[next_index].x += -1
    else:
        if not are_knots_touching(index):
            if current_head_y > current_tail_y:
                current_knot_positions[next_index].y += 1
            elif current_head_y < current_tail_y:
                current_knot_positions[next_index].y += -1
            if current_head_x > current_tail_x:
                current_knot_positions[next_index].x += 1
            elif current_head_x < current_tail_x:
                current_knot_positions[next_index].x += -1
    if index == 8:
        tail_movement_set.add((current_knot_positions[next_index].x, current_knot_positions[next_index].y))

def move_one_direction(move: Move):
    direction, steps = move.direction, move.steps
    for step in range(steps):
        if direction == Direction.Left:
            current_knot_positions[0].x -= 1
        elif direction == Direction.Right:
            current_knot_positions[0].x += 1
        elif direction == Direction.Up:
            current_knot_positions[0].y += 1
        elif direction == Direction.Down:
            current_knot_positions[0].y -= 1
        for knot in range(9):
            how_to_update_y(knot)

def move_all(head_move_list: List[Move]):
    for move in head_move_list:
        move_one_direction(move)

def count_distinct_tail_positions() -> int:
    return len(tail_movement_set)

if __name__ == '__main__':
    head_move_list = parseInput()
    move_all(head_move_list)
    print(tail_movement_set)
    print(count_distinct_tail_positions())
    # current_head_coordinate.x, current_head_coordinate.y = 2, 0
    # print(how_to_update_y())


from re import *
from collections import OrderedDict

t_list=OrderedDict()
nt_list=OrderedDict()
production_list=[]

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

class Terminal:

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

	def __str__(self):
		return self.symbol

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

class NonTerminal:

	def __init__(self, symbol):
		self.symbol=symbol
		self.first=set()
		self.follow=set()

	def __str__(self):
		return self.symbol

	def add_first(self, symbols): self.first |= set(symbols) #union operation

	def add_follow(self, symbols): self.follow |= set(symbols)

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

def compute_first(symbol): #chr(1013) corresponds (ϵ) in Unicode

	global production_list, nt_list, t_list

# if X is a terminal then first(X) = X
	if symbol in t_list:
		return set(symbol)

	for prod in production_list:
		head, body=prod.split('->')

		if head!=symbol: continue

# if X -> is a production, then first(X) = epsilon
		if body=='':
			nt_list[symbol].add_first(chr(1013))
			continue

		if body[0]==symbol: continue

		for i, Y in enumerate(body):
# for X -> Y1 Y2 ... Yn, first(X) = non-epsilon symbols in first(Y1)
# if first(Y1) contains epsilon,
#	first(X) = non-epsilon symbols in first(Y2)
#	if first(Y2) contains epsilon
#   ...
			t=compute_first(Y)
			nt_list[symbol].add_first(t-set(chr(1013)))
			if chr(1013) not in t:
				break
# for i=1 to n, if Yi contains epsilon, then first(X)=epsilon
			if i==len(body)-1:
				nt_list[symbol].add_first(chr(1013))

	return nt_list[symbol].first

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

def get_first(symbol): #wrapper method for compute_first

	return compute_first(symbol)

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

def compute_follow(symbol):

	global production_list, nt_list, t_list

# if A is the start symbol, follow (A) = $
	if symbol == list(nt_list.keys())[0]: #this is okay since I'm using an OrderedDict
		nt_list[symbol].add_follow('$')

	for prod in production_list:
		head, body=prod.split('->')

		for i, B in enumerate(body):
			if B != symbol: continue

# for A -> aBb, follow(B) = non-epsilon symbols in first(b)
			if i != len(body)-1:
				nt_list[symbol].add_follow(get_first(body[i+1]) - set(chr(1013)))

# if A -> aBb where first(b) contains epsilon, or A -> aB then follow(B) = follow (A)
			if i == len(body)-1 or chr(1013) in get_first(body[i+1]) and B != head:
				nt_list[symbol].add_follow(get_follow(head))

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

def get_follow(symbol):

	global nt_list, t_list

	if symbol in t_list.keys():
		return None

	return nt_list[symbol].follow

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

def main(pl=None):

	#print('''Enter the grammar productions (enter 'end' or return to stop)
#(Format: "A->Y1Y2..Yn" {Yi - single char} OR "A->" {epsilon})''')

	global production_list, t_list, nt_list
	ctr=1

	t_regex, nt_regex=r'[a-z\W]', r'[A-Z]'

	if pl==None:

		while True:

			#production_list.append(input('{})\t'.format(ctr)))

			production_list.append(input().replace(' ', ''))

			if production_list[-1].lower() in ['end', '']:
				del production_list[-1]
				break

			head, body=production_list[ctr-1].split('->')

			if head not in nt_list.keys():
				nt_list[head]=NonTerminal(head)

			#for all terminals in the body of the production
			for i in finditer(t_regex, body):
				s=i.group()
				if s not in t_list.keys(): t_list[s]=Terminal(s)

			#for all non-terminals in the body of the production
			for i in finditer(nt_regex, body):
				s=i.group()
				if s not in nt_list.keys(): nt_list[s]=NonTerminal(s)

			ctr+=1

	if pl!=None:

		for i, prod in enumerate(pl):

			if prod.lower() in ['end', '']:
				del pl[i:]
				break

			head, body=prod.split('->')

			if head not in nt_list.keys():
				nt_list[head]=NonTerminal(head)

			#for all terminals in the body of the production
			for i in finditer(t_regex, body):
				s=i.group()
				if s not in t_list.keys(): t_list[s]=Terminal(s)

			#for all non-terminals in the body of the production
			for i in finditer(nt_regex, body):
				s=i.group()
				if s not in nt_list.keys(): nt_list[s]=NonTerminal(s)

		return pl
# ------------------------------------------------------------------

if __name__=='__main__':

	main()


import torch
import torch.nn as nn
import numpy as np
from tqdm import tqdm

t_start = 2000
t_end   = 40000
interval= 400
final_density = (0.05, 0.05, 0.2)

def sparsity(net, i):
    if i < t_start:
        return
    if (i - t_start) % interval != 0 and i < t_end:
        return
    p = net.module.gru1.state_dict()['weight_hh_l0'].transpose(1, 0)
    nb = p.shape[1] // p.shape[0]
    N = p.shape[0]
    for k in range(nb):
        density = final_density[k]
        if i < t_end:
            r = 1.0 - (i - t_start) / (t_end - t_start)
            density = 1 - (1 - final_density[k]) * (1-r*r*r)
        A = p[:, k*N:(k+1)*N]
        A = A - torch.diag(torch.diag(A))
        L = torch.reshape(A, (N, N//16, 16))
        S = torch.sum(L*L, axis=-1)
        SS, _ = torch.sort(torch.reshape(S, (-1,)))
        thresh = SS[round(N*N//16*(1-density))]
        mask = (S>=thresh).float()
        mask = torch.repeat_interleave(mask, 16, axis=1)
        mask.add_(torch.eye(N).cuda()).clamp_(max=1)
        p[:, k*N:(k+1)*N] = p[:, k*N:(k+1)*N]*mask
    net.module.gru1.state_dict()['weight_hh_l0'][:] = p.transpose(1, 0)

def train(net, dataloader, loss, lr=0.001, epochs=120):
    opt = torch.optim.Adam(net.parameters(), betas=(0.9, 0.99), eps=1e-7, lr=lr)
    scheduler = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda=lambda it: lr/(1. + 5e-5 * it))
    iteration = 0
    for epoch in range(1, epochs+1):
        print('Epoch:\t'+str(epoch)+'/'+str(epochs))
        total_loss = []
        for i, (pcm, feat, pitch, target) in enumerate(tqdm(dataloader), 1):
            iteration += 1
            pcm    = pcm.type(torch.LongTensor).cuda()
            feat   = feat.cuda()
            pitch  = pitch.type(torch.LongTensor).cuda()
            target = target.type(torch.LongTensor).reshape(-1).cuda()
            prob   = net(pcm, feat, pitch).reshape(-1, 256)
            L      = loss(prob, target)
            opt.zero_grad()
            L.backward()
            opt.step()
            scheduler.step()
            sparsity(net, iteration)
            total_loss.append(L.item())
        avg_loss = sum(total_loss)/len(total_loss)
        print('\nEpoch Loss %.4f' % avg_loss)
        torch.save(net.state_dict(), './ckpts/%03d.pkl' % epoch)


import unittest
from datetime import datetime

KEY_INPUT = "input"
KEY_EXPECTED = "expected"

class ZipCheckTestCase(unittest.TestCase):
    def setUp(self):
        self.success_test_params = [
            {
                KEY_INPUT: "07663",
                KEY_EXPECTED: True,
            },
            {
                KEY_INPUT: "abcde",
                KEY_EXPECTED: False,
            },
            {
                KEY_INPUT: "123456",
                KEY_EXPECTED: False,
            },
        ]

        self.failure_test_params = [
            {
                KEY_INPUT: "00000",
                KEY_EXPECTED: False,
            },
            {
                KEY_INPUT: "OOOOO",
                KEY_EXPECTED: True,
            },
            {
                KEY_INPUT: "",
                KEY_EXPECTED: True,
            },
        ]

    def test_zip_success(self):
        for test in self.success_test_params:
            actual_result = check_zip(test[KEY_INPUT])
            expected_result = test[KEY_EXPECTED]
            self.assertIs(actual_result, expected_result)
            self.assertEqual(actual_result, expected_result)

    def test_zip_failure(self):
        for test in self.failure_test_params:
            actual_result = check_zip(test[KEY_INPUT])

            expected_result = test[KEY_EXPECTED]

            self.assertIsNot(actual_result, expected_result)
            self.assertNotEqual(actual_result, expected_result)

def check_zip(zipcode):
    '''Checks to see if the zipcode is formatted properly'''
    if len(zipcode) == 5:
        for i in zipcode:
            if i in "0123456789":
                continue
            return False
    else:
        return False

    return True

class TimeTestCase(unittest.TestCase):
    def setUp(self):
        self.success_test_params = [
            {
                KEY_INPUT: "1618693467",
                KEY_EXPECTED: ["04/17", "Saturday"],
            },
            {
                KEY_INPUT: "1735707601",
                KEY_EXPECTED: ["01/01", "Wednesday"],
            },
            {
                KEY_INPUT: "1609477201",
                KEY_EXPECTED: ["01/01", "Friday"],
            },
        ]

        self.failure_test_params = [
            {
                KEY_INPUT: "1618693467",
                KEY_EXPECTED: ["04/18", "Sunday"],
            },
            {
                KEY_INPUT: "1618693467",
                KEY_EXPECTED: ["Saturday", "04/17"],
            },
            {
                KEY_INPUT: "1609563601",
                KEY_EXPECTED: ["02/01", "Sunday"],
            },
        ]

    def test_time_success(self):
        for test in self.success_test_params:
            date, day = convert(test[KEY_INPUT])
            actual_result = [date, day]
            expected_result = test[KEY_EXPECTED]

            self.assertEqual(actual_result, expected_result)
            self.assertListEqual(actual_result, expected_result)

    def test_time_failure(self):
        for test in self.failure_test_params:
            date, day = convert(test[KEY_INPUT])
            actual_result = [date, day]
            expected_result = test[KEY_EXPECTED]

            self.assertNotEqual(actual_result[0], expected_result[0])
            self.assertNotEqual(actual_result[1], expected_result[1])

def convert(time):
    '''Used to convert UNIX time to MM-DD, and Day of the Week'''
    temp = int(time)
    date = datetime.utcfromtimestamp(temp).strftime('%m/%d')
    day = datetime.fromtimestamp(temp).strftime("%A")
    return date, day

class PullWeatherTestCase(unittest.TestCase):
    def setUp(self):
        self.success_test_params = [
            {
                KEY_INPUT: data1,
                KEY_EXPECTED: ['01/01', 'Friday', '60', '40', 'Cloudy', '10d'],
            },
            {
                KEY_INPUT: data2,
                KEY_EXPECTED: ['04/17', 'Saturday', '50', '6', 'Rain', '01d'],
            },
            {
                KEY_INPUT: data3,
                KEY_EXPECTED: ['01/02', 'Saturday', '32', '10', 'Snow', '13d'],
            },
        ]

        self.failure_test_params = [
            {
                KEY_INPUT: data1,
                KEY_EXPECTED: ['10d', 'Cloudy', '40', '60', 'Friday', '01/01'],
            },
            {
                KEY_INPUT: data2,
                KEY_EXPECTED: ['01/01', 'Friday', '50', '6', 'Rain', '01d'],
            },
            {
                KEY_INPUT: data3,
                KEY_EXPECTED: ['01/01', 'Friday', '60', '40', 'Cloudy', '10d'],
            },
        ]

    def test_time_success(self):
        for test in self.success_test_params:
            actual_result = pull_weather(0, test[KEY_INPUT])
            expected_result = test[KEY_EXPECTED]

            self.assertEqual(actual_result, expected_result)
            self.assertListEqual(actual_result, expected_result)

    def test_time_failure(self):
        for test in self.failure_test_params:
            actual_result = pull_weather(0, test[KEY_INPUT])
            expected_result = test[KEY_EXPECTED]

            self.assertNotEqual(actual_result[0], expected_result[0])
            self.assertNotEqual(actual_result[1], expected_result[1])

data1 = {
    "daily": [{
        "dt": "1609477201",
        "temp": {
            "max": 60.40,
            "min": 40.10,
        },
        "weather": [{
            "main": "Cloudy",
            "icon": "10d"
        }],
    }]
}
data2 = {
    "daily": [{
        "dt": "1618693467",
        "temp": {
            "dt": "1609477201",
            "max": 50,
            "min": 6,
        },
        "weather": [{
            "main": "Rain",
            "icon": "01d"
        }],
        "lat": 1000000,
        "lon": -1000000
    }]
}
data3 = {
    "daily": [{
        "dt": "1609563601",
        "temp": {
            "max": 32.00001,
            "min": 10.0005,
        },
        "weather": [{
            "main": "Snow",
            "icon": "13d"
        }],
        "max": 60.40,
        "min": 40.10,
    }, {
        "dt": "1609477201",
        "temp": {
            "max": 60.40,
            "min": 40.10,
        },
        "weather": [{
            "main": "Cloudy",
            "icon": "10d"
        }],
    }],
}

def pull_weather(index, data):
    '''Pulls the weather data for the specific day'''
    idx = int(index)
    dt_day = str(data["daily"][idx]["dt"])
    date_day, dow = convert(dt_day)
    max_day = str(data["daily"][idx]["temp"]["max"])
    max_day = str(round(float(max_day)))
    min_day = str(data["daily"][idx]["temp"]["min"])
    min_day = str(round(float(min_day)))
    weather_day = str(data["daily"][idx]["weather"][0]["main"])
    icon_day = str(data["daily"][idx]["weather"][0]["icon"])
    icon_day = get_icon(icon_day)
    lst = [date_day, dow, max_day, min_day, weather_day, icon_day]

    return lst

def get_icon(icon):
    '''Fetchs the icon based on the icon code in the API'''
    #url = "http://openweathermap.org/img/wn/{ICON}@2x.png".format(ICON=icon)
    # ALTERED TO NOT USE URL (for the tests)
    url = icon
    return url

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


import os
import struct
import sys

import shlex
import settings

import ssl
import logging
import irc.client
import irc.bot
import irc.strings

from bs4 import UnicodeDammit
import re
from irc.client import ip_numstr_to_quad, ip_quad_to_numstr

# Horrible hackyclass that I'm using to monkey-patch the line decoder. Unfortunately,
# short of subclassing ALL THE THINGS, I can't very easily override the decoder.
# As such, we just stick a patched decoder into the class at runtime.
class TolerantDecodingLineBuffer(object):

	line_sep_exp = re.compile(b'\r?\n')

	def __init__(self):
		self.buffer = b''

	def feed(self, inBytes):
		self.buffer += inBytes

	def __iter__(self):
		return self.lines()

	def __len__(self):
		return len(self.buffer)

	encodings = ['utf-8', "iso-8859-1", "latin-1"]
	errors = 'strict'

	def lines(self):
		lines = self.line_sep_exp.split(self.buffer)
		# save the last, unfinished, possibly empty line
		self.buffer = lines.pop()

		for line in lines:
			ret = UnicodeDammit(line, self.encodings).unicode_markup
			if not ret:
				raise UnicodeDecodeError("Could not decode '%s'" % line)
			yield ret

class TestBot(irc.bot.SingleServerIRCBot):
	def __init__(self, nickname, realname, server, port=9999):
		ssl_factory = irc.connection.Factory(wrapper=ssl.wrap_socket)

		# Horrible monkey-patch the ServerConnection instance so we can fix some encoding issues.
		print("Old buffer class", irc.client.ServerConnection.buffer_class)
		irc.client.ServerConnection.buffer_class = TolerantDecodingLineBuffer
		print("New buffer class", irc.client.ServerConnection.buffer_class)

		irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, realname, connect_factory=ssl_factory)

		self.log = logging.getLogger("Main.Manga.IRC<%s>" % server)
		self.received_bytes = 0

		self.welcomed = False

	def on_ctcp(self, c, e):
		"""Default handler for ctcp events.

		Replies to VERSION and PING requests and relays DCC requests
		to the on_dccchat method.
		"""

		print("On CTCP", e.arguments)
		nick = e.source.nick
		if e.arguments[0] == "VERSION":
			c.ctcp_reply(nick, "VERSION " + self.get_version())
		elif e.arguments[0] == "PING":
			if len(e.arguments) > 1:
				c.ctcp_reply(nick, "PING " + e.arguments[1])

		elif e.arguments[0] == "DCC":

			# Filenames are a giant PITA. Basically, we try to split the
			# CTCP command. If we get more then 5 items, the name must
			# have spaces, so we then try `shlex.split`. This works
			# around the issue that filenames without spaces
			# can have single quotation marks.
			args = e.arguments[1].strip().split()
			if len(args) != 5:
				args = shlex.split(e.arguments[1])
			if args[0] != "SEND":
				self.log.warning("Not DCC Send. Wat? '%s'", e.arguments)
				return

			self.log.info("Received DCC send command - '%s'", e)

			if hasattr(self, "get_filehandle"):
				self.file = self.get_filehandle(args[1])
				if not self.file:
					self.log.error("Could not get filehandle. XDCC is being dropped.")
					raise irc.client.DCCConnectionError
			else:
				self.filename = os.path.basename(args[1])

				self.log.info("Saving to '%s'", self.filename)

				if os.path.exists(self.filename):
					self.log.error("A file named '%s'", self.filename,)
					self.log.error("already exists. Refusing to save it.")
					# self.connection.quit()
				else:
					self.log.info("Saving item to '%s'", self.filename)
				self.file = open(self.filename, "wb")

			if hasattr(self, "xdcc_receive_start"):
				status = self.xdcc_receive_start()
				if not status:
					return

			peeraddress = irc.client.ip_numstr_to_quad(args[2])
			peerport = int(args[3])

			self.dcc = self.dcc_connect(peeraddress, peerport, "raw")
		else:
			print("Wut?", e)

	def on_dccmsg(self, connection, event):
		data = event.arguments[0]
		self.file.write(data)
		self.received_bytes = self.received_bytes + len(data)
		self.dcc.send_bytes(struct.pack("!I", self.received_bytes))

	def on_dcc_disconnect(self, connection, event):
		self.file.close()
		self.log.info("Received file - %d bytes." % (self.received_bytes))
		if hasattr(self, "xdcc_receive_finish"):
			self.xdcc_receive_finish()

	def on_nicknameinuse(self, connection, event):
		self.log.warning("Nickname %s is in use, adding a trailing '_'", connection.get_nickname() )
		connection.nick(connection.get_nickname() + "_")

	def on_welcome(self, c, e):
		self.log.info("On Welcome. Connected with nickname: %s.", c.get_nickname())
		self.welcomed = True
		if hasattr(self, "welcome_func"):
			self.welcome_func(c, e)

	def on_privmsg(self, c, e):
		self.log.info("On Privmsg = '%s', '%s'", c, e)
		self.say_command(e, e.arguments[0])

	def on_pubmsg(self, c, e):

		a = e.arguments[0].split(":", 1)
		self.log.info("Pubmessage = %s", e.arguments)
		if len(a) > 1 and irc.strings.lower(a[0]) == irc.strings.lower(self.connection.get_nickname()):
			self.log.info("Executing command '%s'", a[1])
			self.say_command(e, a[1].strip())
		return

	def on_dccchat(self, c, e):
		self.log.info("On DccChat")
		if len(e.arguments) != 2:
			return
		args = e.arguments[1].split()
		if len(args) == 4:
			try:
				address = ip_numstr_to_quad(args[2])
				port = int(args[3])
			except ValueError:
				return
			self.dcc_connect(address, port)

	def say_command(self, e, cmd, ):
		nick = e.source.nick
		c = self.connection

		if cmd.startswith(settings.ircBot["pubmsg_prefix"]):
			c.privmsg(e.channel, str(cmd[len(settings.ircBot["pubmsg_prefix"]):]))
		if cmd == "dcc":
			dcc = self.dcc_listen()
			self.log.info("Starting DCC - Command: '%s'", "CHAT chat %s %d" % (ip_quad_to_numstr(dcc.localaddress), dcc.localport))
			c.ctcp("DCC", nick, "CHAT chat %s %d" % (ip_quad_to_numstr(dcc.localaddress), dcc.localport))
		else:
			self.log.error("Unknown command = '%s'" % cmd)

	def say_in_channel(self, channel, message):
		self.log.info("Saygin %s in channel %s", message, channel)
		self.connection.privmsg(channel, message)

	def startup(self):
		self.log.info("Bot entering select loop")
		self.start()

def main():
	print("Sys argv length = ", len(sys.argv))
	if len(sys.argv) != 4:
		print("Usage: testbot <server[:port]> <channel> <nickname>")
		sys.exit(1)

	s = sys.argv[1].split(":", 1)
	server = s[0]
	if len(s) == 2:
		try:
			port = int(s[1])
		except ValueError:
			print("Error: Erroneous port.")
			sys.exit(1)
	else:
		port = 9999
	channel = sys.argv[2]
	nickname = sys.argv[3]

	bot = TestBot(channel, nickname, server, port)
	print("Bot created. Connecting")
	bot.start()

if __name__ == "__main__":
	main()


import pygame
import pygame.locals as locals
import random
import neural_network
import aigame_config as config
import evolution
import numpy as np
import os

pygame.init()

class Pipe(object):
    # 图片
    BTM_IMG = pygame.image.load("./res/pipe.png")
    TOP_IMG = pygame.transform.rotate(BTM_IMG, 180)
    min_visual_value = 80
    WIDTH = BTM_IMG.get_width()
    HEIGHT = BTM_IMG.get_height()

    def __init__(self):
        self.x = Game.SIZE[0]
        # 上下管道的管口Y坐标
        self.top_y = random.randint(Pipe.min_visual_value, Game.SIZE[1] - Game.PIPE_GAP_SIZE - Pipe.min_visual_value)
        self.btm_y = self.top_y + Game.PIPE_GAP_SIZE
        self.alive = True
        self.score = 1

    def draw(self, surface):
        surface.blit(Pipe.TOP_IMG, (self.x, self.top_y - Pipe.HEIGHT))
        surface.blit(Pipe.BTM_IMG, (self.x, self.btm_y))

    def update(self):
        self.x -= 5
        if self.x < -Pipe.WIDTH:
            self.alive = False

class PipeManager(object):
    def __init__(self, score):
        self.pipes = [Pipe()]
        self.count = 0  # 用来做生成水管的计时器，当count=creatime时生成一个管
        self.create_times = random.randint(45, 55)

    def drawPipes(self, surface):
        for pipe in self.pipes:
            pipe.draw(surface)

    def updatePipes(self):
        self.createPipe()
        index = len(self.pipes) - 1
        while index >= 0:
            pipe = self.pipes[index]
            if pipe.alive:
                pipe.update()
            else:
                self.pipes.remove(pipe)
                pass
            index -= 1

    def createPipe(self):
        self.count += 1
        if self.count % self.create_times == 0:
            self.pipes.append(Pipe())
            self.count = 0
            self.create_times = random.randint(45, 55)

class Bird(object):
    IMG = pygame.image.load("./res/bird.png")
    WIDTH = IMG.get_width()
    HEIGHT = IMG.get_height()

    def __init__(self, network):
        self.x = 50
        self.y = 200
        self.speed = 0
        self.fly_speed = -8
        self.max_speed = 8
        self.alive = True
        self.neural_network = network  # 把神经网络数据模型赋给小鸟

    def draw(self, surface):
        surface.blit(Bird.IMG, (self.x, self.y))

    def update(self):
        self.y += self.speed
        self.speed += 1
        if self.speed >= self.max_speed:
            self.speed = self.max_speed
        if self.y <= 0 or self.y + Bird.HEIGHT >= Game.SIZE[1]:
            self.alive = False

    def fly(self):
        self.speed = self.fly_speed

    def collision(self, pipes):
        for pipe in pipes:
            # 判断当前管道是否被小鸟飞跃（没有飞跃）
            if self.x < pipe.x + Pipe.WIDTH:
                if self.x + Bird.WIDTH > pipe.x and self.x < pipe.x + Pipe.WIDTH:
                    if self.y < pipe.top_y or self.y + Bird.HEIGHT > pipe.btm_y:
                        self.alive = False
                        return True
                return False

    def get_inputs(self, pipes):
        pipe = None
        for p in pipes:
            if self.x < p.x + Pipe.WIDTH:
                pipe = p
                break
        inputs = []
        for _ in range(config.network[0]):
            inputs.append(0.0)
        inputs[0] = self.y / Game.SIZE[1]
        if pipe:
            inputs[1] = (self.x + Bird.WIDTH) - pipe.x
            inputs[2] = self.x - (pipe.x + Pipe.WIDTH)
            inputs[3] = self.y - pipe.top_y
            inputs[4] = (self.y + Bird.HEIGHT) - pipe.btm_y
        return inputs

class BirdManager(object):
    """
    管理所有鸟的类
    """

    def __init__(self, ai):
        """
        1.初始化ai类，用来管理鸟
        2.创建出一代个体
        3.将每个个体的神经网络数据模型赋给每个鸟
        :param ai:一个遗传进化的ai类，里面有[[前一代的个体、个体、个体、个体、个体][前一代的个体、个体、个体、个体、个体]]
        """
        self.birds = []
        self.ai = ai
        network_data_list = self.ai.manager.create_generation()
        for network_data in network_data_list:
            network = neural_network.NeuralNetwork(config.network[0], config.network[1], config.network[2])
            network.setNetwork(network_data)
            bird = Bird(network)
            self.birds.append(bird)

    def drawBirds(self, surface):
        """
        画所有的鸟
        :param surface:
        :return:
        """
        for bird in self.birds:
            bird.draw(surface)

    def updateBirds(self, pipes, score):
        """
        遍历每个鸟，更新他们的状态
        如果活着：
            获取要输入的5个信息
            根据输入信息，通过神经网络计算出结果
            如果结果>0.5则飞
        如果死了：
            记录他们获得的分数，插入到数组中
        :param pipes:
        :param score:
        :return:
        """
        index = len(self.birds) - 1
        while index >= 0:
            bird = self.birds[index]
            if bird.alive:
                inputs = bird.get_inputs(pipes)
                ret = bird.neural_network.getResult(inputs)
                if ret[0] > 0.5:
                    bird.fly()
                bird.update()
            else:
                self.ai.collect_score(bird.neural_network, score)
                self.birds.remove(bird)
            index -= 1

    def collision(self, pipes):
        """
        判断每个鸟是否与管道相撞
        :param pipes:管道列表
        :return:
        """
        for bird in self.birds:
            bird.collision(pipes)

    def is_all_died(self):
        """
        判断鸟是否都死了
        返回一个bool型
        :return:
        """
        if len(self.birds) == 0:
            return True
        return False

class Evolution_ANN_AI(object):
    """
    世代个体管理者类，是一个[[前一代的个体、个体、个体、个体、个体][后一代的个体、个体、个体、个体、个体]]
    """

    def __init__(self):
        self.manager = evolution.GenerationManager()

    def collect_score(self, network, score):
        genome = evolution.Genome(network.getNetwork(), score)
        self.manager.add_genome(genome)

class Game(object):
    SIZE = (360, 420)
    FPS = 500
    PIPE_GAP_SIZE = 80

    def __init__(self):
        self.surface = pygame.display.set_mode(Game.SIZE)
        self.clock = pygame.time.Clock()
        self.ai = Evolution_ANN_AI()
        self.generation_num = 0
        self.game_init()

    def game_init(self):
        self.time = 0
        self.score = 0
        self.gameRunning = True
        self.birdManger = BirdManager(self.ai)
        self.pipeManager = PipeManager(self.score)
        self.generation_num += 1

    def start(self):
        while self.gameRunning:
            self.control()
            self.update()
            self.draw()
            pygame.display.update()  # 提交绘制内容
            print("世代：", self.generation_num, "存活数量：", len(self.birdManger.birds), "分数：", self.score)
            if self.score >= 5000 and not os.path.exists("my_modle.csv"):
                data = self.birdManger.birds[0].neural_network.getNetwork()
                weight_array = np.array(data['weights'])
                np.savetxt("./res/my_modle.csv", weight_array, delimiter=',')
                break
            self.time += self.clock.tick(Game.FPS)
        # print(self.time)

    def draw(self):
        # 绘制背景
        self.surface.fill((160, 160, 160))
        self.pipeManager.drawPipes(self.surface)
        self.birdManger.drawBirds(self.surface)
        # self.score.draw(self.surface)

    def update(self):
        if self.birdManger.is_all_died():
            self.restart()
            return
        self.birdManger.collision(self.pipeManager.pipes)
        self.pipeManager.updatePipes()
        self.birdManger.updateBirds(self.pipeManager.pipes, self.score)
        # self.score.update()
        self.score += 1

    def control(self):
        # pygame.mouse.get_pos()#获取鼠标的坐标（当前窗口内的相对坐标）
        # pygame.mouse.get_pressed()#鼠标的点击状态（0，0，0）
        for event in pygame.event.get():
            if event.type == locals.QUIT:
                self.stop()

    def stop(self):
        self.gameRunning = False

    def restart(self):
        self.game_init()

if __name__ == '__main__':
    game = Game()
    game.start()


from tkinter import *
import os
from lib.operations import kinships

#create and setup the root window
root = Tk()
root.title("Kinship")
root.geometry("300x100")

#create Frame to hold widgets
app = Frame(root).grid()

#create Widgets
labelWord = Label(app, text = "Enter word").grid(row=0, column=0)
textWord = StringVar()
entryWord = Entry(app, textvariable=textWord).grid(row=0, column=1)
labelKins = Label(app, text = "Enter no. of kins").grid(row=2, column=0)
textKins = IntVar()
entryKins = Entry(app, textvariable=textKins).grid(row=2, column=1)
labelTweetCount = Label(app, text = "Enter tweet count").grid(row=1, column=0)
textTweetCount = IntVar()
entryTweetCount = Entry(app, textvariable=textTweetCount).grid(row=1, column=1)
def getKin():
    kinships(
        ACCESS_TOKEN = 'xx',
        ACCESS_SECRET = 'xx',
        CONSUMER_KEY = 'xx',
        CONSUMER_SECRET = 'xx',
        word = textWord.get(),
        kins = textKins.get(),
        tweet_count = textTweetCount.get()
        )
buttonGetKins = Button(app, text = "Get kins", command=getKin).grid(row=3, column=0, columnspan=2)
buttonQuit = Button(app, text = "Quit", command=quit).grid(row=3, column=1, columnspan=2)

#start eventloop to display the window
root.mainloop()