import tensorflow as tf

import modules as m
#global variable
learning_rate = 0.01
max_steps = 3000
hidden1 = 128
hidden2 = 32
batch_size = 100
reg = 0.0001

#from modules give the handle
import tensorflow.examples.tutorials.mnist.input_data as input_data

data_sets = input_data.read_data_sets('MNIST')

for lr in [0.01, 0.001, 0.005, 0.002]:

    with tf.Graph().as_default():
        images_pl, labels_pl = m.placeholder_inputs(batch_size)

        logits, inf_cache = m.inference(images_pl, hidden1, hidden2)

        correct_nums = m.evaluation(logits, labels_pl)

        loss_h = m.loss(logits, labels_pl, inf_cache, reg)

        sess = tf.Session()

        train_op = m.training(loss_h, lr)

        ######################for tensorboard#############################
        log_dir = 'logs/fully_connected_net_scope/lr' + str(lr)
        #######################for tensorboard logs##############################3
        if tf.gfile.Exists(log_dir):
            tf.gfile.DeleteRecursively(log_dir)
        tf.gfile.MakeDirs(log_dir)
        tf.summary.scalar('loss' + str(lr), loss_h)
        tf.summary.scalar('loss', loss_h)
        summary = tf.summary.merge_all()
        summary_writer = tf.summary.FileWriter(log_dir, sess.graph)

        sess.run(tf.global_variables_initializer())

        for step in xrange(max_steps):

            feed_dict = m.fill_feed_dict(data_sets.train, images_pl, labels_pl, batch_size)

            _, loss = sess.run([train_op, loss_h], feed_dict=feed_dict)

            if step % 100 == 0 or step == max_steps - 1:
                print ('lr %.4f, step %d: loss = %.3f' % (lr, step, loss))

                ##########################for tensorboard########################
                summary_str = sess.run(summary, feed_dict=feed_dict)
                summary_writer.add_summary(summary_str, step)
                summary_writer.flush()

            if (step + 1) == max_steps:
                print ('Training Eval:')
                m.do_eval(sess, correct_nums, images_pl, labels_pl, data_sets.train, batch_size)

                print ('Validation Eval:')
                m.do_eval(sess, correct_nums, images_pl, labels_pl, data_sets.validation, batch_size)

                print ('Test Eval:')
                m.do_eval(sess, correct_nums, images_pl, labels_pl, data_sets.test, batch_size)


import utils

m = utils.Opener.lines()

stars = {'1': 0, '2': 0}
d = {chr(i+ord('a')): i+1 for i in range(0, 26)} |\
    {chr(i+ord('A')): i+27 for i in range(0, 26)}

for line in m:
    half = len(line)//2
    unique = set(line[:half]) & set(line[half:])
    stars['1'] += d[unique.pop()]

for i in range(0, len(m), 3):
    unique = set(m[i]) & set(m[i+1]) & set(m[i+2])
    stars['2'] += d[unique.pop()]

print(stars)

print(sum(map(
    lambda c: ord(c) + (-ord('a') + 1, -ord('A') + 27)[c.isupper()],
    ((set(a) & set(b) & set(c)).pop()
        for a, b, c in zip(*[iter(open("input/d03.txt").read().split('\n'))]*3)
    )
)))


import pygame
from pygame import image
# from pygame.sprite import Sprite
from block import Block

class Floor(Block):

    def __init__(self, screen, settings, is_underground=False):
        super(Floor, self).__init__(screen, settings, is_underground=is_underground)
        self.screen = screen
        self.settings = settings
        self.image = None

        if is_underground:
            self.image = pygame.transform.scale(
                image.load(settings.floor_ug_image),
                (self.settings.brick_width,
                 self.settings.brick_height)
            )
        else:
            self.image = pygame.transform.scale(
                image.load(settings.floor_image),
                (self.settings.brick_width,
                 self.settings.brick_height)
        )
        self.rect = self.image.get_rect()
        self.collision_pts = self.get_collision_points()

    def draw(self):
        self.screen.blit(self.image, self.rect)


#!/usr/bin/env python3

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QButtonGroup, QVBoxLayout, QLabel,
        QListWidget, QListWidgetItem, QSizePolicy, QStackedWidget, QToolBox,
        QToolButton, QWidget)

class SelectView(QWidget):
    def __init__(self, parent=None):
        super(SelectView, self).__init__(parent)

        self.leftWidget = self.createLeft()
        self.leftWidget.setMinimumHeight(256)
        self.leftWidget.setMaximumWidth(128)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.leftWidget)
        self.setLayout(mainLayout)

    def createLeft(self):
        leftBox = QToolBox()
        leftSys = self.createLeftSys()
        leftBind = self.createLeftBind()
        leftBox.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))
        leftBox.addItem(leftSys, "系统信息")
        leftBox.addItem(leftBind, "BIND调整")

        return leftBox

    def createLeftSys(self):
        sysWidget = QListWidget()

        sysWidget.setSpacing(5)
        sysButton = QListWidgetItem(sysWidget)
        sysButton.setText("系统平台")
        sysButton.setTextAlignment(Qt.AlignHCenter)
        sysButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        sysButton = QListWidgetItem(sysWidget)
        sysButton.setText("CPU信息")
        sysButton.setTextAlignment(Qt.AlignHCenter)
        sysButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        memButton = QListWidgetItem(sysWidget)
        memButton.setText("内存信息")
        memButton.setTextAlignment(Qt.AlignHCenter)
        memButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
#        if memButton.isSelected():
#            print(memButton.text())

        partButton = QListWidgetItem(sysWidget)
        partButton.setText("分区详情")
        partButton.setTextAlignment(Qt.AlignHCenter)
        partButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        netButton = QListWidgetItem(sysWidget)
        netButton.setText("网络信息")
        netButton.setTextAlignment(Qt.AlignHCenter)
        netButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        loginButton = QListWidgetItem(sysWidget)
        loginButton.setText("登陆用户")
        loginButton.setTextAlignment(Qt.AlignHCenter)
        loginButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        return sysWidget
#        self.contentsWidgetItemChanged.connect(self.changeView)
    def createLeftBind(self):
        bindWidget = QListWidget()
        bindWidget.setSpacing(5)

        azoneButton = QListWidgetItem(bindWidget)
        azoneButton.setText("添加域")
        azoneButton.setTextAlignment(Qt.AlignHCenter)
        azoneButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        zoneButton = QListWidgetItem(bindWidget)
        zoneButton.setText("域管理")
        zoneButton.setTextAlignment(Qt.AlignHCenter)
        zoneButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        aviewButton = QListWidgetItem(bindWidget)
        aviewButton.setText("添加视图")
        aviewButton.setTextAlignment(Qt.AlignHCenter)
        aviewButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        viewButton = QListWidgetItem(bindWidget)
        viewButton.setText("视图管理")
        viewButton.setTextAlignment(Qt.AlignHCenter)
        viewButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        ipbeButton = QListWidgetItem(bindWidget)
        ipbeButton.setText("IP归属地")
        ipbeButton.setTextAlignment(Qt.AlignHCenter)
        ipbeButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        return bindWidget

if __name__ == "__main__":

    import sys
    app = QApplication(sys.argv)
    select = SelectView()
    select.show()
    sys.exit(app.exec_())


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('polls', '0003_auto_20160202_1530'),
    ]

    operations = [
        migrations.AddField(
            model_name='pollresultspluginmodel',
            name='ordering',
            field=models.CharField(default='pk', max_length=8, choices=[('natural', 'pk'), ('descending', '-votes'), ('ascending', 'votes')]),
        ),
    ]


# PROGRAMMER: Steve M
# DATE CREATED: 31.07.20
# REVISED DATE:
# PURPOSE: Utility functions to load data and process images

# Import necessary libraries
import torchvision.models as models

## Get model
def get_model(arch):
    if arch == 'vgg19': #setting model based on vgg19
        model = models.vgg19(pretrained=True)
    elif arch == 'alexnet': #setting model based on alexnet
        model = models.alexnet(pretrained = True)
    return model

########

6. Neural Networks/2. Image Classifier Part 2/1. Work In Progress/util_get_model.py


import torch
from torch import optim
from torch.utils.data import ConcatDataset
import numpy as np
import tqdm
import copy
import utils
import time
from data import SubDataset, ExemplarDataset
from continual_learner import ContinualLearner
import evaluate
import datetime
import os
import csv
import datetime
output=[]
output5=[]

def train_cl(model, train_datasets, test_datasets, replay_mode="none", scenario="domain", classes_per_task=None, iters=2000, batch_size=32,
             generator=None, gen_iters=0, gen_loss_cbs=list(), loss_cbs=list(), eval_cbs=list(), sample_cbs=list(),
             use_exemplars=True, add_exemplars=False, eval_cbs_exemplars=list(), savepath='./'):
    '''Train a model (with a "train_a_batch" method) on multiple tasks, with replay-strategy specified by [replay_mode].

    [model]             <nn.Module> main model to optimize across all tasks
    [train_datasets]    <list> with for each task the training <DataSet>
    [replay_mode]       <str>, choice from "generative", "exact", "current", "offline" and "none"
    [scenario]          "domain"
    [classes_per_task]  <int>, # of classes per task
    [iters]             <int>, # of optimization-steps (i.e., # of batches) per task
    [generator]         None or <nn.Module>, if a seperate generative model should be trained (for [gen_iters] per task)
    [*_cbs]             <list> of call-back functions to evaluate training-progress'''

    # Set model in training-mode
    model.train()

    # Use cuda?
    cuda = model._is_on_cuda()
    device = model._device()

    # Initiate possible sources for replay (no replay for 1st task)
    Exact = Generative = Current = False
    previous_model = None

    # Register starting param-values (needed for "intelligent synapses").
    if isinstance(model, ContinualLearner) and (model.si_c>0):
        for n, p in model.named_parameters():
            if p.requires_grad:
                n = n.replace('.', '__')
                model.register_buffer('{}_SI_prev_task'.format(n), p.data.clone())

    # Loop over all tasks.
    for task, train_dataset in enumerate(train_datasets, 1):
        # If offline replay-setting, create large database of all tasks so far
        if replay_mode == "offline":
            train_dataset = ConcatDataset(train_datasets[:task])

        # Add exemplars (if available) to current dataset (if requested)
        if add_exemplars and task>1:
            # ---------- ADHOC SOLUTION: permMNIST needs transform to tensor, while splitMNIST does not ---------- #
            if len(train_datasets)>6:
                target_transform = (lambda y, x=classes_per_task: torch.tensor(y%x)) if (
                        scenario=="domain"
                ) else (lambda y: torch.tensor(y))
            else:
                target_transform = (lambda y, x=classes_per_task: y%x) if scenario=="domain" else None
            # ---------------------------------------------------------------------------------------------------- #
            exemplar_dataset = ExemplarDataset(model.exemplar_sets, target_transform=target_transform)
            training_dataset = ConcatDataset([train_dataset, exemplar_dataset])
        else:
            training_dataset = train_dataset

        # Prepare <dicts> to store running importance estimates and param-values before update ("Synaptic Intelligence")
        if isinstance(model, ContinualLearner) and (model.si_c > 0):
            W = {}
            p_old = {}
            for n, p in model.named_parameters():
                if p.requires_grad:
                    n = n.replace('.', '__')
                    W[n] = p.data.clone().zero_()
                    p_old[n] = p.data.clone()

        # Find [active_classes]
        active_classes = None  # -> for Domain-IL scenario, always all classes are active

        # Reset state of optimizer(s) for every task (if requested)
        if model.optim_type=="adam_reset":
            model.optimizer = optim.Adam(model.optim_list, betas=(0.9, 0.999))
        if (generator is not None) and generator.optim_type=="adam_reset":
            generator.optimizer = optim.Adam(model.optim_list, betas=(0.9, 0.999))

        # Initialize # iters left on current data-loader(s)
        iters_left = iters_left_previous = 1

        # Define tqdm progress bar(s)
        progress = tqdm.tqdm(range(1, iters+1))
        if generator is not None:
            progress_gen = tqdm.tqdm(range(1, gen_iters+1))

        # Loop over all iterations
        iters_to_use = iters if (generator is None) else max(iters, gen_iters)
        for batch_index in range(1, iters_to_use+1):

            # Update # iters left on current data-loader(s) and, if needed, create new one(s)
            iters_left -= 1
            if iters_left==0:
                data_loader = iter(utils.get_data_loader(training_dataset, batch_size, cuda=cuda, drop_last=True))
                # NOTE:  [train_dataset]  is training-set of current task
                #      [training_dataset] is training-set of current task with stored exemplars added (if requested)
                iters_left = len(data_loader)
            if Exact:
                iters_left_previous -= 1
                if iters_left_previous==0:
                    batch_size_to_use = min(batch_size, len(ConcatDataset(previous_datasets)))
                    data_loader_previous = iter(utils.get_data_loader(ConcatDataset(previous_datasets),
                                                                      batch_size_to_use, cuda=cuda, drop_last=True))
                    iters_left_previous = len(data_loader_previous)

            # -----------------Collect data------------------#

            #####-----CURRENT BATCH-----#####
            x, y = next(data_loader)                                    #--> sample training data of current task
            x, y = x.to(device), y.to(device)                           #--> transfer them to correct device

            scores = None

            #####-----REPLAYED BATCH-----#####
            if not Exact and not Generative and not Current:
                x_ = y_ = scores_ = None   #-> if no replay

            ##-->> Exact Replay <<--##
            if Exact:
                scores_ = None

                # Sample replayed training data, move to correct device
                x_, y_ = next(data_loader_previous)
                x_ = x_.to(device)
                y_ = y_.to(device) if (model.replay_targets=="hard") else None
                # If required, get target scores (i.e, [scores_]         -- using previous model, with no_grad()
                if (model.replay_targets=="soft"):
                    with torch.no_grad():
                        scores_ = previous_model(x_)
                    scores_ = scores_

            ##-->> Generative / Current Replay <<--##
            if Generative or Current:
                # Get replayed data (i.e., [x_]) -- either current data or use previous generator
                x_ = x if Current else previous_generator.sample(batch_size)

                # Get target scores and labels (i.e., [scores_] / [y_]) -- using previous model, with no_grad()
                # -if there are no task-specific mask, obtain all predicted scores at once
                if (not hasattr(previous_model, "mask_dict")) or (previous_model.mask_dict is None):
                    with torch.no_grad():
                        all_scores_ = previous_model(x_)
                # -depending on chosen scenario, collect relevant predicted scores (per task, if required)
                if scenario in ("domain") and (
                        (not hasattr(previous_model, "mask_dict")) or (previous_model.mask_dict is None)
                ):
                    scores_ = all_scores_
                    _, y_ = torch.max(scores_, dim=1)
                else:
                    # NOTE: it's possible to have scenario=domain with task-mask (so actually it's the Task-IL scenario)
                    # -[x_] needs to be evaluated according to each previous task, so make list with entry per task
                    scores_ = list()
                    y_ = list()
                    for task_id in range(task - 1):
                        # -if there is a task-mask (i.e., XdG is used), obtain predicted scores for each task separately
                        if hasattr(previous_model, "mask_dict") and previous_model.mask_dict is not None:
                            previous_model.apply_XdGmask(task=task_id + 1)
                            with torch.no_grad():
                                all_scores_ = previous_model(x_)
                        temp_scores_ = all_scores_

                        _, temp_y_ = torch.max(temp_scores_, dim=1)
                        scores_.append(temp_scores_)
                        y_.append(temp_y_)

                # Only keep predicted y/scores if required (as otherwise unnecessary computations will be done)
                y_ = y_ if (model.replay_targets == "hard") else None
                scores_ = scores_ if (model.replay_targets == "soft") else None

            #---> Train MAIN MODEL
            if batch_index <= iters:

                # Train the main model with this batch
                loss_dict = model.train_a_batch(x, y, x_=x_, y_=y_, scores=scores, scores_=scores_,
                                                active_classes=active_classes, task=task, rnt = 1./task)

                # Update running parameter importance estimates in W
                if isinstance(model, ContinualLearner) and (model.si_c>0):
                    for n, p in model.named_parameters():
                        if p.requires_grad:
                            n = n.replace('.', '__')
                            if p.grad is not None:
                                W[n].add_(-p.grad*(p.detach()-p_old[n]))
                            p_old[n] = p.detach().clone()

                # Fire callbacks (for visualization of training-progress / evaluating performance after each task)
                for loss_cb in loss_cbs:
                    if loss_cb is not None:
                        loss_cb(progress, batch_index, loss_dict, task=task)
                for eval_cb in eval_cbs:
                    if eval_cb is not None:
                        eval_cb(model, batch_index, task=task)
                if model.label == "VAE":
                    for sample_cb in sample_cbs:
                        if sample_cb is not None:
                            sample_cb(model, batch_index, task=task)

            #---> Train GENERATOR
            if generator is not None and batch_index <= gen_iters:
                # Train the generator with this batch
                loss_dict = generator.train_a_batch(x, y, x_=x_, y_=y_, scores_=scores_, active_classes=active_classes,
                                                    task=task, rnt=1./task)

                # Fire callbacks on each iteration
                for loss_cb in gen_loss_cbs:
                    if loss_cb is not None:
                        loss_cb(progress_gen, batch_index, loss_dict, task=task)
                for sample_cb in sample_cbs:
                    if sample_cb is not None:
                        sample_cb(generator, batch_index, task=task)

        ##----------> UPON FINISHING EACH TASK...

        # Close progres-bar(s)
        progress.close()
        if generator is not None:
            progress_gen.close()

        # EWC: estimate Fisher Information matrix (FIM) and update term for quadratic penalty
        if isinstance(model, ContinualLearner) and (model.ewc_lambda>0):
            # -find allowed classes
            allowed_classes = None
            # -if needed, apply correct task-specific mask
            if model.mask_dict is not None:
                model.apply_XdGmask(task=task)
            # -estimate FI-matrix
            model.estimate_fisher(training_dataset, allowed_classes=allowed_classes)

        # SI: calculate and update the normalized path integral
        if isinstance(model, ContinualLearner) and (model.si_c>0):
            model.update_omega(W, model.epsilon)

        # EXEMPLARS: update exemplar sets
        if (add_exemplars or use_exemplars) or replay_mode=="exemplars":
            exemplars_per_class = int(np.floor(model.memory_budget / (classes_per_task*task)))
            # reduce examplar-sets
            model.reduce_exemplar_sets(exemplars_per_class)
            # for each new class trained on, construct examplar-set
            new_classes = list(range(classes_per_task))
            for class_id in new_classes:
                start = time.time()
                # create new dataset containing only all examples of this class
                class_dataset = SubDataset(original_dataset=train_dataset, sub_labels=[class_id])
                # based on this dataset, construct new exemplar-set for this class
                model.construct_exemplar_set(dataset=class_dataset, n=exemplars_per_class)
                print("Constructed exemplar-set for class {}: {} seconds".format(class_id, round(time.time()-start)))
            model.compute_means = True
            # evaluate this way of classifying on test set
            for eval_cb in eval_cbs_exemplars:
                if eval_cb is not None:
                    eval_cb(model, iters, task=task)

        # REPLAY: update source for replay
        previous_model = copy.deepcopy(model).eval()
        if replay_mode == 'generative':
            Generative = True
            previous_generator = copy.deepcopy(generator).eval() if generator is not None else previous_model
        elif replay_mode == 'current':
            Current = True
        elif replay_mode in ('exemplars', 'exact'):
            Exact = True
            if replay_mode == "exact":
                previous_datasets = train_datasets[:task]
            else:
                target_transform = (lambda y, x=classes_per_task: y % x)
                previous_datasets = [
                    ExemplarDataset(model.exemplar_sets, target_transform=target_transform)]

        precs = [evaluate.validate(
            model, test_datasets[i], verbose=False, test_size=None, task=i + 1, with_exemplars=False,
            allowed_classes= None
        ) for i in range(len(test_datasets))]
        output.append(precs)

        precs5 = [evaluate.validate5(
            model, test_datasets[i], verbose=False, test_size=None, task=i + 1, with_exemplars=False,
            allowed_classes=None
        ) for i in range(len(test_datasets))]
        output5.append(precs5)

    os.makedirs(savepath+'/top5',exist_ok=True)
    savepath1=savepath+'/'+str(datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S'))+'.csv'
    f = open(savepath1, 'w')
    writer=csv.writer(f)
    writer.writerows(output)
    f.close()
    savepath5=savepath+'/top5/'+str(datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S'))+'.csv'
    f = open(savepath5, 'w')
    writer=csv.writer(f)
    writer.writerows(output5)
    f.close()
    print(savepath)


import time
from typing import TYPE_CHECKING

import signal
from subprocess import Popen, PIPE
from threading import Thread

if TYPE_CHECKING:
    # pylint: disable=ungrouped-imports
    from typing import BinaryIO
    from queue import SimpleQueue
    from threading import Lock
    from ...devices.structure import Structure
    # pylint: enable=ungrouped-imports

def loadController(program_path: str, ship: 'Structure', json_info: str,
                   debug_queue: 'SimpleQueue', lock: 'Lock') -> 'Thread':

    return ControllerLoader().load(program_path, ship, json_info,
                                   debug_queue, lock)

class ControllerLoader:

    def load(self, program_path: str, ship: 'Structure', json_info: str,
             debug_queue: 'SimpleQueue', lock: 'Lock') -> 'Thread':

        process = Popen([program_path, json_info], stdin=PIPE, stdout=PIPE,
                        stderr=PIPE)

        Thread(target=self.__controllerThreadWatcher,
               args=(process, ship, lock)).start()

        Thread(target=self.__controllerThreadDebugMessages, daemon=True,
               args=(process.stderr, debug_queue)).start()

        return Thread(target=self.__controllerThread, daemon=True,
                      args=(process.stdout, process.stdin, ship, lock))

    @staticmethod
    def __controllerThreadWatcher(process: 'Popen', device: 'Structure',
                                  lock: 'Lock') -> None:

        while True:
            with lock:
                if device.isDestroyed():
                    break
            time.sleep(1)

        process.send_signal(signal.SIGHUP)

    @staticmethod
    def __controllerThreadDebugMessages(pstderr: 'BinaryIO',
                                        debug_queue: 'SimpleQueue') -> None:

        try:
            while True:
                text = pstderr.readline().decode()
                if not text:
                    return
                debug_queue.put(text[:-1])

        except BrokenPipeError:
            pass

    @staticmethod
    def __controllerThread(pstdout: 'BinaryIO', pstdin: 'BinaryIO',
                           device: 'Structure', lock: 'Lock') -> None:

        try:
            while True:
                question = pstdout.readline().decode()

                if question and question[-1] == '\n':
                    question = question[:-1]

                with lock:
                    answer = device.communicate(question)

                pstdin.write(answer.encode())
                pstdin.write(b'\n')
                pstdin.flush()

        except BrokenPipeError:
            pass


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

from xlwt import Workbook,easyxf

start_pos = 9   # НЕ ставити менше 3! Установка початкової комірки

day_style = easyxf(
	'font: bold on;'
	'align: vertical center, horizontal center, rotation 90;'
	'borders: left 2, right 2, top 2, bottom 2;'
	)

pair_style = easyxf(
	'font: bold on;'
	'align: vertical center, horizontal center;'
	'borders: left 2, right 2, top 2, bottom 2;'
	)

sybject_style1 = easyxf(
	'font: height 220;'
	'align: horizontal center;'
	'borders: left 1, right 1, top 1;'
	)

sybject_style2 = easyxf(
	'font: height 220;'
	'align: vertical top, horizontal center;'
	'borders: left 1, right 1, bottom 1;'
	)

groups_style = easyxf(
	'font: bold on;'
	'align: vertical center, horizontal center;'
	'borders: left 2, right 2, top 2, bottom 2;'
	)

group_pair_style = easyxf(
	'font: height 160;'
	'borders: left 1, right 1, top 1, bottom 1;'
	)

def SetDays():					#Фунція установки розмітки днів і пар
	st_pos_days = start_pos
	st_pos_pairs = start_pos
	days = [u'Понеділок', u'Вівторок', u'Середа', u'Четвер', u'Пятниця']
	pairs = [u'I', u'II', u'III', u'IV', u'V', u'VI']
	ws.col(0).width = 0x470
	ws.col(1).width = 0x470
	for day in range(5):
		ws.write_merge(st_pos_days, st_pos_days+23, 0, 0, days[day], day_style)
		for pair in range(6):
			ws.write_merge(st_pos_pairs, st_pos_pairs+3, 1, 1, pairs[pair], pair_style)
			st_pos_pairs += 4
		st_pos_days += 24

def SetGroups(groups):			#Функція установки розмітки груп
	st_pos_row = start_pos
	st_pos_col = 2
	ws.write(st_pos_row-2, 1, u'групи', group_pair_style)
	ws.write(st_pos_row-1, 1, u'пари', group_pair_style)
	for group in range(len(groups)):
		ws.write_merge(st_pos_row-2, st_pos_row-1, st_pos_col, st_pos_col, unicode(groups[group]), groups_style)
		ws.col(st_pos_col).width = 0x1950
		st_pos_col += 1

def SetSubject(day, pair, group, pairtype, sybject, audience):		#Фуккція запису предмету в розклад
	st_pos = start_pos
	start_day_pos = st_pos + day*24
	start_pair_pos = pair*4
	start_subj_pos = 0

	start_subj_pos = 0 if pairtype == (1 or 3) else 2

	if pairtype == 1 or pairtype == 2:
		ws.write(start_day_pos+start_pair_pos+start_subj_pos, group, sybject, sybject_style1)
		ws.write(start_day_pos+start_pair_pos+start_subj_pos+1, group, audience, sybject_style2)
	elif pairtype == 3:
		ws.write_merge(start_day_pos+start_pair_pos, start_day_pos+start_pair_pos+1, group, group, sybject, sybject_style1)
		ws.write_merge(start_day_pos+start_pair_pos+2, start_day_pos+start_pair_pos+3, group, group, audience, sybject_style2)


#!/usr/bin/env python3

from collections import defaultdict
import sys

start = [int(x) for x in sys.stdin.read().strip().split(',')]

start_cnt = defaultdict(int)
rest_cnt = defaultdict(int)

for x in start:
    start_cnt[x] += 1
for _ in range(256):
    #print('start',sorted(start_cnt.items()))
    #print('rest ',sorted(rest_cnt.items()))
    start_cnt_new = defaultdict(int)
    rest_cnt_new = defaultdict(int)
    for age, cnt in start_cnt.items():
        if age == 0:
            start_cnt_new[6] += cnt
            rest_cnt_new[8] += cnt
        else:
            start_cnt_new[age-1] += cnt
    for age, cnt in rest_cnt.items():
        if age == 0:
            start_cnt_new[6] += cnt
            rest_cnt_new[8] += cnt
        else:
            rest_cnt_new[age-1] += cnt
    rest_cnt = rest_cnt_new
    start_cnt = start_cnt_new
a = sum(x for x in start_cnt.values())
b = sum(x for x in rest_cnt.values())
sys.stdout.write(f'{a+b}\n')


#coding=utf-8
import logging
import os
import datetime

class UserLog(object):
    def __init__(self):
        self.logger = logging.getLogger()#得到一个对象
        self.logger.setLevel(logging.DEBUG)#设置一个等级

        #文件名字
        base_dir = os.path.dirname(os.path.abspath(__file__))#abspath获取当前文件路径。dirname获取目录路径，不包含文件名
        log_dir = os.path.join(base_dir,"logs")
        log_file = datetime.datetime.now().strftime("%Y-%m-%d")+".log"#获取当前时间，并要求格式为年月日 拼接
        log_name = log_dir+"/"+log_file

        #文件输出日志
        self.file_handle = logging.FileHandler(log_name,'a',encoding='utf-8')#("D:\\SeleniumPython\\Mooc\\log\\logs\\test.log")
        self.file_handle.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s %(filename)s--> %(funcName)s %(levelno)s :%(levelname)s---> %(message)s ')
        self.file_handle.setFormatter(formatter)#file_handle设置格式，格式为formatter格式
        self.logger.addHandler(self.file_handle)
        '''
        consle = logging.StreamHandler()#得到一个流对象
        logger.addHandler(consle)
        logger.debug("teste")#将这个流对象添加进一个 ，使其能在控制台输出
        consle.close()
        logger.removeHandler(consle)#两个对象都记得清空！！！
        '''
        #self.logger.debug("teste")

    def get_log(self):
        return self.logger

    def close_handle(self):
        self.logger.removeHandler(self.file_handle)
        self.file_handle.close()


import cv2
import torch
from numpy import random
import numpy as np

import perception.tools._init_paths
from models.experimental import attempt_load
from utils.general import check_img_size, non_max_suppression, scale_coords, set_logging
from utils.plots import plot_one_box
from utils.torch_utils import select_device

def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):
    # Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232
    shape = img.shape[:2]  # current shape [height, width]
    if isinstance(new_shape, int):
        new_shape = (new_shape, new_shape)

    # Scale ratio (new / old)
    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
    if not scaleup:  # only scale down, do not scale up (for better test mAP)
        r = min(r, 1.0)

    # Compute padding
    ratio = r, r  # width, height ratios
    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding
    if auto:  # minimum rectangle
        dw, dh = np.mod(dw, 32), np.mod(dh, 32)  # wh padding
    elif scaleFill:  # stretch
        dw, dh = 0.0, 0.0
        new_unpad = (new_shape[1], new_shape[0])
        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios

    dw /= 2  # divide padding into 2 sides
    dh /= 2

    if shape[::-1] != new_unpad:  # resize
        img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
    img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border
    return img, ratio, (dw, dh)

class Yolo:

    def __init__(self):
        self.weights = 'yolov5x.pt'
        self.source = 'data/images'  # file/folder, 0 for webcam
        self.img_size = 640
        self.conf_thres = 0.25
        self.iou_thres = 0.45
        self.device_type = '0'
        self.view_img = True
        self.save_txt = True
        self.save_conf = True
        self.classes = 0
        self.agnostic_nms = True
        self.augment = True

        # Initialize
        set_logging()
        self.device = select_device(self.device_type)  # select CUDA device at 0
        self.half = self.device.type != 'cpu'  # half precision only supported on CUDA

        # Load model
        self.model = attempt_load(self.weights, map_location=self.device)  # load FP32 model
        self.imgsz = check_img_size(self.img_size, s=self.model.stride.max())  # check img_size
        if self.half:
            self.model.half()  # to FP16

        # Get names and colors
        self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names
        self.colors = [[random.randint(0, 255) for _ in range(3)] for _ in self.names]

        img = torch.zeros((1, 3, self.imgsz, self.imgsz), device=self.device)  # init img
        _ = self.model(img.half() if self.half else img) if self.device.type != 'cpu' else None  # run once
        print("Detector Model Initialized!")

    def detect(self, img0):
        # Run inference
        img0 = cv2.resize(img0, (640, 360))

        # Padded resize
        img = letterbox(img0, new_shape=self.img_size)[0]
        img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
        img = np.ascontiguousarray(img)
        img = torch.from_numpy(img).to(self.device)

        img = img.half() if self.half else img.float()  # uint8 to fp16/32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)

        # Inference
        with torch.no_grad():
            pred = self.model(img, augment=self.augment)[0]

        # Apply NMS
        pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes=self.classes,
                                   agnostic=self.agnostic_nms)

        # Process detections
        img_with_detections = np.copy(img0)

        for i, det in enumerate(pred):  # detections per image

            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img_with_detections.shape).round()

                # Write resultsq
                for *xyxy, conf, cls in reversed(det):
                    if self.view_img:  # Add bbox to image
                        label = '%s %.2f' % (self.names[int(cls)], conf)
                        plot_one_box(xyxy, img_with_detections, label=label, color=self.colors[int(cls)],
                                     line_thickness=3)

        return img_with_detections


import loginPage
import disciplineForm

#import addCourse
import home
import registration
import  marksEntry
import pymysql
from tkinter import *
import  sys
from tkinter import scrolledtext

def showMainPage():

    h = home.Home()
    h.show()

if __name__=='__main__':

    conn = pymysql.connect(user='root',password="")
    cursor = conn.cursor()

    try:
        cursor.execute('CREATE DATABASE {} DEFAULT CHARACTER SET "utf8"'.format('tabulationSystemKU'))
    except pymysql.Error as err:
        print(err)
    try:
        cursor.execute('USE tabulationSystemKU')
        #cursor.execute('DROP TABLE coursetable')
        cursor.execute('CREATE TABLE coursetable (course_ID INT NOT NULL AUTO_INCREMENT,'
                       'yearborsho VARCHAR(10) NOT NULL ,'
                       'term VARCHAR (10) NOT NULL ,'
                       'courseno VARCHAR(20) NOT NULL,'
                       'coursetitle VARCHAR(250) NOT NULL,'
                       'credit DOUBLE NOT NULL ,'
                       'PRIMARY KEY(course_ID))'
                       'ENGINE=InnoDB')

    except pymysql.Error as err:
        print(err)

    try:
        cursor.execute("USE tabulationSystemKU")
        #cursor.execute("DROP TABLE students")
        cursor.execute("CREATE TABLE students ("
                       "rollNo VARCHAR(20) NOT NULL,"
                       "name VARCHAR(250) NOT NULL,"
                       "batch INT NOT NULL,"
                       "tech DOUBLE NOT NULL,"
                       "tecp DOUBLE NOT NULL ,"
                       "PRIMARY KEY(rollNo)) ENGINE=InnoDB")

    except pymysql.Error as err:
        print(err)

    #addcrs=addCourse.AddCourse()
    #addcrs.show()

    try:
        cursor.execute('USE tabulationSystemKU')
        #cursor.execute("DROP TABLE disciplineInfo")
        cursor.execute('CREATE TABLE disciplineInfo (ID INT NOT NULL AUTO_INCREMENT,'
                       'disciplineName VARCHAR (250) NOT NULL, '
                       'schoolName VARCHAR(100) NOT NULL ,'
                       'disciplineCode VARCHAR(10) NOT NULL,'
                       'requiredCredit DOUBLE NOT NULL ,'
                       'thesisCategory VARCHAR(400) NOT NULL,'
                       'PRIMARY KEY(ID))ENGINE=InnoDB ')

    except pymysql.Error as err:
        print(err)

    try:
        cursor.execute("USE tabulationSystemKU")
        #cursor.execute("DROP TABLE theory_result")
        cursor.execute("CREATE TABLE theory_result (ID INT NOT NULL AUTO_INCREMENT,"
                       "session VARCHAR(30) NOT NULL,"
                       "year VARCHAR (30) NOT NULL,"
                       "term VARCHAR(30) NOT NULL,"
                       "courseNo VARCHAR (50) NOT NULL,"
                       "roll VARCHAR (20) NOT NULL,"
                       "attendance DOUBLE NOT NULL,"
                       "ct DOUBLE NOT NULL,"
                       "seca DOUBLE NOT NULL,"
                       "secb DOUBLE NOT NULL,"
                       "gpa DOUBLE NOT NULL,"
                       "grade VARCHAR (10) NOT NULL,"
                       "PRIMARY KEY (ID))ENGINE = InnoDB")

    except pymysql.Error as err:
        print(err)

    try:
        cursor.execute("USE tabulationSystemKU")
        #cursor.execute("DROP TABLE prerequisite_table")
        cursor.execute("CREATE TABLE prerequisite_table (ID INT NOT NULL AUTO_INCREMENT,"
                       "course VARCHAR(30) NOT NULL,"
                       "prerequisite VARCHAR (30) NOT NULL,"
                       "PRIMARY KEY (ID))ENGINE = InnoDB")

    except pymysql.Error as err:
        print(err)

    try:
        cursor.execute("USE tabulationSystemKU")
        #cursor.execute("DROP TABLE sessional_result")
        cursor.execute("CREATE TABLE sessional_result (ID INT NOT NULL AUTO_INCREMENT,"
                       "session VARCHAR(30) NOT NULL,"
                       "year VARCHAR (30) NOT NULL,"
                       "term VARCHAR(30) NOT NULL,"
                       "courseNo VARCHAR (50) NOT NULL,"
                       "roll VARCHAR (20) NOT NULL,"
                       "attendance DOUBLE NOT NULL,"
                       "sa DOUBLE NOT NULL,"
                       "viva DOUBLE NOT NULL,"
                       "gpa DOUBLE NOT NULL,"
                       "grade VARCHAR (10) NOT NULL,"
                       "PRIMARY KEY (ID))ENGINE = InnoDB")

    except pymysql.Error as err:
        print(err)

    try:
        cursor.execute("USE tabulationSystemKU")
        #cursor.execute("DROP TABLE batch")
       # cursor.execute("CREATE  TABLE batch (ID INT NOT NULL AUTO_INCREMENT,"
        #               "batch_number VARCHAR(5) NOT NULL,"
         #              "PRIMARY KEY (ID))ENGINE =InnoDB")
    except pymysql.Error as err:
        print(err)

    try:
        cursor.execute("USE tabulationSystemKU")
        #cursor.execute('DROP TABLE login')
        cursor.execute("CREATE TABLE login (ID INT NOT NULL AUTO_INCREMENT,"
                       "username VARCHAR(50) NOT NULL,"
                       "password VARCHAR(50) NOT NULL,"
                       "PRIMARY KEY(ID))ENGINE=InnoDB")
        cursor.execute("INSERT INTO login (username,password) VALUES ('{}','{}')".format("admin" ,'cse'))
        conn.commit()

    except pymysql.Error as err:
        print(err)

    try:
        cursor.execute("USE tabulationSystemKu")
        #cursor.execute("DROP TABLE CourseConfiguration")
        cursor.execute("CREATE TABLE CourseConfiguration (ID INT NOT NULL AUTO_INCREMENT,"
                       "year VARCHAR(25) NOT NULL,"
                       "term VARCHAR (25) NOT NULL,"
                       "session VARCHAR (25) NOT NULL,"
                       "creditLimit VARCHAR (25),"
                        "batch VARCHAR (10) NOT NULL,"
                       "PRIMARY KEY(ID))ENGINE  = InnoDB")

    except pymysql.Error as err:
        print(err)

    try:
        cursor.execute("USE tabulationSystemKU")
        #cursor.execute("DROP TABLE registration")
        cursor.execute('''CREATE TABLE registration (ID INT NOT NULL AUTO_INCREMENT,
                        rollNo VARCHAR(15) NOT NULL,
                        courseNo VARCHAR (20) NOT NULL,
                        year VARCHAR (15) NOT NULL,
                        term VARCHAR (15) NOT NULL,
                        es VARCHAR (20) NOT NULL,
                        retake INT NOT NULL DEFAULT 0,
                        PRIMARY KEY(ID))ENGINE=InnoDB''')
    except pymysql.Error as err:
        print(err)

    conn.close()

    loginObject =loginPage.Login()
    loginObject.show()

    #discipline=disciplineForm.DisciplineFormClass()
    #discipline.show_form()
    #test =inputtest.InputTest()
    # test.show()
    #nstndt=newstudentform.NewStudentForm()
    #nstndt.show()

    #hm=home.Home()
    #hm.show()

    #rgtr = registration.Registration()
    #rgtr.show()

    #mrks= marksEntry.MarksEntry()
    #mrks.show()

    #loginPageObject = loginPage.Login()
    #loginPageObject.show()

#mainloop()


import math
import os
import random
import asyncio
from aiohttp import web
import socketio
import aiohttp_jinja2
import jinja2
from entities.Player import Player
from entities.Food import Food

sio = socketio.AsyncServer(async_mode='aiohttp')
app = web.Application()
sio.attach(app)

# Set up Jinja2 environment for aiohttp
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(['templates']))

players = {}  # A dictionary to store players' state
entities = {}  # A dictionary to store entities' state

# Create a bunch of entities
for i in range(500):
    entities[i] = Food()

@aiohttp_jinja2.template('index.html')
async def index(request):
    return {}

@sio.event
async def connect(sid, environ):
    player_id = sid
    players[player_id] = Player()
    await broadcast_update()
    print(f'Client connected - SID: {player_id}')

@sio.event
async def disconnect(sid):
    player_id = sid
    del players[player_id]
    print('Client disconnected')
    await broadcast_update()

async def handle_collisions(player_id, player):
    tasks = []
    for other_id, other_player in players.items():
        if player_id != other_id:
            tasks.append(player.check_collision(other_player))

    collisions = await asyncio.gather(*tasks)
    for idx, collision in enumerate(collisions):
        if collision:
            other_id = list(players.keys())[idx]
            other_player = players[other_id]
            await player.consume(other_player)
            break

    tasks = []
    for entity_id, entity in entities.items():
        tasks.append(player.check_collision(entity))

    collisions = await asyncio.gather(*tasks)
    for idx, collision in enumerate(collisions):
        if collision:
            entity_id = list(entities.keys())[idx]
            entity = entities[entity_id]
            await player.consume(entity)
            entities.pop(entity_id)
            break

async def process_movement(player_id, player, angle=None, direction=None):
    if angle is not None:
        await player.moveViaMouse(angle)
    elif direction is not None:
        await player.move(direction)

    await handle_collisions(player_id, player)
    players[player_id] = player

@sio.event
async def player_mouse_movement(sid, data):
    player_id = sid
    player = players[player_id]
    angle = int(data)
    await process_movement(player_id, player, angle=angle)

@sio.event
async def player_arrow_movement(sid, data):
    player_id = sid
    player = players[player_id]
    direction = data
    await process_movement(player_id, player, direction=direction)

async def broadcast_updates_periodically(interval):
    while True:
        await broadcast_update()
        await asyncio.sleep(interval)

async def start_periodic_broadcast(app):
    app['broadcast_task'] = asyncio.create_task(broadcast_updates_periodically(0.1))

async def broadcast_update():
    players_list = [{'id': player_id, **player.__dict__} for player_id, player in players.items()]
    entities_list = [{'id': entity_id, **entity.__dict__} for entity_id, entity in entities.items()]
    await sio.emit('update', {'players': players_list, 'entities': entities_list}, room=None)

app.router.add_get('/', index)
app.on_startup.append(start_periodic_broadcast)

if __name__ == '__main__':
    web.run_app(app, host='0.0.0.0', port=8000)