"""
This module implements a simple mobile object with
a very rudimentary AI as well as an aggressive enemy
object based on that mobile class.

"""

import random, time
from django.conf import settings

from ev import search_object, utils, Script
from contrib.tutorial_world import objects as tut_objects
from contrib.tutorial_world import scripts as tut_scripts

BASE_CHARACTER_TYPECLASS = settings.BASE_CHARACTER_TYPECLASS

#------------------------------------------------------------
#
# Mob - mobile object
#
# This object utilizes exits and moves about randomly from
# room to room.
#
#------------------------------------------------------------

class Mob(tut_objects.TutorialObject):
    """
    This type of mobile will roam from exit to exit at
    random intervals. Simply lock exits against the is_mob attribute
    to block them from the mob (lockstring = "traverse:not attr(is_mob)").
    """
    def at_object_creation(self):
        "This is called when the object is first created."
        self.db.tutorial_info = "This is a moving object. It moves randomly from room to room."

        self.scripts.add(tut_scripts.IrregularEvent)
        # this is a good attribute for exits to look for, to block
        # a mob from entering certain exits.
        self.db.is_mob = True
        self.db.last_location = None
        # only when True will the mob move.
        self.db.roam_mode = True

    def announce_move_from(self, destination):
        "Called just before moving"
        self.location.msg_contents("With a cold breeze, %s drifts in the direction of %s." % (self.key, destination.key))

    def announce_move_to(self, source_location):
        "Called just after arriving"
        self.location.msg_contents("With a wailing sound, %s appears from the %s." % (self.key, source_location.key))

    def update_irregular(self):
        "Called at irregular intervals. Moves the mob."
        if self.roam_mode:
            exits = [ex for ex in self.location.exits
                                    if ex.access(self, "traverse")]
            if exits:
                # Try to make it so the mob doesn't backtrack.
                new_exits = [ex for ex in exits
                                     if ex.destination != self.db.last_location]
                if new_exits:
                    exits = new_exits
                self.db.last_location = self.location
                # execute_cmd() allows the mob to respect exit and
                # exit-command locks, but may pose a problem if there is more
                # than one exit with the same name.
                # - see Enemy example for another way to move
                self.execute_cmd("%s" % exits[random.randint(0, len(exits) - 1)].key)

#------------------------------------------------------------
#
# Enemy - mobile attacking object
#
# An enemy is a mobile that is aggressive against players
# in its vicinity. An enemy will try to attack characters
# in the same location. It will also pursue enemies through
# exits if possible.
#
# An enemy needs to have a Weapon object in order to
# attack.
#
# This particular tutorial enemy is a ghostly apparition that can only
# be hurt by magical weapons. It will also not truly "die", but only
# teleport to another room. Players defeated by the apparition will
# conversely just be teleported to a holding room.
#
#------------------------------------------------------------

class AttackTimer(Script):
    """
    This script is what makes an eneny "tick".
    """
    def at_script_creation(self):
        "This sets up the script"
        self.key = "AttackTimer"
        self.desc = "Drives an Enemy's combat."
        self.interval = random.randint(2, 3) # how fast the Enemy acts
        self.start_delay = True # wait self.interval before first call
        self.persistent = True

    def at_repeat(self):
        "Called every self.interval seconds."
        if self.obj.db.inactive:
            return
        #print "attack timer: at_repeat", self.dbobj.id, self.ndb.twisted_task,
        # id(self.ndb.twisted_task)
        if self.obj.db.roam_mode:
            self.obj.roam()
            #return
        elif self.obj.db.battle_mode:
            #print "attack"
            self.obj.attack()
            return
        elif self.obj.db.pursue_mode:
            #print "pursue"
            self.obj.pursue()
            #return
        else:
            #dead mode. Wait for respawn.
            if not self.obj.db.dead_at:
                self.obj.db.dead_at = time.time()
            if (time.time() - self.obj.db.dead_at) > self.obj.db.dead_timer:
                self.obj.reset()

class Enemy(Mob):
    """
    This is a ghostly enemy with health (hit points). Their chance to hit,
    damage etc is determined by the weapon they are wielding, same as
    characters.

    An enemy can be in four modes:
       roam (inherited from Mob) - where it just moves around randomly
       battle - where it stands in one place and attacks players
       pursue - where it follows a player, trying to enter combat again
       dead - passive and invisible until it is respawned

    Upon creation, the following attributes describe the enemy's actions
      desc - description
      full_health - integer number > 0
      defeat_location - unique name or #dbref to the location the player is
                        taken when defeated. If not given, will remain in room.
      defeat_text - text to show player when they are defeated (just before
                    being whisped away to defeat_location)
      defeat_text_room - text to show other players in room when a player
                         is defeated
      win_text - text to show player when defeating the enemy
      win_text_room - text to show room when a player defeates the enemy
      respawn_text - text to echo to room when the mob is reset/respawn in
                     that room.

    """
    def at_object_creation(self):
        "Called at object creation."
        super(Enemy, self).at_object_creation()

        self.db.tutorial_info = "This moving object will attack players in the same room."

        # state machine modes
        self.db.roam_mode = True
        self.db.battle_mode = False
        self.db.pursue_mode = False
        self.db.dead_mode = False
        # health (change this at creation time)
        self.db.full_health = 20
        self.db.health = 20
        self.db.dead_at = time.time()
        self.db.dead_timer = 100 # how long to stay dead
        # this is used during creation to make sure the mob doesn't move away
        self.db.inactive = True
        # store the last player to hit
        self.db.last_attacker = None
        # where to take defeated enemies
        self.db.defeat_location = "darkcell"
        self.scripts.add(AttackTimer)

    def update_irregular(self):
        "the irregular event is inherited from Mob class"
        strings = self.db.irregular_echoes
        if strings:
            self.location.msg_contents(strings[random.randint(0, len(strings) - 1)])

    def roam(self):
        "Called by Attack timer. Will move randomly as long as exits are open."

        # in this mode, the mob is healed.
        self.db.health = self.db.full_health
        players = [obj for obj in self.location.contents
                   if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser]
        if players:
            # we found players in the room. Attack.
            self.db.roam_mode = False
            self.db.pursue_mode = False
            self.db.battle_mode = True

        elif random.random() < 0.2:
            # no players to attack, move about randomly.
            exits = [ex.destination for ex in self.location.exits
                                                if ex.access(self, "traverse")]
            if exits:
                # Try to make it so the mob doesn't backtrack.
                new_exits = [ex for ex in exits
                                    if ex.destination != self.db.last_location]
                if new_exits:
                    exits = new_exits
                self.db.last_location = self.location
                # locks should be checked here
                self.move_to(exits[random.randint(0, len(exits) - 1)])
            else:
                # no exits - a dead end room. Respawn back to start.
                self.move_to(self.home)

    def attack(self):
        """
        This is the main mode of combat. It will try to hit players in
        the location. If players are defeated, it will whisp them off
        to the defeat location.
        """
        last_attacker = self.db.last_attacker
        players = [obj for obj in self.location.contents
                   if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser]
        if players:

            # find a target
            if last_attacker in players:
                # prefer to attack the player last attacking.
                target = last_attacker
            else:
                # otherwise attack a random player in location
                target = players[random.randint(0, len(players) - 1)]

            # try to use the weapon in hand
            attack_cmds = ("thrust", "pierce", "stab", "slash", "chop")
            cmd = attack_cmds[random.randint(0, len(attack_cmds) - 1)]
            self.execute_cmd("%s %s" % (cmd, target))

            # analyze result.
            if target.db.health <= 0:
                # we reduced enemy to 0 health. Whisp them off to
                # the prison room.
                tloc = search_object(self.db.defeat_location)
                tstring = self.db.defeat_text
                if not tstring:
                    tstring = "You feel your conciousness slip away ... you fall to the ground as "
                    tstring += "the misty apparition envelopes you ...\n The world goes black ...\n"
                target.msg(tstring)
                ostring = self.db.defeat_text_room
                if tloc:
                    if not ostring:
                        ostring = "\n%s envelops the fallen ... and then their body is suddenly gone!" % self.key
                        # silently move the player to defeat location
                        # (we need to call hook manually)
                    target.location = tloc[0]
                    tloc[0].at_object_receive(target, self.location)
                elif not ostring:
                    ostring = "%s falls to the ground!" % target.key
                self.location.msg_contents(ostring, exclude=[target])
                # Pursue any stragglers after the battle
                self.battle_mode = False
                self.roam_mode = False
                self.pursue_mode = True
        else:
            # no players found, this could mean they have fled.
            # Switch to pursue mode.
            self.battle_mode = False
            self.roam_mode = False
            self.pursue_mode = True

    def pursue(self):
        """
        In pursue mode, the enemy tries to find players in adjoining rooms, preferably
        those that previously attacked it.
        """
        last_attacker = self.db.last_attacker
        players = [obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser]
        if players:
            # we found players in the room. Maybe we caught up with some,
            # or some walked in on us before we had time to pursue them.
            # Switch to battle mode.
            self.battle_mode = True
            self.roam_mode = False
            self.pursue_mode = False
        else:
            # find all possible destinations.
            destinations = [ex.destination for ex in self.location.exits
                                                if ex.access(self, "traverse")]
            # find all players in the possible destinations. OBS-we cannot
            # just use the player's current position to move the Enemy; this
            # might have changed when the move is performed, causing the enemy
            # to teleport out of bounds.
            players = {}
            for dest in destinations:
                for obj in [o for o in dest.contents
                           if utils.inherits_from(o, BASE_CHARACTER_TYPECLASS)]:
                    players[obj] = dest
            if players:
                # we found targets. Move to intercept.
                if last_attacker in players:
                    # preferably the one that last attacked us
                    self.move_to(players[last_attacker])
                else:
                    # otherwise randomly.
                    key = players.keys()[random.randint(0, len(players) - 1)]
                    self.move_to(players[key])
            else:
                # we found no players nearby. Return to roam mode.
                self.battle_mode = False
                self.roam_mode = True
                self.pursue_mode = False

    def at_hit(self, weapon, attacker, damage):
        """
        Called when this object is hit by an enemy's weapon
        Should return True if enemy is defeated, False otherwise.

        In the case of players attacking, we handle all the events
        and information from here, so the return value is not used.
        """

        self.db.last_attacker = attacker
        if not self.db.battle_mode:
            # we were attacked, so switch to battle mode.
            self.db.roam_mode = False
            self.db.pursue_mode = False
            self.db.battle_mode = True
            #self.scripts.add(AttackTimer)

        if not weapon.db.magic:
            # In the tutorial, the enemy is a ghostly apparition, so
            # only magical weapons can harm it.
            string = self.db.weapon_ineffective_text
            if not string:
                string = "Your weapon just passes through your enemy, causing no effect!"
            attacker.msg(string)
            return
        else:
            # an actual hit
            health = float(self.db.health)
            health -= damage
            self.db.health = health
            if health <= 0:
                string = self.db.win_text
                if not string:
                    string = "After your last hit, %s folds in on itself, it seems to fade away into nothingness. " % self.key
                    string += "In a moment there is nothing left but the echoes of its screams. But you have a "
                    string += "feeling it is only temporarily weakened. "
                    string += "You fear it's only a matter of time before it materializes somewhere again."
                attacker.msg(string)
                string = self.db.win_text_room
                if not string:
                    string = "After %s's last hit, %s folds in on itself, it seems to fade away into nothingness. " % (attacker.name, self.key)
                    string += "In a moment there is nothing left but the echoes of its screams. But you have a "
                    string += "feeling it is only temporarily weakened. "
                    string += "You fear it's only a matter of time before it materializes somewhere again."
                self.location.msg_contents(string, exclude=[attacker])

                # put mob in dead mode and hide it from view.
                # AttackTimer will bring it back later.
                self.db.dead_at = time.time()
                self.db.roam_mode = False
                self.db.pursue_mode = False
                self.db.battle_mode = False
                self.db.dead_mode = True
                self.location = None
            else:
                self.location.msg_contents("%s wails, shudders and writhes." % self.key)
        return False

    def reset(self):
        """
        If the mob was 'dead', respawn it to its home position and reset
        all modes and damage."""
        if self.db.dead_mode:
            self.db.health = self.db.full_health
            self.db.roam_mode = True
            self.db.pursue_mode = False
            self.db.battle_mode = False
            self.db.dead_mode = False
            self.location = self.home
            string = self.db.respawn_text
            if not string:
                string = "%s fades into existence from out of thin air. It's looking pissed." % self.key
                self.location.msg_contents(string)


#!/bin/env python3
import time, sys
def load(loading):
	import time, sys
	def bar(bar):
		for i in bar:
			time.sleep(0.1)
			sys.stdout.write(i)
			sys.stdout.flush()
	frames = "/ | \\ -"
	i = 0
	while i < 35:
		print (frames[i % len(frames)], bar(loading), end='\r')
		i += 1
		time.sleep(0.1)
#def bar(bar):
#	for a in bar:
#		time.sleep(0.1)
#		sys.stdout.write(a)
#		sys.stdout.flush()
load("fuck .......")


import pytest
import os
import logging
import show.main as show
import config.main as config

from click.testing import CliRunner
from utilities_common.db import Db
from .mock_tables import dbconnector
from .hash_input import assert_show_output

test_path = os.path.dirname(os.path.abspath(__file__))
input_path = os.path.join(test_path, "hash_input")
mock_config_path = os.path.join(input_path, "mock_config")
mock_state_path = os.path.join(input_path, "mock_state")

logger = logging.getLogger(__name__)

HASH_FIELD_LIST = [
    "DST_MAC",
    "SRC_MAC",
    "ETHERTYPE",
    "IP_PROTOCOL",
    "DST_IP",
    "SRC_IP",
    "L4_DST_PORT",
    "L4_SRC_PORT"
]
INNER_HASH_FIELD_LIST = [
    "INNER_DST_MAC",
    "INNER_SRC_MAC",
    "INNER_ETHERTYPE",
    "INNER_IP_PROTOCOL",
    "INNER_DST_IP",
    "INNER_SRC_IP",
    "INNER_L4_DST_PORT",
    "INNER_L4_SRC_PORT"
]

HASH_ALGORITHM = [
    "CRC",
    "XOR",
    "RANDOM",
    "CRC_32LO",
    "CRC_32HI",
    "CRC_CCITT",
    "CRC_XOR"
]

SUCCESS = 0
ERROR2 = 2

class TestHash:
    @classmethod
    def setup_class(cls):
        logger.info("Setup class: {}".format(cls.__name__))
        os.environ['UTILITIES_UNIT_TESTING'] = "1"
        dbconnector.dedicated_dbs["STATE_DB"] = os.path.join(mock_state_path, "ecmp_and_lag")

    @classmethod
    def teardown_class(cls):
        logger.info("Teardown class: {}".format(cls.__name__))
        os.environ['UTILITIES_UNIT_TESTING'] = "0"
        dbconnector.dedicated_dbs.clear()

    ########## CONFIG SWITCH-HASH GLOBAL ##########

    @pytest.mark.parametrize(
        "hash", [
            "ecmp-hash",
            "lag-hash"
        ]
    )
    @pytest.mark.parametrize(
        "args", [
            pytest.param(
                " ".join(HASH_FIELD_LIST),
                id="outer-frame"
            ),
            pytest.param(
                " ".join(INNER_HASH_FIELD_LIST),
                id="inner-frame"
            )
        ]
    )
    def test_config_hash(self, hash, args):
        db = Db()
        runner = CliRunner()

        result = runner.invoke(
            config.config.commands["switch-hash"].commands["global"].
            commands[hash], args, obj=db
        )

        logger.debug("\n" + result.output)
        logger.debug(result.exit_code)

        assert result.exit_code == SUCCESS

    @pytest.mark.parametrize(
        "hash", [
            "ecmp-hash",
            "lag-hash"
        ]
    )
    @pytest.mark.parametrize(
        "args,pattern", [
            pytest.param(
                "DST_MAC1 SRC_MAC ETHERTYPE",
                "invalid choice: DST_MAC1.",
                id="INVALID,SRC_MAC,ETHERTYPE"
            ),
            pytest.param(
                "DST_MAC SRC_MAC1 ETHERTYPE",
                "invalid choice: SRC_MAC1.",
                id="DST_MAC,INVALID,ETHERTYPE"
            ),
            pytest.param(
                "DST_MAC SRC_MAC ETHERTYPE1",
                "invalid choice: ETHERTYPE1.",
                id="DST_MAC,SRC_MAC,INVALID"
            ),
            pytest.param(
                "DST_MAC DST_MAC SRC_MAC ETHERTYPE",
                "duplicate hash field(s) DST_MAC",
                id="DUPLICATE,SRC_MAC,ETHERTYPE"
            ),
            pytest.param(
                "DST_MAC DST_MAC SRC_MAC SRC_MAC ETHERTYPE",
                "duplicate hash field(s) DST_MAC, SRC_MAC",
                id="DUPLICATE,DUPLICATE,ETHERTYPE"
            ),
            pytest.param(
                "DST_MAC DST_MAC SRC_MAC SRC_MAC ETHERTYPE ETHERTYPE",
                "duplicate hash field(s) DST_MAC, SRC_MAC, ETHERTYPE",
                id="DUPLICATE,DUPLICATE,DUPLICATE"
            )
        ]
    )
    def test_config_hash_neg(self, hash, args, pattern):
        db = Db()
        runner = CliRunner()

        result = runner.invoke(
            config.config.commands["switch-hash"].commands["global"].
            commands[hash], args, obj=db
        )

        logger.debug("\n" + result.output)
        logger.debug(result.exit_code)

        assert pattern in result.output
        assert result.exit_code == ERROR2

    @pytest.mark.parametrize(
        "hash", [
            "ecmp-hash-algorithm",
            "lag-hash-algorithm"
        ]
    )
    @pytest.mark.parametrize(
        "arg", HASH_ALGORITHM
    )
    def test_config_hash_algorithm(self, hash, arg):
        db = Db()
        runner = CliRunner()

        result = runner.invoke(
            config.config.commands["switch-hash"].commands["global"].
            commands[hash], arg, obj=db
        )

        logger.debug("\n" + result.output)
        logger.debug(result.exit_code)

        assert result.exit_code == SUCCESS

    @pytest.mark.parametrize(
        "hash", [
            "ecmp-hash-algorithm",
            "lag-hash-algorithm"
        ]
    )
    @pytest.mark.parametrize(
        "arg,pattern", [
            pytest.param(
                "CRC1",
                "invalid choice: CRC1.",
                id="INVALID"
            )
        ]
    )
    def test_config_hash_algorithm_neg(self, hash, arg, pattern):
        db = Db()
        runner = CliRunner()

        result = runner.invoke(
            config.config.commands["switch-hash"].commands["global"].
            commands[hash], arg, obj=db
        )

        logger.debug("\n" + result.output)
        logger.debug(result.exit_code)

        assert pattern in result.output
        assert result.exit_code == ERROR2

    ########## SHOW SWITCH-HASH GLOBAL ##########

    @pytest.mark.parametrize(
        "cfgdb,output", [
            pytest.param(
                os.path.join(mock_config_path, "empty"),
                {
                    "plain": assert_show_output.show_hash_empty,
                    "json": assert_show_output.show_hash_empty
                },
                id="empty"
            ),
            pytest.param(
                os.path.join(mock_config_path, "ecmp"),
                {
                    "plain": assert_show_output.show_hash_ecmp,
                    "json": assert_show_output.show_hash_ecmp_json
                },
                id="ecmp"
            ),
            pytest.param(
                os.path.join(mock_config_path, "lag"),
                {
                    "plain": assert_show_output.show_hash_lag,
                    "json": assert_show_output.show_hash_lag_json
                },
                id="lag"
            ),
            pytest.param(
                os.path.join(mock_config_path, "ecmp_and_lag"),
                {
                    "plain": assert_show_output.show_hash_ecmp_and_lag,
                    "json": assert_show_output.show_hash_ecmp_and_lag_json
                },
                id="all"
            )
        ]
    )
    @pytest.mark.parametrize(
        "format", [
            "plain",
            "json",
        ]
    )
    def test_show_hash(self, cfgdb, output, format):
        dbconnector.dedicated_dbs["CONFIG_DB"] = cfgdb

        db = Db()
        runner = CliRunner()

        result = runner.invoke(
            show.cli.commands["switch-hash"].commands["global"],
            [] if format == "plain" else ["--json"], obj=db
        )

        logger.debug("\n" + result.output)
        logger.debug(result.exit_code)

        assert result.output == output[format]
        assert result.exit_code == SUCCESS

    @pytest.mark.parametrize(
        "statedb,output", [
            pytest.param(
                os.path.join(mock_state_path, "no_capabilities"),
                {
                    "plain": assert_show_output.show_hash_capabilities_no,
                    "json": assert_show_output.show_hash_capabilities_no_json
                },
                id="no"
            ),
            pytest.param(
                os.path.join(mock_state_path, "not_applicable"),
                {
                    "plain": assert_show_output.show_hash_capabilities_na,
                    "json": assert_show_output.show_hash_capabilities_na_json
                },
                id="na"
            ),
            pytest.param(
                os.path.join(mock_state_path, "empty"),
                {
                    "plain": assert_show_output.show_hash_capabilities_empty,
                    "json": assert_show_output.show_hash_capabilities_empty_json
                },
                id="empty"
            ),
            pytest.param(
                os.path.join(mock_state_path, "ecmp"),
                {
                    "plain": assert_show_output.show_hash_capabilities_ecmp,
                    "json": assert_show_output.show_hash_capabilities_ecmp_json
                },
                id="ecmp"
            ),
            pytest.param(
                os.path.join(mock_state_path, "lag"),
                {
                    "plain": assert_show_output.show_hash_capabilities_lag,
                    "json": assert_show_output.show_hash_capabilities_lag_json
                },
                id="lag"
            ),
            pytest.param(
                os.path.join(mock_state_path, "ecmp_and_lag"),
                {
                    "plain": assert_show_output.show_hash_capabilities_ecmp_and_lag,
                    "json": assert_show_output.show_hash_capabilities_ecmp_and_lag_json
                },
                id="all"
            )
        ]
    )
    @pytest.mark.parametrize(
        "format", [
            "plain",
            "json",
        ]
    )
    def test_show_hash_capabilities(self, statedb, output, format):
        dbconnector.dedicated_dbs["STATE_DB"] = statedb

        db = Db()
        runner = CliRunner()

        result = runner.invoke(
            show.cli.commands["switch-hash"].commands["capabilities"],
            [] if format == "plain" else ["--json"], obj=db
        )

        logger.debug("\n" + result.output)
        logger.debug(result.exit_code)

        assert result.output == output[format]
        assert result.exit_code == SUCCESS


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

# 0001: 读一个文件，每次读两行，并打印出来

def readFile(filepath):
	f = open(filepath, 'r')
	lines = ''
	count = 0
	for line in f:
		lines += line
		count += 1
		if count % 2 == 0:
			print('-------------')
			print(lines)
			lines = ''

if __name__ == '__main__':
	filepath = '0001/words.txt'
	readFile(filepath)


import sys
import os
import os.path
__REPOSITORY_ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
if __REPOSITORY_ROOT_DIR not in sys.path:
    sys.path.insert(0, __REPOSITORY_ROOT_DIR)
os.chdir(__REPOSITORY_ROOT_DIR)

import setuptools
from sidein.SideinConstants import SideinConstants

with open("./README.md", "r") as readme_io:
    readme_text = readme_io.read()

setuptools.setup(
    name="sidein",
    version=SideinConstants.LIBRARY_VERSION,
    description="A flexible, object-oriented Python dependency injector",
    long_description=readme_text,
    long_description_content_type="text/markdown",
    author="Vít Labuda",
    author_email="dev@vitlabuda.cz",
    license="BSD License",
    url="https://github.com/vitlabuda/sidein",
    project_urls={
        "Bug Tracker": "https://github.com/vitlabuda/sidein/issues",
    },
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Topic :: Software Development :: Libraries",
        "Typing :: Typed",
    ],
    packages=setuptools.find_packages(),
    python_requires=">=3.9",
    tests_require=["pytest"],
)


class OutOfBoundsException(Exception):
    def __init__(self, *, index:int, is_row_index=False, is_col_index=False):
        self.type = 'Table'
        if is_row_index and not is_col_index:
            self.type='Row'
        if not is_row_index and is_col_index:
            self.type='Column'
        if is_row_index and is_col_index:
            self.type='Row&Column'
        super().__init__(f'{self.type}IndexOutOfBounds: {index}')


import tensorflow as tf

import numpy as np

# 512 hidden units in layer 1, 256 units in layer2 - Larger Network
class ValueFunctionBayesHypernet:
    def __init__(self, state_dim=2, n_actions=3, batch_size=64):
        self.graph = tf.Graph()
        with self.graph.as_default():
            # Inputs, weights, biases and targets of the ANN
            self.x = tf.placeholder(tf.float32, shape=(None, state_dim))                    # Single sample
            self.train_data = tf.placeholder(tf.float32, shape=(batch_size, state_dim))     # Training batch of samples
            self.train_targets = tf.placeholder(tf.float32, shape=(batch_size, n_actions))  # Training batch of targets

            #self.l1_weights = tf.Variable(tf.truncated_normal([state_dim, 512], stddev=0.1), trainable=True, name="w1")
            self.l1_weights = tf.get_variable(name="w1", shape=[state_dim, 512],
                                              initializer=tf.contrib.layers.xavier_initializer())
            self.l1_biases = tf.Variable(tf.zeros([512]), trainable=True, name="b1")

            #self.l2_weights = tf.Variable(tf.truncated_normal([512, 256], stddev=0.1), trainable=True, name="w2")
            self.l2_weights = tf.get_variable(name="w2", shape=[512, 256],
                                              initializer=tf.contrib.layers.xavier_initializer())
            self.l2_biases = tf.Variable(tf.zeros([256]), trainable=True, name="b2")

            #self.l3_weights = tf.Variable(tf.truncated_normal([256, n_actions], stddev=0.1), trainable=True, name="w3")
            self.l3_weights = tf.get_variable(name="w3", shape=[256, n_actions],
                                              initializer=tf.contrib.layers.xavier_initializer())
            self.l3_biases = tf.Variable(tf.zeros([n_actions]), trainable=True, name="b3")

            # Interconnection of the various ANN nodes
            self.train_prediction = self.model(self.train_data)

            # Training calculations - squared difference between the TD Target and TD Predictions
            self.loss = tf.reduce_mean(tf.squared_difference(self.train_targets, self.train_prediction))

            #using Adam Optimizer for the training
            self.optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(self.loss)

            self.test_prediction = self.model(self.x)

            self.w1_max = tf.reduce_max(self.l1_weights)
            self.w2_max = tf.reduce_max(self.l2_weights)
            self.w3_max = tf.reduce_max(self.l3_weights)

            self.init_op = tf.global_variables_initializer()

        self.session = None

    def model(self, data):
        logits1 = tf.matmul(data, self.l1_weights) + self.l1_biases
        hidden1 = tf.nn.relu(logits1)  # Define units of layer

        logits2 = tf.matmul(hidden1, self.l2_weights) + self.l2_biases
        hidden2 = tf.nn.relu(logits2)  # Define units of layer

        return tf.matmul(hidden2, self.l3_weights) + self.l3_biases

    def init_tf_session(self):
        if self.session is None:
            self.session = tf.Session(graph=self.graph)
            self.session.run(self.init_op)  # Global Variables Initializer (init op)

    def predict(self, states):
        self.init_tf_session()  # Make sure the Tensorflow session exists

        feed_dict = {self.x: states}
        q = self.session.run(self.test_prediction, feed_dict=feed_dict)
        return q

    def train(self, states, targets):
        self.init_tf_session()  # Make sure the Tensorflow session exists

        feed_dict = {self.train_data: states, self.train_targets: targets}
        [l, _, w1_m, w2_m, w3_m] = self.session.run([self.loss, self.optimizer, self.w1_max, self.w2_max, self.w3_max],
                                                    feed_dict=feed_dict)

        return [l, w1_m, w2_m, w3_m]


import streamlit as st
import requests
import json
from typing import List, Dict, Literal
from pydantic import BaseModel
import streamlit.components.v1 as components

from template_validation import highlight_placeholders_and_macros_with_html

class Template(BaseModel):
    template_id: str
    content: str
    variableNames: List[str] = []
    maxWords: int = 100
    height: int = 300

def get_templates()->List[Template]:

    response = requests.get(f"https://lmwznlj2ta.execute-api.us-east-1.amazonaws.com/Prod/templates/{user_name}")
    #response = requests.get(f"http://127.0.0.1:8000/templates/{user_name}")

    if response.status_code == 200:
        templates = json.loads(response.content.decode())
        return [Template(**template) for template in templates]
    else:
        return []

def update_templates():

    dictTemplates = [template.model_dump() for template in templates]
    response = requests.put(f"https://lmwznlj2ta.execute-api.us-east-1.amazonaws.com/Prod/templates/{user_name}",data=json.dumps(dictTemplates))
    #response = requests.put(f"http://127.0.0.1:8000/templates/{user_name}",data=json.dumps(dictTemplates))
    print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!!!!!!!!!!!!!")
    if response.status_code == 200:
        st.success(f"Templates updated")
    else:
        st.error(f"Templates failed to update")

    # for template in templates:
    #     response = requests.put(f"https://lmwznlj2ta.execute-api.us-east-1.amazonaws.com/Prod/templates/{user_name}",data=json.dumps(template.model_dump()))

    #     if response.status_code == 200:
    #         #st.success(f"Template {template.template_id} updated")
    #         pass
    #     else:
    #         st.error(f"Template {template.template_id} failed to update")

templates : List[Template] = []
user_name : Literal['User1', 'User2', 'User3' , 'User4' ] = 'User1'

def main():

    st.set_page_config(page_title="Template Editor", page_icon=":pencil2:" , layout="wide")

    st.subheader("Simulation Prompt Templates")

    global user_name
    user_name = st.selectbox(
        "Prompt templates for:",
        ("User1", "User2", "User3" , "User4"),
        index=0,
        #placeholder="Select contact method...",
    )

    st.write(f"{user_name} templates")

    global templates
    templates = get_templates()

    for template in templates:

        with st.expander(template.template_id):
            template.content = st.text_area('', template.content , height=template.height , key=template.template_id)

            st.write(', '.join(template.variableNames))

            if st.button('Validate' , key=f'{template.template_id}_va'):
                components.html(highlight_placeholders_and_macros_with_html(template.content,template.variableNames , template.height - 20), height=template.height , scrolling=True)

    st.button("Update",on_click=update_templates)

if __name__ == "__main__":
    main()


from bs4 import BeautifulSoup

with open("movies_website.html") as file:
    data = file.read()

soup = BeautifulSoup(data, "html.parser")
all_h3s = soup.find_all(name="h3")
movies100 = []
for item in all_h3s:
    movies100.append(item.getText())
movies100.reverse()
with open("movies.txt", "w") as file:
    for item in movies100:
        file.writelines(item)
        file.write("\n")


import os,sys
import pandas as pd
from sklearn.model_selection import train_test_split
from pandas import DataFrame
import shutil

from sentiment.exception import SentimentException
from sentiment.logger import logging
from sentiment.entity.config_entity import DataValidationConfig
from sentiment.entity.artifact_entity import DataValidationArtifact, DataIngestionArtifact
# from sentiment.data_access.sentiment_data import SentimentData
from sentiment.utils.main_utils import read_yaml_file
from sentiment.constant.training_pipeline import SCHEMA_FILE_PATH
#from sentiment.constant.s3_bucket import TRAINING_BUCKET_NAME
from sentiment.configuration.s3_operations import S3Operation

class DataValidation:

    def __init__(self, data_validation_config: DataValidationConfig, data_ingestion_artifacts: DataIngestionArtifact):
        try:
            logging.info("Staring Data Validation >>>>>")
            self.data_validation_config = data_validation_config
            self.data_ingestion_artifacts= data_ingestion_artifacts
            self._schema_config = read_yaml_file(SCHEMA_FILE_PATH)
        except Exception as e:
            raise SentimentException(e,sys)

    def _accepted_columns(self):
        try:
            col_names_list = []
            column_names: list = self._schema_config['columns']
            for names in column_names:
                col_names_list.append(list(names.keys())[0])
            return col_names_list
        except Exception as e:
            raise SentimentException(e, sys)

    def read_data(self) -> pd.DataFrame:
        try:
            ingested_data = pd.read_csv(self.data_ingestion_artifacts.ingested_file_path,\
                                        encoding=self.data_validation_config.encoding,
                                        names= self._accepted_columns())
            return ingested_data
        except Exception as e:
            raise SentimentException(e,sys)

    def check_column_type(self) -> bool:
        col_dtype_list = []
        column_dtype: list = self._schema_config['columns']
        for names in column_dtype:
            col_dtype_list.append(list(names.values())[0])

        for r in range(len(col_dtype_list)):
            if col_dtype_list[r] != self.read_data().dtypes.to_list()[r]:
                return False
        return True

    @staticmethod
    def save_file(previous_path: str, new_path: str) -> None:
        try:
            shutil.copy(previous_path, new_path)
        except shutil.SameFileError:
            raise (" Source and Destination is Same")
        except PermissionError:
            raise ('Permission Denied')
        except Exception as e:
            raise SentimentException(e,sys)

    def initiate_data_validation(self) -> DataValidationArtifact:
        try:
            if self.check_column_type():
                logging.info("Data Accepted>>>>")
                ingested_data = self.read_data()
                validation_status = True
                # Copy the file from ingested artifacts to Validated artifacts
                os.makedirs(self.data_validation_config.validated_data_dir, exist_ok= True)
                ingested_data.to_csv(self.data_validation_config.validated_file_name, index= False)

            else:
                validation_status= False
                logging.info("Data Not Accepted>>>>")
            data_validation_artifacts= DataValidationArtifact(validation_status=validation_status,\
                                            valid_file_path= self.data_validation_config.validated_file_name)
            return data_validation_artifacts
        except Exception as e:
            raise SentimentException(e,sys)

if __name__ == "__main__":
    dataval = DataValidation(data_validation_config = DataValidationConfig(),
            data_ingestion_artifacts= DataIngestionArtifact())


import numpy as np
import numpy.linalg as la
import random

# We will find coefficients alpha to estimate: X * alpha ≈ y, using the provided data sets X and y.
#   We will compare two approaches, least squares and ridge regression.
def main():

    X = np.loadtxt('X.csv', delimiter=',')
    y = np.loadtxt('y.csv', delimiter=',')

    s_options = [0.2, 0.4, 0.8, 1.0, 1.2, 1.4, 1.6]
    s = random.choice(s_options)

    alpha = la.inv(X.T @ X) @ X.T @ y.T
    alphas = la.inv(X.T @ X + s * np.identity(50)) @ X.T @ y.T

    print(alpha)
    print(alphas)

    # A: Solve for the coefficients alpha(or alphas) using Least Squares and Ridge Regression with
    #       s ∈ {0.2, 0.4, 0.8, 1.0, 1.2, 1.4, 1.6} (i.e. s will take on one of those 7 values each
    #       time you try, say obtaining alpha04 for s = 0.4). For each set of coefficients, report the
    #       error in the estimate y_hat of y as norm(y - X * alpha, 2).

    X1 = X[:66, :]
    Y1 = y[:66]
    X2 = X[33:, :]
    Y2 = y[33:]
    X3 = np.vstack((X[:33, :], X[66:, :]))
    Y3 = np.vstack(y[:33], y[66:])

    # Report the error in the estimate of y_hat of y as: norm(y - X * alpha, 2).
    # error = np.norm(y - X * alpha, 2)

    # B: Create three row-subsets of X and Y. Repeat the above procedure on these subsets and
    #       cross-validate the solution on the remainder of X and Y. Specifically, learn the coefficients
    #       alpha using, say, X1 and Y1 and then measure np.norm(Y[66:] - X[66:, :] @ alpha, 2).

    # C: Which approach works best (averaging the results from the three subsets): Least Squares, or
    #       for which value of s using Ridge Regression?

    # D: Use the same 3 test / train splits, taking their average errors, to estimate the average
    #       squared error on each predicted data point.
    #   What is problematic about the above estimate, especially for the best performing parameter
    #       value s?

    # E: Even circumventing the issue raised in part D, what assumptions about how the data set (X, y)
    #       is generated are needed in an assessment based on cross-validation?

    # 2: Consider a linear equation W = M * S where M is a measurement matrix filled with random values
    #       {-1, 0, +1} (although now that they are there, they are no longer random), and W is the
    #       output of the sparse signal S when measured by M.
    #   Use Matching Pursuit (as described in the book as Algorithm 5.5.1 to recover the non-zero entries
    #       S. Record the order in which you find each entry and the residual vector after each step.

def lin_regression():
    return

def cross_validation():
    return

if __name__ == '__main__':
    main()


import numpy
from numbers import Number
import functools
from cil.utilities.multiprocessing import NUM_THREADS

class BlockDataContainer(object):
    '''Class to hold DataContainers as column vector

    Provides basic algebra between BlockDataContainer's, DataContainer's and
    subclasses and Numbers

    1) algebra between `BlockDataContainer`s will be element-wise, only if
       the shape of the 2 `BlockDataContainer`s is the same, otherwise it
       will fail
    2) algebra between `BlockDataContainer`s and `list` or `numpy array` will
       work as long as the number of `rows` and element of the arrays match,
       independently on the fact that the `BlockDataContainer` could be nested
    3) algebra between `BlockDataContainer` and one `DataContainer` is possible.
       It will require all the `DataContainers` in the block to be
       compatible with the `DataContainer` we want to operate with.
    4) algebra between `BlockDataContainer` and a `Number` is possible and it
       will be done with each element of the `BlockDataContainer` even if nested

    A = [ [B,C] , D]
    A * 3 = [ 3 * [B,C] , 3* D] = [ [ 3*B, 3*C]  , 3*D ]

    '''
    ADD       = 'add'
    SUBTRACT  = 'subtract'
    MULTIPLY  = 'multiply'
    DIVIDE    = 'divide'
    POWER     = 'power'
    SAPYB     = 'sapyb'
    MAXIMUM   = 'maximum'
    MINIMUM   = 'minimum'
    ABS       = 'abs'
    SIGN      = 'sign'
    SQRT      = 'sqrt'
    CONJUGATE = 'conjugate'
    __array_priority__ = 1
    __container_priority__ = 2

    @property
    def dtype(self):
        return tuple(i.dtype for i in self.containers)

    def __init__(self, *args, **kwargs):
        ''''''
        self.containers = args
        self.index = 0
        self.geometry = None
        #if len(set([i.shape for i in self.containers])):
        #    self.geometry = self.containers[0].geometry

        shape = kwargs.get('shape', None)
        if shape is None:
           shape = (len(args),1)
#        shape = (len(args),1)
        self.shape = shape

        n_elements = functools.reduce(lambda x,y: x*y, shape, 1)
        if len(args) != n_elements:
            raise ValueError(
                    'Dimension and size do not match: expected {} got {}'
                    .format(n_elements, len(args)))

    def __iter__(self):
        '''BlockDataContainer is Iterable'''
        return self
    def next(self):
        '''python2 backwards compatibility'''
        return self.__next__()
    def __next__(self):
        try:
            out = self[self.index]
        except IndexError as ie:
            raise StopIteration()
        self.index+=1
        return out

    def is_compatible(self, other):
        '''basic check if the size of the 2 objects fit'''

        if isinstance(other, Number):
            return True
        elif isinstance(other, (list, tuple, numpy.ndarray)) :
            for ot in other:
                if not isinstance(ot, Number):
                    raise ValueError('List/ numpy array can only contain numbers {}'\
                                     .format(type(ot)))
            return len(self.containers) == len(other)
        elif isinstance(other, BlockDataContainer):
            return len(self.containers) == len(other.containers)
        else:
            # this should work for other as DataContainers and children
            ret = True
            for i, el in enumerate(self.containers):
                if isinstance(el, BlockDataContainer):
                    a = el.is_compatible(other)
                else:
                    a = el.shape == other.shape
                ret = ret and a
            # probably will raise
            return ret

    def get_item(self, row):
        if row > self.shape[0]:
            raise ValueError('Requested row {} > max {}'.format(row, self.shape[0]))
        return self.containers[row]

    def __getitem__(self, row):
        return self.get_item(row)

    def add(self, other, *args, **kwargs):
        '''Algebra: add method of BlockDataContainer with number/DataContainer or BlockDataContainer

        :param: other (number, DataContainer or subclasses or BlockDataContainer
        :param: out (optional): provides a placehold for the resul.
        '''
        out = kwargs.get('out', None)
        if out is not None:
            self.binary_operations(BlockDataContainer.ADD, other, *args, **kwargs)
        else:
            return self.binary_operations(BlockDataContainer.ADD, other, *args, **kwargs)
    def subtract(self, other, *args, **kwargs):
        '''Algebra: subtract method of BlockDataContainer with number/DataContainer or BlockDataContainer

        :param: other (number, DataContainer or subclasses or BlockDataContainer
        :param: out (optional): provides a placeholder for the result.
        '''
        out = kwargs.get('out', None)
        if out is not None:
            self.binary_operations(BlockDataContainer.SUBTRACT, other, *args, **kwargs)
        else:
            return self.binary_operations(BlockDataContainer.SUBTRACT, other, *args, **kwargs)
    def multiply(self, other, *args, **kwargs):
        '''Algebra: multiply method of BlockDataContainer with number/DataContainer or BlockDataContainer

        :param: other (number, DataContainer or subclasses or BlockDataContainer)
        :param: out (optional): provides a placeholder for the result.
        '''
        out = kwargs.get('out', None)
        if out is not None:
            self.binary_operations(BlockDataContainer.MULTIPLY, other, *args, **kwargs)
        else:
            return self.binary_operations(BlockDataContainer.MULTIPLY, other, *args, **kwargs)
    def divide(self, other, *args, **kwargs):
        '''Algebra: divide method of BlockDataContainer with number/DataContainer or BlockDataContainer

        :param: other (number, DataContainer or subclasses or BlockDataContainer)
        :param: out (optional): provides a placeholder for the result.
        '''
        out = kwargs.get('out', None)
        if out is not None:
            self.binary_operations(BlockDataContainer.DIVIDE, other, *args, **kwargs)
        else:
            return self.binary_operations(BlockDataContainer.DIVIDE, other, *args, **kwargs)
    def power(self, other, *args, **kwargs):
        '''Algebra: power method of BlockDataContainer with number/DataContainer or BlockDataContainer

        :param: other (number, DataContainer or subclasses or BlockDataContainer
        :param: out (optional): provides a placeholder for the result.
        '''
        out = kwargs.get('out', None)
        if out is not None:
            self.binary_operations(BlockDataContainer.POWER, other, *args, **kwargs)
        else:
            return self.binary_operations(BlockDataContainer.POWER, other, *args, **kwargs)
    def maximum(self, other, *args, **kwargs):
        '''Algebra: power method of BlockDataContainer with number/DataContainer or BlockDataContainer

        :param: other (number, DataContainer or subclasses or BlockDataContainer)
        :param: out (optional): provides a placeholder for the result.
        '''
        out = kwargs.get('out', None)
        if out is not None:
            self.binary_operations(BlockDataContainer.MAXIMUM, other, *args, **kwargs)
        else:
            return self.binary_operations(BlockDataContainer.MAXIMUM, other, *args, **kwargs)
    def minimum(self, other, *args, **kwargs):
        '''Algebra: power method of BlockDataContainer with number/DataContainer or BlockDataContainer

        :param: other (number, DataContainer or subclasses or BlockDataContainer)
        :param: out (optional): provides a placeholder for the result.
        '''
        out = kwargs.get('out', None)
        if out is not None:
            self.binary_operations(BlockDataContainer.MINIMUM, other, *args, **kwargs)
        else:
            return self.binary_operations(BlockDataContainer.MINIMUM, other, *args, **kwargs)

    def sapyb(self, a, y, b, out, num_threads = NUM_THREADS):
        r'''performs axpby element-wise on the BlockDataContainer containers

        Does the operation .. math:: a*x+b*y and stores the result in out, where x is self

        :param a: scalar
        :param b: scalar
        :param y: compatible (Block)DataContainer
        :param out: (Block)DataContainer to store the result

        Example:
        --------

        >>> a = 2
        >>> b = 3
        >>> ig = ImageGeometry(10,11)
        >>> x = ig.allocate(1)
        >>> y = ig.allocate(2)
        >>> bdc1 = BlockDataContainer(2*x, y)
        >>> bdc2 = BlockDataContainer(x, 2*y)
        >>> out = bdc1.sapyb(a,bdc2,b)
        '''
        if out is None:
            raise ValueError("out container cannot be None")
        kwargs = {'a':a, 'b':b, 'out':out, 'num_threads': NUM_THREADS}
        self.binary_operations(BlockDataContainer.SAPYB, y, **kwargs)

    def axpby(self, a, b, y, out, dtype=numpy.float32, num_threads = NUM_THREADS):
        '''Deprecated method. Alias of sapyb'''
        return self.sapyb(a,y,b,out,num_threads)

    def binary_operations(self, operation, other, *args, **kwargs):
        '''Algebra: generic method of algebric operation with BlockDataContainer with number/DataContainer or BlockDataContainer

        Provides commutativity with DataContainer and subclasses, i.e. this
        class's reverse algebraic methods take precedence w.r.t. direct algebraic
        methods of DataContainer and subclasses.

        This method is not to be used directly
        '''
        if not self.is_compatible(other):
            raise ValueError('Incompatible for operation {}'.format(operation))
        out = kwargs.get('out', None)
        if isinstance(other, Number):
            # try to do algebra with one DataContainer. Will raise error if not compatible
            kw = kwargs.copy()
            res = []
            for i,el in enumerate(self.containers):
                if operation == BlockDataContainer.ADD:
                    op = el.add
                elif operation == BlockDataContainer.SUBTRACT:
                    op = el.subtract
                elif operation == BlockDataContainer.MULTIPLY:
                    op = el.multiply
                elif operation == BlockDataContainer.DIVIDE:
                    op = el.divide
                elif operation == BlockDataContainer.POWER:
                    op = el.power
                elif operation == BlockDataContainer.MAXIMUM:
                    op = el.maximum
                elif operation == BlockDataContainer.MINIMUM:
                    op = el.minimum
                else:
                    raise ValueError('Unsupported operation', operation)
                if out is not None:
                    kw['out'] = out.get_item(i)
                    op(other, *args, **kw)
                else:
                    res.append(op(other, *args, **kw))
            if out is not None:
                return
            else:
                return type(self)(*res, shape=self.shape)
        elif isinstance(other, (list, tuple, numpy.ndarray, BlockDataContainer)):
            kw = kwargs.copy()
            res = []
            if isinstance(other, BlockDataContainer):
                the_other = other.containers
            else:
                the_other = other

            for i,zel in enumerate(zip ( self.containers, the_other) ):
                el = zel[0]
                ot = zel[1]
                if operation == BlockDataContainer.ADD:
                    op = el.add
                elif operation == BlockDataContainer.SUBTRACT:
                    op = el.subtract
                elif operation == BlockDataContainer.MULTIPLY:
                    op = el.multiply
                elif operation == BlockDataContainer.DIVIDE:
                    op = el.divide
                elif operation == BlockDataContainer.POWER:
                    op = el.power
                elif operation == BlockDataContainer.MAXIMUM:
                    op = el.maximum
                elif operation == BlockDataContainer.MINIMUM:
                    op = el.minimum
                elif operation == BlockDataContainer.SAPYB:
                    if not isinstance(other, BlockDataContainer):
                        raise ValueError("{} cannot handle {}".format(operation, type(other)))
                    op = el.sapyb
                else:
                    raise ValueError('Unsupported operation', operation)

                if out is not None:
                    if operation == BlockDataContainer.SAPYB:
                        if isinstance(kw['a'], BlockDataContainer):
                            a = kw['a'].get_item(i)
                        else:
                            a = kw['a']

                        if isinstance(kw['b'], BlockDataContainer):
                            b = kw['b'].get_item(i)
                        else:
                            b = kw['b']

                        el.sapyb(a, ot, b, out.get_item(i), num_threads=kw['num_threads'])
                    else:
                        kw['out'] = out.get_item(i)
                        op(ot, *args, **kw)
                else:
                    res.append(op(ot, *args, **kw))
            if out is not None:
                return
            else:
                return type(self)(*res, shape=self.shape)
        else:
            # try to do algebra with one DataContainer. Will raise error if not compatible
            kw = kwargs.copy()
            if operation != BlockDataContainer.SAPYB:
                # remove keyworded argument related to SAPYB
                for k in ['a','b','y', 'num_threads', 'dtype']:
                    if k in kw.keys():
                        kw.pop(k)

            res = []
            for i,el in enumerate(self.containers):
                if operation == BlockDataContainer.ADD:
                    op = el.add
                elif operation == BlockDataContainer.SUBTRACT:
                    op = el.subtract
                elif operation == BlockDataContainer.MULTIPLY:
                    op = el.multiply
                elif operation == BlockDataContainer.DIVIDE:
                    op = el.divide
                elif operation == BlockDataContainer.POWER:
                    op = el.power
                elif operation == BlockDataContainer.MAXIMUM:
                    op = el.maximum
                elif operation == BlockDataContainer.MINIMUM:
                    op = el.minimum
                elif operation == BlockDataContainer.SAPYB:

                    if isinstance(kw['a'], BlockDataContainer):
                        a = kw['a'].get_item(i)
                    else:
                        a = kw['a']

                    if isinstance(kw['b'], BlockDataContainer):
                        b = kw['b'].get_item(i)
                    else:
                        b = kw['b']

                    el.sapyb(a, other, b, out.get_item(i), kw['num_threads'])

                    # As axpyb cannot return anything we `continue` to skip the rest of the code block
                    continue

                else:
                    raise ValueError('Unsupported operation', operation)
                if out is not None:
                    kw['out'] = out.get_item(i)
                    op(other, *args, **kw)
                else:
                    res.append(op(other, *args, **kw))

            if out is not None:
                return
            else:
                return type(self)(*res, shape=self.shape)

    ## unary operations

    def unary_operations(self, operation, *args, **kwargs ):
        '''Unary operation on BlockDataContainer:

        generic method of unary operation with BlockDataContainer: abs, sign, sqrt and conjugate

        This method is not to be used directly
        '''
        out = kwargs.get('out', None)
        kw = kwargs.copy()
        if out is None:
            res = []
            for el in self.containers:
                if operation == BlockDataContainer.ABS:
                    op = el.abs
                elif operation == BlockDataContainer.SIGN:
                    op = el.sign
                elif operation == BlockDataContainer.SQRT:
                    op = el.sqrt
                elif operation == BlockDataContainer.CONJUGATE:
                    op = el.conjugate
                res.append(op(*args, **kw))
            return BlockDataContainer(*res)
        else:
            kw.pop('out')
            for el,elout in zip(self.containers, out.containers):
                if operation == BlockDataContainer.ABS:
                    op = el.abs
                elif operation == BlockDataContainer.SIGN:
                    op = el.sign
                elif operation == BlockDataContainer.SQRT:
                    op = el.sqrt
                elif operation == BlockDataContainer.CONJUGATE:
                    op = el.conjugate
                kw['out'] = elout
                op(*args, **kw)

    def abs(self, *args, **kwargs):
        return self.unary_operations(BlockDataContainer.ABS, *args, **kwargs)
    def sign(self, *args, **kwargs):
        return self.unary_operations(BlockDataContainer.SIGN, *args, **kwargs)
    def sqrt(self, *args, **kwargs):
        return self.unary_operations(BlockDataContainer.SQRT, *args, **kwargs)
    def conjugate(self, *args, **kwargs):
        return self.unary_operations(BlockDataContainer.CONJUGATE, *args, **kwargs)
    # def abs(self, *args,  **kwargs):
    #     return type(self)(*[ el.abs(*args, **kwargs) for el in self.containers], shape=self.shape)
    # def sign(self, *args,  **kwargs):
    #     return type(self)(*[ el.sign(*args, **kwargs) for el in self.containers], shape=self.shape)
    # def sqrt(self, *args,  **kwargs):
    #     return type(self)(*[ el.sqrt(*args, **kwargs) for el in self.containers], shape=self.shape)
    # def conjugate(self, out=None):
    #     return type(self)(*[el.conjugate() for el in self.containers], shape=self.shape)

    ## reductions

    def sum(self, *args, **kwargs):
        return numpy.sum([ el.sum(*args, **kwargs) for el in self.containers])

    def squared_norm(self):
        y = numpy.asarray([el.squared_norm() for el in self.containers])
        return y.sum()

    def norm(self):
        return numpy.sqrt(self.squared_norm())

    def pnorm(self, p=2):

        if p==1:
            return sum(self.abs())
        elif p==2:
            tmp = functools.reduce(lambda a,b: a + b.conjugate()*b, self.containers, self.get_item(0) * 0 ).sqrt()
            return tmp
        else:
            return ValueError('Not implemented')

    def copy(self):
        '''alias of clone'''
        return self.clone()
    def clone(self):
        return type(self)(*[el.copy() for el in self.containers], shape=self.shape)
    def fill(self, other):
        if isinstance (other, BlockDataContainer):
            if not self.is_compatible(other):
                raise ValueError('Incompatible containers')
            for el,ot in zip(self.containers, other.containers):
                el.fill(ot)
        else:
            return ValueError('Cannot fill with object provided {}'.format(type(other)))

    def __add__(self, other):
        return self.add( other )
    # __radd__

    def __sub__(self, other):
        return self.subtract( other )
    # __rsub__

    def __mul__(self, other):
        return self.multiply(other)
    # __rmul__

    def __div__(self, other):
        return self.divide(other)
    # __rdiv__
    def __truediv__(self, other):
        return self.divide(other)

    def __pow__(self, other):
        return self.power(other)
    # reverse operand
    def __radd__(self, other):
        '''Reverse addition

        to make sure that this method is called rather than the __mul__ of a numpy array
        the class constant __array_priority__ must be set > 0
        https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.classes.html#numpy.class.__array_priority__
        '''
        return self + other
    # __radd__

    def __rsub__(self, other):
        '''Reverse subtraction

        to make sure that this method is called rather than the __mul__ of a numpy array
        the class constant __array_priority__ must be set > 0
        https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.classes.html#numpy.class.__array_priority__
        '''
        return (-1 * self) + other
    # __rsub__

    def __rmul__(self, other):
        '''Reverse multiplication

        to make sure that this method is called rather than the __mul__ of a numpy array
        the class constant __array_priority__ must be set > 0
        https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.classes.html#numpy.class.__array_priority__
        '''
        return self * other
    # __rmul__

    def __rdiv__(self, other):
        '''Reverse division

        to make sure that this method is called rather than the __mul__ of a numpy array
        the class constant __array_priority__ must be set > 0
        https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.classes.html#numpy.class.__array_priority__
        '''
        return pow(self / other, -1)
    # __rdiv__
    def __rtruediv__(self, other):
        '''Reverse truedivision

        to make sure that this method is called rather than the __mul__ of a numpy array
        the class constant __array_priority__ must be set > 0
        https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.classes.html#numpy.class.__array_priority__
        '''
        return self.__rdiv__(other)

    def __rpow__(self, other):
        '''Reverse power

        to make sure that this method is called rather than the __mul__ of a numpy array
        the class constant __array_priority__ must be set > 0
        https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.classes.html#numpy.class.__array_priority__
        '''
        return other.power(self)

    def __iadd__(self, other):
        '''Inline addition'''
        if isinstance (other, BlockDataContainer):
            for el,ot in zip(self.containers, other.containers):
                el += ot
        elif isinstance(other, Number):
            for el in self.containers:
                el += other
        elif isinstance(other, list) or isinstance(other, numpy.ndarray):
            if not self.is_compatible(other):
                raise ValueError('Incompatible for __iadd__')
            for el,ot in zip(self.containers, other):
                el += ot
        return self
    # __iadd__

    def __isub__(self, other):
        '''Inline subtraction'''
        if isinstance (other, BlockDataContainer):
            for el,ot in zip(self.containers, other.containers):
                el -= ot
        elif isinstance(other, Number):
            for el in self.containers:
                el -= other
        elif isinstance(other, list) or isinstance(other, numpy.ndarray):
            if not self.is_compatible(other):
                raise ValueError('Incompatible for __isub__')
            for el,ot in zip(self.containers, other):
                el -= ot
        return self
    # __isub__

    def __imul__(self, other):
        '''Inline multiplication'''
        if isinstance (other, BlockDataContainer):
            for el,ot in zip(self.containers, other.containers):
                el *= ot
        elif isinstance(other, Number):
            for el in self.containers:
                el *= other
        elif isinstance(other, list) or isinstance(other, numpy.ndarray):
            if not self.is_compatible(other):
                raise ValueError('Incompatible for __imul__')
            for el,ot in zip(self.containers, other):
                el *= ot
        return self
    # __imul__

    def __idiv__(self, other):
        '''Inline division'''
        if isinstance (other, BlockDataContainer):
            for el,ot in zip(self.containers, other.containers):
                el /= ot
        elif isinstance(other, Number):
            for el in self.containers:
                el /= other
        elif isinstance(other, list) or isinstance(other, numpy.ndarray):
            if not self.is_compatible(other):
                raise ValueError('Incompatible for __idiv__')
            for el,ot in zip(self.containers, other):
                el /= ot
        return self
    # __rdiv__
    def __itruediv__(self, other):
        '''Inline truedivision'''
        return self.__idiv__(other)

    def __neg__(self):
        """ Return - self """
        return -1 * self

    def dot(self, other):
#
        tmp = [ self.containers[i].dot(other.containers[i]) for i in range(self.shape[0])]
        return sum(tmp)

    def __len__(self):

        return self.shape[0]


import codecs
import logging
import os
import sys

from optparse     import OptionParser

from nltools.misc import init_app, load_config, mkdirs

PROC_TITLE          = 'speech_build_lm'

SENTENCES_STATS     = 100000

LANGUAGE_MODELS_DIR = "data/dst/lm"
TEXT_CORPORA_DIR    = "data/dst/text-corpora"

DEFAULT_ORDER       = 4
DEFAULT_PRUNE       = '0 3 5'

#
# init
#

init_app(PROC_TITLE)

#
# config
#

config = load_config('.speechrc')

#
# commandline
#

parser = OptionParser("usage: %prog [options] <language_model> <text_corpus> [ <text_corpus2> ... ]")

parser.add_option ("-d", "--debug", dest="debug", type='int', default=0, help="debug limit")

parser.add_option ("-o", "--order", dest="order", type='int', default=DEFAULT_ORDER, help="order of the model, default: %d" % DEFAULT_ORDER)

parser.add_option ("-p", "--prune", dest="prune", type='str', default=DEFAULT_PRUNE, help="prune n-grams with count less than or equal to the given threshold, default: %s" % DEFAULT_PRUNE)

parser.add_option ("-v", "--verbose", action="store_true", dest="verbose",
                   help="verbose output")

(options, args) = parser.parse_args()

if options.verbose:
    logging.basicConfig(level=logging.DEBUG)
else:
    logging.basicConfig(level=logging.INFO)

if len(args) < 2:
    parser.print_usage()
    sys.exit(1)

language_model = args[0]
text_corpora   = args[1:]

#
# re-create output dir
#

outdir = '%s/%s' % (LANGUAGE_MODELS_DIR, language_model)
logging.info('cleaning output dir %s' % outdir)
cmd = 'rm -rf %s' % outdir
logging.debug(cmd)
os.system(cmd)
logging.debug('mkdirs %s' % outdir)
mkdirs(outdir)

#
# extract sentences into one big text file
#

train_fn = '%s/train_all.txt' % outdir

num_sentences = 0

with codecs.open(str(train_fn), 'w', 'utf8') as dstf:
    for text_corpus_name in text_corpora:
        src = '%s/%s.txt' % (TEXT_CORPORA_DIR, text_corpus_name)
        logging.info('reading from sources %s' % src)
        with codecs.open(str(src), 'r', 'utf8') as srcf:
            while True:

                line = srcf.readline()
                if not line:
                    break

                dstf.write(line)

                num_sentences += 1
                if num_sentences % SENTENCES_STATS == 0:
                    logging.info('%8d sentences.' % num_sentences)

                if options.debug > 0 and num_sentences >= options.debug:
                    logging.warning('stopping because sentence debug limit is reached.')
                    break

logging.info('done. %s written, %d sentences.' % (train_fn, num_sentences))

#
# compute lm
#

lm_fn = '%s/lm.arpa' % outdir

cmd = 'lmplz --skip_symbols -o %d -S 70%% --prune %s --text %s > %s' % (options.order, options.prune, train_fn, lm_fn)
logging.info(cmd)
os.system(cmd)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []

        # we can use queue to traverse in level order
        # we also need to keep track of the level so that we can divide each level into different list
        curr_lvl = 0
        q = [(root, curr_lvl)]
        ans = [[]]
        while q:
            node, lvl = q.pop(0)
            if node:
                if curr_lvl == lvl:
                    ans[-1].append(node.val)
                else:
                    ans.append([node.val])
                    curr_lvl += 1

                q.append((node.left, lvl+1))
                q.append((node.right, lvl+1))

        return ans


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

# 205p Timestamp -> Period 변환
import pandas as pd

dates = ['2019-01-01', '2020-03-01', '2021-06-01'] # 날짜 형식의 문자열로 구성되는 리스트 정의

ts_dates = pd.to_datetime(dates) # 문자열의 배열(시리즈 객체) -> Timestamp 변환
print(ts_dates)
print('\n')

#    Timestamp -> Period(기간) 변환
pr_day = ts_dates.to_period(freq='D') # D = 1일의 기간
print(pr_day)
pr_month = ts_dates.to_period(freq='M') # M = 1개월의 기간
print(pr_month)
pr_year = ts_dates.to_period(freq='A') # A = 1년의 기간
print(pr_year)

# 206p Timestamp 배열 만들기
import pandas as pd

ts_ms = pd.date_range(start='2019-01-01', # 날짜 범위 시작
                      end=None, # 날짜 범위 끝
                      periods=6, # 생성할 Timestamp 개수
                      freq='MS', # 시간 간격(MS: 월의 시작일)
                      tz='Asia/Seoul') # 시간대(timezone)
print(ts_ms)

ts_me = pd.date_range('2019-01-01', periods=6,
                      freq='M', # 시간 간격 (M: 월의 마지막 날)
                      tz='Asia/Seoul')  # 시간대(timezone)
print(ts_ms)

# 208p Period 배열 만들기

import pandas as pd

pr_m = pd.period_range(start='2019-01-01',
                     end=None,
                     periods=3,
                     freq='M')
print(pr_m)

#   period 배열 만들기 - 1시간 길이
pr_h = pd.period_range(start='2019-01-01',
                       end=None,
                       periods=3,
                       freq='H')
print(pr_h)
print('\n')

#   period 배열 만들기 - 2시간 길이
pr_2h = pd.period_range(start='2019-01-01',
                       end=None,
                       periods=3,
                       freq='2H')
print(pr_2h)


from chess_game import game, board

def main():

    current_game = game.Game()

    while not False:  # tant que la partie n'est pas finis
        board.draw_board(current_game.piece_list)
        print(f" au tour des {current_game.turn}")

        destination_case = None
        while destination_case is None:  # tant que la destination n'est pas valide

            piece_to_move = None
            while piece_to_move is None:  # tant que la piece n'est pas valide

                piece_to_move = current_game.select_piece(
                    board.convert_alpha_to_num(
                        input("quel piece voulez vous jouer ?").upper()
                    )
                )

            destination_case = current_game.select_destination(
                board.convert_alpha_to_num(
                    input("ou voulez vous aller ?").upper()
                )
            )

            current_game.move(piece_to_move, destination_case)

        print("\n")

main()


import dns.resolver, dns.reversename
import re
import sre_yield
import time

# https://www.regextester.com/
# https://habr.com/ru/post/567106/
knownIP = "[1-9]1\.[1-9]1\.2\d5\.1\d{2}" # IP: *1.*1.2*5*.1**
knownDomain = "si[a-z]+\.ru" # si*.ru

reDomain = re.compile(knownDomain)
reIP = re.compile(knownIP)

nameservers=["8.8.8.8", "8.8.4.4", "1.1.1.1"]

a = 0 # counter
resolver = dns.resolver.Resolver()
resolver.nameservers = nameservers

for aDomain in sre_yield.AllStrings(knownDomain): # regexp generator for all domains
    #print(aDomain)
    a+=1
    try:
        answer = resolver.resolve(aDomain , "A")
        #print(answer)
        for anIP in list(answer): # checking all A entries
            if(reIP.match(str(anIP))): # if A entry contains mathing IP
                print("FOUND!#{} Checking: {} Answer: {} FOUND!".format(a, aDomain, list(answer)))
                with open("found.txt", "a") as f: # adding "good" IP to file
                    f.write("Domain: {} IP: {}\n".format(aDomain, anIP))
            #break
        print("#{} Checking: {} Answer: {}".format(a, aDomain, list(answer)))
    except dns.exception.Timeout: # in case DNS serer failed to answer in right time try *one* more time
        try:
            print("Sleep for 2 seconds, due to timeout error")
            time.sleep(2)
            answer = resolver.resolve(aDomain , "A")
            #print(answer)
            for anIP in list(answer):
                if(reIP.match(str(anIP))):
                    print("FOUND!#{} Checking: {} Answer: {} FOUND!".format(a, aDomain, list(answer)))
                    with open("found.txt", "a") as f:
                        f.write("Domain: {} IP: {}\n".format(aDomain, anIP))
                #break
            print("#{} Checking: {} Answer: {}".format(a, aDomain, list(answer)))
        except Exception:
            pass
    except ( # in case domain not exist
        dns.resolver.NXDOMAIN,
        dns.resolver.NoNameservers,
        dns.resolver.NoAnswer):
        print("#{} Checking: {} Answer: Do not exist".format(a, aDomain))
    #print(a)


import pandas as pd
import secret as se

# If you see a test failure when checking your solution,
# note that [left] refers to YOUR code while [right]
# refers to the correct code that the computer is comparing
# to your work

# This challenge includes a cruise_ships.csv with 4 columns:
# Name, Operator, Year, and Tonnage
# Import the cruise_ships.csv DataFrame and assign it to
# a cruise_ships variable

cruise_ships = pd.read_csv(se.SECREAT + "cruise_ships.csv")

# Extract the "Operator" column from the DataFrame
# and assign it to an "operators" variable.

operators = cruise_ships['Operator']

# Extract the "Tonnage" column from the DataFrame
# and assign it to an "tonnages" variable.

tonnages = cruise_ships['Tonnage']

# Extract the "Name" column from the DataFrame
# and assign it to an "cruise_names" variable.

cruise_names = cruise_ships['Name']

# print(cruise_ships)
# print(operators)
# print(tonnages)
print(cruise_names)


import io
import unittest

from acqdiv.parsers.corpora.main.nungon.reader import NungonReader

class TestNungonReaderRecord(unittest.TestCase):
    """Test record readers of NungonReader."""

    @classmethod
    def setUpClass(cls):
        session = ('@UTF8\n'
                   '@Begin\n'
                   '*MEM:\t&foo ma(i)nline [: utterance]. \x150_1111\x15\n'
                   '%xgls:\tThis is the segment tier\n'
                   '%xcod:\tThis is the gloss/POS tier\n'
                   '@End')
        cls.reader = NungonReader(io.StringIO(session))
        cls.reader.load_next_record()

    def test_get_seg_tier(self):
        actual_output = self.reader.get_seg_tier()
        desired_output = 'This is the segment tier'
        self.assertEqual(actual_output, desired_output)

    def test_get_gloss_tier(self):
        actual_output = self.reader.get_gloss_tier()
        desired_output = 'This is the gloss/POS tier'
        self.assertEqual(actual_output, desired_output)

    def test_get_pos_tier(self):
        actual_output = self.reader.get_pos_tier()
        desired_output = 'This is the gloss/POS tier'
        self.assertEqual(actual_output, desired_output)


tech = []
bw = []
ue_power = []

test_item = {'tx': True, 'rx': False, 'rx_sweep': False}

band_lte = [1, 2]
band_wcdma = []
band_hsupa = []
band_hsdpa = []
band_gsm =[]

tx = []
rx = []
rx_sweep = []

instrument = ''


#!/usr/bin/env python3
# coding=utf-8
'''
name : ZhouLiang
email : Brookzhoul@163.com
data : 2019-2-14
company :http://www.dltxsoft.com/
project : captcha recognize
env : python3.6
'''

import numpy as np
import tensorflow as tf
from PIL import Image
import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"

class MalaiCaprcha:
    """
    马来西亚验证码的识别
        6位数字、英文，区分大小写
    """

    def __init__(self):
        self.image_width = 150
        self.image_height = 40
        self.char_sets = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIGJKLMNOPQRSTUVWXYZ'
        self.classes_num = len(self.char_sets)
        self.chars_num = 6
        # 模型存放地址
        self.model_path = './captcha_model'

    # 构建卷积层
    def conv2d(self, value, weight):
        '''该函数用于返回一个二维卷积层'''
        # tf.nn.conv2d() 函数实现卷积操作
        # padding='SAME'会对图像边缘补0,完成图像上所有像素（特别是边缘象素）的卷积操作
        return tf.nn.conv2d(value, weight,
                            strides=[1, 1, 1, 1], padding='SAME')

    # 构建池化层
    def max_pool_2x2(self, value, name):
        '''max_pool_2x2将特征映射向下采样2倍'''
        # tf.nn.max_pool()函数实现最大池化操作，进一步提取图像的抽象特征，并且降低特征维度
        # ksize=[1, 2, 2, 1]定义最大池化操作的核尺寸为2*2
        return tf.nn.max_pool(value, ksize=[1, 2, 2, 1],
                              strides=[1, 2, 2, 1],
                              padding='SAME',
                              name=name)

    def weight_variable(self, name, shape):
        '''weight_variable生成给定变量的权值变量'''
        with tf.device('/cpu:0'):
            initializer = tf.truncated_normal_initializer(stddev=0.1)
            # print(initializer)
            var = tf.get_variable(name, shape, initializer=initializer,
                                  dtype=tf.float32)
        return var

    def bias_variable(self, name, shape):
        '''bias_variable生成给定形状的偏差变量'''
        with tf.device('cpu:0'):
            initializer = tf.constant_initializer(0.1)
            var = tf.get_variable(name, shape, initializer=initializer,
                                  dtype=tf.float32)
        return var

    def inference(self, images, keep_prob):
        # 获得输入
        images = tf.reshape(images, [-1, self.image_height, self.image_width, 1])
        # 卷积层1
        with tf.variable_scope('conv1') as scope:
            # shape[3, 3, 1, 32]
            # 里前两个参数表示卷积核尺寸大小，即patch;
            # 第三个参数是图像通道数;
            # 第四个参数是该层卷积核的数量，有多少个卷积核就会输出多少个卷积特征图像
            kernel = self.weight_variable('weights', shape=[3, 3, 1, 64])
            # 每个卷积核都配置一个偏置量，该层有多少个输出，就应该配置多少个偏置量
            biases = self.bias_variable('biases', [64])
            # tf.nn.bias_add() 函数的作用是将偏置项biases加到卷积结果上去;
            # 注意这里的偏置项biases必须是一维的，并且数量一定要与卷积结果最后一维数量相同
            pre_activation = tf.nn.bias_add(self.conv2d(images, kernel), biases)
            # tf.nn.relu() 函数是relu激活函数，实现输出结果的非线性转换;
            conv1 = tf.nn.relu(pre_activation, name=scope.name)
        # 池化层1
        pool1 = self.max_pool_2x2(conv1, name='pool1')
        # 原图像height = 48, WIDTH = 128,
        # 经过神经网络第一层卷积（图像尺寸不变、特征×64）、池化（图像尺寸缩小一半，特征不变）之后;
        # 输出大小为 24*64*64
        # print(pool1)

        # 卷积层2
        with tf.variable_scope('conv2') as scope:
            kernel = self.weight_variable('weights', shape=[3, 3, 64, 64])
            biases = self.bias_variable('biases', [64])
            pre_activation = tf.nn.bias_add(self.conv2d(pool1, kernel), biases)
            conv2 = tf.nn.relu(pre_activation, name=scope.name)
        # 池化层2
        pool2 = self.max_pool_2x2(conv2, name='pool2')
        # 原图像HEIGHT = 60 WIDTH = 160，经过神经网络第一层后输出大小为 24*64*64
        # 经过神经网络第二层运算后输出为 12*32*64
        # 24*64的图像经过3*3的卷积核池化，padding为SAME，输出维度是12*32
        # print(pool2)

        # 卷积层3
        with tf.variable_scope('conv3') as scope:
            kernel = self.weight_variable('weights', shape=[3, 3, 64, 64])
            biases = self.bias_variable('biases', [64])
            pre_activation = tf.nn.bias_add(self.conv2d(pool2, kernel), biases)
            conv3 = tf.nn.relu(pre_activation, name=scope.name)
        # 池化层3
        pool3 = self.max_pool_2x2(conv3, name='pool3')
        # 原图像HEIGHT = 60 WIDTH = 160，
        # 经过神经网络第一层后输出大小为 24*64*64 ;
        # 经过神经网络第二层运算后输出为 12*32*64 ;
        # 经过神经网络第三层后输出大小为 6*16*64 ;
        # print(pool3)

        # 卷积层4
        with tf.variable_scope('conv4') as scope:
            kernel = self.weight_variable('weights', shape=[3, 3, 64, 64])
            biases = self.bias_variable('biases', [64])
            pre_activation = tf.nn.bias_add(self.conv2d(pool3, kernel), biases)
            conv4 = tf.nn.relu(pre_activation, name=scope.name)
        # 池化层4
        pool4 = self.max_pool_2x2(conv4, name='pool4')
        # 经过神经网络第一层后输出大小为 24*64*64 ;
        # 经过神经网络第二层运算后输出为 12*32*64 ;
        # 经过神经网络第三层后输出大小为 6*16*64 ;
        # 经过神经网络第四层后输出大小为 3*8*64 ;
        # print(pool4)

        # 搭建全连接层
        with tf.variable_scope('local1') as scope:
            # images.get_shape()作用是把张量images的形状转换为元组tuple的形式
            batch_size = images.get_shape()[0].value
            reshape = tf.reshape(pool4, [batch_size, -1])
            dim = reshape.get_shape()[1].value
            weights = self.weight_variable('weights', shape=[dim, 1024])
            biases = self.bias_variable('biases', [1024])
            # tf.matmul()函数是矩阵相乘
            local1 = tf.nn.relu(tf.matmul(reshape, weights) + biases,
                                name=scope.name)
        # tf.nn.dropout是tf里为了防止或减轻过拟合而使用的函数，一般用在全连接层;
        # Dropout机制就是在不同的训练过程中根据一定概率
        # （大小可以设置，一般情况下训练推荐0.5）随机扔掉（屏蔽）一部分神经元，
        # 不参与本次神经网络迭代的计算（优化）过程，权重保留但不做更新;
        # tf.nn.dropout()中 keep_prob用于设置概率，需要是一个占位变量，在执行的时候具体给定数值
        local1_drop = tf.nn.dropout(local1, keep_prob)

        with tf.variable_scope('softmax_linear') as scope:
            weights = self.weight_variable(
                'weights', shape=[1024, self.chars_num * self.classes_num])
            biases = self.bias_variable('biases', [self.classes_num * self.chars_num])
            softmax_linear = tf.add(tf.matmul(local1_drop, weights),
                                    biases, name=scope.name)
        # 返回6*62的向量，6代表识别结果的位数，62是每一位上可能的结果（数字，大小写字母）
        return tf.reshape(softmax_linear, [-1, self.chars_num, self.classes_num])

    # 将one-hot编码变为文本
    def one_hot_to_tests(self, recog_result):
        texts = []
        for i in range(recog_result.shape[0]):
            index = recog_result[i]
            texts.append(''.join([self.char_sets[i] for i in index]))
        return texts

    # 图片预处理
    def imageProcess(self, img):
        with open('code.png', 'wb') as f:
            f.write(img)
        image = Image.open('code.png')
        # 图像灰度化
        gray_image = image.convert('L')
        # 修改图像的大小
        image_resize = gray_image.resize(size=(self.image_width, self.image_height))
        image.close()
        # 将图片转化为numpy数组
        input_img = np.array(image_resize, dtype='float32')
        input_img = np.multiply(input_img.flatten(), 1. / 255) - 0.5
        images = np.zeros([1, self.image_height * self.image_width], dtype='float32')
        images[0, :] = input_img
        return images

    # 验证码的识别
    def codeDemo(self, img):
        with tf.Graph().as_default(), tf.device('/cpu:0'):
            input_images = self.imageProcess(img)
            images = tf.constant(input_images)
            logits = self.inference(images, keep_prob=1)
            result = tf.argmax(logits, 2)
            saver = tf.train.Saver()
            sess = tf.Session()
            saver.restore(sess, tf.train.latest_checkpoint(self.model_path))
            recog_result = sess.run(result)
            sess.close()
            text = self.one_hot_to_tests(recog_result)
        return text[0]

if __name__ == "__main__":
    a = MalaiCaprcha()
    import requests

    url = "https://www.windowmalaysia.my/evisa/captchaImaging?_=1553594761349"
    sessions = requests.session()
    sessions.get('https://www.windowmalaysia.my/evisa/evisa.jsp?alreadyCheckLang=1&lang=zh')
    img = sessions.get(url).content
    res = a.codeDemo(img)
    print(res)


dna = input("DNA: ")
base = input("base: ")
if base.isalpha() and dna.isalpha() and base in ["A", "C", "G", "T"]:
    boo = True
    for ch in dna:
        if ch not in ["A", "C", "G", "T"]:
            boo = False
    if boo:
        count = 0
        for ch in dna:
            print("c: %s" % ch)
            if ch == base:
                print("True if test")
                count += 1
        if count > 0:
            print(f"There are {count} times that the base {base} occur in this DNA.")
        else:
            print("This is not DNA String.")
    else:
        print("This is not DNA String.")
else:
    print("This is not DNA String.")


import tkinter as tk
import time
import random

#GAME PARAMETERS
square_size = 30
grid_height = 20
grid_width = 20
HEIGHT = square_size*grid_height
WIDTH = square_size*grid_width
background_colour = 'black'
snake_colour = 'red'
food_colour = 'green'

#CREATING GAME WINDOW
window = tk.Tk()
window.title("SNAKE")
c = tk.Canvas(master=window, width=WIDTH, height=HEIGHT, background=background_colour)
c.pack()

#CREATING SNAKE OBJECT CLASS
class Snake:
	def __init__(self, position, food_position):
		self.position = position[1:len(position)]
		self.direction = position[0]
		self.food_position = food_position

	#CHECKING IF SNAKE HAS EATEN FOOD
	def eaten(self):
		if self.position[0] == self.food_position:

			#EXTENDING SNAKE
			square_one = self.position[0]
			if self.direction == 'u':
				self.position.insert(0, [square_one[0], square_one[1]-1])
			elif self.direction == 'd':
				self.position.insert(0, [square_one[0], square_one[1]+1])
			elif self.direction == 'l':
				self.position.insert(0, [square_one[0]-1, square_one[1]])
			elif self.direction == 'r':
				self.position.insert(0, [square_one[0]+1, square_one[1]])

			#GENERATING NEW FOOD SQUARE
			corners = [[1,1], [1,grid_height], [grid_width, 1], [grid_width, grid_height]]
			chosen = False
			while chosen == False:
				new_food_position = [random.randint(1, grid_width), random.randint(1, grid_height)]
				if new_food_position not in self.position and new_food_position not in corners:
					self.food_position = new_food_position
					chosen = True

    #DISPLAYING SNAKE AND FOOD
	def display(self):
		for i in self.position:
			c.create_rectangle((i[0]-1)*square_size, (i[1]-1)*square_size, i[0]*square_size, i[1]*square_size,
				fill=snake_colour)

		c.create_rectangle((self.food_position[0]-1)*square_size, (self.food_position[1]-1)*square_size,
		                    self.food_position[0]*square_size, self.food_position[1]*square_size, fill=food_colour)

    #SNAKE MOVEMENT
	def auto_move(self):
		#WHEN FIRST TWO SQUARES VERTICAL
		if self.direction == 'd':
			square_one = [self.position[0][0], self.position[0][1]+1]
			del self.position[len(self.position)-1]
			self.position.insert(0, square_one)
		elif self.direction == 'u':
			square_one = [self.position[0][0], self.position[0][1]-1]
			del self.position[len(self.position)-1]
			self.position.insert(0, square_one)

		#WHEN FIRST TWO SQUARES HORIZONTAL
		if self.direction == 'r':
			square_one = [self.position[0][0]+1, self.position[0][1]]
			del self.position[len(self.position)-1]
			self.position.insert(0, square_one)
		if self.direction == 'l':
			square_one = [self.position[0][0]-1, self.position[0][1]]
			del self.position[len(self.position)-1]
			self.position.insert(0, square_one)

    #DIRECTION CHANGES
	def up(self, event):
		if self.direction == 'l' or 'r':
			self.direction = 'u'

	def down(self, event):
		if self.direction == 'l' or 'r':
			self.direction = 'd'

	def left(self, event):
		if self.direction == 'u' or 'd':
			self.direction = 'l'

	def right(self, event):
		if self.direction == 'u' or 'd':
			self.direction = 'r'

	#CHECKING IF SNAKE HAS COLLIDED WITH WALL OR ITSELF
	def check(self):
		#WALLS
		if self.position[0][0] > grid_width or self.position[0][0] < 1:
			window.quit()
		if self.position[0][1] > grid_height or self.position[0][1] < 1:
			window.quit()
		#ITSELF
		if any(self.position.count(x) > 1 for x in self.position) == True:
			window.quit()

snek = Snake(['u',[5,10], [5,11], [5,12]], [10, 10])
snek.display()

#ANIMATING SNAKE
def draw():
	c.delete("all")
	snek.auto_move()
	snek.eaten()
	snek.display()
	snek.check()
	c.after(100, draw)

#CONTROLS
window.bind("<Up>", snek.up)
window.bind("<Down>", snek.down)
window.bind("<Left>", snek.left)
window.bind("<Right>", snek.right)

draw()
window.mainloop()


"""
constants.py

constants for opticool and cooltheatom
"""

################################################################
# REAL constants

# Planck's Constant
H = 6.62607e-34
# Boltzmann's Constant (J/K)
B = 1.38065e-23
# specific heat of each atom
K = 2 * B
# speed of light
C = 3e8
# density of magnesium (atoms per m^3)
D = 2e13
# absorption wavelength (meters)
MAG_ABS = 2.852e-7

# radius of a magnesium atom
MAG_RAD = 1.45e-10
# mass of a magnesium atom (in kg
MAG_MASS = (24.305/1000)/6.02214e23
# frequency of magnesium atom
MAG_F = 200000.

##################################################################
# conversion constants

# for opticool:
# The radius of the atom (scaled up by 1,000,000) should be 20 pixels. The amplitude should not exceed 3 times (scaled) r.
# Light (scaled) should travel at 4 pixels per tick.

# 1 = 137931. pixel / meter
M_TO_PIX = 137931.
# 1 = 1.93333E-6 seconds / TICK
S_TO_TICK = 1.0344825e8
# 1 = 1,000,000 gameR / R (radius of atoms is scaled up in the game, for collisions and drawing)
ENLARGE_ATOM = 1000000.
# 1 = 100,000 gameC / c  (speed of light is scaled down in the game. scale back up for doppler!)
SLOW_LIGHT = 1/100000.
# 1 = .075 PIX / wavelength-nm (wavelengths are adjusted so that they are visible, and vary visibly over the spectrum shown.
LONG_WAVES = .075*1e9
# 1 = 10GameH/H (where H is planck's constant)
BIG_PHOTON = 20

##################################################################
# "game" constants

# tick length
TICK = 20 #milliseconds
# dimensions of the screen
WIDTH = 640
HEIGHT = 480

# atoms per column
A_PER_COL = 9
# columns of atoms
COL = 3

# Percent chance of a photon firing per tick
FIRE_PERCENT = .6

# background of screen
BACKGROUND_COLOR = "black"

# photon color
PHOTON_COLOR = "red"

###################################################
# Slider constants (in nanometers)
# LAMBSLIDEr min
LAMBSLIDE_MIN = 2900000.
# LAMBSLIDEr max
LAMBSLIDE_MAX = 2800000.
# default LAMBSLIDEr setting
LAMBSLIDE_DEFAULT = 2862001.
# LAMBSLIDEr Modifier (puts lambda in terms of tenths of nanometers)
LAMBSlideMod = 1e-13
# LAMBSLIDEr Length
LAMBSLIDE_LEN = 150

#minimum frequency for absorption (in terms of lambda)
ABS_MIN = C / (2.852e-7 + 1e-9)
#maximum frequency for absorption (in terms of lambda)
ABS_MAX = C / (2.852e-7 - 1e-9)

# Photon hold time: time before absorbed photons are reemited (in TICKs)
HOLD_TICKS = 10.


# login_controller.py
#
# ATM MVC program
#
# Team alroda
#
# Aldrich Huang A01026502 2B
# Robert Janzen A01029341 2B
# David Xiao A00725026 2B

from tkinter import *
from observe.observer import Observer

class LoginController(Observer):
    def __init__(self, view, state_model, user_db):
        self.view = view
        self.state_model = state_model
        self.state_model.addObserver(self)
        self._usr_db = user_db
        self._db = self._usr_db.model_content

        self.msg = ''

    def checkCardNum(self, input_number):
        """
            Checks the inputted card number to see if it is a valid card number

        Args:
            input_number:
                Card Number entered at the Card Entry page

        Returns:
            None
        """

        for account in self.db:
            if account["card_number"] == input_number:
                self.state_model.uid = account["uid"]
                self.state_model.state = "PIN"
                return

        self.msg = 'Invalid Card Number'
        self.state_model.state = 'LoginError'

    def checkPin(self, input_PIN):
        """
            Checks the PIN to see if it matches

        Args:
            input_PIN:
                PIN entered at the PIN Entry page

        Returns:
            None
        """
        target_account = {}

        partial_hash = ''

        for digit in input_PIN:
            partial_hash += str(int(digit) * 2)

        for account in self.db:
            if account["uid"] == self.state_model.uid:
                target_account = account
                break

        if self.reverseHash(target_account["PIN"]) == partial_hash:
            self.state_model.state = "Selection"

        else:
            self.msg = 'Invalid PIN'
            self.state_model.state = "LoginError"

    @staticmethod
    def reverseHash(input_hash):
        """
            Function for removing randomized dummy values from the hashed PIN

        Args:
            input_hash:
                Hashed PIN

        Returns:
            Clean Hashed PIN
        """

        num_str = ''
        curr_num = ''
        for character in input_hash:
            if int(character) % 2 != 0 and int(character) != 1:
                if curr_num != '':
                    num_str += str(curr_num)
                    curr_num = ''
            else:
                curr_num += character

        if curr_num != '':
            num_str += str(curr_num)

        return num_str

    @property
    def db(self):
        self._usr_db.openModelFile()
        self._db = self._usr_db.model_content
        return self._db

    def update(self, publisher, **kwargs):
        """
            Updates the ATM view

        Args:
            publisher:
                Object that is updated
            **kwargs:
                The updated attribute name and value as reported by the observer

        Returns:
            None
        """

        updated_data = kwargs.keys()

        if 'entry' in updated_data:
            input_value = kwargs['entry']

            if self.state_model.state == "Card" or self.state_model.state == "PIN":
                self.view.mid_title_input.insert(END, input_value)

        elif 'input' in updated_data:
            input_command = kwargs['input']
            if self.state_model.state == "Card" or self.state_model.state == "PIN":
                if input_command == 'DEL':
                    last_index = len(self.view.mid_title_input.get()) - 1
                    self.view.mid_title_input.delete(last_index)

                elif input_command == 'OK':
                    entry = self.view.mid_title_input.get()

                    if self.state_model.state == "Card":
                        self.checkCardNum(entry)
                    elif self.state_model.state == "PIN":
                        self.checkPin(entry)
                    else:
                        pass

        elif 'state' in updated_data:
            new_state = kwargs['state']
            if new_state == "Card":
                self.state_model.reset()
                self.view.renderCard()

            elif new_state == "PIN":
                self.view.renderPin()

            elif new_state == "LoginError":
                self.view.renderError(self.msg)


import logging
import sys
from pathlib import Path

from clldutils.clilib import ArgumentParser, command, ParserError

from segments import Tokenizer, Profile

def _write(args, line):
    print('%s' % line)

def _read(args):
    string = args.args[0] if args.args else sys.stdin.read()
    if not isinstance(string, str):
        string = string.decode(args.encoding)
    return string.strip()

@command()
def tokenize(args):
    """
    Tokenize a string (passed as argument or read from stdin)

    segments [--profile=PATH/TO/PROFILE] tokenize [STRING]
    """
    if args.profile and not Path(args.profile).exists():  # pragma: no cover
        raise ParserError('--profile must be a path for an existing file')
    _write(args, Tokenizer(profile=args.profile)(_read(args), column=args.mapping))

@command()
def profile(args):
    """
    Create an orthography profile for a string (passed as argument or read from stdin)

    segments profile [STRING]
    """
    _write(args, Profile.from_text(_read(args)))

def main():  # pragma: no cover
    logging.basicConfig()
    parser = ArgumentParser('segments')
    parser.add_argument("--encoding", help='input encoding', default="utf8")
    parser.add_argument("--profile", help='path to an orthography profile', default=None)
    parser.add_argument(
        "--mapping",
        help='column name in ortho profile to map graphemes',
        default=Profile.GRAPHEME_COL)
    sys.exit(parser.main())

if __name__ == '__main__':  # pragma: no cover
    main()