# Text only RPG
# venombash@gmail.com
#
# This is a text only Role-Playing Game. This is based off of a DND story that
# I wrote a while back.
# Enjoy!

player = ""# the players name
health = 0# the players health
armor = 0# the players armor
hd = 0# the players hit die
race = ""# the players race
Class = ""# the players class
lang = []# the languages the players character knows
enemies = [""]# the list of enemies in a battle
enemy_health = 0# the enemies health(the one that the players currently fighting)
enemy_armor = 0# the current enemies armor
enemy_hd = 0# the enemies hit die
gp = 0# the players gold pieces
sp = 0# the players silver pieces
bp = 0# the players bronze pieces
inventory = []# the players inventory
hunger = 0# the players hunger
num_enemies = 0# the number of enemies the player has to fight

def menu():
    global player, health, armor, hd, race, Class, lang

    MENU = """
0 - Exit
1 - Name your player
2 - Choose race
3 - Choose class
4 - Start your adventure!
"""

    print(MENU)# prints the menu

    choice = input()

    if choice == "0":
        import sys
        sys.exit()
    elif choice == "1":# the player wants to name their character
        i = input("Name: ")
        player = i
    elif choice == "2":# the player wants to choose their characters race
        RACES = """
1 - Human, 6 HP, 10 Armor, Languages: Basic
2 - Dwarf, 8 HP, 15 Armor, Languages: Basic, Dwarfish
3 - Elf, 6 HP, 10 Armor, Languages: Basic, Elvish, Ald Tang
4 - Halfling, 4 HP, 5 Armor, Languages: Basic, Plesant
"""

        print(RACES)
        i = input("Race: ")
        if i == "1":
            race = "Human"
            hp = 6
            armor = 10
            lang.append("Basic")
        elif i == "2":
            race = "Dwarf"
            hp = 8
            armor = 15
            lang.append("Basic")
            lang.append("Dwarfish")
        elif i == "3":
            race = "Elf"
            hp = 6
            armor = 10
            lang.append("Basic")
            lang.append("Elvish")
            lang.append("Ald Tang")
        elif i == "4":
            race = "Halfling"
            hp = 4
            armor = 5
            lang.append("Basic")
            lang.append("Plesant")
        else:
            print("Please choose one of the above.")
    elif choice == "3":# the player wants to choose their characters class
        CLASSES = """
1 - Warrior, 6 HD
2 - Priest, 6 HD
3 - Hunter, 8 HD
4 - Rouge, 10 HD
"""
        print(CLASSES)
        i = input("Class: ")

        if i == "1":
            Class = "Warrior"
            hd = 6
        elif i == "2":
            Class = "Priest"
            hd = 6
        elif i == "3":
            Class = "Hunter"
            hd = 8
        elif i == "4":
            Class = "Rouge"
            hd = 10
        else:
            print("Please choose one of the options above.")
    elif choice == "4":# the player wants to start their adventure
        if player != "" and Class != "" and race != "":
            scene1()
        else:# the player has not finished creating their character
            print("Not done creating your player.")
    else:# the player has entered some unknown option
        print("Please enter one of the options above.")

def scene1():

    SCENE = """
You are riding to a place called Lathos for it's exquisite purple. When you get
there you are increasingly thirsty, and decide to stop for a drink at The White
Horse. A big tavern/inn.
"""
    print(SCENE)

    playerTurn('White Horse')

def playerTurn(location):

    global num_enemies

    if location == "White Horse":
        options = """
0 - Exit
1 - Inspect the Tavern
2 - Talk to the barman
3 - Leave the tavern
4 - Check Inventory
"""
        print(options)
        choice = input()

        if choice == "1":
            inspect('White Horse')
        elif choice == "2":
            talk('Barman')
        elif choice == "3":
            scene2(1)
        elif choice == "4":
            print(inventory)
            go(1)
        elif choice == "0":
            import sys
            sys.exit()

    elif location == "Lathos":
        options = """
0 - Exit
1 - Go to The White Horse
2 - Inspect the village
3 - Check inventory
"""
        print(options)
        choice = input()

        if choice == "1":
            scene3(1)
        elif choice == "2":
            inspect("Lathos")
        elif choice == "3":
            print(inventory)
            go(2)
        elif choice == "0":
            import sys
            sys.exit()

    elif location == "Bar":
        options = """
1 - \"I want a couple bottles of ale.
2 - \"I want to talk to the mayor.
"""

        print(options)
        choice = input()

        if choice == "1":
            scene4(1)
        elif choice == "2":
            scene4(2)

    elif location == "bakery":
        options = """
0 - Exit
1 - Buy some bread
2 - Talk to the baker
3 - Leave the bakery
4 - Check inventory
"""

        print(options)
        choice = input()

        if choice == "1":
            buy("bread")
        elif choice == "2":
            talk("Baker")
        elif choice == "3":
            scene2(1)
        elif choice == "4":
            print(inventory)
            go(3)
        elif choice == "0":
            import sys
            sys.exit()
    elif location == "baker":
        options = """
1 - \"I want to buy some pastries
2 - \"I want to talk to the mayor
"""
        print(options)
        choice = input()

        if choice == "1":
            buy("paste")
        elif choice == "2":
            scene6(1)

    elif location == "lib?":
        options = """
0 - Exit
1 - Go to the library
2 - Go to the White Horse
"""

        print(options)
        choice = input()

        if choice == "1":
            go('library')
        elif choice == "2":
            go(1)
        elif choice == "0":
            import sys
            sys.exit()

    elif location == "library":
        options = """
0 - Exit
1 - Inspect the library
2 - Ask about Cron
3 - Check inventory
"""

        print(options)
        choice = input()

        if choice == "1":
            inspect('lib')
        elif choice == "2":
            ask('cron')
        elif choice == "3":
            print(inventory)
            go('library')
        elif choice == "0":
            import sys
            sys.exit()

    elif location == "cron":
        SCENE = """
You go up to a man sitting at a table, by himself, sipping slowly
from an iron flask. You approch the man with caution,
\"Hello sir. I am looking for a Cron?\"
He slowly turns one eyepatched eye toward you,
\"Looks like you found him.\"
"""

        print(SCENE)
        options = """
0 - Exit
1 - \"Someone told me you knew about the fall.\"
2 - \"Sorry to bother you.\"
"""
        print(options)
        choice = input()

        if choice == "1":
            talk('cron')
        elif choice == "2":
            go('library')
        elif choice == "0":
            import sys
            sys.exit()

    elif location == "fort?":
        options = """
0 - Exit
1 - Start travling North to the fort
2 - Stay in Lathos
"""

        print(options)
        choice = input()

        if choice == "1":
            scene9(1)
        elif choice == "2":
            go('library')
        elif choice == "0":
            import sys
            sys.exit()

    elif location == 'camp':
        options = """
0 - Exit
1 - Set up camp in the clearing
2 - Set up camp in the woods
"""

        print(options)
        choice = input()

        if choice == "1":
            scene9(2)
            num_enemies = 3
        elif choice == "2":
            scene9(3)
        elif choice == "0":
            import sys
            sys.exit()

    elif location == "cave":
        options = """
0 - Exit
1 - Go through the cave
2 - Go over the cave
"""

        print(options)
        choice = input()

        if choice == "1":
            scene10(1)
        elif choice == "2":
            scene10(2)
        elif choice == "3":
            callExit()

    elif location == "woods":
        SCENE = """
As you walk you come to woods with a sign that says beware.
There is a narrow path around it.
"""
        print(SCENE)
        options = """
0 - Exit
1 - Go through woods
2 - Go around
"""
        print(options)
        choice = input()

        if choice == "1":
            endStory('woods')
        elif choice == "2":
            scene11(1)
        elif choice == "3":
            callExit()

    elif location == "canyon":
        options = """
0 - Exit
1 - Try to climb down
2 - Give up
3 - Set up camp
"""
        print(options)
        choice = input()

        if choice == "1":
            scene12(1)
        elif choice == "2":
            print("You still regret that choice")
            endGame()
        elif choice == "3":
            scene12(2)
        elif choice == "0":
            callExit()

    elif location == "beg":
        options = """
0 - Exit
1 - Attack the begger
2 - Scream at him
3 - Offer him  some meat
"""
        print(options)
        choice = input()

        if choice == "1":
            battle('begger', 1)
            scene13(1)
        elif choice == "2":
            scene13(2)
        elif choice == "3":
            scene13(3)

    elif location == "begger":
        options = """
1 - Give him some meat
2 - Force him to help you
3 - Check inventory
"""
        print(options)
        choice = input()

        if choice == "1":
            scene14(1)
        elif choice == "2":
            scene14(2)
        elif choice == "3":
            print(inventory)

    elif location == "talon":
        options = """
1 - Let him come with you
2 - Abandon him
"""
        print(options)
        choice = input()

        if choice == "1":
            scene15(1)
        elif choice == "2":
            scene15(2)

    elif location == "orc_pack":
        options = """
1 - Try to fight your way out
2 - Hide behind some rocks
"""
        print(options)
        choice = input()

        if choice == "1":
            battle('orcs, talon', 5)
        elif choice == "2":
            scene16(1)

    elif location == "orc_slave":
        SCENE = """
As you raise your sword again, it flies out of your hand and into a
nearby rock. As you look up you see a wizard, holding a staff of fire.
\"That's enough!\" he roared.
\"Take these scumbags into my dungeon!\"
As told the pack of orcs drags you and Talon a short way, and into the
dungeon.
\"Do you suppose that wizard was Drastone?\" you ask Talon.
He looks at you with fire in his eyes,
\"I have no doubt.\"
"""
        print(SCENE)
        goodbye()

def inspect(location):
    global gp, sp, bp, armor, inventory, hd

    if location == "White Horse":
        import random
        roll = random.randint(1, 2)
        if roll == 1:
            print("You found 10 GP!")
            gp += 10
            playerTurn("White Horse")
        elif roll == 2:
            print("You found 10 GP and Leather armor!")
            gp += 10
            armor += 15
            playerTurn("White Horse")

    elif location == "Lathos":
        import random
        roll = random.randint(1, 2)
        if roll == 1:
            print("You found a bakery!")
            playerTurn("bakery")
        elif roll == 2:
            print("You found a sword!")
            inventory.append("sword")
            hd += 5
            playerTurn("Lathos")

    elif location == "lib":
        import random
        roll = random.randint(1, 2)
        if roll == 1:
            print("You found a book in Ald Tang!")# ald tang = old tounge
            playerTurn('library')
        elif roll == 2:
            print("You found 5 SP!")
            sp += 5
            playerTurn('libarary')

def talk(person):
    global health, armor, enemies, iventory, gp, sp, bp

    if person == "Barman":
        import random
        roll = random.randint(1, 6)

        if roll < 4:
            print("Go away kid.")
            scene2(3)
        else:
            print("What do you need kid?")
            scene2(2)

    elif person == "Baker":
        import random
        roll = random.randint(1, 4)

        if roll < 3:
            print("Go away.")
            scene5(1)
        else:
            print("What do you need?")
            scene5(2)

    elif person == "cron":
        import random
        roll = random.randint(1, 2)

        if roll == 1:
            print("Go away")
            playerTurn('library')
        elif roll == 2:
            print('"Aye"')
            scene8("cron's story")

def scene2(scene):

    if scene == 1:
        SCENE = """
You walk out into the village and see a busy, bustling population. As you
realize the sun is going down, you have no place to sleep."""
        print(SCENE)

        playerTurn("Lathos")

    elif scene == 2:
        SCENE = """
The bartender leans across the bar toward you."""
        print(SCENE)

        playerTurn("Bar")

    elif scene == 3:

        playerTurn("White Horse")

def scene3(scene):

    if scene == 1:
        SCENE = """
You walk back to the White Horse
"""
        playerTurn("White Horse")

def buy(product):
    global gp, sp, bp, inventory, armor

    if product == "bread":# the player wants to buy bread
        if gp > 0:# the player is not broke
            if gp == 10 or gp > 10:# the player has enough money
                gp -= 10
                inventory.append("bread")
                print("You have bought some bread!")
                playerTurn('bakery')
            else:
                print("You don't have enough money")
                playerTurn('bakery')
        else:
            print("You are broke")
            playerTurn('bakery')

    elif product == "alex2":# the player wants to buy ale x2
        if gp > 0:# the player is not broke
            if gp == 20 or gp > 20:# the player has enough money
                gp -= 20
                inventory.append('ale')
                inventory.append('ale')
                print("You have bought ale x2!")
                playerTurn("White Horse")
            else:
                print("You don't have enough money")
                playerTurn('White Horse')
        else:
            print("You are broke")
            playerTurn('White Horse')

    elif product == "paste":# the player wants to buy pastries
        if gp > 0:# the player is not broke
            if gp == 5 or gp > 5:# the player has enough money
                gp -= 5
                inventory.append('pastry')
                print("You have bought a pastry!")
                playerTurn("bakery")
            else:
                print("You don't have enough money")
                playerTurn('bakery')
        else:
            print("You are broke")
            playerTurn('bakery')

def scene4(scene):

	if scene == 1:
		buy('alex2')
	elif scene == 2:
		print("No can do kid.")
		playerTurn('White Horse')

def scene5(scene):

	if scene == 1:
		playerTurn('bakery')
	elif scene == 2:
		playerTurn('baker')

def go(location):

    if location == 1:
        playerTurn("White Horse")
    elif location == 2:
        playerTurn("Lathos")
    elif location == 3:
        playerTurn("bakery")
    elif location == "library":
        playerTurn('library')
    elif location == "cave":
        scene9(3)

def scene6(scene):

    if scene == 1:
        SCENE = """
The baker looks at you with sad eyes,
\"Dead\", she says. \"Been dead for a long time\".
You look at her, puzzled,
\"So who rules this place?\", you ask.
\"No one, not since the fall. Go to the library, Cron will tell
you everyhing\""""

        print(SCENE)
        playerTurn('lib?')

def ask(person):

    if person == "cron":
        import random
        roll = random.randint(1, 2)
        if roll == 1:
            scene7(1)
        else:
            scene7(2)

def scene7(scene):

    if scene == 1:
        playerTurn('cron')
    elif scene == 2:
        print("Nobody knew where cron was")
        playerTurn('library')

def scene8(scene):

    if scene == "cron's story":
        STORY = """
\"Once, long time ago, this village was the heart of the world.
Busy, bustling, Lathos sold the finest purple that you would ever see.
There was a very old family, called the Strongs, had a very tempramental
son named Drastone.

Well old Drastone was always up to some trouble, when he got mad,
he took it out on others. Well, one day he got into a disagreement
with another farmer down the way. Killed the entire family and sent
a darkness over the village like a plague.

The witch doctor had a right old time clearing it all up, destroyed
Drastone's father. Then one morning, Drastone's father was dead. They
took Flaco, the old killer into custody, but they had to let him go
couldn't prove it was him.\"

Cron got an ugly look on his face.

\"I'd bet money that old Drastone hired him to do it. We'd all like to
see his head on a spit.\"

You look over at cron.

\"I can bring you Drastone.\"

Cron looked at you,

\"What's your name kid?\"

\"%s sir.\"

\"Well %s, if you do it I will pay you handsomly.\"

\"Consider it done sir.\""""

        print(STORY % (player,player))
        playerTurn('fort?')

def scene9(scene):

    global num_enemies

    if scene == 1:
        SCENE = """
You walk down the road North for hours until the sunset.
When you come to a mile marker, you decide to set up camp
with the tent Cron gave you.
"""

        print(SCENE)
        playerTurn('camp')

    elif scene == 2:
        battle('orcs', 1)
        battle('orcs', 1)
        battle('orcs', 1)
        print("You won the battle!")
        go('cave')

    elif scene == 3:
        SCENE = """
After a refreshing night of sleep, you get up and start to walk again.
Soon you come to a cave.
"""

        print(SCENE)
        playerTurn('cave')

def battle(enemy, number):
    global armor, enemy_armor, enemy_health, hd, health, inventory

    if enemy == 'orcs':
        import random
        enemy_health = 5
        enemy_armor = 5
        for i in range(number):
            enemies.insert(0, 'orc')
        player_roll = random.randint(1, hd)
        print("You rolled a %d" % (player_roll))
        checkDead('enemy', player_roll)
        enemy_roll = random.randint(1, 6)
        print("%s rolled a %s" % (enemy, enemy_roll))
        checkDead('player', enemy_roll)
        playerTurn('battle?')

    elif enemy == 'goblin':
        import random
        enemy_health = 5
        enemy_armor = 5
        for i in range(number):
            enemies.insert(0, 'goblin')
        player_roll = random.randint(1, hd)
        print("You rolled a %d" % (player_roll))
        checkDead('enemy', player_roll)
        enemy_roll = random.randint(1, 6)
        print("%s rolled a %s" % (enemy, enemy_roll))
        checkDead('player', enemy_roll)
        playerTurn('battle?')

    elif enemy == 'begger':
        import random
        enemy_health = 10
        enemy_armor = 0
        for i in range(number):
            enemies.insert(0, 'begger')
        player_roll = random.randint(1, hd)
        print("You rolled a %d" % (player_roll))
        checkDead('enemy', player_roll)
        enemy_roll = random.randint(1, 8)
        print("%s rolled a %s" % (enemy, enemy_roll))
        checkDead('player', enemy_roll)
        playerTurn('battle?')

    elif enemy == "orcs, talon":
        import random
        enemy_health = 5
        enemy_armor = 5
        for i in range(number):
            enemies.insert(0, 'orc')
        player_roll = random.randint(1, hd)
        print("You rolled a %d" % (player_roll))
        checkDead('enemy', player_roll)
        enemy_roll = random.randint(1, 6)
        print("%s rolled a %s" % (enemy, enemy_roll))
        checkDead('player', enemy_roll)
        talon_roll = random.randint(1, 10)
        print("Talon rolled a %d" % (talon_roll))
        checkDead('enemy', talon_roll)
        playerTurn('orc_slave')

def checkDead(pawn, roll):

    global enemy_health, enemy_armor, armor, health

    if pawn == 'enemy':
        if enemy_health > 0 and enemy_armor < 0 or enemy_armor == 0:
            enemy_health -= roll
            if enemy_health < 0 or enemy_health == 0:
                print("Enemy died")
        else:
            enemy_armor -= roll
    elif pawn == 'player':
        if health > 0 and armor < 0 or armor == 0:
            health -= roll
            if health < 0 or health == 0:
                print("Hero died")
                import sys
                sys.exit()
        else:
            armor -= roll

def callExit():
    import sys
    sys.exit()

def scene10(scene):

    if scene == 1:
        SCENE = """
As you walk into the cave you see a bright light coming from a hole
in the celing and water pooling on the floor underneath it. As you
walk through it three Goblins drop from the celing.
"""
        print(SCENE)
        battle('goblin', 1)
        battle('goblin', 1)
        battle('goblin', 1)
        print("You won the battle!")
        playerTurn('woods')

    elif scene == 2:
        SCENE = """
As you climb over the cave you see three goblins sitting with their
feet dangling over the edge of the hole. You just manage to escape
them.
"""

        print(SCENE)
        playerTurn('woods')

def endStory(where):

    if where == "woods":
        SCENE = """
As you walk through the woods you see a big pack of orcs. You try
to hide but it's too late. You get destroyed by a mace.
"""
        print(SCENE)
        endGame()

def endGame():
    import time
    print("Game Over.")
    time.sleep(10)
    callExit()

def scene11(scene):

    SCENE = """
As you walk down the path you come to a big canyon. So deep you
can't even see the bottom. You have to cross.
"""
    print(SCENE)
    playerTurn('canyon')

def scene12(scene):

    if scene == 1:

        SCENE = """
As you begin to climb down you slip and fall into the black...
"""
        print(SCENE)
        endGame()

    elif scene == 2:
        SCENE = """
After a night of refreshing sleep, you get up to find a begger eating
your food.
"""
        print(SCENE)
        playerTurn('beg')

def scene13(scene):

    if scene == 1:
        SCENE = """
As your raise your weapon again the begger turns into a large eagle
and flies over the caynon. As you wait for him to come back, your
food slowly runs out.
"""
        print(SCENE)
        endGame()

    elif scene == 2:
        SCENE = """
\"Hey!\" you scream. \"Get out of my food!\"
The begger jumps and turns into a big eagle and flies over the canyon.
As you wait your food slowly runs out.
"""
        print(SCENE)
        endGame()

    elif scene == 3:
        SCENE = """
\"Hey.\" you say. \"Need some food?\"
He looks at you,
\"You need a ride?\" he asks.
You look at him, suprised.
\"Yeah, can you help me?\"
\"Let's see about that meat first.\"
"""
        print(SCENE)
        playerTurn('begger')

def scene14(scene):

    if scene == 1:
        SCENE = """
As the man eats, you wait impatiently for him to help you.
Finally he tears the last of the meat off and looks at you.
\"Get on,\" he says, as he turns into a large eagle.
When you get across to the other side the man extends his hand,
\"Talon,\" he said.
\"%s,\" you say shaking his hand.
\"Right let's get moving then.\"
"""
        print(SCENE % (player))
        playerTurn('talon')

    elif scene == 2:
        if "sword" in inventory:
            SCENE = """
As you draw your sword and approach him, he turns into an eagle and
fly away. As you wait your food runs out.
"""
        else:
            SCENE = """
As you reach into your pack you realize you have no weapons.
"""
        print(SCENE)
        endGame()

def scene15(scene):

    if scene == 1:
        SCENE = """
As you begin to travel down the road on the other side, you stumble
upon a pack of orcs.
"""
        print(SCENE)
        playerTurn('orc_pack')

    elif scene == 2:
        SCENE = """
\"You can't come,\" you say. \"It will be to dangerous.\"
He looks at you sadly.
\"Too bad,\" he says suddenly knocking you over the edge.
\"I was looking forward to it.\"
"""
        print(SCENE)
        endGame()

def scene16(scene):

    if scene == 1:
        SCENE = """
As you dive behind some rocks you fall into the den of a
giant bear.
"""
        print(SCENE)
        endGame()

def goodbye():
    print("\n")
    goodbye = """
Thanks for playing The Evil Wizard!
leave feedback at venombash@gmail.com

don't miss coming soon,
The Evil Wizard II Wrath of Drastone.

Thanks for playing!
"""
    import time, sys
    print(goodbye)
    input("\n\nPress enter to exit.")
    sys.exit()

if __name__ == "__main__":
    while True:
        menu()


def main():
    n = int(input())
    _list = list(range(1,n+1))
    for x in _list:
        if x % 3 == 0 or any(list(map(lambda x: int(x) == 3, list(str(x))))):
            print(' %d' %  x, end = '')
    print()

main()


#!/usr/bin/python3
"""This script takes in a URL, sends a request to the URL and displays
    the body of the response. (Catching errors)
"""
from sys import argv
from urllib.request import Request, urlopen
from urllib.error import HTTPError

if __name__ == "__main__":
    req = Request(argv[1])
    try:
        with urlopen(req) as response:
            print(response.read().decode('utf-8'))
    except HTTPError as e:
        print("Error code: {}".format(e.code))


import cv2
import time
from calculate import *
from face import *
from faceset import *
from skeleton_detect import *
from csvfile import *

outer_id = 'yfacesy'
csvfilepath = "./faces/face_token.csv"
create_faceset(outer_id, csvfilepath)
print("初始化人脸数据集\n")
print(get_detail(outer_id))

cap = cv2.VideoCapture("./")
i = 1
testtime = 0
sign = False
while(True):
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    ret, frame = cap.read()
    if ret == False:
        break

    if i >= 40:# 40帧=1s 基础用时10s 每个功能平均5s
        time1 = time.time()
        savepath = "./data/cap.jpg"
        cv2.imwrite(savepath, frame)
        testtime += 1
        print('第%d'%testtime + '次检测')
        if sign == False:
            print("\n签到\n")
            print(is_signing(savepath, outer_id))
            sign = True
        print("\n抬头低头\n")
        print(is_pitch(savepath ,outer_id))
        print("\n玩手机\n")
        print(is_playing_phone(savepath ,outer_id))
        print("\n睡觉\n")
        print(is_sleeping(savepath ,outer_id))
        print("\n发言\n")
        print(is_standing(savepath ,outer_id))
        time2 = time.time()
        usetime = time2 - time1
        print('此次测试总共用时为%d' % usetime)
        print('\n####################################################\n')
        i = 0
        os.remove(savepath)
    else :
        i += 1

cap.release()
cv2.destroyAllWindows()

os.remove("./faces/face_token.csv")
os.remove('./faces/body_rect.csv')
result = delete_set(outer_id)
print("\n\n\nfaceset "+result['outer_id']+" 已删除")


import warnings
from typing import AnyStr, Container, Dict
import maya.cmds as cmds

def serialize_network_1(name, mask=None, warn=False):
    # type: (AnyStr, Container, bool) -> Dict
    """
    Serializes node network by traversing the dependency graph's node
    connections from a single given point.
    :param name:
        Name of the source node to start traversal from.
    :param mask:
        Masks the traversal to only contain these given nodes.
        Connections leading outside of the mask are still included.
    :param warn:
        Given warnings for excepted exceptions.
    :return:
        Table of node data, structured as such:
            {
                `nodes name`:
                {
                    "nodeType": `nodes type`,
                    "settings":
                    {
                        `plug's name`: `plug's value`,
                        ...
                    }
                    "connections":
                    {
                        `source plug`: `destination plug`,
                        ...
                    }
                },
                ...
            }
    """

    def recurse(name, _all_nodes={}):

        node = {
            'nodeType': cmds.nodeType(name),
            'settings': {},
            'connections': {}
        }

        settings = node['settings']
        for a in cmds.listAttr(name):
            try:
                settings[a] = cmds.getAttr(name + '.' + a)
            except (RuntimeError, ValueError) as e:
                if warn:
                    warnings.warn(str(e))

        connections = node['connections']
        c = cmds.listConnections(name, connections=True, plugs=True)
        if c:
            for s, d in zip(c[::2], c[1::2]):
                connections[s] = d

        _all_nodes[name] = node

        c = cmds.listConnections(name)
        if c:
            for n in c:
                if n in _all_nodes:
                    continue
                if mask and n not in mask:
                    continue
                recurse(n)

        return _all_nodes

    return recurse(name)

def serialize_network_2(nodes, on_error=None):

    nodes = cmds.ls(nodes, long=True)

    network = {}
    for node in nodes:

        data = network.setdefault(node, {
            'type': cmds.nodeType(node),
            'settings': {},
            'connections': {}
        })

        settings = data['settings']
        for a in cmds.listAttr(node):
            try:
                settings[a] = cmds.getAttr(node + '.' + a)
            except (ValueError, RuntimeError) as e:
                if on_error == 'ignore':
                    pass
                elif on_error == 'warn':
                    warnings.warn(str(e))
                elif on_error == 'raise':
                    raise e
                else:
                    raise ValueError(
                        'unrecognized value for `on_error`: ' + on_error
                    )

        connections = data['connections']
        c = cmds.listConnections(node, connections=True, plugs=True)
        if c:
            for s, d in zip(c[::2], c[1::2]):
                connections[s] = d

    return network

def serialize_network_3(root, mask=None, on_error=None):

    nodes = set()
    connections = {}
    plugs = set()
    settings = {}

    def recurse(node):

        if node in nodes:
            return None

        nodes.add(node)

        src = cmds.listConnections(node, destindation=False, plugs=True)
        dst = cmds.listConnections(node, source=False, plugs=True)
        con = src[::-1] + dst
        for s, d in zip(con[::2], con[1::2]):
            connections[s] = d
            plugs.add(s)
            plugs.add(d)

if __name__ == '__main__':

    # s = cmds.ls(selection=True)
    # x = serialize_network_1(s[0], set(s[1:]))

    from pprint import pprint
    pprint(x, indent=4)


import sqlite3

#dbName = 'example.db'

def setUpDb(dbName):
	conn = sqlite3.connect(dbName)
	c = conn.cursor()

	# Drop if existing
	c.execute("DROP TABLE IF EXISTS Checks;")

	# Create table
	c.execute('''CREATE TABLE Checks ( Id INTEGER PRIMARY KEY, Datestamp TEXT, Siteurl TEXT, Gps INTEGER );''')

	conn.close()

def writeRowToDb(dbName):
	conn = sqlite3.connect(dbName)
	c = conn.cursor()

	# Insert a row of data
	c.execute("INSERT INTO Checks ( Datestamp, Siteurl, Gps) VALUES ('2015-01-05','goteborg.se', -7 );")

	conn.commit()

	conn.close()

setUpDb("tmpTest.db")
writeRowToDb("tmpTest.db")


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

from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
import generic.search
import rights.utils

class Migration(migrations.Migration):

    dependencies = [
        ('auth', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='TruffeUser',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(default=django.utils.timezone.now, verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
                ('username', models.CharField(unique=True, max_length=255, verbose_name='Sciper ou username')),
                ('first_name', models.CharField(max_length=100, verbose_name='Pr\xe9nom', blank=True)),
                ('last_name', models.CharField(max_length=100, verbose_name='Nom de famille', blank=True)),
                ('email', models.EmailField(max_length=255, verbose_name='Adresse email')),
                ('email_perso', models.EmailField(max_length=255, null=True, verbose_name='Adresse email priv\xe9e', blank=True)),
                ('is_active', models.BooleanField(default=True, help_text='D\xe9fini si cet utilisateur doit \xeatre consid\xe9r\xe9 comme actif. D\xe9sactiver ceci au lieu de supprimer le compte.', verbose_name='Actif')),
                ('is_betatester', models.BooleanField(default=False, help_text='Rend visible les \xe9l\xe9ments en cours de d\xe9veloppement', verbose_name='Betatesteur')),
                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name="Date d'inscription")),
                ('mobile', models.CharField(max_length=25, blank=True)),
                ('adresse', models.TextField(blank=True)),
                ('nom_banque', models.CharField(help_text='Pour la poste, mets Postfinance. Sinon, mets le nom de ta banque.', max_length=128, blank=True)),
                ('iban_ou_ccp', models.CharField(help_text='Pour la poste, mets ton CCP. Sinon, mets ton IBAN', max_length=128, blank=True)),
                ('body', models.CharField(default=b'.', max_length=1)),
                ('homepage', models.TextField(null=True, blank=True)),
                ('avatar', models.ImageField(help_text='Si pas renseign\xe9, utilise la photo EPFL. Si pas de photo EPFL publique, utilise un poney.', null=True, upload_to=b'uploads/avatars/', blank=True)),
                ('groups', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Group', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.', verbose_name='groups')),
                ('user_permissions', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Permission', blank=True, help_text='Specific permissions for this user.', verbose_name='user permissions')),
            ],
            options={
                'verbose_name': 'User',
                'verbose_name_plural': 'Users',
            },
            bases=(models.Model, rights.utils.ModelWithRight, generic.search.SearchableModel),
        ),
        migrations.CreateModel(
            name='UserPrivacy',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('field', models.CharField(max_length=64, choices=[(b'mobile', 'Mobile'), (b'adresse', 'Adresse'), (b'nom_banque', 'Nom banque'), (b'iban_ou_ccp', 'IBAN ou CCP'), (b'email_perso', 'Adresse email priv\xe9e')])),
                ('level', models.CharField(max_length=64, choices=[(b'prive', 'Priv\xe9'), (b'groupe', 'Membres de mes groupes'), (b'member', 'Accr\xe9dit\xe9s AGEPoly'), (b'public', 'Public')])),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.deletion.PROTECT)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


# -*- coding: utf-8 -*-

from __future__ import print_function
from sys import hexversion

import copy
import bisect
import random
from sortedcontainers import SortedKeyList
from functools import wraps

if hexversion < 0x03000000:
    from itertools import izip as zip
    range = xrange

random.seed(0)
actions = []

def frange(start, stop, step):
    while start < stop:
        yield start
        start += step

class actor:
    def __init__(self, count):
        self._count = count
    def __call__(self, func):
        actions.extend([func] * self._count)
        return func

def not_empty(func):
    @wraps(func)
    def wrapper(slt):
        if len(slt) < 100:
            stress_update(slt)
        func(slt)
    return wrapper

@actor(1)
def stress_clear(slt):
    if random.randrange(100) < 10:
        slt.clear()
    else:
        values = list(slt)
        slt.clear()
        slt.update(values[:int(len(values) / 2)])

@actor(1)
def stress_add(slt):
    if random.randrange(100) < 10:
        slt.clear()
    slt.add(random.random())

@actor(1)
def stress_update(slt):
    slt.update((random.random() for rpt in range(350)))

@actor(1)
@not_empty
def stress_contains(slt):
    if random.randrange(100) < 10:
        slt.clear()
        assert 0 not in slt
    else:
        val = slt[random.randrange(len(slt))]
        assert val in slt
        assert 1 not in slt

@actor(1)
@not_empty
def stress_discard(slt):
    val = slt[random.randrange(len(slt))]
    slt.discard(val)

@actor(1)
def stress_discard2(slt):
    if random.randrange(100) < 10:
        slt.clear()
    slt.discard(random.random())

@actor(1)
def stress_remove(slt):
    if len(slt) > 0:
        val = slt[random.randrange(len(slt))]
        slt.remove(val)

    try:
        slt.remove(1)
        assert False
    except ValueError:
        pass

    try:
        slt.remove(-1)
        assert False
    except ValueError:
        pass

@actor(1)
@not_empty
def stress_delitem(slt):
    del slt[random.randrange(len(slt))]

@actor(1)
def stress_getitem(slt):
    if len(slt) > 0:
        pos = random.randrange(len(slt))
        assert slt[pos] == list(slt)[pos]

        try:
            slt[-(slt._len + 5)]
            assert False
        except IndexError:
            pass

        try:
            slt[slt._len + 5]
            assert False
        except IndexError:
            pass
    else:
        try:
            slt[0]
            assert False
        except IndexError:
            pass

@actor(1)
@not_empty
def stress_delitem_slice(slt):
    start, stop = sorted(random.randrange(len(slt)) for rpt in range(2))
    step = random.choice([-3, -2, -1, 1, 1, 1, 1, 1, 2, 3])
    del slt[start:stop:step]

@actor(1)
def stress_iter(slt):
    itr1 = iter(slt)
    itr2 = (slt[pos] for pos in range(len(slt)))
    assert all(tup[0] == tup[1] for tup in zip(itr1, itr2))

@actor(1)
def stress_reversed(slt):
    itr = reversed(list(reversed(slt)))
    assert all(tup[0] == tup[1] for tup in zip(slt, itr))

@actor(1)
def stress_bisect_left(slt):
    values = list(slt)
    value = random.random()
    values.sort()
    assert bisect.bisect_left(values, value) == slt.bisect_left(value)

@actor(1)
def stress_bisect(slt):
    values = list(slt)
    value = random.random()
    values.sort()
    assert bisect.bisect(values, value) == slt.bisect(value)

@actor(1)
def stress_bisect_right(slt):
    values = list(slt)
    value = random.random()
    values.sort()
    assert bisect.bisect_right(values, value) == slt.bisect_right(value)

@actor(1)
@not_empty
def stress_dups(slt):
    pos = min(random.randrange(len(slt)), 300)
    val = slt[pos]
    for rpt in range(pos):
        slt.add(val)

@actor(1)
@not_empty
def stress_count(slt):
    values = list(slt)
    val = slt[random.randrange(len(slt))]
    assert slt.count(val) == values.count(val)

@actor(1)
@not_empty
def stress_pop(slt):
    pos = random.randrange(len(slt)) + 1
    assert slt[-pos] == slt.pop(-pos)

@actor(1)
@not_empty
def stress_index(slt):
    values = set(slt)
    slt.clear()
    slt.update(values)
    pos = random.randrange(len(slt))
    assert slt.index(slt[pos]) == pos

@actor(1)
@not_empty
def stress_index2(slt):
    values = list(slt)[:3] * 200
    slt = SortedKeyList(values)
    for idx, val in enumerate(slt):
        assert slt.index(val, idx) == idx

@actor(1)
def stress_mul(slt):
    values = list(slt)
    mult = random.randrange(10)
    values *= mult
    values.sort()
    assert (slt * mult) == values

@actor(1)
def stress_imul(slt):
    mult = random.randrange(10)
    slt *= mult

@actor(1)
@not_empty
def stress_reversed(slt):
    itr = reversed(slt)
    pos = random.randrange(1, len(slt))
    for rpt in range(pos):
        val = next(itr)
    assert val == slt[-pos]

@actor(1)
@not_empty
def stress_eq(slt):
    values = []
    assert not (values == slt)

@actor(1)
@not_empty
def stress_lt(slt):
    values = list(slt)
    assert not (values < slt)
    values = SortedKeyList(value - 1 for value in values)
    assert values < slt
    values = []
    assert values < slt
    assert not (slt < values)

def test_stress(repeat=1000):
    slt = SortedKeyList((random.random() for rpt in range(1000)))

    for rpt in range(repeat):
        action = random.choice(actions)
        action(slt)

        slt._check()

        while len(slt) > 2000:
            # Shorten the sortedlist. This maintains the "jaggedness"
            # of the sublists which helps coverage.
            pos = random.randrange(len(slt._maxes))
            del slt._maxes[pos]
            del slt._keys[pos]
            del slt._lists[pos]
            slt._len = sum(len(sublist) for sublist in slt._lists)
            slt._index = []
            slt._check()

    slt._check()

    stress_update(slt)

    while len(slt) > 0:
        pos = random.randrange(len(slt))
        del slt[pos]

    slt._check()

if __name__ == '__main__':
    import sys
    from datetime import datetime

    start = datetime.now()

    print('Python', sys.version_info)

    try:
        num = int(sys.argv[1])
        print('Setting iterations to', num)
    except:
        print('Setting iterations to 1000 (default)')
        num = 1000

    try:
        pea = int(sys.argv[2])
        random.seed(pea)
        print('Setting seed to', pea)
    except:
        print('Setting seed to 0 (default)')
        random.seed(0)

    try:
        test_stress(num)
    except:
        raise
    finally:
        print('Exiting after', (datetime.now() - start))


import falcon
import json
import sys
import codecs
import urllib
import html
#from BeautifulSoup import BeautifulSoup

sys.path.insert(0, '/home/puru/Documents/d/arithmetic/code/api/solver')
import SI

class ThingsResource(object):
    def on_get(self, req, resp,filename):
        """Handles GET requests"""
        resp.status = falcon.HTTP_200
        resp.content_type = 'text/html'
        with open(filename, 'r') as f:
            resp.body = f.read()

class Starting(object):
	#def on_get(self, req, resp):
	#	p = ('\nTwo things awe me most, the starry sky '
    #                 'above me and the moral law within me.\n'
    #                 '\n'
    #                 '    ~ Immanuel Kant\n\n')
	#	print("p")

    def on_post(self,req,resp):
        print("get it")
        data=req.stream.read()
        data=data.decode()
        data=urllib.parse.unquote(data)
        data=urllib.parse.parse_qs(data)
        print(data["question"][0])
        answer=SI.main(data["question"][0])
        answer=str(answer)
        print(answer)
        d={}
        d["answer"]=answer

        resp.body = json.dumps(d, ensure_ascii=False)
        resp.status = falcon.HTTP_200

        #html_decoded_string = BeautifulSoup(data, convertEntities=BeautifulSoup.HTML_ENTITIES)
        #print(html_decoded_string)
        #da.read()
        #print(da)

	#def on_post(self,req,resp):
    #    print(req.stream)
		#reader = codecs.getreader("utf-8")
		#obj = json.loads(reader(req.stream))
		#resp.status = falcon.HTTP_201
        #resp.location = '/things/' + name

app = falcon.API()
things = ThingsResource()
thi = Starting()

app.add_route('/things/{filename}', things)
app.add_route('/things',thi)


class SaleReportFormPurposeTypes:
    OPEN_NEW = 0
    IMPLEMENT = 1
    CARE = 2

    CHOICES = (
        (OPEN_NEW, 'Mở mới'),
        (IMPLEMENT, 'Triển khai'),
        (CARE, 'Chăm sóc'),
    )

class SaleReportFormCreateNewResults:
    CONTRACT_OK = 0
    CONTRACT_NOT_OK = 1
    CONSIDER_FURTHER = 2
    REJECT = 3

    CHOICES = (
        (CONTRACT_OK, 'Dong y, da ky duoc HD'),
        (CONTRACT_NOT_OK, 'Dong y, chua ky duoc HD'),
        (CONSIDER_FURTHER, 'Can xem xet them'),
        (REJECT, 'Tu choi hop tac'),
    )

class SaleReportFormNewUsingApplications:

    CHOICES = (
        ('iPos', 'iPos'),
        ('Sapo', 'Sapo'),
        ('KiotViet', 'KiotViet'),
        ('POS365', 'POS365'),
        ('Cukcuk', 'Cukcuk'),
        ('Ocha', 'Ocha'),
        ('PM khác', 'PM khác'),
        ('Chưa sử dụng', 'Chưa sử dụng'),
    )

class SaleReportFormShopStatus:
    CLOSED = 0
    LIQUIDATION_QR = 1
    ACTIVE = 2
    UNCOOPERATIVE = 3
    CHANGED_LOCATION = 4

    CHOICES = (
        (CLOSED, 'Da nghi kinh doanh/ khong co cua hang thuc te'),
        (LIQUIDATION_QR, 'Muon thanh ly QR'),
        (ACTIVE, 'Dang hoat dong'),
        (UNCOOPERATIVE, 'Không hợp tác'),
        (CHANGED_LOCATION, 'Da chuyen dia diem'),
    )

class SaleReportFormShopConfirm:
    CORRECT_ADDRESS = 0
    INCORRECT_ADDRESS = 1
    NOT_FOUND = 2

    CHOICES = (
        (CORRECT_ADDRESS, 'Cua hang dung dia chi'),
        (INCORRECT_ADDRESS, 'Cua hang sai dia chi/ da chuyen dia diem'),
        (NOT_FOUND, 'Khong tim duoc cua hang'),
    )

class SaleReportFormCashierReward:
    NO = 0
    YES = 1

    CHOICES = (
        (NO, 'Không'),
        (YES, 'Có'),
    )


from threading import Thread
import threading
import time

basket=0

lock=threading.Lock()

class Cook(Thread):
    chefname=''
    count=0

    def run(self) -> None:
        global  basket

        while 1:

            if basket>=500:
                time.sleep(10)

                    #break
            else:
                with lock:
                    basket = basket + 1
                    self.count = self.count + 1
                    print(self.chefname, '共做了', self.count, '个', sep='')

class Customer(Thread):
    name=''
    num=3000
    def run(self) -> None:
        global num
        global basket

        while 1 :
            if basket>0:
                with lock:
                    basket=basket-1
                    self.num=self.num-2
                    print(self.name,'买了一个！')
                    time.sleep(2)
            if self.num==0:
                    print(self.name,'买完了！',sep='')
                    break
            else:
                time.sleep(2)

cook1=Cook()
cook1.chefname='张三'
cook2=Cook()
cook2.chefname='李四'
cook3=Cook()
cook3.chefname='王五'
customer1=Customer()
customer1.name='1'
customer2=Customer()
customer2.name='2'

customer3=Customer()
customer3.name='3'
customer4=Customer()
customer4.name='4'
customer5=Customer()
customer5.name=5
customer6=Customer()
customer6.name='6'
cook1.start()
cook2.start()
cook3.start()
customer1.start()
customer2.start()
customer3.start()
customer4.start()
customer5.start()
customer6.start()


# Sub-class for linked list
class node:
    def __init__(self,data=None):
        self.data = data
        self.next = None

class linked_list:
    # start with head node, which contains no data.
    def __init__(self):
        self.head = node()

        # Node Adder
    def append(self,data):
        # instantiate the next node with node class data object
        next_node = node(data)
        # insertion is from left to right, which means we start with head node (no data)
        current_node = self.head
        # while the node in question is not the head node or tail node:
        # current_node inherits the 'next' node object in the node class
        # current_node.next is defined as the 'next' node.
        while current_node.next != None:
            current_node = current_node.next
        current_node.next = next_node

        # Utility Function to Calculate Length of Linked List
    def length(self):
        current_node = self.head
        # counter for visited indices
        visited_index = 0
        while current_node.next != None:
             visited_index +=1
             current_node = current_node.next
        return visited_index

    def display(self):
        elements_seen = []
        current_node = self.head
        while current_node.next != None:
            current_node = current_node.next
            elements_seen.append(current_node.data)
        print (elements_seen)

    def search_by_index(self,x):
        if x >= self.length():
            print('the index you are fetching exceeds length of the linked list')
            return None

        current_node = self.head
        current_index = 0

        while True:
            current_node = current_node.next
            if current_index == x:
                return print(current_node.data)
            current_index +=1
        return print(current_node.data)

    def search_by_value(self,value):
        current_node = self.head
        current_index = 0
        if current_index>= self.length():
            print('the index you are fetching exceeds length of hte linked list')
            return None

        while True:
            current_node = current_node.next
            if current_node.data == value:
                return print(current_node.data)
        current_index +=1

    def delete_by_index(self,x):
        if x>= self.length():
            print('the index you are fetching exceeds length of the linked list')
            return None

        current_node = self.head
        target_index = 0

        while True:
            last_node = current_node
            current_node = current_node.next
            if target_index == x:
                return last_node.next == current_node.next
            target_index +=1

# Testing the linked list
test_linked_list = linked_list()
test_linked_list.append(1)
test_linked_list.append(2)
test_linked_list.append(3)
test_linked_list.append(4)
test_linked_list.append(5)
test_linked_list.append(5)
test_linked_list.append(10)
test_linked_list.append(20)
test_linked_list.append(121)
test_linked_list.append(87)
test_linked_list.append(64)
test_linked_list.append(11)
test_linked_list.append(27)

test_linked_list.display()
test_linked_list.search_by_index(7)
test_linked_list.search_by_value(20)
print('The length of the linked list is =',test_linked_list.length())


# -*- coding: utf-8 -*-

from parameters import *

class Values(object):
    def __init__(self):
        self.val = []

    def update(self, v):
        tmp = self.val
        if len(tmp) > CONTROL_LISTSIZE:
            tmp = [v]
        else:
            tmp.append(v)
        self.val = tmp


from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager

from .db_config import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_TRACK_MODIFICATIONS, SECRET_KEY

def db_init(app):
    app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
    app.config['DATABASE_URL'] = SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = SQLALCHEMY_TRACK_MODIFICATIONS
    app.config['SECRET_KEY'] = SECRET_KEY

    db = SQLAlchemy(app)
    migrate = Migrate()

    return db

def jwt_init(app):
    jwt_manager = JWTManager(app)

    @jwt_manager.invalid_token_loader  # merge two functions into one?
    def get_invalid_token_response(invalid_token):
        token_type = invalid_token['type']
        return {
            'status': 401,
            'sub_status': 42,
            'msg': 'The {} token has expired'.format(token_type)
        }, 401

    @jwt_manager.expired_token_loader
    def get_token_expired_response(expired_token):
        token_type = expired_token['type']
        return {
            'status': 401,
            'sub_status': 42,
            'msg': 'The {} token has expired'.format(token_type)
        }, 401

    return jwt_manager


import re
import sys
from functions import *

def settings(s):
    regex = "\n[\s]+[-][\S]+[\s]+[-][-]([\S]+)[^\n]+= ([\S]+)"
    mo = re.findall(regex, s)
    d = dict(mo)
    return d

def cli(options):
    args = sys.argv[1:]
    for k, v in options.items():
        v = str(v)
        for n, x in enumerate(args):
            if x == '-' + k[0] or x == '--' + k:
                if v == 'false':
                    v = 'true'
                elif v == 'true':
                    v = 'false'
                else:
                    v = args[n + 1]
            options[k] = coerce(v)
    return options


# Start out with some users that need to be verified,
#  and an empty list to hold confirmed users.
potential_users = ['alice', 'jonathan', 'charlie', 'sandra', 'brian', 'hank',
                   'paula', 'michael', 'candace']
unconfirmed_users = []
confirmed_users = []
still_alive_users = []

# Verify each user, until there are no more potential users.
#  Move each verified user into the list of confirmed users.
#  Move each unconfirmed user into the list of unconfirmed users.
#  Move users that are neither confirmed or unconfirmed into still alive users.
while potential_users:
    for potential_user in potential_users:
        current_user = potential_users.pop()
        check = input("\nHas " + current_user.title() +
                      " been confirmed? (Please enter yes or no.): ")
        check = check.lower()
        if check == "no":
            unconfirmed_users.append(current_user)
        elif check == "yes":
            print("Verifying user: " + current_user.title())
            confirmed_users.append(current_user)
        else:
            print("You did not enter yes or no for " +
                  current_user.title() + ".")
            still_alive_users.append(current_user)

# Display all unconfirmed users in alphabetical order.
print("\nThe following users are still unconfirmed:")
for unconfirmed_user in sorted(unconfirmed_users):
    print(unconfirmed_user.title())

# Display all confirmed users in alphabetical order.
print("\nThe following users have been confirmed:")
for confirmed_user in sorted(confirmed_users):
    print(confirmed_user.title())

# Display user that are neither confirmed or unconfirmed in alphabetical order.
print("\nThe following users are neither confirmed or unconfirmed:")
for still_alive_user in sorted(still_alive_users):
    print(still_alive_user.title())


import common_config

from telegram.ext import Updater, CommandHandler

REQUEST_KWARGS = {
    'proxy_url': common_config.PROXY,
}

def start_message(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text='Приветули')

def main():
    updater = Updater(common_config.TOCKEN_TELEBOT, request_kwargs=REQUEST_KWARGS)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('start', start_message))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()


#!/usr/bin/env python3.7
# Copyright: Ismael Narváez Berenjeno
import asyncio
from unittest.mock import MagicMock, patch
import pytest
from async_redis_connection.connector.database.async_redis_connection import AsynRedisConnection
from async_redis_connection.data_model.async_redis_params import AsyncRedisParams
from async_redis_connection.util.logger import logger

test_key = "key"
test_value = {"key": "test:0001", "value": "test"}
test_value_updated = {"key": "test:0001", "value": "test-updated"}
async_redis_params = AsyncRedisParams(address="", database=0)

@pytest.mark.asyncio
async def test_flow_async_redis_connection_database_mode():
    """Test async redis connection class."""
    with patch("async_redis_connection.connector.database.async_redis_connection.create_redis_pool") as mock_redis_connection:
        aioredis_calls_mock = MagicMock()
        asyncio_future = asyncio.Future()
        asyncio_future.set_result(aioredis_calls_mock)
        mock_redis_connection.return_value = asyncio_future
        connection = AsynRedisConnection(async_redis_params, logger=logger)
        await connection.create(test_key, test_value)
        assert len(aioredis_calls_mock.mock_calls) == 2
        await connection.read(test_key, test_value)
        assert len(aioredis_calls_mock.mock_calls) == 3
        await connection.update(test_key, test_value_updated)
        assert len(aioredis_calls_mock.mock_calls) == 4
        await connection.read(test_key, test_value_updated)
        assert len(aioredis_calls_mock.mock_calls) == 5
        await connection.delete(test_key, test_value_updated)
        assert len(aioredis_calls_mock.mock_calls) == 6
        await connection.read(test_key, test_value_updated)
        assert len(aioredis_calls_mock.mock_calls) == 7


import re
from datetime import datetime, timezone

def clean_cust_no(cust_no: str, cust_no_pattern: str, cust_no_int_fixes: list[tuple]) -> str:
    # Remove characters other than alphanumerical
    cust_no = re.search(pattern=cust_no_pattern, string=cust_no).group(0)
    # Fix customer's number int part char misspellings
    for pair in cust_no_int_fixes:
        cust_no = f"{cust_no[0]}{cust_no[1:].replace(pair[0], pair[1])}"
    return cust_no

def format_date_to_utc(input_date: str, datetime_format: str) -> str:
    input_date = datetime.strptime(input_date, datetime_format).replace(tzinfo=timezone.utc)
    return input_date.isoformat()

def convert_data_to_string(data: list) -> str:
    str_data = str()
    for row in data:
        current_row = '\t'.join(row) + '\n'
        str_data += current_row
    return str_data

def convert_data_to_html(columns: list, content: list) -> str:
    html_header = '<!DOCTYPE html>\n\n\n\n\n
'
    html_footer = '
\n\n'
    # Build table header
    table_columns = '
\n'
    for column in columns:
        table_columns += f'{column}	\n'
    table_columns += '
\n'
    # Build table body
    table_rows = str()
    for row in content:
        current_row = '
\n'
        for element in row:
            current_row += f'{element}	\n'
        current_row += '
\n'
        table_rows += current_row

    html_data = f'{html_header}{table_columns}{table_rows}{html_footer}'
    return html_data


import json
import logging

from string import Template
from flask_restful import Resource
from flask import jsonify
from accessors.s3_accessor import S3Accessor
from resource_helpers.abort_logger import AbortLogger

MESSAGE_500 = Template("File failed to download: $error")

class GeneListReturn(Resource):
    def __init__(self):
        self.logger = logging.getLogger(__name__)

    def get(self):

        download_file_url = ""
        file_path = "variant.txt"
        path = ""

        # --------------download file from s3--------------
        try:
            download_file_url = S3Accessor().get_download_url(file_path)

        except Exception as e:
            AbortLogger.log_and_abort(500, self.logger.error, MESSAGE_500.substitute(error=e))

        try:
            if download_file_url != "":
                path = S3Accessor().download(file_path)
        except Exception as e:
            AbortLogger.log_and_abort(500, self.logger.error, MESSAGE_500.substitute(error=e))

        return jsonify({
            "keys": json.loads(open(path).read()).keys(),
        })


class Order:
    def __init__(self, orderNumber = 1, orderName = "", orderPrice = 0,
            pickupTime = None, statusCode = "", bowls = [], appetizers = [], payment = None):
        self.orderNumber = orderNumber
        self.orderName = orderName
        self.orderPrice = orderPrice
        self.pickupTime = pickupTime
        self.statusCode = statusCode
        self.bowls = bowls
        self.appetizers = appetizers
        self.payment = payment

    def getStatusCode(status):
        if status == "waiting":
            return 0
        elif status == "readForPickup":
            return 1
        elif status == "completed":
            return 2
        elif status == "canceled":
            return 3
        else:
            return 3

class Bowl:
    def __init__(self, bowlNumber = 0, orderNumber = 0, bowlPrice = 0,
            size = "", riceType = 0, sauceType = 0, ingredients = []):
        self.bowlNumber = bowlNumber
        self.orderNumber = orderNumber
        self.bowlPrice = bowlPrice
        self.size = size
        self.riceType = riceType
        self.sauceType = sauceType
        self.ingredients = ingredients

    def getSizeNumber(self):
        if self.size == "small":
            return 0
        elif self.size == "medium":
            return 1
        elif self.size == "large":
            return 2
        else:
            return 3

class RiceType:
	def __init__(self, id = 0, name = "", upcharge = 0, available = True):
		self.id = id
		self.name = name
		self.upcharge = upcharge
		self.available = available

class IngredientType:
	def __init__(self, id = 0, name = "", upcharge = 0, ratio = 1, available = True):
		self.id = id
		self.name = name
		self.upcharge = upcharge
		self.ratio = ratio
		self.available = available

class SauceType:
	def __init__(self, id = 0, name = "", upcharge = 0, available = True):
		self.id = id
		self.name = name
		self.upcharge = upcharge
		self.available = available

class AppetizerType:
	def __init__(self, id = 0, appetizerName = "", price = 0):
		self.id = id
		self.appetizerName = appetizerName
		self.price = price

class Payment:
	def __init__(self, paymentType = "", cardInfo = None):
		self.paymentType = paymentType
		self.cardInfo = cardInfo

class CardInfo:
	def __init__(self, firstName = "", lastName = "", address = "", cardNumber = "",
			ccv = "", zipCode = ""):
		self.firstName = firstName
		self.lastName = lastName
		self.address = address
		self.cardNumber = cardNumber
		self.ccv = ccv
		self.zipCode = zipCode


# -*- coding: utf-8 -*-
"""
Created on Tue Nov 15 10:17:32 2016

@author: alec
"""

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import numpy as np
import cwesr_fit_single as cwesr

font = {'family' : 'Arial',
        'weight' : 'normal',
        'size'   : 15}

matplotlib.rc('font', **font)

#material parameters
pi = np.pi

#file constants

basepath = '/Users/alec/UCSB/calibration_data/tacofeb_nv_angle/anglecal'
num_avg = 10
filenum = 2

data = np.loadtxt(basepath+str(filenum).zfill(6)+'_'+str(num_avg)+'.txt', skiprows=1)[:,0:3:2]

edata = np.transpose(data)
#print(edata)
x, y = edata

cwresult = cwesr.cwesr_fit(x,y,gauss=False,gamp=2.5e4)
popt = cwresult[0]
pcov = cwresult[1]
perr = np.sqrt(np.diag(pcov))
fit = cwresult[2]
fitg = cwresult[3]
dips = cwresult[4]

plt.close('all')

plt.figure(1,[8,6])

plt.plot(x,y,color='#ED1035',marker='.',label="data")
plt.plot(x,fit,color='#97CC04',linewidth=2.0)
#plt.plot(x,fitg,color='#2D7DD2',linewidth=2.0)
#plt.plot(dips[0][0],dips[1][0],'b.')
#plt.plot(dips[0][1],dips[1][1],'b.')

plt.xlabel(r'$freq \quad (MHz)$')
plt.ylabel(r'$NV \quad PL \quad (counts)$')
plt.tight_layout()
#pylab.savefig('/Users/alec/UCSB/scan_data/images/linecut_lrgunc_'+str(filenum)+'.pdf')

fig = plt.gcf()
fig.canvas.manager.window.raise_()

#print(popt)
bnv = (popt[4]-popt[1])/(2*2.8)
bz = 12.0
print(180*np.arccos(bnv/bz)/np.pi)


from .uc480_lib import lib, UC480LibError, errcheck

from ...core.devio.interface import IDevice
from ...core.utils import py3, general
from ...core.dataproc import image as image_utils

_depends_local=[".uc480_lib","...core.devio.interface"]

import numpy as np
import collections
import contextlib
import ctypes
import time

class UC480Error(RuntimeError):
    "Generic uc480 camera error."
class UC480TimeoutError(UC480Error):
    "Timeout while waiting."

def get_cameras_number():
    """Get number of connected uc480 cameras"""
    lib.initlib()
    return lib.is_GetNumberOfCameras()

def get_cameras_list():
    """Get list of connected uc480 cameras"""
    lib.initlib()
    return lib.is_GetCameraList()

class UC480Camera(IDevice):
    """
    Thorlabs uc480 camera.

    Args:
        idx(int): camera ID; use 0 to get the first available camera
        roi_binning_mode: determines whether binning in ROI refers to binning or subsampling;
            can be ``"bin"``, ``"subsample"``, or ``"auto"`` (since most cameras only support one, it will pick the one which has non-trivial value, or ``"bin"`` if both are available).
    """
    def __init__(self, id=0, roi_binning_mode="auto"):
        IDevice.__init__(self)
        lib.initlib()
        self.cam_id=id
        self.hcam=None
        self._buffers=None
        self._next_read_buffer=0
        self._default_nframes=100
        self._acq_params=(False,None)
        self._last_wait_frame=0
        self.image_indexing="rct"
        self.open()
        self._all_color_modes=self._check_all_color_modes()
        self._set_auto_mono_color_mode()
        if roi_binning_mode=="auto":
            if self.get_supported_binning_modes()==([1],[1]):
                roi_binning_mode="subsample"
            else:
                roi_binning_mode="bin"
        self._roi_binning_mode=roi_binning_mode

        self._add_full_info_node("model_data",self.get_model_data)
        self._add_settings_node("subsampling",self.get_subsampling,self.set_subsampling)
        self._add_full_info_node("subsampling_modes",self.get_supported_subsampling_modes)
        self._add_settings_node("binning",self.get_binning,self.set_binning)
        self._add_full_info_node("binning_modes",self.get_supported_binning_modes)
        self._add_settings_node("roi",self.get_roi,self.set_roi)
        self._add_settings_node("pixel_rate",self.get_pixel_rate,self.set_pixel_rate)
        self._add_settings_node("frame_time",self.get_frame_time,self.set_frame_time)
        self._add_settings_node("exposure",self.get_exposure,self.set_exposure)
        self._add_full_info_node("max_gains",self.get_max_gains)
        self._add_settings_node("gains",self.get_gains,self.set_gains)
        self._add_settings_node("gain_boost",self.get_gain_boost,self.set_gain_boost)
        self._add_status_node("timings",self.get_timings)
        self._add_status_node("buffer_size",self.get_buffer_size)
        self._add_status_node("buffer_status",self.get_buffer_status)
        self._add_status_node("data_dimensions",self.get_data_dimensions)
        self._add_full_info_node("pixel_rates_range",self.get_pixel_rates_range)
        self._add_full_info_node("all_color_modes",self.get_all_color_modes)
        self._add_settings_node("color_mode",self.get_color_mode,self.set_color_mode)
        self._add_full_info_node("detector_size",self.get_detector_size)
        self._add_status_node("roi_limits",self.get_roi_limits)
        self._add_status_node("acq_status",self.get_acquisition_status)
        self._add_status_node("acq_in_progress",self.acquisition_in_progress)

    def open(self):
        """Open connection to the camera"""
        if self.hcam is None:
            self.hcam=lib.is_InitCamera(None,self.cam_id)
    def close(self):
        """Close connection to the camera"""
        if self.hcam is not None:
            lib.is_ExitCamera(self.hcam)
            self.hcam=None
        self.hcam=None
    def is_opened(self):
        """Check if the device is connected"""
        return self.hcam is not None

    ModelData=collections.namedtuple("ModelData",["model","manufacturer","serial_number","usb_version","date","dll_version","camera_type"])
    def get_model_data(self):
        """
        Get camera model data.

        Return tuple ``(model, manufacturer, serial_number, usb_version, date, dll_version, camera_type)``.
        """
        sen_info=self._get_sensor_info()
        cam_info=lib.is_GetCameraInfo(self.hcam)
        dll_ver=lib.is_GetDLLVersion()
        dll_ver="{}.{}.{}".format((dll_ver>>24),(dll_ver>>16)&0xFF,dll_ver&0xFFFF)
        return self.ModelData(py3.as_str(sen_info.strSensorName),py3.as_str(cam_info.ID),py3.as_str(cam_info.SerNo),py3.as_str(cam_info.Version),
            py3.as_str(cam_info.Date),dll_ver,cam_info.Type)
    def _get_sensor_info(self):
        return lib.is_GetSensorInfo(self.hcam)

    ### Buffer controls ###
    def _allocate_buffers(self, n):
        self._deallocate_buffers()
        frame_size=self._get_data_dimensions_rc()[::-1]
        bpp=self._get_pixel_mode_settings()[0]
        self._buffers=[]
        for _ in range(n):
            self._buffers.append(lib.is_AllocImageMem(1,frame_size[0],frame_size[1],bpp))
            lib.is_AddToSequence(self.hcam,*self._buffers[-1])
        self._next_read_buffer=0
        return n
    def _deallocate_buffers(self):
        if self._buffers is not None:
            lib.is_ClearSequence(self.hcam)
            for b in self._buffers:
                lib.is_FreeImageMem(self.hcam,*b)
            self._buffers=None

    def _read_buffer(self, n):
        buff=self._buffers[n%len(self._buffers)]
        frame_info=lib.is_GetImageInfo(self.hcam,buff[1])
        bpp,nchan=self._get_pixel_mode_settings()
        shape=(frame_info.dwImageHeight,frame_info.dwImageWidth)+((nchan,) if nchan>1 else ())
        frame=np.empty(shape=shape,dtype=self._np_dtypes[bpp//nchan])
        lib.is_CopyImageMem(self.hcam,buff[0],buff[1],frame.ctypes.data)
        return frame,frame_info

    def get_buffer_size(self):
        """Get number of frames in the ring buffer"""
        return len(self._buffers) if self._buffers is not None else 0
    TBufferStatus=collections.namedtuple("TBufferStatus",["unread","size"])
    def get_buffer_status(self):
        unread=self._get_unread_images()
        size=self.get_buffer_size()
        return self.TBufferStatus(unread,size)
    TAcqusitionStatus=collections.namedtuple("TAcqusitionStatus",["acquired","last_read","transfer_missed"])
    def get_acquisition_status(self):
        acquired=lib.is_CameraStatus(self.hcam,2,0x8000)
        last_read=self._next_read_buffer
        cstat=lib.is_GetCaptureStatus(self.hcam).adwCapStatusCnt_Detail
        transfer_missed=sum([cstat[i] for i in [0xa2,0xa3,0xb2,0xc7]])
        return self.TAcqusitionStatus(acquired,last_read,transfer_missed)
    def _get_unread_images(self):
        acq_status=self.get_acquisition_status()
        return acq_status.acquired-acq_status.last_read

    ### Generic controls ###
    AcqTimes=collections.namedtuple("AcqTimes",["exposure","frame_time"])
    def get_timings(self):
        """
        Get acquisition timing.

        Return tuple ``(exposure, frame_time)``.
        """
        exp=lib.is_Exposure_d8(self.hcam,7)*1E-3
        frame_rate=lib.is_SetFrameRate(self.hcam,0x8000)
        return self.AcqTimes(exp,1./frame_rate)
    def set_exposure(self, exposure):
        """Set camera exposure"""
        exposure=lib.is_Exposure_d8(self.hcam,12,exposure*1E3)
        return exposure*1E-3
    def get_exposure(self):
        """Get current exposure"""
        return lib.is_Exposure_d8(self.hcam,7)*1E-3
    def set_frame_time(self, frame_time):
        """
        Set frame time (frame acquisition period).

        If the time can't be achieved and ``adjust_exposure==True``, try to adjust the exposure to get the desired frame time;
        otherwise, keep the exposure the same.
        """
        ftr=lib.is_GetFrameTimeRange(self.hcam)
        frame_time=min(max(frame_time,ftr[0]),ftr[1])
        lib.is_SetFrameRate(self.hcam,1./frame_time)
        return self.get_frame_time()
    def get_frame_time(self):
        """Get current frame time (frame acquisition period)"""
        return self.get_timings().frame_time
    def get_pixel_rate(self):
        """Get camera pixel rate (in Hz)"""
        return lib.is_PixelClock_dt(self.hcam,5,ctypes.c_uint).value*1E6
    def get_available_pixel_rates(self):
        """Get all available pixel rates (in Hz)"""
        nrates=lib.is_PixelClock_dt(self.hcam,1,ctypes.c_uint).value
        rates=lib.is_PixelClock_dt(self.hcam,2,ctypes.c_uint*nrates)[:]
        return sorted([r*1E6 for r in rates])
    def get_pixel_rates_range(self):
        """
        Get range of allowed pixel rates (in Hz).

        Return tuple ``(min, max, step)`` if minimal and maximal value, and a step.
        """
        rng=lib.is_PixelClock_dt(self.hcam,3,ctypes.c_uint*3)[:]
        return tuple([v*1E6 for v in rng])
    def set_pixel_rate(self, rate=None):
        """
        Set camera pixel rate (in Hz)

        The rate is always rounded to the closest available.
        If `rate` is ``None``, set the maximal possible rate.
        """
        rates=self.get_available_pixel_rates()
        if rate is None:
            rate=rates[-1]
        else:
            rate=sorted(rates,key=lambda r: abs(r-rate))[0]
        lib.is_PixelClock_dt(self.hcam,6,ctypes.c_uint,int(np.round(rate/1E6)))
        return self.get_pixel_rate()

    _color_modes={"raw8":11, "raw10":33, "raw12":27, "raw16":29, "mono8":6, "mono10":34, "mono12":26,"mono16":28,
                "bgr5p":3, "bgr565p":2, "rgb8p":129, "bgr8p":1, "rgba8p":128, "bgra8p":0, "rgby8p":152, "bgry8p":24,
                "rgb10p":153, "bgr10p":25, "rgb10up":163, "bgr10up":35, "rgb12up":158, "bgr12up":30, "rgba12up":159, "bgra12up":31,
                "jpeg":32, "uyuvp":12, "uyvy_monop":13, "uyuv_bayerp":14, "cbycryp":23}
    _color_modes_inv=general.invert_dict(_color_modes)
    def _check_all_color_modes(self):
        names=[]
        m0=lib.is_SetColorMode(self.hcam,0x8000)
        for n,m in self._color_modes.items():
            try:
                lib.is_SetColorMode(self.hcam,m)
                nm=lib.is_SetColorMode(self.hcam,0x8000)
                if m==nm:
                    names.append(n)
            except UC480LibError as err:
                if err.code!=174: # invalid color mode
                    raise
        lib.is_SetColorMode(self.hcam,m0)
        return names
    def get_all_color_modes(self):
        """Get a list of all available color modes"""
        return self._all_color_modes
    def get_color_mode(self):
        """
        Get current color mode.

        For possible modes, see :meth:`get_all_color_modes`.
        """
        mode=lib.is_SetColorMode(self.hcam,0x8000)
        return self._color_modes_inv.get(mode,mode)
    def set_color_mode(self, mode):
        """
        Set current color mode.

        For possible modes, see :meth:`get_all_color_modes`.
        """
        mode=self._color_modes.get(mode,mode)
        res=lib.is_SetColorMode(self.hcam,mode)
        errcheck()(res,lib.is_SetColorMode,None)
        return self.get_color_mode()
    def _set_auto_mono_color_mode(self):
        """Set color mode to the most appropriate mono setting, if the sensor is mono"""
        si=self._get_sensor_info()
        if si.nColorMode==1: # monochrome
            for mode in ["mono16","mono8"]:
                try:
                    self.set_color_mode(mode)
                    return
                except UC480LibError as err:
                    if err.code!=174: # invalid color mode
                        raise
    _mode_bpps=     {11:8, 33:16, 27:16, 29:16, 6:8, 34:16, 26:16, 28:16, 3:16, 2:16, 1:24, 0:32, 24:32, 25:32, 35:48, 30:48, 31:64, 12:16, 13:16, 14:16, 23:16}
    _mode_channels= {11:1, 33:1 , 27:1 , 29:1 , 6:1, 34:1 , 26:1 , 28:1 , 3:1 , 2:1 , 1:3 , 0:4 , 24:4 , 25:1 , 35:3 , 30:3 , 31:4 , 12:2 , 13:2 , 14:2 , 23:2 }
    def _get_pixel_mode_settings(self, mode=None):
        """.
        Get pixel mode settings (bits per pixel and channels per pixel)

        Packed modes are assumed to be one-channel (i.e., no unpacking is done).
        """
        if mode is None:
            mode=self.get_color_mode()
            mode=self._color_modes.get(mode,mode)
        mode&=0x7F
        return self._mode_bpps[mode],self._mode_channels[mode]
    _np_dtypes={8:"u1",16:"<u2",32:"<u4"}

    def get_gains(self):
        """
        Get current gains.

        Return tuple ``(master, red, green, blue)`` of corresponding gain factors.
        """
        return tuple([lib.is_SetHWGainFactor(self.hcam,0x8000+i,0)/100 for i in range(4)])
    def get_max_gains(self):
        """
        Get maximal gains.

        Return tuple ``(master, red, green, blue)`` of corresponding maximal gain factors.
        """
        return tuple([lib.is_SetHWGainFactor(self.hcam,0x800c+i,100)/100 for i in range(4)])
    def _set_channel_gain(self, i, ivalue):
        max_gain=lib.is_SetHWGainFactor(self.hcam,0x800c+i,100)
        min_gain=100
        ivalue=max(min(ivalue,max_gain),min_gain)
        lib.is_SetHWGainFactor(self.hcam,0x8004+i,ivalue)
    def set_gains(self, master=None, red=None, green=None, blue=None):
        """
        Set current gains.

        If supplied value is ``None``, keep it unchanged.
        """
        for i,g in enumerate([master,red,green,blue]):
            if g is not None:
                self._set_channel_gain(i,int(g*100))
        return self.get_gains()
    def get_gain_boost(self):
        """Check if gain boost is enabled"""
        return bool(lib.is_SetGainBoost(self.hcam,2) and lib.is_SetGainBoost(self.hcam,0x8008))
    def set_gain_boost(self, enabled):
        """Enabel or disable gain boost"""
        if lib.is_SetGainBoost(self.hcam,2):
            lib.is_SetGainBoost(self.hcam,1 if enabled else 0)
        return self.get_gain_boost()

    ### Acquisition process controls ###
    def start_acquisition(self, buffn=None):
        """
        Start camera acquisition.

        `buffn` specifies number of frames in the ring buffer (automatically capped at 32, which is the SDK limit)
        """
        self.stop_acquisition()
        self._allocate_buffers(n=buffn or self._default_nframes)
        lib.is_ResetCaptureStatus(self.hcam)
        lib.is_CaptureVideo(self.hcam,0)
        self._acq_params=(True,buffn)
    def stop_acquisition(self):
        """
        Stop acquisition.

        Clears buffers as well, so any readout after acquisition stop is impossible.
        """
        lib.is_StopLiveVideo(self.hcam,0)
        self._deallocate_buffers()
        self._acq_params=(False,None)
    def acquisition_in_progress(self):
        """Check if the acquisition is in progress"""
        return self._acq_params[0]
    def wait_for_frame(self, since="lastread", timeout=20., period=1E-3):
        """
        Wait for a new camera frame.

        `since` specifies what constitutes a new frame.
        Can be ``"lastread"`` (wait for a new frame after the last read frame), ``"lastwait"`` (wait for a new frame after last :meth:`wait_for_frame` call),
        or ``"now"`` (wait for a new frame acquired after this function call).
        If `timeout` is exceeded, raise :exc:`.PCOSC2TimeoutError`.
        `period` specifies camera polling period.
        """
        if not self.acquisition_in_progress():
            return
        acq_status=self.get_acquisition_status()
        last_acq_frame=acq_status.acquired-1
        last_read_frame=acq_status.last_read-1
        if since=="lastread" and last_acq_frame>last_read_frame:
            self._last_wait_frame=last_acq_frame
            return
        if since=="lastwait" and last_acq_frame>self._last_wait_frame:
            self._last_wait_frame=last_acq_frame
            return
        new_valid=False
        ctd=general.Countdown(timeout)
        while not ctd.passed():
            acq_status=self.get_acquisition_status()
            new_valid=acq_status.acquired>last_acq_frame+1
            if new_valid:
                break
            time.sleep(period)
        if not new_valid:
            raise UC480TimeoutError()
        self._last_wait_frame=acq_status.acquired-1
    @contextlib.contextmanager
    def pausing_acquisition(self):
        """
        Context manager which temporarily pauses acquisition during execution of ``with`` block.

        Useful for applying certain settings which can't be changed during the acquisition (any settings except for exposure).
        """
        acq=self.acquisition_in_progress()
        try:
            self.stop_acquisition()
            yield
        finally:
            if acq:
                self.start_acquisition()

    ### Image settings and transfer controls ###
    _subsampling_modes= {   0x0001:("v",2),0x0004:("v",4),0x0010:("v",3),0x0040:("v",5),0x0100:("v",6),0x0400:("v",8),0x1000:("v",16),
                            0x0002:("h",2),0x0008:("h",4),0x0020:("h",3),0x0080:("h",5),0x0200:("h",6),0x0800:("h",8),0x2000:("h",16) }
    _subsampling_modes_inv=general.invert_dict(_subsampling_modes)
    def _truncate_subsampling(self, hsub, vsub, all_modes):
        hsub=max(hsub,1)
        vsub=max(vsub,1)
        hmodes,vmodes=all_modes
        hsub=max([m for m in hmodes if m<=hsub])
        vsub=max([m for m in vmodes if m<=vsub])
        return hsub,vsub
    def get_supported_subsampling_modes(self):
        """
        Get all supported subsampling modes.

        Return tuple ``(horizontal, vertical)`` of lists with all possible supported subsampling factors.
        """
        all_modes=lib.is_SetSubSampling(self.hcam,0x8001)
        supp={"v":{1},"h":{1}}
        for mask,(d,s) in self._subsampling_modes.items():
            if all_modes&mask:
                supp[d].add(s)
        return sorted(supp["h"]),sorted(supp["v"])
    def get_subsampling(self):
        """Get current subsampling"""
        return lib.is_SetSubSampling(self.hcam,0x8004),lib.is_SetSubSampling(self.hcam,0x8008)
    def set_subsampling(self, hsub=1, vsub=1):
        """
        Set subsampling.

        If values are not supported, get the closest value below the requested.
        """
        hsub,vsub=self._truncate_subsampling(hsub,vsub,self.get_supported_subsampling_modes())
        mask=self._subsampling_modes_inv.get(("h",hsub),0)|self._subsampling_modes_inv.get(("v",vsub),0)
        res=lib.is_SetSubSampling(self.hcam,mask)
        errcheck()(res,lib.is_SetSubSampling,None)
        return self.get_subsampling()

    def get_supported_binning_modes(self):
        """
        Get all supported binning modes.

        Return tuple ``(horizontal, vertical)`` of lists with all possible supported binning factors.
        """
        all_modes=lib.is_SetBinning(self.hcam,0x8001)
        supp={"v":{1},"h":{1}}
        for mask,(d,s) in self._subsampling_modes.items():
            if all_modes&mask:
                supp[d].add(s)
        return sorted(supp["v"]),sorted(supp["h"])
    def get_binning(self):
        """Get current binning"""
        return lib.is_SetBinning(self.hcam,0x8004),lib.is_SetBinning(self.hcam,0x8008)
    def set_binning(self, hbin=1, vbin=1):
        """
        Set binning.

        If values are not supported, get the closest value below the requested.
        """
        hbin,vbin=self._truncate_subsampling(hbin,vbin,self.get_supported_binning_modes())
        mask=self._subsampling_modes_inv.get(("h",hbin),0)|self._subsampling_modes_inv.get(("v",vbin),0)
        res=lib.is_SetBinning(self.hcam,mask)
        errcheck()(res,lib.is_SetBinning,None)
        return self.get_binning()

    def get_detector_size(self):
        """Get camera detector size (in pixels) as a tuple ``(width, height)``"""
        sensor=self._get_sensor_info()
        return sensor.nMaxWidth,sensor.nMaxHeight
    def _check_aoi(self, aoi):
        lib.is_SetAOI(self.hcam,aoi)
        return tuple(lib.is_GetAOI(self.hcam))==aoi
    def _get_roi_binning(self):
        return self.get_subsampling() if self._roi_binning_mode=="subsample" else self.get_binning()
    def _set_roi_binning(self, hbin, vbin):
        if self._roi_binning_mode=="subsample":
            self.set_subsampling(hbin,vbin)
            self.set_binning()
        else:
            self.set_subsampling()
            self.set_binning(hbin,vbin)
    def _truncate_roi_binning(self, hbin, vbin):
        all_modes=self.get_supported_subsampling_modes() if self._roi_binning_mode=="subsample" else self.get_supported_binning_modes()
        return self._truncate_subsampling(hbin,vbin,all_modes)
    def _get_roi_limits(self):
        smin=lib.is_GetAOISize(self.hcam,8)
        sstep=lib.is_GetAOISize(self.hcam,18)
        pstep=lib.is_GetAOIPos(self.hcam,17)
        return (smin[0],sstep[0],pstep[0]),(smin[1],sstep[1],pstep[1])
    def _adj_roi_axis(self, start, end, minsize, detsize, wstep, pstep, bin):
        if end is None:
            end=detsize
        start//=bin
        end//=bin
        detsize//=bin
        end=min(end,detsize)
        start=min(start,detsize)
        start-=start%pstep
        end-=end%pstep
        end-=(end-start)%wstep
        if end-start<minsize:
            end=start+minsize
        if end>detsize:
            end=detsize
            start=detsize-minsize
        return start*bin,end*bin
    def _trunc_roi(self, hstart=0, hend=None, vstart=0, vend=None, hbin=1, vbin=1):
        wdet,hdet=self.get_detector_size()
        hbin,vbin=self._truncate_roi_binning(hbin,vbin)
        hlims,vlims=self._get_roi_limits()
        hstart,hend=self._adj_roi_axis(hstart,hend,hlims[0],wdet,hlims[1],hlims[2],hbin)
        vstart,vend=self._adj_roi_axis(vstart,vend,vlims[0],hdet,vlims[1],vlims[2],vbin)
        return hstart,hend,vstart,vend,hbin,vbin
    def get_roi(self):
        """
        Get current ROI.

        Return tuple ``(hstart, hend, vstart, vend, hbin, vbin)``.
        """
        rect=lib.is_GetAOI(self.hcam)
        hbin,vbin=self._get_roi_binning()
        return (rect.s32X*hbin,(rect.s32X+rect.s32Width)*hbin,rect.s32Y*vbin,(rect.s32Y+rect.s32Height)*vbin,hbin,vbin)
    def set_roi(self, hstart=0, hend=None, vstart=0, vend=None, hbin=1, vbin=1):
        """
        Setup camera ROI.

        `hstart` and `hend` specify horizontal image extent, `vstart` and `vend` specify vertical image extent
        (start are inclusive, stop are exclusive, starting from 0), `hbin` and `vbin` specify binning.
        By default, all non-supplied parameters take extreme values.
        """
        roi=hstart,hend,vstart,vend,hbin,vbin
        hstart,hend,vstart,vend,hbin,vbin=self._trunc_roi(*roi)
        self._set_roi_binning(hbin,vbin)
        lib.is_SetAOI(self.hcam,(hstart//hbin,vstart//vbin,(hend-hstart)//hbin,(vend-vstart)//vbin))
        return self.get_roi()
    def get_roi_limits(self):
        """
        Get the minimal and maximal ROI parameters.

        Return tuple ``(min_roi, max_roi)``, where each element is in turn 6-tuple describing the ROI.
        """
        wdet,hdet=self.get_detector_size()
        hlims,vlims=self._get_roi_limits()
        hbin,vbin=self._truncate_roi_binning(wdet,hdet)
        min_roi=(0,0,hlims[0],vlims[0],1,1)
        max_roi=(wdet-hlims[0],wdet-vlims[0],wdet,hdet,hbin,vbin)
        return (min_roi,max_roi)

    def _get_data_dimensions_rc(self):
        roi=self.get_roi()
        return (roi[3]-roi[2])//roi[5],(roi[1]-roi[0])//roi[4]
    def get_data_dimensions(self):
        """Get readout data dimensions"""
        return image_utils.convert_shape_indexing(self._get_data_dimensions_rc(),"rc",self.image_indexing)

    def get_new_images_range(self):
        """
        Get the range of the new images.

        Return tuple ``(first, last)`` with images range (inclusive).
        If no images are available, return ``None``.
        If some images were in the buffer were overwritten, exclude them from the range.
        """
        if not self._buffers:
            return None
        acq_status=self.get_acquisition_status()
        if acq_status.last_read==acq_status.acquired:
            return None
        last_read=max(acq_status.last_read,acq_status.acquired-len(self._buffers))
        return last_read,acq_status.acquired-1
    def read_multiple_images(self, rng=None, return_info=False):
        """
        Read multiple images specified by `rng` (by default, all un-read images).

        If ``return_info==True``, return tuple ``(images, info)``, where ``images`` is a list of frames,
        and ``info`` is a list of frame info tuples with frame internal index, timestamp, etc.
        If ``return_info==False``, just return a list of frames.
        Each frame is a 2D (for single-channel) or 3D (for multi-channel) numpy array, wich channel being the last (i.e., third) axis.
        Note that some color modes (BGR5, BGR565, and RGB/BGR10 packed) aren't automatically unpacked, so they result in a single-channel image.
        """
        acq_status=self.get_acquisition_status()
        new_images_rng=self.get_new_images_range()
        if rng is None:
            rng=new_images_rng
        if rng is None:
            return [] if return_info else [],[]
        rng=list(rng)
        rng[0]=max(rng[0],acq_status.acquired-len(self._buffers))
        rng[1]=min(rng[1],acq_status.acquired-1)
        if rng is None:
            return [] if return_info else [],[]
        self._next_read_buffer=max(self._next_read_buffer,rng[1]+1)
        frames=[self._read_buffer(i) for i in range(rng[0],rng[1]+1)]
        imgs,infos=list(zip(*frames))
        imgs=[image_utils.convert_image_indexing(im,"rct",self.image_indexing) for im in imgs]
        if return_info:
            return imgs,infos
        else:
            return imgs

    ### Combined functions ###
    def snap(self, n=1, buffn=None):
        """Snap n images"""
        self.start_acquisition(buffn=buffn)
        frames=[]
        while len(frames)<n:
            self.wait_for_frame()
            frames+=self.read_multiple_images()
        self.stop_acquisition()
        return frames[:n]


from da import DenoisingAutoencoder
from dataset import Dataset
import theano.tensor as T
import theano
import numpy
import cPickle as  pkl

def standardize(data):
    """
    Normalize the data with respect to finding the mean and standard deviation of it
    and dividing by mean and standard deviation.
    """
    mu = numpy.mean(data, axis=0)
    sigma = numpy.std(data, axis=0)

    if sigma.nonzero()[0].shape[0] == 0:
        raise Exception("Std dev should not be zero")

    norm_data = (data - mu) / sigma
    return norm_data

if __name__=="__main__":
    fname = "/data/lisa/data/mnist/mnist_all.pickle"
    input = T.fmatrix("x_input")

    ds = Dataset()
    data = ds._get_data(fname)
    x_data = numpy.asarray(data[0][0:42000], dtype=theano.config.floatX)

    weights_file_l1 = "dae_mnist_weights_l1.npy"
    weights_file_l2 = "dae_mnist_weights_l2.npy"

    rnd = numpy.random.RandomState(1231)
    nhid_l1 = 800
    nhid_l2 = 800

    dae_l1 = DenoisingAutoencoder(input,
            nvis=28*28,
            nhid=nhid_l1,
            L1_reg=9.3*1e-5,
            L2_reg=8*1e-4,
            rnd=rnd)

    #std_data = standardize(x_data)
    std_data = numpy.asarray(x_data, dtype=theano.config.floatX)

    dae_l1.fit(learning_rate=9.96*1e-3,
            shuffle_data=True,
            data=std_data,
            weights_file=weights_file_l1,
            recons_img_file=None,
            corruption_level=0.096,
            batch_size=30,
            n_epochs=1400)

    dae_l1_obj_out = file("dae_l1_obj.pkl", "wb")
    pkl.dump(dae_l1, dae_l1_obj_out,  protocol=pkl.HIGHEST_PROTOCOL)

    dae_l1_out = dae_l1.encode(input)
    dae_l1_h = dae_l1.encode(std_data)
    dae_l1_h_fn = theano.function([], dae_l1_h)
    dae_l2_in = dae_l1_h_fn()
    dae_l2_in = numpy.asarray(dae_l2_in, dtype=theano.config.floatX)

    dae_l2 = DenoisingAutoencoder(dae_l1_out,
            L1_reg=1e-4,
            L2_reg=6*1e-4,
            nvis=nhid_l1,
            nhid=nhid_l2,
            rnd=rnd)

    dae_l2.fit(learning_rate=0.95*1e-2,
            data=dae_l2_in,
            shuffle_data=True,
            recons_img_file=None,
            weights_file=weights_file_l2,
            corruption_level=0.1,
            batch_size=25,
            n_epochs=1400)

    dae_l2_obj_out = file("dae_l2_obj.pkl", "wb")
    pkl.dump(dae_l2, dae_l2_obj_out,  protocol=pkl.HIGHEST_PROTOCOL)

    samples = dae_l2.sample(dae_l2_in[10], 0.1, 1000)
    numpy.save(open("data_samples_l2_dae.npy", "wb"), samples)


from urllib import urlencode
from xml.etree import ElementTree as et

import requests

from errors import GoodreadsError
from response import GoodreadsResponseHandler

class GoodreadsClient(object):
    """API client object for querying the Goodreads API."""

    BASE_URL = 'https://www.goodreads.com'

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

    def book_by_isbn(self, isbn):
        """Search Goodreads by 10- or 13-digit ISBN.

        Args:
            isbn (string): 10- or 13-digit ISBN

        Returns:
            GoodreadsBook if book found; otherwise raise
            GoodreadsBookNotFoundError.
        """

        isbn = self._normalize_isbn(isbn)
        path = '/book/isbn/{}/'.format(isbn)
        return self._request(path)

    def book_by_title(self, title, author=''):
        """Search Goodreads by title and optionally author.

        Args:
            title (string): Title of book
            author (string, optional): Author

        Returns:
            GoodreadsBook if book found; otherwise raise
            GoodreadsBookNotFoundError.

        Notes:
            - Include author where possible to improve matching success
        """

        path = '/book/title/'
        params = {'title': title, 'author': author}
        return self._request(path, params=params)

    def books_by_author(self, author_id):
        raise NotImplementedError()

    def author(self, author_id):
        raise NotImplementedError()

    def search(self, query):
        """Seach Goodreads by title, author or ISBN.

        Args:
            query (string): Search query (title, author, ISBN)

        """

        # TODO: Search returns multiple 'works' -- need to handle
        path = '/search/'
        params = {'q': query}
        return self._request(path, params=params)

    def _request(self, path, method='GET', params=None):
        path = self._normalize_path(path)

        if params:
            params.update(self._default_params)
        else:
            params = self._default_params

        params = urlencode(params)
        url = self._generate_url(path, params)

        try:
            response = requests.request(method, url)

        except (requests.ConnectionError, requests.HTTPError):
            raise GoodreadsError('Connection error.')  # TODO: Retry

        parsed_response = et.fromstring(response.content)

        if parsed_response is None:
            raise GoodreadsError('Unexpected error.')

        return GoodreadsResponseHandler.handle(parsed_response)

    @property
    def _default_params(self):
        return {'key': self.api_key}

    def _generate_url(self, path, params):
        return '{}{}?{}'.format(self.BASE_URL, path, params)

    @staticmethod
    def _normalize_path(path):
        if not path.startswith('/'):
            path = '/' + path
        if not path.endswith('/'):
            path += '/'
        return path

    @staticmethod
    def _normalize_isbn(isbn):
        return isbn.replace('-', '')