# civMap module
# contains classes related to the game board

import sys

class Map(object):
    """PocketCiv: the map, which is divided into 8 regions"""
    """Each region can have a number of objects in them listed below as icons"""
    """There will be a fixed number of "scenario" maps that are loadable and playable"""
    ICONS = ["Mountain", "Forest", "Desert", "Volcano", "Farm", "Fault Line"]
    #the below icons are objects in their own right
    CIV_ICONS = ["Tribe", "City"]
    def __init__(self, scenN):
        self.__scenarioNum = scenN
        self.__regions = []
        #for now, let's just do the basic scenario
        import scenarioData
        lines = getattr(scenarioData, "scenario" + str(scenN))
        #hasMountain, hasForest, borderSea, borderFron, neighbors
        line = 1
        for regLine in lines:
            reg = Region(line, regLine[0], regLine[1], regLine[2], regLine[3], regLine[4])
            self.__regions.append(reg)
            line += 1
    def __str__(self):
        strRep = "\n** PocketCiv Map ** \n"
        for r in self.__regions:
            strRep += str(r) + "\n"
        return strRep
    #below methods are related to game stage 1
    def countTribes(self):
        tribes = 0
        for r in self.__regions:
            tribes += r.getNumTribes()
        return tribes
    def countCities(self):
        cities = 0
        for r in self.__regions:
            if r.hasCity():
                cities += 1
        return cities
    def countRegionTribes(self, regionNum):
        t = 0
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                t = r.getNumTribes()
                break
        return t
    def addTribes(self, regionNum, numTribes):
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                r.addTribes(numTribes)
                break
    def addFaultLine(self, regionNum):
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                r.setFaultLine(True)
                break
    def containsDesert(self, regionNum):
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                if r.hasDesert():
                    return True
                break
        return False
    def growCity(self, regionNum, numAV, canDecimate):
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                r.growCity(numAV, canDecimate)
                break
    def moveTribes(self, regionNum, numTribes):
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                r.holdTempTribes(numTribes)
                break
    def getEligibleRegions(self, needsCity = False, needsTribes = False):
        eligibleRegions = []
        for r in self.__regions:
                if (r.hasCity() or not needsCity) and (r.getNumTribes() > 0 or not needsTribes):
                    eligibleRegions.append(r.getRegionNumber())
        return eligibleRegions
    def getCityCandidates(self):
        eligibleRegions = []
        for r in self.__regions:
            if not r.hasCity() and r.getNumTribes() > 3 and r.hasFarm():
                eligibleRegions.append(r.getRegionNumber())
        return eligibleRegions
    def getFarmCandidates(self):
        eligibleRegions = []
        for r in self.__regions:
            if not r.hasFarm() and r.getNumTribes() > 1 and r.hasForest():
                eligibleRegions.append(r.getRegionNumber())
        return eligibleRegions
    def addFarm(self, regionNum):
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                r.buildFarm()
                break
    def addCity(self, regionNum):
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                r.buildCity()
                break
    def advanceCity(self, regionNum):
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                r.advanceCity()
                break
    def growTribes(self):
        for r in self.__regions:
            if r.getNumTribes() > 0:
                r.addTribes(1)
    def chooseTribes(self, maxTribes):
        t = -1
        while t < 0 or t > maxTribes:
            try:
                t = int(input("How many tribes: "))
            except:
                print("Not a valid entry.\n")
        return t
    def getNeighbors(self, regionNum):
        neigh = []
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                neigh = r.getNeighbors()
                break
        return neigh
    def containsFaultLine(self, regionNum):
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                return r.hasFaultLine()
        return False
    def containsVolcano(self, regionNum):
        for r in self.__regions:
            if r.getRegionNumber() == regionNum:
                return r.hasVolcano()
        return False
    def getMoveableRegions(self, regNo, techStack):
        moveReg = []
        movesAllowed = 1
        if techStack.containsTech("Road Building"):
            movesAllowed = 2
        elif techStack.containsTech("Equestrian Skill"):
            movesAllowed = 100

        if movesAllowed == 100:
            moveReg = [1,2,3,4,5,6,7,8]
        else:
            moveReg = self.getAdjacentRegions(regNo, movesAllowed)
        return moveReg
    def getAdjacentRegions(self, regNo, moves):
        adjReg = []
        if moves > 0:
            adjReg = self.getNeighbors(regNo)
        if moves > 2:
            newReg = []
            for regNo in adjReg:
                newReg.append(self.getNeighbors(regNo))
            adjReg.append(newReg)
        return set(adjReg) #to remove duplicates
    def resolveTribeMovement(self):
        for r in self.__regions:
            r.resetTempTribes()
    def chooseFromRegionList(self, eligibleRegionsList):
        print("\nPlease choose a region from these: ")
        for rNum in eligibleRegionsList:
            print ("\t" + str(rNum))
        print("\n")
        regChosen = -1
        validChoice = False
        while regChosen < 0 or not validChoice:
            try:
                regChosen = int(input("Enter a region number: "))
            except:
                print("Not a valid entry.\n")

            if regChosen != 0 and regChosen not in eligibleRegionsList:
                print("Not a valid choice.\n")
            else:
                validChoice = True
        return regChosen
    def addTribesInterface(self, numOfTribes, needsCity = False):
        tribesToPlace = numOfTribes
        eligibleRegions = self.getEligibleRegions(needsCity)
        while tribesToPlace > 0:
            print("Choose region to add a tribe to. You have " + str(tribesToPlace) + " tribes left" )
            regChosen = self.chooseFromRegionList(eligibleRegions)
            self.addTribes(regChosen, 1)
            tribesToPlace -= 1
    def moveTribesInterface(self, techStack):
        eligRegions = self.getEligibleRegions(False, True)
        moveableRegions = len(eligRegions)
        continueMoving = True
        while continueMoving and moveableRegions > 0:
            print("Choose a region to move tribes from (enter zero if done).\n")
            regChosenFrom = self.chooseFromRegionList(eligRegions)
            if regChosenFrom == 0:
                break
            moveToRegions = self.getMoveableRegions(regChosenFrom, techStack)
            print("Choose a region to move tribes into.\n")
            regChosenTo = self.chooseFromRegionList(moveToRegions)
            maxTribes = self.countRegionTribes(regChosenFrom)
            print("How many tribes to you want to move from " + str(regChosenFrom) + " to " +  str(regChosenTo) +"?\n")
            tribesMoved = self.chooseTribes(maxTribes)
            self.moveTribes(regChosenFrom, -tribesMoved)
            self.moveTribes(regChosenTo, tribesMoved)
            eligRegions.remove(regChosenFrom)
            moveableRegions -= 1
        self.resolveTribeMovement()
    #below methods are related to events game stage
    def anarchyResolve(self, techStack):
        hasLiteracy = techStack.containsTech("Literacy")
        hasLaw = techStack.containsTech("Law")
        hasReligion= techStack.containsTech("Organized Religion")
        hasMachine = techStack.containsTech("Machining")
        tribeReduce = 3
        maxRegions = 8
        regionsHit = 0
        if hasLiteracy:
            tribeReduce = 5
        if hasReligion:
            maxRegions = 4
        if hasLaw:
            for r in self.__regions:
                r.addTribes(-r.getCitySize())
        else:
            for r in self.__regions:
                if regionsHit < maxRegions:
                    if r.getNumTribes() > r.getCitySize():
                        while r.getCitySize() > 1 and r.getNumTribes() > r.getCitySize():
                            r.growCity(-1, False)
                            r.addTribes(-tribeReduce)
                else:
                    break
        if hasMachine and not hasLaw:
            cityCount = 2
            eligRegions = self.getEligibleRegions(True, False)
            while cityCount > 0 and len(eligRegions) > 1:
                someReg = chooseFromRegionList(eligRegions)
                self.growCity(someReg, 1, True)
                eligRegions.remove(someReg)
    def reduceTribesByChosen(self, numTribes):
        while numTribes > 0 and self.countTribes() > 0:
            eligRegions = self.getEligibleRegions(False, True)
            someReg = chooseFromRegionList(eligRegions)
            self.addTribes(someReg, -1)
            numTribes -= 1

class Region(object):
    """A Map is made up of 8 regions this class represents them"""
    """Cities are so intristically tied to regions that they need no seperate class"""
    def __init__(self, no, hasM, hasF, borderS, borderF, neighbors):
        #at the beginning of the game, the above 4 items are the only thing that populates a region
        self.__regionNumber = no
        self.__hasMountain = hasM
        self.__hasForest = hasF
        self.__bordersSea = borderS
        self.__bordersFrontier = borderF
        self.__neighbors = neighbors #list of regionNumbers
        self.__hasDesert = not(self.__hasForest or self.__hasMountain)
        self.__numOfTribes = 0
        self.__tempTribes = 0
        self.__hasCity = False
        self.__hasFaultLine = False
        self.__hasVolcano = False
        self.__hasFarm = False
        self.__cityAV = 0
    def __str__(self):
        strRep = "** Region " + str(self.__regionNumber) + " **\n"
        strRep += "** Neighboring Regions: "
        for regNo in self.__neighbors:
            strRep += str(regNo) + " "
        strRep += " **\n"
        if(self.__hasForest):
            strRep += "** Forest **\n"
        if(self.__hasMountain):
            strRep += "** Mountain **\n"
        if(self.__hasDesert):
            strRep += "** Desert**\n "
        if(self.__hasFaultLine):
            strRep += "** Fault Line**\n "
        if(self.__hasVolcano):
            strRep += "** Volcano!**\n "
        if(self.__hasFarm):
            strRep += "** Farm **\n "
        if(self.__numOfTribes > 0):
            strRep += "** Number of Tribes: " + str(self.__numOfTribes) + " **\n"
        if(self.__hasCity):
            strRep += " ** City AV: " + str(self.__cityAV) + " **\n"
        return strRep
    def getNumTribes(self):
        return self.__numOfTribes
    def addTribes(self, noT):
        self.__numOfTribes += noT
        if (self.__numOfTribes) < 0:
            self.__numOfTribes = 0
    def plantForest(self):
        self.__hasForest = true
    def hasForest(self):
        return self.__hasForest
    def hasCity(self):
        return self.__hasCity
    def hasDesert(self):
        return self.__hasDesert
    def hasFaultLine(self):
        return self.__hasFaultLine
    def hasVolcano(self):
        return self.__hasVolcano
    def hasFarm(self):
        return self.__hasFarm
    def setFaultLine(self, b):
        self.__hasFaultLine = b
    def getCitySize(self):
        return self.__cityAV
    def getRegionNumber(self):
        return self.__regionNumber
    def holdTempTribes(self, num):
        self.__tempTribes += num
    def resetTempTribes(self):
        self.__numOfTribes += self.__tempTribes
        self.__tempTribes = 0
    def getNeighbors(self):
        return self.__neighbors
    def buildFarm(self):
        self.__numOfTribes -= 2
        self.__hasForest = False
        self.__hasFarm = True
    def buildCity(self):
        self.__numOfTribes -= 4
        self.__hasCity = True
        self.__cityAV = 1
    def advanceCity(self):
        self.__cityAV += 1
    #poor choice of below function name
    def growCity(self, av, canDecimate):
        self.__cityAV += av
        if (self.__cityAV < 0):
            if (canDecimate):
                self.__cityAV = 0
                self.__hasCity = False
            else:
                self.__cityAV = 1


import os

from flask import Flask

def create_app(test_config=None):
	app = Flask(__name__, instance_relative_config=True)
	app.config.from_mapping(
		SECRET_KEY='dev',
		DATABASE=os.path.join(app.instance_path, 'coach_scheduler.sqlite'),
	)

	if test_config is None:
		app.config.from_pyfile('config.py', silent=True)
	else:
		app.config.from_mapping(test_config)

	try:
		os.makedirs(app.instance_path)
	except OSError:
		pass

	from . import db
	db.init_app(app)

	from . import auth
	app.register_blueprint(auth.bp)

	from . import schedule
	app.register_blueprint(schedule.bp)
	app.add_url_rule('/', endpoint='index')

	return app


__author__ = 'Roglan'
__author__ = 'Roglan'
from time import *

stevilo1 = int(input("vpisi 1. stevilo \n"))
stevilo2 = int(input("vpisi 2. stevilo \n"))
produkt = stevilo1 * stevilo2
if (stevilo1 == 6 & stevilo2 == 7):
    sleep(4.2)
else:
    sleep(produkt / 10)
print("zmozek stevil je ", produkt)


# Sean Page
# Week 2,01/27/20
# Python Project, Text Based RPG Game

# In is a RPG game, the hero fights goblins and zombies. The hero has the following options:
# 1. Fight a goblin or zombie. The fight encounters are random.
# 2. Run away from the fight which can randomly result in either escape or staying in the fight anyway. The hero may be hit while attempting to run.
# 3. The hero can also gain gold from downed creatures. I subbed gold for power because what's an rpg without gold?!

import sys         #sys — System-specific parameters and functions. This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
import os          #The OS module in python provides functions for interacting with the operating system. OS, comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality.
import textwrap
import time
import random

screen_with = 100

""" HERO & ENEMY SETUP """
                                        #Notes:
class hero():                           #Classes allow the programer to initialize & store the state of the values so that it can be accessed later in the program.
    def __init__(self, name):           #A class defines the general behavior that a whole category of objects can follow & the info can be associated with those objects.
        self.name = name                # the __init__ is a constructor method. The info in the () are objects (aka parameters. The objects have...
        self.max_health_points = 100    #...attributes attached to them. In this example those attributes such as name, max_health_points, attack, etc..
        self.health_points = self.max_health_points
        self.attack = 20
        self.gold = 0
        self.game_over = False
heroIG = hero(hero)   #heroIG is a variable sets a new instance of the class hero. It invokes the class hero() & has all of its attributes.
                                        #Example:  class Hero()""
class Goblin():                                     #    def __init__(self, name, max_health_points, health__points, attack, gold_gain)
    def __init__(self, name):                       #Goblin = Hero(self, name, max_health_points, health__points, attack, gold_gain)
        self.name = name                            #Zombie = Hero(self, name, max_health_points, health__points, attack, gold_gain)
        self.max_health_points = 30
        self.health_points = self.max_health_points
        self.attack = 10
        self.gold_gain = 10
GoblinIG = Goblin('Goblin')

class Zombie():
    def __init__(self, name):
        self.name = name
        self.max_health_points = 150
        self.health_points = self.max_health_points
        self.attack = 10
        self.gold_gain = 50
ZombieIG = Zombie('Zombie')

""" MAIN TITLE SCREEN """

def title_screen():                          #Defined a new method and named it title_screen().
    os.system('clear')                       #Calls a command from the OS that clears the terminal after each section to reduce clutter.
    print('##################################')
    print('#                                #')
    print('#       Welcome Brave One!       #')
    print('#                                #')
    print('##################################')
    print('#                                #')
    print('#        -- Start Game --        #')
    print('#         - Quit Game -          #')
    print('#                                #')
    print('#                                #')
    print('#                                #')
    print('#  Type Start Game or Quit Game  #')
    print('##################################')
    print('                                  ')
    option = input('> ')                        # Using > to mark input area for hero.
    if option.lower() == ('start game'):        # Using if, elif & while as conditions settings for the title screen.
        setup_game()                            #.lower method will make everthing lower so capitalization want create an error.
    elif option.lower() == ('quit game'):
        sys.exit()
    else:
        title_screen()

""" START OPTION Q & A for gaining character info & greeting the character """

def setup_game():
    os.system('clear')                        # Clears the screen to reduce clutter.
    print("Hello. You seem new to these parts. What is your name stranger?")
    option = input('> ')
    global heroIG               #Global variable.
    heroIG = hero(option)
    setup_game2()

def setup_game2():
    os.system('clear')
    print('"These are dark times brave one & we are in need of a person with your skills. -  Book of Zartoes the Wise"')
    print('"Destroy the evil and become our hero." - Book of the Brave One"')
    print('')
    print('############################')
    print('#                          #')
    print('#    CHARACTER  SHEET      #')
    print('#                          #')
    print('############################')
    print('                            ')
    print('Hero\'s Name:    {}'.format(heroIG.name))    #These could have been f'strings. print(f'Hero\'s Name: {heroIG.name}')
    print('Attack Power:    {}'.format(heroIG.attack))
    print('Health Points:   {}/{}'.format(heroIG.max_health_points, heroIG.health_points))
    print('Gold Pieces:     {}'.format(heroIG.gold))
    print('')
    print(' 1. Do Battle!')
    print('')
    print(' 2. Exit Game.')
    print('')
    print( 'Type 1 or 2 & press enter.')
    print('')
    option = input('> ')
    if option == '1':                         #The logic for the the character sheet.
        pre_fight()           #Could have used a while loop. Example, while option != '1' and option != '2:
    elif option == '2':                                                 #set_game2()
        sys.exit()              #if a while loop was used I would have created a def option_picked with if & elif with their perspective call paths.
    else:
        setup_game2()

""" COMBAT """

def pre_fight():
    global enemy
    enemy_number = random.randint(1,2)
    if enemy_number == 1:
        enemy = GoblinIG
    else:
        enemy = ZombieIG
    fight()

def fight():
    os.system('clear')
    print('#### {}            vs.        {} ####'.format(heroIG.name, enemy.name))
    print('')
    print('{}\'s Health: {}/{}           {}\'s Health: {}/{}'.format(heroIG.name, heroIG.max_health_points, heroIG.health_points, enemy.name, enemy.max_health_points, enemy.health_points))
    print('')
    print(' 1. Fight!')
    print('')
    print(' 2. Run Away.')
    print('')
    option = input('> ')
    if option == '1':
        attack()
    elif option == '2':
        run()
    else:
        fight()

def attack():
    os.system('clear')
    hero_attack = random.randint(heroIG.attack - 2, heroIG.attack) #Lowest attack will have 2 subtracted from it and the hightest attack will be unchanged.
    enemy_attack = random.randint(enemy.attack - 2, enemy.attack)
    if hero_attack == heroIG.attack - 2:
        print('You missed wildly!')
    else:
        enemy.health_points -= hero_attack                         #This takes the enemy health and has the hero attack subtract from it.
        print('You hit the creature! {} damaged taken by the shawdow dweller!'.format(hero_attack))
    option = input('')       #This empty set acts as pauses.       #Once the enemy's health get to or less than 0 the code go to the win(), code runs and displays that the player won.
    if enemy.health_points <= 0:
        win()
    os.system('clear')
    if enemy_attack == enemy_attack - 2:
        print("The foul beast missed!!")
    else:
        heroIG.health_points -= enemy_attack
        print("The creature strikes and you have been wounded! Blood flows from your injury. {} damanged taken.".format(enemy_attack))
    option = input('')
    if heroIG.health_points <= 0:
        dead()
    else:
        fight()
    os.system('clear')

def run():
    os.system('clear')
    run_num = random.randint(1,4)
    if run_num ==  1:
        print("Your legs carry you away from the battle, but your heart died that day and your thoughts never left the battle field.")
        option = input ('')
        setup_game2()
    else:
        print("Your legs feel like dead weight. The hour of challenge is at hand. Stand your ground!!!")
        option = input ('')
        os.system('clear')
        enemy_attack = random.randint(enemy.attack - 2, enemy.attack)
        if enemy_attack == enemy_attack - 2:
            print("The foul beast missed!")
        else:
            heroIG.health_points -= enemy_attack
            print("You have been wounded! {} damanged taken.".format(enemy_attack))
        option = input('')
        if heroIG.health_points <= 0:
            dead()
        else:
            fight()
        os.system('clear')

def win():
    os.system('clear')
    enemy.health_points = enemy.max_health_points
    heroIG.gold += enemy.gold_gain
    print('                ### Sweet Victory! ###')
    print('                      ')
    print('You have defeated the {} & have found {} gold pieces.'.format(enemy.name, enemy.gold_gain))
    option = input('')
    setup_game2()

def dead():
    os.system('clear')
    print('                      ')
    print('                                +++GAME OVER+++')
    print('                      ')
    print('{} is no longer among the living. You are dead. May your soul know peace.'.format(heroIG.name))
    option = input ('')
    sys.exit()

title_screen()


# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.

from __future__ import absolute_import, print_function, unicode_literals

import pytest

from ptvsd.common import log
from ptvsd.common.compat import reload

from ptvsd.server import cli, options

@pytest.mark.parametrize("target_kind", ["file", "module", "code"])
@pytest.mark.parametrize("client", ["", "client"])
@pytest.mark.parametrize("wait", ["", "wait"])
@pytest.mark.parametrize("subprocesses", ["", "subprocesses"])
@pytest.mark.parametrize("extra", ["", "extra"])
def test_targets(target_kind, client, wait, subprocesses, extra):
    args = ["--host", "localhost", "--port", "8888"]

    if client:
        args += ["--client"]

    if wait:
        args += ["--wait"]

    if not subprocesses:
        args += ["--no-subprocesses"]

    if target_kind == "file":
        target = "spam.py"
        args += [target]
    elif target_kind == "module":
        target = "spam"
        args += ["-m", target]
    elif target_kind == "code":
        target = "123"
        args += ["-c", target]
    else:
        pytest.fail(target_kind)

    if extra:
        extra = [
            "ham",
            "--client",
            "--wait",
            "-y",
            "spam",
            "--",
            "--host",
            "--port",
            "-c",
            "--something",
            "-m",
        ]
        args += extra
    else:
        extra = []

    log.debug("args = {0!r}", args)
    reload(options)
    rest = list(cli.parse(args))
    assert rest == extra

    expected_options = {
        "target_kind": target_kind,
        "target": target,
        "host": "localhost",
        "port": 8888,
        "wait": bool(wait),
        "multiprocess": bool(subprocesses),
    }
    actual_options = {name: vars(options)[name] for name in expected_options}
    assert expected_options == actual_options

def test_unsupported_arg():
    reload(options)
    with pytest.raises(Exception):
        cli.parse(["--port", "8888", "--xyz", "123", "spam.py"])

def test_host_required():
    reload(options)
    with pytest.raises(Exception):
        cli.parse(["--port", "8888", "-m", "spam"])

def test_host_empty():
    reload(options)
    cli.parse(["--host", "", "--port", "8888", "spam.py"])
    assert options.host == ""

def test_port_default():
    reload(options)
    cli.parse(["--host", "localhost", "spam.py"])
    assert options.port == 5678


#!/usr/bin/env python
__author__ = 'Albino'

"""
将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中
"""

import xlrd
import xml.dom.minidom as md

def get_xls_data(filename):
     book = xlrd.open_workbook(filename)
     sheet = book.sheet_by_index(0)
     content = {}
     for i in range(sheet.nrows):
         content[i+1] = sheet.row_values(i)[1:]
     return content

def write_to_xml(xlscontent):
    xmlfile = md.Document()
    root = xmlfile.createElement('root')
    citys = xmlfile.createElement('citys')
    xmlfile.appendChild(root)
    root.appendChild(citys)
    comment = xmlfile.createComment('城市信息')
    citys.appendChild(comment)
    xmlcontent = xmlfile.createTextNode(str(xlscontent))
    citys.appendChild(xmlcontent)
    with open('citys.xml', 'wb') as f:
        f.write(xmlfile.toprettyxml(encoding='utf-8'))

if __name__ == '__main__':
    write_to_xml(get_xls_data('city.xls'))


class User(object):

    def __init__(self):
        self.progress = 0
        self._ranks = range(-8,0) + range(1, 9)
        self._rank = 0

    @property
    def rank(self):
        return self._ranks[self._rank]

    @rank.setter
    def rank(self, i):
        self._rank = i

    def inc_progress(self, rank):
        delta = self._ranks.index(rank) - self._ranks.index(self.rank)
        if self.rank == 8: return
        if delta > 0:
            self.progress += 10 * delta ** 2
        elif delta == 0:
            self.progress += 3
        elif delta == -1:
            self.progress += 1
        while self.progress >= 100:
            self.progress -= 100
            self._rank += 1
            if self.rank == 8:
                self.progress = 0


import numpy as np

def gamma(A, B):
    print(A@B)
    G = np.array([B, A@B])
    G = G.squeeze()
    print('gamma', G)
    print('rank', np.linalg.matrix_rank(G))

# A = np.array([
#     [2, 0],
#     [1, 1]
# ])
# B = np.array([[1], [1]])
# gamma(A, B)
# print()
# A = np.array([
#     [0, 1],
#     [0, 0]
# ])
# B = np.array([[0], [1]])
# gamma(A, B)
A = np.array([
    [0, 1, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 1],
    [0, 0, 0, 0]
])
B = np.array([
    [0], [1], [0], [0]
])
u = 2

a = np.linalg.eig(A)
print(a)

print(A@A)
gamma = np.array([
    B, A@B, A@A@B, A@A@A@B
])
print(gamma)
r = np.linalg.matrix_rank(gamma)
print(r)
gamma1 = gamma.reshape((4, 4))
print(gamma1)
r = np.linalg.matrix_rank(gamma1)
print(r)
gamma2 = gamma.squeeze()
print(gamma2)
r = np.linalg.matrix_rank(gamma1)
print(r)

B = np.array([[0, 0], [1, 0], [0, 0], [0, 1]])
# controllability matrix
gamma = np.array([
    B, A@B, A@A@B, A@A@A@B
])
gamma = gamma.reshape((8, 4))
r = np.linalg.matrix_rank(gamma)
print(gamma)
print(r)


import numpy as np

x_train = np.load('./_save/_npy/k59_3_train_x.npy')
y_train = np.load('./_save/_npy/k59_3_train_y.npy')
x_test = np.load('./_save/_npy/k59_3_test_x.npy')
y_test = np.load('./_save/_npy/k59_3_test_y.npy')

# 2. 모델
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten

model = Sequential()
model.add(Conv2D(32, (2,2), input_shape=(150,150,3)))
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))

# 3. 컴파일, 훈련
model.compile(loss= 'binary_crossentropy', optimizer='adam', metrics=['acc'])

# model.fit(x_train, y_train)
hist = model.fit(x_train, y_train, epochs=10, steps_per_epoch=32, validation_split=0.1
    # validation_data=x_test,
    # validation_steps=4
) # 160/5 = 32

acc = hist.history['acc']
# val_acc = hist.history['val_acc']
loss = hist.history['loss']
# val_loss = hist.history['val_loss']

# 위에거로 시각화 할 것

print('acc :', acc[-1])
# print('val_acc: ', val_acc[:-1])


# -*- coding: utf-8 -*-
# @Time    : 3/21/18 10:56 AM
# @Author  : Zhu Junwei
# @File    : download_sample.py
import os
import requests
import concurrent.futures as futures

def downloadimgs(datafile):
    cid32namedict = dict()
    cid3downloadednum = dict()
    targetpath = "/data1/36w/"
    cid32namefile = "/data1/img_list/cid32namefinal.txt"

    cid32namelines = open(cid32namefile, mode='r', encoding='UTF-8').readlines()
    for line in cid32namelines:
        words = line.split(' ')
        cid32namedict[words[0]] = words[words.__len__() - 1][0:words[words.__len__() - 1].__len__() - 1]
        cid3downloadednum[words[0]] = 0
    imgdatalines = open(datafile, mode='r', encoding='UTF-8').readlines()

    for cid3 in cid32namedict:
        folder_path = os.path.join(targetpath, cid3 + "_" + cid32namedict.get(cid3))
        if os.path.exists(folder_path) == False:
            os.mkdir(folder_path)

    successcounter = 0
    failcounter = 0
    for line in imgdatalines:
        strlist = line.split()
        skuidstr = strlist[0]
        cid3 = strlist[1]
        if cid3 not in cid32namedict:
            continue
        if cid3downloadednum[cid3] > 3000:
            continue
        imgstr = strlist[2]
        imgurl = "http://img10.360buyimg.com/n12/" + imgstr
        savepath = os.path.join(targetpath, cid3 + "_" + cid32namedict.get(cid3))
        savename = cid3 + '_' + skuidstr + '_' + imgstr.replace('/', '_')
        save_file_path = os.path.join(savepath,savename)
        print(save_file_path)
        if os.path.exists(save_file_path):
            continue
        try:
            response = requests.get(imgurl)
            with open(save_file_path, "wb") as imgfile:
                imgfile.write(response.content)
                successcounter+=1
                imgfile.close()
            cid3downloadednum[cid3] += 1
        except Exception:
            print(skuidstr + " " + imgstr + " cannot download or save successfully!")
            failcounter+=1
        if successcounter % 1000 == 0:
            print("image saved: " + str(successcounter))
    print("done")
    print("image saved: " + str(successcounter))
    print("image failed: " + str(failcounter))

if __name__ == "__main__":
    downloadimgs('/home/zjw/Desktop/new_add_pics.txt')
    # thread_num = 10
    # with futures.ProcessPoolExecutor(max_workers=thread_num) as executor:
    #     future_list = list()
    #     for i in range(thread_num):
    #         file_list = '/data1/img_list/pick_imgs{}.txt'.format(i+1)
    #
    #         future_list.append(executor.submit(downloadimgs, file_list))
    #     for future in futures.as_completed(future_list):
    #         if future.exception():
    #             print(future.exception())


"""
Salt Factories PyTest plugin interface.
"""
import logging

import pytest

import saltfactories.utils.tempfiles

log = logging.getLogger(__name__)

def pytest_runtest_logstart(nodeid):
    """
    Signal the start of running a single test item.

    This hook will be called **before** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and
    :func:`pytest_runtest_teardown` hooks.

    :param str nodeid: full id of the item
    :param location: a triple of ``(filename, linenum, testname)``
    """
    log.debug(">>>>>>> START %s >>>>>>>", nodeid)

def pytest_runtest_logfinish(nodeid):
    """
    Signal the complete finish of running a single test item.

    This hook will be called **after** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and
    :func:`pytest_runtest_teardown` hooks.

    :param str nodeid: full id of the item
    :param location: a triple of ``(filename, linenum, testname)``
    """
    log.debug("<<<<<<< END %s <<<<<<<", nodeid)

def pytest_runtest_logreport(report):
    """
    Log the test running.

    Process the :py:class:`_pytest.reports.TestReport` produced for each
    of the setup, call and teardown runtest phases of an item.
    See :func:`pytest_runtest_protocol` for a description of the runtest protocol.
    """
    if report.when == "call":
        log.debug("======= %s %s ========", report.outcome.upper(), report.nodeid)

@pytest.hookimpl(trylast=True)
def pytest_load_initial_conftests(*_):
    """
    Register our pytest helpers.
    """
    # Do not move these deferred imports. It allows running against a Salt
    # onedir build in salt's repo checkout.
    import salt.version  # pylint: disable=import-outside-toplevel

    if salt.version.__saltstack_version__ < "3005":
        msg = f"Only salt>=3005 is supported(Installed version {salt.version.__saltstack_version__}"
        raise pytest.UsageError(msg)
    if "temp_directory" not in pytest.helpers:
        pytest.helpers.register(saltfactories.utils.tempfiles.temp_directory, name="temp_directory")
    if "temp_file" not in pytest.helpers:
        pytest.helpers.register(saltfactories.utils.tempfiles.temp_file, name="temp_file")


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 子图
fig = plt.figure(figsize=(10,6), facecolor='gray')

ax1 = fig.add_subplot(2,2,1) # 切换到 两行两列 第一张图
plt.plot(np.random.rand(50).cumsum(), 'k--')

ax1 = fig.add_subplot(2,2,2) # 切换到 两行两列 第二张图
plt.plot(np.random.rand(50).cumsum(), 'b--')

plt.show()

fig,axes = plt.subplots(2, 3, figsize=(10,4),
	sharex=True, sharey=True # 共享坐标轴
	)

ax1 = axes[0,1]
ts = pd.Series(np.random.randn(1000).cumsum())
ax1.plot(ts)

df = pd.DataFrame(np.random.randn(100, 2))
df.plot(ax=axes[1,0])

plt.show()


import glob
import sys

import elasticsearch
import elasticsearch.client
import elasticsearch.helpers

from .break_down import process_file
from .prepare_index import create_index

INDEX_NAME = "oracc"

def debug(msg):
    print(msg)

def upload_entries(es, entries):
    for entry in entries:
        entry["_index"] = INDEX_NAME
        entry["completions"] = [entry["cf"], entry["gw"]]
    elasticsearch.helpers.bulk(es, entries)

def upload_file(es, input_file):
    upload_entries(es, process_file(input_file, write_file=False))

def ICU_installed(es):
    """Check whether the ICU Analysis plugin is installed locally."""
    cc = elasticsearch.client.CatClient(es)
    return "analysis-icu" in [p["component"] for p in cc.plugins(format="json")]

if __name__ == "__main__":
    es = elasticsearch.Elasticsearch()
    if not ICU_installed(es):
        debug("ICU Analysis plugin is required but could not be found. Exiting.")
        sys.exit()

    clear_database = True

    if len(sys.argv) > 1:
        files = sys.argv[1:]
        print(files)
    else:
        files = glob.glob("neo/gloss-???.json")
    debug("Will index {}".format(",".join(files)))

    # Clear ES database if desired
    client = elasticsearch.client.IndicesClient(es)
    if clear_database:
        try:
            debug("Will delete index " + INDEX_NAME)
            client.delete(INDEX_NAME)
        except elasticsearch.exceptions.NotFoundError:
            debug("Index not found, continuing")

    # Create the index with the required settings
    create_index(es, INDEX_NAME)

    for file in files:
        # Break down into individual entries and upload to ES using the bulk API
        upload_file(es, file)


# Add a screen overlay to a kml file
#
###############################################################################
# Copyright (c) 2018, Patrick Broxton
#
#  Permission is hereby granted, free of charge, to any person obtaining a
#  copy of this software and associated documentation files (the "Software"),
#  to deal in the Software without restriction, including without limitation
#  the rights to use, copy, modify, merge, publish, distribute, sublicense,
#  and/or sell copies of the Software, and to permit persons to whom the
#  Software is furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included
#  in all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
#  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
#  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
#  DEALINGS IN THE SOFTWARE.
###############################################################################

import sys,os
import shutil

def add_screen_overlay(kml_path,image_path,overlay_folder_name,OverlayName):

    if os.path.isdir(overlay_folder_name) == False:
        os.makedirs(overlay_folder_name)

    shutil.copy(image_path, overlay_folder_name + os.path.sep + OverlayName)

    f = open(kml_path)
    kml_str = f.read()
    f.close()

    kml_rep = '''<ScreenOverlay>
        <Icon>
          <href>%s</href>
        </Icon>
        <overlayXY x="0" y="0.05" xunits="fraction" yunits="fraction"/>
        <screenXY x="0" y="0.05" xunits="fraction" yunits="fraction"/>
        <rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
        <size x="0" y="0" xunits="fraction" yunits="fraction"/>
    </ScreenOverlay>
    </Document>''' %(OverlayName)

    kml_str = kml_str.replace('</Document>',kml_rep)

    fid_out = open(kml_path,'w')
    fid_out.write(kml_str);
    fid_out.close()

if __name__ == '__main__':
    kml_path = sys.argv[1]
    image_path = sys.argv[2]
    overlay_folder_name,OverlayName = os.path.split(sys.argv[3])
    add_screen_overlay(kml_path,image_path,overlay_folder_name,OverlayName)


import FWCore.ParameterSet.Config as cms

from Configuration.Eras.Era_Run3_DDD_cff import Run3_DDD

process = cms.Process('HARVESTING',Run3_DDD)

# import of standard configurations
process.load('Configuration.StandardSequences.Services_cff')
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('Configuration.EventContent.EventContent_cff')
process.load('SimGeneral.MixingModule.mixNoPU_cfi')
process.load('Configuration.Geometry.GeometryExtended2021Reco_cff')
process.load('Configuration.StandardSequences.MagneticField_cff')
process.load('Configuration.StandardSequences.DQMSaverAtRunEnd_cff')
process.load('Configuration.StandardSequences.Harvesting_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')

process.maxEvents = cms.untracked.PSet(
    input = cms.untracked.int32(100),
    output = cms.optional.untracked.allowed(cms.int32,cms.PSet)
)

# Input source
process.source = cms.Source("DQMRootSource",
    fileNames = cms.untracked.vstring('file:step3_ZMM_ddd_inDQM.root')
)

process.options = cms.untracked.PSet(
    FailPath = cms.untracked.vstring(),
    IgnoreCompletely = cms.untracked.vstring(),
    Rethrow = cms.untracked.vstring('ProductNotFound'),
    SkipEvent = cms.untracked.vstring(),
    allowUnscheduled = cms.obsolete.untracked.bool,
    canDeleteEarly = cms.untracked.vstring(),
    emptyRunLumiMode = cms.obsolete.untracked.string,
    eventSetup = cms.untracked.PSet(
        forceNumberOfConcurrentIOVs = cms.untracked.PSet(

        ),
        numberOfConcurrentIOVs = cms.untracked.uint32(1)
    ),
    fileMode = cms.untracked.string('FULLMERGE'),
    forceEventSetupCacheClearOnNewRun = cms.untracked.bool(False),
    makeTriggerResults = cms.obsolete.untracked.bool,
    numberOfConcurrentLuminosityBlocks = cms.untracked.uint32(1),
    numberOfConcurrentRuns = cms.untracked.uint32(1),
    numberOfStreams = cms.untracked.uint32(0),
    numberOfThreads = cms.untracked.uint32(1),
    printDependencies = cms.untracked.bool(False),
    sizeOfStackForThreadsInKB = cms.optional.untracked.uint32,
    throwIfIllegalParameter = cms.untracked.bool(True),
    wantSummary = cms.untracked.bool(False)
)

# Production Info
process.configurationMetadata = cms.untracked.PSet(
    annotation = cms.untracked.string('step4 nevts:100'),
    name = cms.untracked.string('Applications'),
    version = cms.untracked.string('$Revision: 1.19 $')
)

# Output definition

# Additional output definition

# Other statements
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:phase1_2022_realistic', '')

# Path and EndPath definitions
process.genHarvesting = cms.Path(process.postValidation_gen)
process.validationprodHarvesting = cms.Path(process.hltpostvalidation_prod+process.postValidation_gen)
process.validationHarvestingHI = cms.Path(process.postValidationHI)
process.alcaHarvesting = cms.Path()
process.validationHarvestingFS = cms.Path(process.recoMuonPostProcessors+process.postValidationTracking+process.MuIsoValPostProcessor+process.calotowersPostProcessor+process.hcalSimHitsPostProcessor+process.hcaldigisPostProcessor+process.hcalrechitsPostProcessor+process.electronPostValidationSequence+process.photonPostProcessor+process.pfJetClient+process.pfMETClient+process.pfJetResClient+process.pfElectronClient+process.rpcRecHitPostValidation_step+process.makeBetterPlots+process.bTagCollectorSequenceMCbcl+process.METPostProcessor+process.L1GenPostProcessor+process.bdHadronTrackPostProcessor+process.siPixelPhase1OfflineDQM_harvestingV+process.MuonGEMHitsPostProcessors+process.MuonGEMDigisPostProcessors+process.MuonGEMRecHitsPostProcessors+process.postValidation_gen)
process.validationpreprodHarvesting = cms.Path(process.postValidation_preprod+process.hltpostvalidation_preprod+process.postValidation_gen)
process.validationHarvestingNoHLT = cms.Path(process.postValidation+process.postValidation_gen)
process.validationpreprodHarvestingNoHLT = cms.Path(process.postValidation_preprod+process.postValidation_gen)
process.dqmHarvestingPOGMC = cms.Path(process.DQMOffline_SecondStep_PrePOGMC)
process.dqmHarvestingFakeHLT = cms.Path(process.DQMOffline_SecondStep_FakeHLT+process.DQMOffline_Certification)
process.DQMHarvestMiniAOD_step = cms.Path(process.DQMHarvestMiniAOD)
process.dqmsave_step = cms.Path(process.DQMSaver)

# Schedule definition
process.schedule = cms.Schedule(process.validationHarvesting,process.dqmHarvesting,process.dqmHarvestingExtraHLT,process.validationHarvestingMiniAOD,process.DQMHarvestMiniAOD_step,process.dqmsave_step)
from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask
associatePatAlgosToolsTask(process)

# Customisation from command line

# Add early deletion of temporary data products to reduce peak memory need
from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete
process = customiseEarlyDelete(process)
# End adding early deletion


import numpy as np
from numba import jit

@jit
def nroot(x0,f,fp,tol=1e-5,miter=15):
    i=0
    xold=x0
    xnew=np.inf
    while abs(xold-xnew)>tol and i < 15:
        if i != 0:
            xold = np.copy(xnew)
        xnew = xold - f(xold)/fp(xold)
        # xold = np.copy(xnew)
        i+=1
        # print(xold)
    if abs(xold-xnew)<tol:
        return xnew
    else:
        return "fail"

@jit
def pdif(r, p1, p2, n1, n2):
    dif = p2 * (1 - (1 + r) ** (-n2)) - p1 * (((1 + r) ** n1) - 1)
    return dif

@jit
def pder(r, p1, p2, n1, n2, h=1e-10):
    der = (pdif(r + h, p1, p2, n1, n2) - pdif(r - h, p1, p2, n1, n2)) / (2 * h)
    return der

# @jit

def psolve(p1, p2, n1, n2,tol=1e-5, miter=1500):
        i = 0
        xold = .1
        xnew = - 1000 + tol
        while abs(xold - xnew) > tol and i < miter:
            if i != 0:
                xold = np.copy(xnew)
            xnew = xold - pdif(xold,p1, p2, n1, n2) / pder(xold,p1, p2, n1, n2)
            i += 1
            # xold = np.copy(xnew)
            # print(xnew)
        if abs(xold - xnew) < tol:
            return xnew
        else:
            return "fail"


from status.models import Status
from permisos.models import UsersPerfiles
from productos.models import Insumos, Productos, ProductosInsumos
from inventarios.models import Stock
from configuraciones.models import Puntos, PuntosAlmacenes, Almacenes

from controllers.DefaultValues import DefaultValues

from django.db import transaction

class StockController(DefaultValues):
    def __init__(self):
        DefaultValues.__init__(self)

        self.table_name = 'registros'
        self.table_id = 'registro_id'

    def update_stock(self, user_perfil, almacen, producto, cantidad, fecha_elaboracion=None, fecha_vencimiento=None, lote=''):
        """actualizamos el stock"""
        try:
            with transaction.atomic():
                # productos normales
                stock_filter = Stock.objects.filter(almacen_id=almacen, insumo_id=producto, fecha_elaboracion=fecha_elaboracion, fecha_vencimiento=fecha_vencimiento, lote=lote.upper())
                stock = stock_filter.first()
                if not stock:
                    # creamos el registro
                    stock = Stock.objects.create(almacen_id=almacen, insumo_id=producto, fecha_elaboracion=fecha_elaboracion,
                                                 fecha_vencimiento=fecha_vencimiento, lote=lote.upper(), user_perfil_id=user_perfil, status_id=self.status_activo)

                cantidad_update = stock.cantidad + cantidad
                stock.cantidad = cantidad_update
                stock.save()

            return True

        except Exception as ex:
            print('Error update stock: ' + str(ex))
            self.error_operation = 'Error al actualizar stock, ' + str(ex)
            return False

    def stock_producto(self, producto_id, user_perfil, almacen_id):
        """devuelve el stock del producto"""
        try:
            almacen = Almacenes.objects.get(pk=almacen_id)
            #producto = Productos.objects.get(pk=producto_id)
            producto = Insumos.objects.get(pk=producto_id)

            filtros = {}
            filtros['almacen_id'] = almacen
            filtros['cantidad__gt'] = 0
            filtros['insumo_id'] = producto
            stock_almacen = Stock.objects.filter(**filtros).order_by('fecha_vencimiento', 'fecha_elaboracion', 'lote')

            return stock_almacen

        except Exception as ex:
            self.error_operation = 'Error al recuperar stock, ' + str(ex)
            raise ValueError('Error al recuperar stock del producto, ' + str(ex))

    def stock_producto_insumo(self, producto_id, almacen_id):
        """devuelve el stock del producto con sus insumos"""
        try:
            producto = Productos.objects.get(pk=producto_id)

            productos_insumos = ProductosInsumos.objects.filter(producto_id=producto)
            lista_insumos = []
            for pro_ins in productos_insumos:
                dato_insumo = {}
                dato_insumo['insumo_id'] = pro_ins.insumo_id.insumo_id
                dato_insumo['insumo'] = pro_ins.insumo_id.insumo

                datos_stock = self.stock_producto(pro_ins.insumo_id.insumo_id, None, almacen_id)
                actual = 0
                for dato_aux in datos_stock:
                    actual = actual + int(dato_aux.cantidad)

                dato_insumo['cantidad'] = actual
                lista_insumos.append(dato_insumo)

            return lista_insumos

        except Exception as ex:
            self.error_operation = 'Error al recuperar stock, ' + str(ex)
            raise ValueError('Error al recuperar stock del producto, ' + str(ex))


from davidyu_cfg import *
from functions.common.loadModule.load_module_kdj import *
from functions.common.dfProcess import *

def makeFeature(df,fea_cols=None):
    '''
    feature mv_avg minus
    '''
    feature_column_list = []
    if fea_cols is None:
        fea_cols = ['mv_avg5','mv_avg10','mv_avg20','mv_avg30']
    for i in fea_cols:
        for j in fea_cols:
            fea_name = '%s%s%s'%(i,'_',j)
            fea_name1 = '%s%s%s'%(j,'_',i)
            if i!=j and fea_name not in feature_column_list and fea_name1 not in feature_column_list:
                feature_column_list.append(fea_name)
                df[fea_name] = df[i]/df[j]
                #df = dfProcess.featureProcess(df,fea_name)
    return df,feature_column_list

def featureShift(DF,feature_list,max_shift=None):
    df1 = DF.copy(deep=True)
    if max_shift is None:
        max_shift = 10
    feature_name_list = []
    for f1 in feature_list:
        for k in range(1,max_shift):
            new_name = f1+"_shift"+str(k)
            df1[new_name] = df1[f1].shift(k)
            feature_name_list.append(new_name)
    return df1,feature_name_list

data_dir = data_dict.get("test")
input_file = sys.argv[1]

df1 = pd.read_csv(os.path.join(data_dir,input_file))
df1 = cleanData.cleanColName(df1)

mv_feature = [ x for x in df1.columns.tolist() if "mv" in x ]

df2,feature_column_list = makeFeature(df1,mv_feature)
df3,feature_column_list2 = featureShift(df2,feature_column_list)
feature_names_all = feature_column_list + feature_column_list2

df3.round(3).to_csv(os.path.join(data_dir,"sh_mv_avg.csv"),index=0)
np.save(os.path.join(data_dir,"sh_index_mvavg_feature_name.npy"),feature_names_all)


import random
import json

from automoticz.extensions import proximity
from automoticz.utils import tool
from automoticz.utils import constants

@tool.cached_with_key('beacon')
def get_default_auth_beacon_name(**kwargs) -> str:
    ''' Returns name of the beacon which property "auth" is set to
    "true".

    :return: beacon name
    '''
    api = proximity.api
    query = 'status:active'
    response = api.beacons().list(q=query).execute()
    default_beacon_name = response['beacons'][0]['beaconName']
    return default_beacon_name

@tool.cached_with_key('project_namespace')
def get_default_project_namespace(**kwargs) -> str:
    ''' Returns name of default namespace for attachments

    :return: default namespace name
    '''
    api = proximity.api
    query = {'projectId': proximity.project_id}
    resp = api.namespaces().list(**query).execute()
    default_project_namespace = resp['namespaces'][0]['namespaceName']
    return default_project_namespace.split('/')[1]

@tool.cached_with_key(constants.CACHE_PIN_KEY)
def get_pin(**kwargs) -> str:
    ''' Checks if for beacon with given name pin attachment
    is set.

    :param beacon_name: name of the beacon
    :param namespace: namespace
    '''
    api = proximity.api
    beacon_name = get_default_auth_beacon_name(cached=True)
    namespace = get_default_project_namespace(cached=True)
    namespaced_type = '{}/{}'.format(namespace, constants.PIN_ATTACHMENT_KEY)
    query = {'beaconName': beacon_name, 'namespacedType': namespaced_type}
    resp = api.beacons().attachments().list(**query).execute()
    attachments = resp.get('attachments')
    if not attachments:
        return None
    b64_data = attachments[0]['data']
    data = json.loads(tool.base64_to_str(b64_data))
    return data[constants.PIN_ATTACHMENT_KEY]

def is_pin_valid(pin: str) -> bool:
    ''' Checks if recieved token is valid with current
    u_token attachment.

    :param pin: incomming pin
    :return: True or False
    '''
    request_pin = tool.base64_to_str(pin)
    current_pin = get_pin(cached=True)
    return request_pin == current_pin

def unset_pin() -> dict:
    ''' Unsets "pin" type attachment on authentication beacon identified
    by beacon_name.
    '''
    api = proximity.api
    beacon_name = get_default_auth_beacon_name(cached=True)
    namespace = get_default_project_namespace(cached=True)
    namespaced_type = '{}/{}'.format(namespace,constants.PIN_ATTACHMENT_KEY)
    query = {
        'beaconName': beacon_name,
        'namespacedType': namespaced_type,
    }
    resp = api.beacons().attachments().batchDelete(**query).execute()
    return resp

def set_pin(pin: str) -> dict:
    ''' Sets "pin" type attachment on authentication beacon identified
    by beacon_name.

    :param pin: unique token
    '''
    api = proximity.api
    beacon_name = get_default_auth_beacon_name(cached=True)
    namespace = get_default_project_namespace(cached=True)
    namespaced_type = '{}/{}'.format(namespace, constants.PIN_ATTACHMENT_KEY)
    if get_pin() is not None:
        unset_pin()
    query = {
        'beaconName': beacon_name,
        'projectId': proximity.project_id,
        'body': {
            'namespacedType': namespaced_type,
            'data': tool.str_to_base64(pin),
        }
    }
    resp = api.beacons().attachments().create(**query).execute()
    return resp

def generate_pin() -> dict:
    ''' Generates new pin.

    :return: pin
    '''
    app = proximity.app
    return {
        'url': app.config.PUBLIC_URL,
        constants.PIN_ATTACHMENT_KEY: str(random.randint(1, 999999999))
    }


import voluptuous as vol
from voluptuous import Any

DEFAULT_DISCOVERY = False
DEFAULT_DISCOVERY_PREFIX = "homeassistant"
DEFAULT_AVAILABILITY_TOPIC = "home-assistant/cover/availabilty"
DEFAULT_PAYLOAD_AVAILABLE = "online"
DEFAULT_PAYLOAD_NOT_AVAILABLE ="offline"
DEFAULT_STATE_MODE = "normally_open"
DEFAULT_INVERT_RELAY = False
DEFAULT_POLL_DELAY = 0
DEFAULT_PRESS_TIME = 0.2
DEFAULT_READ_DELAY = 0.5
DEFAULT_SWITCH_DEBOUNCE = 300

CONFIG_SCHEMA = vol.Schema(
    {
    "logging": vol.Schema(
        {
            vol.Required("log_level"): Any('DEBUG', 'INFO', 'WARNING','ERROR', 'CRITICAL'),
            vol.Required("show_timestamp"): bool
        }),
    "mqtt": vol.Schema(
        {
            vol.Required("host"): str,
            vol.Required("port"): int,
            vol.Required("user"): str,
            vol.Required("password"): str,
            vol.Optional("discovery", default = DEFAULT_DISCOVERY): Any(bool, None),
            vol.Optional("discovery_prefix", default = DEFAULT_DISCOVERY_PREFIX): Any(str, None),
            vol.Optional("availability_topic", default = DEFAULT_AVAILABILITY_TOPIC): Any(str, None),
            vol.Optional("payload_available", default = DEFAULT_PAYLOAD_AVAILABLE): Any(str,None),
            vol.Optional("payload_not_available", default = DEFAULT_PAYLOAD_NOT_AVAILABLE ): Any(str, None)

        }
    ),
    "doors": [vol.Schema(
        {
            vol.Required("id"): str,
            vol.Optional("uuid"): Any(str, None),
            vol.Optional("name"): Any(str, None),
            vol.Required("relay"): int,
            vol.Required("state"): int,
            vol.Optional("open"): int,
            vol.Optional("state_mode", default = DEFAULT_STATE_MODE): Any(None, 'normally_closed', 'normally_open'),
            vol.Optional("invert_relay", default = DEFAULT_INVERT_RELAY): bool,
            vol.Optional("state_topic"): str,
            vol.Required("command_topic"): str,
            vol.Optional("poll_delay", default=DEFAULT_POLL_DELAY): int,
            vol.Optional("press_time", default=DEFAULT_PRESS_TIME): float,
            vol.Optional("read_delay", default=DEFAULT_READ_DELAY): float,
            vol.Optional("switch_debounce", default=DEFAULT_SWITCH_DEBOUNCE): int

        }
    )]
    })


from flask import Flask, jsonify, send_from_directory

import os

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

@app.route('/<path:path>', methods=['GET'])
def static_proxy(path):
  return send_from_directory('./', path)

@app.route('/')
def root():
  return send_from_directory('./', 'index.html')

@app.route('/api/prose', methods=['GET'])
def get_prose():

    folder = 'prose'

    articles = []

    directory = os.fsencode(folder)
    for file in os.listdir(directory):
         filename = os.fsdecode(file)
         articles.append(process_article(folder + '/' + filename))

    return jsonify(articles)

@app.route('/api/poetry', methods=['GET'])
def get_poetry():

    folder = 'poetry'

    poems = []

    directory = os.fsencode(folder)
    for file in os.listdir(directory):
         filename = os.fsdecode(file)
         poems.append(process_poem(folder + '/' + filename))

    return jsonify(poems)

def process_article(filename):
    article = {}
    firstLine = True
    curPar = ''
    with open(filename) as f:
        for line in f:
            line = line.rstrip()
            if firstLine:
                article['title'] = line
                firstLine = False
                article['body'] = []
            elif line:
                curPar += line + ' '
            else:
                article['body'].append(curPar)
                curPar = ''
    return article

def process_poem(filename):
    poem = {}
    firstLine = True
    with open(filename) as f:
        for line in f:
            line = line.rstrip()
            if firstLine:
                poem['title'] = line
                firstLine = False
                poem['body'] = [[]]
            elif line:
                poem['body'][-1].append(line)
            else:
                poem['body'].append([])
    return poem

if __name__ == '__main__':
   app.run()

@app.errorhandler(500)
def server_error(e):
  return 'An internal error occurred [main.py] %s' % e, 500

# No caching at all for API endpoints.
@app.after_request
def add_header(response):
    # response.cache_control.no_store = True
    response.headers['Cache-Control'] = 'no-store, no-cache, must-\
    revalidate, post-check=0, pre-check=0, max-age=0'
    response.headers['Pragma'] = 'no-cache'
    response.headers['Expires'] = '-1'
    return response


'''
coding language:    Python 3.7.0

written by:         Jonah Merrell
date written:       April 25 2019
written for:        Homework7 Task4
course:             Math 5610

purpose:            This method tests the QR factorization method on various hilbert matrices.
'''

import sys, os
sys.path.append(os.path.abspath('../../mylibrary'))
from _mymodules import matrix_solve_steepest_descent, matrix_mult, matrix_transpose, abs_error_2norm, matrix_mult, convert_vec_mat

def hilbert_matrix_steepest_descent_test():

    selection = [4,8,16,32]
    hilbert_matrix = []
    solution = []

    # Create the hilbert matrices and their corresponding Q factorization matrix.
    for n in selection:
        hilbert_matrix.append([[1/(1+i+j) for i in range(n)] for j in range(n)])  # Hilbert Matrix generator
        solution.append(matrix_solve_steepest_descent(hilbert_matrix[-1],[1]*n,0.0001,10000))

    for i in range(0,len(selection)):  # 4, 6, 8, 10
        #print(matrix_mult(hilbert_matrix[i],convert_vec_mat(solution[i])))
        print("Absolute error for " + str(selection[i]) + "x" + str(selection[i]) + ": " + str(abs_error_2norm([1]*selection[i],convert_vec_mat(matrix_mult(hilbert_matrix[i],convert_vec_mat(solution[i]))))))
        print(solution[i])
hilbert_matrix_steepest_descent_test()


# 迭代器与生成器测试代码
# reference: http://www.runoob.com/python3/python3-iterator-generator.html

import sys # 引入sys模块

# 1. 迭代器: iter
list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
for x in it:
    print (x, end=" ")
print("\n")

# 2. 迭代器： next
list = [1, 2, 3, 4]
it = iter(list)  # 创建迭代器对象

#while True:
#    try:
#        print(next(it))
#    except StopIteration:
#        sys.exit()
print(next(it))
print(next(it))

# 3. 生成器: yield
def fibonacci(n):  # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n):
            return
        yield a
        a, b = b, a + b
        counter += 1

f = fibonacci(10)  # f 是一个迭代器，由生成器返回生成
#print(f)
while True:
    try:
        print(next(f), end=" ")
    except StopIteration:
        sys.exit()


"""

Game Over / 'Restart from last save point?' pseudo-"room"

"""

import pickle, os
import pygame as pg
from .. import setup, tools
from .. import observer
from ..components import person
from .. import constants as c

class Arrow(pg.sprite.Sprite):
    """
    Arrow to select restart or saved gamed.
    """
    def __init__(self, pos_x, pos_y):
        super(Arrow, self).__init__()
        self.image = setup.GFX['smallarrow']
        self.rect = self.image.get_rect(x=pos_x, y=pos_y)
        self.index = 0
        self.pos_list = [pos_y, pos_y+34]
        self.allow_input = False
        self.observers = [observer.SoundEffects()]

    def notify(self, event):
        """
        Notify all observers of event.
        """

        for listener in self.observers:
            listener.on_notify(event)

    def update(self):
        """
        Update arrow position.
        """

        keys = setup.keys()

        if self.allow_input:
            if (
                    keys[pg.K_DOWN] and
                    not keys[pg.K_UP] and
                    self.index == 0):
                self.index = 1
                self.allow_input = False
                self.notify(c.CLICK)
            elif (keys[pg.K_UP] and
                  not keys[pg.K_DOWN] and
                  self.index == 1):
                self.index = 0
                self.allow_input = False
                self.notify(c.CLICK)

            self.rect.y = self.pos_list[self.index]

        if not keys[pg.K_DOWN] and not keys[pg.K_UP]:
            self.allow_input = True

class DeathScene(tools.State):
    """
    Scene when the player has died.
    """
    def __init__(self):
        super(DeathScene, self).__init__()

        self.name = c.DEATH_SCENE

        self.arrow = None
        self.alpha = None
        self.observers = None
        self.message_box = None
        self.background = None
        self.font = None
        self.player = None
        self.state_dict = None

        self.next = c.TOWN
        setup.mixer().set_level_song(self.name, 'shop_theme')

    def startup(self):
        self.font = pg.font.Font(setup.FONTS[c.MAIN_FONT], 22)
        self.background = pg.Surface(setup.SCREEN_RECT.size)
        self.background.fill(c.BLACK_BLUE)
        self.player = person.Player('down', 1, 1, 'resting', 1)
        self.player.image = pg.transform.scale2x(self.player.image)
        self.player.rect = self.player.image.get_rect()
        self.player.rect.center = setup.SCREEN_RECT.center
        self.message_box = self.make_message_box()
        self.arrow = Arrow(300, 532)
        self.state_dict = self.make_state_dict()
        self.state = c.TRANSITION_IN
        self.alpha = 255
        if not os.path.isfile("save.p"):
            # initializes setup.game_data internally
            tools.create_game_data_dict()
            with open("save.p", "wb") as save_file:
                pickle.dump(setup.game_data(), save_file)
        self.observers = [observer.SoundEffects()]

    def notify(self, event):
        """
        Notify all observers of event.
        """
        for listener in self.observers:
            listener.on_notify(event)

    def make_message_box(self):
        """
        Make the text box informing of death.
        """
        box_image = setup.GFX['dialoguebox']
        box_rect = box_image.get_rect()
        text = 'You have died. Restart from last save point?'
        text_render = self.font.render(text, True, c.NEAR_BLACK)
        text_rect = text_render.get_rect(centerx=box_rect.centerx,
                                         y=30)
        text2 = 'Yes'
        text2_render = self.font.render(text2, True, c.NEAR_BLACK)
        text2_rect = text2_render.get_rect(centerx=box_rect.centerx,
                                           y=70)

        text3 = 'No'
        text3_render = self.font.render(text3, True, c.NEAR_BLACK)
        text3_rect = text3_render.get_rect(centerx=box_rect.centerx,
                                           y=105)

        temp_surf = pg.Surface(box_rect.size)
        temp_surf.set_colorkey(c.BLACK)
        temp_surf.blit(box_image, box_rect)
        temp_surf.blit(text_render, text_rect)
        temp_surf.blit(text2_render, text2_rect)
        temp_surf.blit(text3_render, text3_rect)

        box_sprite = pg.sprite.Sprite()
        box_sprite.image = temp_surf
        box_sprite.rect = temp_surf.get_rect(bottom=608)

        return box_sprite

    def update(self):
        """
        Update scene.
        """
        update_level = self.state_dict[self.state]
        update_level()
        self.draw_level()

    def normal_update(self):
        self.arrow.update()
        self.check_for_input()

    def check_for_input(self):
        """
        Check if player wants to restart from last save point
        or just start from the beginning of the game.
        """

        keys = setup.keys()

        if keys[pg.K_SPACE]:
            if self.arrow.index == 0:
                self.next = c.TOWN
                with open("save.p", "rb") as save_file:
                    setup.register_game_data(pickle.load(save_file))
            elif self.arrow.index == 1:
                self.next = c.MAIN_MENU
            self.state = c.TRANSITION_OUT
            self.notify(c.CLICK2)

    def draw_level(self):
        """
        Draw background, player, and message box.
        """

        surface = setup.screen()

        surface.blit(self.background, (0, 0))
        surface.blit(self.player.image, self.player.rect)
        surface.blit(self.message_box.image, self.message_box.rect)
        surface.blit(self.arrow.image, self.arrow.rect)
        surface.blit(self.transition_surface, (0, 0))


import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

x = np.where(arr%2 == 1)

print(x)

# Find the indexes where the values are odd:

Python Examples/02) NumPy Intro/index169.py


from gevent import monkey
monkey.patch_all()

from flask import Flask
from gevent.pywsgi import WSGIServer

def run_server():
    app = Flask(__name__)

    @app.route("/")
    def hello():
        return "Hello, World!"

    server = WSGIServer(('0.0.0.0', 5005), app)
    server.serve_forever()

if __name__ == '__main__':
    from werkzeug.serving import run_with_reloader
    run_with_reloader(run_server)


from django.db.models import Max, Count
from django.shortcuts import render
import itertools
from pingpong.models import Category, Group, GroupMember, Bracket, BracketSlot

def brackets_slideshow(request):
    bracket_groups = [[], [], []]
    pages = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

    for i, category in enumerate(Category.objects.order_by('id')):
        new_brackets = list(Bracket.objects.filter(category=category).order_by('id').annotate(rounds=Max('bracketslot__level')))
        bracket_groups[pages[i]].extend(new_brackets)

    return render(request, 'brackets_slideshow.html', dict(bracket_groups=bracket_groups[2:]))

def groups_slideshow(request):
    males = Category.objects.filter(gender=0).annotate(player_count=Count('players'))

    male_members = {
        category: []
        for category in males
    }
    for member in GroupMember.objects \
                             .filter(group__category__in=males) \
                             .order_by('group__category', 'group', 'place', '-leader', 'player__surname') \
                             .prefetch_related('group', 'group__category', 'player'):
        male_members[member.group.category].append(member)

    females = Category.objects.filter(gender=1).annotate(player_count=Count('players'))
    female_members = {
        category: []
        for category in females
    }
    for member in GroupMember.objects \
        .filter(group__category__in=females) \
        .order_by('group__category', 'group', 'place', '-leader', 'player__surname') \
        .prefetch_related('group', 'group__category', 'player'):
        female_members[member.group.category].append(member)

    groups = Group.objects.select_related('category')

    single_matches = BracketSlot.objects.filter(status=1, bracket__category__gender__lt=2) \
        .select_related('player', 'bracket__category')
    single_matches = [(a, list(b)) for a, b in itertools.groupby(single_matches, lambda x: x.winner_goes_to_id)]
    single_matches = [(match, slots) for match, slots in single_matches if len(slots) == 2]

    pair_matches = BracketSlot.objects.filter(status=1, bracket__category__gender__gte=2) \
        .select_related('player', 'bracket__category')
    pair_matches = [(a, list(b)) for a, b in itertools.groupby(pair_matches, lambda x: x.winner_goes_to_id)]
    pair_matches = [(match, slots) for match, slots in pair_matches if len(slots) == 2]

    return render(request, 'groups_slideshow.html', {
        'males': male_members.items(),
        'females': female_members.items(),
        'groups': groups,
        'single_matches': single_matches,
        'pair_matches': pair_matches,
    })


import argparse
import os
import torch
import logging

import numpy as np
import torch.nn as nn

from utils import *
import utils_own
import network

import torch.optim as optim

parser = argparse.ArgumentParser(description='PyTorch CNN Training')

parser.add_argument('--save_dir', metavar='SAVE_DIR', default='./training_data/conv/', help='Save dir')
parser.add_argument('--batch', metavar='BATCH', default=256, type=int, help='Batch size to use')
parser.add_argument('--size', metavar='SIZE', default=0, type=int, help='Size of network. 1 means large and 0 means medium')
parser.add_argument('--dataset', metavar='DATASET', default='SVHN', help='Dataset to train on. Currently choose from SVHN and CIFAR10')
parser.add_argument('--full', metavar='FULL', default=0, type=int, help='If 1, train with full precision')
parser.add_argument('--binary', metavar='BINARY', default=0, type=int, help='If 1, train with dense binary')
parser.add_argument('--conv_sparsity', metavar='CONV_SPARSITY', default=0.9, type=float, help='Sparsity of the convolutional layers')
parser.add_argument('--fc_sparsity', metavar='FC_SPARSITY', default=0.9, type=float, help='Sparsity of fully-connected layers')
parser.add_argument('--permute', metavar='PERMUTE', default=-1, type=int, help='Permutation method. -1 means no permutation')
parser.add_argument('--pad', metavar='PAD', default=0, type=int, help='Padding value used')
parser.add_argument('--seed', metavar='SEED', default=0, type=int, help='Seed to use for this run')
parser.add_argument('--cpu', dest='cpu', default=False, action='store_true', help='Train using cpu')

def main():
    global args, best_prec1
    args = parser.parse_args()
    seed = args.seed
    torch.manual_seed(seed)
    np.random.seed(seed)
    torch.backends.cudnn.deterministic = True

    dataset = args.dataset
    conv_sparsity = args.conv_sparsity
    fc_sparsity = args.fc_sparsity
    permute = args.permute
    size = args.size
    batch = args.batch
    pad = args.pad
    pack = 32
    if args.full==1:
        full=True
    else:
        full=False
    if args.binary==1:
        binary=True
    else:
        binary=False
    device = 0

    trainset, testset, classes = utils_own.load_dataset(dataset)
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch,
                                              shuffle=True, num_workers=2)
    testloader = torch.utils.data.DataLoader(testset, batch_size=batch,
                                             shuffle=False, num_workers=2)

    save_dir = args.save_dir
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    if args.size==1:
        net = network.CNN_large(full=full, binary=binary, conv_thres=conv_sparsity, fc_thres=fc_sparsity, align=True, pad=pad)
    elif args.size==0:
        net = network.CNN_medium(full=full, binary=binary, conv_thres=conv_sparsity, fc_thres=fc_sparsity, align=True, pad=pad)

    save_file = save_dir + '{0}_s_{1}'.format(dataset, size)

    setup_logging(save_file + '_log.txt')
    logging.info("saving to %s", save_file)

    save_file += '.pt'
    regime = getattr(net, 'regime', {0: {'optimizer': 'Adam', 'lr': 0.1,'momentum': 0.9,'weight_decay': 1e-4}})

    if not args.cpu:
        torch.cuda.empty_cache()
        net.cuda(device)

    learning_rate = 0.001
    criterion = nn.CrossEntropyLoss()
    lr_decay = np.power((2e-6/learning_rate), (1./100))

    optimizer = optim.Adam(net.parameters(), lr=learning_rate)

    ### Training section

    # Train without packing constraints
    utils_own.adjust_pack(net,1)
    for epoch in range(0, 25):
        optimizer = adjust_optimizer(optimizer, epoch, regime)
        train_loss, train_prec1, train_prec5 = utils_own.train(trainloader, net, criterion, epoch, optimizer)
        val_loss, val_prec1, val_prec5 = utils_own.validate(testloader, net, criterion, epoch, verbal=True)

    # Retrain with permutation + packing constraint
    utils_own.adjust_pack(net, pack)
    utils_own.permute_all_weights_once(net, pack=pack, mode=permute)

    for epoch in range(0, 25):
        optimizer = adjust_optimizer(optimizer, epoch, regime)
        train_loss, train_prec1, train_prec5 = utils_own.train(trainloader, net, criterion, epoch, optimizer)
        val_loss, val_prec1, val_prec5 = utils_own.validate(testloader, net, criterion, epoch, verbal=True)

    # Fix pruned packs and fine tune
    for mod in net.modules():
        if hasattr(mod, 'mask'):
            mod.mask = torch.abs(mod.weight.data)
    net.pruned = True
    best_prec1 = 0

    for epoch in range(0, 200):
        optimizer = adjust_optimizer(optimizer, epoch, regime)
        train_loss, train_prec1, train_prec5 = utils_own.train(trainloader, net, criterion, epoch, optimizer)
        val_loss, val_prec1, val_prec5 = utils_own.validate(testloader, net, criterion, epoch, verbal=False)
        # remember best prec@1 and save checkpoint
        is_best = val_prec1 > best_prec1
        best_prec1 = max(val_prec1, best_prec1)

        if is_best:
            torch.save(net, save_file)
            logging.info('\n Epoch: {0}\t'
                         'Training Loss {train_loss:.4f} \t'
                         'Training Prec {train_prec1:.3f} \t'
                         'Validation Loss {val_loss:.4f} \t'
                         'Validation Prec {val_prec1:.3f} \t'
                         .format(epoch+1, train_loss=train_loss, val_loss=val_loss,
                                 train_prec1=train_prec1, val_prec1=val_prec1))
    logging.info('\nTraining finished')

    # Extract data
    conv_count = 0
    bn2d_count = 0
    bn1d_count = 0
    fc_count = 0

    upload_dir = save_dir

    for mod in net.modules():
        if isinstance(mod, nn.Conv2d):
            print(mod)
            weight = mod.weight.data.type(torch.int16).cpu().numpy()
            conv_count += 1
            np.save(upload_dir+'conv_{0}_weight'.format(conv_count), weight)
        if isinstance(mod, nn.BatchNorm2d):
            print(mod)
            weight = mod.weight.data.cpu().numpy()
            bias = mod.bias.data.cpu().numpy()
            mean = mod.running_mean.cpu().numpy()
            var = mod.running_var.cpu().numpy()

            bn2d_count += 1
            np.save(upload_dir+'bn2d_{0}_weight'.format(bn2d_count), weight)
            np.save(upload_dir+'bn2d_{0}_bias'.format(bn2d_count), bias)
            np.save(upload_dir+'bn2d_{0}_mean'.format(bn2d_count), mean)
            np.save(upload_dir+'bn2d_{0}_var'.format(bn2d_count), var)

        if isinstance(mod, nn.Linear):
            print(mod)
            weight = mod.weight.data.type(torch.int16).cpu().numpy()
            fc_count += 1
            np.save(upload_dir+'fc_{0}_weight'.format(fc_count), weight)
        if isinstance(mod, nn.BatchNorm1d):
            print(mod)
            bn1d_count += 1
            if type(mod.weight) != type(None):
                weight = mod.weight.data.cpu().numpy()
                np.save(upload_dir+'bn1d_{0}_weight'.format(bn1d_count), weight)
            if type(mod.bias) != type(None):
                bias = mod.bias.data.cpu().numpy()
                np.save(upload_dir+'bn1d_{0}_bias'.format(bn1d_count), bias)
            mean = mod.running_mean.cpu().numpy()
            var = mod.running_var.cpu().numpy()

            np.save(upload_dir+'bn1d_{0}_mean'.format(bn1d_count), mean)
            np.save(upload_dir+'bn1d_{0}_var'.format(bn1d_count), var)

    return 0

if __name__ == '__main__':
    main()


import re

handle = open('mbox-short.rtf')

numlist = list()

for line in handle:
    line = line.rstrip()
    stuff = re.findall('^X-DSPAM-Confidence: ([0-9.]*)', line)
    if len(stuff) != 1: continue
    num = float(stuff[0])
    numlist.append(num)

numlist.sort(reverse = True)

print(numlist[:3])


from django import forms

from .models import Invoice

class LoginForm(forms.Form):
    pass

class InvoiceForm(forms.ModelForm):
    send_text = forms.BooleanField(label="Отправить краткий текст", required=False)
    send_full_text = forms.BooleanField(label="Отправить полный текст", required=False)
    class Meta:
        model = Invoice
        fields = ('text',
                  'full_text',
                  'image',
                  'departure_date',
                  'receive_date',
                  'send_text',
                  'send_full_text')
        widgets = {
            'departure_date': forms.DateTimeInput(attrs={'type': 'datetime', 'class': 'datetimepicker'}),
            'receive_date': forms.DateTimeInput(attrs={'type': 'datetime', 'class': 'datetimepicker'}),
        }